Sign in to follow this  
fishbulb52

OpenGL MD2 and OpenGL Game Programming code...

Recommended Posts

Hello everyone! I've been battling with MD2's for the last two days, and I've run into a little problem... I've basically copied the code from OpenGL Game Programming, and changed it a tad so that I wouldn't have to worry about textures just yet. The program compiles with no errors or warnings, but when I run it, it doesn't display the model at all, and it sucks up all my ram in a matter of seconds! I'm using Dev-C++ to do this, by the way. Here's my code:
 
// Includes

#include <stdlib.h>
#include <windows.h>
#include <gl/gl.h>
#include <stdio.h>
#include <stdlib.h>

// Function Declarations

// START MD2 JUNK

//header declarations... took a while to figure out this was missing...
typedef struct
{
        int ident;
        int version;
        int skinwidth;
        int skinheight;
        int framesize;
        int numSkins;
        int numXYZ;
        int numST;
        int numTris;
        int numGLcmds;
        int numFrames;
        int offsetSkins;
        int offsetST;
        int offsetTris;
        int offsetFrames;
        int offsetGLcmds;
        int offsetEnd;
} modelHeader_t;

//Vectors, in all their glory!

typedef struct
{
 float point[3];
} vector_t;


//Vector Subtraction...

vector_t operator-(vector_t a, vector_t b)
{
 vector_t c;

 c.point[0] = a.point[0] - b.point[0];
 c.point[1] = a.point[1] - b.point[1];
 c.point[2] = a.point[2] - b.point[2];

 return c;
}

//Vector Multiplication...

vector_t operator*(float f, vector_t b)
{
 vector_t c;

 c.point[0] = f * b.point[0];
 c.point[1] = f * b.point[1];
 c.point[2] = f * b.point[2];

 return c;
}

//Vector Division...

vector_t operator/(vector_t a, vector_t b)
{
 vector_t c;

 c.point[0] = a.point[0]/b.point[0];
 c.point[1] = a.point[1]/b.point[1];
 c.point[2] = a.point[2]/b.point[2];

 return c;
}

//Vector Addition...

vector_t operator+(vector_t a, vector_t b)
{
 vector_t c;

 c.point[0] = a.point[0] + b.point[0];
 c.point[1] = a.point[1] + b.point[1];
 c.point[2] = a.point[2] + b.point[2];

 return c;
}

//All About Textures!

//A texture coordinate!!

typedef struct
{
 float s;
 float t;
} texCoord_t;

//Index of a texture coordinate!!

typedef struct
{
 short s;
 short t;
} stIndex_t;


//These are the supported formats:
enum texTypes_t
{
 PCX, BMP, TGA
};

//A simple texture...

typedef struct
{
 texTypes_t textureType;          //type of image file this texture is...

 int width;
 int height;
 long int scaledWidth;
 long int scaledHeight;
 unsigned int texID;              //texture object ID.
 unsigned char *data;             //texture data.
 unsigned char *palette;          //palette for texture (if it exists).
} texture_t;





//A single frame point!!

typedef struct
{
 unsigned char v[3];                 //point info
 unsigned char normalIndex;          //not used... just so it loads...
} framePoint_t;

//Info for that single frame...

typedef struct
{
 float scale [3];                    //scaling of the vertices.
 float translate[3];                 //translation for the vertices.
 char name[16];                      //name of the model.
 framePoint_t fp[1];                 //starting point in memory of
} frame_t;                           //frames's vertex list.

//A triangle, since the MD2 format is all triangles.

typedef struct
{
 unsigned short meshIndex[3];        //vertex indices.
 unsigned short stIndex[3];          //texture-coordinate indices.
} mesh_t;


//The model data for a single model - where it all ties together!

typedef struct
{
 int numFrames;
 int numPoints;
 int numTriangles;
 int numST;
 int frameSize;                      //size of each frame in bytes.
 int texWidth, texHeight;
 int currentFrame;                   //current frame # in animation.
 int nextFrame;                      //next frame #.
 float interpol;                     //percentage through frame.
 mesh_t *triIndex;                   //triangle list.
 texCoord_t *st;                    //texture coordinate list
 vector_t *pointList;                //vertex list
 texture_t *modelTex;                //texture data
} modelData_t;



//LOAD THE MODEL!!
modelData_t *LoadMD2Model(char *filename, char *textureName)
{
 FILE *filePtr;                      //file pointer
 int fileLen;                        //length of model file
 char *buffer;                       //file buffer

 modelData_t *model;                 //the model
 modelHeader_t *modelHeader;         //model header
 texture_t *md2Texture;              //model texture

 stIndex_t *stPtr;                   //texture indices
 frame_t *frame;                     //frame data
 vector_t *pointListPtr;             //index variable
 mesh_t *triIndex, *bufIndexPtr;     //index variables
 int i, j;                           //index variables


 //open the model file
 filePtr = fopen(filename, "rb");
 if (filePtr == NULL)
    return NULL;

 //find length of file
 fseek(filePtr, 0, SEEK_END);
 fileLen = ftell(filePtr);
 fseek(filePtr, 0, SEEK_SET);

 //read entire file into buffer
 buffer = (char*)malloc(fileLen + 1);
 fread(buffer, sizeof(char), fileLen, filePtr);

 //extract model file header from buffer
 modelHeader = (modelHeader_t*)buffer;

 //allocate memory for model data
 model = (modelData_t*)malloc(sizeof(modelData_t));
 if (model == NULL)
    return NULL;

 //allocate memory for all vertices on all frames
 model->pointList = (vector_t*)malloc(sizeof(vector_t)*modelHeader->numXYZ *
                     modelHeader->numFrames);

 //store vital model data
 model->numPoints = modelHeader->numXYZ;            //number of vertices
 model->numFrames = modelHeader->numFrames;         //number of frames
 model->frameSize = modelHeader->framesize;         //size of each frame

 //loop number of frames in model
 for(j = 0; j < modelHeader->numFrames; j++)
 {
       //offset points in this frame.
       frame = (frame_t*)&buffer[modelHeader->offsetFrames +
             modelHeader->framesize * j];

       //calculate the point positions based on frame details
       pointListPtr = (vector_t*)&model->pointList[modelHeader->numXYZ * j];
       for(i = 0; i < modelHeader->numXYZ; i++)
       {
             pointListPtr[i].point[0] = frame->scale[0] * frame->fp[i].v[0] +
                                        frame->translate[0];
             pointListPtr[i].point[1] = frame->scale[1] * frame->fp[i].v[1] +
                                        frame->translate[1];
             pointListPtr[i].point[2] = frame->scale[2] * frame->fp[i].v[2] +
                                        frame->translate[2];
        }
 }


/*
 //load the model texture
 md2Texture = LoadTexture(textureName);
 if (md2Texture != NULL)
 {
    //set texture up for OpenGL and store it (in the model data structure)
    SetupMd2Texture(md2Texture);
    model->modelTex = md2Texture;
 }
 else
     return NULL;

 //alocate memory for the model texture coordinates
 model->st = (texCoord_t*)malloc(sizeof(texCoord_t)*modelHeader->numST);

 //store number of texture coordinates
 model->numST = modelHeader->numST;

 //set texture pointer to texture coordinate offset
 strPtr = (stIndex_t*)&buffer[modelHeader->offsetST];

 //calculate and store the texture coordinates for the model
 for (i = 0; i < modelHeader->numST; i++)
 {
     model->st[i].s = (float)stPtr[i].s / (float)md2Texture->width;
     model->st[i].t = (float)stPtr[i].t / (float)md2Texture->height;
 }
*/
//A bunch of stuff wrong with these... who knows... figure it out later...
//not using textures now anyway... and no, im not rationalizing >_> 


 //allocate the list of triangle indices
 triIndex = (mesh_t*)malloc(sizeof(mesh_t) * modelHeader->numTris);

 //set total number of triangles
 model->numTriangles = modelHeader->numTris;
 model->triIndex = triIndex;

 //point to triangle indices in buffer
 bufIndexPtr = (mesh_t*)&buffer[modelHeader->offsetTris];



 //create a mesh (triangle) list by looping!!
 for (j = 0; j < model->numFrames; j++)
 {
     //for all triangles in each frame
     for(i = 0; i < modelHeader->numTris; i++)
     {
           //store the mesh and texture indices...
           triIndex[i].meshIndex[0] = bufIndexPtr[i].meshIndex[0];
           triIndex[i].meshIndex[1] = bufIndexPtr[i].meshIndex[1];
           triIndex[i].meshIndex[2] = bufIndexPtr[i].meshIndex[2];
           triIndex[i].stIndex[0] = bufIndexPtr[i].meshIndex[0];
           triIndex[i].stIndex[1] = bufIndexPtr[i].meshIndex[1];
           triIndex[i].stIndex[2] = bufIndexPtr[i].meshIndex[2];
     }
 }

 //close file and free memory
 fclose(filePtr);
 free(buffer);

 //initialize the animation variables
 model->currentFrame = 0;
 model->nextFrame = 1;
 model->interpol = 0.0;

 return model;
}

 //The Function to DISPLAY THE MODEL!! IMPORTANT!!!
void DisplayMD2(modelData_t *model, int frameNum)
{
     vector_t *pointList;            //current frame's vertices
     int i;                         //index counter

     //create the pointer to the frame we want to show
     pointList = &model->pointList[model->numPoints * frameNum];

     //display the model as SOLID TRIANGLES!!
     glBegin(GL_TRIANGLES);
             for(i = 0; i < model->numTriangles; i++)
             {
                 glVertex3fv(pointList[model->triIndex[i].meshIndex[0]].point);
                 glVertex3fv(pointList[model->triIndex[i].meshIndex[2]].point);
                 glVertex3fv(pointList[model->triIndex[i].meshIndex[1]].point);
             }
     glEnd;
}


// End MD2 junk



LRESULT CALLBACK 
WndProc( HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam );
VOID EnableOpenGL( HWND hWnd, HDC * hDC, HGLRC * hRC );
VOID DisableOpenGL( HWND hWnd, HDC hDC, HGLRC hRC );

// WinMain

int WINAPI 
WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int iCmdShow )
{
WNDCLASS wc;
HWND hWnd;
HDC hDC;
HGLRC hRC;
MSG msg;
BOOL bQuit = FALSE;
float theta = 0.0f;

// register window class
wc.style = CS_OWNDC;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon( NULL, IDI_APPLICATION );
wc.hCursor = LoadCursor( NULL, IDC_ARROW );
wc.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH );
wc.lpszMenuName = NULL;
wc.lpszClassName = "MainWindow";
RegisterClass( &wc );

// create main window
hWnd = CreateWindow( 
"MainWindow", "MD2 Thing",
WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE,
50, 50, 600, 600,
NULL, NULL, hInstance, NULL );

// enable OpenGL for the window
EnableOpenGL( hWnd, &hDC, &hRC );

// program main loop
while ( !bQuit ) {

// check for messages
if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) {

// handle or dispatch messages
if ( msg.message == WM_QUIT ) {
bQuit = TRUE;
} else {
TranslateMessage( &msg );
DispatchMessage( &msg );
}

} else {

// OpenGL animation code goes here
glTranslatef(0.0f, 0.0f, -10.0f);
modelData_t *Hobgoblin;
Hobgoblin = LoadMD2Model("hobgoblin.md2", "hobgoblin.pcx");
DisplayMD2(Hobgoblin, 0);


}

}

// shutdown OpenGL
DisableOpenGL( hWnd, hDC, hRC );

// destroy the window explicitly
DestroyWindow( hWnd );

return msg.wParam;

}

// Window Procedure

LRESULT CALLBACK 
WndProc( HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam )
{

switch ( message ) {

case WM_CREATE:
return 0;

case WM_CLOSE:
PostQuitMessage( 0 );
return 0;

case WM_DESTROY:
return 0;

case WM_KEYDOWN:
switch ( wParam ) {

case VK_ESCAPE:
PostQuitMessage( 0 );
return 0;

}
return 0;

default:
return DefWindowProc( hWnd, 
message, wParam, lParam );

}

}

// Enable OpenGL

VOID EnableOpenGL( HWND hWnd, HDC * hDC, HGLRC * hRC )
{
PIXELFORMATDESCRIPTOR pfd;
int iFormat;

// get the device context (DC)
*hDC = GetDC( hWnd );

// set the pixel format for the DC
ZeroMemory( &pfd, sizeof( pfd ) );
pfd.nSize = sizeof( pfd );
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | 
PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
iFormat = ChoosePixelFormat( *hDC, &pfd );
SetPixelFormat( *hDC, iFormat, &pfd );

// create and enable the render context (RC)
*hRC = wglCreateContext( *hDC );
wglMakeCurrent( *hDC, *hRC );

}

// Disable OpenGL

VOID DisableOpenGL( HWND hWnd, HDC hDC, HGLRC hRC )
{
wglMakeCurrent( NULL, NULL );
wglDeleteContext( hRC );
ReleaseDC( hWnd, hDC );
} 


I've searched the forums, and found a post about how this code only works with unoptimized MD2 models... well this doesn't work with the old ones either; I checked.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Announcements

  • Forum Statistics

    • Total Topics
      628394
    • Total Posts
      2982427
  • Similar Content

    • By test opty
      Hi all,
       
      I'm starting OpenGL using a tut on the Web. But at this point I would like to know the primitives needed for creating a window using OpenGL. So on Windows and using MS VS 2017, what is the simplest code required to render a window with the title of "First Rectangle", please?
       
       
    • By DejayHextrix
      Hi, New here. 
      I need some help. My fiance and I like to play this mobile game online that goes by real time. Her and I are always working but when we have free time we like to play this game. We don't always got time throughout the day to Queue Buildings, troops, Upgrades....etc.... 
      I was told to look into DLL Injection and OpenGL/DirectX Hooking. Is this true? Is this what I need to learn? 
      How do I read the Android files, or modify the files, or get the in-game tags/variables for the game I want? 
      Any assistance on this would be most appreciated. I been everywhere and seems no one knows or is to lazy to help me out. It would be nice to have assistance for once. I don't know what I need to learn. 
      So links of topics I need to learn within the comment section would be SOOOOO.....Helpful. Anything to just get me started. 
      Thanks, 
      Dejay Hextrix 
    • By mellinoe
      Hi all,
      First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
      Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
      The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
      Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
    • By aejt
      I recently started getting into graphics programming (2nd try, first try was many years ago) and I'm working on a 3d rendering engine which I hope to be able to make a 3D game with sooner or later. I have plenty of C++ experience, but not a lot when it comes to graphics, and while it's definitely going much better this time, I'm having trouble figuring out how assets are usually handled by engines.
      I'm not having trouble with handling the GPU resources, but more so with how the resources should be defined and used in the system (materials, models, etc).
      This is my plan now, I've implemented most of it except for the XML parts and factories and those are the ones I'm not sure of at all:
      I have these classes:
      For GPU resources:
      Geometry: holds and manages everything needed to render a geometry: VAO, VBO, EBO. Texture: holds and manages a texture which is loaded into the GPU. Shader: holds and manages a shader which is loaded into the GPU. For assets relying on GPU resources:
      Material: holds a shader resource, multiple texture resources, as well as uniform settings. Mesh: holds a geometry and a material. Model: holds multiple meshes, possibly in a tree structure to more easily support skinning later on? For handling GPU resources:
      ResourceCache<T>: T can be any resource loaded into the GPU. It owns these resources and only hands out handles to them on request (currently string identifiers are used when requesting handles, but all resources are stored in a vector and each handle only contains resource's index in that vector) Resource<T>: The handles given out from ResourceCache. The handles are reference counted and to get the underlying resource you simply deference like with pointers (*handle).  
      And my plan is to define everything into these XML documents to abstract away files:
      Resources.xml for ref-counted GPU resources (geometry, shaders, textures) Resources are assigned names/ids and resource files, and possibly some attributes (what vertex attributes does this geometry have? what vertex attributes does this shader expect? what uniforms does this shader use? and so on) Are reference counted using ResourceCache<T> Assets.xml for assets using the GPU resources (materials, meshes, models) Assets are not reference counted, but they hold handles to ref-counted resources. References the resources defined in Resources.xml by names/ids. The XMLs are loaded into some structure in memory which is then used for loading the resources/assets using factory classes:
      Factory classes for resources:
      For example, a texture factory could contain the texture definitions from the XML containing data about textures in the game, as well as a cache containing all loaded textures. This means it has mappings from each name/id to a file and when asked to load a texture with a name/id, it can look up its path and use a "BinaryLoader" to either load the file and create the resource directly, or asynchronously load the file's data into a queue which then can be read from later to create the resources synchronously in the GL context. These factories only return handles.
      Factory classes for assets:
      Much like for resources, these classes contain the definitions for the assets they can load. For example, with the definition the MaterialFactory will know which shader, textures and possibly uniform a certain material has, and with the help of TextureFactory and ShaderFactory, it can retrieve handles to the resources it needs (Shader + Textures), setup itself from XML data (uniform values), and return a created instance of requested material. These factories return actual instances, not handles (but the instances contain handles).
       
       
      Is this a good or commonly used approach? Is this going to bite me in the ass later on? Are there other more preferable approaches? Is this outside of the scope of a 3d renderer and should be on the engine side? I'd love to receive and kind of advice or suggestions!
      Thanks!
    • By nedondev
      I 'm learning how to create game by using opengl with c/c++ coding, so here is my fist game. In video description also have game contain in Dropbox. May be I will make it better in future.
      Thanks.
  • Popular Now