virtual void startup() { static const char * vs_source[] = { "#version 430 core \n" " \n" "in vec4 position; \n" " \n" "uniform mat4 mv_matrix; \n" "uniform mat4 proj_matrix; \n" " \n" "out VS_OUT \n" "{ \n" " vec2 tc; \n" "} vs_out; \n" " \n" "void main(void) \n" "{ \n" " gl_Position = proj_matrix * mv_matrix * position; \n" " vs_out.tc = position.xy; \n" "} \n" }; static const char * fs_source[] = { "#version 430 core \n" " \n" "out vec4 color; \n" " \n" "in VS_OUT \n" "{ \n" " vec2 tc; \n" "} fs_in; \n" " \n" "void main(void) \n" "{ \n" " float val = abs(fs_in.tc.x + fs_in.tc.y) * 20.0f; \n" " color = vec4(fract(val) >= 0.5 ? 1.0 : 0.25); \n" "} \n" }; program = glCreateProgram(); GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, fs_source, NULL); glCompileShader(fs); GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, vs_source, NULL); glCompileShader(vs); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); mv_location = glGetUniformLocation(program, "mv_matrix"); proj_location = glGetUniformLocation(program, "proj_matrix"); glGenVertexArrays(1, &vao); glBindVertexArray(vao); static const GLushort vertex_indices[] = { 0, 1, 2, 2, 1, 3, 2, 3, 4, 4, 3, 5, 4, 5, 6, 6, 5, 7, 6, 7, 0, 0, 7, 1, 6, 0, 2, 2, 4, 6, 7, 5, 3, 7, 3, 1 }; static const GLfloat vertex_positions[] = { -0.25f, -0.25f, -0.25f, -0.25f, 0.25f, -0.25f, 0.25f, -0.25f, -0.25f, 0.25f, 0.25f, -0.25f, 0.25f, -0.25f, 0.25f, 0.25f, 0.25f, 0.25f, -0.25f, -0.25f, 0.25f, -0.25f, 0.25f, 0.25f, }; glGenBuffers(1, &position_buffer); glBindBuffer(GL_ARRAY_BUFFER, position_buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_positions), vertex_positions, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(0); glGenBuffers(1, &index_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(vertex_indices), vertex_indices, GL_STATIC_DRAW); glEnable(GL_CULL_FACE); }
void VertexManager::vFlush(bool useDstAlpha) { GLVertexFormat* nativeVertexFmt = (GLVertexFormat*)VertexLoaderManager::GetCurrentVertexFormat(); u32 stride = nativeVertexFmt->GetVertexStride(); if (m_last_vao != nativeVertexFmt->VAO) { glBindVertexArray(nativeVertexFmt->VAO); m_last_vao = nativeVertexFmt->VAO; } PrepareDrawBuffers(stride); // Makes sure we can actually do Dual source blending bool dualSourcePossible = g_ActiveConfig.backend_info.bSupportsDualSourceBlend; // If host supports GL_ARB_blend_func_extended, we can do dst alpha in // the same pass as regular rendering. if (useDstAlpha && dualSourcePossible) { ProgramShaderCache::SetShader(DSTALPHA_DUAL_SOURCE_BLEND, m_current_primitive_type); } else { ProgramShaderCache::SetShader(DSTALPHA_NONE, m_current_primitive_type); } // upload global constants ProgramShaderCache::UploadConstants(); // setup the pointers nativeVertexFmt->SetupVertexPointers(); Draw(stride); // run through vertex groups again to set alpha if (useDstAlpha && !dualSourcePossible) { ProgramShaderCache::SetShader(DSTALPHA_ALPHA_PASS, m_current_primitive_type); // only update alpha glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE); glDisable(GL_BLEND); Draw(stride); // restore color mask g_renderer->SetColorMask(); if (bpmem.blendmode.blendenable || bpmem.blendmode.subtract) glEnable(GL_BLEND); } #if defined(_DEBUG) || defined(DEBUGFAST) if (g_ActiveConfig.iLog & CONF_SAVESHADERS) { // save the shaders ProgramShaderCache::PCacheEntry prog = ProgramShaderCache::GetShaderProgram(); std::string filename = StringFromFormat( "%sps%.3d.txt", File::GetUserPath(D_DUMPFRAMES_IDX).c_str(), g_ActiveConfig.iSaveTargetId); std::ofstream fps; OpenFStream(fps, filename, std::ios_base::out); fps << prog.shader.strpprog; filename = StringFromFormat("%svs%.3d.txt", File::GetUserPath(D_DUMPFRAMES_IDX).c_str(), g_ActiveConfig.iSaveTargetId); std::ofstream fvs; OpenFStream(fvs, filename, std::ios_base::out); fvs << prog.shader.strvprog; } if (g_ActiveConfig.iLog & CONF_SAVETARGETS) { std::string filename = StringFromFormat("%starg%.3d.png", File::GetUserPath(D_DUMPFRAMES_IDX).c_str(), g_ActiveConfig.iSaveTargetId); TargetRectangle tr; tr.left = 0; tr.right = Renderer::GetTargetWidth(); tr.top = 0; tr.bottom = Renderer::GetTargetHeight(); g_renderer->SaveScreenshot(filename, tr); } #endif g_Config.iSaveTargetId++; ClearEFBCache(); }
void TextRenderer::LoadText(unsigned int _w, unsigned int _h) { m_TextShader = new ShaderHandler(); m_TextShader->CreateShaderProgram(); m_TextShader->AddShader("../../../Content/Shaders/text_vertex.glsl", GL_VERTEX_SHADER); m_TextShader->AddShader("../../../Content/Shaders/text_fragment.glsl", GL_FRAGMENT_SHADER); m_TextShader->LinkShaderProgram(); LoadLetters(); float w = (8.f * (Text::LETTERS-1)) / (_w); float h = 8.0f / (_h); // Load texture file and convert to openGL format GLbyte imgData[64 * Text::LETTERS]; int k = 0; int x = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < m_letters64.size(); j++) { for (int g = 0; g < 8; g++) { imgData[k] = (*m_letters64[j])[i * 8 + g];//[j]; k++; x++; } } } glActiveTexture(GL_TEXTURE3); glGenTextures(1, &m_TextInfo.TexHandle); glBindTexture(GL_TEXTURE_2D, m_TextInfo.TexHandle); // Copy file to OpenGL //glActiveTexture(GL_TEXTURE0); error = glGetError(); glGenTextures(1, &m_TextInfo.TexHandle); glBindTexture(GL_TEXTURE_2D, m_TextInfo.TexHandle); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //gluBuild2DMipmaps(GL_TEXTURE_2D, channels, width, height, GL_RGBA, GL_UNSIGNED_BYTE, imgData); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED,(GLsizei)(8 * m_letters64.size()), 8, 0, GL_RED, GL_BYTE, imgData); m_TextInfo.Height = h; m_TextInfo.Width = w; m_TextInfo.X = 0; m_TextInfo.Y = 0; //buffra datan till 2D shader float positionData[] = { -1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0 }; float texCoordData[] = { 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f }; int nrOfPoints = 12; GLuint m_2DVBO[2]; glGenBuffers(2, m_2DVBO); // "Bind" (switch focus to) first buffer glBindBuffer(GL_ARRAY_BUFFER, m_2DVBO[0]); glBufferData(GL_ARRAY_BUFFER, nrOfPoints * sizeof(float), positionData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, m_2DVBO[1]); glBufferData(GL_ARRAY_BUFFER, nrOfPoints * sizeof(float), texCoordData, GL_STATIC_DRAW); // create 1 VAO glGenVertexArrays(1, &m_2DVAO); glBindVertexArray(m_2DVAO); // enable "vertex attribute arrays" glEnableVertexAttribArray(0); // position glEnableVertexAttribArray(1); // texCoord // map index 0 to position buffer glBindBuffer(GL_ARRAY_BUFFER, m_2DVBO[0]); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (GLubyte *)NULL); glBindBuffer(GL_ARRAY_BUFFER, m_2DVBO[1]); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (GLubyte *)NULL); glBindVertexArray(0); // disable VAO glUseProgram(0); // disable shader program glDeleteBuffers(2, m_2DVBO); GLenum error = glGetError(); if (error != GL_NO_ERROR) { printf("Error loading text %d\n", error); } }
void InitLivin(int width, int height){ int i; char letterpath[] = "data/x.obj"; /* character mesh mask */ char letterlist[LETTERNUM] = "bceginrsty"; /* Cybernetic genetics characters */ char greetingspath[21]; /* OpenGL related initialization */ glClearColor(0.0, 0.0, 0.0, 0.0); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); perspectiveMatrix(pmatrix, 35.0, (float)width/(float)height, 0.1, 1500.0); /* Demo related initialization */ head = openDepthVideo("data/head.dv"); matat = openDepthVideo("data/matat.dv"); face = initFace("shaders/face.vs", "shaders/face.fs"); armface = initFace("shaders/face.vs", "shaders/face.fs"); knock = openOutline("data/knock.pyd", "shaders/knock.vs", "shaders/knock.fs"); jump = openOutline("data/jump.pyd", "shaders/jump.vs", "shaders/outline.fs"); hang = openOutline("data/hanging.pyd", "shaders/hang.vs", "shaders/outline.fs"); run = openOutline("data/run.pyd", "shaders/run.vs", "shaders/outline.fs"); falling = openOutline("data/falling_letters.pyd", "shaders/run.vs", "shaders/outline.fs"); door = openOutline("data/door.pyd", "shaders/door.vs", "shaders/door.fs"); trap = openOutline("data/trap.pyd", "shaders/trap.vs", "shaders/outline.fs"); fractalme = openOutline("data/fractalme.pyd", "shaders/frme.vs", "shaders/frme.fs"); /* Acrobatic outlines */ tiger = openOutline("data/tiger.pyd", "shaders/acrobat.vs", "shaders/outline.fs"); hop = openOutline("data/hop.pyd", "shaders/acrobat.vs", "shaders/outline.fs"); katf = openOutline("data/kezenatfordulas.pyd", "shaders/acrobat.vs", "shaders/outline.fs"); flip = openOutline("data/flip.pyd", "shaders/acrobat.vs", "shaders/outline.fs"); run2 = openOutline("data/run2.pyd", "shaders/acrobat.vs", "shaders/outline.fs"); catwheel = openOutline("data/catwheel.pyd", "shaders/acrobat.vs", "shaders/outline.fs"); tbill = openOutline("data/tarkobillenes.pyd", "shaders/acrobat.vs", "shaders/outline.fs"); createBox(); createBackground(); initGreetings(); createDistBack(); bigcube = createBigCube(600); titletex = loadPNGTexture("data/title.png"); greentex = loadPNGTexture("data/green.png"); creditstex = loadPNGTexture("data/credits.png"); bgalphatex = loadPNGTexture("data/bg_alpha.png"); whitetex = loadPNGTexture("data/white.png"); icubetex = loadPNGTexture("data/innercube.png"); headouttex = loadPNGTexture("data/headout.png"); chesstex = loadPNGTexture("data/chessboard.png"); atpartytex = loadPNGTexture("data/at_party.png"); for(i = 0; i < 12; i++){ sprintf(greetingspath, "data/greetings%d.png", i+1); greetingstex[i] = loadPNGTexture(greetingspath); } for(i = 0; i < MAXKNOCKINGMAN; i++){ knockingmans[i * 3 + 0] = drand48() * 4.0 + 8.0; knockingmans[i * 3 + 1] = drand48() * 6.0 + 1.0; knockingmans[i * 3 + 2] = drand48(); } /* Shaders */ background_src[0] = loadShader(GL_VERTEX_SHADER, "shaders/background.vs"); background_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/background.fs"); background_src[2] = loadShader(GL_TESS_EVALUATION_SHADER, "shaders/background.te"); background_src[3] = loadShader(GL_TESS_CONTROL_SHADER, "shaders/background.tc"); background_src[4] = loadShader(GL_GEOMETRY_SHADER, "shaders/background.gs"); background_shader = createProgram(5, background_src); title_src[0] = background_src[0]; title_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/title.fs"); title_src[2] = background_src[2]; title_src[3] = background_src[3]; title_src[4] = background_src[4]; title_shader = createProgram(5, title_src); scroll_src[0] = background_src[0]; scroll_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/scroll.fs"); scroll_src[2] = background_src[2]; scroll_src[3] = background_src[3]; scroll_src[4] = background_src[4]; scroll_shader = createProgram(5, scroll_src); credits_src[0] = background_src[0]; credits_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/credits.fs"); credits_src[2] = background_src[2]; credits_src[3] = background_src[3]; credits_src[4] = loadShader(GL_GEOMETRY_SHADER, "shaders/credits.gs"); credits_shader = createProgram(5, credits_src); letter_src[0] = loadShader(GL_VERTEX_SHADER, "shaders/letter.vs"); letter_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/letter.fs"); letter_shader = createProgram(2, letter_src); cube_src[0] = loadShader(GL_VERTEX_SHADER, "shaders/cube.vs"); cube_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/cube.fs"); cube_src[2] = loadShader(GL_GEOMETRY_SHADER, "shaders/cube.gs"); cube_shader = createProgram(3, cube_src); gr_src[0] = loadShader(GL_VERTEX_SHADER, "shaders/greetings.vs"); gr_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/greetings.fs"); gr_shader = createProgram(2, gr_src); dbgr_src[0] = loadShader(GL_VERTEX_SHADER, "shaders/dbgr.vs"); dbgr_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/dbgr.fs"); dbgr_shader = createProgram(2, dbgr_src); bigcube_src[0] = loadShader(GL_VERTEX_SHADER, "shaders/bigcube.vs"); bigcube_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/bigcube.fs"); bigcube_shader = createProgram(2, bigcube_src); /* Letters */ for(i = 0; i < LETTERNUM; i++){ letterpath[5] = letterlist[i]; letters[i] = loadOBJ(letterpath); glBindVertexArray(letters[i]->vao); bindVarToBuff(letter_shader, "vertex", letters[i]->vbo[MESHVERTEXINDEX], 3); bindVarToBuff(letter_shader, "normal", letters[i]->vbo[MESHNORMALINDEX], 3); bindVarToBuff(letter_shader, "tcoord", letters[i]->vbo[MESHTEXINDEX], 2); } cube = loadOBJ("data/cube.obj"); glBindVertexArray(cube->vao); bindVarToBuff(cube_shader, "vertex", cube->vbo[MESHVERTEXINDEX], 3); bindVarToBuff(cube_shader, "normal", cube->vbo[MESHNORMALINDEX], 3); bindVarToBuff(cube_shader, "tcoord", cube->vbo[MESHTEXINDEX], 2); initExplosion(); startTime(); }
int main() { sf::Window window(sf::VideoMode(1280, 720), "OpenGLCube"); //GLEW glewExperimental = GL_TRUE; glewInit(); //Vertex Shader Source const GLchar* vertexShaderSource[] = { "#version 150\n" "\n" "in vec2 position;\n" "in vec2 texcoord;\n" "in vec3 color;\n" "\n" "out vec3 Color;\n" "out vec2 Texcoord;\n" "\n" "void main()\n" "{\n" " Texcoord = texcoord;" " Color = color;\n" " gl_Position = vec4(position, 0.0, 1.0);\n" "}\n" }; //Fragment Shader Source const GLchar* fragmentShaderSource[] = { "#version 150\n" "\n" "in vec3 Color;\n" "in vec2 Texcoord;\n" "\n" "out vec4 outColor;\n" "\n" "uniform sampler2D tex;" "\n" "void main()\n" "{\n" " outColor = texture(tex, Texcoord) * vec4(Color, 1.0);\n" "}\n" }; //Create Vertex Array Object //VAO's are used to store information about our vertex data so we don't have to resend everything if we change shaders GLuint vaoHandle; glGenVertexArrays(1, &vaoHandle); //Reserve memory for 1 vao //Active the VAO //Only calls after a VAO will stick, so we have to create and bind it before anything else glBindVertexArray(vaoHandle); //Triangle Vertices /*float vertices[] = { 0.0f, 0.5f, 1.0f, 0.0f, 0.0f, // X/Y/R/G/B/A 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, };*/ //Rectangle Vertices float vertices[] = { //Pos //Col //Tex -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, //Top-Left 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, //Top-Right 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, //Bottom-Right -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f //Bottom-Left }; //Create Vertex Buffer Object //This is so that we can upload our vertices to the GPU memory GLuint vboHandle; //Handle to the VBO glGenBuffers(1, &vboHandle); //Generate 1 VBO and return the handle to us glBindBuffer(GL_ARRAY_BUFFER, vboHandle); //Set our VBO to the active one used by OpenGL glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //Upload our vertices to the GPU //GL_STATIC_DRAW: The vertex data will be uploaded once and drawn many times (e.g. the world). //GL_DYNAMIC_DRAW: The vertex data will be changed from time to time, but drawn many times more than that. //GL_STREAM_DRAW: The vertex data will change almost every time it's drawn (e.g. user interface). //Element Buffer specifies the order in which to draw, as well as reuse existing vertices GLuint elements[] = { 0, 1, 2, //Top-Left, Top-Right, Bottom-Right 2, 3, 0 //Bottom-Right, Bottom-Left, Top-Left }; GLuint eboHandle; glGenBuffers(1, &eboHandle); //Generate memory for 1 EBO glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, eboHandle); //Set as active glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW); //Upload to GPU //Create Shaders GLuint vertexShaderHandle = glCreateShader(GL_VERTEX_SHADER); //Reserve memory in OpenGL GLuint fragmentShaderHandle = glCreateShader(GL_FRAGMENT_SHADER); //Reserve memory in OpenGL //Upload Shader Source glShaderSource(vertexShaderHandle, 1, vertexShaderSource, NULL); //Compile the shader glShaderSource(fragmentShaderHandle, 1, fragmentShaderSource, NULL); //Compile the shader //Compile Shaders glCompileShader(vertexShaderHandle); glCompileShader(fragmentShaderHandle); //Check Shader Compilation for errors GLint status; glGetShaderiv(vertexShaderHandle, GL_COMPILE_STATUS, &status); if (!status) { std::cout << "VertexShader failed\n"; char buffer[512]; glGetShaderInfoLog(vertexShaderHandle, 512, NULL, buffer); std::cout << buffer << "\n\n"; } glGetShaderiv(fragmentShaderHandle, GL_COMPILE_STATUS, &status); if (!status) { std::cout << "FragmentShader failed\n"; char buffer[512]; glGetShaderInfoLog(vertexShaderHandle, 512, NULL, buffer); std::cout << buffer << "\n\n"; } //Create a program that knows about each shader, like in C++ with adding library headers GLuint shaderProgramHandle = glCreateProgram(); //Reserve memory glAttachShader(shaderProgramHandle, vertexShaderHandle); glAttachShader(shaderProgramHandle, fragmentShaderHandle); //glBindFragDataLocation(shaderProgramHandle, 0, "outColor") //Not sure what 0 is, but it's a default. This tells the fragment shader where to send its output //Link the shaders in the program, similar to building a C++ project glLinkProgram(shaderProgramHandle); //Activate the shader program, similar to running a C++ project //Only one program can be active at once glUseProgram(shaderProgramHandle); //Get a handle to our input position in the vertex shader (now in the shader program) GLint positionAttributeHandle = glGetAttribLocation(shaderProgramHandle, "position"); //Enable the positionAttribute so that it can be used glEnableVertexAttribArray(positionAttributeHandle); //Tell OpenGL what this input looks like. handle, numValues, valueType, normalize (true/false) //The last two values specify how the attribute is detailed in the Vertex Array //The first of the two is how many bytes are between each attribute //The second of the two is how many bytes from the start is the first attribute located, i.e. the offset from the start //This also binds the current VBO to this attribute, so it doesn't need to be specified when drawing. glVertexAttribPointer(positionAttributeHandle, 2, GL_FLOAT, GL_FALSE, 7*sizeof(float), 0); GLint colorAttributeHandle = glGetAttribLocation(shaderProgramHandle, "color"); glEnableVertexAttribArray(colorAttributeHandle); glVertexAttribPointer(colorAttributeHandle, 3, GL_FLOAT, GL_FALSE, 7*sizeof(float), (void*)(2*sizeof(float))); GLint texAttributeHandle = glGetAttribLocation(shaderProgramHandle, "texcoord"); glEnableVertexAttribArray(texAttributeHandle); glVertexAttribPointer(texAttributeHandle, 2, GL_FLOAT, GL_FALSE, 7*sizeof(float), (void*)(5*sizeof(float))); //Generate texture GLuint texHandle; glGenTextures(1, &texHandle); //Set texture as active glBindTexture(GL_TEXTURE_2D, texHandle); //Texture float pixels[] = { 0.2f, 0.2f, 0.2f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.2f, 0.2f, 0.2f }; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_FLOAT, pixels); //2nd: level of detail, 0 = base, others = mipmap //3rd: pixel format //4th&5th: width and height //6th: must always be zero (border) //7th&8th: pixel format in array //9th: pixel array //Set Wrapping //GL_REPEAT: The integer part of the coordinate will be ignored and a repeating pattern is formed. //GL_MIRRORED_REPEAT: The texture will also be repeated, but it will be mirrored when the integer part of the coordinate is odd. //GL_CLAMP_TO_EDGE: The coordinate will simply be clamped between 0 and 1. //GL_CLAMP_TO_BORDER: The coordinates that fall outside the range will be given a specified border color. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); //For border clamp colour //float color[] = {1.0f, 0.0f, 0.0f, 1.0f}; //glTexParameterfv(GL_TEXTURE_2D, GL-TEXTURE_BORDER_COLOR, color); //Set filtering //GL_NEAREST: Returns the pixel that is closest to the coordinates. //GL_LINEAR: Returns the weighted average of the 4 pixels surrounding the given coordinates. //GL_NEAREST_MIPMAP_NEAREST, GL_LINEAR_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_LINEAR: Sample from mipmaps instead. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //Generate mipmap //Mipmaps are different resolution copies of the texture glGenerateMipmap(GL_TEXTURE_2D); //Game Loop sf::Time prevFrameTime = sf::seconds(1.f/60.f); sf::Clock frameTime; sf::Clock totalTime; sf::Event event; while (window.isOpen()) { //Event while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: { window.close(); break; } default: { break; } } } //Update //Draw glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); //glDrawArrays(GL_TRIANGLES, 0, 6); //Draw an array of vertices that we binded before to our VBO //The second argument is the offset from the beginner of the vertices, the third argument is the number of vertices glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); //2nd: # of indicies. 3rd: element type. 4th: offset between elements. window.display(); //PostDraw prevFrameTime = frameTime.restart(); //std::cout << "FPS: " << 1.f / prevFrameTime.asSeconds() << "\n"; } glDeleteProgram(shaderProgramHandle); glDeleteShader(fragmentShaderHandle); glDeleteShader(vertexShaderHandle); glDeleteBuffers(1, &vboHandle); glDeleteBuffers(1, &eboHandle); glDeleteVertexArrays(1, &vaoHandle); return 0; }
int main() { std::cout << glfwGetVersionString() << std::endl; GLuint texture{ 0 }, sampler{ 0 }; GLuint vbo{ 0 }, vao{ 0 }; GLuint vs{ 0 }, fs{ 0 }, program{ 0 }; FT_Library ft_lib{ nullptr }; FT_Face face{ nullptr }; auto cleanup = [&]() { FT_Done_Face(face); FT_Done_FreeType(ft_lib); glDeleteTextures(1, &texture); glDeleteSamplers(1, &sampler); glDeleteBuffers(1, &vbo); glDeleteVertexArrays(1, &vao); glDeleteShader(vs); glDeleteShader(fs); glDeleteProgram(program); }; // Initialize and load our freetype face if (FT_Init_FreeType(&ft_lib) != 0) { std::cerr << "Couldn't initialize FreeType library\n"; cleanup(); return 1; } if (FT_New_Face(ft_lib, "../Dependencies/fonts/Kalypsa-Medium.ttf", 0, &face) != 0) { std::cerr << "Unable to load myfont.ttf\n"; cleanup(); return 1; } // Create a GLFW window if (glfwInit() != GL_TRUE) { std::cerr << "Couldn't load GLFW library\n"; cleanup(); return 1; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); const int WIDTH = 640; const int HEIGHT = 480; const double SCALEX = 2.0 / WIDTH; const double SCALEY = 2.0 / HEIGHT; auto window = glfwCreateWindow(WIDTH, HEIGHT, "OpenGL Text Rendering", nullptr, nullptr); glfwMakeContextCurrent(window); glViewport(0, 0, WIDTH, HEIGHT); // Initialize our texture and VBOs glGenBuffers(1, &vbo); glGenVertexArrays(1, &vao); glGenTextures(1, &texture); glGenSamplers(1, &sampler); glSamplerParameteri(sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glSamplerParameteri(sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Initialize shader vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, &VERTEX_SHADER, 0); glCompileShader(vs); fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &FRAGMENT_SHADER, 0); glCompileShader(fs); program = glCreateProgram(); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); // Set some initialize GL state glEnable(GL_BLEND); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearColor(0.1, 0.2, 0.4, 0); // Get shader uniforms glUseProgram(program); glBindAttribLocation(program, 0, "in_Position"); GLuint texUniform = glGetUniformLocation(program, "tex"); GLuint colorUniform = glGetUniformLocation(program, "color"); while (glfwWindowShouldClose(window) != GL_TRUE) { glfwMakeContextCurrent(window); glClear(GL_COLOR_BUFFER_BIT); // Bind stuff glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glBindSampler(0, sampler); glBindVertexArray(vao); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vbo); glUseProgram(program); glUniform4f(colorUniform, 1, 1, 1, 1); glUniform1i(texUniform, 0); FT_Set_Pixel_Sizes(face, 0, 50); render_text("Hello World!", face, -0.5, 0, SCALEX, SCALEY); glfwSwapBuffers(window); glfwPollEvents(); } cleanup(); return 0; }
GLUSboolean update(GLUSfloat time) { GLfloat modelMatrix[16]; GLfloat normalMatrix[9]; // // Render to FBO. // glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, g_texture[0]); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_CUBE_MAP, g_texture[1]); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, g_texture[2]); glActiveTexture(GL_TEXTURE0); glBindFramebuffer(GL_FRAMEBUFFER, g_fullscreenFBO); glEnable(GL_MULTISAMPLE); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Render the background. // Rendering the sphere from inside, so change front facing. glFrontFace(GL_CW); glUseProgram(g_backgroundProgram.program); glUniformMatrix4fv(g_viewProjectionMatrixBackgroundLocation, 1, GL_FALSE, g_viewProjectionMatrix); glBindVertexArray(g_backgroundVAO); glDrawElements(GL_TRIANGLES, g_numberIndicesBackground, GL_UNSIGNED_INT, 0); glFrontFace(GL_CCW); // Render model using BRDF and IBL. glusMatrix4x4Identityf(modelMatrix); glusMatrix4x4Scalef(modelMatrix, 0.001f, 0.001f, 0.001f); glusMatrix4x4ExtractMatrix3x3f(normalMatrix, modelMatrix); glUseProgram(g_modelProgram.program); glBindVertexArray(g_modelVAO); // Roughness of material. glUniform1f(g_roughnessMaterialModelLocation, g_roughness); glUniform1f(g_R0MaterialModelLocation, g_R0); glUniform3fv(g_colorMaterialModelLocation, 1, g_colorMaterial); glUniformMatrix4fv(g_viewProjectionMatrixModelLocation, 1, GL_FALSE, g_viewProjectionMatrix); glUniformMatrix4fv(g_modelMatrixModelLocation, 1, GL_FALSE, modelMatrix); glUniformMatrix3fv(g_normalMatrixModelLocation, 1, GL_FALSE, normalMatrix); glDrawArrays(GL_TRIANGLES, 0, g_numberVerticesModel); // // Render full screen to resolve the buffer: MSAA, tone mapping and gamma correction. // glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, g_fullscreenTexture); glBindFramebuffer(GL_FRAMEBUFFER, 0); glDisable(GL_MULTISAMPLE); // No clear needed, as we just draw over the last content. glDisable(GL_DEPTH_TEST); glUseProgram(g_fullscreenProgram.program); glUniform1f(g_exposureFullscreenLocation, g_exposure); glUniform1f(g_gammaFullscreenLocation, g_gamma); glBindVertexArray(g_fullscreenVAO); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glEnable(GL_DEPTH_TEST); return GLUS_TRUE; }
/*! Initialize the scene, reserve shaders, compile and cache program \param[in] None. \return None */ void Cube::InitModel() { if (! ( program = ProgramManagerObj->Program( (char *)"Cube" ))){ program = ProgramManagerObj->ProgramInit( (char *)"Cube" ); ProgramManagerObj->AddProgram( program ); } //Initialize Vertex and Fragment shader program->VertexShader = ShaderManager::ShaderInit( VERTEX_SHADER_PRG, GL_VERTEX_SHADER ); program->FragmentShader = ShaderManager::ShaderInit( FRAGMENT_SHADER_PRG, GL_FRAGMENT_SHADER ); // Compile Vertex shader CACHE *m = reserveCache( VERTEX_SHADER_PRG, true ); if( m ) { if( !ShaderManager::ShaderCompile( program->VertexShader, ( char * )m->buffer, 1 ) ) exit( 1 ); freeCache( m ); } // Compile Fragment shader m = reserveCache( FRAGMENT_SHADER_PRG, true ); if( m ) { if( !ShaderManager::ShaderCompile( program->FragmentShader, ( char * )m->buffer, 1 ) ) exit( 2 ); freeCache( m ); } // Link program if( !ProgramManagerObj->ProgramLink( program, 1 ) ) exit( 3 ); glUseProgram( program->ProgramID ); // Create VBO size = 24*sizeof(float); glGenBuffers(1, &vId); glBindBuffer( GL_ARRAY_BUFFER, vId ); glBufferData( GL_ARRAY_BUFFER, size + size, 0, GL_STATIC_DRAW ); glBufferSubData( GL_ARRAY_BUFFER, 0, size, cubeVerts ); glBufferSubData( GL_ARRAY_BUFFER, size, size, cubeColors ); // Create VBO for transformation matrix glGenBuffers(1, &matrixId); glBindBuffer( GL_ARRAY_BUFFER, matrixId ); glm::mat4 transformMatrix[dimension][dimension][dimension]; glBufferData(GL_ARRAY_BUFFER, sizeof(transformMatrix) , 0, GL_DYNAMIC_DRAW); // Create IBO unsigned short indexSize = sizeof( unsigned short )*36; glGenBuffers(1, &iId); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, iId ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, indexSize, 0, GL_STATIC_DRAW ); glBufferSubData( GL_ELEMENT_ARRAY_BUFFER, 0, indexSize, cubeIndices ); glGenVertexArrays(1, &Vertex_VAO_Id); glBindVertexArray(Vertex_VAO_Id); // Create VBO and set attribute parameters glBindBuffer( GL_ARRAY_BUFFER, vId ); glEnableVertexAttribArray(VERTEX_LOCATION); glEnableVertexAttribArray(COLOR_LOCATION); glVertexAttribPointer(VERTEX_LOCATION, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); glVertexAttribPointer(COLOR_LOCATION, 3, GL_FLOAT, GL_FALSE, 0, (void*)size); // Create VBO for transformation matrix and set attribute parameters glBindBuffer( GL_ARRAY_BUFFER, matrixId ); glEnableVertexAttribArray(MATRIX1_LOCATION); glEnableVertexAttribArray(MATRIX2_LOCATION); glEnableVertexAttribArray(MATRIX3_LOCATION); glEnableVertexAttribArray(MATRIX4_LOCATION); glVertexAttribPointer(MATRIX1_LOCATION, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)(sizeof(float) * 0)); glVertexAttribPointer(MATRIX2_LOCATION, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)(sizeof(float) * 4)); glVertexAttribPointer(MATRIX3_LOCATION, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)(sizeof(float) * 8)); glVertexAttribPointer(MATRIX4_LOCATION, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)(sizeof(float) * 12)); glVertexAttribDivisor(MATRIX1_LOCATION, 1); glVertexAttribDivisor(MATRIX2_LOCATION, 1); glVertexAttribDivisor(MATRIX3_LOCATION, 1); glVertexAttribDivisor(MATRIX4_LOCATION, 1); // Bind IBO glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, iId ); // Make sure the VAO is not changed from outside code glBindVertexArray(0); return; }
void My_TestGLDrawing::InitTest() { _renderIndex = HdRenderIndex::New(&_renderDelegate); TF_VERIFY(_renderIndex != nullptr); _delegate = new Hdx_UnitTestDelegate(_renderIndex); _delegate->SetRefineLevel(_refineLevel); // prepare render task SdfPath renderSetupTask("/renderSetupTask"); SdfPath renderTask("/renderTask"); _delegate->AddRenderSetupTask(renderSetupTask); _delegate->AddRenderTask(renderTask); // render task parameters. HdxRenderTaskParams param = _delegate->GetTaskParam( renderSetupTask, HdTokens->params).Get<HdxRenderTaskParams>(); param.enableLighting = true; // use default lighting _delegate->SetTaskParam(renderSetupTask, HdTokens->params, VtValue(param)); _delegate->SetTaskParam(renderTask, HdTokens->collection, VtValue(HdRprimCollection(HdTokens->geometry, _reprName))); // prepare scene _delegate->AddCube(SdfPath("/cube0"), _GetTranslate( 5, 0, 5)); _delegate->AddCube(SdfPath("/cube1"), _GetTranslate(-5, 0, 5)); _delegate->AddCube(SdfPath("/cube2"), _GetTranslate(-5, 0,-5)); _delegate->AddCube(SdfPath("/cube3"), _GetTranslate( 5, 0,-5)); { _delegate->AddInstancer(SdfPath("/instancerTop")); _delegate->AddCube(SdfPath("/protoTop"), GfMatrix4d(1), false, SdfPath("/instancerTop")); std::vector<SdfPath> prototypes; prototypes.push_back(SdfPath("/protoTop")); VtVec3fArray scale(3); VtVec4fArray rotate(3); VtVec3fArray translate(3); VtIntArray prototypeIndex(3); scale[0] = GfVec3f(1); rotate[0] = GfVec4f(0); translate[0] = GfVec3f(3, 0, 2); prototypeIndex[0] = 0; scale[1] = GfVec3f(1); rotate[1] = GfVec4f(0); translate[1] = GfVec3f(0, 0, 2); prototypeIndex[1] = 0; scale[2] = GfVec3f(1); rotate[2] = GfVec4f(0); translate[2] = GfVec3f(-3, 0, 2); prototypeIndex[2] = 0; _delegate->SetInstancerProperties(SdfPath("/instancerTop"), prototypeIndex, scale, rotate, translate); } { _delegate->AddInstancer(SdfPath("/instancerBottom")); _delegate->AddCube(SdfPath("/protoBottom"), GfMatrix4d(1), false, SdfPath("/instancerBottom")); std::vector<SdfPath> prototypes; prototypes.push_back(SdfPath("/protoBottom")); VtVec3fArray scale(3); VtVec4fArray rotate(3); VtVec3fArray translate(3); VtIntArray prototypeIndex(3); scale[0] = GfVec3f(1); rotate[0] = GfVec4f(0); translate[0] = GfVec3f(3, 0, -2); prototypeIndex[0] = 0; scale[1] = GfVec3f(1); rotate[1] = GfVec4f(0); translate[1] = GfVec3f(0, 0, -2); prototypeIndex[1] = 0; scale[2] = GfVec3f(1); rotate[2] = GfVec4f(0); translate[2] = GfVec3f(-3, 0, -2); prototypeIndex[2] = 0; _delegate->SetInstancerProperties(SdfPath("/instancerBottom"), prototypeIndex, scale, rotate, translate); } SetCameraTranslate(GfVec3f(0, 0, -20)); // XXX: Setup a VAO, the current drawing engine will not yet do this. glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBindVertexArray(0); }
void BlockParticleManager::RenderInstanced(bool noWorldOffset) { glShader* pShader = m_pRenderer->GetShader(m_instanceShader); GLint in_position = glGetAttribLocation(pShader->GetProgramObject(), "in_position"); GLint in_color = glGetAttribLocation(pShader->GetProgramObject(), "in_color"); GLint in_model_matrix = glGetAttribLocation(pShader->GetProgramObject(), "in_model_matrix"); int numBlockParticles = (int)m_vpBlockParticlesList.size(); int numBlockParticlesRender = GetNumRenderableParticles(noWorldOffset); if (numBlockParticlesRender > 0) { float* newMatrices = new float[16 * numBlockParticlesRender]; float* newColors = new float[4 * numBlockParticlesRender]; int counter = 0; for (int i = 0; i < numBlockParticles; i++) { // If we are a emitter creation particle, don't render. if (m_vpBlockParticlesList[i]->m_createEmitters == true) { continue; } // If we are to be erased, don't render if (m_vpBlockParticlesList[i]->m_erase == true) { continue; } // If we are rendering the special viewport particles and our parent particle effect viewport flag isn't set, don't render. if (noWorldOffset) { if (m_vpBlockParticlesList[i]->m_pParent == NULL || m_vpBlockParticlesList[i]->m_pParent->m_pParent == NULL || m_vpBlockParticlesList[i]->m_pParent->m_pParent->m_renderNoWoldOffsetViewport == false) { continue; } } newColors[counter + 0] = m_vpBlockParticlesList[i]->m_currentRed; newColors[counter + 1] = m_vpBlockParticlesList[i]->m_currentGreen; newColors[counter + 2] = m_vpBlockParticlesList[i]->m_currentBlue; newColors[counter + 3] = m_vpBlockParticlesList[i]->m_currentAlpha; counter += 4; } counter = 0; for (int i = 0; i < numBlockParticles; i++) { // If we are a emitter creation particle, don't render. if (m_vpBlockParticlesList[i]->m_createEmitters == true) { continue; } // If we are to be erased, don't render if (m_vpBlockParticlesList[i]->m_erase == true) { continue; } // If we are rendering the special viewport particles and our parent particle effect viewport flag isn't set, don't render. if (noWorldOffset) { if (m_vpBlockParticlesList[i]->m_pParent == NULL || m_vpBlockParticlesList[i]->m_pParent->m_pParent == NULL || m_vpBlockParticlesList[i]->m_pParent->m_pParent->m_renderNoWoldOffsetViewport == false) { continue; } } m_vpBlockParticlesList[i]->CalculateWorldTransformMatrix(); if (noWorldOffset) { newMatrices[counter + 0] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[0]; newMatrices[counter + 1] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[1]; newMatrices[counter + 2] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[2]; newMatrices[counter + 3] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[3]; newMatrices[counter + 4] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[4]; newMatrices[counter + 5] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[5]; newMatrices[counter + 6] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[6]; newMatrices[counter + 7] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[7]; newMatrices[counter + 8] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[8]; newMatrices[counter + 9] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[9]; newMatrices[counter + 10] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[10]; newMatrices[counter + 11] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[11]; newMatrices[counter + 12] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[12]; newMatrices[counter + 13] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[13]; newMatrices[counter + 14] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[14]; newMatrices[counter + 15] = m_vpBlockParticlesList[i]->m_worldMatrix_NoPositionOffset.m[15]; } else { newMatrices[counter + 0] = m_vpBlockParticlesList[i]->m_worldMatrix.m[0]; newMatrices[counter + 1] = m_vpBlockParticlesList[i]->m_worldMatrix.m[1]; newMatrices[counter + 2] = m_vpBlockParticlesList[i]->m_worldMatrix.m[2]; newMatrices[counter + 3] = m_vpBlockParticlesList[i]->m_worldMatrix.m[3]; newMatrices[counter + 4] = m_vpBlockParticlesList[i]->m_worldMatrix.m[4]; newMatrices[counter + 5] = m_vpBlockParticlesList[i]->m_worldMatrix.m[5]; newMatrices[counter + 6] = m_vpBlockParticlesList[i]->m_worldMatrix.m[6]; newMatrices[counter + 7] = m_vpBlockParticlesList[i]->m_worldMatrix.m[7]; newMatrices[counter + 8] = m_vpBlockParticlesList[i]->m_worldMatrix.m[8]; newMatrices[counter + 9] = m_vpBlockParticlesList[i]->m_worldMatrix.m[9]; newMatrices[counter + 10] = m_vpBlockParticlesList[i]->m_worldMatrix.m[10]; newMatrices[counter + 11] = m_vpBlockParticlesList[i]->m_worldMatrix.m[11]; newMatrices[counter + 12] = m_vpBlockParticlesList[i]->m_worldMatrix.m[12]; newMatrices[counter + 13] = m_vpBlockParticlesList[i]->m_worldMatrix.m[13]; newMatrices[counter + 14] = m_vpBlockParticlesList[i]->m_worldMatrix.m[14]; newMatrices[counter + 15] = m_vpBlockParticlesList[i]->m_worldMatrix.m[15]; } counter += 16; } glBindVertexArray(m_vertexArray); if (m_colourBuffer != -1) { glDeleteBuffers(1, &m_colourBuffer); } // Bind buffer for colors and copy data into buffer glGenBuffers(1, &m_colourBuffer); glBindBuffer(GL_ARRAY_BUFFER, m_colourBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 4 * numBlockParticlesRender, newColors, GL_STATIC_READ); glEnableVertexAttribArray(in_color); glVertexAttribPointer(in_color, 4, GL_FLOAT, GL_FALSE, 4 * 4, 0); glVertexAttribDivisor(in_color, 1); if (m_matrixBuffer != -1) { glDeleteBuffers(1, &m_matrixBuffer); } // Bind buffer for matrix and copy data into buffer glGenBuffers(1, &m_matrixBuffer); glBindBuffer(GL_ARRAY_BUFFER, m_matrixBuffer); for (int i = 0; i < 4; i++) { glVertexAttribPointer(in_model_matrix + i, // Location 4, GL_FLOAT, GL_FALSE, // vec4 4 * 16, // Stride reinterpret_cast<void *>(16 * i)); // Start offset glEnableVertexAttribArray(in_model_matrix + i); glVertexAttribDivisor(in_model_matrix + i, 1); } glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 16 * numBlockParticlesRender, newMatrices, GL_STATIC_READ); delete[] newColors; delete[] newMatrices; } // Render the block particle instances m_pRenderer->BeginGLSLShader(m_instanceShader); GLint projMatrixLoc = glGetUniformLocation(pShader->GetProgramObject(), "projMatrix"); GLint viewMatrixLoc = glGetUniformLocation(pShader->GetProgramObject(), "viewMatrix"); Matrix4x4 projMat; Matrix4x4 viewMat; m_pRenderer->GetProjectionMatrix(&projMat); m_pRenderer->GetModelViewMatrix(&viewMat); glUniformMatrix4fv(projMatrixLoc, 1, false, projMat.m); glUniformMatrix4fv(viewMatrixLoc, 1, false, viewMat.m); GLint in_light_position = glGetUniformLocation(pShader->GetProgramObject(), "in_light_position"); GLint in_light_const_a = glGetUniformLocation(pShader->GetProgramObject(), "in_light_const_a"); GLint in_light_linear_a = glGetUniformLocation(pShader->GetProgramObject(), "in_light_linear_a"); GLint in_light_quad_a = glGetUniformLocation(pShader->GetProgramObject(), "in_light_quad_a"); GLint in_light_ambient = glGetUniformLocation(pShader->GetProgramObject(), "in_light_ambient"); GLint in_light_diffuse = glGetUniformLocation(pShader->GetProgramObject(), "in_light_diffuse"); if (m_renderWireFrame) { m_pRenderer->SetLineWidth(1.0f); m_pRenderer->SetRenderMode(RM_WIREFRAME); m_pRenderer->SetCullMode(CM_NOCULL); } else { m_pRenderer->SetCullMode(CM_BACK); m_pRenderer->SetRenderMode(RM_SOLID); } m_pRenderer->EnableTransparency(BF_SRC_ALPHA, BF_ONE_MINUS_SRC_ALPHA); glDrawElementsInstanced(GL_QUADS, 24, GL_UNSIGNED_INT, indices, numBlockParticlesRender); m_pRenderer->DisableTransparency(); m_pRenderer->EndGLSLShader(m_instanceShader); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); }
void BlockParticleManager::SetupGLBuffers() { if (m_instanceShader != -1) { glShader* pShader = m_pRenderer->GetShader(m_instanceShader); GLint in_position = glGetAttribLocation(pShader->GetProgramObject(), "in_position"); GLint in_normal = glGetAttribLocation(pShader->GetProgramObject(), "in_normal"); GLint in_color = glGetAttribLocation(pShader->GetProgramObject(), "in_color"); GLint in_model_matrix = glGetAttribLocation(pShader->GetProgramObject(), "in_model_matrix"); glBindFragDataLocation(pShader->GetProgramObject(), 0, "outputColor"); glBindFragDataLocation(pShader->GetProgramObject(), 1, "outputPosition"); glBindFragDataLocation(pShader->GetProgramObject(), 2, "outputNormal"); if (m_vertexArray != -1) { glDeleteVertexArrays(1, &m_vertexArray); } glGenVertexArrays(1, &m_vertexArray); glBindVertexArray(m_vertexArray); if (m_positionBuffer != -1) { glDeleteBuffers(1, &m_positionBuffer); } glGenBuffers(1, &m_positionBuffer); glBindBuffer(GL_ARRAY_BUFFER, m_positionBuffer); int sizeOfVertices = sizeof(vertices); glBufferData(GL_ARRAY_BUFFER, sizeOfVertices, vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(in_position); glVertexAttribPointer(in_position, 4, GL_FLOAT, 0, 0, 0); if (m_normalBuffer != -1) { glDeleteBuffers(1, &m_normalBuffer); } glGenBuffers(1, &m_normalBuffer); glBindBuffer(GL_ARRAY_BUFFER, m_normalBuffer); int sizeOfNormals = sizeof(normals); glBufferData(GL_ARRAY_BUFFER, sizeOfNormals, normals, GL_STATIC_DRAW); glEnableVertexAttribArray(in_normal); glVertexAttribPointer(in_normal, 4, GL_FLOAT, 0, 0, 0); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } float l_length = 0.5f; float l_height = 0.5f; float l_width = 0.5f; // Create the cube static buffer m_vertexBuffer[0].x = l_length; m_vertexBuffer[0].y = -l_height; m_vertexBuffer[0].z = -l_width; m_vertexBuffer[0].nx = 0.0f; m_vertexBuffer[0].ny = 0.0f; m_vertexBuffer[0].nz = -1.0f; m_vertexBuffer[1].x = -l_length; m_vertexBuffer[1].y = -l_height; m_vertexBuffer[1].z = -l_width; m_vertexBuffer[1].nx = 0.0f; m_vertexBuffer[1].ny = 0.0f; m_vertexBuffer[1].nz = -1.0f; m_vertexBuffer[2].x = -l_length; m_vertexBuffer[2].y = l_height; m_vertexBuffer[2].z = -l_width; m_vertexBuffer[2].nx = 0.0f; m_vertexBuffer[2].ny = 0.0f; m_vertexBuffer[2].nz = -1.0f; m_vertexBuffer[3].x = l_length; m_vertexBuffer[3].y = l_height; m_vertexBuffer[3].z = -l_width; m_vertexBuffer[3].nx = 0.0f; m_vertexBuffer[3].ny = 0.0f; m_vertexBuffer[3].nz = -1.0f; // m_vertexBuffer[4].x = -l_length; m_vertexBuffer[4].y = -l_height; m_vertexBuffer[4].z = l_width; m_vertexBuffer[4].nx = 0.0f; m_vertexBuffer[4].ny = 0.0f; m_vertexBuffer[4].nz = 1.0f; m_vertexBuffer[5].x = l_length; m_vertexBuffer[5].y = -l_height; m_vertexBuffer[5].z = l_width; m_vertexBuffer[5].nx = 0.0f; m_vertexBuffer[5].ny = 0.0f; m_vertexBuffer[5].nz = 1.0f; m_vertexBuffer[6].x = l_length; m_vertexBuffer[6].y = l_height; m_vertexBuffer[6].z = l_width; m_vertexBuffer[6].nx = 0.0f; m_vertexBuffer[6].ny = 0.0f; m_vertexBuffer[6].nz = 1.0f; m_vertexBuffer[7].x = -l_length; m_vertexBuffer[7].y = l_height; m_vertexBuffer[7].z = l_width; m_vertexBuffer[7].nx = 0.0f; m_vertexBuffer[7].ny = 0.0f; m_vertexBuffer[7].nz = 1.0f; // m_vertexBuffer[8].x = l_length; m_vertexBuffer[8].y = -l_height; m_vertexBuffer[8].z = l_width; m_vertexBuffer[8].nx = 1.0f; m_vertexBuffer[8].ny = 0.0f; m_vertexBuffer[8].nz = 0.0f; m_vertexBuffer[9].x = l_length; m_vertexBuffer[9].y = -l_height; m_vertexBuffer[9].z = -l_width; m_vertexBuffer[9].nx = 1.0f; m_vertexBuffer[9].ny = 0.0f; m_vertexBuffer[9].nz = 0.0f; m_vertexBuffer[10].x = l_length; m_vertexBuffer[10].y = l_height; m_vertexBuffer[10].z = -l_width; m_vertexBuffer[10].nx = 1.0f; m_vertexBuffer[10].ny = 0.0f; m_vertexBuffer[10].nz = 0.0f; m_vertexBuffer[11].x = l_length; m_vertexBuffer[11].y = l_height; m_vertexBuffer[11].z = l_width; m_vertexBuffer[11].nx = 1.0f; m_vertexBuffer[11].ny = 0.0f; m_vertexBuffer[11].nz = 0.0f; // m_vertexBuffer[12].x = -l_length; m_vertexBuffer[12].y = -l_height; m_vertexBuffer[12].z = -l_width; m_vertexBuffer[12].nx = -1.0f; m_vertexBuffer[12].ny = 0.0f; m_vertexBuffer[12].nz = 0.0f; m_vertexBuffer[13].x = -l_length; m_vertexBuffer[13].y = -l_height; m_vertexBuffer[13].z = l_width; m_vertexBuffer[13].nx = -1.0f; m_vertexBuffer[13].ny = 0.0f; m_vertexBuffer[13].nz = 0.0f; m_vertexBuffer[14].x = -l_length; m_vertexBuffer[14].y = l_height; m_vertexBuffer[14].z = l_width; m_vertexBuffer[14].nx = -1.0f; m_vertexBuffer[14].ny = 0.0f; m_vertexBuffer[14].nz = 0.0f; m_vertexBuffer[15].x = -l_length; m_vertexBuffer[15].y = l_height; m_vertexBuffer[15].z = -l_width; m_vertexBuffer[15].nx = -1.0f; m_vertexBuffer[15].ny = 0.0f; m_vertexBuffer[15].nz = 0.0f; // m_vertexBuffer[16].x = -l_length; m_vertexBuffer[16].y = -l_height; m_vertexBuffer[16].z = -l_width; m_vertexBuffer[16].nx = 0.0f; m_vertexBuffer[16].ny = -1.0f; m_vertexBuffer[16].nz = 0.0f; m_vertexBuffer[17].x = l_length; m_vertexBuffer[17].y = -l_height; m_vertexBuffer[17].z = -l_width; m_vertexBuffer[17].nx = 0.0f; m_vertexBuffer[17].ny = -1.0f; m_vertexBuffer[17].nz = 0.0f; m_vertexBuffer[18].x = l_length; m_vertexBuffer[18].y = -l_height; m_vertexBuffer[18].z = l_width; m_vertexBuffer[18].nx = 0.0f; m_vertexBuffer[18].ny = -1.0f; m_vertexBuffer[18].nz = 0.0f; m_vertexBuffer[19].x = -l_length; m_vertexBuffer[19].y = -l_height; m_vertexBuffer[19].z = l_width; m_vertexBuffer[19].nx = 0.0f; m_vertexBuffer[19].ny = -1.0f; m_vertexBuffer[19].nz = 0.0f; // m_vertexBuffer[20].x = l_length; m_vertexBuffer[20].y = l_height; m_vertexBuffer[20].z = -l_width; m_vertexBuffer[20].nx = 0.0f; m_vertexBuffer[20].ny = 1.0f; m_vertexBuffer[20].nz = 0.0f; m_vertexBuffer[21].x = -l_length; m_vertexBuffer[21].y = l_height; m_vertexBuffer[21].z = -l_width; m_vertexBuffer[21].nx = 0.0f; m_vertexBuffer[21].ny = 1.0f; m_vertexBuffer[21].nz = 0.0f; m_vertexBuffer[22].x = -l_length; m_vertexBuffer[22].y = l_height; m_vertexBuffer[22].z = l_width; m_vertexBuffer[22].nx = 0.0f; m_vertexBuffer[22].ny = 1.0f; m_vertexBuffer[22].nz = 0.0f; m_vertexBuffer[23].x = l_length; m_vertexBuffer[23].y = l_height; m_vertexBuffer[23].z = l_width; m_vertexBuffer[23].nx = 0.0f; m_vertexBuffer[23].ny = 1.0f; m_vertexBuffer[23].nz = 0.0f; for (int i = 0; i < 24; i++) { m_vertexBuffer[i].r = 1.0f; m_vertexBuffer[i].g = 1.0f; m_vertexBuffer[i].b = 1.0f; m_vertexBuffer[i].a = 1.0f; } }
GLUSboolean init(GLUSvoid) { GLUStextfile vertexSource; GLUStextfile fragmentSource; GLUStgaimage image; GLUSshape plane; // glusMatrix4x4LookAtf(g_viewMatrix, g_camera.eye[0], g_camera.eye[1], g_camera.eye[2], g_camera.center[0], g_camera.center[1], g_camera.center[2], g_camera.up[0], g_camera.up[1], g_camera.up[2]); // if (!initWavefront(g_viewMatrix, &g_light)) { return GLUS_FALSE; } // glusFileLoadText("../Example19_ES/shader/basic_proj.vert.glsl", &vertexSource); glusFileLoadText("../Example19_ES/shader/texture_multi_proj.frag.glsl", &fragmentSource); glusProgramBuildFromSource(&g_program, (const GLUSchar**) &vertexSource.text, (const GLUSchar**) &fragmentSource.text); glusFileDestroyText(&vertexSource); glusFileDestroyText(&fragmentSource); // // Retrieve the uniform locations in the program. g_viewProjectionMatrixLocation = glGetUniformLocation(g_program.program, "u_viewProjectionMatrix"); g_viewProjectionBiasTextureMatrixLocation = glGetUniformLocation(g_program.program, "u_viewProjectionBiasTextureMatrix"); g_modelMatrixLocation = glGetUniformLocation(g_program.program, "u_modelMatrix"); g_normalMatrixLocation = glGetUniformLocation(g_program.program, "u_normalMatrix"); g_lightDirectionLocation = glGetUniformLocation(g_program.program, "u_lightDirection"); g_repeatLocation = glGetUniformLocation(g_program.program, "u_repeat"); g_textureLocation = glGetUniformLocation(g_program.program, "u_texture"); g_mirrorTextureLocation = glGetUniformLocation(g_program.program, "u_mirrorTexture"); // Retrieve the attribute locations in the program. g_vertexLocation = glGetAttribLocation(g_program.program, "a_vertex"); g_normalLocation = glGetAttribLocation(g_program.program, "a_normal"); g_texCoordLocation = glGetAttribLocation(g_program.program, "a_texCoord"); // // Texture set up. glusImageLoadTga("ice.tga", &image); glGenTextures(1, &g_texture); glBindTexture(GL_TEXTURE_2D, g_texture); glTexImage2D(GL_TEXTURE_2D, 0, image.format, image.width, image.height, 0, image.format, GL_UNSIGNED_BYTE, image.data); // Mipmap generation is now included in OpenGL 3 and above glGenerateMipmap(GL_TEXTURE_2D); // Trilinear filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glBindTexture(GL_TEXTURE_2D, 0); // // Setting up the offscreen frame buffer. // glGenTextures(1, &g_mirrorTexture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, g_mirrorTexture); glTexImage2D(GL_TEXTURE_2D, 0, GLUS_RGB, TEXTURE_WIDTH, TEXTURE_HEIGHT, 0, GLUS_RGB, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); // glGenRenderbuffers(1, &g_depthMirrorTexture); glBindRenderbuffer(GL_RENDERBUFFER, g_depthMirrorTexture); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, TEXTURE_WIDTH, TEXTURE_HEIGHT); glBindRenderbuffer(GL_RENDERBUFFER, 0); // glGenFramebuffers(1, &g_fboMirrorTexture); glBindFramebuffer(GL_FRAMEBUFFER, g_fboMirrorTexture); // Attach the color buffer ... glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, g_mirrorTexture, 0); // ... and the depth buffer, glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, g_depthMirrorTexture); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { printf("GL_FRAMEBUFFER_COMPLETE error 0x%x", glCheckFramebufferStatus(GL_FRAMEBUFFER)); return GLUS_FALSE; } glBindFramebuffer(GL_FRAMEBUFFER, 0); // // // glusShapeCreatePlanef(&plane, 3.0f); g_numberIndicesSphere = plane.numberIndices; glGenBuffers(1, &g_verticesVBO); glBindBuffer(GL_ARRAY_BUFFER, g_verticesVBO); glBufferData(GL_ARRAY_BUFFER, plane.numberVertices * 4 * sizeof(GLfloat), (GLfloat*) plane.vertices, GL_STATIC_DRAW); glGenBuffers(1, &g_normalsVBO); glBindBuffer(GL_ARRAY_BUFFER, g_normalsVBO); glBufferData(GL_ARRAY_BUFFER, plane.numberVertices * 3 * sizeof(GLfloat), (GLfloat*) plane.normals, GL_STATIC_DRAW); glGenBuffers(1, &g_texCoordsVBO); glBindBuffer(GL_ARRAY_BUFFER, g_texCoordsVBO); glBufferData(GL_ARRAY_BUFFER, plane.numberVertices * 2 * sizeof(GLfloat), (GLfloat*) plane.texCoords, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &g_indicesVBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesVBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, plane.numberIndices * sizeof(GLuint), (GLuint*) plane.indices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glusShapeDestroyf(&plane); // glUseProgram(g_program.program); glGenVertexArrays(1, &g_vao); glBindVertexArray(g_vao); glBindBuffer(GL_ARRAY_BUFFER, g_verticesVBO); glVertexAttribPointer(g_vertexLocation, 4, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_vertexLocation); glBindBuffer(GL_ARRAY_BUFFER, g_normalsVBO); glVertexAttribPointer(g_normalLocation, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_normalLocation); glBindBuffer(GL_ARRAY_BUFFER, g_texCoordsVBO); glVertexAttribPointer(g_texCoordLocation, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_texCoordLocation); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesVBO); // glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, g_texture); glUniform1i(g_textureLocation, 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, g_mirrorTexture); glUniform1i(g_mirrorTextureLocation, 1); // How many times the surface texture is repeated. glUniform1f(g_repeatLocation, 6.0f); // glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepthf(1.0f); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); return GLUS_TRUE; }
GLUSvoid terminate(GLUSvoid) { glBindBuffer(GL_ARRAY_BUFFER, 0); if (g_verticesVBO) { glDeleteBuffers(1, &g_verticesVBO); g_verticesVBO = 0; } if (g_normalsVBO) { glDeleteBuffers(1, &g_normalsVBO); g_normalsVBO = 0; } if (g_texCoordsVBO) { glDeleteBuffers(1, &g_texCoordsVBO); g_texCoordsVBO = 0; } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); if (g_indicesVBO) { glDeleteBuffers(1, &g_indicesVBO); g_indicesVBO = 0; } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); if (g_texture) { glDeleteTextures(1, &g_texture); g_texture = 0; } glBindVertexArray(0); if (g_vao) { glDeleteVertexArrays(1, &g_vao); g_vao = 0; } glUseProgram(0); glusProgramDestroy(&g_program); // glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, 0); if (g_mirrorTexture) { glDeleteTextures(1, &g_mirrorTexture); g_mirrorTexture = 0; } glBindRenderbuffer(GL_RENDERBUFFER, 0); if (g_depthMirrorTexture) { glDeleteRenderbuffers(1, &g_depthMirrorTexture); g_depthMirrorTexture = 0; } glBindFramebuffer(GL_FRAMEBUFFER, 0); if (g_fboMirrorTexture) { glDeleteFramebuffers(1, &g_fboMirrorTexture); g_fboMirrorTexture = 0; } terminateWavefront(); }
GLUSboolean update(GLUSfloat time) { // Bias needed to convert the from [-1;1] to [0;1] GLfloat biasMatrix[16] = {0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f}; // Frame buffer has another view port and so perspective projection. Needed for projected texturing of the mirror texture. GLfloat viewProjectionBiasTextureMatrix[16]; // This matrix is used to flip the rendered object upside down. GLfloat scaleMatrix[16]; // Store current width and height for later reseting. GLuint width = g_width; GLuint height = g_height; // // Upside down rendering to frame buffer. // glBindFramebuffer(GL_FRAMEBUFFER, g_fboMirrorTexture); reshape(TEXTURE_WIDTH, TEXTURE_HEIGHT); glClearColor(1.0f, 1.0f, 1.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glusMatrix4x4Identityf(scaleMatrix); glusMatrix4x4Scalef(scaleMatrix, 1.0f, -1.0f, 1.0f); glFrontFace(GL_CW); if (!updateWavefront(time, scaleMatrix)) { return GLUS_FALSE; } glBindFramebuffer(GL_FRAMEBUFFER, 0); // Save the current projection matrix for later usage. glusMatrix4x4Copyf(viewProjectionBiasTextureMatrix, g_viewProjectionMatrix, GLUS_FALSE); glusMatrix4x4Multiplyf(viewProjectionBiasTextureMatrix, biasMatrix, viewProjectionBiasTextureMatrix); // // Scene rendering // reshape(width, height); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Normal rendering glusMatrix4x4Identityf(scaleMatrix); glFrontFace(GL_CCW); if (!updateWavefront(time, scaleMatrix)) { return GLUS_FALSE; } glUseProgram(g_program.program); // This matrix is needed to calculate the vertices into the frame buffer render pass. glUniformMatrix4fv(g_viewProjectionBiasTextureMatrixLocation, 1, GL_FALSE, viewProjectionBiasTextureMatrix); glBindVertexArray(g_vao); glDrawElements(GL_TRIANGLES, g_numberIndicesSphere, GL_UNSIGNED_INT, 0); return GLUS_TRUE; }
void SetupRC() { bool loadFromFile = false; instancingShader = gltLoadShaderPair("instancing.vs", "instancing.fs", loadFromFile); glLinkProgram(instancingShader); glUseProgram(instancingShader); glFinish(); ModelViewMatrix = glGetUniformLocation(instancingShader, "ModelViewMatrix"); ProjectionMatrix = glGetUniformLocation(instancingShader, "ProjectionMatrix"); NormalMatrix = glGetUniformLocation(instancingShader, "NormalMatrix"); uniform_texture_diffuse = glGetUniformLocation(instancingShader, "Diffuse"); GLuint offset = 0; glGenVertexArrays(1, &cube_vao); glGenBuffers(1, &cube_vbo); glBindVertexArray(cube_vao); glBindBuffer(GL_ARRAY_BUFFER, cube_vbo); instance_positions_ptr = (GLfloat*)new float[NUM_OBJECTS*4]; instance_quaternion_ptr = (GLfloat*)new float[NUM_OBJECTS*4]; int index=0; for (int i=0;i<NUM_OBJECTS_X;i++) for (int j=0;j<NUM_OBJECTS_Y;j++) for (int k=0;k<NUM_OBJECTS_Z;k++) { instance_positions_ptr[index*4]=-(i-NUM_OBJECTS_X/2)*10; instance_positions_ptr[index*4+1]=-(j-NUM_OBJECTS_Y/2)*10; instance_positions_ptr[index*4+2]=-k*10; instance_positions_ptr[index*4+3]=1; instance_quaternion_ptr[index*4]=0; instance_quaternion_ptr[index*4+1]=0; instance_quaternion_ptr[index*4+2]=0; instance_quaternion_ptr[index*4+3]=1; index++; } glBufferData(GL_ARRAY_BUFFER, sizeof(cube_vertices) + sizeof(instance_colors) + POSITION_BUFFER_SIZE+ORIENTATION_BUFFER_SIZE, NULL, GL_DYNAMIC_DRAW);//GL_STATIC_DRAW); ///initialize parts of the buffer glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(cube_vertices), cube_vertices); glBufferSubData(GL_ARRAY_BUFFER, sizeof(cube_vertices), sizeof(instance_colors), instance_colors); glBufferSubData(GL_ARRAY_BUFFER, sizeof(cube_vertices) + sizeof(instance_colors), POSITION_BUFFER_SIZE, instance_positions_ptr); glBufferSubData(GL_ARRAY_BUFFER, sizeof(cube_vertices) + sizeof(instance_colors)+POSITION_BUFFER_SIZE,ORIENTATION_BUFFER_SIZE , instance_quaternion_ptr); glBindBuffer(GL_ARRAY_BUFFER,0); glGenBuffers(1, &index_vbo); int indexBufferSize = sizeof(cube_indices); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_vbo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexBufferSize, NULL, GL_STATIC_DRAW); glBufferSubData(GL_ELEMENT_ARRAY_BUFFER,0,indexBufferSize,cube_indices); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); }
void TreeNode::init(Tree * tree, HeightMapNode * heightMapNode){ _heightMapNode = heightMapNode; this-> tree = tree; std::vector<float> vertices; std::vector<float> normals; std::vector<int> indices; glm::vec3 * branchNodes = tree->branchNodes; float radius = tree->radius; float twigging = 0.7*(1.0-pow(2,-1*(float)tree->MAXDEPTH)); { //make trunk glm::vec3 curr = branchNodes[0]; glm::vec3 next = branchNodes[1]; glm::vec3 axis1 = glm::normalize(next - curr); glm::vec3 axis2 = glm::normalize(glm::vec3(0,float(-1)*axis1.z,axis1.y)); glm::vec3 axis3 = glm::cross(axis1,axis2); //generate vertices int subdivisions = 20; for(int i=0;i<=subdivisions;i++){ float angle = 2*PI*((float)i/(float) subdivisions); //bottom glm::vec3 norm = float(cos(angle))*axis2 + float(sin(angle))*axis3; glm::vec3 point1 = (float(cos(angle))*axis2 + float(sin(angle))*axis3)*radius + curr; vertices.push_back(point1.x); vertices.push_back(point1.y); vertices.push_back(point1.z); vertices.push_back(norm.x); vertices.push_back(norm.y); vertices.push_back(norm.z); //top glm::vec3 point2 = (float(cos(angle))*axis2 + float(sin(angle))*axis3)*radius + next; vertices.push_back(point2.x); vertices.push_back(point2.y); vertices.push_back(point2.z); vertices.push_back(norm.x); vertices.push_back(norm.y); vertices.push_back(norm.z); } //generate triangles // 0 2 1, 1 2 3, 2 4 3, 3 4 5 for(int i= 0; i< subdivisions;i++){ int k = 2*i; indices.push_back(k); indices.push_back(k+2); indices.push_back(k+1); indices.push_back(k+1); indices.push_back(k+2); indices.push_back(k+3); } //rest of the branches for(int branch=1;branch < tree->numNodes/2;branch++){ int leftI = 2*branch; int rightI = leftI+1; curr = branchNodes[branch]; //for the left next = branchNodes[leftI]; axis1 = glm::normalize(next - curr); axis2 = glm::normalize(glm::vec3(0,float(-1)*axis1.z,axis1.y)); axis3 = glm::cross(axis1,axis2); int start = vertices.size()/6; for(int i=0;i<=subdivisions;i++){ float angle = 2*PI*((float)i/(float) subdivisions); //bottom glm::vec3 norm = float(cos(angle))*axis2 + float(sin(angle))*axis3; glm::vec3 point1 = (float(cos(angle))*axis2 + float(sin(angle))*axis3 ) *radius*(float)pow(twigging,floor(log2(branch)))+ curr; vertices.push_back(point1.x); vertices.push_back(point1.y); vertices.push_back(point1.z); vertices.push_back(norm.x); vertices.push_back(norm.y); vertices.push_back(norm.z); //top glm::vec3 point2 = (float(cos(angle))*axis2 + float(sin(angle))*axis3)*radius*(float)pow(twigging,floor(log2(branch)) + 1) + next; vertices.push_back(point2.x); vertices.push_back(point2.y); vertices.push_back(point2.z); vertices.push_back(norm.x); vertices.push_back(norm.y); vertices.push_back(norm.z); } for(int i= 0; i< subdivisions;i++){ int k = 2*i + start; indices.push_back(k); indices.push_back(k+2); indices.push_back(k+1); indices.push_back(k+1); indices.push_back(k+2); indices.push_back(k+3); } //for the right next = branchNodes[rightI]; axis1 = glm::normalize(next - curr); axis2 = glm::vec3(0,float(-1)*axis1.z,axis1.y); axis3 = glm::cross(axis1,axis2); start = vertices.size()/6; for(int i=0;i<=subdivisions;i++){ float angle = 2*PI*((float)i/(float) subdivisions); //bottom glm::vec3 norm = float(cos(angle))*axis2 + float(sin(angle))*axis3; glm::vec3 point1 = (float(cos(angle))*axis2 + float(sin(angle))*axis3 ) *radius*(float)pow(twigging,floor(log2(branch)))+ curr; vertices.push_back(point1.x); vertices.push_back(point1.y); vertices.push_back(point1.z); vertices.push_back(norm.x); vertices.push_back(norm.y); vertices.push_back(norm.z); //top glm::vec3 point2 = (float(cos(angle))*axis2 + float(sin(angle))*axis3)*radius*(float)pow(twigging,floor(log2(branch)) + 1) + next; vertices.push_back(point2.x); vertices.push_back(point2.y); vertices.push_back(point2.z); vertices.push_back(norm.x); vertices.push_back(norm.y); vertices.push_back(norm.z); } for(int i= 0; i< subdivisions;i++){ int k = 2*i + start; indices.push_back(k); indices.push_back(k+2); indices.push_back(k+1); indices.push_back(k+1); indices.push_back(k+2); indices.push_back(k+3); } nindices = indices.size(); } } { glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, vertices.size()*sizeof(float), &vertices[0], GL_STATIC_DRAW); glGenBuffers(1, &ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size()*sizeof(int), &indices[0], GL_STATIC_DRAW); // glActiveTexture(GL_TEXTURE0); // glGenTextures(1, &tex); // glBindTexture(GL_TEXTURE_2D, tex); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, heightMap->getResolutionX(), heightMap->getResolutionY(), 0, GL_RED, GL_FLOAT, heightMap->getHeightData()); } { std::vector<std::string> files; files.push_back(core::Resources::pathForResource("Shaders/Common.glsl")); files.push_back(core::Resources::pathForResource("Shaders/Terrain/Helper.glsl")); files.push_back(core::Resources::pathForResource("Shaders/Tree/Tree.glsl")); // files.push_back(core::Resources::pathForResource("Shaders/Terrain/Material.glsl")); materialShader.loadFromFiles(files); materialShader.addUniform("modelMatrix"); materialShader.addUniform("viewMatrix"); materialShader.addUniform("projectionMatrix"); materialShader.addUniform("terrain_heightMap"); materialShader.addUniform("terrain_size"); materialShader.addUniform("terrain_height"); materialShader.addAttribute("position"); materialShader.addAttribute("normal"); glBindVertexArray(vao); materialShader.use(); glUniform1f(materialShader("terrain_size"), heightMapNode->heightMap->getSizeX()); glUniform1f(materialShader("terrain_height"), heightMapNode->height); glEnableVertexAttribArray(materialShader["position"]); glVertexAttribPointer(materialShader["position"], 3, GL_FLOAT, GL_FALSE, 6*sizeof(float), 0); glEnableVertexAttribArray(materialShader["normal"]); glVertexAttribPointer(materialShader["normal"], 3, GL_FLOAT, GL_FALSE, 6*sizeof(float), (void *) (3*sizeof(float))); materialShader.unUse(); glBindVertexArray(0); } }
bool render() { glm::vec2 WindowSize(this->getWindowSize()); { glBindBuffer(GL_UNIFORM_BUFFER, BufferName[buffer::TRANSFORM]); glm::mat4* Pointer = (glm::mat4*)glMapBufferRange( GL_UNIFORM_BUFFER, 0, sizeof(glm::mat4), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); glm::mat4 Projection = glm::perspectiveFov(glm::pi<float>() * 0.25f, WindowSize.x, WindowSize.y, 0.1f, 100.0f); glm::mat4 Model = glm::mat4(1.0f); *Pointer = Projection * this->view() * Model; // Make sure the uniform buffer is uploaded glUnmapBuffer(GL_UNIFORM_BUFFER); } glViewportIndexedf(0, 0, 0, WindowSize.x, WindowSize.y); glClearBufferfv(GL_COLOR, 0, &glm::vec4(1.0f)[0]); glBindProgramPipeline(PipelineName); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D_ARRAY, TextureName); glBindVertexArray(VertexArrayName); glBindBufferBase(GL_UNIFORM_BUFFER, semantic::uniform::TRANSFORM0, BufferName[buffer::TRANSFORM]); glBeginQuery(GL_VERTICES_SUBMITTED_ARB, this->QueryName[statistics::VERTICES_SUBMITTED]); glBeginQuery(GL_PRIMITIVES_SUBMITTED_ARB, this->QueryName[statistics::PRIMITIVES_SUBMITTED]); glBeginQuery(GL_VERTEX_SHADER_INVOCATIONS_ARB, this->QueryName[statistics::VERTEX_SHADER_INVOCATIONS]); glBeginQuery(GL_TESS_CONTROL_SHADER_PATCHES_ARB, this->QueryName[statistics::TESS_CONTROL_SHADER_PATCHES]); glBeginQuery(GL_TESS_EVALUATION_SHADER_INVOCATIONS_ARB, this->QueryName[statistics::TESS_EVALUATION_SHADER_INVOCATIONS]); glBeginQuery(GL_GEOMETRY_SHADER_INVOCATIONS, this->QueryName[statistics::GEOMETRY_SHADER_INVOCATIONS]); glBeginQuery(GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED_ARB, this->QueryName[statistics::GEOMETRY_SHADER_PRIMITIVES_EMITTED]); glBeginQuery(GL_FRAGMENT_SHADER_INVOCATIONS_ARB, this->QueryName[statistics::FRAGMENT_SHADER_INVOCATIONS]); glBeginQuery(GL_COMPUTE_SHADER_INVOCATIONS_ARB, this->QueryName[statistics::COMPUTE_SHADER_INVOCATIONS]); glBeginQuery(GL_CLIPPING_INPUT_PRIMITIVES_ARB, this->QueryName[statistics::CLIPPING_INPUT_PRIMITIVES]); glBeginQuery(GL_CLIPPING_OUTPUT_PRIMITIVES_ARB, this->QueryName[statistics::CLIPPING_OUTPUT_PRIMITIVES]); glDrawElementsInstancedBaseVertexBaseInstance(GL_TRIANGLES, ElementCount, GL_UNSIGNED_SHORT, 0, 1, 0, 0); glEndQuery(GL_VERTICES_SUBMITTED_ARB); glEndQuery(GL_PRIMITIVES_SUBMITTED_ARB); glEndQuery(GL_VERTEX_SHADER_INVOCATIONS_ARB); glEndQuery(GL_TESS_CONTROL_SHADER_PATCHES_ARB); glEndQuery(GL_TESS_EVALUATION_SHADER_INVOCATIONS_ARB); glEndQuery(GL_GEOMETRY_SHADER_INVOCATIONS); glEndQuery(GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED_ARB); glEndQuery(GL_FRAGMENT_SHADER_INVOCATIONS_ARB); glEndQuery(GL_COMPUTE_SHADER_INVOCATIONS_ARB); glEndQuery(GL_CLIPPING_INPUT_PRIMITIVES_ARB); glEndQuery(GL_CLIPPING_OUTPUT_PRIMITIVES_ARB); std::array<GLuint, statistics::MAX> QueryResult; for(std::size_t i = 0; i < QueryResult.size(); ++i) glGetQueryObjectuiv(this->QueryName[i], GL_QUERY_RESULT, &QueryResult[i]); fprintf(stdout, "Verts: %d; Prims: (%d, %d); Shaders(%d, %d, %d, %d, %d, %d); Clip(%d, %d)\r", QueryResult[statistics::VERTICES_SUBMITTED], QueryResult[statistics::PRIMITIVES_SUBMITTED], QueryResult[statistics::GEOMETRY_SHADER_PRIMITIVES_EMITTED], QueryResult[statistics::VERTEX_SHADER_INVOCATIONS], QueryResult[statistics::TESS_CONTROL_SHADER_PATCHES], QueryResult[statistics::TESS_EVALUATION_SHADER_INVOCATIONS], QueryResult[statistics::GEOMETRY_SHADER_INVOCATIONS], QueryResult[statistics::FRAGMENT_SHADER_INVOCATIONS], QueryResult[statistics::COMPUTE_SHADER_INVOCATIONS], QueryResult[statistics::CLIPPING_INPUT_PRIMITIVES], QueryResult[statistics::CLIPPING_OUTPUT_PRIMITIVES]); return true; }
void FillPath(Geometry::Path& path,Graphics::Colour colour) { const unsigned int first_offset = total_vertex_count; const unsigned int vertex_count = path.size() + 1; ShapeSegmentData data = {{colour.red,colour.green,colour.blue,colour.alpha},{0,0}}; double x_max; double x_min; double y_max; double y_min; if(!path.isClosed()) { throw std::runtime_error("Path must be closed to use draw a shape."); } x_max = std::numeric_limits<double>::lowest(); x_min = -x_max; y_max = std::numeric_limits<double>::lowest(); y_min = -y_max; for(Point& point : path) { if(point.x < x_min) { x_min = point.x; } if(point.x > x_max) { x_max = point.x; } if(point.y < y_min) { y_min = point.y; } if(point.y > y_max) { y_max = point.y; } } glBindBuffer(GL_ARRAY_BUFFER,buffer_handle); data.position[0] = (x_min + x_max) / 2; data.position[1] = (y_min + y_max) / 2; glBufferSubData(GL_ARRAY_BUFFER,total_vertex_count * sizeof(data),sizeof(data),&data); ++total_vertex_count; for(Point& point : path) { data.position[0] = point.x; data.position[1] = point.y; glBufferSubData(GL_ARRAY_BUFFER,total_vertex_count * sizeof(data),sizeof(data),&data); ++total_vertex_count; } glBindBuffer(GL_ARRAY_BUFFER,0); Point translate = OpenGL::GetOrigin(); OpenGL::AddRenderTask([first_offset,vertex_count,translate](){ glUseProgram(program_handle); glBindVertexArray(array_handle); glBindBuffer(GL_ARRAY_BUFFER,buffer_handle); glUniform2f(uniform_translate,translate.x,translate.y); glDrawArrays(GL_TRIANGLE_FAN,first_offset,vertex_count); glBindBuffer(GL_ARRAY_BUFFER,0); glBindVertexArray(0); glUseProgram(0); total_vertex_count -= vertex_count; }); }
GLUSboolean init(GLUSvoid) { GLUSshape backgroundSphere; GLUSshape wavefront; // 6 sides of diffuse and specular; all roughness levels of specular. GLUShdrimage image[6 * NUMBER_ROUGHNESS + 6]; // The look up table (LUT) is stored in a raw binary file. GLUSbinaryfile rawimage; GLUStextfile vertexSource; GLUStextfile fragmentSource; GLchar buffer[27] = "doge2/doge2_POS_X_00_s.hdr"; GLint i, k, m; // glusLoadTextFile("../Example33/shader/brdf.vert.glsl", &vertexSource); glusLoadTextFile("../Example33/shader/brdf.frag.glsl", &fragmentSource); glusBuildProgramFromSource(&g_modelProgram, (const GLchar**)&vertexSource.text, 0, 0, 0, (const GLchar**)&fragmentSource.text); glusDestroyTextFile(&vertexSource); glusDestroyTextFile(&fragmentSource); g_viewProjectionMatrixModelLocation = glGetUniformLocation(g_modelProgram.program, "u_viewProjectionMatrix"); g_modelMatrixModelLocation = glGetUniformLocation(g_modelProgram.program, "u_modelMatrix"); g_normalMatrixModelLocation = glGetUniformLocation(g_modelProgram.program, "u_normalMatrix"); g_eyeModelLocation = glGetUniformLocation(g_modelProgram.program, "u_eye"); g_textureSpecularModelLocation = glGetUniformLocation(g_modelProgram.program, "u_textureSpecular"); g_textureDiffuseModelLocation = glGetUniformLocation(g_modelProgram.program, "u_textureDiffuse"); g_textureLUTModelLocation = glGetUniformLocation(g_modelProgram.program, "u_textureLUT"); g_colorMaterialModelLocation = glGetUniformLocation(g_modelProgram.program, "u_colorMaterial"); g_roughnessMaterialModelLocation = glGetUniformLocation(g_modelProgram.program, "u_roughnessMaterial"); g_roughnessScaleModelLocation = glGetUniformLocation(g_modelProgram.program, "u_roughnessScale"); g_R0MaterialModelLocation = glGetUniformLocation(g_modelProgram.program, "u_R0Material"); g_vertexModelLocation = glGetAttribLocation(g_modelProgram.program, "a_vertex"); g_normalModelLocation = glGetAttribLocation(g_modelProgram.program, "a_normal"); // glusLoadTextFile("../Example33/shader/fullscreen.vert.glsl", &vertexSource); glusLoadTextFile("../Example33/shader/fullscreen.frag.glsl", &fragmentSource); glusBuildProgramFromSource(&g_fullscreenProgram, (const GLchar**)&vertexSource.text, 0, 0, 0, (const GLchar**)&fragmentSource.text); glusDestroyTextFile(&vertexSource); glusDestroyTextFile(&fragmentSource); // g_framebufferTextureFullscreenLocation = glGetUniformLocation(g_fullscreenProgram.program, "u_framebufferTexture"); g_msaaSamplesFullscreenLocation = glGetUniformLocation(g_fullscreenProgram.program, "u_msaaSamples"); g_exposureFullscreenLocation = glGetUniformLocation(g_fullscreenProgram.program, "u_exposure"); g_gammaFullscreenLocation = glGetUniformLocation(g_fullscreenProgram.program, "u_gamma"); // // glusLoadTextFile("../Example33/shader/background.vert.glsl", &vertexSource); glusLoadTextFile("../Example33/shader/background.frag.glsl", &fragmentSource); glusBuildProgramFromSource(&g_backgroundProgram, (const GLUSchar**)&vertexSource.text, 0, 0, 0, (const GLUSchar**)&fragmentSource.text); glusDestroyTextFile(&vertexSource); glusDestroyTextFile(&fragmentSource); // g_viewProjectionMatrixBackgroundLocation = glGetUniformLocation(g_backgroundProgram.program, "u_viewProjectionMatrix"); g_textureBackgroundLocation = glGetUniformLocation(g_backgroundProgram.program, "u_texture"); g_vertexBackgroundLocation = glGetAttribLocation(g_backgroundProgram.program, "a_vertex"); // // Setting up the full screen frame buffer. // glGenTextures(1, &g_fullscreenTexture); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, g_fullscreenTexture); // Create MSAA texture. glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, MSAA_SAMPLES, GL_RGB32F, SCREEN_WIDTH, SCREEN_HEIGHT, GL_TRUE); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); // No need to access the depth buffer, so a render buffer is sufficient. glGenRenderbuffers(1, &g_fullscreenDepthRenderbuffer); glBindRenderbuffer(GL_RENDERBUFFER, g_fullscreenDepthRenderbuffer); glRenderbufferStorageMultisample(GL_RENDERBUFFER, MSAA_SAMPLES, GL_DEPTH_COMPONENT, SCREEN_WIDTH, SCREEN_HEIGHT); glBindRenderbuffer(GL_RENDERBUFFER, 0); // glGenFramebuffers(1, &g_fullscreenFBO); glBindFramebuffer(GL_FRAMEBUFFER, g_fullscreenFBO); // Attach the color buffer ... glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, g_fullscreenTexture, 0); // ... and the depth buffer. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, g_fullscreenDepthRenderbuffer); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { printf("GL_FRAMEBUFFER_COMPLETE error 0x%x", glCheckFramebufferStatus(GL_FRAMEBUFFER)); return GLUS_FALSE; } glBindFramebuffer(GL_FRAMEBUFFER, 0); // // // for (i = 0; i < 2; i++) { if (i == 0) { buffer[21] = 's'; } else { buffer[21] = 'd'; } for (k = 0; k < NUMBER_ROUGHNESS; k++) { if (i == 1 && k > 0) { continue; } buffer[18] = '0' + k / 10; buffer[19] = '0' + k % 10; for (m = 0; m < 6; m++) { if (m % 2 == 0) { buffer[12] = 'P'; buffer[13] = 'O'; buffer[14] = 'S'; } else { buffer[12] = 'N'; buffer[13] = 'E'; buffer[14] = 'G'; } switch (m) { case 0: case 1: buffer[16] = 'X'; break; case 2: case 3: buffer[16] = 'Y'; break; case 4: case 5: buffer[16] = 'Z'; break; } printf("Loading '%s' ...", buffer); if (!glusLoadHdrImage(buffer, &image[i*NUMBER_ROUGHNESS*6 + k*6 + m])) { printf(" error!\n"); continue; } printf(" done.\n"); } } } glGenTextures(1, &g_texture[0]); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, g_texture[0]); glTexImage3D(GL_TEXTURE_CUBE_MAP_ARRAY, 0, GL_RGB32F, image[0].width, image[0].height, 6*NUMBER_ROUGHNESS, 0, GL_RGB, GL_FLOAT, 0); glusLogPrintError(GLUS_LOG_INFO, "glTexImage3D()"); for (i = 0; i < NUMBER_ROUGHNESS; i++) { for (k = 0; k < 6; k++) { glTexSubImage3D(GL_TEXTURE_CUBE_MAP_ARRAY, 0, 0, 0, 6*i + k, image[i*6 + k].width, image[i*6 + k].height, 1, image[i*6 + k].format, GL_FLOAT, image[i*6 + k].data); glusLogPrintError(GLUS_LOG_INFO, "glTexSubImage3D() %d %d", i, k); } } glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, 0); // glGenTextures(1, &g_texture[1]); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_CUBE_MAP, g_texture[1]); for (i = 0; i < 6; i++) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, image[i + 6*NUMBER_ROUGHNESS].format, image[i + 6*NUMBER_ROUGHNESS].width, image[i + 6*NUMBER_ROUGHNESS].height, 0, image[i + 6*NUMBER_ROUGHNESS].format, GL_FLOAT, image[i + 6*NUMBER_ROUGHNESS].data); glusLogPrintError(GLUS_LOG_INFO, "glTexImage2D() %d", i); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); // printf("Loading 'doge2/EnvironmentBRDF_1024.data' ..."); if (!glusLoadBinaryFile("doge2/EnvironmentBRDF_1024.data", &rawimage)) { printf(" error!\n"); } else { printf(" done.\n"); } glGenTextures(1, &g_texture[2]); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, g_texture[2]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RG32F, 1024, 1024, 0, GL_RG, GL_FLOAT, (GLfloat*)rawimage.binary); glusLogPrintError(GLUS_LOG_INFO, "glTexImage2D()"); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); glusDestroyBinaryFile(&rawimage); // for (i = 0; i < 2; i++) { for (k = 0; k < NUMBER_ROUGHNESS; k++) { if (i == 1 && k > 0) { continue; } for (m = 0; m < 6; m++) { glusDestroyHdrImage(&image[i*NUMBER_ROUGHNESS*6 + k*6 + m]); } } } // glusCreateSpheref(&backgroundSphere, 500.0f, 32); g_numberIndicesBackground = backgroundSphere.numberIndices; glGenBuffers(1, &g_verticesBackgroundVBO); glBindBuffer(GL_ARRAY_BUFFER, g_verticesBackgroundVBO); glBufferData(GL_ARRAY_BUFFER, backgroundSphere.numberVertices * 4 * sizeof(GLfloat), (GLfloat*)backgroundSphere.vertices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &g_indicesBackgroundVBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesBackgroundVBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, backgroundSphere.numberIndices * sizeof(GLuint), (GLuint*)backgroundSphere.indices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glusDestroyShapef(&backgroundSphere); // // // Use a helper function to load an wavefront object file. glusLoadObjFile("venusm.obj", &wavefront); g_numberVerticesModel = wavefront.numberVertices; glGenBuffers(1, &g_verticesModelVBO); glBindBuffer(GL_ARRAY_BUFFER, g_verticesModelVBO); glBufferData(GL_ARRAY_BUFFER, wavefront.numberVertices * 4 * sizeof(GLfloat), (GLfloat*)wavefront.vertices, GL_STATIC_DRAW); glGenBuffers(1, &g_normalsModelVBO); glBindBuffer(GL_ARRAY_BUFFER, g_normalsModelVBO); glBufferData(GL_ARRAY_BUFFER, wavefront.numberVertices * 3 * sizeof(GLfloat), (GLfloat*)wavefront.normals, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glusDestroyShapef(&wavefront); // glUseProgram(g_modelProgram.program); glUniform4fv(g_eyeModelLocation, 1, g_eye); glUniform1i(g_textureSpecularModelLocation, 0); glUniform1i(g_textureDiffuseModelLocation, 1); glUniform1i(g_textureLUTModelLocation, 2); glUniform1f(g_roughnessScaleModelLocation, (GLfloat)(NUMBER_ROUGHNESS - 1)); glGenVertexArrays(1, &g_modelVAO); glBindVertexArray(g_modelVAO); glBindBuffer(GL_ARRAY_BUFFER, g_verticesModelVBO); glVertexAttribPointer(g_vertexModelLocation, 4, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_vertexModelLocation); glBindBuffer(GL_ARRAY_BUFFER, g_normalsModelVBO); glVertexAttribPointer(g_normalModelLocation, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_normalModelLocation); // glUseProgram(g_fullscreenProgram.program); glUniform1i(g_framebufferTextureFullscreenLocation, 0); glUniform1i(g_msaaSamplesFullscreenLocation, MSAA_SAMPLES); glGenVertexArrays(1, &g_fullscreenVAO); glBindVertexArray(g_fullscreenVAO); // glUseProgram(g_backgroundProgram.program); glUniform1i(g_textureBackgroundLocation, 0); glGenVertexArrays(1, &g_backgroundVAO); glBindVertexArray(g_backgroundVAO); glBindBuffer(GL_ARRAY_BUFFER, g_verticesBackgroundVBO); glVertexAttribPointer(g_vertexBackgroundLocation, 4, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(g_vertexBackgroundLocation); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_indicesBackgroundVBO); // glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0f); glEnable(GL_CULL_FACE); return GLUS_TRUE; }
void SceneBase::Init() { // Black background glClearColor(0.0f, 0.7f, 0.0f, 0.0f); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glGenVertexArrays(1, &m_vertexArrayID); glBindVertexArray(m_vertexArrayID); m_programID = LoadShaders( "Shader//comg.vertexshader", "Shader//comg.fragmentshader" ); // Get a handle for our uniform m_parameters[U_MVP] = glGetUniformLocation(m_programID, "MVP"); //m_parameters[U_MODEL] = glGetUniformLocation(m_programID, "M"); //m_parameters[U_VIEW] = glGetUniformLocation(m_programID, "V"); m_parameters[U_MODELVIEW] = glGetUniformLocation(m_programID, "MV"); m_parameters[U_MODELVIEW_INVERSE_TRANSPOSE] = glGetUniformLocation(m_programID, "MV_inverse_transpose"); m_parameters[U_MATERIAL_AMBIENT] = glGetUniformLocation(m_programID, "material.kAmbient"); m_parameters[U_MATERIAL_DIFFUSE] = glGetUniformLocation(m_programID, "material.kDiffuse"); m_parameters[U_MATERIAL_SPECULAR] = glGetUniformLocation(m_programID, "material.kSpecular"); m_parameters[U_MATERIAL_SHININESS] = glGetUniformLocation(m_programID, "material.kShininess"); m_parameters[U_LIGHTENABLED] = glGetUniformLocation(m_programID, "lightEnabled"); m_parameters[U_NUMLIGHTS] = glGetUniformLocation(m_programID, "numLights"); m_parameters[U_LIGHT0_TYPE] = glGetUniformLocation(m_programID, "lights[0].type"); m_parameters[U_LIGHT0_POSITION] = glGetUniformLocation(m_programID, "lights[0].position_cameraspace"); m_parameters[U_LIGHT0_COLOR] = glGetUniformLocation(m_programID, "lights[0].color"); m_parameters[U_LIGHT0_POWER] = glGetUniformLocation(m_programID, "lights[0].power"); m_parameters[U_LIGHT0_KC] = glGetUniformLocation(m_programID, "lights[0].kC"); m_parameters[U_LIGHT0_KL] = glGetUniformLocation(m_programID, "lights[0].kL"); m_parameters[U_LIGHT0_KQ] = glGetUniformLocation(m_programID, "lights[0].kQ"); m_parameters[U_LIGHT0_SPOTDIRECTION] = glGetUniformLocation(m_programID, "lights[0].spotDirection"); m_parameters[U_LIGHT0_COSCUTOFF] = glGetUniformLocation(m_programID, "lights[0].cosCutoff"); m_parameters[U_LIGHT0_COSINNER] = glGetUniformLocation(m_programID, "lights[0].cosInner"); m_parameters[U_LIGHT0_EXPONENT] = glGetUniformLocation(m_programID, "lights[0].exponent"); // Get a handle for our "colorTexture" uniform m_parameters[U_COLOR_TEXTURE_ENABLED] = glGetUniformLocation(m_programID, "colorTextureEnabled"); m_parameters[U_COLOR_TEXTURE] = glGetUniformLocation(m_programID, "colorTexture"); // Get a handle for our "textColor" uniform m_parameters[U_TEXT_ENABLED] = glGetUniformLocation(m_programID, "textEnabled"); m_parameters[U_TEXT_COLOR] = glGetUniformLocation(m_programID, "textColor"); // Use our shader glUseProgram(m_programID); lights[0].type = Light::LIGHT_DIRECTIONAL; lights[0].position.Set(0, 20, 0); lights[0].color.Set(1, 1, 1); lights[0].power = 1; lights[0].kC = 1.f; lights[0].kL = 0.01f; lights[0].kQ = 0.001f; lights[0].cosCutoff = cos(Math::DegreeToRadian(45)); lights[0].cosInner = cos(Math::DegreeToRadian(30)); lights[0].exponent = 3.f; lights[0].spotDirection.Set(0.f, 1.f, 0.f); glUniform1i(m_parameters[U_NUMLIGHTS], 0); glUniform1i(m_parameters[U_TEXT_ENABLED], 0); glUniform1i(m_parameters[U_LIGHT0_TYPE], lights[0].type); glUniform3fv(m_parameters[U_LIGHT0_COLOR], 1, &lights[0].color.r); glUniform1f(m_parameters[U_LIGHT0_POWER], lights[0].power); glUniform1f(m_parameters[U_LIGHT0_KC], lights[0].kC); glUniform1f(m_parameters[U_LIGHT0_KL], lights[0].kL); glUniform1f(m_parameters[U_LIGHT0_KQ], lights[0].kQ); glUniform1f(m_parameters[U_LIGHT0_COSCUTOFF], lights[0].cosCutoff); glUniform1f(m_parameters[U_LIGHT0_COSINNER], lights[0].cosInner); glUniform1f(m_parameters[U_LIGHT0_EXPONENT], lights[0].exponent); camera.Init(Vector3(0, 0, 1), Vector3(0, 0, 0), Vector3(0, 1, 0)); for(int i = 0; i < NUM_GEOMETRY; ++i) { meshList[i] = NULL; } meshList[GEO_AXES] = MeshBuilder::GenerateAxes("reference", 1000, 1000, 1000); meshList[GEO_BALL] = MeshBuilder::GenerateSphere("ball", Color(1, 1, 1), 10, 10, 1.f); meshList[GEO_BALL2] = MeshBuilder::GenerateSphere("ball2", Color(1, 0, 0), 10, 10, 1.f); meshList[GEO_CUBE] = MeshBuilder::GenerateCube("cube", Color(1, 1, 1), 1.f); meshList[GEO_TEXT] = MeshBuilder::GenerateText("text", 16, 16); meshList[GEO_TEXT]->textureID = LoadTGA("Image//calibri.tga"); meshList[GEO_TEXT]->material.kAmbient.Set(1, 0, 0); meshList[GEO_SHIP] = MeshBuilder::GenerateQuad("space ship",Color(1,1,1),2.f); meshList[GEO_SHIP]->textureID = LoadTGA("Image//spaceship.tga"); meshList[GEO_ESHIP] = MeshBuilder::GenerateQuad("enemy space ship",Color(1,1,1),2.f); meshList[GEO_ESHIP]->textureID = LoadTGA("Image//enemyship.tga"); meshList[GEO_ASTEROID] = MeshBuilder::GenerateQuad("asteroid", Color(1,1,1),2.f); meshList[GEO_ASTEROID]->textureID = LoadTGA("Image//asteroid.tga"); meshList[GEO_MISSILE] = MeshBuilder::GenerateQuad("missile", Color(1,1,1),2.f); meshList[GEO_MISSILE]->textureID = LoadTGA("Image//missile.tga"); meshList[GEO_PLANETS] = MeshBuilder::GenerateQuad("planets", Color(1,1,1),2.f); meshList[GEO_PLANETS]->textureID = LoadTGA("Image//planet.tga"); meshList[GEO_BACKGROUND] = MeshBuilder::GenerateQuad("background",Color(1,1,1),2.f); meshList[GEO_BACKGROUND]->textureID = LoadTGA("Image//background.tga"); meshList[GEO_POWERUP] = MeshBuilder::GenerateQuad("power up",Color(1,1,1),2.f); meshList[GEO_POWERUP]->textureID = LoadTGA("Image//powerup.tga"); meshList[GEO_EBULLETS] = MeshBuilder::GenerateSphere("ball", Color(1, 0, 0), 10, 10, 1.f); meshList[GEO_START] = MeshBuilder::GenerateQuad("start menu",Color(1,1,1),2.f); meshList[GEO_START]->textureID = LoadTGA("Image//Menu.tga"); meshList[GEO_WIN] = MeshBuilder::GenerateQuad("win menu",Color(1,1,1),2.f); meshList[GEO_WIN]->textureID = LoadTGA("Image//winscreen.tga"); meshList[GEO_DRAW] = MeshBuilder::GenerateQuad("draw screen",Color(1,1,1),2.f); meshList[GEO_DRAW]->textureID = LoadTGA("Image//draw.tga"); meshList[GEO_INSTRUCT] = MeshBuilder::GenerateQuad("tutorial screen",Color(1,1,1),2.f); meshList[GEO_INSTRUCT]->textureID = LoadTGA("Image//instruction.tga"); meshList[GEO_WIN1] = MeshBuilder::GenerateQuad("win menu",Color(1,1,1),2.f); meshList[GEO_WIN1]->textureID = LoadTGA("Image//win1.tga"); meshList[GEO_WIN2] = MeshBuilder::GenerateQuad("win menu",Color(1,1,1),2.f); meshList[GEO_WIN2]->textureID = LoadTGA("Image//win2.tga"); meshList[GEO_GAMEOVER] = MeshBuilder::GenerateQuad("game over screen",Color(1,1,1),2.f); meshList[GEO_GAMEOVER]->textureID = LoadTGA("Image//losescreen.tga"); bLightEnabled = false; }
GLUSvoid terminate(GLUSvoid) { glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, 0); if (g_texture[0]) { glDeleteTextures(1, &g_texture[0]); g_texture[0] = 0; } glBindTexture(GL_TEXTURE_CUBE_MAP, 0); if (g_texture[1]) { glDeleteTextures(1, &g_texture[1]); g_texture[1] = 0; } glBindTexture(GL_TEXTURE_2D, 0); if (g_texture[2]) { glDeleteTextures(1, &g_texture[2]); g_texture[2] = 0; } // glBindBuffer(GL_ARRAY_BUFFER, 0); if (g_verticesModelVBO) { glDeleteBuffers(1, &g_verticesModelVBO); g_verticesModelVBO = 0; } if (g_normalsModelVBO) { glDeleteBuffers(1, &g_normalsModelVBO); g_normalsModelVBO = 0; } if (g_verticesBackgroundVBO) { glDeleteBuffers(1, &g_verticesBackgroundVBO); g_verticesBackgroundVBO = 0; } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); if (g_indicesBackgroundVBO) { glDeleteBuffers(1, &g_indicesBackgroundVBO); g_indicesBackgroundVBO = 0; } glBindVertexArray(0); if (g_modelVAO) { glDeleteVertexArrays(1, &g_modelVAO); g_modelVAO = 0; } if (g_backgroundVAO) { glDeleteVertexArrays(1, &g_backgroundVAO); g_backgroundVAO = 0; } if (g_fullscreenVAO) { glDeleteVertexArrays(1, &g_fullscreenVAO); g_fullscreenVAO = 0; } glUseProgram(0); glusDestroyProgram(&g_modelProgram); glusDestroyProgram(&g_backgroundProgram); glusDestroyProgram(&g_fullscreenProgram); // glBindTexture(GL_TEXTURE_2D, 0); if (g_fullscreenTexture) { glDeleteTextures(1, &g_fullscreenTexture); g_fullscreenTexture = 0; } glBindRenderbuffer(GL_RENDERBUFFER, 0); if (g_fullscreenDepthRenderbuffer) { glDeleteRenderbuffers(1, &g_fullscreenDepthRenderbuffer); g_fullscreenDepthRenderbuffer = 0; } glBindFramebuffer(GL_FRAMEBUFFER, 0); if (g_fullscreenFBO) { glDeleteFramebuffers(1, &g_fullscreenFBO); g_fullscreenFBO = 0; } }
virtual void startup() { static const char * vs_source[] = { "#version 410 core \n" " \n" "void main(void) \n" "{ \n" " const vec4 vertices[] = vec4[](vec4( 0.25, -0.25, 0.5, 1.0), \n" " vec4(-0.25, -0.25, 0.5, 1.0), \n" " vec4( 0.25, 0.25, 0.5, 1.0)); \n" " \n" " gl_Position = vertices[gl_VertexID]; \n" "} \n" }; static const char * tcs_source[] = { "#version 410 core \n" " \n" "layout (vertices = 3) out; \n" " \n" "void main(void) \n" "{ \n" " if (gl_InvocationID == 0) \n" " { \n" " gl_TessLevelInner[0] = 5.0; \n" " gl_TessLevelOuter[0] = 5.0; \n" " gl_TessLevelOuter[1] = 5.0; \n" " gl_TessLevelOuter[2] = 5.0; \n" " } \n" " gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position; \n" "} \n" }; static const char * tes_source[] = { "#version 410 core \n" " \n" "layout (triangles, equal_spacing, cw) in; \n" " \n" "void main(void) \n" "{ \n" " gl_Position = (gl_TessCoord.x * gl_in[0].gl_Position) + \n" " (gl_TessCoord.y * gl_in[1].gl_Position) + \n" " (gl_TessCoord.z * gl_in[2].gl_Position); \n" "} \n" }; static const char * gs_source[] = { "#version 410 core \n" " \n" "layout (triangles) in; \n" "layout (points, max_vertices = 3) out; \n" " \n" "void main(void) \n" "{ \n" " int i; \n" " \n" " for (i = 0; i < gl_in.length(); i++) \n" " { \n" " gl_Position = gl_in[i].gl_Position; \n" " EmitVertex(); \n" " } \n" "} \n" }; static const char * fs_source[] = { "#version 410 core \n" " \n" "out vec4 color; \n" " \n" "void main(void) \n" "{ \n" " color = vec4(0.0, 0.8, 1.0, 1.0); \n" "} \n" }; program = glCreateProgram(); GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, vs_source, NULL); glCompileShader(vs); GLuint tcs = glCreateShader(GL_TESS_CONTROL_SHADER); glShaderSource(tcs, 1, tcs_source, NULL); glCompileShader(tcs); GLuint tes = glCreateShader(GL_TESS_EVALUATION_SHADER); glShaderSource(tes, 1, tes_source, NULL); glCompileShader(tes); GLuint gs = glCreateShader(GL_GEOMETRY_SHADER); glShaderSource(gs, 1, gs_source, NULL); glCompileShader(gs); GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, fs_source, NULL); glCompileShader(fs); glAttachShader(program, vs); glAttachShader(program, tcs); glAttachShader(program, tes); glAttachShader(program, gs); glAttachShader(program, fs); glLinkProgram(program); glDeleteShader(vs); glDeleteShader(tcs); glDeleteShader(tes); glDeleteShader(gs); glDeleteShader(fs); glGenVertexArrays(1, &vao); glBindVertexArray(vao); }
int main(int /*argc*/, char ** /*argv*/) { BaseApp app; ProgramObject programEnv, program; auto mainWindow = app.getMainWindow(); PerspectiveCamera cam; OrbitManipulator manipulator(&cam); manipulator.setupCallbacks(app); GLuint diffuseTextureTop; GLuint diffuseTextureSide; GLuint diffuseTextureDown; GLuint vao; GLuint vaoEmpty; GLuint vbo; int32_t sphereSizeX = 20; int32_t sphereSizeY = 20; app.addInitCallback([&]() { std::string prefix = app.getResourceDir() + "Shaders/Tutorial/"; auto vs = compileShader(GL_VERTEX_SHADER, "#version 450\n", Loader::text(prefix + "triplanar.vp")); auto fs = compileShader(GL_FRAGMENT_SHADER, "#version 450\n", Loader::text(prefix + "lighting.vp"), Loader::text(prefix + "triplanar.fp")); program = createProgram(vs, fs); std::string texPrefix = app.getResourceDir() + "Textures/Tutorial/"; diffuseTextureTop = Loader::texture(texPrefix + "grass.png"); diffuseTextureSide = Loader::texture(texPrefix + "dirt.jpg"); diffuseTextureDown = Loader::texture(texPrefix + "rock.jpg"); glCreateBuffers(1, &vbo); const uint32_t floatsPerVertex = 6; const uint32_t vertiesPerFace = 6; float*vertices = new float[sphereSizeX*sphereSizeY*vertiesPerFace*floatsPerVertex]; for (int32_t y = 0; y<sphereSizeY; ++y) { for (int32_t x = 0; x<sphereSizeX; ++x) { for (uint32_t k = 0; k<vertiesPerFace; ++k) { const int32_t xOffset[] = { 0,1,0,0,1,1 }; const int32_t yOffset[] = { 0,0,1,1,0,1 }; float u = (float)(x + xOffset[k]) / sphereSizeX; float v = (float)(y + yOffset[k]) / sphereSizeY; float xAngle = -u*glm::two_pi<float>(); float yAngle = v*glm::pi<float>(); uint32_t faceId = y*sphereSizeX + x; uint32_t faceVertex = faceId*vertiesPerFace + k; vertices[faceVertex*floatsPerVertex + 0] = glm::cos(xAngle)*glm::sin(yAngle); vertices[faceVertex*floatsPerVertex + 1] = -glm::cos(yAngle); vertices[faceVertex*floatsPerVertex + 2] = glm::sin(xAngle)*glm::sin(yAngle); vertices[faceVertex*floatsPerVertex + 3] = 1; vertices[faceVertex*floatsPerVertex + 4] = u; vertices[faceVertex*floatsPerVertex + 5] = v; } } } glNamedBufferData(vbo, sizeof(float)*sphereSizeX*sphereSizeY*vertiesPerFace*floatsPerVertex, vertices, GL_STATIC_DRAW); delete[]vertices; glCreateVertexArrays(1, &vao); glEnableVertexArrayAttrib(vao, 0); glVertexArrayAttribFormat(vao, 0, 4, GL_FLOAT, 0, 0); glVertexArrayVertexBuffer(vao, 0, vbo, 0, sizeof(float)*floatsPerVertex); glEnableVertexArrayAttrib(vao, 1); glVertexArrayAttribFormat(vao, 1, 2, GL_FLOAT, 0, 0); glVertexArrayVertexBuffer(vao, 1, vbo, sizeof(float) * 4, sizeof(float)*floatsPerVertex); glClearColor(0, 0, 0, 1); glDisable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); }); app.addResizeCallback([&](int w, int h) { glViewport(0, 0, w, h); cam.setAspect(float(w) / float(h)); }); app.addDrawCallback([&]() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); program.use(); glBindTextureUnit(0, diffuseTextureTop); glBindTextureUnit(1, diffuseTextureSide); glBindTextureUnit(2, diffuseTextureDown); program.setMatrix4fv("p", value_ptr(cam.getProjection())); program.setMatrix4fv("v", value_ptr(cam.getView())); glBindVertexArray(vao); glDrawArrays(GL_TRIANGLES, 0, sphereSizeX*sphereSizeY * 6); glBindVertexArray(0); }); return app.run(); }
void OpenGL41::setVertexAttributeArrayConfiguration(VertexAttributeArrayConfigurationObject configuration) { glBindVertexArray(GLuint(uintptr_t(configuration))); CARBON_CHECK_OPENGL_ERROR(glBindVertexArray); }
int main () { GLFWwindow* window = NULL; const GLubyte* renderer; const GLubyte* version; GLuint vao; GLuint vbo; GLuint colours_vbo; /* geometry to use. these are 3 xyz points (9 floats total) to make a triangle */ GLfloat points[] = { 0.0f, 0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.00f, 0.8f, 0.0f, -0.5f, -0.2f, 0.0f, 0.5f, -0.2f, 0.0f }; GLfloat colours[] = { 1.0f, 1.0f, 0.0f, //yellow rgb(255,255,0) 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, //red rgb(255,0,0) 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, }; /* these are the strings of code for the shaders the vertex shader positions each vertex point */ const char* vertex_shader = "#version 400\n" "layout(location = 0) in vec3 vertex_position;" "layout(location = 1) in vec3 vertex_colour;" "out vec3 color;" "uniform mat4 matrix;" "void main () {" " color = vertex_colour;" " gl_Position=matrix * vec4(vertex_position, 1.0);" "}"; /* the fragment shader colours each fragment (pixel-sized area of the triangle) */ const char* fragment_shader = "#version 400\n" "in vec3 color;" "out vec4 frag_colour;" "void main () {" " frag_colour = vec4 (color, 1.0);" "}"; /* GL shader objects for vertex and fragment shader [components] */ GLuint vs, fs; /* GL shader programme object [combined, to link] */ GLuint shader_programme; /* start GL context and O/S window using the GLFW helper library */ if (!glfwInit ()) { fprintf (stderr, "ERROR: could not start GLFW3\n"); return 1; } /* change to 3.2 if on Apple OS X */ glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow ( 640, 480, "Hello Triangle", NULL, NULL ); if (!window) { fprintf (stderr, "ERROR: could not open window with GLFW3\n"); glfwTerminate(); return 1; } glfwMakeContextCurrent (window); /* start GLEW extension handler */ glewExperimental = GL_TRUE; glewInit (); /* get version info */ renderer = glGetString (GL_RENDERER); /* get renderer string */ version = glGetString (GL_VERSION); /* version as a string */ printf ("Renderer: %s\n", renderer); printf ("OpenGL version supported %s\n", version); /* tell GL to only draw onto a pixel if the shape is closer to the viewer */ glEnable (GL_DEPTH_TEST); /* enable depth-testing */ glDepthFunc (GL_LESS);/*depth-testing interprets a smaller value as "closer"*/ /* a vertex buffer object (VBO) is created here. this stores an array of data on the graphics adapter's memory. in our case - the vertex points */ glGenBuffers (1, &vbo); glBindBuffer (GL_ARRAY_BUFFER, vbo); glBufferData (GL_ARRAY_BUFFER, 9 * sizeof (GLfloat), points, GL_STATIC_DRAW); glGenBuffers (1, &colours_vbo); glBindBuffer (GL_ARRAY_BUFFER, colours_vbo); glBufferData (GL_ARRAY_BUFFER, sizeof (colours), colours, GL_STATIC_DRAW); /* the vertex array object (VAO) is a little descriptor that defines which data from vertex buffer objects should be used as input variables to vertex shaders. in our case - use our only VBO, and say 'every three floats is a variable' */ glGenVertexArrays (1, &vao); glBindVertexArray (vao); glEnableVertexAttribArray (0); glBindBuffer (GL_ARRAY_BUFFER, vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray (1); //enable glBindBuffer (GL_ARRAY_BUFFER, colours_vbo); glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, NULL); /* here we copy the shader strings into GL shaders, and compile them. we then create an executable shader 'program' and attach both of the compiled shaders. we link this, which matches the outputs of the vertex shader to the inputs of the fragment shader, etc. and it is then ready to use */ vs = glCreateShader (GL_VERTEX_SHADER); glShaderSource (vs, 1, &vertex_shader, NULL); glCompileShader (vs); fs = glCreateShader (GL_FRAGMENT_SHADER); glShaderSource (fs, 1, &fragment_shader, NULL); glCompileShader (fs); shader_programme = glCreateProgram (); glAttachShader (shader_programme, fs); glAttachShader (shader_programme, vs); glLinkProgram (shader_programme); double theta=180; GLfloat matrix[] = { 0.5f,0.0f,0.0f,0.00f, 0.0f,0.5f,0.0f,0.00f, 0.0f,0.0f,0.5f,0.00f, 0.25f,0.5f,0.75f,1.0f, }; int matrix_location = glGetUniformLocation (shader_programme, "matrix"); while (!glfwWindowShouldClose (window)) { glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram (shader_programme); glBindVertexArray (vao); glDrawArrays (GL_TRIANGLES, 0, 3); glDrawArrays (GL_TRIANGLES, 3, 6); // update other events like input handling glfwPollEvents (); if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_ESCAPE)) { glfwSetWindowShouldClose (window, 1); } if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_U)) { //return to normal matrix[0] += 0.015f; matrix[5] += 0.005f; } if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_J)) { //return to normal matrix[0] -= 0.015f; matrix[5] -= 0.005f; } //uniformed scaling make smaller if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_D)) { //return to normal matrix[0] -= 0.005f; matrix[5] -= 0.005f; } //uniformed scaling bigger if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_E)) { //return to normal matrix[0] += 0.005f; matrix[5] += 0.005f; matrix[10] += 0.005f; } //non-uniform scaling if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_X)) { //return to normal matrix[5] = cos(theta); matrix[6] = sin(theta); matrix[9] = -sin(theta); matrix[10] =cos(theta); theta+=0.025; } //rotation around Y axis if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_Y)) { //return to normal matrix[0] = cos(theta); matrix[2] = sin(theta); matrix[8] = -sin(theta); matrix[10] =cos(theta); theta+=0.025; } //rotation around Z axis if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_Z)) { //return to normal matrix[0] = cos(theta); matrix[1] = -sin(theta); matrix[4] = sin(theta); matrix[5] = cos(theta); theta+=0.025; } //combined transformations if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_C)) { matrix[0] += 0.005f; matrix[5] += 0.005f; matrix[10] +=0.005f; matrix[12] += 0.025f; } if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_V)) { matrix[0] -= 0.005f; matrix[5] -= 0.005f; matrix[10] -=0.005f; matrix[12] -= 0.025f; } // X left if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_LEFT)) { matrix[12] -= 0.025f; } //X Right if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_RIGHT)) { matrix[12] += 0.025f; } //Y Down if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_DOWN)) { matrix[13] -= 0.025f; } //Y UP if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_UP)) { matrix[13] += 0.025f; } glUniformMatrix4fv (matrix_location, 1, GL_FALSE, matrix); //control triangle seperately // draw points 0-3 from the currently bound VAO with current in-use shader // put the stuff we've been drawing onto the display glfwSwapBuffers (window); } /* close GL context and any other GLFW resources */ glfwTerminate(); return 0; }
void RenderableStars::update(const UpdateData& data) { if (_dataIsDirty) { const int value = _colorOption; LDEBUG("Regenerating data"); createDataSlice(ColorOption(value)); int size = static_cast<int>(_slicedData.size()); if (_vao == 0) { glGenVertexArrays(1, &_vao); LDEBUG("Generating Vertex Array id '" << _vao << "'"); } if (_vbo == 0) { glGenBuffers(1, &_vbo); LDEBUG("Generating Vertex Buffer Object id '" << _vbo << "'"); } glBindVertexArray(_vao); glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferData(GL_ARRAY_BUFFER, size*sizeof(GLfloat), &_slicedData[0], GL_STATIC_DRAW); GLint positionAttrib = _program->attributeLocation("in_position"); GLint brightnessDataAttrib = _program->attributeLocation("in_brightness"); const size_t nStars = _fullData.size() / _nValuesPerStar; const size_t nValues = _slicedData.size() / nStars; GLsizei stride = static_cast<GLsizei>(sizeof(GLfloat) * nValues); glEnableVertexAttribArray(positionAttrib); glEnableVertexAttribArray(brightnessDataAttrib); const int colorOption = _colorOption; switch (colorOption) { case ColorOption::Color: glVertexAttribPointer(positionAttrib, 4, GL_FLOAT, GL_FALSE, stride, reinterpret_cast<void*>(offsetof(ColorVBOLayout, position))); glVertexAttribPointer(brightnessDataAttrib, 3, GL_FLOAT, GL_FALSE, stride, reinterpret_cast<void*>(offsetof(ColorVBOLayout, bvColor))); break; case ColorOption::Velocity: { glVertexAttribPointer(positionAttrib, 4, GL_FLOAT, GL_FALSE, stride, reinterpret_cast<void*>(offsetof(VelocityVBOLayout, position))); glVertexAttribPointer(brightnessDataAttrib, 3, GL_FLOAT, GL_FALSE, stride, reinterpret_cast<void*>(offsetof(VelocityVBOLayout, bvColor))); GLint velocityAttrib = _program->attributeLocation("in_velocity"); glEnableVertexAttribArray(velocityAttrib); glVertexAttribPointer(velocityAttrib, 3, GL_FLOAT, GL_TRUE, stride, reinterpret_cast<void*>(offsetof(VelocityVBOLayout, vx))); break; } case ColorOption::Speed: { glVertexAttribPointer(positionAttrib, 4, GL_FLOAT, GL_FALSE, stride, reinterpret_cast<void*>(offsetof(SpeedVBOLayout, position))); glVertexAttribPointer(brightnessDataAttrib, 3, GL_FLOAT, GL_FALSE, stride, reinterpret_cast<void*>(offsetof(SpeedVBOLayout, bvColor))); GLint speedAttrib = _program->attributeLocation("in_speed"); glEnableVertexAttribArray(speedAttrib); glVertexAttribPointer(speedAttrib, 1, GL_FLOAT, GL_TRUE, stride, reinterpret_cast<void*>(offsetof(SpeedVBOLayout, speed))); } } glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); _dataIsDirty = false; } if (_pointSpreadFunctionTextureIsDirty) { LDEBUG("Reloading Point Spread Function texture"); _pointSpreadFunctionTexture = nullptr; if (_pointSpreadFunctionTexturePath.value() != "") { _pointSpreadFunctionTexture = std::move(ghoul::io::TextureReader::ref().loadTexture(absPath(_pointSpreadFunctionTexturePath))); if (_pointSpreadFunctionTexture) { LDEBUG("Loaded texture from '" << absPath(_pointSpreadFunctionTexturePath) << "'"); _pointSpreadFunctionTexture->uploadTexture(); } _pointSpreadFunctionTexture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); delete _psfTextureFile; _psfTextureFile = new ghoul::filesystem::File(_pointSpreadFunctionTexturePath); _psfTextureFile->setCallback([&](const ghoul::filesystem::File&) { _pointSpreadFunctionTextureIsDirty = true; }); } _pointSpreadFunctionTextureIsDirty = false; } if (_colorTextureIsDirty) { LDEBUG("Reloading Color Texture"); _colorTexture = nullptr; if (_colorTexturePath.value() != "") { _colorTexture = std::move(ghoul::io::TextureReader::ref().loadTexture(absPath(_colorTexturePath))); if (_colorTexture) { LDEBUG("Loaded texture from '" << absPath(_colorTexturePath) << "'"); _colorTexture->uploadTexture(); } delete _colorTextureFile; _colorTextureFile = new ghoul::filesystem::File(_colorTexturePath); _colorTextureFile->setCallback([&](const ghoul::filesystem::File&) { _colorTextureIsDirty = true; }); } _colorTextureIsDirty = false; } }
void RenderUtils::InitVAO() { //Method to initialise a vertex array object GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); }
int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // build and compile our shader zprogram // ------------------------------------ Shader ourShader("5.2.transform.vs", "5.2.transform.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ float vertices[] = { // positions // texture coords 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, // top right 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, // bottom right -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, // bottom left -0.5f, 0.5f, 0.0f, 0.0f, 1.0f // top left }; unsigned int indices[] = { 0, 1, 3, // first triangle 1, 2, 3 // second triangle }; unsigned int VBO, VAO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // texture coord attribute glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // load and create a texture // ------------------------- unsigned int texture1, texture2; // texture 1 // --------- glGenTextures(1, &texture1); glBindTexture(GL_TEXTURE_2D, texture1); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps int width, height, nrChannels; stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis. unsigned char *data = stbi_load(FileSystem::getPath("resources/textures/container.jpg").c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); // texture 2 // --------- glGenTextures(1, &texture2); glBindTexture(GL_TEXTURE_2D, texture2); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps data = stbi_load(FileSystem::getPath("resources/textures/awesomeface.png").c_str(), &width, &height, &nrChannels, 0); if (data) { // note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); // tell opengl for each sampler to which texture unit it belongs to (only has to be done once) // ------------------------------------------------------------------------------------------- ourShader.use(); ourShader.setInt("texture1", 0); ourShader.setInt("texture2", 1); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // bind textures on corresponding texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); glm::mat4 transform; // first container // --------------- transform = glm::translate(transform, glm::vec3(0.5f, -0.5f, 0.0f)); transform = glm::rotate(transform, (float)glfwGetTime(), glm::vec3(0.0f, 0.0f, 1.0f)); // get their uniform location and set matrix (using glm::value_ptr) unsigned int transformLoc = glGetUniformLocation(ourShader.ID, "transform"); glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(transform)); // with the uniform matrix set, draw the first container glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // second transformation // --------------------- transform = glm::mat4(); // reset it to an identity matrix transform = glm::translate(transform, glm::vec3(-0.5f, 0.5f, 0.0f)); float scaleAmount = sin(glfwGetTime()); transform = glm::scale(transform, glm::vec3(scaleAmount, scaleAmount, scaleAmount)); glUniformMatrix4fv(transformLoc, 1, GL_FALSE, &transform[0][0]); // this time take the matrix value array's first element as its memory pointer value // now with the uniform matrix being replaced with new transformations, draw it again. glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; }
/* Page 41 */ static bool test_bindvertexarray() { glBindVertexArray(200); return piglit_check_gl_error(GL_INVALID_OPERATION); }
int main(int argc, const char * argv[]) { const int WIDTH = 800; const int HEIGHT = 600; glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwSetErrorCallback(glfwErrorCallback); GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { printf("Failed to create GLFW window"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // GLEW负责管理每个平台上应该调用哪个函数指针,所以在调用openGL之前,先初始化它 glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cerr << "Failed to initialize GLEW" << std::endl; return -1; } // Define the viewport dimensions int width, height; glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); glfwSetKeyCallback(window, key_callback); // Build and compile our shader program // Vertex shader GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glCompileShader(vertexShader); // Check for compile time errors GLint success; GLchar infoLog[512]; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; } // Fragment shader GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); glCompileShader(fragmentShader); // Check for compile time errors glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; } // Link shaders GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); // Check for linking errors glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog); std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); // Set up vertex data (and buffer(s)) and attribute pointers GLfloat vertices[] = { 0.5f, 0.5f, 0.0f, // Top Right 0.5f, -0.5f, 0.0f, // Bottom Right -0.5f, -0.5f, 0.0f, // bottom left }; GLfloat vertices2[] = { 0.8f, 0.5f, 0.0f, // Top Right 0.8f, -0.5f, 0.0f, // Bottom Right -0.2f, -0.5f, 0.0f, // bottom left }; GLuint VBO, VAO, VBO2, VAO2; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenVertexArrays(2, &VAO2); glGenBuffers(2, &VBO2); // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs), remember: do NOT unbind the EBO, keep it bound to this VAO glBindVertexArray(VAO2); glBindBuffer(GL_ARRAY_BUFFER, VBO2); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices2), vertices2, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs), remember: do NOT unbind the EBO, keep it bound to this VAO glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); while(!glfwWindowShouldClose(window)) { glfwPollEvents(); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Draw our first triangle glUseProgram(shaderProgram); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); glBindVertexArray(VAO2); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); glfwSwapBuffers(window); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO2); glDeleteBuffers(1, &VBO2); glfwTerminate(); return 0; }