• Advertisement
Sign in to follow this  

OpenGL Code Structure for Model Data

This topic is 2329 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I've built a few model importers in the past, but I'm stuck on code structure. Should I create one Model class that can load static and dynamic (animated) geometry, and use one vertex format? I could reduce my vertex positions to GL_SHORT vectors and cache static geometry data using VBOs in OpenGL but I'd still have to use floating-point vectors for vertex positions and normals for software skinning.

What I have now is an abstract Model class that doesn't do much but manage materials (one material per mesh), then my two subclasses of my Model class will load and store data for OBJ and MD5 models. The vertex structures are different between the two, and therefore, the collection of mesh data are also different too.


Does this seem about right?

Share this post


Link to post
Share on other sites
Advertisement
Be more modular.

Most people write simple wrappers around OpenGL rather than calling OpenGL functions directly.
One thing they commonly do is to make an index buffer class, and that class will automatically resize to GL_INT if you add an index larger than 0xFFFF. Don’t hardcode GL_SHORT. Use GL_SHORT until it is no longer sufficient.

Next, break your model class into multiple classes.
Firstly, a “model” is a collection of meshes, so you will at least need another class to encapsulate the functionality of a mesh (this is what stores your vertex buffers etc.)

Although you don’t have to follow my system exactly, what I have done is to break the model class into its core parts.
CModel.
CAnimatedModel.
CDrawableModel.

A CModel just holds the actual model data. Bounding boxes, vertices, etc. The vertices can be removed after the graphics data has been compiled.
A CAnimatedModel adds animation functionality. It holds the bind pose and anything else related to animations. It is fairly small because it only holds the animation data. Model instances actually use the animation data.
A CDrawableModel is of course responsible for taking the vertices, putting them into vertex buffers, and providing a Render() function. Logically, it adds whatever functionality is needed to render the model.


This applies to the shared model data.

Next you need to make instances of this shared data.
The instances can also be layered as above, so that the CAnimatedModelInstance can update joint matrices on each tick, etc.
The CDrawableModelInstance class can perform CPU skinning (if that is what you want).


Though you don’t have to follow my system exactly, break things down into logical blocks. What parts of the model are related, or more specifically unrelated to the other parts?
It is foreseeable that you would want a model that has no graphics data. Only collision data. So don’t mix core model data with graphics model data.



Additionally, don’t use only one vertex format. Skinning on the CPU will be more efficient if you store vertices in their own buffer and normals in their own buffer, and pad them to 16 bytes between elements. This allows you to exploit SIMD. And a single vertex format is simply restrictive. Build a format based on what model data exists.


L. Spiro

Share this post


Link to post
Share on other sites
@YogurtEmperor:

Do you see an advantage to having each mesh have its own vertex/index buffers rather than just having one in the model and have the meshes use that via vertex offsets, etc?


I've been recently thinking of a better structure myself and I have something similar to what YogurtEmperor has mentioned but a little simplified IMO. Here are roughly the 5 main classes that I've been thinking of:

Geometry
Contains the model data (vertex streams like position, normal, uv, bone weights) and the vertex/index buffers formed from the available streams. There should be only one of these in memory for each unique model loaded from disk and therefore this data is shared between model instances.

AnimationController
A higher level structure which contains a number of shared Animation resources. It is responsible for updating the animations and doing any blending trickery.

Animation
Contains the key-frame data for one animation. There should be only one of these in memory for each unique animation loaded from disk and therefore this data is shared between animation controllers.

Model
Represents an instance of a model and is basically a container of Mesh objects that makes up a complete model. It can either be static or animated with an AnimationController.

Mesh
Represents part of a model and simply contains the offsets to the vertex/index buffers within the Geometry.

Share this post


Link to post
Share on other sites

@YogurtEmperor:

Do you see an advantage to having each mesh have its own vertex/index buffers rather than just having one in the model and have the meshes use that via vertex offsets, etc?

Having multiple parts in one buffer should theoretically be faster, but I personally prefer the organization and freedom of multiple buffers. Since the different meshes that make up a model can have different vertex attributes, you won’t always be able to make just one buffer for the whole model.
One thing you would want to do though if you plan on CPU skinning is to at least keep the skinned vertices and normals separate.


L. Spiro

Share this post


Link to post
Share on other sites
I've thought about concatenating everything into one vertex buffer and one index buffer, but would that be beneficial? I'm still calling sections of it using glDrawElements() per mesh.

Here's my older setup:
ModelVertex: common vertex format for all models --use to be a total buffer of unsigned chars that held data based on my model's vertex format
ModelMesh: each holds a vertex and index buffer to render a mesh of the model
Model: holds a collection of meshes which will be rendered
Object: renderable instance of a model --holds a pointer to a valid Model with data loaded. Each "Object" holds it's own transformation matrix, can be attached to other matrices, "point" at other objects, and run along a spline among other features. Object also contains a collection of AnimationChannel instances which will process skinned animations
AnimationChannel: holds current playback information such as current playback frame, playback status, and looping flag for a single animation to be blended with another animation
Animation: holds animation keys to translation and scale vectors, and quaternion keys. One only instance is held.

So, I load models up once, then place instances of it in the world using Object. This is the old setup, but now I'm giving static geometry some love by supporting the OBJ format for static objects, giving them a smaller vertex format, and using static VBOs.

Doing so, I now have two subclasses of the Model and Object for OBJ and MD5:
Model: OBJModel and MD5Model
Object: OBJObject and MD5Object

This is my current setup, but I want to switch to the COLLADA format for easier loading. If I switch to this format, I'm thinking of storing all my model data in one Model/Mesh/Vertex class, and use one Object class to load it. If it's a dynamic object, I'll have pointers to animation data, and have an animation flag in the model format. All my skinning is done on the CPU right now since my target's GPU isn't ready for GPU skinning.

[color=#1C2837][size=2]
I agree with that, but my game is targeted for iOS platforms where I've been told that interleaved vertex are much faster. I can cram the data into an interleaved buffer of unsigned chars, then ship it to the static VBO for static models... By the way, when a VBO is created, the vertex arrays can be deleted, right?

Share this post


Link to post
Share on other sites
The way I handle data is that anything static is static, and anything animated is dynamic. This way it doesn’t matter what the source of the data is. Anything with no joint weights is static, period.
I have only one format, which is custom, but if I wanted to directly load another format, it would only require a new loading routine, not a new model class.

Again, using only one vertex buffer is a valid approach, but it may give you headaches.

Yes you can delete the source vertex buffer after you make a VBO out of it.


L. Spiro

Share this post


Link to post
Share on other sites

The way I handle data is that anything static is static, and anything animated is dynamic. This way it doesn’t matter what the source of the data is. Anything with no joint weights is static, period.
I have only one format, which is custom, but if I wanted to directly load another format, it would only require a new loading routine, not a new model class.

Again, using only one vertex buffer is a valid approach, but it may give you headaches.

Yes you can delete the source vertex buffer after you make a VBO out of it.


L. Spiro


Do you perform your skinning on the GPU? Since I'm going for iOS devices, GPU skinning isn't a very good option from personal experience.

When I started implementing VBOs for my static geometry, it seems like I get an exception whenever I release my vertex from main memory. Here's what I'm doing:

void OBJMesh::CompileBuffers()
{
// generate the VBO
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(ModelVertex) * numVertices, (void*)vertices, GL_STATIC_DRAW);

// generate the IBO
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned long)*numIndices, (void*)indices, GL_STATIC_DRAW);
//ReleaseVertexData(); // release the vertex data (THIS CAUSES A CRASH WHEN DRAWING)

// use regular data for buffering
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}



ReleaseVertexData() is commented since it releases the vertex data that's generated during load-time. Uncommenting it will release the vertex data, but crash the game when it tries to draw something.

Here's a stripped-down version of my rendering code:

// draw each mesh in the model

OBJMesh *objMesh = NULL;

for(int i=0;i<model->GetNumMeshes();i++)

{

// make sure the mesh exists
objMesh = (OBJMesh*)model->GetMesh(i);
if(!objMesh || !objMesh->GetMaterial()) continue;
glBindBuffer(GL_ARRAY_BUFFER, objMesh->GetVBO());
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, objMesh->GetIBO());

// upload the vertex data from the VBO/IBO based on
glVertexAttribPointer(GL_VERTEX_ATTRIB0, 3, GL_FLOAT, GL_FALSE, sizeof(ModelVertex), 0);
glVertexAttribPointer(GL_VERTEX_ATTRIB1, 2, GL_FLOAT, GL_FALSE, sizeof(ModelVertex), (void*)12);
glVertexAttribPointer(GL_VERTEX_ATTRIB2, 3, GL_FLOAT, GL_FALSE, sizeof(ModelVertex), (void*)20);
glVertexAttribPointer(GL_VERTEX_ATTRIB3, 3, GL_FLOAT, GL_FALSE, sizeof(ModelVertex), (void*)32);
glDrawElements(GL_TRIANGLES, objMesh->GetNumIndices(), GL_UNSIGNED_INT, NULL);
}


I removed some uniform and texture-setting code, but this is what I have.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By QQemka
      Hello. I am coding a small thingy in my spare time. All i want to achieve is to load a heightmap (as the lowest possible walking terrain), some static meshes (elements of the environment) and a dynamic character (meaning i can move, collide with heightmap/static meshes and hold a varying item in a hand ). Got a bunch of questions, or rather problems i can't find solution to myself. Nearly all are deal with graphics/gpu, not the coding part. My c++ is on high enough level.
      Let's go:
      Heightmap - i obviously want it to be textured, size is hardcoded to 256x256 squares. I can't have one huge texture stretched over entire terrain cause every pixel would be enormous. Thats why i decided to use 2 specified textures. First will be a tileset consisting of 16 square tiles (u v range from 0 to 0.25 for first tile and so on) and second a 256x256 buffer with 0-15 value representing index of the tile from tileset for every heigtmap square. Problem is, how do i blend the edges nicely and make some computationally cheap changes so its not obvious there are only 16 tiles? Is it possible to generate such terrain with some existing program?
      Collisions - i want to use bounding sphere and aabb. But should i store them for a model or entity instance? Meaning i have 20 same trees spawned using the same tree model, but every entity got its own transformation (position, scale etc). Storing collision component per instance grats faster access + is precalculated and transformed (takes additional memory, but who cares?), so i stick with this, right? What should i do if object is dynamically rotated? The aabb is no longer aligned and calculating per vertex min/max everytime object rotates/scales is pretty expensive, right?
      Drawing aabb - problem similar to above (storing aabb data per instance or model). This time in my opinion per model is enough since every instance also does not have own vertex buffer but uses the shared one (so 20 trees share reference to one tree model). So rendering aabb is about taking the model's aabb, transforming with instance matrix and voila. What about aabb vertex buffer (this is more of a cosmetic question, just curious, bumped onto it in time of writing this). Is it better to make it as 8 points and index buffer (12 lines), or only 2 vertices with min/max x/y/z and having the shaders dynamically generate 6 other vertices and draw the box? Or maybe there should be just ONE 1x1x1 cube box template moved/scaled per entity?
      What if one model got a diffuse texture and a normal map, and other has only diffuse? Should i pass some bool flag to shader with that info, or just assume that my game supports only diffuse maps without fancy stuff?
      There were several more but i forgot/solved them at time of writing
      Thanks in advance
    • By RenanRR
      Hi All,
      I'm reading the tutorials from learnOpengl site (nice site) and I'm having a question on the camera (https://learnopengl.com/Getting-started/Camera).
      I always saw the camera being manipulated with the lookat, but in tutorial I saw the camera being changed through the MVP arrays, which do not seem to be camera, but rather the scene that changes:
      Vertex Shader:
      #version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0f); TexCoord = vec2(aTexCoord.x, aTexCoord.y); } then, the matrix manipulated:
      ..... glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); .... glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); ourShader.setMat4("view", view); .... model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model);  
      So, some doubts:
      - Why use it like that?
      - Is it okay to manipulate the camera that way?
      -in this way, are not the vertex's positions that changes instead of the camera?
      - I need to pass MVP to all shaders of object in my scenes ?
       
      What it seems, is that the camera stands still and the scenery that changes...
      it's right?
       
       
      Thank you
       
    • By dpadam450
      Sampling a floating point texture where the alpha channel holds 4-bytes of packed data into the float. I don't know how to cast the raw memory to treat it as an integer so I can perform bit-shifting operations.

      int rgbValue = int(textureSample.w);//4 bytes of data packed as color
      // algorithm might not be correct and endianness might need switching.
      vec3 extractedData = vec3(  rgbValue & 0xFF000000,  (rgbValue << 8) & 0xFF000000, (rgbValue << 16) & 0xFF000000);
      extractedData /= 255.0f;
    • By Devashish Khandelwal
      While writing a simple renderer using OpenGL, I faced an issue with the glGetUniformLocation function. For some reason, the location is coming to be -1.
      Anyone has any idea .. what should I do?
    • By Andrey OGL_D3D
      Hi all!
      I try to use the Sun shafts effects via post process in my 3DEngine, but i have some artefacts on final image(Please see attached images).
      The effect contains the following passes:
      1) Depth scene pass;
      2) "Shafts pass" Using DepthPass Texture + RGBA BackBuffer texture.
      3) Shafts pass texture +  RGBA BackBuffer texture.
      Shafts shader for 2 pass:
      // uniform sampler2D FullSampler; // RGBA Back Buffer uniform sampler2D DepthSampler; varying vec2 tex; #ifndef saturate float saturate(float val) {     return clamp(val, 0.0, 1.0); } #endif void main(void) {     vec2 uv = tex;     float sceneDepth = texture2D(DepthSampler, uv.xy).r;     vec4  scene        = texture2D(FullSampler, tex);     float fShaftsMask     = (1.0 - sceneDepth);     gl_FragColor = vec4( scene.xyz * saturate(sceneDepth), fShaftsMask ); } final shader:
      // uniform sampler2D FullSampler; // RGBA Back Buffer uniform sampler2D BlurSampler; // shafts sampler varying vec4 Sun_pos; const vec4    ShaftParams = vec4(0.1,2.0,0.1,2.0); varying vec2 Tex_UV; #ifndef saturate  float saturate(float val) {     return clamp(val, 0.0, 1.0); } #endif vec4 blendSoftLight(vec4 a, vec4 b) {   vec4 c = 2.0 * a * b + a * a * (1.0 - 2.0 * b);   vec4 d = sqrt(a) * (2.0 * b - 1.0) + 2.0 * a * (1.0 - b);       // TODO: To look in Crysis what it the shit???   //return ( b < 0.5 )? c : d;   return any(lessThan(b, vec4(0.5,0.5,0.5,0.5)))? c : d; } void main(void) {     vec4 sun_pos = Sun_pos;     vec2    sunPosProj = sun_pos.xy;     //float    sign = sun_pos.w;     float    sign = 1.0;     vec2    sunVec = sunPosProj.xy - (Tex_UV.xy - vec2(0.5, 0.5));     float    sunDist = saturate(sign) * saturate( 1.0 - saturate(length(sunVec) * ShaftParams.y ));     sunVec *= ShaftParams.x * sign;     vec4 accum;     vec2 tc = Tex_UV.xy;     tc += sunVec;     accum = texture2D(BlurSampler, tc);     tc += sunVec;     accum += texture2D(BlurSampler, tc) * 0.875;     tc += sunVec;     accum += texture2D(BlurSampler, tc) * 0.75;     tc += sunVec;     accum += texture2D(BlurSampler, tc) * 0.625;     tc += sunVec;     accum += texture2D(BlurSampler, tc) * 0.5;     tc += sunVec;     accum += texture2D(BlurSampler, tc) * 0.375;     tc += sunVec;     accum += texture2D(BlurSampler, tc) * 0.25;     tc += sunVec;     accum += texture2D(BlurSampler, tc) * 0.125;     accum  *= 0.25 * vec4(sunDist, sunDist, sunDist, 1.0);           accum.w += 1.0 - saturate(saturate(sign * 0.1 + 0.9));     vec4    cScreen = texture2D(FullSampler, Tex_UV.xy);           vec4    cSunShafts = accum;     float fShaftsMask = saturate(1.00001 - cSunShafts.w) * ShaftParams.z * 2.0;              float fBlend = cSunShafts.w;     vec4 sunColor = vec4(0.9, 0.8, 0.6, 1.0);     accum =  cScreen + cSunShafts.xyzz * ShaftParams.w * sunColor * (1.0 - cScreen);     accum = blendSoftLight(accum, sunColor * fShaftsMask * 0.5 + 0.5);     gl_FragColor = accum; } Demo project:
      Demo Project
      Shaders for postprocess Shaders/SunShaft/
      What i do wrong ?
      Thanks!
       


  • Advertisement