Home

Implementation of a 2D Game Engine Using

image

Contents

1. Computer Science Daniel Linds th and Martin Persson Implementation of a 2D Game Engine Using DirectX 8 1 Bachelor s Project 2004 24 Implementation of a 2D Game Engine Using DirectX 8 1 Daniel Linds th and Martin Persson 6 2004 The author s and Karlstad University This report is submitted in partial fulfillment of the requirements for the Bachelor s degree in Computer Science All material in this report which is not our own work has been identified and no material is included for which a degree has previously been conferred Daniel Linds th Martin Persson Approved 2004 06 03 Advisor Hannes Persson Examiner Donald F Ross iii Abstract This paper describes our game engine written in C using the DirectX libraries for graphics sound and input Since the engine is written using DirectX an introduction to this system is given The report gives a description of the structure of the game and the game kernel Following this is a description of the graphics engine and its core compo nents T he main focus of the engine is on the physics and how it is used in the game to simulate reality Input is discussed briefly with examples to show how it relates to the physics engine Implementation of audio in the game engine is not described but a general description of how sound is used in games is given theory for the basics of how artificial intelligence can be used in the engine is p
2. aktuellt block Att ndra den p ground vore korkat Current_Original_Block 1 v nsterknappen f r att placera ut block v nsterknappen f r att v la ett block och flytta det v nsterknappen p inget block f r att avmarkera blocket flyta runnt de valda blocket med piltangenterna och tryck Ctrl f r hastighet O och P anv nds p att ka och minska aktuella blocket tryck p B f r att st nga av ringen runt det aktuella blocket anv nd pilarna f r att flytta sk rmen n r inget block r markerat tryck p S f r att spara kartan i filen level00 ban tryck p D f r att ladda kartan fr n filen level00 ban Dockans possitioner X 512 Y 384 aktuell fiendetyp 1 aktuell fiende 1 Tryck p SPACE f r att v xla mellan mark fiender och h ndelser mark 1 fiender 2 h ndelser 3 aktuell objekttyp 1 antal fiender 0 antal h ndelser 0 aktuell h ndelse 1 aktuell h ndelse typ 1 Figure A 1 Empty Level Editor To begin with ignore the blue doll To place an object on the map left click the object in question in the toolbox and then left click on the edit area where you want it placed 43 To move the object to another place use the arrow keys O and P are used iterate the list of placed objects The space key is used to change between terrain enemies and events To specify the terrain layer use the keys 0 1 and 2 To make objects move faster or slower than the player K and L are used for changing the s
3. ifndef game h define game h Ua ecd LIE DEFINES g MIMMMMMMMMMMMIMMEIMMMMMMMMMIIMMMMM define TITLE Martins Spelmotor Title of the window terrain layertype defines to keep track of what you are doing define BACKGROUND 0 Hdefine GROUND T define FOREGROUND 2 only used for the ground layer of terram to indicate that pixelscan should be used insted of the ordinery Bob Collision define TERRAIN TYPE NON SQUARE 1 define NUM ORIGINAL GROUND 6 define NUM ORIGINAL ENEMIES 2 define NUM EVENT TYPES 1 define HOPPARE 0 define RULLARE 1 character defines define STANDING STILL define WALKING RIGHT 1 define WALKING LEFT 2 define FACING LEFT 1 define FACING RIGHT 2 define IN FREE AIR 0 define ON GROUND 1 define HITTING ROOF 2 define ON LEFT WALL 4 define ON RIGHT WALL define HITTING UP LEFT CORNER 16 define HITTING UP RIGHT CORNER 32 define HITTING DOWN LEFT CORNER 64 define HITTING DOWN RIGHT CORNER 128 devierd eneny defines define HOPPARE ANIMATION 0 define ROLL RIGHT 0 define ROLL LEFT 1 III PP EP PI LIAS AT E DERA OBJECT DEFINES MI MMMMMMIMMIMMEMMMMMMMEPMELM 59 VARR ARRA ARRA KAR AAA AA AA AAA AA RR R ll lll lll ll ll ll t ARRA ARRA ARRA RA ll ll ll ll lt hh E 1 Terrain kf por TIT typedef class errain public Bo protected int Terrain Attributes public used to identify what type of original terrain it was cloned from ZY so the filename can be saved in the x b
4. It s now time to check for new input and repeat until the program is terminated 15 4 The Kernel The kernel is the module of the game that keeps track of all other modules It tells them when to execute and makes sure they re all working in the right order In the engine the kernel consists of the object Game Game has three member functions Init Main and Shutdown Init is used to start DirectX and set state variables within the engine Main is a simple state machine that keeps track of what level the player is currently in Shutdown closes DirectX and deallocates all dynamic memory The function Game Main is repeatedly called from within WinMain see Appendix B Each call to Game Main represents a single frame update in the game sometimes called a tick Kernel Check for exit Start Clear Execute Flip the Wait til command timer screen gameplay surfaces next frame Input Enemy Physics Collision Draw to back handling Al detect surface Figure 4 1 Game Kernel structure Game Main in turn calls the different modules that make up the game Figure 4 1 shows a simplifiied call tree with time increasing from left to right and to a lesser extent from top to bottom Most of the individual blocks will be described in the following sections The function is basically a finite state machine that chooses which sub event loop should be called The object Game see Appendix E 7 has member data to supervise the play
5. 3 Another Collision Example A simple solution would be to limit the maximum speed but that wouldn t conform well with the idea of a realistic physics engine The solution chosen for this engine is to move the object one pixel at a time following a line from its start location to the end point and perform a collision detect on every step This way a collision is discovered the first time a pixel is overlapping another and proper 28 actions can be taken Of course a good line approximation algorithm is essential to this approach 6 3 2 The Bresenham Algorithm Drawing exact lines on a computer is impossible since lines are defined as an infinite number of zero area points which lie between two end points The smallest unit on a computer screen is the pixel and its area is quite alot more than zero Approximations on the other hand are quite easy to draw if you use floating point operations void draw line int x1 int yl int x2 int y2 1 int dx x2 xl int dy y2 yl float m dy dx for int x x1 x x2 x int y m x yl 0 5 putpixel x y This however is too slow to be acceptable in a game where speed is of the essence The solution is Bresenham s midpoint algorithm 13 that will compute the point coordinates correctly using only integer math Figure 6 4 shows how pixel positions the dots in the corners of the grid are chosen depending on the true line s th
6. 3 The Components of DirectX Figure 2 2 shows how the components of DirectX are interconnected below are semi de tailed descriptions of each component 2 3 1 DirectDraw DirectDraw is the main rendering device of bitmap graphics DirectDraw also controls the graphics memory which is the main medium through which all graphics must go before it can be displayed on the monitor DirectDraw more or less controlls the graphics card DirectX 8 0 and above don t use DirectDraw as a component in its own right but runs everything through DirectX Graphics The part of a computer that does most of the data processing the CPU and the memory form the central part of a computer to which the peripherals are attached The most basic of image formats stores each pixel as three byte of data one for each of the colours Red Green and Blue Win32 Application DirectX 8 0 subsystems i i Q ta o i e 2 1 GDWDirectX a p j 5 le f E interface 9 5 E 18 E z 18 1 I gt I E a g A E rs 9 2 LS A A JA JAJ j A i a Merged to Merged to DirectX Graphics DirectX Audio Windows DDI Devive Driver Interface Low level HEL Hardware Emulation Layer Software emulation drivers HAL Hardware Abstraction Layer Hardware Figure 2 2 DirectX and Windows 2 3 2 DirectSound This component helps standardising sound playback Before DirectSound exis
7. DD_Flip void int DD VVait For Vsync void int DD Fill Surface LPDIRECIDRAWSURFACE lpdds int color UCHAR x DD Lock Surface LPDIRECTDRAVVSURFACE lpdds int xlpitch int DD Unlock Surface LPDIRECIDRAWSURFACE lpdds UCHAR x surface buffer UCHAR x DD Lock Primary Surface void int DD Unlock Primary Surface void UCHAR DD Lock Back Surface void int DD Unlock Back Surface void general utility functions DWORD Get Clock void DWORD Start Clock void DWORD Wait Clock DWORD count int Collision Test int x1 int yl int wl int hl int x2 int y2 int w2 int h2 int Color Scan int xl int yl int x2 int y2 UCHAR scan start UCHAR scan end UCHAR scan buffer int scan lpitch graphics functions int Draw Clip Line int x0 int y0 int x1 int yl UCHAR color UCHAR dest buffer int lpitch int Clip Line int amp xl int amp yl int amp x2 int amp y2 int Draw Line int xo int yo int x1 int yl UCHAR color UCHAR xvb start int lpitch int Draw Pixel int x int y int color UCHAR video buffer int lpitch int Draw Rectangle int xl int yl int x2 int y2 int color LPDIRECTDRAWSURFACE lpdds int Screen Transition void void HLine int xl int x2 int y int color UCHAR x vbuffer int lpitch void VLine int yl int y2 int x int color UCHAR x vbuffer int lpitch void Screen Transitions int effect UCHAR x vbuffer int lpitch palette functions int Set Palette Entry int color inde
8. File bob h Content Bitmap Objekt Blitter include file EVA watch for multiple inclusions ifndef bob h define bob h PE DEFINES TA defines for Bobs define BOB STATE DEAD 0 this is a dead bob define BOB STATE ALIVE 1 this is a live bob define BOB STATE DYING 2 this bob is dying define BOB STATE ANIM DONE 1 done animation state define MAX BOB FRAMES 64 maximum number of bob frames define MAX BOB ANIMATIONS 16 ZY maximum number of animation ZY sequeces define BOB ATTR SINGLE FRAME 1 bob has single frame define BOB ATTR MULTI FRAME 2 bob has multiple frames define BOB ATTR MULTI ANIM 4 bob has multiple animations define BOB ATTR ANIM ONE SHOT 8 bob will perform the animation once define BOB ATTR VISIBLE 16 bob is visible define BOB ATTR BOUNCE 32 bob bounces off edges define BOB ATIR WRAPAROUND 64 bob wraps around edges define BOB ATTR LOADED 128 the bob has been loaded define BOB ATTR CLONE 256 the bob is a clone bitmap defines define BITMAP ID 0x4D42 universal id for a bitmap define BITMAP EXTRACT MODE CELL 0 define BITMAP EXTRACT MODE ABS 1 this builds a 16 bit color value define RGBI6BIT r g b b9632 8 32 lt lt 5 1 32 lt lt 10 bit manipulation macros define SET_BIT word bit flag word word bit flag define RESET BIT word bit flag word word amp bit_flag class d
9. ILLIA LLI IA LLI LALI ALLA LALI AL ALIA LALI LALI LALI LULI TERRAIN CLASS JIJI IVVSA AAA G9 typedef class Terrain public Bob protected int Terrain Attributes public Used to identify what type of original terrain it was cloned from so the filename can be saved in the x ban file int Type Index double t x t y double t xv t yv Used to make the ForeGround and BackGround move faster or slower than the player double SpeedFactor 61 int Move void void Move int X int Y Terrain int X int Y int Width int Height int Num frames int Attr int Mem flags LPDIRECTDRAWSURFACE x destination surface Terrain void Terrain Terrain terrain _src Terrain ptr cna CLASS Pg III M MM M MIMIMMMMMMMWiltttttthtl typedef class Map Editor protected ZY Used to point at the global DirectInput mouse Bob ptr mouse This array might be converted to a linked list later om Terrain_ptr Ground 3 The original terrain that will be used to clone all other terrain Terrain ptr Original Ground NUM ORIGINAL GROUND The player doll It is the reference point to all othet objects ZY in the map It is not the starting position of the player The starting possition will be set by the game Terrain ptr player doll toolbox doll The size of the map int Terrain_Size 3 The enemies used to clone the enemies shown on the map Terrain ptr Orginal Fiender NUM ENEMY TYPES Terra
10. Terrain ptr player doll the size of the map int Terrain Size 3 ponter to the same data in Level Enemy ptr Level Fiender enemies local to the Sublevel Enemy ptr Sublevel_Fiender int antal sublevel fiender the original enemies that will be used to clone all other terrain Enemy ptr Original Enemies NUM ORIGINAL ENEMYS events on the map Terrain ptr Original Events NUM EVENT TYPES Terrain ptr Sublevel_Events 58 int antal_sublevel_handelser int Level To Play pointer to the same data in game Player ptr Player ONE SUBLEVEL METODS B M IMIMIMIMMMMMMMMMMMMIMMMMMPPHHPHPREEMLLTF TTA void Load Terrain Graphics void void Load Map Data char filename void Move int x int y void Draw void public Sublevel char level filename Player ptr Player source Sublevel void int Playing void Sublevel_ptr E 6 Level KA ed CLASS IH ypedef class Leve protected the number of maps in level int maps the sublevel that the player is playing on int Level To Play the curent map that the player i on int Current Map the maps or different rooms in level Sublevel ptr karta 2 the list of the enemies in the level if you leave a room the enemies are still there when you come back Enemy ptr Fiender pointer to the same data in game Player ptr Player ONE public Level Player ptr Global Player Level void the main
11. air A is the cross section area of the moving object and the minus sign means that the force works in the opposite direction of the speed The first formula is valid for objects moving slow enough not to cause any turbulence in the fluid or gas currently not used in the game engine The second is for fast moving objects that causes the flow streamlines surrounding it to become disturbed Cy is usually not equal for these two formulae Example code float dragx 0 5f x sublev gt rho x tempvx tempvx x area Cd x sign tempvx 23 6 1 3 Free fall Objects falling towards a large body will experience acceleration due to gravity the general formula for this is peg 0 M r2 M ma G r acer where F is the force acting on both bodies G is Newton s Universal Constant gravitational constant m is the mass of the smaller object M is the mass of the large body and r is the distance between the center of graivty of both bodies The vector a is the acceleration resulting from the force Example code Check to see if object is om the ground if On Ground amp ON GROUND the ground sets the gravity acceleration to 0 yv 0 else is it touching the roof if On Ground amp HITTING ROOF 24 set speed downwards to 19 s yv sublev GRAVITY else apply regular gravity yvt sublev gt GRAVITY 6 2 Physics Within the Game Th
12. apply to the objects in a game Most formulae in this chapter are taken from 4 and 7 1 Law of Inertia If no force is acting on a body it will remain at rest or move in a straight line at a constant velocity 2 Law of Acceleration The acceleration of a body is proportional and in the same direction as the resultant force that is acting on it 3 Law of Action and Reaction For any action force on a body there is an equal and opposite reaction reacting force 6 1 Newtonian Mechanics Newtonian or classical mechanics is the first part of physics most people will learn in school It deals with how forces interact with bodies and is based on Newton s laws of motion 6 1 1 Movements Acceleration and Inertia To alter the velocity of an object in any direction the application of a force is required the change in velocity is proportional and equal in direction to the force according to the following ma F 22 Example code Temporary velocity variable used to calculate the drag float tempvx xv walk force mass 6 1 2 Drag When objects move through gases or fluids the surrounding environment acts as a resis tance to slow them down There are two formulae to describe this resistive force F Cf 0 5 p vA and F C 0 5 p v A where F is the viscous drag force C is the fluid drag coefficient v is the speed of the object p is the density of the
13. are obviously in the background since the player character is partially blocking them The rightmost bush is in the foreground 36 SCIRE ail RP Figure 10 1 The Different Layers The meta data which describes the objects of the maps are stored in arrays which are allocated and deallocated each time a player enters or exits a sublevel DirectX was used for the level editor simply because this made it easier to save the data to a format that could easily be read by the game engine Any graphics API could have been used instead with a little more work Some basic instructions for how to use the map editor is shown when the program is executed 37 11 Conclusion The result of the dissertation is a fully working although pretty basic game engine with an accompanying level editor used for creating level meta data so one can make new levels A good system that vill be used for the implementation of AI has been created The system for keeping track of the terrain blocks in the game has been designed and implemented The terrain blocks inherits the main graphics object BOB as does the class where the physics is implemented Character which is then derived into Player and Enemy The level system in the game uses the graphics engine in the sense that all objects on the map use types derived from the base class BOB but the level objects themselves use no graphics except for debugging purposes The Level object contains the cha
14. dx m 0 we conclude that 1 F a 1n 5 2 dy 2 dy 2 de Y dr 2dr m 2 dy de This is the initial decision variable and will be designated dy Changes in midpoint values can be calculated using incR F Mzx 1 My F Mz My 2 dy when the pixel is to the right and incU R F Mx 1 My F Mx My 2 dy 1 dx when it s to the right and up This means that all that has to be done to figure out what the next pixel should be is to add incR or incUR to the current d value and check if it is positive or negative See 13 for more details 31 7 Input A player has to be able to interact with the game or the game will have no purpose whatsoever The interaction between the player and the game is called input So far only keyboard input is supported by this game engine but eventually it will also take care of mouse events and joysticks including gamepads Player input is handled by the Player class The Input function uses input functions through wrapper macros such as KEY DOWN define KEY DOWN vk code GetAsyncKeyState vk code amp 0x8000 1 0 7 1 Forces Input sets physics variables such as walk force in the Player class and the Logic function then calculates movements based on these values if KEY DOWN VK LEFT is he not already walking left if Statel WALKINGLEFT Zj Om stillast ende s tt walk force till walk_beg_left if On Ground amp ON GROUN
15. event loop for the level void Playing Level void x Level ptr E 7 Game GAME CLASS It MMMMMIIIMIIM LG L b gl l LS class Game protected 59 the player data Global Player ptr Player ONE the Levels in the game Level ptr Level 1 Animations GAME FUNKTIONS III ILI ILIA II LLALLA LL LALI LLALLA ALIA LL LLALLA LLI public int Game Init void parms NULL int Game Shutdown void parms NULL int Game Main void parms NULL E endif game h 60 F mapeditor h Copyright C 2004 Martin Persson All Rights Reserved x File game h x Content Main Game include file KKK watch for multiple inclusions ifndef game h define game h Ua ecd LIE DEFINES JIM MMMMIMMEIMMMMMMMIMIMMIMMMMMHIWTTPHA define TITLE Martins Spelmotor Title of the window terrain layer type defines to keep track of what you are doing define BACKGROUND 0 define GROUND 1 define FOREGROUND 2 define NO BLOCK SELECTED 1 define PLAYER SELECTED 2 only used for the ground layer of terrain to indicate that pixel scan should be used insted of the ordinary Bob Collision define TERRAIN TYPE NON SQUARE 1 define NUM ORIGINAL GROUND 6 define NUM ENEMY TYPES 2 define NUM EVENT TYPES 1 define GROUND TYPE Le ff define ENEMY TYPE 2 used for selection on the objects on the map define EVENT TYPE 3 GLOBALS IIS IIA AAA AAA Pg PROTOTYPES
16. fire or other objects that he can move After the player is done the computer takes care of all of its own characters with artificial intelligence This is similar to the input stage but instead of reading from input devices such as a keyboard the computer executes predefined AI functions for all of its characters The AI physics is handled the same way as player physics In fact they re most likely the same function inherited from the Character class 1 Player Player T arsi h ko iiie Ground a PE errain 1A ee i 1 5 Fiender Sublevel Fiender i wt eve Level Fiender Figure 3 2 Object Diagram of the Game Structure Note in Figure 3 2 that Game Level and Sublevel all contain the same player object Also note that the pointers Fiender in Level and Level Fiender in Sublevel both point to the same memory area Once the velocities have been set the physics engine moves all the objects to their new positions and check for collisions Collisions are treated depending on the objects that l Enemy units can have uniquely implemented physics functions if they aren t supposed to adhere to the normal laws of the world 14 collide a player colliding with a wall will simply stop but characters colliding with bullets will take damage After the objects have moved they will be dispatched to the graphics engine where they are drawn on a surface which then replaces the image that is currently on the screen
17. include dripping water the rush of wind in trees and sounds of distant traffic Transient sounds may be handled by events and played when a player reaches a certain place on the map or performs a task The graphical objects Terrain Characters and its descendants are inherited from BOB This isn t a very good way to do things since it complicates relocation to another graphics library such as DirectX Graphics or OpenGL It would be better if the graphical objects included a BOB or simliar as a data member It would also be a good idea to imple ment characters as a number of smaller BOBs for different parts such as the main body the weapon armour etc This allows the character to change appearance depending on equipment This obviously assumes that each group of equipment will be fairly uniform so the same animations can be used for at least most of them to save memory and ease implementation A nice side effect of such a system would be that it would allow separate collision detect and physics for different parts of the character This would allow for special vulnerable points where extra damage would be dealt or part of the character acting as a m l e weapon The map system wouldn t notice this change since there d still be a general collision function for the whole object which would be used to detect collisions between the terrain and character The map editor has to be altered so objects can be moved outwards and inwards within
18. intelligence none of which have actually been implemented yet Instead they show how an implementation could be used in the future and what to think about Section 10 describes how the system for levels and maps works This is the system that tells the graphics engine what to draw and where The levels also contain all the information used by the physics engine such as gravity and atmospheric density Finally Section 11 is a conclusion which summarizes the whole thesis 2 DirectX and COM The purpose of this chapter is to give the reader a brief introduction to the basic concepts of the DirectX Application Programming Interface API and Microsoft Component Object Model COM The chapter comprises e An introduction to DirectX e An introduction to COM e How DirectX and COM relate 2 1 The DirectX Kernel DirectX is an abstraction of many sub components that allows the programmer to uti lize any hardware that is DirectX compatible Rather than creating a module for each hardware manufacturer as was common a few years ago a programmer may use DirectX to get working code for virtually any home computer configuration DirectX is a single component controlling the communication with all hardware in a faster and more stable way than regular Windows components such as Graphics Device Interface GDI and Media Control Interface MCI see Figure 2 1 which are standard Windows libraries for graphics and sound The functionality of D
19. stack of 16 integers float varsF 16 stack of 16 floats int curr frame current animation frame int num frames total number of animation frames int curr animation index of current animation int anim counter used to time animation transitions int anim index animation element index int anim count max number of cycles before animation int xanimations MAX BOB ANIMATIONS 77 animation sequences public Bob metods Bob int x int y int width int height int num frames int attr int mem flags LPDIRECTDRAWSURFACE x destination surface virtual Bob void Bob void int Draw void int Draw Scaled int swidth int sheight int Load_Frame Bitmap_File_Ptr bitmap int frame int cx int cy int mode int Animate void int Scroll void int Move void int Load Animation int Anim index int Num frames int xsequence 3 ys 93 int Set Pos int X int Y int Set Anim Speed int speed int Set Animation int Anim index int Set Vel int Xv int Yv int Hide void int Show void int Collision Bob xbob2 Bob Bob x bob src Bob_ptr gendif bob h 54 E game h E E SE Sk Sk ke ke e He ok ole koe e ok o ok ke ok ok ook oko kk k k ok k k k k e e kok K K ok okok Copyright C 2004 Martin Persson All rigths reserved x File game h x Content Main Game include file Padilla ok kk ee kok I A ok ok okok ok watch for multiple inclusions
20. to concern him or herself with it As mentioned earlier in this thesis the authors won t go into detail regarding the COM objects but this introduction is included because DirectInput uses GUIDs to locate hardware keyboards mice joysticks hand controls etc 11 As opposed to containing any code POpen Graphics Library 13Simple DirectMedia Layer The SDL implementation in Windows uses DirectX for input and sound 11 2 5 DirectX and COM DirectX comprises a large number of COM objects These objects are located in DLL files that are loaded when a DirectX program is started Once in the memory the DirectX program can begin to use their interfaces which in turn use their methods to manipulate data When Microsoft created DirectX they had to offer more than efficient execution The game programmers wanted the API to be as easy to use as possible Since COM isn t a very nice interface to work with MS encapsulated about 90 96 of all COM calls in DirectX functions thus hiding the fact that it s COM one has to deal with Compiling a DirectX program requires a number of library files and associated header files Each component in DirectX usually has a lib file and a header file but these files don t contain the actual COM object but rather shells and references to the DLL files which do DirectX objects are almost exclusively called using a function pointer or function reference The value of this pointer is set during runtime not comp
21. CRUNCH define SCREEN BLUENESS define SCREEN REDNESS define SCREEN GREENNESS fade to black fade to white do a horizontal swipe do a vertical swipe a pixel disolve a square compression fade to blue fade to red fade to green MACROS IIMMMMMMMMMMMMIMMIMIMMMIMMIMMMMMIEEEM these read the keyboard asynchromously define KEYDOWN vk code GetAsyncKeyState vk code amp 0x8000 define KEY UP vk code GetAsyncKeyState vk code amp 0x8000 ANaw1 kWwNnNnr oO 1 0 0 1 initializes a direct draw struct define DD INIT STRUCT ddstruct memset amp ddstruct 0 sizeof ddstruct ddstruct dwSize sizeof ddstruct gt sets the volyme to 0 100 whitout crapy logaritms define DSVOLUME TO DB volume DWORD 30 100 volume V TYPES DAI EET 48 this holds a single sound typedef struct pcm sound typ LPDIRECTSOUNDBUFFER dsbuffer the ds buffer containing the sound int state state of the sound int rate playback rate int size size of sound int id id number of the sound pem sound xpcm sound ptr PROTOTYPES FT 5 IM MMMMMMMMIomIMMMMMWMMMIMMMIEPMPeM DirectDraw functions int DD Init int width int height int bpp int DD Shutdown void LPDIRECTDRAWCLIPPER DD Attach Clipper LPDIRECTDRAWSURFACE lpdds int num rects LPRECT clip list LPDIRECTDRAWSURFACE DD Create Surface int width int height int mem flags int
22. D walk force WALK BEG LEFT else 32 walk force WALK BEG LEFT e set walking left State VALKING LEFT ff set face left Direction FACING LEFT set the walking left animation Set Animation 1 7 2 Impulses Only once does input alter a movement variable directly on impulses such as jumping i f KEYDOWN VK SPACE 1 if On Ground KON GROUND yv 50 the initziation speed in the y aris from the jump 17The change in momentum over a short period of time The collision between too billiard balls is a good example of an impulse the energies and momenta of both balls change momentarily 33 8 Sound and Music Even though sound isn t implemented within this engine it is an important enough subject to merit a brief discussion Music and sound effects help giving depth and emotions to a gaming experience Com pare it to the sounds in a movie the soundtrack can enhance or destroy the whole viewing exprience and the sound effects most certainly affect us A good example is eerie music and sudden sound effects in horror movies Old games rarely used digitally sampled sound since this requires enormous amounts of memory for storage instead they used formats such as MIDI which use notation representations to play short sampled sounds thus creating music Later with the advent of CDs games began using CD tracks for their music Eventually HDD space became che
23. My Game Engine DEFINES Jg MMMMMMMMMMMMM MMIMMMMMMWtMlkkiltttlll defines for windows define WINDOW CLASS NAME WINXCLASS class name define WINDOW WIDTH 64 size of window define WINDOW HEIGHT 48 GLOBALS SSI MM MM PL L L lg Mg HWND main_window_handle NULL pointer to toe the window handle HINSTANCE main instance NULL pointer to the instance VI LE MEE ZI POETI LL RD WINDOW FUNCTIONS 711111 111111111111 111 11 M E III III B g lg Lg DML LRESULT CALLBACK WindowProc HWND hwnd UINT msg WPARAM wparam LPARAM lparam this is the main message handler of the system PAINTSTRUCT ps ZY used in WM PAINT HDC hdc JI handle to a device context what is the message switch msg case WM CREATE do initialization stuff here 45 return 0 break case WM PAINT start painting hdc BeginPaint hwnd amp ps end painting EndPaint hwnd amp ps return 0 break case WM DESTROY kill the application Post Quit Message 0 return 0 break default break end switch process any messages that we didn t take care of return DefWindowProc hwnd msg wparam lparam end WinProc IW PP EE EL int WINAPI WinMain HINSTANCE hinstance this HINSTANCE hprevinstance LPSTR Ipemdline int ncmdshow is the winmain function WNDCLASS winclass this will hold the class we create HWND hwnd generic wi
24. _y 256 int DI Init Mouse void int DI Init Keyboard void int DI Read Joystick void int DI Read Mouse void int DI Read Keyboard void void DI Release Joystick void void DI Release Mouse void void DI Release Keyboard void EXTERNALS MM IM MM B STL extern FILE fp error general error file extern LPDIRECIDRAW Ipdd dd object extern LPDIRECIDRAWSURFACE Ipddsprimary dd primary surface extern LPDIRECTDRAWSURFACE Ipddsback dd back surface extern LPDIRECIDRAWPALETTE Ipddpal a pointer to the created dd palette extern LPDIRECTDRAWCLIPPER lpddclipper dd clipper extern PALETTEENTRY palette 256 color palette extern PALETTEENTRY save palette 256 used to save palettes extern DDSURFACEDESC ddsd a direct draw surface description struct extern DDBLIFX ddbltfx used to fill extern DDSCAPS ddscaps a direct draw surface capabilities struct extern HRESULT ddrval result back from dd calls extern UCHAR primary buffer primary video buffer extern UCHAR xback buffer secondary back buffer 50 extern extern extern DWORD int int primary lpitch back lpitch start clock count memory line pitch memory line pitch used for timing these defined the general clipping rectangle extern int min clip x max clip x min clip y max clip y clipping rectangle these are overwritten globally by DD_Init extern e
25. a EX ODE De fen E d fed epa fe DAI AA od DN F mapeditor h G Screenshot vill 42 43 45 48 52 List of Figures 2 1 Classical Programming vs DirectX o ies pira 5 2 2 DirectX and Windows esa ert Xo ente s Le OX dC XGA S T 3 1 Module Overview s sure us exu deese stitit Sos Aes ENS S A oodd 13 3 2 Object Diagram of the Game Structures ues a ce ew ses src n e RS 14 4 1 Game Kernel structure 8 de s JE T esse ERE rs Pu Ud bip d MUS 16 5 1 Bitmap Example courtesy Q 6 so 9543549 E ees 18 5o IJIOBIBBeHbdPeC n E NO xeu gru ok 21 6 1 Velocity VeCctot rt a e e rl Erde LACE E ERNEUT E Eoi G 26 56 23 Collision Example nce s eos son e RE A A 1 28 6 3 Another Collision Example e e 28 64 Tine Approximations isi ta ld A A Ss Ge ONE A E 30 10 1 The Different Layers eiue uou dote hon OP A A nes 37 Al Empty Level Za a Kae Ra he ye Rh RS oa ok RA AA dada 43 G 1 A Screen Shot of an Example Game 2l len 64 1 Introduction According to the authors the gaming industry of today focuses solely on 3D games often with wondrous graphics as their main goal This has had the effect that modern games seldom have any depth story or feel to them The authors think that this is a shame and decided to create a 2D game engine in the hopes of returning some of the feel of the old games 1 1 Problem A 2D game engine is a relatively complex thing to design The main problem is to make the
26. a layer As it is now they have to be placed on the map in the correct order at 40 once or they ll be rendered incorrectly This is a major drawback if one should chose to alter a map Player and Enemy should be reimplemented somewhat to make them more similar to the kernel A common interface used by the kernel would be a good idea so it can simply store all moving objects in the same list and call their respective input AI physics and graphics functions without discrimination 41 References 1 10 11 12 13 14 15 Andr LaMothe Tricks of the Windows Game Programming GURUS Sams 2nd Edition 2002 Andr LaMothe Windows Spelprogrammering f r DUMMIES IDG AB ISBN 91 7241 006 X 1999 Steve Rabin AI Game Programming Wisdom Jenifer Niles 1st Edition 2002 David M Bourg Physics for Game Developers O Reiley amp Associates 1st Edition 2002 Unknown author Component object model Wikipedia the free encyclopedia home page http en wikipedia org wiki Component object model 2004 04 28 Unknown author Raster graphics Wikipedia the free encyclopedia home page http en wikipedia org wiki Bitmap 2004 05 14 Carl Nordling and Jonny Osterman Physics Handbook for Science and Engineering Studentlitteratur Lund 6th Edition 1999 J M Meriam and L G Kraige Engineering Mechanics Statics SI version Wiley 5th Edition 2003 J M Meriam and L G Kraige Engin
27. al Rullare void virtual void Al void Rullare ptr punc ARES typedef class Hoppare public Enemy protected public 57 Hoppare Hoppare LPDIRECIDRAWSURFACE x destination surface Hoppare Hoppare src Hoppare Enemy x Enemy src Hoppare Enemy 1 virtual Hoppare void virtual void Al void Hoppare ptr E 4 Player PLAYER CLASS M 111111 LL LLI LL A AAA AAAAAAAAAAAAAAAAAAAAAAAAAAAA AAA AAA AAN NNS typedef class Player public Character A as LR this is the Player class protected void Init void used fore the movement of enemies when the player is moving Enemy ptr Sublevel_Fiender int Antal Fiender i Sublevel public Player int X int Y int Width int Height int Num frames int Attr int Mem flags LPDIRECTDRAWSURFACE x destination surface virtual Player void void Input void void Logic void void Player Move void void Set Enemies Enemy ptr xFiende arg int antal fiender void Move Level int x int y Player ptr E 5 Sublevel NT BER A E AS typedef class ubleve protected Terrain in dynamic arrays Terrain ptr Ground 3 the original terrain that will be used to clone all other terrain Terrain ptr Original Ground NUM ORIGINAL GROUND the player doll It is the referensepoint to all othet objekts in the map it is not the starting possition of the player the starting possition will be set by the game
28. alk_force public Sublevel ptr sublev void Move int dx int dy Character int X int Y int Width int Height int Num frames int Attr int Mem flags LPDIRECTDRAWSURFACE x destination surface virtual Character void Character Bob used for cloneing of enemies int Collision Terrain_ptr Block inline bool Collision_v_1_5 Terrain_ptr Block returnvalue depends on where the character is int On_Ground void void Set Ground Terrain ptr Global_Ground int size void Set Referencepoint Terrain ptr Reference void Set Sublevel Events Terrain ptr xhandelse arg int antal handelser Character ptr E 3 Enemy ENEMY CLASS SSI MI M MMMMMMMIIMMMMIoiA ttlllhl typedef class Enemy public Character this is the enemy class protected public Enemy int X int Y int Width int Height int Num frames int Attr int Mem flags LPDIRECTDRAWSURFACE x destination surface Enemy Character used for cloneing of enemies virtual Enemy void virtual void Init void virtual void Enemy Move void virtual void Al void motsvarar input i player virtual void Logic void Enemy ptr typedef class Rullare public Enemy protected inline bool Reached Right Edge void inline bool Reached Left Edge void public Rullare Rullare LPDIRECIDRAWSURFACE x destination surface Rullare Rullare src Rullare Enemy x Enemy src Rullare Enemy virtu
29. an file int Type Index double t x t y double t xv t yv used to make the ForeGround and BackGround move faster or slower than the player double SpeedFactor void Set Type int type arg void Set SpeedFactor double SpeedFactor arg void Set Pos int x arg int y arg int Move void void Move int X int Y Terrain int X int Y int Width int Height int Num frames int Attr int Mem flags LPDIRECTDRAWSURFACE x destination surface Terrain void Terrain Terrain terrain_src Terrain ptr E 2 Character CHARACTER CLASS gg M MM M LISI ILIA LA LALI LLALLA ILIA LULI LLI LLALLA ZY ska senare rvas ner till en underklass f r spelare och en f r varje fiende typedef class Character public Bob this is where the physics engine is implemented protected attrubutes int Sty Fys Smi Int Psy Kar Sto skills jag l gger till mer sem used to know what direction the player is faceing int Direction used to know what the player is doing int State pointer to the ground in the sublevel Terrain ptr Ground the size of the map in the sublevel int Terrain Size the reference Terrain ptr Referencepoint void Move Level int x int y only used by the player inline bool Ground_Collision void int Antal_Handelser_i_Sublevel Terrain ptr Sublevel_Events These values are used for the physics 56 int mass float area float Cd float w
30. aper and wav files were used At that time the quality of both sound effects and music increased alot thanks to the capabilities of the sound format Nowadays the use of compressed sound formats such as MP3 and OGG are gaining in popularity since they permit alot of sound to be stored with a small amount of space 8 1 Sound in the Engine As mentioned above there currently is no sound support within the engine Eventually though it will be and should then use the existing DirectX Audio API within a simple wrapper class Music will be part of the Sublevel class possibly to be triggered by events see Sec tion 10 Ambient sounds will be part of sublevels to be played semi randomly and sound effects will be triggered by events and character actions 34 9 The Basics of Artificial Intelligence Since Artificial Intelligence is a whole science this thesis won t be able to do more than scratch the surface The object Enemy has a member function calles AI which replaces the Input O function of the Player object Since the player orientates himself by looking at the screen the enemies will have to orientate themselves in a similar fashion The class Character which Enemy inherits has a reference to the terrain of the level and can use this to see what surrounds it In his book 3 Steve Rabin includes an article that mentions how to implement intel ligent maps with objects that send useful information to computer controlled ch
31. aracters M in which items that may provide food for the char The game in question was The Sims acters tell the characters about this if they come close The characters then evaluate their current needs and wants and if the want for food is high enough they will then approach the object and get something to eat A similar feature in this game engine would be to let obstacles and hiding places tell the enemy characters that they may hide there and if the enemies think that an ambush is appropriate they will hide A more advanced AI would make sure that the object is large enough to hide it completely and try to stand as close to the center as possible to ensure protection A simpler implementation of AI would be something that prevents enemies from falling over edges perhaps by making them stop and change direction or by making them look for platforms to jump to None of the ideas above have been implemented yet but they are all possible for future versions 35 10 The Level System A graphical game without a playing field of some kind doesn t have much to offer and unless the game in question is a board game a game with only a single layout grows old rather quickly Therefore this game engine comes with a level system and level editor to simplify the creation of new levels A level comprises five different parts foreground ground background enemies and events foreground ground and background consist of Terrain obje
32. ctX by creating a DirectDraw object and two drawing surfaces which are used to make sure the drawing of a new frame is smooth BOB takes care of the coordinates at which a bitmap will be drawn what image should be shown how quickly images should change and in what direction and velocity the object is moving BOB also draws the image on the surface When Draw is called BOB simply tells DirectDraw where to draw and what to draw by using the Blt method of a DirectDraw surface Figure 5 2 shows how BOB is inherited by the other graphical components of the game Character is the base of all movable objects and is inherited by Player and Enemy which are somewhat more specialised Player is the object that handles input from a human player and Enemy is an abstract class that is inherited by all computer controlled characters in the game Enemy contains a virtual function AI O which replaces the Input function of the Player class Rullare and Hoppare are the two enemy types used in the demo games created for this report 20 Terrain Rullare AA SSS Figure 5 2 BOB Inheritage 21 6 Physics For a game to be satisfyingly realistic it will have to use realistic physics This means that the movements of characters monsters projectiles and simlar will have to adhere to the same laws of physics that act in the real world This chapter will explain what laws will be needed why they are needed and how they
33. cted 6 3 Collision Detect There must be a way to prevent objects from moving through walls floor and ceilings as well as making sure that something happens when objects collide with eachother The BOB object has a function which will check if two BOBs are overlapping There is however another problem 6 3 1 Running Through Walls Keeping track of the speed and direction of a moving object in a game can easily be done with a velocity variable for each axis For each frame the position of the object will change as many pixels as the velocity variables state in each direction Now imagine a 20 pixel wide object moving at the speed 200 pixels per frame towards a wall Fig 6 2 a The object is 50 pixels away from the wall which is 50 pixels thick Let s move one frame forward without collision detect or with collision detect only on the position where the object ends up it would move through the wall and stop 80 pixels farther away Fig 6 2 b 2T GJ v 200 DJ v 200 Figure 6 2 Collision Example This is of course not acceptable in a game claiming to have a decent physics engine Imagine how irritated a player Fig 6 3 a would be if he went straight through a ledge he aimed for Fig 6 3 b rather than stopping at it Fig 6 3 c Or possibly worse imagine people running through all the walls from the beginning of a level to the end cheating their way through a whole game a b C Figure 6
34. cts Enemies is an abstract class that is inherited to create moving objects which are con trolled by artificial intelligence The only implementation that has to be done is construc tors destructors the AI function and in some cases the physics and logic functions Events are areas on a map which trigger special occurances when the player enters them Each event has to be implemented separately to work properly Events currently use the Terrain class but that will change in future versions Objects are drawn in the following order background ground events enemies and foreground with background being drawn first and foreground last The player is drawn concurrently with the enemies Internally within the layers objects are drawn in the order they are placed on the map If a cloud were to be placed after a bush the cloud would appear in front of the bush Objects in background ground and foreground have an attribute called SpeedFactor By changing its value the object s speed relative to the player changes A value of 0 makes the objects freeze on the screen and follow the player s movements It is not recommended to change the value of this attribute for objects in the ground layer Collision detect is only performed on the ground layer foreground and background are solely for graphical purposes Figure 10 1 shows how the layers are drawn on the screen The long bar at the bottom is part of the ground layer The cloud and the left bush
35. d The same applies to DirectSound DirectSound3D and DirectMusic which are now bundled into DirectX Audio A great advantage of this system is complete backwards compatibility any program that works with old versions of DirectX will work with new versions Thanks to the usage of COM there s not even a need to recompile programs when a new version of DirectX is released Another advantage is that when you learn one version of DirectX you basically know them all New versions don t alter old functions merely add more functionality 2 2 HAL and HEL Figure 2 2 shows a couple of things that have not been mentioned thus far Hardware Abstraction Layer HAL and Hardware Emulation Layer HEL Their purpose is to fill any gaps in hardware drivers If some hardware component does not support a certain function HAL and HEL will take care of it HAL is as the name suggests a layer that communicates directly with the hardware DirectX makes sure that available hardware is used whenever possible to minize the load on the central processing unit CPU The HAL implementations lie within the drivers of the hardware When HAL cannot be used for a specific task due to hardware restrictions HEL will emulate hardware capabilities to let the CPU take care of the calculations instead This results in slower but working code and is vital to ensure universal compatibility Compared to the 80s programmers have an easy job creating games with DirectX 2
36. e formulae described above are used in the game engine to make objects move as nat urally as possible The most basic is the gravitation that pulls all objects towards the ground this is implemented using actual gravitational constants and masses for all objects and the resulting accelleration is stored in the Level objects The next part is drag and user input Both these instances cause force variables to be set to certain values The drag calculations are performed with the actual area of the object in question aswell as proper density and pressure values When all forces have been correctly setup the physics engine will calculate the proper acceleration and alter the velocity variables xv and yv Appendix D accordingly Fig ure 6 1 shows a player character with the velocity vector actually drawn next to it This was only used in debug mode the vector does not show in normal gameplay 25 Figure 6 1 Velocity Vector 26 Example code The actual velocity variable xv int walk force dragx mass Finally there s collision detection which prohibits objects from falling through the ground they re being pulled towards When an object touches a piece of ground its velocity along the y axis is set to 0 When touching the ceiling the same velocity vector is set to 0 and gravity kicks in Collision with walls are handled the same way as with the ground but it s the veolcity along the x axis that is affe
37. e line between the bottom left corner and the top right 29 ae xl yl dx Figure 6 4 Line Approximations corner of the grid position relative to a midpoint short horizontal lines If the blue line is below the current midline we plot the next pixel to the right If however the blue line is above the midline we should plot above and to the right If BlueLine lt Midpoint Plot Right _Pixel Else Plot_AboveRight_Pixel Now to determine if a line is above or below a midline at the specific point To do this we work a bit with the line funktion y kx m where we replace k with dy dz d y erem dx dz y dy x dz m 0 dy x dzx y dzx m Any point x y above the line will give a negative result and a point below the line 30 will give a positive result We use this fact to define a function F such that Flx y 2 dy r 2 dr y 2 dx m the factor 2 will become evident shortly When provided with a midpoint between the two possible next points the function F will return lt 0 when the true line is below the midpoint and gt 0 when the true line is above If we start at point x1 y the next point will be either x 1 yj or zi 1 y 1 so the reference midpoint will be x 1 yj 1 2 In order to determine which point is the best approximation we evaluate F for the midpoint 1 1 F athu 2 dy z 1 2 dz nt 2 dx m Since F ri y1 2 dy z 2 dz y 2
38. e player wants it to do the Enemy class has the member AI to simulate user input Both classes use the function Logic which handles basic collision detection and movement Events such as doors one can walk through will be implemented on a case to case basis These implementations will deal with special animations sounds and possible movie sequences 17 5 Graphics Engine A graphics engine is the part of a game that simplifies the drawing of things on a screen Using a graphics API such as DirectX or OpenGL directly is quite arduous with lots of repeated function calls and similar The graphics engine used in this program is a rewritten version of Andr LaMothe s engine described in 1 and 2 The main difference is that this version is object oriented with classes as the main datatype rather than structs The central object is the Bitmap Object Blitter BOB see Appendix D which loads a bitmap and shows it on the screen 5 1 Bitmaps Bitmaps constitute the simplest form of computer graphics They consist of a matrix of numbers corresponding to colours Figure 5 1 Bitmap Example courtesy of 6 18 There are different versions of the bitmap format among these are 1 bit Also known as monochrome Each value in the value matrix points to one of two colours in a small palette These are usually black and white but can be changed to other values 8 bit Like the monochrome format the values po
39. ectSound3D and DirectMusic into DirectX Audio The old components still exist for backwards compatibility 2 3 11 DirectShow This is the component that is used for playing video in DirectX It will automatically locate any hardware acceleration and use it if it exists This component is very useful since you don t have to care about anything but loading the film and playing it on the monitor 2 4 COM Computer programs of today can contain millions of lines of code Red Hat 7 1 for example contains over 30 million lines of code 15 The sheer size of this code requires a structured hierarchy and data abstraction to avoid chaos COM short for Component Object Model is one solution to this problem COM is designed to be modular like pieces of Lego or microchips They work the same way no matter what you connect them to They are all modular and they care only about what input they get not what sent it to them In the same way COM doesn t care what language is used to send it input as long as it gets input it knows how to deal with This modularity comes with a few nice advantages It provides for easy re implementation of a component since any COM object with the same interface can replace another and it allows components to be programmed in different languages thus giving the developers a chance to utilize the language that is best for any given task Yet another step towards modularity comes from the fact that COM objects are c
40. eering Mechanics Dynamics SI version Wiley 5th Edition 2003 Zelda II The Adventure of Link Nintendo 1988 Robert A Adams Calculus Addison Wesley 4th Edition 1998 Bjarne Stroustrup The C Programming Language Addison Wesley Special Edi tion 2000 Hexar Drawing Lines The Bresenham Algorithm http gamedev cs colorado edu tutorials Bresenham pdf 2004 05 10 Charles Petzold Programming Windows Microsoft Press 5th Edition 1998 David A Wheeler More Than a Gigabuck Estimating GNU Linux s Size home page http www dwheeler com sloc redhat71 v1 redhat71sloc html 2004 05 30 42 A User Manual for the Map Editor The level editor isn t exactly user friendly but all functionality is described in a text field on the left hand side of the monitor Some debuggning information is still printed The screen is partitioned into two surfaces edit area and toolbox The edit area is the actual map as it will look in the game and the toolbox contains all the objects that can be placed on the level Figure A 1 shows what the editor looks like before any objects have been placed on the edit area Muspossitioner X 512 Y 384 P editerinstyan mouse state rgbButtons 0 0 mouse state rgbButtons 1 0 antal block i background 0 antal block i ground 0 antal block i foreground 0 aktuellt lager aktuellt block 1 V lj lager med siffertangenterna background 0 ground 1 foreground 2 K och L ndrar SpeedFacktor p
41. effinitions SSLILILILILILILLLILILLLLLLLLLLLLLLLLLLLLLLLLLLLSLLLLLLSLSSV Bitmap typedef class Bitmap public this contains the bitmapfile header BITMAPFILEHEADER bitmapfileheader this is all the info including the palette BITMAPINFOHEADER bitmapinfoheader we will store the palette here 52 PALETTEENTRY palette 256 this is a pointer to the data UCHAR xbuffer Bitmap void int Flip Bitmap UCHAR image int bytes per line int height int Load File char xfilename int Unload File void Bitmap File x Bitmap_File_Ptr Bob typedef class Bob the Bitmap Object Blitter class Bob protected the bitmap images DD surfaces LPDIRECIDRAWSURFACE images MAX BOB FRAMES the surface to draw on LPDIRECTDRAWSURFACE x Destination Surface public LPDIRECTDRAWSURFACEx Get Destination Surface void return Destination Surface LPDIRECTDRAWSURFACEx Get images void return images protected int state the state of the object general int anim state an animation state variable up to you int attr attributes pertaining to the object general int x y position bitmap will be displayed at int xv yv velocity of object int width height the width and height of the bob int width fill internal used to force 8xx wide surfaces int counter 1 general counters int counter 2 int max count 1 general threshold values int max count 2 int varsI 16
42. er and levels One of the members is of type Level see Appendix E 6 which is a master 6the main function in a Windows program 16 level with a number of sublevels Appendix E 5 These sublevels contain the actual maps that the players can see and interact with The Level object has a function called Playing Level The function acts like a state machine deciding what sublevel to call Playing Level has to be called once for each frame just like Game Main The sublevels have a method called Playing which handles input and logic for the game The sublevel also contains the enemies and events Some of the enemies are local to the sublevel and will disappear reappear when the player enters and exits the room while others belong to the master Level object and can only be killed once A good example of a similar system is Zelda II 10 where the castles are levels and all the rooms one can enter are sublevels The game logic and physics is implemented in the object Character which inherits BOB and is inherited by Player and Enemy The Player object has a pointer to the terrain in sublevel which is used when the player moves It is not in fact the player that moves but all the surrounding terrain and enemies that are moved around the player which always stays centered on the screen Player and Enemy are fairly similar The main difference is that where Player has the function Input that makes calls to DirectInput to do what th
43. ilation and is yet another step to modularization and hardware independence 12 3 Game Engine Structure Figure 3 1 shows a simple overview of the modules used within the engine The first step is initialization which then allows the main event loop to take control and start executing game instructions The main event loop consisting of input handler AI executioner physics simulator and graphical engine continues until the exit command is given by the user most commonly by pressing the escape key For all enemies For all BOB s Figure 3 1 Module Overview The only purpose of the main event loop also known as the Kernel is to tell the other objects when it s their turn to execute and to make sure that each frame within the game takes place at its correct time Input is handled by the Player object DirectInput is called to check if any of the used keys are pressed and variables are set with corresponding values For example if the left MA frame is one image on the screen When a game is played a multitude of frames are shown every second to ensure smooth movements 13 key is pressed the variable walk force is set to a value appropriate for walking to the left When this is done the physics engine is called into action The values set by the input are calculated into accellerations which then affect the velocities of the object in question mainly the player character but also weapons he might
44. in ptr Fiender The evets used to clone the events on the map Terrain ptr Original Events NUM EVENT TYPES Terrain ptr Events int Antal_Fiender int Current Enemy type int Current Enemy int Current Terrain Block int Current Layer int Current Original Block int Current Event int Current Event Type int Antal_Handelser bool show ring int objekttype metods Adds an enemy to the map void Nev Enemy int Enemytype 62 Removes an enemy from the map void Delete Enemy int index Adds an event to the map void New Event int index Removes an event from the map void Delete Event int index Returns true if the block is clicked bool Terrain Click Left Terrain ptr block bool Terrain Click Right Terrain ptr block Metod that adds an object to the map void New Terrain int original terrain index int layertype Metod that removes an object in the map void Delete Terrain int intex int layertype Saves the map to a x ban file void Save map char filemane ZY Loads a valid x ban file into the memory void Load map char Filemane Moves a terrainblock void Move Terrain Block int index int layertype int x distance int y distance Structuring of Editing void Mouse Editing stuff void void Keyboard Editing stuff void void Move Map int x int y void Move Map Objekt Terrain ptr objekt int x int y public the construkt
45. int to palette entries The difference is that the palette has room for 256 colours rather than just two 16 bit T wo bytes are used to represent the colour of each pixel Each prime colour uses five bit each so the format actually only uses 15 bit not 16 24 bit graphics can be converted to 16 bit by dividing each of the bytes with 8 and then appending the values to eachother in a two byte variable coli6bit red8bit gt gt 3 lt lt 10 green8bit gt gt 3 lt lt 5 blue8bit gt gt 3 24 bit Each pixel is made up of three bytes representing the colours red green and blue These prime colours are then combined with values from 0 to 255 to make just about any colour possible Animations with bitmaps are accomplished by loading a number of images to the video memory and then switching between them rapidly All these images are stored in the same bitmap which is partitioned into squares The Bitmap class is used to read data from a file and is then used as an argument for loading graphics into a BOB Look at the end of the first page of Appendix D for a class definition of the bitmap 5 2 Bitmap Object Blitter As mentioned previously BOB is the central image component of this engine See Ap pendix C and D It is an object oriented version of the struct created by Andr LaMothe BOB is an abstraction on top of DirectDraw and is designed to implement a more user 19 friendly interface The class uses Dire
46. irectX is such that it gives the programmer close to direct control of the hardware DirectX achieves this by using a multitude of libraries and drivers writ ten by both Microsoft and the companies who design and construct hardware Microsoft defined a set of data structures and algorithms to be used by the hardware creators pro grammers when they make DirectX compatible drivers for their components This way the 3A calling convention by which a program can access services such as the file system or monitor It is used to abstract underlying logic thus enabling portability The Windows standard COM object for graphics The Windows standard COM object for sound fast primitive fast slow few options fast WinSock Win32 Input Win32 Network Application Application slow slow ast reliable very fast fast GDI 4 9 MCI Network 94 DirectX 4 Input Lots of latency fast Sound sound output Y output CI S eo Figure 2 1 Classical Programming vs DirectX only functions that are being called are DirectX functions and the application programmer has no need to know what happens at the backend With DirectX 8 0 Microsoft integrated DirectDraw and Direct3D into a single com ponent DirectX Graphics DirectDraw and Direct3D still exist but they are no longer update
47. ject that can hardly be com pleted in the amount of time available for this paper The authors have therefore decided to create the level system and the game physics and then make the rest of the details if there is enough time 1 4 Goal When this dissertation is complete the following shall be done e A well documented and working game engine API that allows programmers to create 2D games with a minimum amount of foundation coding so that they may focus on the gaming experience A good implementation design that will make it easy to add new features later A working two dimensional physics engine A useful level editor that can be used to create the maps of the game A simple and general way to program the AI of the enemies in the game A virtual class for enemies 1 5 Disposition Section 2 gives a shallow technical introdction to DirectX and COM These tools are then used in sections 5 7 and 8 Section 3 shows how the modules of the game are connected and gives an introduction to sections 4 through 9 Section 4 gives a description of the game kernel which handles startup exectution and shutdown of the game engine itself Section 5 explains image formats and relates back to the second section with Direct Draw Sections 6 and 7 show how a player may alter the playing realm through input and physics Section 6 also describes some of the issues related to physics in games Sections 8 and 9 discusses sound and artificial
48. lay This is the network communications component of DirectX DirectPlay allows you to create abstract connections with other computers with an IP address through any medium You don t have to know much if anything about network programming to be able to use DirectPlay properly There s no need to understand the protocol stack or know which socket to use DirectPlay supports sessions and lobbies A session is an ongoing network game and a lobby is a server connection that you connect to inbetween games 2 3 7 Direct3D The 3D graphics part of DirectX is split into two subcomponents Direct3D Retained Mode Direct3DRM and Direct3D Immediate Mode Direct3DIM RM is a basic high level system that is relatively simple but slow IM is a low level system that is alot more complicated but also alot faster The science of 3D graphics optimization is well outside the scope of this document 2 3 8 DirectSetup DirectSetup is used to simplify the installation of DirectX components DirectX is very complex and therefore hard to install manually 2 3 9 DirectX Graphics With version 8 0 of DirectX Microsoft combined DirectDraw and Direct3D to enhance performance and allow 3D effects in a 2D environment Both DirectDraw and Direct3D still exist and work but to call them you have to use the interface from before version 8 0 9 2 3 10 DirectX Audio As with DirectX Graphics Microsoft combined the sound components DirectSound Di r
49. litter E ODE or LX ar aed 6 Physics 6 1 Newtonian Mechanics e sees esse NX Wee d A 6 1 1 Movements Acceleration and Inertia Oke APNG e x denies ca Ae En dS s M LH qi 612 Pree tales e pese ue nach aree EREMO a se A 6 2 Physics Within the Game usse mx e RUE EO du eon uA erede 6 3 Collision DOSE a tonsa God pma f a D pni de up rtu fe sd n ped 6 3 1 Running Through Walls aa Roe E RR BS IIR WSIS ES 6 3 2 The Bresenham Algorithm va a ras ow xe key e a 7 Input Tal FOCOS se ik ati MESE E OON ge TH ORCI OE E EE f RE OE BY Bb de n T2 IPS SS car Qual Virtute dil ie Ll rye Qe Fes rl Bhs eager bls qd ga drip a s Gh n 8 Sound and Music 8 1 Soundin the Engine acp aude oteerd me EVE E E E 9 The Basics of Artificial Intelligence 10 The Level System 11 Conclusion Tl Achievements Vs eek A a ee ue uL due aT vil 13 16 18 18 19 22 22 22 23 24 25 27 27 29 32 32 33 34 34 35 36 38 11 2 EvaluBtlOn ov 6 ss ommo ud ine Ad eA din aln A A ACY A ANOR A TAG Buburest lampa aerem Eee References A User Manual for the Map Editor B winconsole cpp C motor h D bob h E game h BE Terrains sc sd s ren sb S end dar Boa ds bte Ex UU dedos EZ UBI DI a ND RORISeDISOGCNU SiS ED SE di AA ek Edo Enemy as fee alae puce oa Recien pone ee eg SEEN Red EG Player 23406 RA AS A er ds Re RU XR Eo DUDE VE or upto SNR eo detesta x t IMS SUE Mo NR E6 Levels E EAS O A AE a ae aot
50. ndow handle MSG msg gemeric message HDC hdc generic dc PAINTSTRUCT ps generic paintstruct first fill in the window class stucture winclass style CS DBLCLKS CS OWNDC CS HREDRAW CS VREDRAW winclass lpfnWndProc WindowProc winclass cbClsExtra 0 winclass cbWndExtra 0 winclass hInstance hinstance winclass hIcon LoadIcon NULL IDI_APPLICATION winclass hCursor LoadCursor NULL IDCARROW winclass hbrBackground HBRUSH GetStockObject BLACK BRUSH winclass lpszMenuName NULL winclass lpszClassName WINDOW CLASSNAME register the window class if I RegisterClass amp winclass return 0 create the window note the use of WS_POPUP if hwnd Create Window WINDOW_CLASS NAME class 46 TITLE title of the window WS POPUP WS VISIBLE 0 0 2 9 WINDOW WIDTH width WINDOW HEIGHT height NULL handle to parent NULL handle to menu hinstance instance NULL creation parms return 0 save the window handle and instance in a global main_window_handle hwnd main instance hinstance Game Spel perform all game console Spel Game_Init specific initialization enter main event loop while 1 if PeekMessage amp msg NULL 0 0 PM REMOVE test if this is a quit if msg message WM QUIT break translate any accelerator keys TranslateMessage amp msg pointer send the me
51. om piled into Dynamically Linked Library DLL files which are loaded during execution rather than during compilation this means that components can be exchanged without meddling 10 anything with the main program 2 4 1 The COM Objects A COM object is a class that implements a number of interfaces used to communicate with it The most basic object implements the interface IUnknown which doesn t really do anything For an object to be useful however the programmer has to implement at least one interface of his own and add functionality to it Since the objects are completely binary and have a uniform calling convention it doesn t matter what programming language they are coded in nor does it matter what language they are called from They will always behave predictably One of the authors waits for the day when DirectX and COM are ported to Linux so games will be platform independent whereas the other claims that this could already be the case if only developers used OpenGL and SDL Y 2 4 2 GUID To create a COM object a Global Unique IDentifier GUID is needed A GUID is a 128 bit long integer that is created by the operating system The integer is divided into a four byte word three two byte words and six single byte words 5 The whole GUID is always unique within the system and is used to distinquish objects A GUID is assigned to a COM object during runtime by the operating system itself The programmer doesn t have
52. or Map Editor Bob ptr global mouse the destruktor Map Editor void to be used in the main event loop void Editing void metod that draws all terrain blocks and enemys and events void Drav void xMap Editor ptr game console class Game protected GAME OBJEKTS SSL MM MM M M M M M M Map Editor ptr editorn public the mouse Bob ptr mouse public because the editor meeds it GAME FUNKTIONS T III LLI ALLA LLALLA LLI ALLA LLALLA ALAA LALI LALI int Game Init void parms NULL int Game Shutdown void x parms NULL int Game Main void parms NULL h endif game h 63 G Screenshot Figure G 1 shows what the test game looks like The arrows are velocity vectors and Figure G 1 A Screen Shot of an Example Game aren t actually shown during gameplay 64
53. peed factor The default value is 1 which means that object is stationary on the map this is the best value to use for most objects A value less than 1 makes the object move slower than the player appearing to be farther away from the camera and a higher value makes it move faster therefore close to the camera Even the objects in the ground layer can have their speed factor altered but this isn t advisable since it would look rather strange The view is changed by using the arrow keys when no object is marked The speed facter isn t used when moving around in the editor only within the game itself Press S to save the map It will be called level00 ban and placed in the same folder as the map editor To open the map level00 ban in the editor press D 44 B winconsole cpp define WIN32 LEAN AND MEAN define INITGUID include windows h include important windows stuff Hinclude windowsx h include lt mmsystem h gt include lt objbase h gt include lt iostream h gt include important C C stuff Hinclude conio h Zinclude lt stdlib h gt include lt malloc h gt include lt memory h gt include lt string h gt include lt stdarg h gt Hinclude lt stdio h gt include lt math h gt include lt io h gt Hinclude fcntl h include ddraw h directX includes include dinput h directX includes include dsound h directX includes include game h
54. physics in the game correspond in a good looking way to the objects on the screen using the existing graphics engine BOB 1 The engine will except for the the graphics API be built from scratch Problems that have to be solved is how to make the architecture of the levels be useful to the physics A great part of the problem with the physics will be collision detection between the player and the map itself The input handling using DirectInput will have to be integrated to the movement physics of the player How to make the enemies in the game orientate themselves in the environment will also have to be solved A level editor using the same map system as the game will also have to be implemented so that levels created using that editor can be loaded into the game The main part of the work will be programming the engine itself and parallel to the implementation write a documentation describing the engine LA level is an object containing a set of terrain a number of enemies and events which one may interact with The terrain parts of a level Sometimes used interchangeably with level 1 2 Purpose The purpose of this dissertation is to create a fully working game engine that can be used to create two dimensional platform games using DirectX The engine will also be the base that Martin will use when he creates his first commercial computer game 1 3 Limitation A fully functioning game engine is of course a massive pro
55. racter objects Players and Enemies which uses the physics and graphics engine The Input part of the project has been implemented as macros that check if a certain key is pushed or released Neither sound AI nor networking has been implemented due to lack of time 11 1 Achievements e A well documented and working game engine API that allows programmers to create 2D games with a minimum amount of foundation coding so that they may focus on the gaming experience Mainly succeded what is missing in the engine is good grahics sound effects music and a good story Once these elements exist it could be called a complete platform game e A good implementation design that will make it easy to add new features later Done Is is easy to add new terrain types and new enemies to the game The level editor uses a general system for the maps in the game that is easily modified The 38 only coding that needs to be done for each game is for the events but that can t possibly be avoided A working two dimensional physics engine Done No bugs discovered so far A useful level editor that can be used to create the maps of the game It is useful and general The level designer needs no knowledge of programming to use it A simple and general way to program the AI of the enemies in the game AI is never simple when it tries to be good but the Enemy class has a virtual method called AI that was not implemented in this tesi
56. resented The system for the architecture of the levels is described as is its connection to the graphics engine The last section of the report is an evaluation and suggestions for what to do in the future A user manual for the level editor is included as an appendix Contents 1 Introduction 1 1 1 1 2 1 3 1 4 1 5 2 3 The Components of DirectX usd o sees ere sr rr ss ve st 2 4 Problemi eere Ne m tere tim E AM te 1 iq AC LamutaetlOHleecefisem meus e ee a oe NASCE DirectX and COM 2 1 The DirectX Kernel 00000002 eee ee 2 HAT and HEL eme ke da Gy e BA Se e e ee e ee n a 2 3 1 DURS 2 3 3 2 3 4 2 3 9 2 3 6 20 1 2 3 8 2 3 9 2 3 10 2 3 11 2 4 1 2 4 2 wow DN N N DirectDraw TUE ad s g e q DirectSound 04 a A adero trt EA DirectSound3 D i suse sot A dn Me IEEE EET Direct MUSIC oe oM E Dep dX oe ut DifectInput ad war d Tae dora ar qud e GAP nos Direct PIA s mae dee IAE e C Hr pate UE Q an s a od Directo Doe tica le deti S need vu o Udo V qe Ha DireetSetup zan mc A A e a a O o o o oo oo oco oo O MI Q A Ah DirectX Graphics st sh sci oe HERO oe ds DirectX AUdioc scu aan aa ai Rat ode 10 Directshow let A oem xcu MR be a ee a AA 10 GUID up Reb at es ira USER MS Y SER n Gs 11 2 5 Dir etx and OM zo ana ee oh A uln als 12 vi 3 Game Engine Structure 4 The Kernel 5 Graphics Engine DEL DEBEAS ween dyk od opt ous Se E au Pu HELP RADEN eed K di he 5 2 Bitmap Object B
57. s A virtual class for enemies Done derived from character There are no actual enemies of the class Enemy in the game since all enemies are inherited from the virtual Enemy class 11 2 Evaluation The end result is more than satisfactory The collision detect system in the physics part of the engine uses a much more complex algorithm than was originaly planned and the system for maps has pixel precision for placing objects on maps There has been no great problems throughout the work on the engine The goals for the project were set before the implementation and design began so the work has been a more or less straight line from the beginning to the end Not all originally planned goals namely network sound and Al were completed due to lack of time But this doesnt mean they won t ever be implemented they have merely been postponed to a later project a real game using the engine 39 11 3 Future Plans Sound and music haven t played very large parts in the work so far The very first sound related thing to do in the future is to add support for sound objects Music will be added to the Sublevels and possibly be directed by events Sound effects will belong to the objects responsible for making noise For example the sound of gunfire will be stored in the character object that holds the gun Ambient sounds can be stored in Sublevel and be played somewhat randomly to enhance the atmosphere of the map This might
58. ssage to the window proc DispatchMessage amp msg end if main game processing goes here Spel Game Main end while shutdown game and release all resources Spel Game Shutdown return to Windows like this return msg wParam Y end WinMain WII P LP MLB LEE 47 C motor h Copyright C 2004 Martin Persson Directly stolen from Andr LaMothe x File motor h x Content Game Engine include file PK OK OK CK CK OK CK CK K K K OK OK K OK OK CE CE CE CE OK OK CE CE K K K OK OK OK OK K CE CE CE CE CE CE CE CE OK OK OK OK OK CE CE CE CE K K K K OK K OK OK OK CE CE CE OK OK OK K K oe o e K K OK K K ifndef motor h define motor h DEFINES Jg MMMMMMMMMMMMMMMIMMMMMMMMlloMMMhHHwYTOoO default screem size Zidefine SCREEN WIDTH 1600 size of screen define SCREEN HEIGHT 1200 define SCREEN BPP 8 bits per pixel basic unsigned types typedef unsigned short USHORT typedef unsigned short WORD typedef unsigned char UCHAR typedef unsigned char BYTE define MAX SOUNDS 64 max number of sounds in system at once define SOUND NULL 0 define SOUND LOADED 1 define SOUND PLAYING 2 define SOUND STOPPED 3 voc file defines define NVB_SIZE 6 size of new voice block in bytes screen transition commands define SCREEN DARKNESS define SCREEN WHITENESS define SCREEN SWIPE X define SCREEN SWIPE Y define SCREEN DISOLVE define SCREEN S
59. ted sound programming was black magic where every sound card manufacturer supplied their own drivers and the game programmers had to make a routine for each card Remember old games where you had to chose sound card IRQ and DMA Thanks to DirectX you don t have to do that anymore 2 3 3 DirectSound3D The 3D version of DirectSound allows you to place sound sources in a room the same way you do with regular 3D objects When you move around in the room the sound will change according to your movements DirectSound3D supports among other things reflection refraction and the Doppler effect 2 3 4 DirectMusic The component handles the music in your games is called DirectMusic Mainly MIDI MP3 and CD tracks are used 2 3 5 DirectInput DirectInput handles all the input from devices such as the keyboard mouse or joystick It supports Force Feedback At the moment there s no support for speech recognition or voice control but this would be the logical place to put that when it arrives 5 A standard for representing musical information in a digital format MIDI does not use recorded sound for playback but rather mathematical formulae for how each note should sound for every instrument MPEG 1 layer 3 An audio compression standard that can compress CD tracks about ten times with very little quality loss 10A standard for input devices that allows the user to feel a fairly natural response from the game 2 3 6 DirectP
60. x LPPALETTEENTRY color int Get Palette Entry int color index LPPALETTEENTRY color int Load Palette From File char filename LPPALETTEENTRY palette int Save Palette To File char filename LPPALETTEENTRY palette int Save Palette LPPALETTEENTRY sav palette int Set Palette LPPALETTEENTRY set palette int Rotate_Colors int start index int colors int Blink Colors void gdi functions 49 int Draw Text GDI char text int x int y COLORREF color LPDIRECIDRAWSURFACE lpdds int Draw Text GDI char text int x int y int color LPDIRECTDRAWSURFACE lpdds error functions int Open Error File char filename int Close Error File void int Write Error char xstring sound int Load VOC char xfilename int Load WAV char filename int control flags DSBCAPS CTRLPAN DBBCAPS CTRLVOLUME DSBCAPS_CTRLFREQUENCY int Replicate_Sound int source id int Play_Sound int id int flags 0 int volume 0 int rate 0 int pan 0 int Stop Sound int id int Stop All Sounds void int DSound_Init void int DSound_Shutdown void int Delete Sound int id int Delete All Sounds void int Status Sound int id int Set Sound Volume int id int vol int Set Sound Freq int id int freq int Set Sound Pan int id int pan input int DInput Init void void DInput Shutdown void int DI Init Joystick int min x 256 int max x 256 int min y 256 int max
61. xtern extern extern extern extern extern the extern extern extern extern extern extern extern extern int screen width width of screem screen height height of screen screen bpp bits per pixel LPDIRECTSOUND Ipds directsound interface pointer DSBUFFERDESC dsbd directsound description DSCAPS dscaps directsound caps HRESULT dsresult general directsound result DSBCAPS dsbcaps directsound buffer caps LPDIRECTSOUNDBUFFER Ipdsbprimary the primary mizing buffer array of secondary sound buffers pem sound sound fx MAX SOUNDS VVAVEFORMATEX pemwf generic waveformat structure directinput globals LPDIRECTINPUTS Ipdi dinput object LPDIRECTINPUTDEVICES lpdikey dinput keyboard LPDIRECTINPUTDEVICES lpdimouse dinput mouse LPDIRECTINPUTDEVICES Ipdijoy dinput joystick LPDIRECTINPUTDEVICE2 lpdijoy2 dinput joystick GUID joystickGUID guid for main joystick char joyname 80 name of joystick extern these extern extern extern extern endif UCHAR keyboard_state 256 DIMOUSESTATE mouse state DIJOYSTATE joy state int joystick found motor h contain the target records for all di input packets contains keyboard state contains state of mouse contains state of joystick tracks if stick is plugged table in 51 Copyright C 2004 Martin Persson Directly stolen from Andre LaMothe x

Download Pdf Manuals

image

Related Search

Related Contents

Model 363 Two-Channel SR/A-Type Processor User`s Manual  Times PC User Manual  Addonics Technologies DVD R/RW Portable DVD Player User Manual    Samsung SGH-C200N User Manual  HIMSS/NEMA Standard HN 1-2013 Manufacturer Disclosure  5882EUHS Receptor RF GUIA DE INSTALACIÓN Y PROGRAMACIÓN  Betriebsanleitung Mode d'emploi Istruzioni per l    1ch VGA Video Audio UTP Repeater  

Copyright © All rights reserved.
Failed to retrieve file