Certainly! To render buildings similar to how Google Maps does using OpenGL, you'll need both vertex and fragment shaders that handle lighting, texturing, and coloring. Below, I'll provide GLSL shader code tailored to your existing setup and offer guidance on integrating normals for lighting to achieve a more realistic appearance.
1. Understanding Your Current Setup
Based on your provided initialize function, each vertex currently contains:
- Position: 3 floats (
vec3)
- Color: 4 floats (
vec4)
- Texture Coordinates: 2 floats (
vec2)
This totals 9 floats per vertex. However, to incorporate lighting (which adds realism), normals are essential. Normals are vectors perpendicular to the surface and are crucial for lighting calculations.
2. Extending Vertex Data to Include Normals
First, let's modify your initialize function to include normals as additional vertex attributes. This change will update each vertex to have:
- Position: 3 floats
- Normal: 3 floats
- Color: 4 floats
- Texture Coordinates: 2 floats
Totaling 12 floats per vertex.
Modified initialize Function:
void OptimizedMeshRenderer::initialize(uint32_t meshId, const Mesh* mesh, float walkableSlopeAngle, float texScale) {
const float* verts = mesh->getVerts();
const int* tris = mesh->getTris();
int ntris = mesh->getTriCount();
const float walkableThr = cosf(walkableSlopeAngle / 180.0f * DU_PI);
std::vector<float> vertexData;
vertexData.reserve(ntris * 3 * 12); // Updated to 12 floats per vertex
for (int i = 0; i < ntris; ++i) {
float norm[3];
mesh->calculateNormal(i, norm);
for (int j = 0; j < 3; ++j) {
const float* v = &verts[tris[i * 3 + j] * 3];
// Position
vertexData.insert(vertexData.end(), { v[0], v[1], v[2] });
// Normal
vertexData.insert(vertexData.end(), { norm[0], norm[1], norm[2] });
// Color
vertexData.insert(vertexData.end(), { 1.0f, 1.0f, 1.0f, 1.0f }); // Default white color
// Texture Coordinates
vertexData.insert(vertexData.end(), { v[0] * texScale, v[1] * texScale });
}
}
MeshData meshData;
meshData.vertexCount = ntris * 3;
meshData.color = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f); // Updated to white
glGenVertexArrays(1, &meshData.vao);
glGenBuffers(1, &meshData.vbo);
glBindVertexArray(meshData.vao);
glBindBuffer(GL_ARRAY_BUFFER, meshData.vbo);
glBufferData(GL_ARRAY_BUFFER, vertexData.size() * sizeof(float), vertexData.data(), GL_DYNAMIC_DRAW);
// Position Attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// Normal Attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
// Color Attribute
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);
// Texture Coordinates Attribute
glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (void*)(10 * sizeof(float)));
glEnableVertexAttribArray(3);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
meshes[meshId] = meshData;
}
Key Changes:
- Vertex Data Layout: Updated to include normals.
- Attribute Pointers: Adjusted to account for the additional normal data.
- Location 0: Position (
vec3)
- Location 1: Normal (
vec3)
- Location 2: Color (
vec4)
- Location 3: Texture Coordinates (
vec2)
3. Shader Programs
Now, let's create the vertex and fragment shaders that utilize these attributes for lighting and texturing.
Vertex Shader (building.vert):
#version 330 core
layout(location = 0) in vec3 aPos; // Position
layout(location = 1) in vec3 aNormal; // Normal
layout(location = 2) in vec4 aColor; // Color
layout(location = 3) in vec2 aTexCoord; // Texture Coordinates
out vec3 FragPos; // Fragment Position in World Space
out vec3 Normal; // Normal in World Space
out vec4 VertexColor; // Vertex Color
out vec2 TexCoord; // Texture Coordinates
// Uniforms
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main()
{
// Calculate the vertex position in world space
FragPos = vec3(model * vec4(aPos, 1.0));
// Transform the normal to world space
Normal = mat3(transpose(inverse(model))) * aNormal;
// Pass through color and texture coordinates
VertexColor = aColor;
TexCoord = aTexCoord;
// Final vertex position
gl_Position = projection * view * vec4(FragPos, 1.0);
}
Fragment Shader (building.frag):
#version 330 core
in vec3 FragPos; // Fragment Position in World Space
in vec3 Normal; // Normal in World Space
in vec4 VertexColor; // Vertex Color
in vec2 TexCoord; // Texture Coordinates
out vec4 FragColor;
// Material properties
uniform sampler2D texture1;
uniform vec3 materialColor;
// Lighting properties
uniform vec3 lightPos; // Position of the light source
uniform vec3 viewPos; // Position of the camera/viewer
uniform vec3 lightColor; // Color of the light
void main()
{
// Ambient lighting
float ambientStrength = 0.3;
vec3 ambient = ambientStrength * lightColor;
// Diffuse lighting
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(lightPos - FragPos);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = diff * lightColor;
// Specular lighting
float specularStrength = 0.5;
vec3 viewDir = normalize(viewPos - FragPos);
vec3 reflectDir = reflect(-lightDir, norm);
// Phong exponent
float shininess = 32.0;
float spec = pow(max(dot(viewDir, reflectDir), 0.0), shininess);
vec3 specular = specularStrength * spec * lightColor;
// Combine lighting components
vec3 lighting = ambient + diffuse + specular;
// Texture sampling
vec4 texColor = texture(texture1, TexCoord);
// Final color
FragColor = vec4(materialColor, 1.0) * texColor * vec4(lighting, 1.0) * VertexColor;
}
4. Shader Integration
Ensure that your shader class is correctly loading and compiling these shaders. Here's how you can set up and use the shaders:
Loading the Shaders:
// Load shader sources
const char* vertexShaderSource = /* Load from 'building.vert' */;
const char* fragmentShaderSource = /* Load from 'building.frag' */;
// Initialize shader
Shader buildingShader(vertexShaderSource, fragmentShaderSource);
Setting Uniforms:
Before rendering, set the necessary uniforms such as transformation matrices, lighting parameters, and textures.
// Activate shader
buildingShader.use();
// Set transformation matrices
buildingShader.setMat4("model", modelMatrix);
buildingShader.setMat4("view", viewMatrix);
buildingShader.setMat4("projection", projectionMatrix);
// Set lighting uniforms
buildingShader.setVec3("lightPos", lightPosition);
buildingShader.setVec3("viewPos", cameraPosition);
buildingShader.setVec3("lightColor", glm::vec3(1.0f, 1.0f, 1.0f)); // White light
// Set material properties
buildingShader.setVec3("materialColor", glm::vec3(1.0f, 1.0f, 1.0f)); // White color or adjust as needed
// Bind texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureID);
buildingShader.setInt("texture1", 0);
5. Rendering Loop
Ensure your rendering loop activates the shader, binds the appropriate VAO, and draws the meshes.
// Activate shader
buildingShader.use();
// Iterate and render each mesh
for (const auto& [meshId, meshData] : meshes) {
glBindVertexArray(meshData.vao);
glDrawArrays(GL_TRIANGLES, 0, meshData.vertexCount);
}
glBindVertexArray(0);
6. Additional Tips
-
Textures: Ensure you have textures for your buildings. Load them using an image loading library like stb_image and bind them correctly.
-
Lighting Positions: Position your lightPos in a way that illuminates the buildings effectively. You can experiment with directional lights, point lights, or even multiple light sources for more complex lighting.
-
Camera Setup: Properly set up your view and projection matrices to navigate and visualize the 3D environment effectively, similar to Google Maps' 3D buildings.
-
Performance Optimization: For rendering large maps with numerous buildings, consider implementing Level of Detail (LOD), frustum culling, and batching techniques to optimize performance.
7. Final Remarks
By incorporating normals and using lighting calculations in your shaders, your buildings will have a more realistic and visually appealing appearance. This setup allows for dynamic lighting, shading, and texturing, closely resembling the rendering style of platforms like Google Maps.
Feel free to adjust the lighting strengths, colors, and material properties to better fit the aesthetic you're aiming for. If you encounter any issues or have further questions, don't hesitate to ask!