Pokaż wiadomości

Ta sekcja pozwala Ci zobaczyć wszystkie wiadomości wysłane przez tego użytkownika. Zwróć uwagę, że możesz widzieć tylko wiadomości wysłane w działach do których masz aktualnie dostęp.


Wiadomości - Jam_Pawian

Strony: 1 [2]
16
Szkółka / Odp: Problem z Direct Input
« dnia: Maj 03, 2009, 23:28:46 »
Dobra, użyłem kodu z Gamedev.pl i sterowanie działa. O tamtych funkcjach zapominam, bo i tak były trochę przekombinowane. Do tego co robię wystarczy jedna prostsza klasa.

Ale dalej mam problem, którego nie rozwiązało zastosowanie Direct Input. Animacja przycina mi kiedy naciskam przycisk na klawiaturze. Jak myślicie, co tu może być nie tak? Może to, że nie mam timerów mieć na to wpływ?

17
Szkółka / Odp: Problem z Direct Input
« dnia: Maj 02, 2009, 12:31:27 »
Wygląda to tak, że w zależności, gdzie umieszczę tę inicjalizację DirectInput, to albo hwnd jest równe 0, albo wszystko się inicjalizuje bez błędów, ale DI nie reaguje na wciskanie klawisza.

Podaję kod WinMaina:


hInstance = GetModuleHandle(NULL);


WNDCLASSEX windowClass; // window class                                 
MSG    msg; // message
bool    done; // flag saying when our app is complete
DWORD    dwExStyle; // Window Extended Style
DWORD    dwStyle; // Window Style
RECT    windowRect;


// temp var's
int width = 800;
int height = 600;
int bits = 32;

//fullScreen = TRUE;

windowRect.left=(long)0; // Set Left Value To 0
windowRect.right=(long)width; // Set Right Value To Requested Width
windowRect.top=(long)0; // Set Top Value To 0
windowRect.bottom=(long)height; // Set Bottom Value To Requested Height

// fill out the window class structure
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = WndProc;
windowClass.cbClsExtra = 0;
windowClass.cbWndExtra = 0;
windowClass.hInstance = hInstance;
windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); // default icon
windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); // default arrow
windowClass.hbrBackground = NULL; // don't need background
windowClass.lpszMenuName = NULL; // no menu
windowClass.lpszClassName = "MyClass";
windowClass.hIconSm = LoadIcon(NULL, IDI_WINLOGO); // windows logo small icon

// register the windows class
if (!RegisterClassEx(&windowClass))
return 0;

if (fullScreen) // fullscreen?
{
DEVMODE dmScreenSettings; // device mode
memset(&dmScreenSettings,0,sizeof(dmScreenSettings));
dmScreenSettings.dmSize = sizeof(dmScreenSettings);
dmScreenSettings.dmPelsWidth = width; // screen width
dmScreenSettings.dmPelsHeight = height; // screen height
dmScreenSettings.dmBitsPerPel = bits; // bits per pixel
dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

//
if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
{
// setting display mode failed, switch to windowed
MessageBox(NULL, "Display mode failed", NULL, MB_OK);
fullScreen=FALSE;
}
}

if (fullScreen) // Are We Still In Fullscreen Mode?
{
dwExStyle=WS_EX_APPWINDOW; // Window Extended Style
dwStyle=WS_POPUP; // Windows Style
ShowCursor(FALSE); // Hide Mouse Pointer
}
else
{
dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style
dwStyle=WS_OVERLAPPEDWINDOW; // Windows Style
}

AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size

// class registered, so now create our window
hwnd = CreateWindowEx(NULL, // extended style
  "MyClass", // class name
  "3D Model Loading Example X: Loading MD2 Files", // app name
  dwStyle | WS_CLIPCHILDREN |
  WS_CLIPSIBLINGS,
  0, 0, // x,y coordinate
  windowRect.right - windowRect.left,
  windowRect.bottom - windowRect.top, // width, height
  NULL, // handle to parent
  NULL, // handle to menu
  hInstance, // application instance
  NULL); // no extra params


// check if window creation failed (hwnd would equal NULL)
if (!hwnd)
return 0;

ShowWindow(hwnd, SW_SHOW); // display the window
UpdateWindow(hwnd); // update the window

// get a device context
if (!(g_hdc = GetDC(hwnd)))
{
MessageBox(NULL,"Unable to create device context", "Error", MB_OK | MB_ICONEXCLAMATION);
return FALSE;
}

hDC = GetDC(hwnd); // get current window's device context
g_HDC = hDC;
SetupPixelFormat(hDC); // call our pixel format setup function

// create rendering context and make it current
hRC = wglCreateContext(hDC);
wglMakeCurrent(hDC, hRC);


//Inicjalizacja g_input
if(hwnd == 0)
MessageBox(NULL, "Dupa, hwnd == 0...", "BLAD!", MB_OK | MB_ICONEXCLAMATION);
if(hInstance == 0)
MessageBox(NULL, "Dupa, hInstance == 0...", "BLAD!", MB_OK | MB_ICONEXCLAMATION);
if(g_input.Initialize(hwnd, hInstance, true, IS_USEKEYBOARD | IS_USEMOUSE)!= false)
MessageBox(NULL, "Dupa, g_input sie nie zainicjalizowalo...", "BLAD!", MB_OK | MB_ICONEXCLAMATION);




done = false; // intialize the loop condition variable
Initialize(); // initialize OpenGL

// main message loop


while (!done)
{
PeekMessage(&msg, hwnd, NULL, NULL, PM_REMOVE);

if (msg.message == WM_QUIT) // do we receive a WM_QUIT message?
{
done = true; // if so, time to quit the application
}
else
{
if (keyPressed[VK_ESCAPE])
done = true;
/**********************************************************************************************************************/
/*STEROWANIE*/
/**********************************************************************************************************************/

else       
{                
if (keyPressed[VK_UP])
{
//myModel->Ustaw_stan_animacji(Bieg);
if(swiat->dresu->kolizja == false)
  swiat->dresu->Ustaw_predkosc(1);

}
else
{
swiat->dresu->Ustaw_predkosc(0);

if (keyPressed[VK_DOWN])
{
myModel->Ustaw_stan_animacji(Bieg);
//swiat->dresu->position.z-=swiat->dresu->Zwroc_predkosc();
}

else if (keyPressed[VK_LEFT])
{
myModel->Ustaw_stan_animacji(Bieg);
swiat->dresu->direction-= 2;
//swiat->dresu->position.x+=swiat->dresu->Zwroc_predkosc();
}
else if (keyPressed[VK_RIGHT])
{
myModel->Ustaw_stan_animacji(Bieg);
swiat->dresu->direction+= 2;
//swiat->dresu->position.x-=swiat->dresu->Zwroc_predkosc();
}

else if (keyPressed[VK_CONTROL])
myModel->Ustaw_stan_animacji(Kucanie);
else if (keyPressed[VK_SHIFT])
myModel->Ustaw_stan_animacji(Skok);
else
myModel->Ustaw_stan_animacji(Bezczynnosc);
}

/**********************************************************************************************************************/
g_input.Update();

if (g_input.KeyDown(DIK_W))
swiat->dresu->Ustaw_predkosc(1);

Render();         //RENDER
/**********************************************************************************************************************/


TranslateMessage(&msg); // translate and dispatch to event queue
DispatchMessage(&msg);
}
}
}

CleanUp();

if (fullScreen)
{
ChangeDisplaySettings(NULL,0); // If So Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}

return msg.wParam;
}

18
Szkółka / Odp: Problem z Direct Input
« dnia: Maj 01, 2009, 14:08:46 »
Znowu potrzebuję pomocy  ;D

Program nie reaguje na wciśnięcie klawisza. Jak już pisałem używam klasy "CInputSystem" z książki "OpenGl Programowanie gier", która obudowuje funkcje Direct Input. Problem będzie pewnie w moim kodzie, bo przykład z książki działa.


Zmienne globalne:
HWND  hwnd = NULL;                 // uchwyt do gl. okna
HINSTANCE  hInstance;              //instancja do WinMain

CInputSystem  g_input; //Obiekt reprezentujący sterowanie


Inicjalizacja DirectInput przed pętlą komunikatów:
g_input.Initialize(hwnd, hInstance, true, IS_USEKEYBOARD | IS_USEMOUSE);


Sprawdzanie naciśniętego klawisza przed funkcją renderującą klatkę animacji:
g_input.Update();

  if (g_input.KeyDown(DIK_W))
   //Tu powinna się wykonać akcja, która się nie wykonuje :)



To tyle, znowu podejrzewam mój głupi błąd, ale używam Direct Draw po raz pierwszy, więc wybaczcie.

19
Szkółka / Odp: Problem z Direct Input
« dnia: Maj 01, 2009, 00:47:01 »
Dzięki wielkie. Widzę, że to jest dość pospolity problem, sorry, że nie poszukałem na forum zanim napisałem posta.

20
Szkółka / Problem z Direct Input
« dnia: Kwiecień 30, 2009, 23:38:28 »
Witam

Chciałem wykorzystać w moim programie klasę "CInputSystem" z książki "OpenGL Programowanie Gier". Kiedy uruchamiam przykład z płyty, wszystko jest ok, ale jak tylko dołączę te pliki do mojego projektu, to wyskakują błędy w stylu: "unresolved external symbol _c_dfDIKeyboard" . Może ktoś ma jakiś pomysł, co jest nie tak? Z góry dzięki.

21
Grafika 3D / Odp: Blender - problem z UV mappingiem
« dnia: Kwiecień 26, 2009, 01:20:29 »
Dzięki wielkie. Automatycznie nie chciał mi odwrócić, ale ręcznie bezproblemowo. Pomyśleć, że kiedyś robiłem cały model od nowa, bo nie wiedziałem, czemu mi nie wyświetla jednej ściany  ;D

22
Grafika 3D / Blender - problem z UV mappingiem
« dnia: Kwiecień 25, 2009, 17:33:42 »
Witam, mam problem z oteksturowaniem modelu. Niby wszystko jest OK, tworzę Seama, potem Unwrapuję, ale kiedy załaduję obrazek, zauważam, że jest kilka miejsc w modelu, które są oteksturowane nie z tej strony, co powinny( teksturę widać tylko od środka). Z góry dziękuję za jakąkolwiek pomoc.

23
OpenGL / Odp: Problem z eksportem tekstury z Blendera do OpenGL
« dnia: Kwiecień 01, 2009, 22:05:26 »
Dobry jesteś stary, zadziałało. Jakbyś mógł jeszcze powiedzieć, co zrobiłeś. Widzę że coś z mipmapami, ale nie wiem co dokładnie. A i sorry, za kopiowanie tej kupy kodu  ;)

24
OpenGL / Odp: Problem z eksportem tekstury z Blendera do OpenGL
« dnia: Kwiecień 01, 2009, 21:06:12 »
texture.h :

#ifndef __TEXTURE_H
#define __TEXTURE_H

#include <stdio.h>
#include <iostream>
#include <windows.h>
#include <commctrl.h>
#include <windowsx.h>
#include <gl/gl.h>

enum texTypes_t
{
PCX,
BMP,
TGA
};

typedef struct
{
// C Compatible version: enum texTypes textureType;
// We use C++ only version
texTypes_t textureType;

int width; // width of texture
int height; // height of texture
float scaledWidth;
float scaledHeight;

unsigned int texID; // the texture object id of this texture
unsigned char *data; // the texture data
unsigned char *palette;
} texture_t;

// only partial pcx file header
typedef struct
{
unsigned char manufacturer;
unsigned char version;
unsigned char encoding;
unsigned char bits;
unsigned char xMin;
unsigned char yMin;
unsigned char xMax;
unsigned char yMax;
unsigned char *palette;
} PCXHEADER;

#endif

md2.h:

#ifndef __MD2_H
#define __MD2_H

#include "texture.h"

#define MAX_FRAMES 512

// a single vertex
typedef struct
{
   float point[3];
} vector_t;

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_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_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;
}

// texture coordinate
typedef struct
{
   float s;
   float t;
} texCoord_t;

// texture coordinate index
typedef struct
{
   short s;
   short t;
} stIndex_t;

// info for a single frame point
typedef struct
{
   unsigned char v[3];
   unsigned char normalIndex; // not used
} framePoint_t;

// information for a single frame
typedef struct
{
   float scale[3];
   float translate[3];
   char name[16];
   framePoint_t fp[1];
} frame_t;

// data for a single triangle
typedef struct
{
   unsigned short meshIndex[3]; // vertex indices
   unsigned short stIndex[3]; // texture coordinate indices
} mesh_t;

// the model data
typedef struct
{
int numFrames; // number of frames
int numPoints; // number of points
int numTriangles; // number of triangles
    int numST; // number of skins
int frameSize; // size of each frame in bytes
int texWidth, texHeight; // texture width, height
int currentFrame; // current frame # in animation
int nextFrame; // next frame # in animation
float interpol; // percent through current frame
mesh_t *triIndex; // triangle list
texCoord_t *st; // texture coordinate list
vector_t *pointList; // vertex list
texture_t *modelTex; // texture data
} modelData_t;

typedef struct
{
   int ident; // identifies as MD2 file "IDP2"
   int version; // mine is 8
   int skinwidth;    // width of texture
   int skinheight;   // height of texture
   int framesize;    // number of bytes per frame
   int numSkins;     // number of textures
   int numXYZ;       // number of points
   int numST;        // number of texture
   int numTris;      // number of triangles
   int numGLcmds;
   int numFrames;    // total number of frames
   int offsetSkins;  // offset to skin names (64 bytes each)
   int offsetST;     // offset of texture s-t values
   int offsetTris;   // offset of triangle mesh
   int offsetFrames; // offset of frame data (points)
   int offsetGLcmds; // type of OpenGL commands to use
   int offsetEnd;    // end of file
} modelHeader_t;

#endif

25
OpenGL / Odp: Problem z eksportem tekstury z Blendera do OpenGL
« dnia: Kwiecień 01, 2009, 21:04:48 »
main.cpp (m.in funkcja Render):

// Render
// desc: handles drawing of scene
void Render()
{
float percent;

radians =  float(PI*(angle-90.0f)/180.0f);

// calculate the camera's position
cameraX = lookX + (float)sin(radians)*mouseY; // multiplying by mouseY makes the
cameraZ = lookZ + (float)cos(radians)*mouseY;  // camera get closer/farther away with mouseY
cameraY = lookY + mouseY / 2.0f;

// calculate the camera look-at coordinates as the center
lookX = 0.0f;
lookY = 2.0f;
lookZ = 0.0f;

percent = 0.005; // interpolation percent

// clear screen and depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();

// set the camera position
gluLookAt(cameraX, cameraY, cameraZ, lookX, lookY, lookZ, 0.0, 1.0, 0.0);

glPushMatrix();
glRotatef(90.0f, -1.0f, 0.0f, 0.0f);
DisplayMD2Interpolate(myModel, 0, 40, percent);
DisplayMD2Interpolate(gunModel, 0, 40, percent);
glColor3f(1.0, 1.0, 1.0);
glPopMatrix();

glFlush();
SwapBuffers(g_HDC); // bring backbuffer to foreground
}

// function to set the pixel format for the device context
void SetupPixelFormat(HDC hDC)
{
int nPixelFormat; // our pixel format index

static PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR), // size of structure
1, // default version
PFD_DRAW_TO_WINDOW | // window drawing support
PFD_SUPPORT_OPENGL | // OpenGL support
PFD_DOUBLEBUFFER, // double buffering support
PFD_TYPE_RGBA, // RGBA color mode
32, // 32 bit color mode
0, 0, 0, 0, 0, 0, // ignore color bits, non-palettized mode
0, // no alpha buffer
0, // ignore shift bit
0, // no accumulation buffer
0, 0, 0, 0, // ignore accumulation bits
16, // 16 bit z-buffer size
0, // no stencil buffer
0, // no auxiliary buffer
PFD_MAIN_PLANE, // main drawing plane
0, // reserved
0, 0, 0 }; // layer masks ignored

nPixelFormat = ChoosePixelFormat(hDC, &pfd); // choose best matching pixel format

SetPixelFormat(hDC, nPixelFormat, &pfd); // set pixel format to device context
}

// the Windows Procedure event handler
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static HGLRC hRC; // rendering context
static HDC hDC; // device context
int width, height; // window width and height
int oldMouseX, oldMouseY;

switch(message)
{
case WM_CREATE: // window is being created

hDC = GetDC(hwnd); // get current window's device context
g_HDC = hDC;
SetupPixelFormat(hDC); // call our pixel format setup function

// create rendering context and make it current
hRC = wglCreateContext(hDC);
wglMakeCurrent(hDC, hRC);

return 0;
break;

case WM_CLOSE: // windows is closing

// deselect rendering context and delete it
wglMakeCurrent(hDC, NULL);
wglDeleteContext(hRC);

// send WM_QUIT to message queue
PostQuitMessage(0);

return 0;
break;

case WM_SIZE:
height = HIWORD(lParam); // retrieve width and height
width = LOWORD(lParam);

if (height==0) // don't want a divide by zero
{
height=1;
}

glViewport(0, 0, width, height); // reset the viewport to new dimensions
glMatrixMode(GL_PROJECTION); // set projection matrix current matrix
glLoadIdentity(); // reset projection matrix

// calculate aspect ratio of window
gluPerspective(54.0f,(GLfloat)width/(GLfloat)height,1.0f,1000.0f);

glMatrixMode(GL_MODELVIEW); // set modelview matrix
glLoadIdentity(); // reset modelview matrix

return 0;
break;

case WM_KEYDOWN: // is a key pressed?
keyPressed[wParam] = true;
return 0;
break;

case WM_KEYUP:
keyPressed[wParam] = false;
return 0;
break;

case WM_MOUSEMOVE:
// save old mouse coordinates
oldMouseX = mouseX;
oldMouseY = mouseY;

// get mouse coordinates from Windows
mouseX = LOWORD(lParam);
mouseY = HIWORD(lParam);

// these lines limit the camera's range
if (mouseY < 60)
mouseY = 60;
if (mouseY > 450)
mouseY = 450;

if ((mouseX - oldMouseX) > 0) // mouse moved to the right
angle += 3.0f;
else if ((mouseX - oldMouseX) < 0) // mouse moved to the left
angle -= 3.0f;

return 0;
break;
default:
break;
}

return (DefWindowProc(hwnd, message, wParam, lParam));
}

// the main windows entry point
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
WNDCLASSEX windowClass; // window class
HWND    hwnd; // window handle
MSG    msg; // message
bool    done; // flag saying when our app is complete
DWORD    dwExStyle; // Window Extended Style
DWORD    dwStyle; // Window Style
RECT    windowRect;

// temp var's
int width = 800;
int height = 600;
int bits = 32;

//fullScreen = TRUE;

windowRect.left=(long)0; // Set Left Value To 0
windowRect.right=(long)width; // Set Right Value To Requested Width
windowRect.top=(long)0; // Set Top Value To 0
windowRect.bottom=(long)height; // Set Bottom Value To Requested Height

// fill out the window class structure
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = WndProc;
windowClass.cbClsExtra = 0;
windowClass.cbWndExtra = 0;
windowClass.hInstance = hInstance;
windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); // default icon
windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); // default arrow
windowClass.hbrBackground = NULL; // don't need background
windowClass.lpszMenuName = NULL; // no menu
windowClass.lpszClassName = "MyClass";
windowClass.hIconSm = LoadIcon(NULL, IDI_WINLOGO); // windows logo small icon

// register the windows class
if (!RegisterClassEx(&windowClass))
return 0;

if (fullScreen) // fullscreen?
{
DEVMODE dmScreenSettings; // device mode
memset(&dmScreenSettings,0,sizeof(dmScreenSettings));
dmScreenSettings.dmSize = sizeof(dmScreenSettings);
dmScreenSettings.dmPelsWidth = width; // screen width
dmScreenSettings.dmPelsHeight = height; // screen height
dmScreenSettings.dmBitsPerPel = bits; // bits per pixel
dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

//
if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
{
// setting display mode failed, switch to windowed
MessageBox(NULL, "Display mode failed", NULL, MB_OK);
fullScreen=FALSE;
}
}

if (fullScreen) // Are We Still In Fullscreen Mode?
{
dwExStyle=WS_EX_APPWINDOW; // Window Extended Style
dwStyle=WS_POPUP; // Windows Style
ShowCursor(FALSE); // Hide Mouse Pointer
}
else
{
dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style
dwStyle=WS_OVERLAPPEDWINDOW; // Windows Style
}

AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size

// class registered, so now create our window
hwnd = CreateWindowEx(NULL, // extended style
  "MyClass", // class name
  "3D Model Loading Example: Loading MD2 Files", // app name
  dwStyle | WS_CLIPCHILDREN |
  WS_CLIPSIBLINGS,
  0, 0, // x,y coordinate
  windowRect.right - windowRect.left,
  windowRect.bottom - windowRect.top, // width, height
  NULL, // handle to parent
  NULL, // handle to menu
  hInstance, // application instance
  NULL); // no extra params

// check if window creation failed (hwnd would equal NULL)
if (!hwnd)
return 0;

ShowWindow(hwnd, SW_SHOW); // display the window
UpdateWindow(hwnd); // update the window

done = false; // intialize the loop condition variable
Initialize(); // initialize OpenGL

// main message loop
while (!done)
{
PeekMessage(&msg, hwnd, NULL, NULL, PM_REMOVE);

if (msg.message == WM_QUIT) // do we receive a WM_QUIT message?
{
done = true; // if so, time to quit the application
}
else
{
if (keyPressed[VK_ESCAPE])
done = true;
else
{
Render();

TranslateMessage(&msg); // translate and dispatch to event queue
DispatchMessage(&msg);
}
}
}

CleanUp();

if (fullScreen)
{
ChangeDisplaySettings(NULL,0); // If So Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}

return msg.wParam;
}


26
OpenGL / Odp: Problem z eksportem tekstury z Blendera do OpenGL
« dnia: Kwiecień 01, 2009, 21:03:50 »
main.cpp ciąg dalszy:

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

model->currentFrame = 0;
model->nextFrame = 1;
model->interpol = 0.0;

    return model;
}

// CalculateNormal()
// desc: given 3 points, calculates the normal to the points
void CalculateNormal( float *p1, float *p2, float *p3 )
{
   float a[3], b[3], result[3];
   float length;

   a[0] = p1[0] - p2[0];
   a[1] = p1[1] - p2[1];
   a[2] = p1[2] - p2[2];

   b[0] = p1[0] - p3[0];
   b[1] = p1[1] - p3[1];
   b[2] = p1[2] - p3[2];

   result[0] = a[1] * b[2] - b[1] * a[2];
   result[1] = b[0] * a[2] - a[0] * b[2];
   result[2] = a[0] * b[1] - b[0] * a[1];

   // calculate the length of the normal
   length = (float)sqrt(result[0]*result[0] + result[1]*result[1] + result[2]*result[2]);

   // normalize and specify the normal
   glNormal3f(result[0]/length, result[1]/length, result[2]/length);
}

// DisplayMD2()
// desc: displays the frameNum frame of an MD2 model
void DisplayMD2(modelData_t *model, int frameNum)
{
vector_t *pointList;
int i;

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

// set the texture
glBindTexture(GL_TEXTURE_2D, model->modelTex->texID);

// display the textured model with proper lighting normals
    glBegin(GL_TRIANGLES);
for(i = 0; i < model->numTriangles; i++)
        {
CalculateNormal(pointList[model->triIndex[i].meshIndex[0]].point,
                             pointList[model->triIndex[i].meshIndex[2]].point,
                             pointList[model->triIndex[i].meshIndex[1]].point);
glTexCoord2f(model->st[model->triIndex[i].stIndex[0]].s,
model->st[model->triIndex[i].stIndex[0]].t);
glVertex3fv(pointList[model->triIndex[i].meshIndex[0]].point);

glTexCoord2f(model->st[model->triIndex[i].stIndex[2]].s ,
     model->st[model->triIndex[i].stIndex[2]].t);
            glVertex3fv(pointList[model->triIndex[i].meshIndex[2]].point);

glTexCoord2f(model->st[model->triIndex[i].stIndex[1]].s,
     model->st[model->triIndex[i].stIndex[1]].t);
            glVertex3fv(pointList[model->triIndex[i].meshIndex[1]].point);
        }
    glEnd();
}

// DisplayMD2Interpolate()
// desc: displays an animated MD2 model with keyframe interpolation
void DisplayMD2Interpolate(modelData_t *model)
{
vector_t *pointList; // current frame vertices
vector_t *nextPointList; // next frame vertices
int i; // index counter
float x1, y1, z1; // current frame point values
float x2, y2, z2; // next frame point values

vector_t vertex[3];

if (model == NULL)
return;

if (model->interpol >= 1.0)
{
model->interpol = 0.0f;
model->currentFrame++;
if (model->currentFrame >= model->numFrames)
model->currentFrame = 0;

model->nextFrame = model->currentFrame + 1;

if (model->nextFrame >= model->numFrames)
model->nextFrame = 0;
}

pointList = &model->pointList[model->numPoints*model->currentFrame];
nextPointList = &model->pointList[model->numPoints*model->nextFrame];

glBindTexture(GL_TEXTURE_2D, model->modelTex->texID);
glBegin(GL_TRIANGLES);
for (i = 0; i < model->numTriangles; i++)
{
// get first points of each frame
x1 = pointList[model->triIndex[i].meshIndex[0]].point[0];
y1 = pointList[model->triIndex[i].meshIndex[0]].point[1];
z1 = pointList[model->triIndex[i].meshIndex[0]].point[2];
x2 = nextPointList[model->triIndex[i].meshIndex[0]].point[0];
y2 = nextPointList[model->triIndex[i].meshIndex[0]].point[1];
z2 = nextPointList[model->triIndex[i].meshIndex[0]].point[2];

// xi + percentage * (xf - xi)
// store first interpolated vertex of triangle
vertex[0].point[0] = x1 + model->interpol * (x2 - x1);
vertex[0].point[1] = y1 + model->interpol * (y2 - y1);
vertex[0].point[2] = z1 + model->interpol * (z2 - z1);

// get second points of each frame
x1 = pointList[model->triIndex[i].meshIndex[2]].point[0];
y1 = pointList[model->triIndex[i].meshIndex[2]].point[1];
z1 = pointList[model->triIndex[i].meshIndex[2]].point[2];
x2 = nextPointList[model->triIndex[i].meshIndex[2]].point[0];
y2 = nextPointList[model->triIndex[i].meshIndex[2]].point[1];
z2 = nextPointList[model->triIndex[i].meshIndex[2]].point[2];

// store second interpolated vertex of triangle
vertex[2].point[0] = x1 + model->interpol * (x2 - x1);
vertex[2].point[1] = y1 + model->interpol * (y2 - y1);
vertex[2].point[2] = z1 + model->interpol * (z2 - z1);

// get third points of each frame
x1 = pointList[model->triIndex[i].meshIndex[1]].point[0];
y1 = pointList[model->triIndex[i].meshIndex[1]].point[1];
z1 = pointList[model->triIndex[i].meshIndex[1]].point[2];
x2 = nextPointList[model->triIndex[i].meshIndex[1]].point[0];
y2 = nextPointList[model->triIndex[i].meshIndex[1]].point[1];
z2 = nextPointList[model->triIndex[i].meshIndex[1]].point[2];

// store third interpolated vertex of triangle
vertex[1].point[0] = x1 + model->interpol * (x2 - x1);
vertex[1].point[1] = y1 + model->interpol * (y2 - y1);
vertex[1].point[2] = z1 + model->interpol * (z2 - z1);

// calculate the normal of the triangle
CalculateNormal(vertex[0].point, vertex[2].point, vertex[1].point);

// render properly textured triangle
glTexCoord2f(model->st[model->triIndex[i].stIndex[0]].s,
model->st[model->triIndex[i].stIndex[0]].t);
glVertex3fv(vertex[0].point);

glTexCoord2f(model->st[model->triIndex[i].stIndex[2]].s ,
     model->st[model->triIndex[i].stIndex[2]].t);
glVertex3fv(vertex[2].point);

glTexCoord2f(model->st[model->triIndex[i].stIndex[1]].s,
     model->st[model->triIndex[i].stIndex[1]].t);
glVertex3fv(vertex[1].point);
}
glEnd();

model->interpol += 0.05f; // increase percentage of interpolation between frames
}

// DisplayMD2Interpolate()
// desc: displays a frame of the model between startFrame and endFrame with an interpolation percent
void DisplayMD2Interpolate(modelData_t *model, int startFrame, int endFrame, float percent)
{
vector_t *pointList; // current frame vertices
vector_t *nextPointList; // next frame vertices
int i; // index counter
float x1, y1, z1; // current frame point values
float x2, y2, z2; // next frame point values

vector_t vertex[3];

if (model == NULL)
return;

if ( (startFrame < 0) || (endFrame < 0) )
return;

if ( (startFrame >= model->numFrames) || (endFrame >= model->numFrames) )
return;

if (model->interpol >= 1.0)
{
model->interpol = 0.0f;
model->currentFrame++;
if (model->currentFrame >= endFrame)//model->numFrames)
model->currentFrame = startFrame; //0;

model->nextFrame = model->currentFrame + 1;

if (model->nextFrame >= endFrame)
model->nextFrame = startFrame;
}

pointList = &model->pointList[model->numPoints*model->currentFrame];
nextPointList = &model->pointList[model->numPoints*model->nextFrame];

glBindTexture(GL_TEXTURE_2D, model->modelTex->texID);
glBegin(GL_TRIANGLES);
for (i = 0; i < model->numTriangles; i++)
{
// get first points of each frame
x1 = pointList[model->triIndex[i].meshIndex[0]].point[0];
y1 = pointList[model->triIndex[i].meshIndex[0]].point[1];
z1 = pointList[model->triIndex[i].meshIndex[0]].point[2];
x2 = nextPointList[model->triIndex[i].meshIndex[0]].point[0];
y2 = nextPointList[model->triIndex[i].meshIndex[0]].point[1];
z2 = nextPointList[model->triIndex[i].meshIndex[0]].point[2];

// store first interpolated vertex of triangle
vertex[0].point[0] = x1 + model->interpol * (x2 - x1);
vertex[0].point[1] = y1 + model->interpol * (y2 - y1);
vertex[0].point[2] = z1 + model->interpol * (z2 - z1);

// get second points of each frame
x1 = pointList[model->triIndex[i].meshIndex[2]].point[0];
y1 = pointList[model->triIndex[i].meshIndex[2]].point[1];
z1 = pointList[model->triIndex[i].meshIndex[2]].point[2];
x2 = nextPointList[model->triIndex[i].meshIndex[2]].point[0];
y2 = nextPointList[model->triIndex[i].meshIndex[2]].point[1];
z2 = nextPointList[model->triIndex[i].meshIndex[2]].point[2];

// store second interpolated vertex of triangle
vertex[2].point[0] = x1 + model->interpol * (x2 - x1);
vertex[2].point[1] = y1 + model->interpol * (y2 - y1);
vertex[2].point[2] = z1 + model->interpol * (z2 - z1);

// get third points of each frame
x1 = pointList[model->triIndex[i].meshIndex[1]].point[0];
y1 = pointList[model->triIndex[i].meshIndex[1]].point[1];
z1 = pointList[model->triIndex[i].meshIndex[1]].point[2];
x2 = nextPointList[model->triIndex[i].meshIndex[1]].point[0];
y2 = nextPointList[model->triIndex[i].meshIndex[1]].point[1];
z2 = nextPointList[model->triIndex[i].meshIndex[1]].point[2];

// store third interpolated vertex of triangle
vertex[1].point[0] = x1 + model->interpol * (x2 - x1);
vertex[1].point[1] = y1 + model->interpol * (y2 - y1);
vertex[1].point[2] = z1 + model->interpol * (z2 - z1);

// calculate the normal of the triangle
CalculateNormal(vertex[0].point, vertex[2].point, vertex[1].point);

// render properly textured triangle
glTexCoord2f(model->st[model->triIndex[i].stIndex[0]].s,
model->st[model->triIndex[i].stIndex[0]].t);
glVertex3fv(vertex[0].point);

glTexCoord2f(model->st[model->triIndex[i].stIndex[2]].s ,
     model->st[model->triIndex[i].stIndex[2]].t);
glVertex3fv(vertex[2].point);

glTexCoord2f(model->st[model->triIndex[i].stIndex[1]].s,
     model->st[model->triIndex[i].stIndex[1]].t);
glVertex3fv(vertex[1].point);
}
glEnd();

model->interpol += percent; // increase percentage of interpolation between frames
}

void CleanUp()
{
FreeModel(gunModel2);
FreeModel(myModel2);
FreeModel(gunModel);
FreeModel(myModel);
}

// Initialize
// desc: initializes OpenGL
void Initialize()
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // clear to black

glShadeModel(GL_SMOOTH); // use smooth shading
glEnable(GL_DEPTH_TEST); // hidden surface removal
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
glEnable(GL_LIGHTING); // setup cheap-o lighting
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);

glEnable(GL_TEXTURE_2D);

// load model and model texture
myModel = LoadMD2Model("models\\ogro\\mojmodel.md2", "models\\ogro\\tekstura.pcx");
gunModel = LoadMD2Model("models\\ogro\\weapon.md2", "models\\ogro\\weapon.pcx");
myModel2 = LoadMD2Model("models\\sodf8\\tris.md2", "models\\sodf8\\abarlith.pcx");
gunModel2 = LoadMD2Model("models\\sodf8\\weapon.md2", "models\\sodf8\\weapon.pcx");
}


27
OpenGL / Odp: Problem z eksportem tekstury z Blendera do OpenGL
« dnia: Kwiecień 01, 2009, 21:01:30 »
main.cpp ciąg dalszy:

// LoadPCXTexture()
// desc: loads a PCX image file as a texture
texture_t *LoadPCXTexture(char *filename)
{
PCXHEADER texInfo; // header of texture
texture_t *thisTexture; // the texture
unsigned char *unscaledData;// used to calculate pcx
int i; // index counter
int j; // index counter
int width; // width of texture
int height; // height of texture

// allocate memory for texture struct
thisTexture = (texture_t*)malloc(sizeof(texture_t));
if (thisTexture == NULL)
return NULL;

// load the PCX file into the texture struct
thisTexture->data = LoadPCXFile(filename, &texInfo);
if (thisTexture->data == NULL)
{
free(thisTexture->data);
return NULL;
}

// store the texture information
thisTexture->palette = texInfo.palette;
thisTexture->width = texInfo.xMax - texInfo.xMin + 1;
thisTexture->height = texInfo.yMax - texInfo.yMin + 1;
thisTexture->textureType = PCX;

// allocate memory for the unscaled data
unscaledData = (unsigned char*)malloc(thisTexture->width*thisTexture->height*4);

// store the unscaled data via the palette
for (j = 0; j < thisTexture->height; j++)
{
for (i = 0; i < thisTexture->width; i++)
{
unscaledData[4*(j*thisTexture->width+i)+0] = (unsigned char)thisTexture->palette[3*thisTexture->data[j*thisTexture->width+i]+0];
unscaledData[4*(j*thisTexture->width+i)+1] = (unsigned char)thisTexture->palette[3*thisTexture->data[j*thisTexture->width+i]+1];
unscaledData[4*(j*thisTexture->width+i)+2] = (unsigned char)thisTexture->palette[3*thisTexture->data[j*thisTexture->width+i]+2];
unscaledData[4*(j*thisTexture->width+i)+3] = (unsigned char)255;
}
}

// find width and height's nearest greater power of 2
width = thisTexture->width;
height = thisTexture->height;

// find width's
i = 0;
while (width)
{
width /= 2;
i++;
}
thisTexture->scaledHeight = (long)pow(2.0, i-1);

// find height's
i = 0;
while (height)
{
height /= 2;
i++;
}
thisTexture->scaledWidth = (long)pow(2.0, i-1);

// clear the texture data
if (thisTexture->data != NULL)
{
free(thisTexture->data);
thisTexture->data = NULL;
}

// reallocate memory for the texture data
thisTexture->data = (unsigned char*)malloc(thisTexture->scaledWidth*thisTexture->scaledHeight*4);

// use the GL utility library to scale the texture to the unscaled dimensions
gluScaleImage (GL_RGBA, thisTexture->width, thisTexture->height, GL_UNSIGNED_BYTE, unscaledData, thisTexture->scaledWidth, thisTexture->scaledHeight, GL_UNSIGNED_BYTE, thisTexture->data);

return thisTexture;
}

// LoadBMPTexture()
// desc: loads a texture of the BMP format
texture_t *LoadBMPTexture(char *filename)
{
BITMAPINFOHEADER texInfo; // BMP header
texture_t *thisTexture; // the texture

// allocate memory for the texture
thisTexture = (texture_t*)malloc(sizeof(texture_t));
if (thisTexture == NULL)
return NULL;

// store BMP data in texture
thisTexture->data = LoadBitmapFile(filename, &texInfo);
if (thisTexture->data == NULL)
{
free(thisTexture);
return NULL;
}

// store texture information
thisTexture->width = texInfo.biWidth;
thisTexture->height = texInfo.biHeight;
thisTexture->palette = NULL;
thisTexture->scaledHeight = 0;
thisTexture->scaledWidth = 0;
thisTexture->textureType = BMP;

return thisTexture;
}

// LoadTexture()
// desc: loads a texture given the filename
texture_t *LoadTexture(char *filename)
{
texture_t *thisTexture;
char *extStr;

// get extension from filename
extStr = strchr(filename, '.');
extStr++;

// set the texture type based on extension of filename
if ((strcmp(extStr, "BMP") == 0) || (strcmp(extStr, "bmp") == 0))
thisTexture = LoadBMPTexture(filename);
else if ((strcmp(extStr, "PCX") == 0) || (strcmp(extStr, "pcx") == 0) )
thisTexture = LoadPCXTexture(filename);
/*
else if ((strcmp(extStr, "TGA") == 0) || (strcmp(extStr, "tga") == 0) )
thisTexture = LoadTGATexture(filename);
//texType = TGA;
*/
return thisTexture;
}

// SetupMD2Texture()
// desc: sets up a texture for use with an MD2 model
void SetupMD2Texture(texture_t *thisTexture)
{
// set the proper parameters for an MD2 texture
glGenTextures(1, &thisTexture->texID);
glBindTexture(GL_TEXTURE_2D, thisTexture->texID);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

switch (thisTexture->textureType)
{
case BMP:
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, thisTexture->width, thisTexture->height,
  GL_RGB, GL_UNSIGNED_BYTE, thisTexture->data);
break;
case PCX:
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, thisTexture->width, thisTexture->height,
  GL_RGBA, GL_UNSIGNED_BYTE, thisTexture->data);
case TGA:
break;
default:
break;
}
}

// LoadMD2Model()
// desc: loads an MD2 model specified by filename and with the texture
// specified by textureName
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 data
    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 used in model, including animations
    model->pointList = (vector_t*)malloc(sizeof(vector_t)*modelHeader->numXYZ * modelHeader->numFrames);

// store vital model data
    model->numPoints = modelHeader->numXYZ;
    model->numFrames = modelHeader->numFrames;
model->frameSize = modelHeader->framesize;

    // loop number of frames in model file
    for(j = 0; j < modelHeader->numFrames; j++)
    {
       // offset to the 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)
{
// setup texture for opengl and store it in model data structure
SetupMD2Texture(md2Texture);
model->modelTex = md2Texture;
}
else
return NULL;

    // allocate 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
    stPtr = (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;
    }

// allocate an index of triangles
triIndex = (mesh_t*)malloc(sizeof(mesh_t) * modelHeader->numTris);

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

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

// create a mesh (triangle) list
for (j = 0; j < model->numFrames; j++)
{
// for all triangles in each frame
for(i = 0; i < modelHeader->numTris; i++)
{
   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].stIndex[0];
   triIndex[i].stIndex[1] = bufIndexPtr[i].stIndex[1];
   triIndex[i].stIndex[2] = bufIndexPtr[i].stIndex[2];
}
}

28
OpenGL / Odp: Problem z eksportem tekstury z Blendera do OpenGL
« dnia: Kwiecień 01, 2009, 21:00:07 »
main.cpp :

#define WIN32_LEAN_AND_MEAN // trim the excess fat from Windows

/*******************************************************************
* Program: Chapter 18 - Loading an MD2 Model
* Author: Kevin Hawkins
* Description: This example loads, displays, and animates two .MD2 models.
********************************************************************/

////// Defines
#define BITMAP_ID 0x4D42 // the universal bitmap ID
#define PI 3.14159

////// Includes
#include <windows.h> // standard Windows app include
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gl/gl.h> // standard OpenGL include
#include <gl/glu.h> // OpenGL utilties
#include "texture.h"
#include "md2.h"
//#include "HiResTimer.h"

////// Global Variables
HDC g_HDC; // global device context
bool fullScreen = false; // true = fullscreen; false = windowed
bool keyPressed[256]; // holds true for keys that are pressed

float angle = 0.0f; // camera angle
float radians = 0.0f; // camera angle in radians

////// Mouse/Camera Variables
int mouseX, mouseY; // mouse coordinates
float cameraX, cameraY, cameraZ; // camera coordinates
float lookX, lookY, lookZ; // camera look-at coordinates

modelData_t *myModel;
modelData_t *gunModel;
modelData_t *myModel2;
modelData_t *gunModel2;
modelData_t *myModel3;
modelData_t *gunModel3;

float interValue = 0.0f; // percentage to calculate for
// interpolation from current frame
// to next frame.

void FreeModel(modelData_t *model)
{
if (model->triIndex != NULL)
free(model->triIndex);
if (model->pointList != NULL)
free(model->pointList);
if (model->st != NULL)
free(model->st);
if (model != NULL)
free(model);
}

// LoadBitmapFile
// desc: Returns a pointer to the bitmap image of the bitmap specified
//       by filename. Also returns the bitmap header information.
// No support for 8-bit bitmaps.
unsigned char *LoadBitmapFile(char *filename, BITMAPINFOHEADER *bitmapInfoHeader)
{
FILE *filePtr; // the file pointer
BITMAPFILEHEADER bitmapFileHeader; // bitmap file header
unsigned char *bitmapImage; // bitmap image data
unsigned int imageIdx = 0; // image index counter
unsigned char tempRGB; // swap variable

// open filename in "read binary" mode
filePtr = fopen(filename, "rb");
if (filePtr == NULL)
return NULL;

// read the bitmap file header
fread(&bitmapFileHeader, sizeof(BITMAPFILEHEADER), 1, filePtr);

// verify that this is a bitmap by checking for the universal bitmap id
if (bitmapFileHeader.bfType != BITMAP_ID)
{
fclose(filePtr);
return NULL;
}

// read the bitmap information header
fread(bitmapInfoHeader, sizeof(BITMAPINFOHEADER), 1, filePtr);

// move file pointer to beginning of bitmap data
fseek(filePtr, bitmapFileHeader.bfOffBits, SEEK_SET);

// allocate enough memory for the bitmap image data
bitmapImage = (unsigned char*)malloc(bitmapInfoHeader->biSizeImage);

// verify memory allocation
if (!bitmapImage)
{
free(bitmapImage);
fclose(filePtr);
return NULL;
}

// read in the bitmap image data
fread(bitmapImage, 1, bitmapInfoHeader->biSizeImage, filePtr);

// make sure bitmap image data was read
if (bitmapImage == NULL)
{
fclose(filePtr);
return NULL;
}

// swap the R and B values to get RGB since the bitmap color format is in BGR
for (imageIdx = 0; imageIdx < bitmapInfoHeader->biSizeImage; imageIdx+=3)
{
tempRGB = bitmapImage[imageIdx];
bitmapImage[imageIdx] = bitmapImage[imageIdx + 2];
bitmapImage[imageIdx + 2] = tempRGB;
}

// close the file and return the bitmap image data
fclose(filePtr);
return bitmapImage;
}

// LoadPCXFile()
// desc: loads a PCX file into memory
unsigned char *LoadPCXFile(char *filename, PCXHEADER *pcxHeader)
{
int idx = 0; // counter index
int c; // used to retrieve a char from the file
int i; // counter index
int numRepeat;
FILE *filePtr; // file handle
int width; // pcx width
int height; // pcx height
unsigned char *pixelData; // pcx image data
unsigned char *paletteData; // pcx palette data

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

// retrieve first character; should be equal to 10
c = getc(filePtr);
if (c != 10)
{
fclose(filePtr);
return NULL;
}

// retrieve next character; should be equal to 5
c = getc(filePtr);
if (c != 5)
{
fclose(filePtr);
return NULL;
}

// reposition file pointer to beginning of file
rewind(filePtr);

// read 4 characters of data to skip
fgetc(filePtr);
fgetc(filePtr);
fgetc(filePtr);
fgetc(filePtr);

// retrieve leftmost x value of PCX
pcxHeader->xMin = fgetc(filePtr); // loword
pcxHeader->xMin |= fgetc(filePtr) << 8; // hiword

// retrieve bottom-most y value of PCX
pcxHeader->yMin = fgetc(filePtr); // loword
pcxHeader->yMin |= fgetc(filePtr) << 8; // hiword

// retrieve rightmost x value of PCX
pcxHeader->xMax = fgetc(filePtr); // loword
pcxHeader->xMax |= fgetc(filePtr) << 8; // hiword

// retrieve topmost y value of PCX
pcxHeader->yMax = fgetc(filePtr); // loword
pcxHeader->yMax |= fgetc(filePtr) << 8; // hiword

// calculate the width and height of the PCX
width = pcxHeader->xMax - pcxHeader->xMin + 1;
height = pcxHeader->yMax - pcxHeader->yMin + 1;

// allocate memory for PCX image data
pixelData = (unsigned char*)malloc(width*height);

// set file pointer to 128th byte of file, where the PCX image data starts
fseek(filePtr, 128, SEEK_SET);

// decode the pixel data and store
while (idx < (width*height))
{
c = getc(filePtr);
if (c > 0xbf)
{
numRepeat = 0x3f & c;
c = getc(filePtr);

for (i = 0; i < numRepeat; i++)
{
pixelData[idx++] = c;
}
}
else
pixelData[idx++] = c;

fflush(stdout);
}

// allocate memory for the PCX image palette
paletteData = (unsigned char*)malloc(768);

// palette is the last 769 bytes of the PCX file
fseek(filePtr, -769, SEEK_END);

// verify palette; first character should be 12
c = getc(filePtr);
if (c != 12)
{
fclose(filePtr);
return NULL;
}

// read and store all of palette
for (i = 0; i < 768; i++)
{
c = getc(filePtr);
paletteData[i] = c;
}

// close file and store palette in header
fclose(filePtr);
pcxHeader->palette = paletteData;

// return the pixel image data
return pixelData;
}

29
OpenGL / Problem z eksportem tekstury z Blendera do OpenGL
« dnia: Kwiecień 01, 2009, 14:50:24 »
Jak w temacie. Zrobiłem unwrapping sześcianu i dałem prostą teksturkę, wyeksportowałem do md2, po zaimportowaniu z powrotem do Blendera wszystko było ok. Kiedy jednak chcę to wyświetlić w OpenGL, pojawiają się problemy... Kiedy wyświetlam sam model bez tekstury wszystko gra, kiedy chcę wyświetlić oteksturowany, wyświetla biały sześcian.
Przerabiam kod z książki 'Programowanie gier w OpenGL': http://glbook.gamedev.net/source.asp  (chapter 18). Nie jest to chyba wina tekstury, bo jak chcę wyświetlić tą załączoną z przykładem to też nie teksturuje sześcianu.

Proszę o pomoc i z góry dzięki

Strony: 1 [2]