summaryrefslogtreecommitdiff
path: root/src/main/java/net/tylermurphy/Minecraft/Render/Data/Mesh.java
blob: 093a58e03272bd23bd5cf7c117fc118981ad7be8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package net.tylermurphy.Minecraft.Render.Data;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;

import java.io.Serializable;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;

public class Mesh implements Serializable {
	
	private static final long serialVersionUID = -8137846451745511907L;

	public static List<Integer> vaos = new ArrayList<>();
	public static List<Integer> vbos = new ArrayList<>();

	private final int id;
	private final int vertexCount;
	private int counter = 0;

	public Mesh(int vertexCount){
		this.id = GL30.glGenVertexArrays();
		vaos.add(id);
		this.vertexCount = vertexCount;
		GL30.glBindVertexArray(id);
	}

	public Mesh store(float[] data, int coordinateSize){
		int id = GL15.glGenBuffers();
		vbos.add(id);
		GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, id);
		FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length);
		buffer.put(data);
		buffer.flip();
		GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
		GL20.glVertexAttribPointer(counter,coordinateSize, GL11.GL_FLOAT,false,0,0);
		GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
		counter++;
		return this;
	}

	public Mesh finish(){
		GL30.glBindVertexArray(0);
		return this;
	}

	public void delete(){
		IntBuffer amount = BufferUtils.createIntBuffer(1);
		GL20.glGetIntegerv(GL20.GL_MAX_VERTEX_ATTRIBS, amount);
		GL30.glBindVertexArray(id);
		for (int i=0; i < amount.get(0); i++) {
			IntBuffer vbo = BufferUtils.createIntBuffer(1);
			GL20.glGetVertexAttribiv(i, GL20.GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, vbo);
			if(vbo.get(0) > 0) {
				GL15.glDeleteBuffers(vbo.get(0));
			}
		}
		GL30.glDeleteVertexArrays(id);
	}

	public int getID() {
		return id;
	}
	public int getVertexCount() {
		return vertexCount;
	}

	public static void cleanUp() {
		for(int vao:vaos){
			GL30.glDeleteVertexArrays(vao);
		}
		for(int vbo:vbos){
			GL30.glDeleteBuffers(vbo);
		}
	}

}