Skip to Content
ResourcesProject Resources

Project Resources

Resources Directory

For better organisation, we put our .glsl shader files in the src/main/resources directory, which is the default resource directory for Java projects.

This allows us to easily load the shader files using the classpath.

Fragment Shader

One of the shader files we have is fragment.glsl, which is the fragment shader for rendering the color of the pixels.

#version 330 core in vec3 passColor; in vec3 passNormal; in vec3 passFragPos; in vec2 passUV; out vec4 fragColor; // --- Texture atlas --- uniform sampler2D atlasTexture; // bound to texture unit 0 uniform bool useTexture; // false for untextured primitives (Cube etc.) // --- Light properties --- uniform vec3 lightPos; // world-space position of the point light uniform vec3 lightColor; // RGB color/intensity of the light // --- Camera position (needed for specular) --- uniform vec3 viewPos; void main() { // Base color: either sampled from the atlas or the vertex color vec3 baseColor; if (useTexture) { vec4 texSample = texture(atlasTexture, passUV); // Discard fully transparent fragments (e.g. atlas padding) if (texSample.a < 0.01) discard; // Blend texture color with vertex color so tinting still works baseColor = texSample.rgb * passColor; } else { baseColor = passColor; } // --- Ambient --- float ambientStrength = 0.15; vec3 ambient = ambientStrength * lightColor; // --- Diffuse --- vec3 norm = normalize(passNormal); vec3 lightDir = normalize(lightPos - passFragPos); float diff = max(dot(norm, lightDir), 0.0); vec3 diffuse = diff * lightColor; // --- Specular (Phong) --- float specularStrength = 0.5; float shininess = 32.0; vec3 viewDir = normalize(viewPos - passFragPos); vec3 reflectDir = reflect(-lightDir, norm); float spec = pow(max(dot(viewDir, reflectDir), 0.0), shininess); vec3 specular = specularStrength * spec * lightColor; // --- Combine --- vec3 result = (ambient + diffuse + specular) * baseColor; fragColor = vec4(result, 1.0); }

Vertex Shader

The other shader file we have is vertex.glsl, which is the vertex shader for rendering the position of the vertices.

#version 330 core layout(location = 0) in vec3 position; layout(location = 1) in vec3 color; layout(location = 2) in vec3 normal; layout(location = 3) in vec2 uv; out vec3 passColor; out vec3 passNormal; out vec3 passFragPos; out vec2 passUV; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { vec4 worldPos = model * vec4(position, 1.0); gl_Position = projection * view * worldPos; passFragPos = vec3(worldPos); // Normal matrix: inverse-transpose of the model matrix upper-3x3. // Keeps normals perpendicular to the surface under non-uniform scaling. // For uniform scale this is equivalent to mat3(model). passNormal = mat3(transpose(inverse(model))) * normal; passColor = color; passUV = uv; }
Last updated on