### Initialize GLFW and Configure Window Hints Source: https://learnopengl.com/Getting-started/Hello-Window Initializes the GLFW library and sets window hints for the OpenGL context, specifying version 3.3 and the core profile. This prepares GLFW for window creation. ```cpp int main() { 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); return 0; } ``` -------------------------------- ### Configure Global OpenGL State (C++) Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F2.lighting%2F5.3.light_casters_spot%2Flight_casters_spot.cpp Sets up essential global OpenGL states. This example enables depth testing, which is vital for correctly rendering 3D scenes by ensuring that objects closer to the camera obscure objects farther away. ```cpp #include // ... other includes ... int main() { // ... initialization ... // configure global opengl state // ----------------------------- glEnable(GL_DEPTH_TEST); // ... rest of the main function ... return 0; } ``` -------------------------------- ### OpenGL Initialization and Setup (C++) Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F6.pbr%2F1.1.lighting%2Flighting.cpp Initializes GLFW for window creation and OpenGL context management. Configures OpenGL version, profile, and multisampling. Sets up callbacks for window resizing and mouse input, and enables cursor disabling for camera control. Requires GLFW library. ```cpp #include #include // ... other includes ... void framebuffer_size_callback(GLFWwindow* window, int width, int height); void mouse_callback(GLFWwindow* window, double xpos, double ypos); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); void processInput(GLFWwindow *window); // settings const unsigned int SCR_WIDTH = 1280; const unsigned int SCR_HEIGHT = 720; int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // 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); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state // ----------------------------- glEnable(GL_DEPTH_TEST); // ... rest of the code ... return 0; } ``` -------------------------------- ### Initialize GLAD for OpenGL Function Pointers Source: https://learnopengl.com/Getting-started/Hello-Window Initializes the GLAD library to manage OpenGL function pointers. It uses the GLFW-provided function to get the address of OpenGL functions, which is OS-specific. ```cpp if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } ``` -------------------------------- ### Dispatch Compute Shader and Render Texture (C++) Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F8.guest%2F2022%2F5.computeshader_helloworld%2Fcompute_shader_hello_world.cpp Dispatches a compute shader to process a texture and then renders the processed texture to a quad. Includes timing for FPS calculation and memory barriers to ensure synchronization. Requires OpenGL context, shaders, and texture setup. ```cpp #include #include #include #include "learnopengl/shader_m.h" #include "learnopengl/shader_c.h" // ... (global variables and function prototypes) void renderQuad(); // Assumed to be defined elsewhere int main() { // ... (initialization code) Shader screenQuad("screenQuad.vs", "screenQuad.fs"); ComputeShader computeShader("computeShader.cs"); screenQuad.use(); screenQuad.setInt("tex", 0); // ... (texture creation code) // render loop int fCounter = 0; while (!glfwWindowShouldClose(window)) { // Set frame time float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; if(fCounter > 500) { std::cout << "FPS: " << 1 / deltaTime << std::endl; fCounter = 0; } else { fCounter++; } computeShader.use(); computeShader.setFloat("t", currentFrame); glDispatchCompute((unsigned int)TEXTURE_WIDTH/10, (unsigned int)TEXTURE_HEIGHT/10, 1); // make sure writing to image has finished before read glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT); // render image to quad glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); screenQuad.use(); renderQuad(); // glfw: swap buffers and poll IO events glfwSwapBuffers(window); glfwPollEvents(); } // ... (cleanup code) return 0; } ``` -------------------------------- ### Render Cube and Lighting Setup in OpenGL Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F2.lighting%2F5.4.light_casters_spot_soft%2Flight_casters_spot_soft.cpp This C++ code snippet demonstrates the rendering of a cube and the setup for lighting in an OpenGL application. It involves setting up shaders, transforming models using GLM, and drawing primitives. It also includes commented-out code for rendering a light source. ```cpp model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); lightingShader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); } // again, a lamp object is weird when we only have a spot light, don't render the light object // lightCubeShader.use(); // lightCubeShader.setMat4("projection", projection); // lightCubeShader.setMat4("view", view); // model = glm::mat4(1.0f); // model = glm::translate(model, lightPos); // model = glm::scale(model, glm::vec3(0.2f)); // a smaller cube // lightCubeShader.setMat4("model", model); // glBindVertexArray(lightCubeVAO); // glDrawArrays(GL_TRIANGLES, 0, 36); ``` -------------------------------- ### Initialize GLFW and Create Window Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F1.getting_started%2F7.4.camera_class%2Fcamera_class.cpp Initializes the GLFW library, configures OpenGL version and profile, and creates a window. It includes error handling for window creation and sets up essential callbacks for window resizing and mouse input. GLFW is terminated if window creation fails. ```c++ #include #include #include void framebuffer_size_callback(GLFWwindow* window, int width, int height); void mouse_callback(GLFWwindow* window, double xpos, double ypos); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); void processInput(GLFWwindow *window); // settings const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; 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); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // 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); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // ... rest of the code ... return 0; } ``` -------------------------------- ### Flip Texture Vertically on Load (stb_image.h) Source: https://learnopengl.com/Getting-started/Textures Configures stb_image.h to flip the y-axis of loaded images. This corrects the common issue where texture coordinates are upside-down in OpenGL. ```cpp stbi_set_flip_vertically_on_load(true); ``` -------------------------------- ### PBR Shader Setup and Uniforms (C++) Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F6.pbr%2F1.1.lighting%2Flighting.cpp Loads and compiles PBR shaders, then sets initial uniform values for albedo, ambient occlusion, and projection matrix. It also prepares light positions and colors for rendering. Requires a Shader class and GLM for matrix operations. ```cpp #include #include #include #include // ... other includes ... // build and compile shaders // ------------------------- Shader shader("1.1.pbr.vs", "1.1.pbr.fs"); shader.use(); shader.setVec3("albedo", 0.5f, 0.0f, 0.0f); shader.setFloat("ao", 1.0f); // lights // ------ glm::vec3 lightPositions[] = { glm::vec3(-10.0f, 10.0f, 10.0f), glm::vec3( 10.0f, 10.0f, 10.0f), glm::vec3(-10.0f, -10.0f, 10.0f), glm::vec3( 10.0f, -10.0f, 10.0f), }; glm::vec3 lightColors[] = { glm::vec3(300.0f, 300.0f, 300.0f), glm::vec3(300.0f, 300.0f, 300.0f), glm::vec3(300.0f, 300.0f, 300.0f), glm::vec3(300.0f, 300.0f, 300.0f) }; int nrRows = 7; int nrColumns = 7; float spacing = 2.5; // initialize static shader uniforms before rendering // -------------------------------------------------- glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); shader.use(); shader.setMat4("projection", projection); ``` -------------------------------- ### Clean Up GLFW Resources Source: https://learnopengl.com/Getting-started/Hello-Window Properly terminates GLFW and cleans up all allocated resources at the end of the application. This function should be called after the main render loop has finished. ```c++ glfwTerminate(); return 0; ``` -------------------------------- ### OpenGL Render Loop with Lighting and Transformations Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F2.lighting%2F5.1.light_casters_directional%2Flight_casters_directional.cpp This C++ code snippet outlines the main render loop in an OpenGL application. It handles per-frame time logic, processes user input, clears the screen, and then sets up lighting and camera uniforms before rendering objects. It demonstrates how to apply model, view, and projection transformations and bind textures for rendering. ```cpp // render loop // ----------- while (!glfwWindowShouldClose(window)) { // per-frame time logic // -------------------- float currentFrame = static_cast(glfwGetTime()); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // input // ----- processInput(window); // render // ------ glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // be sure to activate shader when setting uniforms/drawing objects lightingShader.use(); lightingShader.setVec3("light.direction", -0.2f, -1.0f, -0.3f); lightingShader.setVec3("viewPos", camera.Position); // light properties lightingShader.setVec3("light.ambient", 0.2f, 0.2f, 0.2f); lightingShader.setVec3("light.diffuse", 0.5f, 0.5f, 0.5f); lightingShader.setVec3("light.specular", 1.0f, 1.0f, 1.0f); // material properties lightingShader.setFloat("material.shininess", 32.0f); // view/projection transformations glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); glm::mat4 view = camera.GetViewMatrix(); lightingShader.setMat4("projection", projection); lightingShader.setMat4("view", view); // world transformation glm::mat4 model = glm::mat4(1.0f); lightingShader.setMat4("model", model); // bind diffuse map glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, diffuseMap); // bind specular map glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, specularMap); // render containers glBindVertexArray(cubeVAO); for (unsigned int i = 0; i < 10; i++) { // calculate the model matrix for each object and pass it to shader before drawing glm::mat4 model = glm::mat4(1.0f); model = glm::translate(model, cubePositions[i]); float angle = 20.0f * i; model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); lightingShader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); } // a lamp object is weird when we only have a directional light, don't render the light object // lightCubeShader.use(); // lightCubeShader.setMat4("projection", projection); // lightCubeShader.setMat4("view", view); // model = glm::mat4(1.0f); // model = glm::translate(model, lightPos); } ``` -------------------------------- ### Include OpenGL and GLFW Headers Source: https://learnopengl.com/Getting-started/Hello-Window Includes the necessary headers for GLAD and GLFW. GLAD should be included before GLFW to ensure OpenGL headers are loaded correctly. ```cpp #include #include ``` -------------------------------- ### Fragment Shader with Multiple Samplers (GLSL) Source: https://learnopengl.com/Getting-started/Textures Defines two texture samplers in a fragment shader and uses the mix function to interpolate between them. This allows for combining the effects of multiple textures. ```glsl #version 330 core ... uniform sampler2D texture1; uniform sampler2D texture2; void main() { FragColor = mix(texture(texture1, TexCoord), texture(texture2, TexCoord), 0.2); } ``` -------------------------------- ### Initialize GLFW and Create Window Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F1.getting_started%2F3.1.shaders_uniform%2Fshaders_uniform.cpp Initializes the GLFW library, configures OpenGL context version, and creates a GLFW window. It includes error handling for window creation and sets up a framebuffer size callback. This is essential for setting up the rendering environment. ```cpp #include #include #include void framebuffer_size_callback(GLFWwindow* window, int width, int height); // settings const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; 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); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // 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; } // ... rest of the code ... return 0; } void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; glViewport(0, 0, width, height); } ``` -------------------------------- ### Render Loop with Lighting and Camera in C++ Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F2.lighting%2F5.3.light_casters_spot%2Flight_casters_spot.cpp This code segment outlines the main render loop. It handles per-frame time logic, processes user input, clears the screen, and then renders objects. It sets up lighting uniforms (position, direction, colors, attenuation) and material properties (shininess) in the shader, along with view and projection matrices. Dependencies include GLFW, camera, shader class, and GLM. ```cpp // render loop // ----------- while (!glfwWindowShouldClose(window)) { // per-frame time logic // -------------------- float currentFrame = static_cast(glfwGetTime()); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // input // ----- processInput(window); // render // ------ glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // be sure to activate shader when setting uniforms/drawing objects lightingShader.use(); lightingShader.setVec3("light.position", camera.Position); lightingShader.setVec3("light.direction", camera.Front); lightingShader.setFloat("light.cutOff", glm::cos(glm::radians(12.5f))); lightingShader.setVec3("viewPos", camera.Position); // light properties lightingShader.setVec3("light.ambient", 0.1f, 0.1f, 0.1f); // we configure the diffuse intensity slightly higher; the right lighting conditions differ with each lighting method and environment. // each environment and lighting type requires some tweaking to get the best out of your environment. lightingShader.setVec3("light.diffuse", 0.8f, 0.8f, 0.8f); lightingShader.setVec3("light.specular", 1.0f, 1.0f, 1.0f); lightingShader.setFloat("light.constant", 1.0f); lightingShader.setFloat("light.linear", 0.09f); lightingShader.setFloat("light.quadratic", 0.032f); // material properties lightingShader.setFloat("material.shininess", 32.0f); // view/projection transformations glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); glm::mat4 view = camera.GetViewMatrix(); lightingShader.setMat4("projection", projection); lightingShader.setMat4("view", view); // world transformation glm::mat4 model = glm::mat4(1.0f); lightingShader.setMat4("model", model); // bind diffuse map glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, diffuseMap); // bind specular map glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, specularMap); // render containers glBindVertexArray(cubeVAO); for (unsigned int i = 0; i < 10; i++) { // calculate the model matrix for each object and pass it to shader before drawing glm::mat4 model = glm::mat4(1.0f); model = glm::translate(model, cubePositions[i]); float angle = 20.0f * i; model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ``` -------------------------------- ### Generate OpenGL Texture Object Source: https://learnopengl.com/Getting-started/Textures This code generates an OpenGL texture object and binds it for subsequent configuration. It uses glGenTextures to create a texture ID and glBindTexture to make it the active texture. ```cpp unsigned int texture; glGenTextures(1, &texture); bindTexture(GL_TEXTURE_2D, texture); ``` -------------------------------- ### Initialize GLFW Window and OpenGL Context Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F6.pbr%2F1.2.lighting_textured%2Flighting_textured.cpp Initializes GLFW, configures OpenGL version and profile, creates a window, and sets up callbacks for window resizing, mouse movement, and scrolling. It also enables cursor disabling for camera control. ```cpp #include #include // ... other includes ... void framebuffer_size_callback(GLFWwindow* window, int width, int height); void mouse_callback(GLFWwindow* window, double xpos, double ypos); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); // settings const unsigned int SCR_WIDTH = 1280; const unsigned int SCR_HEIGHT = 720; int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); glfwMakeContextCurrent(window); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // ... rest of the code ... return 0; } ``` -------------------------------- ### Set Texture Filtering Modes in OpenGL Source: https://learnopengl.com/Getting-started/Textures Configures how a 2D texture is sampled when it is magnified (scaled up) or minified (scaled down). Uses glTexParameteri to set the minification and magnification filters. ```glsl glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); ``` -------------------------------- ### Process Keyboard and Mouse Input with GLFW Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F2.lighting%2F4.4.lighting_maps_exercise4%2Flighting_maps_exercise4.cpp Handles user input from the keyboard and mouse for camera control. It reacts to WASD keys for movement and mouse movements for camera rotation. Requires GLFW and a camera object. ```cpp void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) camera.ProcessKeyboard(FORWARD, deltaTime); if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) camera.ProcessKeyboard(BACKWARD, deltaTime); if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) camera.ProcessKeyboard(LEFT, deltaTime); if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) camera.ProcessKeyboard(RIGHT, deltaTime); } void mouse_callback(GLFWwindow* window, double xposIn, double yposIn) { float xpos = static_cast(xposIn); float ypos = static_cast(yposIn); if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; lastX = xpos; lastY = ypos; camera.ProcessMouseMovement(xoffset, yoffset); } void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { camera.ProcessMouseScroll(static_cast(yoffset)); } ``` -------------------------------- ### Register Window Resize Callback Source: https://learnopengl.com/Getting-started/Hello-Window Registers the `framebuffer_size_callback` function with GLFW to be called automatically when the window size changes. This must be done after creating the window and before the render loop begins. ```c++ glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); ``` -------------------------------- ### Initialize GLFW and Create Window Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F4.advanced_opengl%2F1.1.depth_testing%2Fdepth_testing.cpp Initializes the GLFW library, configures OpenGL version and profile, and creates a GLFW window. It handles window creation failures and sets up callbacks for window resizing and mouse input. GLFW is configured to capture the mouse cursor. ```cpp #include #include #include void framebuffer_size_callback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); } 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); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // glfw window creation // -------------------- const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; 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); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // ... rest of the code ... glfwTerminate(); return 0; } ``` -------------------------------- ### Clean up OpenGL Resources Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F8.guest%2F2022%2F5.computeshader_helloworld%2Fcompute_shader_hello_world.cpp Frees allocated OpenGL resources such as textures and shader programs. It also terminates the GLFW library. This is typically called at the end of an application's lifecycle. ```cpp // ------------------------------------------------------------------------ glDeleteTextures(1, &texture); glDeleteProgram(screenQuad.ID); glDeleteProgram(computeShader.ID); glfwTerminate(); return EXIT_SUCCESS; } ``` -------------------------------- ### OpenGL Render Loop with Lighting Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F2.lighting%2F4.2.lighting_maps_specular_map%2Flighting_maps_specular.cpp This C++ code outlines the main render loop in OpenGL. It handles per-frame time logic, processes user input, clears the screen, and then renders the scene. It sets up lighting uniforms (position, ambient, diffuse, specular), camera transformations (projection, view), and material properties before drawing the main cube and a light source visualization. ```cpp // render loop // ----------- while (!glfwWindowShouldClose(window)) { // per-frame time logic // -------------------- float currentFrame = static_cast(glfwGetTime()); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // input // ----- processInput(window); // render // ------ glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // be sure to activate shader when setting uniforms/drawing objects lightingShader.use(); lightingShader.setVec3("light.position", lightPos); lightingShader.setVec3("viewPos", camera.Position); // light properties lightingShader.setVec3("light.ambient", 0.2f, 0.2f, 0.2f); lightingShader.setVec3("light.diffuse", 0.5f, 0.5f, 0.5f); lightingShader.setVec3("light.specular", 1.0f, 1.0f, 1.0f); // material properties lightingShader.setFloat("material.shininess", 64.0f); // view/projection transformations glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); glm::mat4 view = camera.GetViewMatrix(); lightingShader.setMat4("projection", projection); lightingShader.setMat4("view", view); // world transformation glm::mat4 model = glm::mat4(1.0f); lightingShader.setMat4("model", model); // bind diffuse map glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, diffuseMap); // bind specular map glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, specularMap); // render the cube glBindVertexArray(cubeVAO); glDrawArrays(GL_TRIANGLES, 0, 36); // also draw the lamp object lightCubeShader.use(); lightCubeShader.setMat4("projection", projection); lightCubeShader.setMat4("view", view); model = glm::mat4(1.0f); model = glm::translate(model, lightPos); model = glm::scale(model, glm::vec3(0.2f)); // a smaller cube lightCubeShader.setMat4("model", model); glBindVertexArray(lightCubeVAO); glDrawArrays(GL_TRIANGLES, 0, 36); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } ``` -------------------------------- ### Bind Multiple Textures to Texture Units (OpenGL C++) Source: https://learnopengl.com/Getting-started/Textures Binds two different textures to texture units GL_TEXTURE0 and GL_TEXTURE1 respectively. This prepares the textures to be accessed by the shader samplers. ```cpp glActiveTexture(GL_TEXTURE0); bindTexture(GL_TEXTURE_2D, texture1); glActiveTexture(GL_TEXTURE1); bindTexture(GL_TEXTURE_2D, texture2); bindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); ``` -------------------------------- ### Initialize Shader Uniforms and Viewport (C++) Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F6.pbr%2F2.2.2.ibl_specular_textured%2Fibl_specular_textured.cpp This snippet shows the initialization of projection matrices for PBR and background shaders, and the configuration of the OpenGL viewport to match the window's framebuffer size. It ensures correct rendering dimensions before the main loop begins. Dependencies include GLM and GLFW. ```cpp // initialize static shader uniforms before rendering // -------------------------------------------------- glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); pbrShader.use(); pbrShader.setMat4("projection", projection); backgroundShader.use(); backgroundShader.setMat4("projection", projection); // then before rendering, configure the viewport to the original framebuffer's screen dimensions int scrWidth, scrHeight;glfwGetFramebufferSize(window, &scrWidth, &scrHeight); glViewport(0, 0, scrWidth, scrHeight); ``` -------------------------------- ### OpenGL State Configuration Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F4.advanced_opengl%2F10.2.asteroids%2Fasteroids.cpp Configures global OpenGL states. This example enables depth testing, which is essential for correct 3D rendering by ensuring that objects closer to the camera obscure objects farther away. ```cpp #include #include // ... other includes and function declarations ... int main() { // ... glfw and glad initialization ... // configure global opengl state // ----------------------------- glEnable(GL_DEPTH_TEST); // ... rest of the initialization ... return 0; } ``` -------------------------------- ### Assign Samplers to Texture Units (OpenGL C++) Source: https://learnopengl.com/Getting-started/Textures Assigns shader sampler uniforms ('texture1' and 'texture2') to specific texture units (0 and 1). This links the shader variables to the bound textures. ```cpp ourShader.use(); // don't forget to activate the shader before setting uniforms! glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), 0); // set it manually ourShader.setInt("texture2", 1); // or with shader class while(...) { [...] } ``` -------------------------------- ### Main Render Loop with Time Logic and Input Processing Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F4.advanced_opengl%2F10.2.asteroids%2Fasteroids.cpp The main render loop continuously processes events, updates per-frame time logic, handles user input, and clears the screen. It prepares the view and projection matrices for rendering. ```cpp #include #include #include #include // ... other includes and function declarations ... // timing float deltaTime = 0.0f; float lastFrame = 0.0f; int main() { // ... initialization ... // render loop // ----------- while (!glfwWindowShouldClose(window)) { // per-frame time logic // -------------------- float currentFrame = static_cast(glfwGetTime()); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // input // ----- processInput(window); // render // ------ glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // configure transformation matrices glm::mat4 projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 1000.0f); glm::mat4 view = camera.GetViewMatrix();; shader.use(); shader.setMat4("projection", projection); shader.setMat4("view", view); // ... drawing commands ... glfwSwapBuffers(window); glfwPollEvents(); } // ... cleanup ... return 0; } ``` -------------------------------- ### Vertex Shader with Texture Coordinate Input (GLSL) Source: https://learnopengl.com/Getting-started/Textures This GLSL vertex shader processes vertex data, including position, color, and texture coordinates. It passes the texture coordinates to the fragment shader for sampling. ```glsl #version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec3 aColor; layout (location = 2) in vec2 aTexCoord; out vec3 ourColor; out vec2 TexCoord; void main() { gl_Position = vec4(aPos, 1.0); ourColor = aColor; TexCoord = aTexCoord; } ``` -------------------------------- ### Render Light Source Visualization (OpenGL) Source: https://learnopengl.com/code_viewer_gh.php?code=src%2F2.lighting%2F6.multiple_lights%2Fmultiple_lights.cpp Draws small cube objects to visualize point light sources. It sets the 'lightCubeShader', view, and projection matrices, then iterates through light positions, applying translation and scaling transformations to a model matrix before drawing each light cube. Assumes 'lightCubeVAO' is bound. ```opengl // also draw the lamp object(s) lightCubeShader.use(); lightCubeShader.setMat4("projection", projection); lightCubeShader.setMat4("view", view); // we now draw as many light bulbs as we have point lights. glBindVertexArray(lightCubeVAO); for (unsigned int i = 0; i < 4; i++) { model = glm::mat4(1.0f); model = glm::translate(model, pointLightPositions[i]); model = glm::scale(model, glm::vec3(0.2f)); // Make it a smaller cube lightCubeShader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); } ``` -------------------------------- ### Create GLFW Window and Set Context Source: https://learnopengl.com/Getting-started/Hello-Window Creates a GLFW window with specified dimensions and title, then makes its OpenGL context current for the calling thread. Handles potential window creation failures. ```cpp GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } disebabkanglfwMakeContextCurrent(window); ```