• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
pondwater

OpenGL
OpenGL Superbible Chapter 13 issues

10 posts in this topic

Okay so im having issues trying to the get wglChoosePixelFormatARB functions to work properly. For some reason it cannot find any suitable pixel format... I have a decent graphics card (NVIDIA GeForce GTS 250) and have updated the drivers, I dont see why its having an issue. There are no issues with glew as far as i know. I dont understand why i'm having this issue.

I've inluded the code, its taken straight from the google code project superbible 5th edition source.

This is a screenshot of my console showing the error messages the code produces: [url="http://imgur.com/G0bAA"]http://imgur.com/G0bAA[/url]

Any ideas as to what could be causing the issue?



Code:

[code]// SphereWorld_redux.cpp
// OpenGL SuperBible Chapter 13
// New and improved (performance) sphere world
// Program by Richard S. Wright Jr. and Nicholas Haemel

#include <gltools.h>
#include <GLShaderManager.h>
#include <GLFrustum.h>
#include <GLBatch.h>
#include <GLMatrixStack.h>
#include <GLGeometryTransform.h>
#include <Stopwatch.h>
#include <gl\wglew.h>
#include <math.h>
#include <stdio.h>
#include <iostream>


GLShaderManager shaderManager; // Shader Manager
GLMatrixStack modelViewMatrix; // Modelview Matrix
GLMatrixStack projectionMatrix; // Projection Matrix
GLFrustum viewFrustum; // View Frustum
GLGeometryTransform transformPipeline; // Geometry Transform Pipeline
GLFrame cameraFrame; // Camera frame

GLTriangleBatch torusBatch;
GLTriangleBatch sphereBatch;
GLBatch groundBatch;
GLBatch floorBatch;

GLuint uiTextures[3];

static const TCHAR g_szAppName[] = TEXT("Sphere World Redux");
static const TCHAR g_szClassName[50] = TEXT("OGL_CLASS");

static const int g_nWinWidth = 800;
static const int g_nWinHeight = 600;

HWND g_hWnd;
HGLRC g_hRC;
HDC g_hDC;
HINSTANCE g_hInstance;
WNDCLASS g_windClass;
RECT g_windowRect;
bool g_ContinueRendering;
bool g_InFullScreen;

void DrawSongAndDance(GLfloat yRot) // Called to draw dancing objects
{
static GLfloat vWhite[] = { 1.0f, 1.0f, 1.0f, 1.0f };
static GLfloat vLightPos[] = { 0.0f, 3.0f, 0.0f, 1.0f };

// Get the light position in eye space
M3DVector4f vLightTransformed;
M3DMatrix44f mCamera;
modelViewMatrix.GetMatrix(mCamera);
m3dTransformVector4(vLightTransformed, vLightPos, mCamera);

// Draw the light source
modelViewMatrix.PushMatrix();
modelViewMatrix.Translatev(vLightPos);
shaderManager.UseStockShader(GLT_SHADER_FLAT,
transformPipeline.GetModelViewProjectionMatrix(),
vWhite);
sphereBatch.Draw();
modelViewMatrix.PopMatrix();

// Song and dance
modelViewMatrix.Translate(0.0f, 0.2f, -2.5f);
modelViewMatrix.PushMatrix(); // Saves the translated origin
modelViewMatrix.Rotate(yRot, 0.0f, 1.0f, 0.0f);

// Draw stuff relative to the camera
glBindTexture(GL_TEXTURE_2D, uiTextures[1]);
shaderManager.UseStockShader(GLT_SHADER_TEXTURE_POINT_LIGHT_DIFF,
modelViewMatrix.GetMatrix(),
transformPipeline.GetProjectionMatrix(),
vLightTransformed,
vWhite,
0);
torusBatch.Draw();
modelViewMatrix.PopMatrix(); // Erased the rotate

modelViewMatrix.Rotate(yRot * -2.0f, 0.0f, 1.0f, 0.0f);
modelViewMatrix.Translate(0.8f, 0.0f, 0.0f);

glBindTexture(GL_TEXTURE_2D, uiTextures[2]);
shaderManager.UseStockShader(GLT_SHADER_TEXTURE_POINT_LIGHT_DIFF,
modelViewMatrix.GetMatrix(),
transformPipeline.GetProjectionMatrix(),
vLightTransformed,
vWhite,
0);
sphereBatch.Draw();
}


bool LoadTGATexture(const char *szFileName, GLenum minFilter, GLenum magFilter, GLenum wrapMode)
{
GLbyte *pBits;
int nWidth, nHeight, nComponents;
GLenum eFormat;

// Read the texture bits
pBits = gltReadTGABits(szFileName, &nWidth, &nHeight, &nComponents, &eFormat);
if(pBits == NULL)
return false;

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);

if(minFilter == GL_LINEAR_MIPMAP_LINEAR ||
minFilter == GL_LINEAR_MIPMAP_NEAREST ||
minFilter == GL_NEAREST_MIPMAP_LINEAR ||
minFilter == GL_NEAREST_MIPMAP_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);

glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glTexImage2D(GL_TEXTURE_2D, 0, nComponents, nWidth, nHeight, 0,
eFormat, GL_UNSIGNED_BYTE, pBits);

free(pBits);
return true;
}


//////////////////////////////////////////////////////////////////
// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Initialze Shader Manager
shaderManager.InitializeStockShaders();

glEnable(GL_DEPTH_TEST);
glEnable(GL_MULTISAMPLE);

glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

// This makes a torus
gltMakeTorus(torusBatch, 0.4f, 0.15f, 20, 20);

// This makes a sphere
gltMakeSphere(sphereBatch, 0.1f, 26, 13);

// This makes the ground lines
groundBatch.Begin(GL_LINES, 328);
for(GLfloat x = -20.0f; x <= 20.0f; x+= 0.5f)
{
groundBatch.Vertex3f(x, -0.4f, 20.0f); // Parallel to X, cross the z axis
groundBatch.Vertex3f(x, -0.4f, -20.0f);

groundBatch.Vertex3f(20.0f, -0.4f, x); // Parallel to Z, cross the x axis
groundBatch.Vertex3f(-20.0f, -0.4f, x);
}
groundBatch.End();


// Make the solid ground
GLfloat alpha = 0.25f;
GLfloat texSize = 10.0f;
floorBatch.Begin(GL_TRIANGLE_FAN, 4, 1);
floorBatch.MultiTexCoord2f(0, 0.0f, 0.0f);
floorBatch.Color4f(1.0f, 1.0f, 1.0f, alpha);
floorBatch.Vertex3f(-20.0f, -0.41f, 20.0f);

floorBatch.MultiTexCoord2f(0, texSize, 0.0f);
floorBatch.Color4f(1.0f, 1.0f, 1.0f, alpha);
floorBatch.Vertex3f(20.0f, -0.41f, 20.0f);

floorBatch.MultiTexCoord2f(0, texSize, texSize);
floorBatch.Color4f(1.0f, 1.0f, 1.0f, alpha);
floorBatch.Vertex3f(20.0f, -0.41f, -20.0f);

floorBatch.MultiTexCoord2f(0, 0.0f, texSize);
floorBatch.Color4f(1.0f, 1.0f, 1.0f, alpha);
floorBatch.Vertex3f(-20.0f, -0.41f, -20.0f);
floorBatch.End();

// Make 3 texture objects
glGenTextures(3, uiTextures);

// Load the Marble
glBindTexture(GL_TEXTURE_2D, uiTextures[0]);
LoadTGATexture("marble.tga", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_REPEAT);

// Load Mars
glBindTexture(GL_TEXTURE_2D, uiTextures[1]);
LoadTGATexture("marslike.tga", GL_LINEAR_MIPMAP_LINEAR,
GL_LINEAR, GL_CLAMP_TO_EDGE);

// Load Moon
glBindTexture(GL_TEXTURE_2D, uiTextures[2]);
LoadTGATexture("moonlike.tga", GL_LINEAR_MIPMAP_LINEAR,
GL_LINEAR, GL_CLAMP_TO_EDGE);
}

void CheckErrors(GLuint progName = 0)
{
GLenum error = glGetError();

if (error != GL_NO_ERROR)
{
fprintf(stderr, "A GL Error has occured\n");
}

GLenum fboStatus = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);

if(fboStatus != GL_FRAMEBUFFER_COMPLETE)
{
switch (fboStatus)
{
case GL_FRAMEBUFFER_UNDEFINED:
// Oops, no window exists?
break;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
// Check the status of each attachment
break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
// Attach at least one buffer to the FBO
break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
// Check that all attachments enabled via
// glDrawBuffers exist in FBO
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
// Check that the buffer specified via
// glReadBuffer exists in FBO
break;
case GL_FRAMEBUFFER_UNSUPPORTED:
// Reconsider formats used for attached buffers
break;
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
// Make sure the number of samples for each
// attachment is the same
break;
//case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:
// Make sure the number of layers for each
// attachment is the same
//break;
}
fprintf(stderr,"The framebuffer is not complete\n");
}

if (progName != 0)
{
glValidateProgram(progName);
int iIsProgValid = 0;
glGetProgramiv(progName, GL_VALIDATE_STATUS, &iIsProgValid);
if(iIsProgValid == 0)
{
fprintf(stderr,"The current program is not valid\n");
}
}
}


// Called to draw scene
void RenderScene(void)
{
if(!g_ContinueRendering)
return;

static CStopWatch rotTimer;
float yRot = rotTimer.GetElapsedSeconds() * 60.0f;

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

modelViewMatrix.PushMatrix();
M3DMatrix44f mCamera;
cameraFrame.GetCameraMatrix(mCamera);
modelViewMatrix.MultMatrix(mCamera);

// Draw the world upside down
modelViewMatrix.PushMatrix();
modelViewMatrix.Scale(1.0f, -1.0f, 1.0f); // Flips the Y Axis
modelViewMatrix.Translate(0.0f, 0.8f, 0.0f); // Scootch the world down a bit...
glFrontFace(GL_CW);
DrawSongAndDance(yRot);
glFrontFace(GL_CCW);
modelViewMatrix.PopMatrix();

// Draw the solid ground
glEnable(GL_BLEND);
glBindTexture(GL_TEXTURE_2D, uiTextures[0]);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
static GLfloat vFloorColor[] = { 1.0f, 1.0f, 1.0f, 0.75f};
shaderManager.UseStockShader(GLT_SHADER_TEXTURE_MODULATE,
transformPipeline.GetModelViewProjectionMatrix(),
vFloorColor,
0);

floorBatch.Draw();
glDisable(GL_BLEND);

DrawSongAndDance(yRot);

modelViewMatrix.PopMatrix();

// Do the buffer Swap
SwapBuffers(g_hDC);

CheckErrors();
}



// Respond to arrow keys by moving the camera frame of reference
void SpecialKeys(int key)
{
float linear = 0.1f;
float angular = float(m3dDegToRad(5.0f));

if(key == VK_UP)
cameraFrame.MoveForward(linear);

if(key == VK_DOWN)
cameraFrame.MoveForward(-linear);

if(key == VK_LEFT)
cameraFrame.RotateWorld(angular, 0.0f, 1.0f, 0.0f);

if(key == VK_RIGHT)
cameraFrame.RotateWorld(-angular, 0.0f, 1.0f, 0.0f);

if(key == VK_ESCAPE ||key == 'q' || key == 'Q')
{
g_ContinueRendering = false;
PostQuitMessage(0);
}
}

void ChangeSize(int nWidth, int nHeight)
{
glViewport(0, 0, nWidth, nHeight);
transformPipeline.SetMatrixStacks(modelViewMatrix, projectionMatrix);

viewFrustum.SetPerspective(35.0f, float(nWidth)/float(nHeight), 1.0f, 100.0f);
projectionMatrix.LoadMatrix(viewFrustum.GetProjectionMatrix());
modelViewMatrix.LoadIdentity();
}

///////////////////////////////////////////////////////////////////////////////
// Callback functions to handle all window functions this app cares about.
// Once complete, pass message on to next app in the hook chain.
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
{
// Handle relevant messages individually
switch(uMsg)
{
case WM_ACTIVATE:
case WM_SETFOCUS:
RenderScene();
return 0;
case WM_SIZE:
ChangeSize(LOWORD(lParam),HIWORD(lParam));
RenderScene();
break;
case WM_CLOSE:
g_ContinueRendering = false;
PostQuitMessage(0);
return 0;
case WM_KEYDOWN:
SpecialKeys((unsigned int)wParam);
return 0;
default:
// Nothing to do now
break;
}

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



///////////////////////////////////////////////////////////////////////////////
// Setup the actual window and related state.
// Create the window, find a pixel format, create the OpenGL context
bool SetupWindow(int nWidth, int nHeight, bool bUseFS)
{
bool bRetVal = true;

int nWindowX = 0;
int nWindowY = 0;
int nPixelFormat = -1;
PIXELFORMATDESCRIPTOR pfd;

DWORD dwExtStyle;
DWORD dwWindStyle;

HINSTANCE g_hInstance = GetModuleHandle(NULL);

// setup window class
g_windClass.lpszClassName = g_szClassName; // Set the name of the Class
g_windClass.lpfnWndProc = (WNDPROC)WndProc;
g_windClass.hInstance = g_hInstance; // Use this module for the module handle
g_windClass.hCursor = LoadCursor(NULL, IDC_ARROW);// Pick the default mouse cursor
g_windClass.hIcon = LoadIcon(NULL, IDI_WINLOGO);// Pick the default windows icons
g_windClass.hbrBackground = NULL; // No Background
g_windClass.lpszMenuName = NULL; // No menu for this window
g_windClass.style = CS_HREDRAW | CS_OWNDC | // set styles for this class, specifically to catch
CS_VREDRAW; // window redraws, unique DC, and resize
g_windClass.cbClsExtra = 0; // Extra class memory
g_windClass.cbWndExtra = 0; // Extra window memory

// Register the newly defined class
if(!RegisterClass( &g_windClass ))
bRetVal = false;

dwExtStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
dwWindStyle = WS_OVERLAPPEDWINDOW;
ShowCursor(TRUE);

g_windowRect.left = nWindowX;
g_windowRect.right = nWindowX + nWidth;
g_windowRect.top = nWindowY;
g_windowRect.bottom = nWindowY + nHeight;

// Setup window width and height
AdjustWindowRectEx(&g_windowRect, dwWindStyle, FALSE, dwExtStyle);

//Adjust for adornments
int nWindowWidth = g_windowRect.right - g_windowRect.left;
int nWindowHeight = g_windowRect.bottom - g_windowRect.top;

// Create window
g_hWnd = CreateWindowEx(dwExtStyle, // Extended style
g_szClassName, // class name
g_szAppName, // window name
dwWindStyle |
WS_CLIPSIBLINGS |
WS_CLIPCHILDREN,// window stlye
nWindowX, // window position, x
nWindowY, // window position, y
nWindowWidth, // height
nWindowHeight, // width
NULL, // Parent window
NULL, // menu
g_hInstance, // instance
NULL); // pass this to WM_CREATE

// now that we have a window, setup the pixel format descriptor
g_hDC = GetDC(g_hWnd);

// Set a dummy pixel format so that we can get access to wgl functions
SetPixelFormat( g_hDC, 1,&pfd);
// Create OGL context and make it current
g_hRC = wglCreateContext( g_hDC );
wglMakeCurrent( g_hDC, g_hRC );

if (g_hDC == 0 ||
g_hDC == 0)
{
bRetVal = false;
printf("!!! An error occured creating an OpenGL window.\n");
}

// Setup GLEW which loads OGL function pointers
GLenum err = glewInit();
if (GLEW_OK != err)
{
/* Problem: glewInit failed, something is seriously wrong. */
bRetVal = false;
printf("Error: %s\n", glewGetErrorString(err));
}
const GLubyte *oglVersion = glGetString(GL_VERSION);
printf("This system supports OpenGL Version %s.\n", oglVersion);

// Now that extensions are setup, delete window and start over picking a real format.
wglMakeCurrent(NULL, NULL);
wglDeleteContext(g_hRC);
ReleaseDC(g_hWnd, g_hDC);
DestroyWindow(g_hWnd);

if(bUseFS)
{
// Prepare for a mode set to the requested resolution
DEVMODE dm;
memset(&dm,0,sizeof(dm));
dm.dmSize=sizeof(dm);
dm.dmPelsWidth = nWidth;
dm.dmPelsHeight = nHeight;
dm.dmBitsPerPel = 32;
dm.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

long error = ChangeDisplaySettings(&dm, CDS_FULLSCREEN);

if (error != DISP_CHANGE_SUCCESSFUL)
{
// Oops, something went wrong, let the user know.
if (MessageBox(NULL, "Could not set fullscreen mode.\n"
"Your video card may not support the requested mode.\n"
"Use windowed mode instead?",
g_szAppName, MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
{
g_InFullScreen = false;
dwExtStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
dwWindStyle = WS_OVERLAPPEDWINDOW;
}
else
{
MessageBox(NULL, "Program will exit.", "ERROR", MB_OK|MB_ICONSTOP);
return false;
}
}
else
{
// Mode set passed, setup the styles for fullscreen
g_InFullScreen = true;
dwExtStyle = WS_EX_APPWINDOW;
dwWindStyle = WS_POPUP;
ShowCursor(FALSE);
}
}

AdjustWindowRectEx(&g_windowRect, dwWindStyle, FALSE, dwExtStyle);

// Create the window again
g_hWnd = CreateWindowEx(dwExtStyle, // Extended style
g_szClassName, // class name
g_szAppName, // window name
dwWindStyle |
WS_CLIPSIBLINGS |
WS_CLIPCHILDREN,// window stlye
nWindowX, // window position, x
nWindowY, // window position, y
nWindowWidth, // height
nWindowHeight, // width
NULL, // Parent window
NULL, // menu
g_hInstance, // instance
NULL); // pass this to WM_CREATE

g_hDC = GetDC(g_hWnd);

int nPixCount = 0;

// Specify the important attributes we care about
int pixAttribs[] = { WGL_SUPPORT_OPENGL_ARB, 1, // Must support OGL rendering
WGL_DRAW_TO_WINDOW_ARB, 1, // pf that can run a window
WGL_ACCELERATION_ARB, 1, // must be HW accelerated
WGL_COLOR_BITS_ARB, 24, // 8 bits of each R, G and B
WGL_DEPTH_BITS_ARB, 16, // 16 bits of depth precision for window
WGL_DOUBLE_BUFFER_ARB, GL_TRUE, // Double buffered context
WGL_SAMPLE_BUFFERS_ARB, GL_TRUE, // MSAA on
WGL_SAMPLES_ARB, 8, // 8x MSAA
WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, // pf should be RGBA type
0}; // NULL termination

// Ask OpenGL to find the most relevant format matching our attribs
// Only get one format back.
wglChoosePixelFormatARB(g_hDC, &pixAttribs[0], NULL, 1, &nPixelFormat, (UINT*)&nPixCount);

if(nPixelFormat == -1)
{
printf("!!! An error occurred trying to find a MSAA pixel format with the requested attribs.\n");

// Try again without MSAA
pixAttribs[15] = 1;
wglChoosePixelFormatARB(g_hDC, &pixAttribs[0], NULL, 1, &nPixelFormat, (UINT*)&nPixCount);

if(nPixelFormat == -1)
{
// Couldn't find a format, perhaps no 3D HW or drivers are installed
g_hDC = 0;
g_hDC = 0;
bRetVal = false;
printf("!!! An error occurred trying to find a pixel format with the requested attribs.\n");
}
}

if(nPixelFormat != -1)
{
// Check for MSAA
int attrib[] = { WGL_SAMPLES_ARB };
int nResults = 0;
wglGetPixelFormatAttribivARB(g_hDC, nPixelFormat, 0, 1, attrib, &nResults);
printf("Chosen pixel format is MSAA with %d samples.\n", nResults);

// Got a format, now set it as the current one
SetPixelFormat( g_hDC, nPixelFormat, &pfd );

GLint attribs[] = {WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
WGL_CONTEXT_MINOR_VERSION_ARB, 3,
0 };

g_hRC = wglCreateContextAttribsARB(g_hDC, 0, attribs);
if (g_hRC == NULL)
{
printf("!!! Could not create an OpenGL 3.3 context.\n");
attribs[3] = 2;
g_hRC = wglCreateContextAttribsARB(g_hDC, 0, attribs);
if (g_hRC == NULL)
{
printf("!!! Could not create an OpenGL 3.2 context.\n");
attribs[3] = 1;
g_hRC = wglCreateContextAttribsARB(g_hDC, 0, attribs);
if (g_hRC == NULL)
{
printf("!!! Could not create an OpenGL 3.1 context.\n");
attribs[3] = 0;
g_hRC = wglCreateContextAttribsARB(g_hDC, 0, attribs);
if (g_hRC == NULL)
{
printf("!!! Could not create an OpenGL 3.0 context.\n");
printf("!!! OpenGL 3.0 and higher are not supported on this system.\n");
}
}
}
}

wglMakeCurrent( g_hDC, g_hRC );
}

if (g_hDC == 0 ||
g_hDC == 0)
{
bRetVal = false;
printf("!!! An error occured creating an OpenGL window.\n");
}

// If everything went as planned, display the window
if( bRetVal )
{
ShowWindow( g_hWnd, SW_SHOW );
SetForegroundWindow( g_hWnd );
SetFocus( g_hWnd );
g_ContinueRendering = true;
}

return bRetVal;
}

///////////////////////////////////////////////////////////////////////////////
// Cleanup window, OGL context and related state
// Called on exit and on error
bool KillWindow( )
{
bool bRetVal = true;

glDeleteTextures(3,uiTextures);

if (g_InFullScreen)
{
ChangeDisplaySettings(NULL,0);
ShowCursor(TRUE);
}
//Cleanup OGL RC
if(g_hRC)
{
wglMakeCurrent(NULL, NULL);
wglDeleteContext(g_hRC);
g_hRC = NULL;
}

// release the DC
if(g_hDC)
{
ReleaseDC(g_hWnd, g_hDC);
g_hDC = NULL;
}

// Destroy the window
if(g_hWnd)
{
DestroyWindow(g_hWnd);
g_hWnd = NULL;;
}

// Delete the window class
UnregisterClass(g_szClassName, g_hInstance);
g_hInstance = NULL;
ShowCursor(TRUE);
return bRetVal;
}

///////////////////////////////////////////////////////////////////////////////
// Main rendering loop
// Check for window messages and handle events, also draw scene
void mainLoop()
{
MSG msg;

// Check for waiting mssgs
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
if (msg.message==WM_QUIT)
{
g_ContinueRendering = false;
}
else
{
// Deal with mssgs
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
RenderScene();
}
}

///////////////////////////////////////////////////////////////////////////////
// Main program function, called on startup
// First setup the window and OGL state, then enter rendering loop
int main(int argc, char* argv[])
{
gltSetWorkingDirectory(argv[0]);

bool bUseFS = false;
if (MessageBox(NULL, "Would you like to run in Fullscreen Mode?", g_szAppName, MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
{
bUseFS = true;
}

if(SetupWindow(g_nWinWidth, g_nWinHeight, bUseFS))
{
SetupRC();
ChangeSize(g_nWinWidth, g_nWinHeight);
while (g_ContinueRendering)
{
mainLoop();
Sleep(0);
}
}
KillWindow();
system("PAUSE");
return 0;
}
[/code]
1

Share this post


Link to post
Share on other sites
So, let's check:

[code]if (g_hDC == 0 ||
        g_hDC == 0)
        {
        bRetVal = false;
        printf("!!! An error occured creating an OpenGL window.\n");
        }[/code]

"g_hDC == 0 || g_hDC == 0" ?... You forgot to put there g_hRC.  :)

Next:[code]int pixAttribs[] = { WGL_SUPPORT_OPENGL_ARB, 1, // Must support OGL rendering
                                                WGL_DRAW_TO_WINDOW_ARB, 1, // pf that can run a window
                                                WGL_ACCELERATION_ARB,   1, // must be HW accelerated
                                                WGL_COLOR_BITS_ARB,     24, // 8 bits of each R, G and B
                                                WGL_DEPTH_BITS_ARB,     16, // 16 bits of depth precision for window
                                                WGL_DOUBLE_BUFFER_ARB,  GL_TRUE, // Double buffered context
                                                        WGL_SAMPLE_BUFFERS_ARB, GL_TRUE, // MSAA on
                                                        WGL_SAMPLES_ARB,        8, // 8x MSAA
                                                WGL_PIXEL_TYPE_ARB,     WGL_TYPE_RGBA_ARB, // pf should be RGBA type
                                                0}; // NULL termination

        // Ask OpenGL to find the most relevant format matching our attribs
        // Only get one format back.
        wglChoosePixelFormatARB(g_hDC, &pixAttribs[0], NULL, 1, &nPixelFormat, (UINT*)&nPixCount);[/code]

"wglChoosePixelFormatARB" like other "gl" commands doesn't work without activated GL context (no page references this but most of examples with MSAA using an activated context). As you see GL context was deleted before:

[code] 
        wglMakeCurrent(NULL, NULL);
        wglDeleteContext(g_hRC);
        ReleaseDC(g_hWnd, g_hDC);
        DestroyWindow(g_hWnd);[/code]

I think it would work if you do this ^ code when you done setting a MSAA pixel format.




-me
0

Share this post


Link to post
Share on other sites
[quote name='FXACE' timestamp='1302801711' post='4798474']
"wglChoosePixelFormatARB" like other "gl" commands doesn't work without activated GL context. As you see GL context was deleted before:

[code]
wglMakeCurrent(NULL, NULL);
wglDeleteContext(g_hRC);
ReleaseDC(g_hWnd, g_hDC);
DestroyWindow(g_hWnd);[/code]

I think it would work if you do this ^ code when you done setting a MSAA pixel format.

[/quote]

hmmm that doesnt seem to be the issue, I get the exact same errors if i move that bit of code to after i use "wglChoosePixelFormatARB". I assume that since my program doesnt crash and burn or get any of the other errors i've inlucded the proper directories and linked the proper libraries.

Do you think it could be a hardware/driver issue?

Link to the source material including the GLTools classes used: [url="http://code.google.com/p/oglsuperbible5/source/browse/#svn%2Ftrunk%2FSrc%2FChapter13"]http://code.google.c...Src%2FChapter13[/url]
0

Share this post


Link to post
Share on other sites
When MSAA fails, the number of samples is set to one, but the WGL_SAMPLE_BUFFERS is still true. I don't suppose setting it to false makes any difference?

Also, isn't 24 bits the norm for depth buffers, rather than 16?
0

Share this post


Link to post
Share on other sites
[quote name='__sprite' timestamp='1302824822' post='4798602']
When MSAA fails, the number of samples is set to one, but the WGL_SAMPLE_BUFFERS is still true. I don't suppose setting it to false makes any difference?

Also, isn't 24 bits the norm for depth buffers, rather than 16?
[/quote]

I changed the code as follows with, but the results are the exactly the same. I also tried the 24 bit depth buffer and that didnt work either...

[code]

if(nPixelFormat == -1)
{
printf("!!! An error occurred trying to find a MSAA pixel format with the requested attribs.\n");

// Try again without MSAA
pixAttribs[13] = GL_FALSE;
pixAttribs[15] = 1;
wglChoosePixelFormatARB(g_hDC, &pixAttribs[0], NULL, 1, &nPixelFormat, (UINT*)&nPixCount);

[/code]
0

Share this post


Link to post
Share on other sites
 [quote name='pondwater' timestamp='1302821445' post='4798585']
Do you think it could be a hardware/driver issue?
[/quote]

It couldn't be a hardware/driver issue if any GL application works with MSAA. Did you tested any OpenGL application with MSAA context on your system?





0

Share this post


Link to post
Share on other sites
[quote name='FXACE' timestamp='1302862014' post='4798724']
[quote name='pondwater' timestamp='1302821445' post='4798585']
Do you think it could be a hardware/driver issue?
[/quote]

It couldn't be a hardware/driver issue if any GL application works with MSAA. Did you tested any OpenGL application with MSAA context on your system?


[/quote]

i dont think so, pretty sure all the games i play use direct x...

Does that code run on your computer?
0

Share this post


Link to post
Share on other sites
 [quote name='pondwater' timestamp='1302934180' post='4799042']
Does that code run on your computer?
[/quote]




Actually, I have no time to test it   :mellow: . But another code to initialize MSAA context can be found [url="http://www.dhpoware.com/demos/glslTerrainTexturing.html"]here[/url] or [url="http://www.dhpoware.com/demos/glMultiSampleAntiAliasing.html"]here[/url]. It's pretty simple and works fine (check out WGL_ARB_multisample.cpp, WGL_ARB_multisample.h and "InitGL()" in main.cpp). I hope it would help you.   :)
0

Share this post


Link to post
Share on other sites
[quote name='FXACE' timestamp='1302967040' post='4799145']
[quote name='pondwater' timestamp='1302934180' post='4799042']
Does that code run on your computer?
[/quote]




Actually, I have no time to test it :mellow: . But another code to initialize MSAA context can be found [url="http://www.dhpoware.com/demos/glslTerrainTexturing.html"]here[/url] or [url="http://www.dhpoware.com/demos/glMultiSampleAntiAliasing.html"]here[/url]. It's pretty simple and works fine (check out WGL_ARB_multisample.cpp, WGL_ARB_multisample.h and "InitGL()" in main.cpp). I hope it would help you. :)
[/quote]

those two programs run perfectly, its a shame i bought an opengl book which has code that doesnt run...
0

Share this post


Link to post
Share on other sites
[quote]its a shame i bought an opengl book which has code that doesnt run...
[/quote]

I too am disappointed at the errors in the repository that they provide. Nevertheless, I have a fixed version for you:

[code]
#ifndef GLEW_STATIC
#define GLEW_STATIC
#endif

#include <GL\glew.h>
#include <gl\wglew.h>
#include <math.h>
#include <stdio.h>
#include <iostream>

#include <gltools.h>
#include <GLShaderManager.h>
#include <GLFrustum.h>
#include <GLBatch.h>
#include <GLMatrixStack.h>
#include <GLGeometryTransform.h>
#include <Stopwatch.h>

#define NUM_SPHERES 50
GLFrame spheres[NUM_SPHERES];

GLShaderManager shaderManager; // Shader Manager
GLMatrixStack modelViewMatrix; // Modelview Matrix
GLMatrixStack projectionMatrix; // Projection Matrix
GLFrustum viewFrustum; // View Frustum
GLGeometryTransform transformPipeline; // Geometry Transform Pipeline
GLFrame cameraFrame; // Camera frame

GLTriangleBatch torusBatch;
GLTriangleBatch sphereBatch;
GLBatch floorBatch;

GLuint uiTextures[3];

static const TCHAR g_szAppName[] = TEXT("Sphere World Redux");
static const TCHAR g_szClassName[50] = TEXT("OGL_CLASS");

static const int g_nWinWidth = 800;
static const int g_nWinHeight = 600;

HWND g_hWnd;
HGLRC g_hRC;
HDC g_hDC;
HINSTANCE g_hInstance;
WNDCLASS g_windClass;
RECT g_windowRect;
bool g_ContinueRendering;
bool g_InFullScreen;

void DrawSongAndDance(GLfloat yRot) // Called to draw dancing objects
{
static GLfloat vWhite[] = { 1.0f, 1.0f, 1.0f, 1.0f };
static GLfloat vLightPos[] = { 0.0f, 3.0f, 0.0f, 1.0f };

// Get the light position in eye space
M3DVector4f vLightTransformed;
M3DMatrix44f mCamera;
modelViewMatrix.GetMatrix(mCamera);
m3dTransformVector4(vLightTransformed, vLightPos, mCamera);

// Draw the light source
modelViewMatrix.PushMatrix();
modelViewMatrix.Translatev(vLightPos);
shaderManager.UseStockShader(GLT_SHADER_FLAT,
transformPipeline.GetModelViewProjectionMatrix(),
vWhite);
sphereBatch.Draw();
modelViewMatrix.PopMatrix();

glBindTexture(GL_TEXTURE_2D, uiTextures[2]);
for(int i = 0; i < NUM_SPHERES; i++) {
modelViewMatrix.PushMatrix();
modelViewMatrix.Rotate(yRot/(i), 0.0f, 1.0f, 0.0f);
modelViewMatrix.MultMatrix(spheres[i]);
shaderManager.UseStockShader(GLT_SHADER_TEXTURE_POINT_LIGHT_DIFF,
modelViewMatrix.GetMatrix(),
transformPipeline.GetProjectionMatrix(),
vLightTransformed,
vWhite,
0);
sphereBatch.Draw();
modelViewMatrix.PopMatrix();
}

// Song and dance
modelViewMatrix.Translate(0.0f, 0.2f, -2.5f);
modelViewMatrix.PushMatrix(); // Saves the translated origin
modelViewMatrix.Rotate(yRot, 0.0f, 1.0f, 0.0f);

// Draw stuff relative to the camera
glBindTexture(GL_TEXTURE_2D, uiTextures[1]);
shaderManager.UseStockShader(GLT_SHADER_TEXTURE_POINT_LIGHT_DIFF,
modelViewMatrix.GetMatrix(),
transformPipeline.GetProjectionMatrix(),
vLightTransformed,
vWhite,
0);
torusBatch.Draw();
modelViewMatrix.PopMatrix(); // Erased the rotate

modelViewMatrix.Rotate(yRot * -2.0f, 0.0f, 1.0f, 0.0f);
modelViewMatrix.Translate(0.8f, 0.0f, 0.0f);

glBindTexture(GL_TEXTURE_2D, uiTextures[2]);
shaderManager.UseStockShader(GLT_SHADER_TEXTURE_POINT_LIGHT_DIFF,
modelViewMatrix.GetMatrix(),
transformPipeline.GetProjectionMatrix(),
vLightTransformed,
vWhite,
0);
sphereBatch.Draw();
}

bool LoadTGATexture(const char *szFileName, GLenum minFilter, GLenum magFilter, GLenum wrapMode)
{
GLbyte *pBits;
int nWidth, nHeight, nComponents;
GLenum eFormat;

// Read the texture bits
pBits = gltReadTGABits(szFileName, &nWidth, &nHeight, &nComponents, &eFormat);
if(pBits == NULL)
return false;

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGB, nWidth, nHeight, 0,
eFormat, GL_UNSIGNED_BYTE, pBits);

free(pBits);

if(minFilter == GL_LINEAR_MIPMAP_LINEAR ||
minFilter == GL_LINEAR_MIPMAP_NEAREST ||
minFilter == GL_NEAREST_MIPMAP_LINEAR ||
minFilter == GL_NEAREST_MIPMAP_NEAREST)
glGenerateMipmap(GL_TEXTURE_2D);

return true;
}

//////////////////////////////////////////////////////////////////
// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Initialze Shader Manager
shaderManager.InitializeStockShaders();

glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);

glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

// This makes a torus
gltMakeTorus(torusBatch, 0.4f, 0.15f, 40, 20);

// This makes a sphere
gltMakeSphere(sphereBatch, 0.1f, 26, 13);


// Make the solid ground
GLfloat texSize = 10.0f;
floorBatch.Begin(GL_TRIANGLE_FAN, 4, 1);
floorBatch.MultiTexCoord2f(0, 0.0f, 0.0f);
floorBatch.Vertex3f(-20.0f, -0.41f, 20.0f);

floorBatch.MultiTexCoord2f(0, texSize, 0.0f);
floorBatch.Vertex3f(20.0f, -0.41f, 20.0f);

floorBatch.MultiTexCoord2f(0, texSize, texSize);
floorBatch.Vertex3f(20.0f, -0.41f, -20.0f);

floorBatch.MultiTexCoord2f(0, 0.0f, texSize);
floorBatch.Vertex3f(-20.0f, -0.41f, -20.0f);
floorBatch.End();

// Make 3 texture objects
glGenTextures(3, uiTextures);

// Load the Marble
glBindTexture(GL_TEXTURE_2D, uiTextures[0]);
LoadTGATexture("marble.tga", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_REPEAT);

// Load Mars
glBindTexture(GL_TEXTURE_2D, uiTextures[1]);
LoadTGATexture("marslike.tga", GL_LINEAR_MIPMAP_LINEAR,
GL_LINEAR, GL_CLAMP_TO_EDGE);

// Load Moon
glBindTexture(GL_TEXTURE_2D, uiTextures[2]);
LoadTGATexture("moonlike.tga", GL_LINEAR_MIPMAP_LINEAR,
GL_LINEAR, GL_CLAMP_TO_EDGE);

// Randomly place the spheres
for(int i = 0; i < NUM_SPHERES; i++) {
GLfloat x = ((GLfloat)((rand() % 400) - 200) * 0.1f);
GLfloat z = ((GLfloat)((rand() % 400) - 200) * 0.1f);
spheres[i].SetOrigin(x, 0.0f, z);
}
}

void CheckErrors(GLuint progName = 0)
{
GLenum error = glGetError();

if (error != GL_NO_ERROR)
{
fprintf(stderr, "A GL Error has occured\n");
}

GLenum fboStatus = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);

if(fboStatus != GL_FRAMEBUFFER_COMPLETE)
{
switch (fboStatus)
{
case GL_FRAMEBUFFER_UNDEFINED:
// Oops, no window exists?
MessageBox(NULL, TEXT("GL_FRAMEBUFFER_UNDEFINED"), g_szAppName, MB_OK|MB_ICONEXCLAMATION);
break;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
// Check the status of each attachment
MessageBox(NULL, TEXT("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"), g_szAppName, MB_OK|MB_ICONEXCLAMATION);
break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
// Attach at least one buffer to the FBO
MessageBox(NULL, TEXT("GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"), g_szAppName, MB_OK|MB_ICONEXCLAMATION);
break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
// Check that all attachments enabled via
// glDrawBuffers exist in FBO
MessageBox(NULL, TEXT("GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"), g_szAppName, MB_OK|MB_ICONEXCLAMATION);
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
// Check that the buffer specified via
// glReadBuffer exists in FBO
MessageBox(NULL, TEXT("GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"), g_szAppName, MB_OK|MB_ICONEXCLAMATION);
break;
case GL_FRAMEBUFFER_UNSUPPORTED:
// Reconsider formats used for attached buffers
MessageBox(NULL, TEXT("GL_FRAMEBUFFER_UNSUPPORTED"), g_szAppName, MB_OK|MB_ICONEXCLAMATION);
break;
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
// Make sure the number of samples for each
// attachment is the same
MessageBox(NULL, TEXT("GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"), g_szAppName, MB_OK|MB_ICONEXCLAMATION);
break;
//case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:
// Make sure the number of layers for each
// attachment is the same
//break;
}
fprintf(stderr,"The framebuffer is not complete\n");
}

if (progName != 0)
{
glValidateProgram(progName);
int iIsProgValid = 0;
glGetProgramiv(progName, GL_VALIDATE_STATUS, &iIsProgValid);
if(iIsProgValid == 0)
{
MessageBox(NULL, TEXT("The current program is not valid\n"), g_szAppName, MB_YESNO|MB_ICONEXCLAMATION);
fprintf(stderr,"The current program is not valid\n");
}
}
}

// Called to draw scene
void RenderScene(void)
{
if(!g_ContinueRendering)
return;

static CStopWatch rotTimer;
float yRot = rotTimer.GetElapsedSeconds() * 60.0f;


glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

modelViewMatrix.PushMatrix();
M3DMatrix44f mCamera;
cameraFrame.GetCameraMatrix(mCamera);
modelViewMatrix.MultMatrix(mCamera);

// Draw the world upside down
modelViewMatrix.PushMatrix();
modelViewMatrix.Scale(1.0f, -1.0f, 1.0f); // Flips the Y Axis
modelViewMatrix.Translate(0.0f, 0.8f, 0.0f); // Scootch the world down a bit...
glFrontFace(GL_CW);
DrawSongAndDance(yRot);
glFrontFace(GL_CCW);
modelViewMatrix.PopMatrix();

// Draw the solid ground
glEnable(GL_BLEND);
glBindTexture(GL_TEXTURE_2D, uiTextures[0]);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
static GLfloat vFloorColor[] = { 1.0f, 1.0f, 1.0f, 0.75f};
shaderManager.UseStockShader(GLT_SHADER_TEXTURE_MODULATE,
transformPipeline.GetModelViewProjectionMatrix(),
vFloorColor,
0);

floorBatch.Draw();
glDisable(GL_BLEND);


DrawSongAndDance(yRot);

modelViewMatrix.PopMatrix();

// Do the buffer Swap
SwapBuffers(g_hDC);

CheckErrors();
}

// Respond to arrow keys by moving the camera frame of reference
void SpecialKeys(int key, int x = 0, int y = 0)
{
float linear = 0.1f;
float angular = float(m3dDegToRad(5.0f));

if(key == VK_UP)
cameraFrame.MoveForward(linear);

if(key == VK_DOWN)
cameraFrame.MoveForward(-linear);

if(key == VK_LEFT)
cameraFrame.RotateWorld(angular, 0.0f, 1.0f, 0.0f);

if(key == VK_RIGHT)
cameraFrame.RotateWorld(-angular, 0.0f, 1.0f, 0.0f);

if(key == VK_PRIOR)
cameraFrame.MoveUp(linear);

if(key == VK_NEXT)
cameraFrame.MoveUp(-linear);

if(key == VK_ESCAPE ||key == 'q' || key == 'Q')
{
g_ContinueRendering = false;
PostQuitMessage(0);
}
}

void ChangeSize(int nWidth, int nHeight)
{
glViewport(0, 0, nWidth, nHeight);
transformPipeline.SetMatrixStacks(modelViewMatrix, projectionMatrix);

viewFrustum.SetPerspective(35.0f, float(nWidth)/float(nHeight), 1.0f, 100.0f);
projectionMatrix.LoadMatrix(viewFrustum.GetProjectionMatrix());
modelViewMatrix.LoadIdentity();
}

///////////////////////////////////////////////////////////////////////////////
// Callback functions to handle all window functions this app cares about.
// Once complete, pass message on to next app in the hook chain.
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
{
// Handle relevant messages individually
switch(uMsg)
{
case WM_ACTIVATE:
case WM_SETFOCUS:
RenderScene();
return 0;
case WM_SIZE:
ChangeSize(LOWORD(lParam),HIWORD(lParam));
RenderScene();
break;
case WM_CLOSE:
g_ContinueRendering = false;
PostQuitMessage(0);
return 0;
case WM_KEYDOWN:
SpecialKeys((unsigned int)wParam);
return 0;
default:
// Nothing to do now
break;
}

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

///////////////////////////////////////////////////////////////////////////////
// Setup the actual window and related state.
// Create the window, find a pixel format, create the OpenGL context
bool SetupWindow(int nWidth, int nHeight, bool bUseFS)
{
bool bRetVal = true;

int nWindowX = 0;
int nWindowY = 0;
int nPixelFormat = NULL;
PIXELFORMATDESCRIPTOR pfd;

DWORD dwExtStyle;
DWORD dwWindStyle;

HINSTANCE g_hInstance = GetModuleHandle(NULL);

// setup window class
g_windClass.lpszClassName = g_szClassName; // Set the name of the Class
g_windClass.lpfnWndProc = (WNDPROC)WndProc;
g_windClass.hInstance = g_hInstance; // Use this module for the module handle
g_windClass.hCursor = LoadCursor(NULL, IDC_ARROW);// Pick the default mouse cursor
g_windClass.hIcon = LoadIcon(NULL, IDI_WINLOGO);// Pick the default windows icons
g_windClass.hbrBackground = NULL; // No Background
g_windClass.lpszMenuName = NULL; // No menu for this window
g_windClass.style = CS_HREDRAW | CS_OWNDC | // set styles for this class, specifically to catch
CS_VREDRAW; // window redraws, unique DC, and resize
g_windClass.cbClsExtra = 0; // Extra class memory
g_windClass.cbWndExtra = 0; // Extra window memory

// Register the newly defined class
if(!RegisterClass( &g_windClass ))
bRetVal = false;

dwExtStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
dwWindStyle = WS_OVERLAPPEDWINDOW;
ShowCursor(TRUE);

g_windowRect.left = nWindowX;
g_windowRect.right = nWindowX + nWidth;
g_windowRect.top = nWindowY;
g_windowRect.bottom = nWindowY + nHeight;

// Setup window width and height
AdjustWindowRectEx(&g_windowRect, dwWindStyle, FALSE, dwExtStyle);

//Adjust for adornments
int nWindowWidth = g_windowRect.right - g_windowRect.left;
int nWindowHeight = g_windowRect.bottom - g_windowRect.top;

// Create window
g_hWnd = CreateWindowEx(dwExtStyle, // Extended style
g_szClassName, // class name
g_szAppName, // window name
dwWindStyle |
WS_CLIPSIBLINGS |
WS_CLIPCHILDREN,// window stlye
nWindowX, // window position, x
nWindowY, // window position, y
nWindowWidth, // height
nWindowHeight, // width
NULL, // Parent window
NULL, // menu
g_hInstance, // instance
NULL); // pass this to WM_CREATE

// now that we have a window, setup the pixel format descriptor
g_hDC = GetDC(g_hWnd);

// Set a dummy pixel format so that we can get access to wgl functions
SetPixelFormat( g_hDC, 1,&pfd);
// Create OGL context and make it current
g_hRC = wglCreateContext( g_hDC );
wglMakeCurrent( g_hDC, g_hRC );

if (g_hDC == 0 ||
g_hDC == 0)
{
bRetVal = false;
MessageBox(NULL,
TEXT("!!! An error accured creating an OpenGL window.\n"),
TEXT("ERROR"),
MB_OK|MB_ICONEXCLAMATION);
}

// Setup GLEW which loads OGL function pointers
GLenum err = glewInit();
if (GLEW_OK != err)
{
/* Problem: glewInit failed, something is seriously wrong. */
bRetVal = false;
printf("Error: %s\n", glewGetErrorString(err));
}
const GLubyte *oglVersion = glGetString(GL_VERSION);
printf("This system supports OpenGL Version %s.\n", oglVersion);

// Now that extensions are setup, delete window and start over picking a real format.
wglMakeCurrent(NULL, NULL);
wglDeleteContext(g_hRC);
ReleaseDC(g_hWnd, g_hDC);
DestroyWindow(g_hWnd);

if(bUseFS)
{
// Prepare for a mode set to the requested resolution
DEVMODE dm;
memset(&dm,0,sizeof(dm));
dm.dmSize=sizeof(dm);
dm.dmPelsWidth = nWidth;
dm.dmPelsHeight = nHeight;
dm.dmBitsPerPel = 32;
dm.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

long error = ChangeDisplaySettings(&dm, CDS_FULLSCREEN);

if (error != DISP_CHANGE_SUCCESSFUL)
{
// Oops, something went wrong, let the user know.
if (MessageBox(NULL, TEXT("Could not set fullscreen mode.\n\
Your video card may not support the requested mode.\n\
Use windowed mode instead?"),
g_szAppName, MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
{
g_InFullScreen = false;
dwExtStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
dwWindStyle = WS_OVERLAPPEDWINDOW;
}
else
{
MessageBox(NULL, TEXT("Program will exit."), TEXT("ERROR"), MB_OK|MB_ICONSTOP);
return false;
}
}
else
{
// Mode set passed, setup the styles for fullscreen
g_InFullScreen = true;
dwExtStyle = WS_EX_APPWINDOW;
dwWindStyle = WS_POPUP;
ShowCursor(FALSE);
}
}

AdjustWindowRectEx(&g_windowRect, dwWindStyle, FALSE, dwExtStyle);

// Create the window again
g_hWnd = CreateWindowEx(dwExtStyle, // Extended style
g_szClassName, // class name
g_szAppName, // window name
dwWindStyle |
WS_CLIPSIBLINGS |
WS_CLIPCHILDREN,// window stlye
nWindowX, // window position, x
nWindowY, // window position, y
nWindowWidth, // height
nWindowHeight, // width
NULL, // Parent window
NULL, // menu
g_hInstance, // instance
NULL); // pass this to WM_CREATE

g_hDC = GetDC(g_hWnd);

int nPixCount = 0;

// Specify the important attributes we care about
int pixAttribs[] = { WGL_SUPPORT_OPENGL_ARB, 1, // Must support OGL rendering
WGL_DRAW_TO_WINDOW_ARB, 1, // pf that can run a window
WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, // must be HW accelerated
WGL_COLOR_BITS_ARB, 24, // 8 bits of each R, G and B
WGL_DEPTH_BITS_ARB, 16, // 16 bits of depth precision for window
WGL_DOUBLE_BUFFER_ARB, GL_TRUE, // Double buffered context
WGL_SAMPLE_BUFFERS_ARB, GL_TRUE, // MSAA on
WGL_SAMPLES_ARB, 8, // 8x MSAA
WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, // pf should be RGBA type
0}; // NULL termination

// Ask OpenGL to find the most relevant format matching our attribs
// Only get one format back.
wglChoosePixelFormatARB(g_hDC, pixAttribs, NULL, 1, &nPixelFormat, (UINT*)&nPixCount);

/*
// Uncomment to print a list of all supported pixel formats
// Enumerate supported pixel formats
GLint pfAttribCount[] = {WGL_NUMBER_PIXEL_FORMATS_ARB};
GLint pfAttribList[] = { WGL_DRAW_TO_WINDOW_ARB,
WGL_ACCELERATION_ARB,
WGL_SUPPORT_OPENGL_ARB,
WGL_DOUBLE_BUFFER_ARB,
WGL_DEPTH_BITS_ARB,
WGL_STENCIL_BITS_ARB,
WGL_RED_BITS_ARB,
WGL_GREEN_BITS_ARB,
WGL_BLUE_BITS_ARB,
WGL_ALPHA_BITS_ARB
};
int nPixelFormatCount = 0;
wglGetPixelFormatAttribivARB(g_hDC, 1, 0, 1, pfAttribCount, &nPixelFormatCount);
for (int i=0; i<nPixelFormatCount; i++)
{
GLint results[10];
printf("Pixel format %d details:\n", nPixelFormatCount);
wglGetPixelFormatAttribivARB(g_hDC, i, 0, 10, pfAttribList, results);
printf(" Draw to Window = %d:\n", results[0]);
printf(" HW Accelerated = %d:\n", results[1]);
printf(" Supports OpenGL = %d:\n", results[2]);
printf(" Double Buffered = %d:\n", results[3]);
printf(" Depth Bits = %d:\n", results[4]);
printf(" Stencil Bits = %d:\n", results[5]);
printf(" Red Bits = %d:\n", results[6]);
printf(" Green Bits = %d:\n", results[7]);
printf(" Blue Bits = %d:\n", results[8]);
printf(" Alpha Bits = %d:\n", results[9]);
}
*/

if(nPixelFormat == NULL)
{
MessageBox(NULL,
TEXT("!!! An error occurred trying to find a MSAA pixel format with the requested attribs.\n"),
TEXT("ERROR"),
MB_OK|MB_ICONEXCLAMATION);

// Try again without MSAA
pixAttribs[15] = 1;
wglChoosePixelFormatARB(g_hDC, pixAttribs, NULL, 1, &nPixelFormat, (UINT*)&nPixCount);

if(nPixelFormat == NULL)
{
// Couldn't find a format, perhaps no 3D HW or drivers are installed
g_hDC = 0;
g_hDC = 0;
bRetVal = false;
MessageBox(NULL,
TEXT("!!! An error occurred trying to find a pixel format with the requested attribs.\n"),
TEXT("ERROR"),
MB_OK|MB_ICONEXCLAMATION);
}
}

if(nPixelFormat != NULL)
{
// Check for MSAA
int attrib[] = { WGL_SAMPLES_ARB };
int nResults = 0;
wglGetPixelFormatAttribivARB(g_hDC, nPixelFormat, 0, 1, attrib, &nResults);
printf("Chosen pixel format is MSAA with %d samples.\n", nResults);

// Got a format, now set it as the current one
SetPixelFormat( g_hDC, nPixelFormat, &pfd );

GLint attribs[] = {WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
WGL_CONTEXT_MINOR_VERSION_ARB, 3,
0 };

g_hRC = wglCreateContextAttribsARB(g_hDC, 0, attribs);
if (g_hRC == NULL)
{
MessageBox(NULL,
TEXT("!!! Could not create an OpenGL 3.3 context.\n"),
TEXT("ERROR"),
MB_OK|MB_ICONEXCLAMATION);

attribs[3] = 2;
g_hRC = wglCreateContextAttribsARB(g_hDC, 0, attribs);

if (g_hRC == NULL)
{
MessageBox(NULL,
TEXT("!!! Could not create an OpenGL 3.2 context.\n"),
TEXT("ERROR"),
MB_OK|MB_ICONEXCLAMATION);

attribs[3] = 1;
g_hRC = wglCreateContextAttribsARB(g_hDC, 0, attribs);

if (g_hRC == NULL)
{
MessageBox(NULL,
TEXT("!!! Could not create an OpenGL 3.1 context.\n"),
TEXT("ERROR"),
MB_OK|MB_ICONEXCLAMATION);

attribs[3] = 0;
g_hRC = wglCreateContextAttribsARB(g_hDC, 0, attribs);

if (g_hRC == NULL)
{
MessageBox(NULL,
TEXT("!!! Could not create an OpenGL 3.0 context.\n!!! OpenGL 3.0 and higher are not supported on this system.\n"),
TEXT("ERROR"),
MB_OK|MB_ICONEXCLAMATION);
}
}
}
}

wglMakeCurrent( g_hDC, g_hRC );
}

if (g_hDC == 0 ||
g_hDC == 0)
{
bRetVal = false;
MessageBox(NULL,
TEXT("!!! An error occured creating an OpenGL window."),
TEXT("ERROR"),
MB_OK|MB_ICONEXCLAMATION);
}

// If everything went as planned, display the window
if( bRetVal )
{
ShowWindow( g_hWnd, SW_SHOW );
SetForegroundWindow( g_hWnd );
SetFocus( g_hWnd );
g_ContinueRendering = true;
}

return bRetVal;
}

///////////////////////////////////////////////////////////////////////////////
// Cleanup window, OGL context and related state
// Called on exit and on error
bool KillWindow( )
{
bool bRetVal = true;

glDeleteTextures(3, uiTextures);

if (g_InFullScreen)
{
ChangeDisplaySettings(NULL,0);
ShowCursor(TRUE);
}
//Cleanup OGL RC
if(g_hRC)
{
wglMakeCurrent(NULL, NULL);
wglDeleteContext(g_hRC);
g_hRC = NULL;
}

// release the DC
if(g_hDC)
{
ReleaseDC(g_hWnd, g_hDC);
g_hDC = NULL;
}

// Destroy the window
if(g_hWnd)
{
DestroyWindow(g_hWnd);
g_hWnd = NULL;;
}

// Delete the window class
UnregisterClass(g_szClassName, g_hInstance);
g_hInstance = NULL;
ShowCursor(TRUE);
return bRetVal;
}

///////////////////////////////////////////////////////////////////////////////
// Main rendering loop
// Check for window messages and handle events, also draw scene
void mainLoop()
{
MSG msg;

// Check for waiting mssgs
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
if (msg.message==WM_QUIT)
{
g_ContinueRendering = false;
}
else
{
// Deal with mssgs
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
RenderScene();
}
}

///////////////////////////////////////////////////////////////////////////////
// Main program function, called on startup
// First setup the window and OGL state, then enter rendering loop
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)
{
gltSetWorkingDirectory(szCmdLine);

bool bUseFS = false;
if (MessageBox(NULL, TEXT("Would you like to run in Fullscreen Mode?"), g_szAppName, MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
{
bUseFS = true;
}

if(SetupWindow(g_nWinWidth, g_nWinHeight, bUseFS))
{
SetupRC();
ChangeSize(g_nWinWidth, g_nWinHeight);
while (g_ContinueRendering)
{
mainLoop();
Sleep(0);
}
}
KillWindow();
return 0;
}
[/code]

The main problem that prevented the program from finding a pixel format was that the WGL_ACCELERATION_ARB attribute needed to be set to WGL_FULL_ACCELERATION_ARB, not just 1! I also made some fixes that took away the black screen issue that you would see even after that problem.

Sorry for reviving an old thread, but I think that this solution will help you and others using the SuperBible code repository. Hope this helps.
2

Share this post


Link to post
Share on other sites
wow awesome! I still get only a black screen using the fixed code, but i got my window! I swapped in other openGL code and have that running using thta as a window though! Thanks a bunch! I really appretiate it!
0

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  
Followers 0

  • Similar Content

    • By Solid_Spy
      Hello, I have been working on SH Irradiance map rendering, and I have been using a GLSL pixel shader to render SH irradiance to 2D irradiance maps for my static objects. I already have it working with 9 3D textures so far for the first 9 SH functions.
      In my GLSL shader, I have to send in 9 SH Coefficient 3D Texures that use RGBA8 as a pixel format. RGB being used for the coefficients for red, green, and blue, and the A for checking if the voxel is in use (for the 3D texture solidification shader to prevent bleeding).
      My problem is, I want to knock this number of textures down to something like 4 or 5. Getting even lower would be a godsend. This is because I eventually plan on adding more SH Coefficient 3D Textures for other parts of the game map (such as inside rooms, as opposed to the outside), to circumvent irradiance probe bleeding between rooms separated by walls. I don't want to reach the 32 texture limit too soon. Also, I figure that it would be a LOT faster.
      Is there a way I could, say, store 2 sets of SH Coefficients for 2 SH functions inside a texture with RGBA16 pixels? If so, how would I extract them from inside GLSL? Let me know if you have any suggestions ^^.
    • By KarimIO
      EDIT: I thought this was restricted to Attribute-Created GL contexts, but it isn't, so I rewrote the post.
      Hey guys, whenever I call SwapBuffers(hDC), I get a crash, and I get a "Too many posts were made to a semaphore." from Windows as I call SwapBuffers. What could be the cause of this?
      Update: No crash occurs if I don't draw, just clear and swap.
      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 32, // 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 24, // 24Bit 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(windowHandle))) return false; unsigned int PixelFormat; if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) return false; if (!SetPixelFormat(hDC, PixelFormat, &pfd)) return false; hRC = wglCreateContext(hDC); if (!hRC) { std::cout << "wglCreateContext Failed!\n"; return false; } if (wglMakeCurrent(hDC, hRC) == NULL) { std::cout << "Make Context Current Second Failed!\n"; return false; } ... // OGL Buffer Initialization glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glBindVertexArray(vao); glUseProgram(myprogram); glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (void *)indexStart); SwapBuffers(GetDC(window_handle));  
    • By Tchom
      Hey devs!
       
      I've been working on a OpenGL ES 2.0 android engine and I have begun implementing some simple (point) lighting. I had something fairly simple working, so I tried to get fancy and added color-tinting light. And it works great... with only one or two lights. Any more than that, the application drops about 15 frames per light added (my ideal is at least 4 or 5). I know implementing lighting is expensive, I just didn't think it was that expensive. I'm fairly new to the world of OpenGL and GLSL, so there is a good chance I've written some crappy shader code. If anyone had any feedback or tips on how I can optimize this code, please let me know.
       
      Vertex Shader
      uniform mat4 u_MVPMatrix; uniform mat4 u_MVMatrix; attribute vec4 a_Position; attribute vec3 a_Normal; attribute vec2 a_TexCoordinate; varying vec3 v_Position; varying vec3 v_Normal; varying vec2 v_TexCoordinate; void main() { v_Position = vec3(u_MVMatrix * a_Position); v_TexCoordinate = a_TexCoordinate; v_Normal = vec3(u_MVMatrix * vec4(a_Normal, 0.0)); gl_Position = u_MVPMatrix * a_Position; } Fragment Shader
      precision mediump float; uniform vec4 u_LightPos["+numLights+"]; uniform vec4 u_LightColours["+numLights+"]; uniform float u_LightPower["+numLights+"]; uniform sampler2D u_Texture; varying vec3 v_Position; varying vec3 v_Normal; varying vec2 v_TexCoordinate; void main() { gl_FragColor = (texture2D(u_Texture, v_TexCoordinate)); float diffuse = 0.0; vec4 colourSum = vec4(1.0); for (int i = 0; i < "+numLights+"; i++) { vec3 toPointLight = vec3(u_LightPos[i]); float distance = length(toPointLight - v_Position); vec3 lightVector = normalize(toPointLight - v_Position); float diffuseDiff = 0.0; // The diffuse difference contributed from current light diffuseDiff = max(dot(v_Normal, lightVector), 0.0); diffuseDiff = diffuseDiff * (1.0 / (1.0 + ((1.0-u_LightPower[i])* distance * distance))); //Determine attenuatio diffuse += diffuseDiff; gl_FragColor.rgb *= vec3(1.0) / ((vec3(1.0) + ((vec3(1.0) - vec3(u_LightColours[i]))*diffuseDiff))); //The expensive part } diffuse += 0.1; //Add ambient light gl_FragColor.rgb *= diffuse; } Am I making any rookie mistakes? Or am I just being unrealistic about what I can do? Thanks in advance
    • By yahiko00
      Hi,
      Not sure to post at the right place, if not, please forgive me...
      For a game project I am working on, I would like to implement a 2D starfield as a background.
      I do not want to deal with static tiles, since I plan to slowly animate the starfield. So, I am trying to figure out how to generate a random starfield for the entire map.
      I feel that using a uniform distribution for the stars will not do the trick. Instead I would like something similar to the screenshot below, taken from the game Star Wars: Empire At War (all credits to Lucasfilm, Disney, and so on...).

      Is there someone who could have an idea of a distribution which could result in such a starfield?
      Any insight would be appreciated
    • By afraidofdark
      I have just noticed that, in quake 3 and half - life, dynamic models are effected from light map. For example in dark areas, gun that player holds seems darker. How did they achieve this effect ? I can use image based lighting techniques however (Like placing an environment probe and using it for reflections and ambient lighting), this tech wasn't used in games back then, so there must be a simpler method to do this.
      Here is a link that shows how modern engines does it. Indirect Lighting Cache It would be nice if you know a paper that explains this technique. Can I apply this to quake 3' s light map generator and bsp format ?
  • Popular Now