Archived

This topic is now archived and is closed to further replies.

04.01 - Some Code to Ponder

This topic is 5741 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Okay folks, no more fooling around…time to learn something. Have your compiler running with the BaseCode1 project loaded, and be sure that your DirectX 7.0 SDK documentation is easily accessible. If you’re missing some files, try here. The Rise and Fall of BaseCode1 Let’s turn our attention first to the overall layout of the program:
  • Program execution starts at WinMain() (true for all Windows applications)
  • The OS is instructed to create a full-screen window (black)
  • Game_Initialize() is called
    • DirectDraw is initialized
    • DirectInput is initialized
    • DirectSound is initialized
  • The main message loop is entered (true for all Windows applications)
    • Windows messages are handled in WindowProc()
      • ESCAPE quits
    • If there are no messages waiting, Game_Main() is called
      • Check for input
      • Clear the display
      • Write a line of text
      • Play a sound if the spacebar was hit
  • Once the main message loop is exited (ESCAPE was hit), call Game_Terminate()
    • DirectSound is shutdown
    • DirectInput is shutdown
    • DirectDraw is shutdown
  • The program ends
Or, more simply stated (ignoring Windows-related procedures):
  • Game_Initialize() is called
  • Game_Main() is called (repeatedly)
  • Game_Terminate() is called
It’s fairly common to see ‘entities’ such as our game code and the DirectX components asking for an opportunity to initialize before being used and a chance to take care of any shutdown tasks before they’re done. If our game requires memory for internal data, it would be a natural process to allocate the memory in Game_Initialize() which is called once at the beginning of the game, and free that memory in Game_Terminate() which is called before the game is completely terminated. Likewise, you’d expect that DirectX components don’t just work off-the-bat – we need to set them up first by calling their initialization functions and feeding them the correct information so that they work properly when they’re needed. Overall Layout The compiler doesn’t care if our template code is in one file or in fifty. It is only for readability that we ‘chop up’ the game’s functions into groups and assign them their own files. Face it – a game with 800 functions all in one file makes for messy game code. There will be an article discussing source files, header files and projects that will further explain the semantics to organizing code in files, so for now let’s just look at the contents of the files themselves:
  • WinBase.cpp contains all of the code that is specific to Windows. We need to at least create a window and process messages coming in from the OS to be considered a true Windows program, and this file keeps them all in one place. It also contains the proper start of execution, WinMain() . Once we dissect this function, the entire flow of the program will make perfect sense.
  • InitTerm.cpp contains, you’ve guessed it, all of the initialization and termination functions for our game template. Game_Initialize() calls other initialization functions, in a sense managing everything else in the game. In the same way, Game_Terminate() ensures that everything that would like a chance to shutdown gets called. This is our last chance to do things before our frame-by-frame code gets called repeatedly, so make sure everything’s prepared!
  • GameMain.cpp is where all of the action takes place. This function is called repeatedly from the message loop in WinMain() , which means that whatever you put in this function is going to execute many times a second. It’s our job to make sure that the code is written to fit this style. If every call to Game_Main() produces a frame of animation on the display, we’ve got ourselves the chassis for a game.
  • Utils.cpp is a convenient place to throw functions into that are used by other parts of the game. For instance, there are functions for loading bitmaps from disk in this file, which is used elsewhere.
And there’s also a couple of header (.H) files:
  • Utils.h contains a ‘description’, called a prototype or declaration, for each of the functions implemented in Utils.cpp. As long as any other source file has access to this header file, it can use the functions contained inside.
  • Globals.h is the master header file for our game template code. Every source file needs to know about Globals.h in order to function properly. If we place any information inside of this header file, it is immediately accessible from anywhere in our entire game. Sounds like a good place for global variables, huh? That’s one of the primary purposes of this file.
So, the rule of thumb is that every source file (.CPP) should include Globals.h so that we can use global variables properly, and any source file that needs to use a function from Utils.cpp should include Utils.h. As you can see at the top of each source file, including a header file is accomplished with the line #include “filename .h” , where filename is either Globals or Utils . Let’s look once more at our organizational ‘chart’ to really drive the point home:
  • Create a window for our game: WinBase.cpp WinMain()
  • Initialize our game: InitTerm.cpp Game_Initialize()
    • Initialize DirectX components
  • Draw animated frames: GameMain.cpp Game_Main()
  • Shutdown our game: InitTerm.cpp Game_Terminate()
    • Shutdown DirectX components
  • End of game
Divide and Conquer What we’re doing here is setting ourselves up to understand the game template code by attacking each component separately. Each of the following has initialization, runtime and shutdown duties:
  • Our game code
  • DirectDraw
  • DirectInput
  • DirectSound
Since we don’t have a game yet, the template code just fills in each section with something simple to serve as a placeholder. For instance, we use DirectDraw to set up our display, but all we’re doing is writing a line of text. Heck, it even goes through the trouble of loading RESOURCE.BMP onto an internal buffer, but we don’t (yet) do anything with it. For input, we have the code necessary to read the keyboard, and all that this program is interested in is the spacebar. Using DirectSound, we load a single sound into memory and play it whenever the spacebar is pressed. Nothing too complicated for any of these components, but just enough to say that we used them – they’re initialized, used and terminated properly. Definitely something good to build on! Of the three DirectX components, only DirectDraw is truly essential. We don’t need fancy sounds this early in our studies, and even input isn’t absolutely necessary, but without DirectDraw we wouldn’t even be able to set our resolution, color depth or display anything on the screen. Therefore, it should come as no surprise that we’ll concentrate our attack there first, but not before looking at DirectX as a whole. Part of the beauty of using DirectX is that the components are used rather consistently – once you get the hang of using one component, the rest aren’t so difficult to manipulate. Questions? Comments? Please reply to this topic. Edited by - teej on April 23, 2001 5:45:57 PM

Share this post


Link to post
Share on other sites
I just wanted to say I think you are doing a HELL of a job Teej, hang in there and we''ll be coding games in our sleep. I really want to thank you for taking the time to put this together for us. SO once again GOOD JOB TEEJ!!!

Share this post


Link to post
Share on other sites
Awww, geez

I''m hoping to get my computer running tomorrow again, and then I''ll give everyone something to be thankful for...

Full speed ahead!

Teej

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Hey, and thanks for this tutorial. Great doing it interactive, so people like me can hang around and ask questions on pretty obvious things that I just don''t understand
I have a question on the ''G'' struct in ''Globals.h'' in the program BaseCode1; how do you define structures? Is it :

struct { bla bla, bla bla..} G;

I mean, does the name (here ''G'') always come after the whole thing, or at the beginning, as with classes, or doesn''t it matter?

Share this post


Link to post
Share on other sites
I think the struct statement looks something like this :

struct structName
{int varOne;
int varTwo;}
varName;


You can omit structName IF you specify a varName but in that case you would NOT be able to define other variables of the same type (struct)

Conversely you can omit the varName in which case you will have to define your variable at a later time like so:

structName varName;
structName otherVarName;

By specifying structName you are in essence creating a new var type which you can use to create other variables of that type withing the scope of that struct.

And by specifying a varName you are simply combining two statements together. The type definition AND the variable definition.


Hope this help, and if i''m wrong please correct me anyone.


Halek

Share this post


Link to post
Share on other sites
G at the end of the struct is an instance of this particular struct, but not the name of the actual struct. If you used:

struct {blah blah blah} G,H,I;

then you would have 3 structures built, one called "G", one called "H" and another called "I". Then you could access them by using G.blah or H.blah, etc.

I have always used the method Teej used to build structs with the name of an instance of my struct at the end of the struct architecture. However you could build one this way:

struct global_architecture
{
blah blah blah
};

and then build a variable of type global_architecture and name it G. Here you have named the struct, and you can build versions of it anytime you need it. It would then give you the exact same results as Teej has gotten. You see, structs are exactly the same as a class, except that members are public by default. In C++, struct is only really provided for backwards compatability. Using classes instead of structs is generally considered good pactice, but if all you need is a slightly more complicated kind of array, (as we do here) then a struct is easier to work with.

Share this post


Link to post
Share on other sites
Hi all,

Teej, this is the most wonderful of tutorials out there on the net. I''ve already read a lot of them, but this is the first one that gives me the feeling you actually know what you''re talking about. Thanks.
Can somebody please provide me with the files that were supposed to be on Teej''s website? They aren''t there.
E-mail: seferis@pandora.be
ICQ: 72428880

Thanks in advance

*** Hi! I''''m a signature virus. Copy me into your signature to help me spread! ***

Share this post


Link to post
Share on other sites
Greetings, Teej.
Several folks have posted this, but I think you have overlooked them. The file BaseCode1.zip is not found at the link on your website. We beginners cannot follow along in this great tutorial without it. Could you please fix it?

Thanks!
Shep

Share this post


Link to post
Share on other sites
To those who have not been able to download BaseCode1.zip:

I did a little experimenting and came up with a different URL.

Try this one instead:

http://freehosting1.at.webjump.com/2a4a785c8/te/teejb-webjump/BaseCode1.zip

Teej...tsk tsk. Methinks ye needs a different host, or somethin''.

Shep

Share this post


Link to post
Share on other sites
way to go man, this tutorial is great. im excited to see more and get into the nitty gritty of C and DirectX. Ive analyzed your code (from basecode) 5000 times plus i read C books. I have always wanted to make games and you are my savior. -kaptan

Share this post


Link to post
Share on other sites
Hi all, OK I''ve been through the code a hundred times and I don''t understand how it takes the bitmap and lets you type a message using the alaphabet from it. Like how do you map all the letters to be associated with the keyboard letters. I guess what I''m asking is how the program knows where each letter ends and starts on the bitmap.I know this is done in the utilities page but cant'' see how. Am I in over my head already? Hope I''m just missing a DirctX function or something.

Share this post


Link to post
Share on other sites
I''ve found that I can download the files if I hold shift while I click the link (open in a new window) but it doesn''t work if I just rightclick on the links and select open in a new window.

Share this post


Link to post
Share on other sites
I've been studying the files from BaseCode1 and on a whim decided to look up the header for windows.h to see what it consisted of. After a fruitless search in the VC++ help files, I tried Microsofts' site.. still nothing definitive. Where can I find a copy of the header? (Microsoft mentions that it is around 8k lines, but not where to get it. The VC++ help eludes to a win32 sdk but nothing comes up in a search on Microsofts site pointing towards my goal.) I guess what I really want to know is: When you include the header, how do you know to include it, and for what reasons? From where do you get this knowledge? Any help would be most appreciated.

Edited by - Mitijea on May 3, 2001 1:02:04 AM

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
The windows.h header file is in the includes directory. When VC++ compiles one of your source files, the first thing that happens is the precompiler opens all of the #include "..." files. Thus, they must be located on your hard disk somewhere. They are usually located in the c:\devstudio\vc\includes directory, so look in there for windows.h

Later,
Buncen

Hi, I''m an Irish signature virus. Please copy me into your signature to help me spread Thanks.

Share this post


Link to post
Share on other sites
In regards to this file layout for the tuts, where would the code for the AI logic be placed(if any). Just wondering. Keep up the great work.

http://angelfire.com/ny5/codeworx.com

Edited by - shdaga on May 3, 2001 2:10:05 AM

Share this post


Link to post
Share on other sites
Also, as far as the 32 bit windows API is concerned, you can find very useful help files on the web that has detailed information about everything in Windows.h. I however cannot find a link to it at the current time, but I do have the help file so I know it exists. I also don''t know if it contains all of the information about Windows.h but I have yet to see a function used that it doesn''t have.

Share this post


Link to post
Share on other sites
Buncen - Thankyou for pointing out where the header is located.. Feeling a little stupid about not figuring it out myself But after purusing it and the header for winuser.h, I''m even more confused. I know that the includes inside angle brackets don''t nescessarily have to have a corresponding cpp file, but can have another type, such as an exe, or a dll, so I''m not sure where to go from here on finding the original code used in conjunction with the headers. But...
RandomGamer - came up with a good suggestion which I will take up (Thanks ). After looking at the header for winuser, I''m thinking the info I''m looking for could fill volumes. Not really sure if I need to dig that deep, but right now I''m really not comfortable with having to rely on someone else saying to use a function when I''ve no idea where they got it from.. And also, I''m just curious about what I''m missing out on.

Share this post


Link to post
Share on other sites
I have been working with the code and I am beginning to understand the whole modular programming thing now. I''m currently making my own direct x wrapper that will hopefully be made into a library. Thanks teej for the great coding ideas. Especially the ingenious grobals function idea. I look forward to the rest of the tutorial!!!

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Rictus,
The resource.bmp file is actually never used. It is just loaded to demonstrate how image files would be laoded in a real game.

The text is painted on the screen using the crude Win32 graphics function TextOut(). As you will see, the font does not even look like the one in the bitmap. It is actually using the default Windows font.
Note: Remember that when you use a Win32 API graphics function like TextOut you must lock your direct draw surfaces and release them when your finished as Teej has done in the example.

Later,
Buncen.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Mitijia,
Don''t think you''ll have much luck finding the ''original code'' that the headers are for. Unless you work at Microsoft or know a good russian hacker. Microsoft do not release the Windows source code to the general public because they think competitors would copy it and they are also terribly embarrased of it.

Later,
Buncen.

Share this post


Link to post
Share on other sites
Anyone that saw my post in Q&A about adding an mp3 track to Teej''s basecode. I got it sorted. Direct Music doesn''t support mp3, and while Directshow does, it severely alters the event handling of a program.

I am using the FMOD library to do it. It takes all of 4 lines of code to do it

Share this post


Link to post
Share on other sites
Mitijea: I know exactly how you feel. I hated reading tutorials where all these functions would be thrown at me, and I''d always want to know how they find out what functions do what and how they all work.

Two things that i learned:
1.) Read the help files!! They''re an invaluable resource. Usually a search on a couple keywords about what your trying to accomplish will be enough.
2.) Patience. In time it will all make sense. Alot of us are still newbies to game programming (why else would we be here), but as long as your determined to learn, you''ll be an all-knowing guru like Teej in no time =)


Teej: awesome idea with the globals structure, since my last attempt at a game i was always wondering if there was a nice easy, organized way to deal with all the globals spread around my files

Share this post


Link to post
Share on other sites
First off, I''ve added an article on that G thang in 03.03 - Selected C Topics.

About the website, well, I didn''t have the local copy of the website at the time, and tried to hack a new index.html. Obviousely, it didn''t work. As of 7pm EST today it should be repaired.

Rictus: Sorry about that! There are some things in the game template code that frankly have nothing to do whatsoever with running it. I''ve added the code to load a bitmap onto a DirectDraw surface only because it''s one of the first things we''ll want to play with. As someone mentioned, I just used a standard (slow) Windows API function to draw some text on the screen. We''ll all be 100% comfortable with the template code shortly...

Mitijea: If it''s the header file that you''re looking for, I can guarantee you that it''s on your machine (otherwise you wouldn''t be able to compile any Windows application). If you''re using MSVC, try right-clicking on the header name and select ''Open File'' (or whatever it says).

leggyguy: Although I haven''t tried it yet, there is a way to run your mp3 through Window''s APIs using an MP3 codec. Of course, you need a codec first!

shdaga: Boy, not too many people dying for some AI Well, until we get the forum to that stage, I''ll have to limit my AI discussions to general concepts. Rest assured that as our games increase in complexity, the need for clean and powerful AI will definitely warrant a section.

Boy, I''d better hurry up and place another great idea online soon -- I don''t think the ''G'' struct thing will hold me forever

Teej



Share this post


Link to post
Share on other sites
Since I''m not quite on speaking terms with any Russian Hackers (at least that I know of...) and I wouldn''t want Microsoft to suffer anymore embarrassment over its ''superb'' coding... I guess I''ll just let nature take its course. Thanks all for replying: at least I''m not the only one feeling a tad bit lost in the wonderful, wide world of windows.

Share this post


Link to post
Share on other sites
Mitijea, just one more thing about those include files:
#include "file.h" vs. #include < file.h>
these are 2 different ways of telling the compiling where/how to look for the file. Basicly it comes down to this: "file" tells it that it is in the current dir and < file> tells it that it's in the include dir. More info on http://msdn.microsoft.com/library/default.asp?URL=/library/devprods/vs6/visualc/vccore/_predir_the_.23.include_directive.htm
< file> doesn't mean that it's using a dll or exe, "file" could be a header file for a dll too (but in a different dir).
Just to give you a little more info

Edited because it wouldn't show the angle brackets correctly (forum code )
Mox

Edited by - MtSMox on May 11, 2001 6:24:49 AM

Share this post


Link to post
Share on other sites