aboutsummaryrefslogtreecommitdiff
path: root/src/libjin/graphics/shaders/shader.cpp
blob: dce795dd770b870dede6dcc62daae849790512d0 (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
#include "../../core/configuration.h"
#if defined(jin_graphics) && (jin_graphics & jin_graphics_shader)

#include <iostream>

#include "../../time/timer.h"
#include "../../filesystem/buffer.h"
#include "../../utils/log.h"
#include "../../utils/macros.h"

#include "../opengl.h"
#include "../window.h"

#include "jsl_compiler.h"
#include "shader.h"

using namespace std;
using namespace JinEngine::Filesystem;
using namespace JinEngine::Time;

namespace JinEngine
{
    namespace Graphics
    {
        namespace Shaders
        {

            // 
            // default_texture
            // base_shader
            // SHADER_FORMAT_SIZE
            // formatShader
            // 
            #include "built-in/default.shader.h"

            // 
            // https://stackoverflow.com/questions/27941496/use-sampler-without-passing-through-value
            // The default value of a sampler variable is 0. From the GLSL 3.30 spec,
            //     section "4.3.5 Uniforms":
            // 
            // The link time initial value is either the value of the variable's 
            // initializer, if present, or 0 if no initializer is present.Sampler
            // types cannot have initializers.
            // 
            // Since a value of 0 means that it's sampling from texture unit 0, it will 
            // work without ever setting the value as long as you bind your textures to
            // unit 0. This is well defined behavior.
            // 
            // Since texture unit 0 is also the default until you call glActiveTexture()
            // with a value other than GL_TEXTURE0, it's very common to always use unit 
            // 0 as long as shaders do not need more than one texture.Which means that
            // often times, setting the sampler uniforms is redundant for simple
            // applications.
            // 
            // I would still prefer to always set the values.If nothing else, it makes
            // it clear to anybody reading your code that you really mean to sample from
            // texture unit 0, and did not just forget to set the value.
            // 
            const int MAIN_TEXTURE_UNIT = 0;

            static GLint textureUnit = 0;

            GLint Shader::mAttributeIndex = 0;

            Shader::Shader(const string& program)
            {
                if (!compile(program))
                {
                    jin_log_error("Compile jsl shader failed.");
                    throw Exception("Compile jsl shader failed");
                }
            }

            Shader::~Shader()
            {
                if (gl.getShader() == this)
                    gl.unuseShader();
                // Delete shader program.
                glDeleteShader(mPID);
            }

            Shader& Shader::begin()
            {

                textureUnit = MAIN_TEXTURE_UNIT;

                // Send uniforms.
                sendInt(SHADER_MAIN_TEXTURE, MAIN_TEXTURE_UNIT);
                sendVec2(SHADER_TIME, Time::getSecond(), Time::getDeltaTime());
                Canvas* rt = gl.getCanvas();
                if (rt == OpenGL::SCREEN)
                {
                    sendVec2(SHADER_RENDERTARGET_SIZE, Window::get()->getW(), Window::get()->getH());
                }
                else if(rt != nullptr)
                {
                    sendVec2(SHADER_RENDERTARGET_SIZE, rt->getWidth(), rt->getHeight());
                }

                gl.activeTextureUnit(MAIN_TEXTURE_UNIT);

                return *this;
            }

            void Shader::end()
            {
                // Reset attribute index.
                for (; mAttributeIndex > 0; --mAttributeIndex)
                    glDisableVertexAttribArray(mAttributeIndex);
            }

            bool Shader::compile(const string& program)
            {
                string vertex_shader, fragment_shader;
                // Compile JSL shader source into GLSL shader source. 
                JSLCompiler* compiler = JSLCompiler::get();
                if (!compiler->compile(program, &vertex_shader, &fragment_shader))
                {
                    return false;
                }

            #define glsl(SHADER_MODE, SHADER, SRC)                      \
                do{                                                     \
                    const GLchar* src = SRC.c_str();                    \
                    glShaderSource(SHADER, 1, &src, NULL);              \
                    glCompileShader(SHADER);                            \
                    GLint success;                                      \
                    glGetShaderiv(SHADER, GL_COMPILE_STATUS, &success); \
                    if (success == GL_FALSE)                            \
                        return false;                                   \
                }while(0)

                // Compile vertex shader.
                GLuint vid = glCreateShader(GL_VERTEX_SHADER);
                glsl(GL_VERTEX_SHADER, vid, vertex_shader);
                // Compile fragment shader.
                GLuint fid = glCreateShader(GL_FRAGMENT_SHADER);
                glsl(GL_FRAGMENT_SHADER, fid, fragment_shader);

            #undef glsl
                // Create OpenGL shader program.
                mPID = glCreateProgram();
                glAttachShader(mPID, vid);
                glAttachShader(mPID, fid);
                glLinkProgram(mPID);
                GLint success;
                glGetProgramiv(mPID, GL_LINK_STATUS, &success);
                if (success == GL_FALSE)
                    return false;
            }

            static inline GLint getMaxTextureUnits()
            {
                GLint maxTextureUnits = 0;
                glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxTextureUnits);
                return maxTextureUnits;
            }

            GLint Shader::claimTextureUnit(/*const std::string& name*/)
            {
                return textureUnit++;
            }

            GLint Shader::getUniformLocation(const char* uniform)
            {
                map<std::string, GLint>::iterator it = mUniformsLocation.find(uniform);
                if (it != mUniformsLocation.end())
                    return it->second;
                GLint loc = glGetUniformLocation(mPID, uniform);
                mUniformsLocation.insert(pair<std::string, GLint>(uniform, loc));
                return loc;
            }

            #define check_jsl() \
                if (gl.getShader() != this) \
                    return *this

            Shader & Shader::sendInt(const char* name, int value)
            {
                check_jsl();
                int loc = getUniformLocation(name);
                glUniform1i(loc, value);
                return *this;
            }

            Shader& Shader::sendFloat(const char* variable, float number)
            {
                check_jsl();
                int loc = getUniformLocation(variable);
                glUniform1f(loc, number);
                return *this;
            }

            // 
            // https://www.douban.com/note/627332677/
            // struct TextureUnit
            // {
            //     GLuint targetTexture1D;
            //     GLuint targetTexture2D;
            //     GLuint targetTexture3D;
            //     GLuint targetTextureCube;
            //     ...
            // };
            // 
            // TextureUnit mTextureUnits[GL_MAX_TEXTURE_IMAGE_UNITS]
            // GLuint mCurrentTextureUnit = 0;
            // 
            Shader& Shader::sendTexture(const char* variable, const Texture* tex)
            {
                check_jsl();
                GLint location = getUniformLocation(variable);
                if (location == -1)
                    return *this;
                GLint unit = claimTextureUnit(/*variable*/);
                if (unit == 0)
                {
                    // TODO: 쳣󶨵
                    return *this;
                }
                gl.activeTextureUnit(unit);
                glUniform1i(location, unit);
                gl.bindTexture2D(tex->getGLTexture());
                gl.activeTextureUnit(MAIN_TEXTURE_UNIT);
                return *this;
            }

            Shader& Shader::sendCanvas(const char* variable, const Canvas* canvas)
            {
                check_jsl();
                GLint location = getUniformLocation(variable);
                if (location == -1)
                    return *this;
                GLint unit = claimTextureUnit(/*variable*/);
                if (unit == 0)
                {
                    // TODO: 쳣󶨵
                    return *this;
                }
                glUniform1i(location, unit);
                glActiveTexture(GL_TEXTURE0 + unit);
                gl.bindTexture2D(canvas->getGLTexture());

                glActiveTexture(GL_TEXTURE0);
                return *this;
            }

            Shader& Shader::sendVec2(const char* name, float x, float y)
            {
                check_jsl();
                int loc = getUniformLocation(name);
                glUniform2f(loc, x, y);
                return *this;
            }

            Shader& Shader::sendVec3(const char* name, float x, float y, float z)
            {
                check_jsl();
                int loc = getUniformLocation(name);
                glUniform3f(loc, x, y, z);
                return *this;
            }

            Shader& Shader::sendVec4(const char* name, float x, float y, float z, float w)
            {
                check_jsl();
                int loc = getUniformLocation(name);
                glUniform4f(loc, x, y, z, w);
                return *this;
            }

            Shader& Shader::sendColor(const char* name, const Color* col)
            {
                check_jsl();
                int loc = getUniformLocation(name);
                glUniform4f(loc,
                    col->r / 255.f,
                    col->g / 255.f,
                    col->b / 255.f,
                    col->a / 255.f
                );
                return *this;
            }

            Shader& Shader::sendMatrix4(const char* name, const Math::Matrix* mat4)
            {
                int loc = getUniformLocation(name);
                glUniformMatrix4fv(loc, 1, GL_FALSE, mat4->getElements());
                return *this;
            }

            Shader& Shader::uploadVertices(int n, GLenum type, GLsizei stride, const GLvoid * pointers, GLboolean normalized)
            {
                uploadAttribute(SHADER_VERTEX_COORDS, n, type, stride, pointers, normalized);
                return *this;
            }

            Shader& Shader::uploadUV(int n, GLenum type, GLsizei stride, const GLvoid * pointers, GLboolean normalized)
            {
                uploadAttribute(SHADER_TEXTURE_COORDS, n, type, stride, pointers, normalized);
                return *this;
            }

            Shader& Shader::uploadColor(int n, GLenum type, GLsizei stride, const GLvoid * pointers, GLboolean normalized)
            {
                uploadAttribute(SHADER_VERTEX_COLOR, n, type, stride, pointers, normalized);
                return *this;
            }

            Shader& Shader::uploadAttribute(const String& name, int n, GLenum type, GLsizei stride, const GLvoid * pointers, GLboolean normalized)
            {
                GLint loc = glGetAttribLocation(mPID, name);
                glEnableVertexAttribArray(mAttributeIndex++);
                glVertexAttribPointer(loc, n, type, normalized, stride, pointers);
                return *this;
            }

        } // namespace Shaders
    } // namespace Graphics
} // namespace JinEngine

#endif // (jin_graphics) && (jin_graphics & jin_graphics_shader)