Below is the GLSL code for converting between sRGB and linear color spaces. These functions operate on vec3 values, assuming the input represents RGB colors in the range [0, 1].
Explanation:
- sRGB to Linear: This conversion applies the sRGB inverse gamma curve. For values ≤ 0.04045, it's a simple linear scaling. Otherwise, it uses a power function with an exponent of 2.4.
- Linear to sRGB: This applies the sRGB gamma curve. For values ≤ 0.0031308, it's a linear scaling. Otherwise, it uses a power function with an exponent of 1/2.4.
These functions are designed to be used in a GLSL shader. Make sure to include them in your shader code (e.g., in the fragment shader).
// Function to convert from sRGB to linear color space
vec3 srgbToLinear(vec3 srgb) {
vec3 linear;
linear.r = (srgb.r <= 0.04045) ? srgb.r / 12.92 : pow((srgb.r + 0.055) / 1.055, 2.4);
linear.g = (srgb.g <= 0.04045) ? srgb.g / 12.92 : pow((srgb.g + 0.055) / 1.055, 2.4);
linear.b = (srgb.b <= 0.04045) ? srgb.b / 12.92 : pow((srgb.b + 0.055) / 1.055, 2.4);
return linear;
}
// Function to convert from linear to sRGB color space
vec3 linearToSrgb(vec3 linear) {
vec3 srgb;
srgb.r = (linear.r <= 0.0031308) ? 12.92 * linear.r : 1.055 * pow(linear.r, 1.0 / 2.4) - 0.055;
srgb.g = (linear.g <= 0.0031308) ? 12.92 * linear.g : 1.055 * pow(linear.g, 1.0 / 2.4) - 0.055;
srgb.b = (linear.b <= 0.0031308) ? 12.92 * linear.b : 1.055 * pow(linear.b, 1.0 / 2.4) - 0.055;
// Clamp the output to [0, 1] to ensure valid sRGB values
return clamp(srgb, 0.0, 1.0);
}
Usage Example:
In a fragment shader, you might use these functions like this:
#version 330 core
in vec3 vColor; // Assume this is in sRGB space
out vec4 fragColor;
void main() {
// Convert sRGB input to linear for calculations
vec3 linearColor = srgbToLinear(vColor);
// Perform some operations in linear space (e.g., lighting)
vec3 processedColor = linearColor * 2.0; // Example operation
// Convert back to sRGB for output
vec3 finalColor = linearToSrgb(processedColor);
fragColor = vec4(finalColor, 1.0);
}
Notes:
- Precision: GLSL shaders often use precision qualifiers like
highp for floating-point operations. If needed, you can add them (e.g., highp vec3 srgbToLinear(highp vec3 srgb)).
- Clamping: In the
linearToSrgb function, I added a clamp to ensure the output stays in [0, 1], as sRGB values should typically be in this range for display. You can remove it if you're handling clamping elsewhere.
- Performance: These functions process each channel (R, G, B) independently, which is standard for color space conversions.
- Edge Cases: The functions assume inputs are in [0, 1]. If your inputs might be outside this range, consider clamping them before conversion.
If you need versions for vec4 (to include alpha) or any modifications, let me know!