GLSL Rendering Mulptile Materials Across a Model

Started by
2 comments, last by too_many_stars 6 years, 1 month ago

Hello Everyone,

Here is what I have so far when it comes to rendering a model with glsl


glsl->setUniform( "Ka" , material.ambient );
glsl->setUniform( "Kd" , material.diffuse );
glsl->setUniform( "Ks" , material.specular );
glsl->setUniform( "mat_shine" , material.shininess );

glBindVertexArray( vao_id );

glDrawArrays( GL_TRIANGLES , 0 , vertices.size() );

glBindVertexArray( 0 );

This works fine for a single material applied across the entire model.

However, I now import an .obj model with various materials from Blender. After mapping triangle faces to material ids I am unsure how the above call to

glDrawArrays( GL_TRIANGLES , 0 , vertices.size() ); needs to change in order to render more than one material on a single model.

Any help would be great appreciated,

Mike

Advertisement

You'll have to split up your model. For each material, you add all its triangles consecutively to your vertex buffer object. Then for each material set the correct uniforms, and draw the correct subrange of the VBO. Something like this


struct Batch
  {
  Material material;
  GLint first;
  GLsizei count;
  };
  
std::vector<Batch> batches;

for (each material in your obj)
  {
  Batch batch;
  batch.material = material;
  batch.first = // current vbo vertex count
  // add vertices to vbo here
  batch.count = // number of vertices added for this material
  batches.push_back(batch);
  }

// assuming everything still fits into one vbo
// you only need to bind a vao once
glBindVertexArray( vao_id );

for (const auto& batch : batches)
  {
  glsl->setUniform( "Ka" , batch.material.ambient );
  glsl->setUniform( "Kd" , batch.material.diffuse );
  glsl->setUniform( "Ks" , batch.material.specular );
  glsl->setUniform( "mat_shine" , batch.material.shininess );
  glDrawArrays( GL_TRIANGLES , batch.first , batch.count);
  }

glBindVertexArray( 0 );

 

Thank you so much Koen, that's a great answer. I figured there was going to have to be some kind of batching process. 

Mike

This topic is closed to new replies.

Advertisement