
#include<windows.h>//HeaderFileForWindows
#include<gl/gl.h>//HeaderFileForTheOpenGL32Library
#include<gl/glu.h>//HeaderFileForTheGLu32Library
#include<gl/glaux.h>//HeaderFileForTheGlauxLibrary
HDChDC=NULL;//PrivateGDIDeviceContext
HGLRChRC=NULL;//PermanentRenderingContext
HWNDhWnd=NULL;//HoldsOurWindowHandle
HINSTANCEhInstance;//HoldsTheInstanceOfTheApplication
boolkeys[256];//ArrayUsedForTheKeyboardRoutine
boolactive=TRUE;//WindowActiveFlagSetToTRUEByDefault
boolfullscreen=TRUE;//FullscreenFlagSetToFullscreenModeByDefault
LRESULTCALLBACKWndProc(HWND,UINT,WPARAM,LPARAM);//DeclarationForWndProc
GLvoidReSizeGLScene(GLsizeiwidth,GLsizeiheight)//ResizeAndInitializeTheGLWindow

{
if(height==0)//PreventADivideByZeroBy

{
height=1;//MakingHeightEqualOne
}
glViewport(0,0,width,height);//ResetTheCurrentViewport
glMatrixMode(GL_PROJECTION);//SelectTheProjectionMatrix
glLoadIdentity();//ResetTheProjectionMatrix
//CalculateTheAspectRatioOfTheWindow
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW);//SelectTheModelviewMatrix
glLoadIdentity();//ResetTheModelviewMatrix
}
intInitGL(GLvoid)//AllSetupForOpenGLGoesHere

{
glShadeModel(GL_SMOOTH);//EnableSmoothShading
glClearColor(0.0f,0.0f,0.0f,0.5f);//BlackBackground
glClearDepth(1.0f);//DepthBufferSetup
glEnable(GL_DEPTH_TEST);//EnablesDepthTesting
glDepthFunc(GL_LEQUAL);//TheTypeOfDepthTestingToDo
glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);//ReallyNicePerspectiveCalculations
returnTRUE;//InitializationWentOK
}
intDrawGLScene(GLvoid)//Here'sWhereWeDoAllTheDrawing

{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);//ClearScreenAndDepthBuffer
glLoadIdentity();//ResetTheCurrentModelviewMatrix
returnTRUE;//EverythingWentOK
}
GLvoidKillGLWindow(GLvoid)//ProperlyKillTheWindow

{
if(fullscreen)//AreWeInFullscreenMode?

{
ChangeDisplaySettings(NULL,0);//IfSoSwitchBackToTheDesktop
ShowCursor(TRUE);//ShowMousePointer
}
if(hRC)//DoWeHaveARenderingContext?

{
if(!wglMakeCurrent(NULL,NULL))//AreWeAbleToReleaseTheDCAndRCContexts?

{
MessageBox(NULL,"ReleaseOfDCAndRCFailed.","SHUTDOWNERROR",MB_OK|MB_ICONINFORMATION);
}
if(!wglDeleteContext(hRC))//AreWeAbleToDeleteTheRC?

{
MessageBox(NULL,"ReleaseRenderingContextFailed.","SHUTDOWNERROR",MB_OK|MB_ICONINFORMATION);
}
hRC=NULL;//SetRCToNULL
}
if(hDC&&!ReleaseDC(hWnd,hDC))//AreWeAbleToReleaseTheDC

{
MessageBox(NULL,"ReleaseDeviceContextFailed.","SHUTDOWNERROR",MB_OK|MB_ICONINFORMATION);
hDC=NULL;//SetDCToNULL
}
if(hWnd&&!DestroyWindow(hWnd))//AreWeAbleToDestroyTheWindow?

{
MessageBox(NULL,"CouldNotReleasehWnd.","SHUTDOWNERROR",MB_OK|MB_ICONINFORMATION);
hWnd=NULL;//SethWndToNULL
}
if(!UnregisterClass("OpenGL",hInstance))//AreWeAbleToUnregisterClass

{
MessageBox(NULL,"CouldNotUnregisterClass.","SHUTDOWNERROR",MB_OK|MB_ICONINFORMATION);
hInstance=NULL;//SethInstanceToNULL
}
}

/**//*ThisCodeCreatesOurOpenGLWindow.ParametersAre:*
*title-TitleToAppearAtTheTopOfTheWindow*
*width-WidthOfTheGLWindowOrFullscreenMode*
*height-HeightOfTheGLWindowOrFullscreenMode*
*bits-NumberOfBitsToUseForColor(8/16/24/32)*
*fullscreenflag-UseFullscreenMode(TRUE)OrWindowedMode(FALSE)*/
BOOLCreateGLWindow(char*title,intwidth,intheight,intbits,boolfullscreenflag)

{
GLuintPixelFormat;//HoldsTheResultsAfterSearchingForAMatch
WNDCLASSwc;//WindowsClassStructure
DWORDdwExStyle;//WindowExtendedStyle
DWORDdwStyle;//WindowStyle
RECTWindowRect;//GrabsRectangleUpperLeft/LowerRightValues
WindowRect.left=(long)0;//SetLeftValueTo0
WindowRect.right=(long)width;//SetRightValueToRequestedWidth
WindowRect.top=(long)0;//SetTopValueTo0
WindowRect.bottom=(long)height;//SetBottomValueToRequestedHeight
fullscreen=fullscreenflag;//SetTheGlobalFullscreenFlag
hInstance=GetModuleHandle(NULL);//GrabAnInstanceForOurWindow
wc.style=CS_HREDRAW|CS_VREDRAW|CS_OWNDC;//RedrawOnSize,AndOwnDCForWindow.
wc.lpfnWndProc=(WNDPROC)WndProc;//WndProcHandlesMessages
wc.cbClsExtra=0;//NoExtraWindowData
wc.cbWndExtra=0;//NoExtraWindowData
wc.hInstance=hInstance;//SetTheInstance
wc.hIcon=LoadIcon(NULL,IDI_WINLOGO);//LoadTheDefaultIcon
wc.hCursor=LoadCursor(NULL,IDC_ARROW);//LoadTheArrowPointer
wc.hbrBackground=NULL;//NoBackgroundRequiredForGL
wc.lpszMenuName=NULL;//WeDon'tWantAMenu
wc.lpszClassName="OpenGL";//SetTheClassName
if(!RegisterClass(&wc))//AttemptToRegisterTheWindowClass

{
MessageBox(NULL,"FailedToRegisterTheWindowClass.","ERROR",MB_OK|MB_ICONEXCLAMATION);
returnFALSE;//ReturnFALSE
}
if(fullscreen)//AttemptFullscreenMode?

{
DEVMODEdmScreenSettings;//DeviceMode
memset(&dmScreenSettings,0,sizeof(dmScreenSettings));//MakesSureMemory'sCleared
dmScreenSettings.dmSize=sizeof(dmScreenSettings);//SizeOfTheDevmodeStructure
dmScreenSettings.dmPelsWidth=width;//SelectedScreenWidth
dmScreenSettings.dmPelsHeight=height;//SelectedScreenHeight
dmScreenSettings.dmBitsPerPel=bits;//SelectedBitsPerPixel
dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
//TryToSetSelectedModeAndGetResults.NOTE:CDS_FULLSCREENGetsRidOfStartBar.
if(ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)

{
//IfTheModeFails,OfferTwoOptions.QuitOrUseWindowedMode.
if(MessageBox(NULL,"TheRequestedFullscreenModeIsNotSupportedBy/nYourVideoCard.UseWindowedModeInstead?","NeHeGL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)

{
fullscreen=FALSE;//WindowedModeSelected.Fullscreen=FALSE
}
else

{
//PopUpAMessageBoxLettingUserKnowTheProgramIsClosing.
MessageBox(NULL,"ProgramWillNowClose.","ERROR",MB_OK|MB_ICONSTOP);
returnFALSE;//ReturnFALSE
}
}
}
if(fullscreen)//AreWeStillInFullscreenMode?

{
dwExStyle=WS_EX_APPWINDOW;//WindowExtendedStyle
dwStyle=WS_POPUP;//WindowsStyle
ShowCursor(FALSE);//HideMousePointer
}
else

{
dwExStyle=WS_EX_APPWINDOW|WS_EX_WINDOWEDGE;//WindowExtendedStyle
dwStyle=WS_OVERLAPPEDWINDOW;//WindowsStyle
}
AdjustWindowRectEx(&WindowRect,dwStyle,FALSE,dwExStyle);//AdjustWindowToTrueRequestedSize
//CreateTheWindow
if(!(hWnd=CreateWindowEx(dwExStyle,//ExtendedStyleForTheWindow
"OpenGL",//ClassName
title,//WindowTitle
dwStyle|//DefinedWindowStyle
WS_CLIPSIBLINGS|//RequiredWindowStyle
WS_CLIPCHILDREN,//RequiredWindowStyle
0,0,//WindowPosition
WindowRect.right-WindowRect.left,//CalculateWindowWidth
WindowRect.bottom-WindowRect.top,//CalculateWindowHeight
NULL,//NoParentWindow
NULL,//NoMenu
hInstance,//Instance
NULL)))//DontPassAnythingToWM_CREATE

{
KillGLWindow();//ResetTheDisplay
MessageBox(NULL,"WindowCreationError.","ERROR",MB_OK|MB_ICONEXCLAMATION);
returnFALSE;//ReturnFALSE
}
staticPIXELFORMATDESCRIPTORpfd=//pfdTellsWindowsHowWeWantThingsToBe

{
sizeof(PIXELFORMATDESCRIPTOR),//SizeOfThisPixelFormatDescriptor
1,//VersionNumber
PFD_DRAW_TO_WINDOW|//FormatMustSupportWindow
PFD_SUPPORT_OPENGL|//FormatMustSupportOpenGL
PFD_DOUBLEBUFFER,//MustSupportDoubleBuffering
PFD_TYPE_RGBA,//RequestAnRGBAFormat
bits,//SelectOurColorDepth
0,0,0,0,0,0,//ColorBitsIgnored
0,//NoAlphaBuffer
0,//ShiftBitIgnored
0,//NoAccumulationBuffer
0,0,0,0,//AccumulationBitsIgnored
16,//16BitZ-Buffer(DepthBuffer)
0,//NoStencilBuffer
0,//NoAuxiliaryBuffer
PFD_MAIN_PLANE,//MainDrawingLayer
0,//Reserved
0,0,0//LayerMasksIgnored
};
if(!(hDC=GetDC(hWnd)))//DidWeGetADeviceContext?

{
KillGLWindow();//ResetTheDisplay
MessageBox(NULL,"Can'tCreateAGLDeviceContext.","ERROR",MB_OK|MB_ICONEXCLAMATION);
returnFALSE;//ReturnFALSE
}
if(!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))//DidWindowsFindAMatchingPixelFormat?

{
KillGLWindow();//ResetTheDisplay
MessageBox(NULL,"Can'tFindASuitablePixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
returnFALSE;//ReturnFALSE
}
if(!SetPixelFormat(hDC,PixelFormat,&pfd))//AreWeAbleToSetThePixelFormat?

{
KillGLWindow();//ResetTheDisplay
MessageBox(NULL,"Can'tSetThePixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
returnFALSE;//ReturnFALSE
}
if(!(hRC=wglCreateContext(hDC)))//AreWeAbleToGetARenderingContext?

{
KillGLWindow();//ResetTheDisplay
MessageBox(NULL,"Can'tCreateAGLRenderingContext.","ERROR",MB_OK|MB_ICONEXCLAMATION);
returnFALSE;//ReturnFALSE
}
if(!wglMakeCurrent(hDC,hRC))//TryToActivateTheRenderingContext

{
KillGLWindow();//ResetTheDisplay
MessageBox(NULL,"Can'tActivateTheGLRenderingContext.","ERROR",MB_OK|MB_ICONEXCLAMATION);
returnFALSE;//ReturnFALSE
}
ShowWindow(hWnd,SW_SHOW);//ShowTheWindow
SetForegroundWindow(hWnd);//SlightlyHigherPriority
SetFocus(hWnd);//SetsKeyboardFocusToTheWindow
ReSizeGLScene(width,height);//SetUpOurPerspectiveGLScreen
if(!InitGL())//InitializeOurNewlyCreatedGLWindow

{
KillGLWindow();//ResetTheDisplay
MessageBox(NULL,"InitializationFailed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
returnFALSE;//ReturnFALSE
}
returnTRUE;//Success
}
LRESULTCALLBACKWndProc(HWNDhWnd,//HandleForThisWindow
UINTuMsg,//MessageForThisWindow
WPARAMwParam,//AdditionalMessageInformation
LPARAMlParam)//AdditionalMessageInformation

{
switch(uMsg)//CheckForWindowsMessages

{
caseWM_ACTIVATE://WatchForWindowActivateMessage

{
if(!HIWORD(wParam))//CheckMinimizationState

{
active=TRUE;//ProgramIsActive
}
else

{
active=FALSE;//ProgramIsNoLongerActive
}
return0;//ReturnToTheMessageLoop
}
caseWM_SYSCOMMAND://InterceptSystemCommands

{
switch(wParam)//CheckSystemCalls

{
caseSC_SCREENSAVE://ScreensaverTryingToStart?
caseSC_MONITORPOWER://MonitorTryingToEnterPowersave?
return0;//PreventFromHappening
}
break;//Exit
}
caseWM_CLOSE://DidWeReceiveACloseMessage?

{
PostQuitMessage(0);//SendAQuitMessage
return0;//JumpBack
}
caseWM_KEYDOWN://IsAKeyBeingHeldDown?

{
keys[wParam]=TRUE;//IfSo,MarkItAsTRUE
return0;//JumpBack
}
caseWM_KEYUP://HasAKeyBeenReleased?

{
keys[wParam]=FALSE;//IfSo,MarkItAsFALSE
return0;//JumpBack
}
caseWM_SIZE://ResizeTheOpenGLWindow

{
ReSizeGLScene(LOWORD(lParam),HIWORD(lParam));//LoWord=Width,HiWord=Height
return0;//JumpBack
}
}
//PassAllUnhandledMessagesToDefWindowProc
returnDefWindowProc(hWnd,uMsg,wParam,lParam);
}
intWINAPIWinMain(HINSTANCEhInstance,//Instance
HINSTANCEhPrevInstance,//PreviousInstance
LPSTRlpCmdLine,//CommandLineParameters
intnCmdShow)//WindowShowState

{
MSGmsg;//WindowsMessageStructure
BOOLdone=FALSE;//BoolVariableToExitLoop
//AskTheUserWhichScreenModeTheyPrefer
if(MessageBox(NULL,"WouldYouLikeToRunInFullscreenMode?","StartFullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)

{
fullscreen=FALSE;//WindowedMode
}
//CreateOurOpenGLWindow
if(!CreateGLWindow("NeHe'sOpenGLFramework",640,480,16,fullscreen))

{
return0;//QuitIfWindowWasNotCreated
}
while(!done)//LoopThatRunsWhiledone=FALSE

{
if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))//IsThereAMessageWaiting?

{
if(msg.message==WM_QUIT)//HaveWeReceivedAQuitMessage?

{
done=TRUE;//IfSodone=TRUE
}
else//IfNot,DealWithWindowMessages

{
TranslateMessage(&msg);//TranslateTheMessage
DispatchMessage(&msg);//DispatchTheMessage
}
}
else//IfThereAreNoMessages

{
//DrawTheScene.WatchForESCKeyAndQuitMessagesFromDrawGLScene()
if(active)//ProgramActive?

{
if(keys[VK_ESCAPE])//WasESCPressed?

{
done=TRUE;//ESCSignalledAQuit
}
else//NotTimeToQuit,UpdateScreen

{
DrawGLScene();//DrawTheScene
SwapBuffers(hDC);//SwapBuffers(DoubleBuffering)
}
}
if(keys[VK_F1])//IsF1BeingPressed?

{
keys[VK_F1]=FALSE;//IfSoMakeKeyFALSE
KillGLWindow();//KillOurCurrentWindow
fullscreen=!fullscreen;//ToggleFullscreen/WindowedMode
//RecreateOurOpenGLWindow
if(!CreateGLWindow("NeHe'sOpenGLFramework",640,480,16,fullscreen))

{
return0;//QuitIfWindowWasNotCreated
}
}
}
}
//Shutdown
KillGLWindow();//KillTheWindow
return(msg.wParam);//ExitTheProgram
}
本文介绍了一个使用OpenGL在Windows环境下创建窗口程序的完整框架。该框架包括初始化OpenGL、设置视口大小、绘制场景等功能,并提供了窗口全屏/窗口模式切换的支持。
1万+

被折叠的 条评论
为什么被折叠?



