其实纹理滤波是什么概念我也还不了解,图形学就是这样,理论和实践都不可偏废,可究竟从何处入手也是个两难的问题,有人说“图形血到最后就是数学”,对我这样的新手来说,快速有个概念也许不失为一个笨办法吧。<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
Nehe在第6课里已经用了线性滤波了,并且还推荐我们把gl_nearest(不光滑)滤波方式和线性滤波结合起来使用,在近处时用线性滤波,在远处时用gl_nearest(不光滑)滤波,因为线性滤波对运行机器的要求高些。
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->#include<windows.h>//HeaderFileForWindows
#include<stdio.h>//HeaderFileForStandardInput/Output
#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
boollight;//LightingON/OFF(NEW)
boollp;//LPressed?(NEW)
boolfp;//FPressed?(NEW)
GLfloatxrot;//XRotation
GLfloatyrot;//YRotation
GLfloatxspeed;//XRotationSpeed
GLfloatyspeed;//YRotationSpeed
GLfloatz=-5.0f;//DepthIntoTheScreen
GLfloatLightAmbient[]={0.5f,0.5f,0.5f,1.0f};
GLfloatLightDiffuse[]={1.0f,1.0f,1.0f,1.0f};
GLfloatLightPosition[]={0.0f,0.0f,2.0f,1.0f};
GLuintfilter;//WhichFilterToUse
GLuinttexture[3];//StorageFor3Textures
LRESULTCALLBACKWndProc(HWND,UINT,WPARAM,LPARAM);//DeclarationForWndProc
AUX_RGBImageRec*LoadBMP(char*Filename)//LoadsABitmapImage
{
FILE*File=NULL;//FileHandle
if(!Filename)//MakeSureAFilenameWasGiven
{
returnNULL;//IfNotReturnNULL
}
File=fopen(Filename,"r");//CheckToSeeIfTheFileExists
if(File)//DoesTheFileExist?
{
fclose(File);//CloseTheHandle
returnauxDIBImageLoad(Filename);//LoadTheBitmapAndReturnAPointer
}
returnNULL;//IfLoadFailedReturnNULL
}
intLoadGLTextures()//LoadBitmapsAndConvertToTextures
{
intStatus=FALSE;//StatusIndicator
AUX_RGBImageRec*TextureImage[1];//CreateStorageSpaceForTheTexture
memset(TextureImage,0,sizeof(void*)*1);//SetThePointerToNULL
//LoadTheBitmap,CheckForErrors,IfBitmap'sNotFoundQuit
if(TextureImage[0]=LoadBMP("Data/Crate.bmp"))
{
Status=TRUE;//SetTheStatusToTRUE
glGenTextures(3,&texture[0]);//CreateThreeTextures
//CreateNearestFilteredTexture
glBindTexture(GL_TEXTURE_2D,texture[0]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D,0,3,TextureImage[0]->sizeX,TextureImage[0]->sizeY,0,GL_RGB,GL_UNSIGNED_BYTE,TextureImage[0]->data);
//CreateLinearFilteredTexture
glBindTexture(GL_TEXTURE_2D,texture[1]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,0,3,TextureImage[0]->sizeX,TextureImage[0]->sizeY,0,GL_RGB,GL_UNSIGNED_BYTE,TextureImage[0]->data);
//CreateMipMappedTexture
glBindTexture(GL_TEXTURE_2D,texture[2]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
gluBuild2DMipmaps(GL_TEXTURE_2D,3,TextureImage[0]->sizeX,TextureImage[0]->sizeY,GL_RGB,GL_UNSIGNED_BYTE,TextureImage[0]->data);
}
if(TextureImage[0])//IfTextureExists
{
if(TextureImage[0]->data)//IfTextureImageExists
{
free(TextureImage[0]->data);//FreeTheTextureImageMemory
}
free(TextureImage[0]);//FreeTheImageStructure
}
returnStatus;//ReturnTheStatus
}
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
{
if(!LoadGLTextures())//JumpToTextureLoadingRoutine
{
returnFALSE;//IfTextureDidn'tLoadReturnFALSE
}
glEnable(GL_TEXTURE_2D);//EnableTextureMapping
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
glLightfv(GL_LIGHT1,GL_AMBIENT,LightAmbient);//SetupTheAmbientLight
glLightfv(GL_LIGHT1,GL_DIFFUSE,LightDiffuse);//SetupTheDiffuseLight
glLightfv(GL_LIGHT1,GL_POSITION,LightPosition);//PositionTheLight
glEnable(GL_LIGHT1);//EnableLightOne
returnTRUE;//InitializationWentOK
}
intDrawGLScene(GLvoid)//Here'sWhereWeDoAllTheDrawing
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);//ClearTheScreenAndTheDepthBuffer
glLoadIdentity();//ResetTheView
glTranslatef(0.0f,0.0f,z);
glRotatef(xrot,1.0f,0.0f,0.0f);
glRotatef(yrot,0.0f,1.0f,0.0f);
glBindTexture(GL_TEXTURE_2D,texture[filter]);
glBegin(GL_QUADS);
//FrontFace
glNormal3f(0.0f,0.0f,1.0f);
glTexCoord2f(0.0f,0.0f);glVertex3f(-1.0f,-1.0f,1.0f);
glTexCoord2f(1.0f,0.0f);glVertex3f(1.0f,-1.0f,1.0f);
glTexCoord2f(1.0f,1.0f);glVertex3f(1.0f,1.0f,1.0f);
glTexCoord2f(0.0f,1.0f);glVertex3f(-1.0f,1.0f,1.0f);
//BackFace
glNormal3f(0.0f,0.0f,-1.0f);
glTexCoord2f(1.0f,0.0f);glVertex3f(-1.0f,-1.0f,-1.0f);
glTexCoord2f(1.0f,1.0f);glVertex3f(-1.0f,1.0f,-1.0f);
glTexCoord2f(0.0f,1.0f);glVertex3f(1.0f,1.0f,-1.0f);
glTexCoord2f(0.0f,0.0f);glVertex3f(1.0f,-1.0f,-1.0f);
//TopFace
glNormal3f(0.0f,1.0f,0.0f);
glTexCoord2f(0.0f,1.0f);glVertex3f(-1.0f,1.0f,-1.0f);
glTexCoord2f(0.0f,0.0f);glVertex3f(-1.0f,1.0f,1.0f);
glTexCoord2f(1.0f,0.0f);glVertex3f(1.0f,1.0f,1.0f);
glTexCoord2f(1.0f,1.0f);glVertex3f(1.0f,1.0f,-1.0f);
//BottomFace
glNormal3f(0.0f,-1.0f,0.0f);
glTexCoord2f(1.0f,1.0f);glVertex3f(-1.0f,-1.0f,-1.0f);
glTexCoord2f(0.0f,1.0f);glVertex3f(1.0f,-1.0f,-1.0f);
glTexCoord2f(0.0f,0.0f);glVertex3f(1.0f,-1.0f,1.0f);
glTexCoord2f(1.0f,0.0f);glVertex3f(-1.0f,-1.0f,1.0f);
//Rightface
glNormal3f(1.0f,0.0f,0.0f);
glTexCoord2f(1.0f,0.0f);glVertex3f(1.0f,-1.0f,-1.0f);
glTexCoord2f(1.0f,1.0f);glVertex3f(1.0f,1.0f,-1.0f);
glTexCoord2f(0.0f,1.0f);glVertex3f(1.0f,1.0f,1.0f);
glTexCoord2f(0.0f,0.0f);glVertex3f(1.0f,-1.0f,1.0f);
//LeftFace
glNormal3f(-1.0f,0.0f,0.0f);
glTexCoord2f(0.0f,0.0f);glVertex3f(-1.0f,-1.0f,-1.0f);
glTexCoord2f(1.0f,0.0f);glVertex3f(-1.0f,-1.0f,1.0f);
glTexCoord2f(1.0f,1.0f);glVertex3f(-1.0f,1.0f,1.0f);
glTexCoord2f(0.0f,1.0f);glVertex3f(-1.0f,1.0f,-1.0f);
glEnd();
xrot+=xspeed;
yrot+=yspeed;
returnTRUE;//KeepGoing
}
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'sTextures,Lighting&KeyboardTutorial",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&&!DrawGLScene())||keys[VK_ESCAPE])//Active?WasThereAQuitReceived?
{
done=TRUE;//ESCorDrawGLSceneSignalledAQuit
}
else//NotTimeToQuit,UpdateScreen
{
SwapBuffers(hDC);//SwapBuffers(DoubleBuffering)
if(keys['L']&&!lp)
{
lp=TRUE;
light=!light;
if(!light)
{
glDisable(GL_LIGHTING);
}
else
{
glEnable(GL_LIGHTING);
}
}
if(!keys['L'])
{
lp=FALSE;
}
if(keys['F']&&!fp)
{
fp=TRUE;
filter+=1;
if(filter>2)
{
filter=0;
}
}
if(!keys['F'])
{
fp=FALSE;
}
if(keys[VK_PRIOR])
{
z-=0.02f;
}
if(keys[VK_NEXT])
{
z+=0.02f;
}
if(keys[VK_UP])
{
xspeed-=0.01f;
}
if(keys[VK_DOWN])
{
xspeed+=0.01f;
}
if(keys[VK_RIGHT])
{
yspeed+=0.01f;
}
if(keys[VK_LEFT])
{
yspeed-=0.01f;
}
if(keys[VK_F1])//IsF1BeingPressed?
{
keys[VK_F1]=FALSE;//IfSoMakeKeyFALSE
KillGLWindow();//KillOurCurrentWindow
fullscreen=!fullscreen;//ToggleFullscreen/WindowedMode
//RecreateOurOpenGLWindow
if(!CreateGLWindow("NeHe'sTextures,Lighting&KeyboardTutorial",640,480,16,fullscreen))
{
return0;//QuitIfWindowWasNotCreated
}
}
}
}
}
//Shutdown
KillGLWindow();//KillTheWindow
return(msg.wParam);//ExitTheProgram
}
这一课里还讲解了如何使用光照。他使用了两种不同的光。第一种称为环境光。环境光来自于四面八方。所有场景中的对象都处于环境光的照射中。第二种类型的光源叫做漫射光。漫射光由特定的光源产生,并在您的场景中的对象表面上产生反射。处于漫射光直接照射下的任何对象表面都变得很亮,而几乎未被照射到的区域就显得要暗一些。创建光源的过程和颜色的创建完全一致,先设置用来创建光源的数组。前三个参数分别是RGB三色分量,最后一个是alpha通道参数。
GLfloat LightAmbient[]= { <?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" /><chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue=".5" unitname="F">0.5f</chmetcnv>, <chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue=".5" unitname="F">0.5f</chmetcnv>, <chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue=".5" unitname="F">0.5f</chmetcnv>, <chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue="1" unitname="F">1.0f</chmetcnv> }; // 环境光参数
GLfloat LightDiffuse[]= { <chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue="1" unitname="F">1.0f</chmetcnv>, <chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue="1" unitname="F">1.0f</chmetcnv>, <chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue="1" unitname="F">1.0f</chmetcnv>, <chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue="1" unitname="F">1.0f</chmetcnv> }; // 漫射光参数
最后保存光源的位置。前三个参数和glTranslate中的一样。依次分别是XYZ轴上的位移。最后一个参数取为<chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue="1" unitname="F"><span lang="EN-US" style="FONT-SIZE: 10pt; FONT-FAMILY: Verdana">1.0f</span></chmetcnv>。这将告诉OpenGL这里指定的坐标就是光源的位置。
GLfloat LightPosition[]= { <chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue="0" unitname="F">0.0f</chmetcnv>, <chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue="0" unitname="F">0.0f</chmetcnv>, <chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue="2" unitname="F">2.0f</chmetcnv>, <chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue="1" unitname="F">1.0f</chmetcnv> }; // 光源位置
教程里使用三种纹理滤波方式,第一种纹理(texture 0)使用gl_nearest(不光滑)滤波方式构建。第二种纹理(texture 1)使用gl_linear(线性滤波)方式,离屏幕越近的图像看起来就越光滑。第三种纹理 (texture 2)使用mipmapped滤波方式,这将创建一个外观十分优秀的纹理。
下面是创建纹理的新方法:Mip-mapping(纹理细化)。您可能会注意到当图像在屏幕上变得很小的时候,很多细节将会丢失。刚才还很不错的图案变得很难看。当您告诉OpenGL创建一个mipmapped的纹理后,OpenGL将尝试创建不同尺寸的高质量纹理。当您向屏幕绘制一个mipmapped纹理的时候,OpenGL将选择它已经创建的外观最佳的纹理(带有更多细节)来绘制,而不仅仅是缩放原先的图像(这将导致细节丢失)。
要绕过OpenGL对纹理宽度和高度所加的限制 (64、128、256等等)。办法就是 gluBuild2DMipmaps,我们可以使用任意的位图来创建纹理。OpenGL将自动将它缩放到正常的大小。
// 创建 MipMapped 纹理
glBindTexture(GL_TEXTURE_2D, texture[2]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
下面生成mipmapped纹理。我们使用三种颜色(红,绿,蓝)来生成一个2D纹理。TextureImage[0]->sizeX 是位图宽度,extureImage[0]->sizeY是位图高度,GL_RGB意味着我们依次使用RGB色彩。GL_UNSIGNED_BYTE意味着纹理数据的单位是字节。TextureImage[0]->data指向我们创建纹理所用的位图。
gluBuild2DMipmaps(GL_TEXTURE_2D, 3,
TextureImage[0]->sizeX, TextureImage[0]->sizeY,
GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data);
现在开始设置光源。下面一行设置环境光的发光量,光源light1开始发光:
glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient); // 设置环境光
设置漫射光的发光量:
glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse); // 设置漫射光
然后设置光源的位置:
glLightfv(GL_LIGHT1, GL_POSITION,LightPosition); // 光源位置
最后,我们启用一号光源,没有启用GL_LIGHTING,所以您看不见任何光线(只对光源进行设置、定位、甚至启用,光源都不会工作。除非我们启用GL_LIGHTING)。
glEnable(GL_LIGHT1); // 启用一号光源
课程中还学习了一个新的函数glNormal<chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue="3" unitname="F">3f</chmetcnv>。Normal就是法线的意思,所谓法线是指经过面(多边形)上的一点且垂直于这个面(多边形)的直线。使用光源的时候必须指定一条法线。法线告诉OpenGL这个多边形的朝向,并指明多边形的正面和背面。如果没有指定法线,什么怪事情都可能发生。