PDA

View Full Version : [C++ e OpenGL]


s0nnyd3marco
14-12-2008, 17:22
Salve a tutti, premetto che sono nuovo di OpenGl. Ho incontrato un problema mentre stavo cercando di caricare una texture seguendo i tutorial del sito NeHe: i tutorial fanno uso di glaux.h che non è più presnte nel SDK di Vista e in Visual Studio 2k8. Sempre sul sito è presente una nota che spiega che si possono riscrivere i tutorial utilizzando la seguente sostituzione :

/************************************************************************
REPLACEMENT FOR GLAUX
************************************************************************
This is not a full blown bitmap loader. It is a quick and easy
way to replace the glAux dependant code in my older tutorials
with code that does not depend on the glAux library!

This code only loads Truecolor Bitmap Images. It will not load
8-bit bitmaps. If you encounter a bitmap that will not load
use a program such as Irfanview to convert the bitmap to 24 bits.
************************************************************************/

bool NeHeLoadBitmap(LPTSTR szFileName, GLuint &texid) // Creates Texture From A Bitmap File
{
HBITMAP hBMP; // Handle Of The Bitmap
BITMAP BMP; // Bitmap Structure

glGenTextures(1, &texid); // Create The Texture
hBMP=(HBITMAP)LoadImage(GetModuleHandle(NULL), szFileName, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_LOADFROMFILE );

if (!hBMP) // Does The Bitmap Exist?
return FALSE; // If Not Return False

GetObject(hBMP, sizeof(BMP), &BMP); // Get The Object
// hBMP: Handle To Graphics Object
// sizeof(BMP): Size Of Buffer For Object Information
// &BMP: Buffer For Object Information

glPixelStorei(GL_UNPACK_ALIGNMENT, 4); // Pixel Storage Mode (Word Alignment / 4 Bytes)

// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_2D, texid); // Bind To The Texture ID
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Linear Min Filter
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Linear Mag Filter
glTexImage2D(GL_TEXTURE_2D, 0, 3, BMP.bmWidth, BMP.bmHeight, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, BMP.bmBits);

DeleteObject(hBMP); // Delete The Object

return TRUE; // Loading Was Successful
}

BOOL Initialize (GL_Window* window, Keys* keys) // Any GL Init Code & User Initialiazation Goes Here
{
g_window = window;
g_keys = keys;

// Start Of User Initialization
if (!NeHeLoadBitmap("Data/NeHe.bmp", texture[0])) // Load The Bitmap
return FALSE; // Return False If Loading Failed



ma mentre modifico ilo codice mi da il seguente errore:
cannot convert parameter 1 from 'const char [19]' to 'LPTSTR'

Se avete idee per modificare questo codice o suggerirmi altri modi per utilizzare le texture in opengl sono aperto a qualunque suggerimento.

fero86
14-12-2008, 18:57
ma mentre modifico ilo codice mi da il seguente errore:
cannot convert parameter 1 from 'const char [19]' to 'LPTSTR' questo probabilmente perché stai tentando di passare al primo parametro della funzione un array di char, mentre lui vuole un array di wchar_t, o meglio di TCHAR, che in Visual C++ 2008 diventa di default wchar_t essendo definita la macro UNICODE; in parole semplici stai passando una stringa ASCII dove é richiesta una stringa Unicode.
hai due possibilitá:
1) rimuovi la definizione della macro UNICODE e continua cosi a lavorare su un programma interamente ANSI; la macro UNICODE non é definita nei tuoi sorgenti ma viene definita dall'IDE nella command line del compilatore, quindi devi rimuoverla dalle opzioni del progetto (non ricordo dove).
2) usa la macro _T (definita in tchar.h, includilo esplicitamente se non riesce a vederla) che serve per convertire automaticamente i char in TCHAR. esempio:
NeHeLoadBitmap(_T("Texture.bmp"), ...);

ti consiglio la seconda per due motivi: il primo é che con il supporto Unicode faciliti l'eventuale internazionalizzazione del tuo programma (i caratteri giapponesi non ci stanno nel set ASCII, ci avevi mai pensato? :p) e quindi é comunque una buona pratica di programmazione, e la seconda é che in Windows i programmi Unicode sono piu veloci.

s0nnyd3marco
15-12-2008, 09:16
Grazie per la risposta. Volevo chiederti se per caso sai se questo è il modo corretto per caricare le texture o è meglio ricorrere alla glaux.h (modo vecchio ma presente ancora in quasi tutti i tutorial)

PS: in effetti ora che posso utilizzare i caratteri giapponesi mi si è aperto un nuovo mondo :sofico:

fero86
15-12-2008, 13:04
Grazie per la risposta. Volevo chiederti se per caso sai se questo è il modo corretto per caricare le texture o è meglio ricorrere alla glaux.h (modo vecchio ma presente ancora in quasi tutti i tutorial) il problema non si pone visto che GLaux non c'é piu, e non manca solo l'header, manca proprio la DLL in Windows. come spiegato da NeHe, non la ritengo una gran perdita visto che praticamente serviva soltanto a caricare le textures.

se invece ci fosse ancora penso che io effettivamente la utilizzerei perchéguadagnerei in portabilitá, ma ancora non é una gran perdita perché il formato BMP é di una semplicitá disarmante (non c'era neanche bisogno di usare le API) e per tutti gli altri formati in genere esistono librerie portabili, come la libpng.


PS: in effetti ora che posso utilizzare i caratteri giapponesi mi si è aperto un nuovo mondo :sofico: dicevo giapponesi per dire :D
nel set ASCII ci stanno solo le lettere dell'alfabeto inglese minuscole, maiuscole e con tutti i tipi di accentature, piu i numeri, le punteggiature e qualche disegno idiota; mancano i caratteri alfabetici di numerose popolazioni della terra: cinesi, giapponesi, ebraici, arabi, cirillici ...
su Wikipedia viene spiegato come funzionano i vari standard Unicode e viene fornita una bella mappa di come sono stati allocati finora i caratteri.

s0nnyd3marco
15-12-2008, 15:02
Appena ritono a casa faccio un test con la nuova procedura di nehe.
Conosci per caso altri siti validi di tutorial su OpenGL magari con qualcosa di più aggiornato?

s0nnyd3marco
16-12-2008, 23:27
Mi autorispondo con la soluzione sperando che sia utile ai posteri:
http://www.gamedev.net/community/forums/topic.asp?topic_id=275238

bmp.cpp

//--------------------------------------------------------------
#include <windows.h> // Header File For Windows - has structures for BMP format
#include <stdio.h> // Header File For Standard Input/Output
#include <stdlib.h>
#include "BMP.h"

/*------------------------------------------------------------------
BMP Loader - a quick and dirty substitute for GLaux
if you only use GLaux to load BMP files will load any format of a
windows DIB BMP format graphics file Only works on a windows box
Caution! memory for the data is allocated using 'new'.
In the NeHe tutorials the memory is reclaimed using 'free'.
For the small tutorials its not a big deal but not a good practice in
larger projects (heap trashing not good). J.M. Doyle : 12 Jan 2003
------------------------------------------------------------------*/

AUX_RGBImageRec *auxDIBImageLoad(const char *FileName)
{
return new AUX_RGBImageRec(FileName);
}


void AUX_RGBImageRec::convertBGRtoRGB()
{
const DWORD BitmapLength = sizeX * sizeY * 3;
byte Temp; // not quick but it works
for(DWORD i=0; i< BitmapLength; i += 3)
{
Temp = data[i];
data[i] = data[i+2];
data[i+2] = Temp;
}
}

AUX_RGBImageRec::AUX_RGBImageRec(const char *FileName): data(NULL), NoErrors(false)
{
loadFile(FileName);
}

AUX_RGBImageRec::~AUX_RGBImageRec()
{
if (data != NULL) delete data;
data = NULL;
}

bool AUX_RGBImageRec::loadFile(const char* Filename)
{
BITMAPINFO BMInfo; // need the current OpenGL device contexts in order to make use of windows DIB utilities
const HDC gldc = wglGetCurrentDC(); // a handle for the current OpenGL Device Contexts
// assume there are errors until file is loaded successfully into memory
NoErrors = false; // release old data since this object could be used to load multiple Textures
if(data != NULL) delete data; // windows needs this info to determine what header info we are looking for
BMInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); // Get windows to determine color bit depth in the file for us
BMInfo.bmiHeader.biBitCount = 0; // Get windows to open and load the BMP file and handle the messy decompression if the file is compressed
// assume perfect world and no errors in reading file, Ha Ha
HANDLE DIBHandle = LoadImage(0,Filename, IMAGE_BITMAP, 0, 0,LR_DEFAULTCOLOR | LR_CREATEDIBSECTION | LR_LOADFROMFILE); // use windows to get header info of bitmap - assume no errors in header format

GetDIBits(gldc, (HBITMAP)DIBHandle, 0,0, NULL, &BMInfo, DIB_RGB_COLORS);
sizeX = BMInfo.bmiHeader.biWidth;
sizeY = BMInfo.bmiHeader.biHeight; // change color depth to 24 bits (3 bytes (BGR) / pixel)
BMInfo.bmiHeader.biBitCount = 24; // don't want the data compressed
BMInfo.bmiHeader.biCompression = BI_RGB;
const DWORD BitmapLength = sizeX * sizeY * 3; // 3 bytes (BGR) per pixel (24bp)
// allocate enough memory to hold the pixel data in client memory
data = new byte[BitmapLength]; // Get windows to do the dirty work of converting the BMP into the format needed by OpenGL
// if file is already 24 bit color then this is a waste of time but makes for short code
// Get the actual Texel data from the BMP object

if (GetDIBits(gldc, (HBITMAP)DIBHandle, 0, sizeY, data, &BMInfo, DIB_RGB_COLORS))
{
NoErrors = true;
convertBGRtoRGB(); // NOTE: BMP is in BGR format but OpenGL needs RGB unless you use GL_BGR_EXT
}

DeleteObject(DIBHandle); // don't need the BMP Object anymore
return NoErrors;
}



bmp.h

//------------------------------------------------------------------------

class AUX_RGBImageRec {
void convertBGRtoRGB();
public:
byte *data;
DWORD sizeX;
DWORD sizeY;
bool NoErrors;
AUX_RGBImageRec(): NoErrors(false), data(NULL) {};
AUX_RGBImageRec(const char *FileName);
~AUX_RGBImageRec();
bool loadFile(const char *FileName);
friend AUX_RGBImageRec *auxDIBImageLoad(const char *FileName);
};



istruzioni

maybe you need step by step instructions.

1. take the bmp.cpp and bmp.h files and copy them to the same directory as lesson7.cpp(in your case it's probobly OpenGL7.cpp instead of lesson7.cpp).

2. open up the project in vc++ 6.0 (other versions should work to)

3. under file view find the "source files" folder, right click on it an select add files to folder, choose "bmp.cpp".

4. do the same for the "header files" folder but choose "bmp.h".

5. in "lesson7.cpp" change the folowing line
#include <gl/glaux.h> // Header File For The Glaux Library
to
#include "bmp.h" // Header File For The Glaux replacement Library

6. compile, run and be happy.