Sign in to follow this  

OpenGL Problem with terrain

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

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

Recommended Posts

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
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
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
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
Ty, solved this.
Didn't know about this Z-fighting problem.... :):)

I knew it was a very noobish error! :)

Ty!

Share this post


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

  • Similar Content

    • By xhcao
      Does sync be needed to read texture content after access texture image in compute shader?
      My simple code is as below,
      glUseProgram(program.get());
      glBindImageTexture(0, texture[0], 0, GL_FALSE, 3, GL_READ_ONLY, GL_R32UI);
      glBindImageTexture(1, texture[1], 0, GL_FALSE, 4, GL_WRITE_ONLY, GL_R32UI);
      glDispatchCompute(1, 1, 1);
      // Does sync be needed here?
      glUseProgram(0);
      glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer);
      glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                                     GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, texture[1], 0);
      glReadPixels(0, 0, kWidth, kHeight, GL_RED_INTEGER, GL_UNSIGNED_INT, outputValues);
       
      Compute shader is very simple, imageLoad content from texture[0], and imageStore content to texture[1]. Does need to sync after dispatchCompute?
    • By Jonathan2006
      My question: is it possible to transform multiple angular velocities so that they can be reinserted as one? My research is below:
      // This works quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); quat quaternion2 = GEMultiplyQuaternions(quaternion1, GEQuaternionFromAngleRadians(angleRadiansVector2)); quat quaternion3 = GEMultiplyQuaternions(quaternion2, GEQuaternionFromAngleRadians(angleRadiansVector3)); glMultMatrixf(GEMat4FromQuaternion(quaternion3).array); // The first two work fine but not the third. Why? quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); vec3 vector1 = GETransformQuaternionAndVector(quaternion1, angularVelocity1); quat quaternion2 = GEQuaternionFromAngleRadians(angleRadiansVector2); vec3 vector2 = GETransformQuaternionAndVector(quaternion2, angularVelocity2); // This doesn't work //quat quaternion3 = GEQuaternionFromAngleRadians(angleRadiansVector3); //vec3 vector3 = GETransformQuaternionAndVector(quaternion3, angularVelocity3); vec3 angleVelocity = GEAddVectors(vector1, vector2); // Does not work: vec3 angleVelocity = GEAddVectors(vector1, GEAddVectors(vector2, vector3)); static vec3 angleRadiansVector; vec3 angularAcceleration = GESetVector(0.0, 0.0, 0.0); // Sending it through one angular velocity later in my motion engine angleVelocity = GEAddVectors(angleVelocity, GEMultiplyVectorAndScalar(angularAcceleration, timeStep)); angleRadiansVector = GEAddVectors(angleRadiansVector, GEMultiplyVectorAndScalar(angleVelocity, timeStep)); glMultMatrixf(GEMat4FromEulerAngle(angleRadiansVector).array); Also how do I combine multiple angularAcceleration variables? Is there an easier way to transform the angular values?
    • By dpadam450
      I have this code below in both my vertex and fragment shader, however when I request glGetUniformLocation("Lights[0].diffuse") or "Lights[0].attenuation", it returns -1. It will only give me a valid uniform location if I actually use the diffuse/attenuation variables in the VERTEX shader. Because I use position in the vertex shader, it always returns a valid uniform location. I've read that I can share uniforms across both vertex and fragment, but I'm confused what this is even compiling to if this is the case.
       
      #define NUM_LIGHTS 2
      struct Light
      {
          vec3 position;
          vec3 diffuse;
          float attenuation;
      };
      uniform Light Lights[NUM_LIGHTS];
       
       
    • By pr033r
      Hello,
      I have a Bachelor project on topic "Implenet 3D Boid's algorithm in OpenGL". All OpenGL issues works fine for me, all rendering etc. But when I started implement the boid's algorithm it was getting worse and worse. I read article (http://natureofcode.com/book/chapter-6-autonomous-agents/) inspirate from another code (here: https://github.com/jyanar/Boids/tree/master/src) but it still doesn't work like in tutorials and videos. For example the main problem: when I apply Cohesion (one of three main laws of boids) it makes some "cycling knot". Second, when some flock touch to another it scary change the coordination or respawn in origin (x: 0, y:0. z:0). Just some streng things. 
      I followed many tutorials, change a try everything but it isn't so smooth, without lags like in another videos. I really need your help. 
      My code (optimalizing branch): https://github.com/pr033r/BachelorProject/tree/Optimalizing
      Exe file (if you want to look) and models folder (for those who will download the sources):
      http://leteckaposta.cz/367190436
      Thanks for any help...

    • By Andrija
      I am currently trying to implement shadow mapping into my project , but although i can render my depth map to the screen and it looks okay , when i sample it with shadowCoords there is no shadow.
      Here is my light space matrix calculation
      mat4x4 lightViewMatrix; vec3 sun_pos = {SUN_OFFSET * the_sun->direction[0], SUN_OFFSET * the_sun->direction[1], SUN_OFFSET * the_sun->direction[2]}; mat4x4_look_at(lightViewMatrix,sun_pos,player->pos,up); mat4x4_mul(lightSpaceMatrix,lightProjMatrix,lightViewMatrix); I will tweak the values for the size and frustum of the shadow map, but for now i just want to draw shadows around the player position
      the_sun->direction is a normalized vector so i multiply it by a constant to get the position.
      player->pos is the camera position in world space
      the light projection matrix is calculated like this:
      mat4x4_ortho(lightProjMatrix,-SHADOW_FAR,SHADOW_FAR,-SHADOW_FAR,SHADOW_FAR,NEAR,SHADOW_FAR); Shadow vertex shader:
      uniform mat4 light_space_matrix; void main() { gl_Position = light_space_matrix * transfMatrix * vec4(position, 1.0f); } Shadow fragment shader:
      out float fragDepth; void main() { fragDepth = gl_FragCoord.z; } I am using deferred rendering so i have all my world positions in the g_positions buffer
      My shadow calculation in the deferred fragment shader:
      float get_shadow_fac(vec4 light_space_pos) { vec3 shadow_coords = light_space_pos.xyz / light_space_pos.w; shadow_coords = shadow_coords * 0.5 + 0.5; float closest_depth = texture(shadow_map, shadow_coords.xy).r; float current_depth = shadow_coords.z; float shadow_fac = 1.0; if(closest_depth < current_depth) shadow_fac = 0.5; return shadow_fac; } I call the function like this:
      get_shadow_fac(light_space_matrix * vec4(position,1.0)); Where position is the value i got from sampling the g_position buffer
      Here is my depth texture (i know it will produce low quality shadows but i just want to get it working for now):
      sorry because of the compression , the black smudges are trees ... https://i.stack.imgur.com/T43aK.jpg
      EDIT: Depth texture attachment:
      glTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT24,fbo->width,fbo->height,0,GL_DEPTH_COMPONENT,GL_FLOAT,NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, fbo->depthTexture, 0);
  • Popular Now