Introduction
When developing graphics applications using OpenGL (or any other graphics API), shader code often requires frequent updates during the development process. Rather than restarting the application every time a change is made, it's more efficient to "hot reload" the shaders, re-compiling them when modifications are detected.
The Idea
The idea is to check for changes in the shader files and automatically reload them when necessary. This eliminates the need to restart your application every time you modify a shader.
Code Example
Here's the relevant code for integrating hot reloading in your shader class:
void Shader::Reload() {
if (ShaderFilesModified()) {
std::cout << "Reloading shaders...\n";
LoadShader();
TrackFileModification();
}
}
bool Shader::ShaderFilesModified() {
return (std::filesystem::last_write_time(vertex_path) != vertex_last_write_time) ||
(std::filesystem::last_write_time(fragment_path) != fragment_last_write_time);
}
void Shader::TrackFileModification() {
vertex_last_write_time = std::filesystem::last_write_time(vertex_path);
fragment_last_write_time = std::filesystem::last_write_time(fragment_path);
}
while (!glfwWindowShouldClose(window)) {
shader.Reload();
// code ...
shader.Use();
// code ...
}
Explanation
The key function is Reload()
, which checks if the shader files have been modified using ShaderFilesModified()
. If they have, it reloads and recompiles the shaders using LoadShader()
and updates the modification timestamps with TrackFileModification()
.
Complete source code
Below you can find the complete source code for the shader class which I personally use in my OpenGL shadertoy alternative.