Sign in to follow this  
LordAsm

OpenGL Problem with terrain

Recommended Posts

LordAsm    144
Hi ppl, I'm starting here with OpenGL, so I think it'll be a noobish question, but here it is I'm loading a heighmap I've hardcoded into my code, just for testing purposes, but as I move my camera (at least my 3rd person camera attempt lol ) my terrain displays it wrongly... I've made it based in NeHe's basecode (as you can see for the Fullscreen option), I think it must be something with z depth or normals. The link to the executable is: (arrow keys move forward/backward and mouse rotates view) www.serverbrasil.org/~lordasm/test.zip My drawing code is:
	glBegin(GL_QUADS);
	glColor3f(1.0f,1.0f,1.0f);		
	for (int y=1;y<=21;y++){
		for (int x=1;x<=21;x++){
			z1 = Height(x, y )*20;
			z2 = Height(x-1, y )*20;
			z3 = Height(x, y-1 )*20;
			z4 = Height(x-1, y-1 )*20;
			v1.x = (x*64);
			v1.y = (y*64);
			v1.z = z1;

		    glTexCoord2f(0.0f, 0.0f); glVertex3i((x*64)-64,   (y*64),z2);	
			glTexCoord2f(1.0f, 0.0f); glVertex3i(   (x*64),   (y*64),z1);	
			glTexCoord2f(1.0f, 1.0f); glVertex3i(   (x*64),(y*64)-64,z3);	
			glTexCoord2f(0.0f, 1.0f); glVertex3i((x*64)-64,(y*64)-64,z4);	
		}
	}





I'm using Depthtest TRUE with GL_LEQUAL Please, anyone knows what I'm doing wrong? If so, what I can do to solve this? Ty! -Roger- [Edited by - LordAsm on March 14, 2006 9:07:24 AM]

Share this post


Link to post
Share on other sites
Kaezin    158
You said you think it may have to do with the normals, but you're not dealing with the normals at all in there, so I'm assuming there's no lighting either. I don't see anything wrong with the code you posted (there could be, I just don't see it) so I'm going to guess that the problem is somewhere else in the code. I'm don't know where though without seeing more of the code.

Share this post


Link to post
Share on other sites
LordAsm    144
Sorry, I'm posting all the code here now, so you can see...

Yes, I'm not using normals, and that's why I thought it would be a normal problem, perhaps the lack of them are making some faces to appear wrongly. But I doubt so now lol.

The entire code is (w/o the camera class code) (It is my testing code, it sucks lol):



#include <windows.h>
#include <stdio.h>
#include <gl\gl.h>
#include <gl\glu.h>
#include <gl\glaux.h>
#include "matrix.h"
#include "vector.h"
#include <math.h>

#define MAP_SIZE 21
#define STEP_SIZE 64
#define HEIGHT_RATIO 0.5f

HDC hDC=NULL; // Private GDI Device Context
HGLRC hRC=NULL; // Permanent Rendering Context
HWND hWnd=NULL; // Holds Our Window Handle
HINSTANCE hInstance; // Holds The Instance Of The Application

bool keys[256];
bool mouse;
bool active=TRUE; // Window Active Flag Set To TRUE By Default
bool fullscreen=TRUE;

float depth = 0.0f;
float hdepth = 0.0f;
float zdepth = 0.0f;
float rot = 0.0f;
float rotation = 0.0f;
float rad = 0.0f;
float movefactor = 5.0f;
float old_mouse_x, old_mouse_y;
float mouse_x, mouse_y;
int z1,z2,z3,z4;

int g_nFPS = 0, g_nFrames = 0;
DWORD g_dwLastFPS = 0;

matrix4 view;
matrix4 view2;
vector eye;
vector center;
vector vis;
vector v1;
vector v2;
vector norm;

matrix4 rotmat;
float s[16];
float r;

GLuint texture[1]; // Storage For One Texture
int heightmap [22][22] = { // My Heightmap
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,1,1,2,2,2,2,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0},
{0,1,2,2,2,2,2,2,1,1,1,0,0,0,0,1,2,2,1,0,0,0},
{1,1,2,3,3,3,3,2,1,1,1,0,0,0,0,0,1,1,0,0,0,0},
{1,1,2,3,4,4,4,3,2,1,1,1,0,0,0,0,0,0,0,0,0,0},
{1,1,1,3,4,5,4,3,2,2,1,1,0,0,0,0,0,0,0,0,0,0},
{0,1,1,2,4,4,4,3,2,1,1,1,0,0,0,0,0,0,0,0,0,0},
{0,0,1,1,1,2,2,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,1,1,2,2,2,2,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0},
{0,1,2,2,2,2,2,2,1,1,1,0,0,0,0,1,2,2,1,0,0,0},
{1,1,2,3,3,3,3,2,1,1,1,0,0,0,0,0,1,1,0,0,0,0},
{1,1,2,3,4,4,4,3,2,1,1,1,0,0,0,0,0,0,0,0,0,0},
{1,1,1,3,4,5,4,3,2,2,1,1,0,0,0,0,0,0,0,0,0,0},
{0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,1,1,2,2,2,2,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0},
{0,1,2,2,2,2,2,2,1,1,1,0,0,0,0,1,2,2,1,0,0,0},
{1,1,2,3,3,3,3,2,1,1,1,0,0,0,0,0,1,1,0,0,0,0},
{1,1,2,3,4,4,4,3,2,1,1,1,0,0,0,0,0,0,0,0,0,1},
};

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

AUX_RGBImageRec *LoadBMP(char *Filename)
{
FILE *File=NULL; // File Handle

if (!Filename) // Make Sure A Filename Was Given
{
return NULL; // If Not Return NULL
}

File=fopen(Filename,"r"); // Check To See If The File Exists

if (File) // Does The File Exist?
{
fclose(File); // Close The Handle
return auxDIBImageLoad(Filename); // Load The Bitmap And Return A Pointer
}

return NULL; // If Load Failed Return NULL
}


int LoadGLTextures() // Load Bitmaps And Convert To Textures
{
int Status=FALSE; // Status Indicator

AUX_RGBImageRec *TextureImage[1]; // Create Storage Space For The Texture

memset(TextureImage,0,sizeof(void *)*1); // Set The Pointer To NULL

// Load The Bitmap, Check For Errors, If Bitmap's Not Found Quit
if (TextureImage[0]=LoadBMP("grass.bmp"))
{
Status=TRUE; // Set The Status To TRUE

glGenTextures(1, &texture[0]); // Create The Texture

// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_2D, texture[0]);
glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[0]->sizeX, TextureImage[0]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
}

if (TextureImage[0]) // If Texture Exists
{
if (TextureImage[0]->data) // If Texture Image Exists
{
free(TextureImage[0]->data); // Free The Texture Image Memory
}

free(TextureImage[0]); // Free The Image Structure
}

return Status; // Return The Status
}

// Loads The .RAW File And Stores It In pHeightMap
void LoadRawFile(LPSTR strName, int nSize, BYTE *pHeightMap)
{
FILE *pFile = NULL;

// Open The File In Read / Binary Mode.
pFile = fopen( strName, "rb" );

// Check To See If We Found The File And Could Open It
if ( pFile == NULL )
{
// Display Error Message And Stop The Function
MessageBox(NULL, "Can't Find The Height Map!", "Error", MB_OK);
return;
}

fread( pHeightMap, 1, nSize, pFile );

// After We Read The Data, It's A Good Idea To Check If Everything Read Fine
int result = ferror( pFile );

// Check If We Received An Error
if (result)
{
MessageBox(NULL, "Failed To Get Data!", "Error", MB_OK);
}

// Close The File.
fclose(pFile);
}


GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window
{
if (height==0) // Prevent A Divide By Zero By
{
height=1; // Making Height Equal One
}

glViewport(0,0,width,height); // Reset The Current Viewport

glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix

// Calculate The Aspect Ratio Of The Window
gluPerspective(30.0f,(GLfloat)width/(GLfloat)height,0.00001f,5000000.0f);
glGetFloatv(GL_PROJECTION_MATRIX, s);
view.SetMatrix(s);
view.Scale(1,-1,1);
//view.RotateX(45);
view.Translate(0.0f, 0.0f, -500.0f);
view.GetMatrix(s);
glLoadMatrixf(s);
eye.x = 0; eye.y = 20; eye.z = 10;
center.x = 0; center.y = 0; center.z = 0;
gluLookAt(eye.x,eye.y,eye.z,center.x,center.y,center.z, 0,1,0);
vis.SetVector(eye, center);

glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
}

int InitGL(GLvoid)
{
if (!LoadGLTextures()) // Jump To Texture Loading Routine ( NEW )
{
return FALSE; // If Texture Didn't Load Return FALSE
}
glEnable(GL_TEXTURE_2D); // Enable Texture Mapping ( NEW )
glEnable(GL_LIGHTING);

GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat mat_shininess[] = { 75.0 };
GLfloat light_position[] = {1.0, 1.0, 10.0, 0.0 };

glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);

glEnable(GL_LIGHT0);

glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
glClearDepth(1.0f);
// Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations

return TRUE; // Initialization Went OK
}

int Height(int X, int Y) // This Returns The Height From A Height Map Index
{
return heightmap[X][Y]; // Index Into Our Height Array And Return The Height
}

int DrawGLScene(GLvoid) // Here's Where We Do All The Drawing
{
vertex v1;
vertex v2;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glLoadIdentity(); // Reset The Current Modelview Matrix
//glTranslatef(0.0f,0.0f,0.0f); // Move Left 1.5 Units And Into The Screen 6.0
glMatrixMode(GL_PROJECTION);
glGetFloatv(GL_PROJECTION_MATRIX, s);
view2.SetMatrix(s);
view2.Translate(0.0f+hdepth,0.0f+depth,0.0f+zdepth);
view2.Translate(center.x,center.y,center.z);
view2.RotateZ(rot);
view2.Translate(-center.x,-center.y,-center.z);
view2.GetMatrix(s);
glLoadMatrixf(s);


hdepth = 0.0f;
zdepth = 0.0f;
depth = 0.0f;
rot = 0.0f;
glMatrixMode(GL_MODELVIEW);


glBegin(GL_QUADS);
glColor3f(1.0f,1.0f,1.0f); // Set The Color To Blue One Time Only
for (int y=1;y<=21;y++){
for (int x=1;x<=21;x++){
z1 = Height(x, y )*20;
z2 = Height(x-1, y )*20;
z3 = Height(x, y-1 )*20;
z4 = Height(x-1, y-1 )*20;
v1.x = (x*64);
v1.y = (y*64);
v1.z = z1;

glTexCoord2f(0.0f, 0.0f); glVertex3i((x*64)-64, (y*64),z2);
glTexCoord2f(1.0f, 0.0f); glVertex3i( (x*64), (y*64),z1);
glTexCoord2f(1.0f, 1.0f); glVertex3i( (x*64),(y*64)-64,z3);
glTexCoord2f(0.0f, 1.0f); glVertex3i((x*64)-64,(y*64)-64,z4);
}
}
glEnd();
return TRUE; // Keep Going
}

GLvoid KillGLWindow(GLvoid) // Properly Kill The Window
{
if (fullscreen) // Are We In Fullscreen Mode?
{
ChangeDisplaySettings(NULL,0); // If So Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}

if (hRC) // Do We Have A Rendering Context?
{
if (!wglMakeCurrent(NULL,NULL)) // Are We Able To Release The DC And RC Contexts?
{
MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
}

if (!wglDeleteContext(hRC)) // Are We Able To Delete The RC?
{
MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
}
hRC=NULL; // Set RC To NULL
}

if (hDC && !ReleaseDC(hWnd,hDC)) // Are We Able To Release The DC
{
MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hDC=NULL; // Set DC To NULL
}

if (hWnd && !DestroyWindow(hWnd)) // Are We Able To Destroy The Window?
{
MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hWnd=NULL; // Set hWnd To NULL
}

if (!UnregisterClass("OpenGL",hInstance)) // Are We Able To Unregister Class
{
MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hInstance=NULL; // Set hInstance To NULL
}
}

/* This Code Creates Our OpenGL Window. Parameters Are: *
* title - Title To Appear At The Top Of The Window *
* width - Width Of The GL Window Or Fullscreen Mode *
* height - Height Of The GL Window Or Fullscreen Mode *
* bits - Number Of Bits To Use For Color (8/16/24/32) *
* fullscreenflag - Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE) */


BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
GLuint PixelFormat; // Holds The Results After Searching For A Match
WNDCLASS wc; // Windows Class Structure
DWORD dwExStyle; // Window Extended Style
DWORD dwStyle; // Window Style
RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values
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

fullscreen=fullscreenflag; // Set The Global Fullscreen Flag

hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window.
wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages
wc.cbClsExtra = 0; // No Extra Window Data
wc.cbWndExtra = 0; // No Extra Window Data
wc.hInstance = hInstance; // Set The Instance
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer
wc.hbrBackground = NULL; // No Background Required For GL
wc.lpszMenuName = NULL; // We Don't Want A Menu
wc.lpszClassName = "OpenGL"; // Set The Class Name

if (!RegisterClass(&wc)) // Attempt To Register The Window Class
{
MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

if (fullscreen) // Attempt Fullscreen Mode?
{
DEVMODE dmScreenSettings; // Device Mode
memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure
dmScreenSettings.dmPelsWidth = width; // Selected Screen Width
dmScreenSettings.dmPelsHeight = height; // Selected Screen Height
dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel
dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

// Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
{
// If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode.
if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
{
fullscreen=FALSE; // Windowed Mode Selected. Fullscreen = FALSE
}
else
{
// Pop Up A Message Box Letting User Know The Program Is Closing.
MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
return FALSE; // Return 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

// Create The Window
if (!(hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window
"OpenGL", // Class Name
title, // Window Title
dwStyle | // Defined Window Style
WS_CLIPSIBLINGS | // Required Window Style
WS_CLIPCHILDREN, // Required Window Style
0, 0, // Window Position
WindowRect.right-WindowRect.left, // Calculate Window Width
WindowRect.bottom-WindowRect.top, // Calculate Window Height
NULL, // No Parent Window
NULL, // No Menu
hInstance, // Instance
NULL))) // Dont Pass Anything To WM_CREATE
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
bits, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};

if (!(hDC=GetDC(hWnd))) // Did We Get A Device Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

ShowWindow(hWnd,SW_SHOW); // Show The Window
SetForegroundWindow(hWnd); // Slightly Higher Priority
SetFocus(hWnd); // Sets Keyboard Focus To The Window
ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen

if (!InitGL()) // Initialize Our Newly Created GL Window
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

return TRUE; // Success
}

LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window
UINT uMsg, // Message For This Window
WPARAM wParam, // Additional Message Information
LPARAM lParam) // Additional Message Information
{
switch (uMsg) // Check For Windows Messages
{
case WM_ACTIVATE: // Watch For Window Activate Message
{
if (!HIWORD(wParam)) // Check Minimization State
{
active=TRUE; // Program Is Active
}
else
{
active=FALSE; // Program Is No Longer Active
}

return 0; // Return To The Message Loop
}

case WM_SYSCOMMAND:
{
switch (wParam)
{
case SC_SCREENSAVE:
case SC_MONITORPOWER:
return 0;
}
break;
}

case WM_CLOSE: // Did We Receive A Close Message?
{
PostQuitMessage(0); // Send A Quit Message
return 0; // Jump Back
}

case WM_KEYDOWN: // Is A Key Being Held Down?
{
keys[wParam] = TRUE; // If So, Mark It As TRUE
return 0; // Jump Back
}

case WM_KEYUP: // Has A Key Been Released?
{
keys[wParam] = FALSE; // If So, Mark It As FALSE
return 0; // Jump Back
}

case WM_MOUSEMOVE:
{
mouse = TRUE;
mouse_x = LOWORD(lParam);
mouse_y = HIWORD(lParam);
return 0;
}

case WM_SIZE: // Resize The OpenGL Window
{
ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height
return 0; // Jump Back
}
}

// Pass All Unhandled Messages To DefWindowProc
return DefWindowProc(hWnd,uMsg,wParam,lParam);
}

int WINAPI WinMain( HINSTANCE hInstance, // Instance
HINSTANCE hPrevInstance, // Previous Instance
LPSTR lpCmdLine, // Command Line Parameters
int nCmdShow) // Window Show State
{
MSG msg; // Windows Message Structure
BOOL done=FALSE; // Bool Variable To Exit Loop

// Ask The User Which Screen Mode They Prefer
if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
{
fullscreen=FALSE; // Windowed Mode
}

// Create Our OpenGL Window
if (!CreateGLWindow("NeHe's First Polygon Tutorial",800,600,16,fullscreen))
{
return 0; // Quit If Window Was Not Created
}

while(!done) // Loop That Runs While done=FALSE
{
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting?
{
if (msg.message==WM_QUIT) // Have We Received A Quit Message?
{
done=TRUE; // If So done=TRUE
}
else // If Not, Deal With Window Messages
{
TranslateMessage(&msg); // Translate The Message
DispatchMessage(&msg); // Dispatch The Message
}
}
else // If There Are No Messages
{
// Get FPS
if( GetTickCount() - g_dwLastFPS >= 1000 ) // When A Second Has Passed...
{
g_dwLastFPS = GetTickCount(); // Update Our Time Variable
g_nFPS = g_nFrames; // Save The FPS
g_nFrames = 0; // Reset The FPS Counter

rad = (float)(rotation*0.0174532925);
char szTitle[256]={0}; // Build The Title String
sprintf( szTitle, "Absinth Camera Test - %d FPS - Camera Position: %f | %f, | %f Angle: %f Mouse X: %f, Mouse Y: %f", g_nFPS, eye.x, eye.y, eye.z, rotation, mouse_x, mouse_y);
SetWindowText( hWnd, szTitle ); // Set The Title
}
g_nFrames++;

// Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene()
if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) // Active? Was There A Quit Received?
{
done=TRUE; // ESC or DrawGLScene Signalled A Quit
}
else // Not Time To Quit, Update Screen
{
SwapBuffers(hDC); // Swap Buffers (Double Buffering)
}
if (keys[VK_UP])
{
rad = (float)(rotation*0.0174532925);
eye.y -= movefactor * (cos(rad));
eye.x -= movefactor * (sin(rad));
center.y -= movefactor * (cos(rad));
center.x -= movefactor * (sin(rad));
depth += movefactor * (cos(rad));
hdepth += movefactor * (sin(rad));
/*eye.y += 10.0f;
center.y += 10.0f;
depth -= 10.0f;*/


}
if (keys[VK_DOWN])
{
rad = (float)(rotation*0.0174532925);
eye.y += movefactor * (cos(rad));
eye.x += movefactor * (sin(rad));
center.y += movefactor * (cos(rad));
center.x += movefactor * (sin(rad));
depth -= movefactor * (cos(rad));
hdepth -= movefactor * (sin(rad));

/*eye.y += 10.0f;
center.y += 10.0f;
depth -= 10.0f;*/

//zdepth -= 5.0f;

}
if (keys[VK_F2])
{
eye.x -= 10.0f;
center.x -= 10.0f;
hdepth += 10.0f;

}
if (keys[VK_F3])
{
eye.x += 10.0f;
center.x += 10.0f;
hdepth -= 10.0f;

}
if (keys[VK_LEFT])
{
rad = (float)(rotation*0.0174532925);
eye.x += movefactor * (cos(rad));
eye.y += movefactor * (sin(rad));
center.x += movefactor * (cos(rad));
center.y += movefactor * (sin(rad));
hdepth -= movefactor * (cos(rad));
depth -= movefactor * (sin(rad));
/*rot += 1.0f;
rotation += 1.0f;
if (rotation >=360) { rotation = rotation - 360; }
rad = (float)(rotation*0.0174532925);
eye.x = center.x + (vis.magnitude() * sin(rad));
eye.y = center.y + (vis.magnitude() * cos(rad));*/


}
if (keys[VK_RIGHT])
{
rot -= 1.0f;
rotation -= 1.0f;
if (rotation <= -360 ) { rotation = rotation + 360; }
rad = (float)(rotation*0.0174532925);
eye.x = center.x + (vis.magnitude() * sin(rad));
eye.y = center.y + (vis.magnitude() * cos(rad));


}
if (keys[VK_F1]) // Is F1 Being Pressed?
{
keys[VK_F1]=FALSE; // If So Make Key FALSE
KillGLWindow(); // Kill Our Current Window
fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode
// Recreate Our OpenGL Window
if (!CreateGLWindow("NeHe's First Polygon Tutorial",800,600,16,fullscreen))
{
return 0; // Quit If Window Was Not Created
}
}
if (mouse == TRUE) {
mouse = FALSE;
if (mouse_x > old_mouse_x) {
rot -= 1.0f * (mouse_x-old_mouse_x);
rotation -= 1.0f * (mouse_x-old_mouse_x);
/*if (rotation < -90) {
rotation = -90;
rot = 0;
}*/

if (rotation <= -360 ) { rotation = rotation + 360; }
rad = (float)(rotation*0.0174532925);
eye.x = center.x + (vis.magnitude() * sin(rad));
eye.y = center.y + (vis.magnitude() * cos(rad));
}
if (mouse_x < old_mouse_x) {
rot += 1.0f * (old_mouse_x-mouse_x);
rotation += 1.0f * (old_mouse_x-mouse_x);
if (rotation >=360) { rotation = rotation - 360; }
rad = (float)(rotation*0.0174532925);
eye.x = center.x + (vis.magnitude() * sin(rad));
eye.y = center.y + (vis.magnitude() * cos(rad));
}
old_mouse_x = mouse_x;
old_mouse_y = mouse_y;
}

}
}

// Shutdown
KillGLWindow(); // Kill The Window
return (msg.wParam); // Exit The Program
}




Hope this helps...

[Edited by - LordAsm on March 14, 2006 1:36:48 PM]

Share this post


Link to post
Share on other sites
Kalidor    1087
Quote:
Original post by LordAsm
...
gluPerspective(30.0f,(GLfloat)width/(GLfloat)height,0.00001f,5000000.0f);
...
My guess is Z-fighting. I don't have much time right now to explain so read this then change your near and far plane values to something more reasonable.

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  

  • Similar Content

    • By Arulbabu Donbosco
      There are studios selling applications which is just copying any 3Dgraphic content and regenerating into another new window. especially for CAVE Virtual reality experience. so that the user opens REvite or CAD or any other 3D applications and opens a model. then when the user selects the rendered window the VR application copies the 3D model information from the OpenGL window. 
      I got the clue that the VR application replaces the windows opengl32.dll file. how this is possible ... how can we copy the 3d content from the current OpenGL window.
      anyone, please help me .. how to go further... to create an application like VR CAVE. 
       
      Thanks
    • By cebugdev
      hi all,

      i am trying to build an OpenGL 2D GUI system, (yeah yeah, i know i should not be re inventing the wheel, but this is for educational and some other purpose only),
      i have built GUI system before using 2D systems such as that of HTML/JS canvas, but in 2D system, i can directly match a mouse coordinates to the actual graphic coordinates with additional computation for screen size/ratio/scale ofcourse.
      now i want to port it to OpenGL, i know that to render a 2D object in OpenGL we specify coordiantes in Clip space or use the orthographic projection, now heres what i need help about.
      1. what is the right way of rendering the GUI? is it thru drawing in clip space or switching to ortho projection?
      2. from screen coordinates (top left is 0,0 nd bottom right is width height), how can i map the mouse coordinates to OpenGL 2D so that mouse events such as button click works? In consideration ofcourse to the current screen/size dimension.
      3. when let say if the screen size/dimension is different, how to handle this? in my previous javascript 2D engine using canvas, i just have my working coordinates and then just perform the bitblk or copying my working canvas to screen canvas and scale the mouse coordinates from there, in OpenGL how to work on a multiple screen sizes (more like an OpenGL ES question).
      lastly, if you guys know any books, resources, links or tutorials that handle or discuss this, i found one with marekknows opengl game engine website but its not free,
      Just let me know. Did not have any luck finding resource in google for writing our own OpenGL GUI framework.
      IF there are no any available online, just let me know, what things do i need to look into for OpenGL and i will study them one by one to make it work.
      thank you, and looking forward to positive replies.
    • By fllwr0491
      I have a few beginner questions about tesselation that I really have no clue.
      The opengl wiki doesn't seem to talk anything about the details.
       
      What is the relationship between TCS layout out and TES layout in?
      How does the tesselator know how control points are organized?
          e.g. If TES input requests triangles, but TCS can output N vertices.
             What happens in this case?
      In this article,
      http://www.informit.com/articles/article.aspx?p=2120983
      the isoline example TCS out=4, but TES in=isoline.
      And gl_TessCoord is only a single one.
      So which ones are the control points?
      How are tesselator building primitives?
    • By Orella
      I've been developing a 2D Engine using SFML + ImGui.
      Here you can see an image
      The editor is rendered using ImGui and the scene window is a sf::RenderTexture where I draw the GameObjects and then is converted to ImGui::Image to render it in the editor.
      Now I need to create a 3D Engine during this year in my Bachelor Degree but using SDL2 + ImGui and I want to recreate what I did with the 2D Engine. 
      I've managed to render the editor like I did in the 2D Engine using this example that comes with ImGui. 
      3D Editor preview
      But I don't know how to create an equivalent of sf::RenderTexture in SDL2, so I can draw the 3D scene there and convert it to ImGui::Image to show it in the editor.
      If you can provide code will be better. And if you want me to provide any specific code tell me.
      Thanks!
    • By Picpenguin
      Hi
      I'm new to learning OpenGL and still learning C. I'm using SDL2, glew, OpenGL 3.3, linmath and stb_image.
      I started following through learnopengl.com and got through it until I had to load models. The problem is, it uses Assimp for loading models. Assimp is C++ and uses things I don't want in my program (boost for example) and C support doesn't seem that good.
      Things like glVertexAttribPointer and shaders are still confusing to me, but I have to start somewhere right?
      I can't seem to find any good loading/rendering tutorials or source code that is simple to use and easy to understand.
      I have tried this for over a week by myself, searching for solutions but so far no luck. With tinyobjloader-c and project that uses it, FantasyGolfSimulator, I was able to actually load the model with plain color (always the same color no matter what I do) on screen and move it around, but cannot figure out how to use textures or use its multiple textures with it.
      I don't ask much: I just want to load models with textures in them, maybe have lights affect them (directional spotlight etc). Also, some models have multiple parts and multiple textures in them, how can I handle those?
      Are there solutions anywhere?
      Thank you for your time. Sorry if this is a bit confusing, English isn't my native language
  • Popular Now