游戏编程入门之隐形的精灵
代码:
MyDirectX.h:
1 #pragma once 2 //header files 3 #define WIN32_EXTRA_LEAN 4 #define DIRECTINPUT_VERSION 0x0800 5 #include <windows.h> 6 #include <d3d9.h> 7 #include <d3dx9.h> 8 #include <dinput.h> 9 #include <xinput.h> 10 #include <ctime> 11 #include <iostream> 12 #include <iomanip> 13 using namespace std; 14 15 //libraries 16 #pragma comment(lib,"winmm.lib") 17 #pragma comment(lib,"user32.lib") 18 #pragma comment(lib,"gdi32.lib") 19 #pragma comment(lib,"dxguid.lib") 20 #pragma comment(lib,"d3d9.lib") 21 #pragma comment(lib,"d3dx9.lib") 22 #pragma comment(lib,"dinput8.lib") 23 #pragma comment(lib,"xinput.lib") 24 25 //program values 26 extern const string APPTITLE; 27 extern const int SCREENW; 28 extern const int SCREENH; 29 extern bool gameover; 30 31 //macro to detect key presses 32 #define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0) 33 34 //Direct3D objects 35 extern LPDIRECT3D9 d3d; 36 extern LPDIRECT3DDEVICE9 d3ddev; 37 extern LPDIRECT3DSURFACE9 backbuffer; 38 extern LPD3DXSPRITE spriteobj; 39 40 //Direct3D functions 41 bool Direct3D_Init(HWND hwnd, int width, int height, bool fullscreen); 42 void Direct3D_Shutdown(); 43 LPDIRECT3DSURFACE9 LoadSurface(string filename); 44 void DrawSurface(LPDIRECT3DSURFACE9 dest, float x, float y, LPDIRECT3DSURFACE9 source); 45 D3DXVECTOR2 GetBitmapSize(string filename); 46 LPDIRECT3DTEXTURE9 LoadTexture(string filename, D3DCOLOR transcolor = D3DCOLOR_XRGB(0, 0, 0)); 47 48 //DirectInput objects, devices, and states 49 extern LPDIRECTINPUT8 dinput; 50 extern LPDIRECTINPUTDEVICE8 dimouse; 51 extern LPDIRECTINPUTDEVICE8 dikeyboard; 52 extern DIMOUSESTATE mouse_state; 53 extern XINPUT_GAMEPAD controllers[4]; 54 55 //DirectInput functions 56 bool DirectInput_Init(HWND); 57 void DirectInput_Update(); 58 void DirectInput_Shutdown(); 59 bool Key_Down(int); 60 int Mouse_Button(int); 61 int Mouse_X(); 62 int Mouse_Y(); 63 void XInput_Vibrate(int contNum = 0, int amount = 65535); 64 bool XInput_Controller_Found(); 65 66 //game functions 67 bool Game_Init(HWND window); 68 void Game_Run(HWND window); 69 void Game_End();
MyDirectX.cpp:
1 #include "MyDirectX.h" 2 #include <iostream> 3 using namespace std; 4 5 //Direct3D variables 6 LPDIRECT3D9 d3d = NULL; 7 LPDIRECT3DDEVICE9 d3ddev = NULL; 8 LPDIRECT3DSURFACE9 backbuffer = NULL; 9 LPD3DXSPRITE spriteobj; 10 11 //DirectInput variables 12 LPDIRECTINPUT8 dinput = NULL; 13 LPDIRECTINPUTDEVICE8 dimouse = NULL; 14 LPDIRECTINPUTDEVICE8 dikeyboard = NULL; 15 DIMOUSESTATE mouse_state; 16 char keys[256]; 17 XINPUT_GAMEPAD controllers[4]; 18 19 20 bool Direct3D_Init(HWND window, int width, int height, bool fullscreen) 21 { 22 //initialize Direct3D 23 d3d = Direct3DCreate9(D3D_SDK_VERSION); 24 if (!d3d) return false; 25 26 //set Direct3D presentation parameters 27 D3DPRESENT_PARAMETERS d3dpp; 28 ZeroMemory(&d3dpp, sizeof(d3dpp)); 29 d3dpp.hDeviceWindow = window; 30 d3dpp.Windowed = (!fullscreen); 31 d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; 32 d3dpp.EnableAutoDepthStencil = 1; 33 d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8; 34 d3dpp.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL; 35 d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; 36 d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8; 37 d3dpp.BackBufferCount = 1; 38 d3dpp.BackBufferWidth = width; 39 d3dpp.BackBufferHeight = height; 40 41 //create Direct3D device 42 d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, window, 43 D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddev); 44 if (!d3ddev) return false; 45 46 47 //get a pointer to the back buffer surface 48 d3ddev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backbuffer); 49 50 //create sprite object 51 D3DXCreateSprite(d3ddev, &spriteobj); 52 53 return 1; 54 } 55 56 void Direct3D_Shutdown() 57 { 58 if (spriteobj) spriteobj->Release(); 59 60 if (d3ddev) d3ddev->Release(); 61 if (d3d) d3d->Release(); 62 } 63 64 void DrawSurface(LPDIRECT3DSURFACE9 dest, float x, float y, LPDIRECT3DSURFACE9 source) 65 { 66 //get width/height from source surface 67 D3DSURFACE_DESC desc; 68 source->GetDesc(&desc); 69 70 //create rects for drawing 71 RECT source_rect = { 0, 0, (long)desc.Width, (long)desc.Height }; 72 RECT dest_rect = { (long)x, (long)y, (long)x + desc.Width, (long)y + desc.Height }; 73 74 //draw the source surface onto the dest 75 d3ddev->StretchRect(source, &source_rect, dest, &dest_rect, D3DTEXF_NONE); 76 77 } 78 79 LPDIRECT3DSURFACE9 LoadSurface(string filename) 80 { 81 LPDIRECT3DSURFACE9 image = NULL; 82 83 //get width and height from bitmap file 84 D3DXIMAGE_INFO info; 85 HRESULT result = D3DXGetImageInfoFromFile(filename.c_str(), &info); 86 if (result != D3D_OK) 87 return NULL; 88 89 //create surface 90 result = d3ddev->CreateOffscreenPlainSurface( 91 info.Width, //width of the surface 92 info.Height, //height of the surface 93 D3DFMT_X8R8G8B8, //surface format 94 D3DPOOL_DEFAULT, //memory pool to use 95 &image, //pointer to the surface 96 NULL); //reserved (always NULL) 97 98 if (result != D3D_OK) return NULL; 99 100 //load surface from file into newly created surface 101 result = D3DXLoadSurfaceFromFile( 102 image, //destination surface 103 NULL, //destination palette 104 NULL, //destination rectangle 105 filename.c_str(), //source filename 106 NULL, //source rectangle 107 D3DX_DEFAULT, //controls how image is filtered 108 D3DCOLOR_XRGB(0, 0, 0), //for transparency (0 for none) 109 NULL); //source image info (usually NULL) 110 111 //make sure file was loaded okay 112 if (result != D3D_OK) return NULL; 113 114 return image; 115 } 116 117 118 D3DXVECTOR2 GetBitmapSize(string filename) 119 { 120 D3DXIMAGE_INFO info; 121 D3DXVECTOR2 size = D3DXVECTOR2(0.0f, 0.0f); 122 123 HRESULT result = D3DXGetImageInfoFromFile(filename.c_str(), &info); 124 125 if (result == D3D_OK) 126 size = D3DXVECTOR2((float)info.Width, (float)info.Height); 127 else 128 size = D3DXVECTOR2((float)info.Width, (float)info.Height); 129 130 return size; 131 } 132 133 LPDIRECT3DTEXTURE9 LoadTexture(std::string filename, D3DCOLOR transcolor) 134 { 135 LPDIRECT3DTEXTURE9 texture = NULL; 136 137 //get width and height from bitmap file 138 D3DXIMAGE_INFO info; 139 HRESULT result = D3DXGetImageInfoFromFile(filename.c_str(), &info); 140 if (result != D3D_OK) return NULL; 141 142 //create the new texture by loading a bitmap image file 143 D3DXCreateTextureFromFileEx( 144 d3ddev, //Direct3D device object 145 filename.c_str(), //bitmap filename 146 info.Width, //bitmap image width 147 info.Height, //bitmap image height 148 1, //mip-map levels (1 for no chain) 149 D3DPOOL_DEFAULT, //the type of surface (standard) 150 D3DFMT_UNKNOWN, //surface format (default) 151 D3DPOOL_DEFAULT, //memory class for the texture 152 D3DX_DEFAULT, //image filter 153 D3DX_DEFAULT, //mip filter 154 transcolor, //color key for transparency 155 &info, //bitmap file info (from loaded file) 156 NULL, //color palette 157 &texture); //destination texture 158 159 //make sure the bitmap textre was loaded correctly 160 if (result != D3D_OK) return NULL; 161 162 return texture; 163 } 164 165 166 bool DirectInput_Init(HWND hwnd) 167 { 168 //initialize DirectInput object 169 DirectInput8Create( 170 GetModuleHandle(NULL), 171 DIRECTINPUT_VERSION, 172 IID_IDirectInput8, 173 (void**)&dinput, 174 NULL); 175 176 //initialize the keyboard 177 dinput->CreateDevice(GUID_SysKeyboard, &dikeyboard, NULL); 178 dikeyboard->SetDataFormat(&c_dfDIKeyboard); 179 dikeyboard->SetCooperativeLevel(hwnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND); 180 dikeyboard->Acquire(); 181 182 //initialize the mouse 183 dinput->CreateDevice(GUID_SysMouse, &dimouse, NULL); 184 dimouse->SetDataFormat(&c_dfDIMouse); 185 dimouse->SetCooperativeLevel(hwnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND); 186 dimouse->Acquire(); 187 d3ddev->ShowCursor(false); 188 189 return true; 190 } 191 192 void DirectInput_Update() 193 { 194 //update mouse 195 dimouse->Poll(); 196 if (!SUCCEEDED(dimouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouse_state))) 197 { 198 //mouse device lose, try to re-acquire 199 dimouse->Acquire(); 200 } 201 202 //update keyboard 203 dikeyboard->Poll(); 204 if (!SUCCEEDED(dikeyboard->GetDeviceState(256, (LPVOID)&keys))) 205 { 206 //keyboard device lost, try to re-acquire 207 dikeyboard->Acquire(); 208 } 209 210 //update controllers 211 for (int i = 0; i< 4; i++) 212 { 213 ZeroMemory(&controllers[i], sizeof(XINPUT_STATE)); 214 215 //get the state of the controller 216 XINPUT_STATE state; 217 DWORD result = XInputGetState(i, &state); 218 219 //store state in global controllers array 220 if (result == 0) controllers[i] = state.Gamepad; 221 } 222 } 223 224 225 int Mouse_X() 226 { 227 return mouse_state.lX; 228 } 229 230 int Mouse_Y() 231 { 232 return mouse_state.lY; 233 } 234 235 int Mouse_Button(int button) 236 { 237 return mouse_state.rgbButtons[button] & 0x80; 238 } 239 240 bool Key_Down(int key) 241 { 242 return (bool)(keys[key] & 0x80); 243 } 244 245 246 void DirectInput_Shutdown() 247 { 248 if (dikeyboard) 249 { 250 dikeyboard->Unacquire(); 251 dikeyboard->Release(); 252 dikeyboard = NULL; 253 } 254 if (dimouse) 255 { 256 dimouse->Unacquire(); 257 dimouse->Release(); 258 dimouse = NULL; 259 } 260 } 261 262 bool XInput_Controller_Found() 263 { 264 XINPUT_CAPABILITIES caps; 265 ZeroMemory(&caps, sizeof(XINPUT_CAPABILITIES)); 266 XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &caps); 267 if (caps.Type != 0) return false; 268 269 return true; 270 } 271 272 void XInput_Vibrate(int contNum, int amount) 273 { 274 XINPUT_VIBRATION vibration; 275 ZeroMemory(&vibration, sizeof(XINPUT_VIBRATION)); 276 vibration.wLeftMotorSpeed = amount; 277 vibration.wRightMotorSpeed = amount; 278 XInputSetState(contNum, &vibration); 279 }
MyGame.cpp:
1 #include "MyDirectX.h" 2 3 const string APPTITLE = "Transparent Sprite Demo"; 4 const int SCREENW = 1024; 5 const int SCREENH = 768; 6 7 LPDIRECT3DTEXTURE9 image_colorkey = NULL; 8 LPDIRECT3DTEXTURE9 image_alpha = NULL; 9 LPDIRECT3DTEXTURE9 image_notrans = NULL; 10 11 12 bool Game_Init(HWND window) 13 { 14 //initialize Direct3D 15 if (!Direct3D_Init(window, SCREENW, SCREENH, false)) 16 { 17 MessageBox(0, "Error initializing Direct3D", "ERROR", 0); 18 return false; 19 } 20 21 //initialize DirectInput 22 if (!DirectInput_Init(window)) 23 { 24 MessageBox(0, "Error initializing DirectInput", "ERROR", 0); 25 return false; 26 } 27 28 //load non-transparent image 29 image_notrans = LoadTexture("shuttle_notrans.bmp"); 30 if (!image_notrans) return false; 31 32 //load color-keyed transparent image 33 image_colorkey = LoadTexture("shuttle_colorkey.bmp", D3DCOLOR_XRGB(255, 0, 255)); 34 if (!image_colorkey) return false; 35 36 //load alpha transparent image 37 image_alpha = LoadTexture("shuttle_alpha.tga"); 38 if (!image_alpha) return false; 39 40 41 //You can use this function to get the size of the image 42 D3DXVECTOR2 size = GetBitmapSize("shuttle_alpha.tga"); 43 44 45 return true; 46 } 47 48 void Game_Run(HWND window) 49 { 50 //make sure the Direct3D device is valid 51 if (!d3ddev) return; 52 53 //update input devices 54 DirectInput_Update(); 55 56 //clear the scene 57 d3ddev->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 100), 1.0f, 0); 58 59 //start rendering 60 if (d3ddev->BeginScene()) 61 { 62 //start drawing 63 spriteobj->Begin(D3DXSPRITE_ALPHABLEND); 64 65 //draw the sprite 66 D3DXVECTOR3 pos1(10, 10, 0); 67 spriteobj->Draw(image_notrans, NULL, NULL, &pos1, D3DCOLOR_XRGB(255, 255, 255)); 68 69 D3DXVECTOR3 pos2(350, 10, 0); 70 spriteobj->Draw(image_colorkey, NULL, NULL, &pos2, D3DCOLOR_XRGB(255, 255, 255)); 71 72 D3DXVECTOR3 pos3(700, 10, 0); 73 spriteobj->Draw(image_alpha, NULL, NULL, &pos3, D3DCOLOR_XRGB(255, 255, 255)); 74 75 //stop drawing 76 spriteobj->End(); 77 78 //stop rendering 79 d3ddev->EndScene(); 80 d3ddev->Present(NULL, NULL, NULL, NULL); 81 } 82 83 //Escape key ends program 84 if (KEY_DOWN(VK_ESCAPE)) gameover = true; 85 86 //controller Back button also ends 87 if (controllers[0].wButtons & XINPUT_GAMEPAD_BACK) 88 gameover = true; 89 } 90 91 void Game_End() 92 { 93 //free memory and shut down 94 image_notrans->Release(); 95 image_colorkey->Release(); 96 image_alpha->Release(); 97 98 DirectInput_Shutdown(); 99 Direct3D_Shutdown(); 100 }
MyWindows.cpp:
1 #include "MyDirectX.h" 2 using namespace std; 3 bool gameover = false; 4 5 6 LRESULT WINAPI WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) 7 { 8 switch (msg) 9 { 10 case WM_DESTROY: 11 gameover = true; 12 PostQuitMessage(0); 13 return 0; 14 } 15 return DefWindowProc(hWnd, msg, wParam, lParam); 16 } 17 18 19 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) 20 { 21 //initialize window settings 22 WNDCLASSEX wc; 23 wc.cbSize = sizeof(WNDCLASSEX); 24 wc.style = CS_HREDRAW | CS_VREDRAW; 25 wc.lpfnWndProc = (WNDPROC)WinProc; 26 wc.cbClsExtra = 0; 27 wc.cbWndExtra = 0; 28 wc.hInstance = hInstance; 29 wc.hIcon = NULL; 30 wc.hCursor = LoadCursor(NULL, IDC_ARROW); 31 wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); 32 wc.lpszMenuName = NULL; 33 wc.lpszClassName = APPTITLE.c_str(); 34 wc.hIconSm = NULL; 35 RegisterClassEx(&wc); 36 37 //create a new window 38 HWND window = CreateWindow(APPTITLE.c_str(), APPTITLE.c_str(), 39 WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 40 SCREENW, SCREENH, NULL, NULL, hInstance, NULL); 41 if (window == 0) return 0; 42 43 //display the window 44 ShowWindow(window, nCmdShow); 45 UpdateWindow(window); 46 47 //initialize the game 48 if (!Game_Init(window)) return 0; 49 50 // main message loop 51 MSG message; 52 while (!gameover) 53 { 54 if (PeekMessage(&message, NULL, 0, 0, PM_REMOVE)) 55 { 56 TranslateMessage(&message); 57 DispatchMessage(&message); 58 } 59 60 //process game loop 61 Game_Run(window); 62 } 63 64 //shutdown 65 Game_End(); 66 return message.wParam; 67 }
结果: