1 /**
2 Copyright: Copyright (c) 2013-2016 Andrey Penechko.
3 License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
4 Authors: Andrey Penechko.
5 */
6 
7 module voxelman.core.chunkmesh;
8 
9 import core.atomic : atomicLoad, atomicOp;
10 import std.concurrency : thisTid;
11 
12 import dlib.math.vector;
13 import dlib.math.quaternion;
14 import derelict.opengl3.gl3;
15 
16 struct Attribute
17 {
18 	uint location;
19 	uint elementNum;///number of
20 	uint elementType;///GL_FLOAT etc
21 	uint elementSize;///in bytes
22 	uint offset;///offset from the begining of buffer
23 	bool normalized;
24 }
25 
26 
27 
28 class ChunkMesh
29 {
30 	vec3 position;
31 	ubyte[] data;
32 	bool isDataDirty = false;
33 	GLuint vao;
34 	GLuint vbo;
35 
36 	private shared static size_t _meshInstanceCount;
37 	static size_t meshInstanceCount() @property
38 	{
39 		return atomicLoad(_meshInstanceCount);
40 	}
41 
42 	this()
43 	{
44 		atomicOp!("+=")(_meshInstanceCount, 1);
45 		glGenBuffers( 1, &vbo );
46 		glGenVertexArrays(1, &vao);
47 	}
48 
49 	~this()
50 	{
51 		atomicOp!("-=")(_meshInstanceCount, 1);
52 	}
53 
54 	void free()
55 	{
56 		glDeleteBuffers(1, &vbo);
57 		glDeleteVertexArrays(1, &vao);
58 	}
59 
60 	alias ElemType = ubyte;
61 	enum VERTEX_SIZE = ubyte.sizeof * 8;
62 
63 	void loadBuffer()
64 	{
65 		glBindBuffer(GL_ARRAY_BUFFER, vbo );
66 		glBufferData(GL_ARRAY_BUFFER, data.length, data.ptr, GL_STATIC_DRAW);
67 		glEnableVertexAttribArray(0);
68 		glEnableVertexAttribArray(1);
69 		// positions
70 		glVertexAttribPointer(0, 3, GL_UNSIGNED_BYTE, GL_FALSE, VERTEX_SIZE, null);
71 		// color
72 		glVertexAttribPointer(1, 3, GL_UNSIGNED_BYTE, GL_TRUE, VERTEX_SIZE, cast(void*)(VERTEX_SIZE / 2));
73 		glBindBuffer(GL_ARRAY_BUFFER,0);
74 	}
75 
76 	void load()
77 	{
78 		glBindVertexArray(vao);
79 		loadBuffer();
80 		glBindVertexArray(0);
81 	}
82 
83 	void bind()
84 	{
85 		glBindVertexArray(vao);
86 	}
87 
88 	void render()
89 	{
90 		if (isDataDirty)
91 		{
92 			loadBuffer();
93 			isDataDirty = false;
94 		}
95 		glDrawArrays(GL_TRIANGLES, 0, cast(uint)numVertexes());//data.length/12);
96 	}
97 
98 	ulong numVertexes() {return data.length/VERTEX_SIZE;}
99 	ulong numTris() {return data.length/(VERTEX_SIZE*3);}
100 
101 }