Allegro Game Programing Tutorial

Embed Size (px)

Citation preview

  • 8/2/2019 Allegro Game Programing Tutorial

    1/130

    Video Game Programming with Allegro

    Written byEric Pietrocupo

    May 1, 2005

  • 8/2/2019 Allegro Game Programing Tutorial

    2/130 ii

  • 8/2/2019 Allegro Game Programing Tutorial

    3/130

    Preface

    This book allows common C programmersto learn how to program video games. Since nobook editor wanted to publish my work due tothe fact that I am not a native English speaker,and surely many other reasons, this book is beingdistributed as donation-ware. Which mean thatyou can download, read and distribute this PDFbook as you wish. Still, if you find it really use-

    ful, if you are actually making money with thingslearned from this book or if you just have to muchmoney and dont know what to do with it, youcan always make a donation to support the au-thor.

    This book is being distributed on my website ariel.bdeb.qc.ca/~ericp/allegro . Youcan find on this web site the latest updates ofthis book, source code example, some web links,

    some game engines and the required informationto make a donation. Thank you very much fordownloading this book and as you already know,I am not a native English speaker which meanthat there can be some orthographic or grammarerrors. Still, I am using Ispell to reduce to mostobvious errors.

    The goal of this book is to allow all pro-grammers to have access to some common videogame programming knowledge. By doing so, it

    will increase the number of open source videogames or the quantity of game programming toolsand engines available on the Internet. A largequantity of home made video games could alsoinfluence greatly the video game industry, but wewont discuss this subject in this book. Videoprogramming knowledge is becoming even moreimportant for open source video game console,like the Game Park 32, which give the playersthe possibility to make their own games for their

    console. So it is a good idea to make this knowl-edge available to everybody.

    Whatever is your reason to read this book,I hope you will find it very useful and you willhave a lot of fun to read it. Enjoy!

    Thank You

    Eric PietrocupoThe Shadow (a.k.a. Larienna)

    [email protected]

    iii

  • 8/2/2019 Allegro Game Programing Tutorial

    4/130iv

  • 8/2/2019 Allegro Game Programing Tutorial

    5/130

    Introduction

    Who am I

    Making video games is like making a dream cometrue. When I was a kid, I remember making var-ious maps and design for video game that I couldsomeday create. I also remember making Zeldamap for new adventures I would never be able to

    play (Zelda Classic1

    did not exist at this time).Of course, all those designs where a bit uselesssince there was no way to play them.

    Interested about making video games, I de-cided to study computer programming. At thebeginning, I have learned some Gwbasic program-ming during high school. This was an horriblelanguage where you needed to write your linenumbers. The syntax was also done during ex-ecution since it was an interpreted language. I

    remember my friend making up this situation :Captain, we are under attack. Quick launch thetorpedoes ... Syntax error in line 3208 I made afew graphic animations programs much like a fakemovie and I have made many attempts to makevideo games. Unfortunately, due to the lack ofcomputer memory, programming knowledge andhard disk, the results where very poor. The bestI could do was some kind of text game like a bookwhere the reader is the hero. At this time, I wasstill coding in spaghetti and all text and choices

    where hard coded (very ugly).

    Then I have started programming lessonsin college and I have learned the C language. Istarted to learn structured programming in C.Unfortunately, the C compiler did not nativelyinclude some graphic routines so I was not ableto make a graphic game. I tried to make a textbased game but it did not work out. There is also

    1www.zeldaclassic.com

    the fact that I did not know anything about rela-tional database yet. So the idea of making videogames in C was soon forgotten.

    A few years later, while shopping for com-puter books, I have fallen on a book called Tricksof the game programming gurus 2. It was a nicebook that taught many video game programming

    logic all coded in C. I was really amazed, I boughtthe book and start reading. I start to practicewhat I had learned from the book and made asmall library. A few months later, I learned Ob-

    ject Oriented Programming in C++ and I decidedto convert my library to an object oriented videogame library I started to make a game calledStar Empire which was a turn based strategyspace warfare game. Of course it did not finishit for many reasons : The library had many limi-tations, the program I was compiling were under

    DOS in real mode (which mean 640K memorylimitation), the code was not portable since a lotof things were done in assembly , the coding tooka lot of time and there was serious memory bugsin the game. From now on, I was absolutely surethat I would never go back into video game pro-gramming again.

    While talking to some guys on the net whowanted to recompile Free DOS in 32 bit, I was in-formed that there was a new DOS compiler avail-

    able named DJGPP which was in fact a port ofGCC for DOS. Just the idea to be able to makesoftware in protected mode was really nice : Nomore memory limitation, No more memory bugand computer crash. The DJGPP web site offereda small tool to select the package of the compileraccording to my need. There was a package called

    2Andree LaMothe et al., Tricks of the game pro-gramming gurus, Indianapolis: Sams Publishing, 1994,746 pages.

    v

  • 8/2/2019 Allegro Game Programing Tutorial

    6/130

    Allegro, Video game library3. I said to my selfthat a library would not be as efficient than cod-ing all the game at bare hand so I thought it wasreally a joke. Still I downloaded the whole stuffand take a look at it.

    I checked the API of the library and I had

    almost lost my sanity. It had more stuff that avideo game programmer could ever need : config-uration System, User input, Video management,Bitmap & Sprite management, Drawing function,Music, Sound, Audio Stream, Translucency, FileArchive management, 3D polygons, 3D Scenes ,Unicode text and even a Graphic user interface.The library compiles on many operating systemand it can make the same code portable on manyOS. All the hardware is auto-detected, it can takeadvantage of hardware acceleration if the user has

    the appropriate material.

    Surprised by everything it could do, I foundquickly a tutorial4 and start learning. Using thislibrary was so easy to learn, the functions wereclear and everything you needed was there. Ofcourse, it was easier for me to learn since I al-ready known the video game programming logic.I only needed to know how to do this and that inAllegro. The only new thing I have learned fromthis FAQ was the concept of frame skipping. In

    about 15 minutes, I became an Allegro program-mer.

    Finally, I decided to try making anothervideo game which was a remake of wizardry calledWizardry Legacy5. It is now 70% complete avail-able with the source code, and might never becompleted. Anyways, I have learned a lot ofthings during this 2 years of wizardry program-ming and it was a nice experience even if it didnot reach the end. While I was programming

    Wizardry Legacy, I also started, with my friend,another project called Rockman Battle Arena. Itwas supposed to be a fighting game containingthe megaman characters and using the same kindof game play. I have learned alot of things aboutreal-time programming while coding this game,

    3http://www.talula.demon.co.uk/allegro4George Foot, Allegro Vivace Tutorial, http://

    www.glost.eclipse.co.uk/gfoot/vivace/vivace.txt.5ariel.bdeb.qc.ca/~ericp/wizardry

    which was totally different than wizardry. Theonly things I have not touched is the ObjectSpawning and Sprite to Sprite collision. I mightfinish these later, just for practice, since I am go-ing to talk about it in this book. Of course thegame is not finished, it is merely a demo. But onmy point of view, making an engine is much more

    important for your video game programming ex-perience than making a complete game.

    Since home made video games is not reallya profitable business, I am not sure if I am goingto make video games again. I might make someengine or micro engines since they are small and abit more fun to code. So I wanted to take all myknowledge about video game programming andteach it to programmers who want to actuallymake video games. It seems that I could not get

    published by a book company and I could notfind a place where I could teach video game pro-gramming. So I said to my self that I will write avirtual book and distribute it on the net to finallypass my knowledge to the next generation.

    So I hope you will like this book, and I hopeit will help you understand better video game pro-gramming. Enjoy reading and have fun.

    What is Allegro

    Allegro is a recursive acronym which stand forLow LEvel Game ROutines. Allegro is a li-brary of plain C functions and procedures thatare used specifically for video game programming.The whole library is in plain C except for one class(fix) which has been made for those who want tocode in C++. Even if the library is in C, you

    can still make your game in C++ without anyproblem. When I say C++, it mean using anObject Oriented programming structure, not us-ing the C++ Libraries like Iostream or containerclasses. In fact, you should not use Iostream orany other library that has not been optimized formaximum speed as required in video games.

    The library was started by Shawn Harg-reaves and it is now being developed by a groupof independent programmers. They continuously

    vi

  • 8/2/2019 Allegro Game Programing Tutorial

    7/130

    Video Game Programming with allegro

    add new features to the library and some peo-ple are managing the various ports of the library.The library is distributed as gift-ware which meanthat you can make free-ware, share-ware and evenmake commercial games without having to payany royalties. This can be interesting if you wantto make some profit with your games, still it could

    be a good idea to show at the beginning of yourgame that is was powered by Allegro. There aremany pictures and logo that you can downloadfrom their web site to incorporate them in yourgame.

    As I have said before, the library supportmany things. The sections that you will mostlyuse is the User input, the graphic output, bitmapmanagement, audio output and the datafile man-agement. There are a few thing that you might

    never use like the graphic user interface (a win-dow like interface), the unicode string conversion,Configuration function (configuration is generallydone automatically). Allegro comes with manyexamples that you can look at in order to test theperformance on your computer or learn how to doit. Allegro comes also with 2 utility program : thegrabber and the setup. The grabber is a programthat allows you to import files like images, musicand sound to group them all into one compressedarchive file which will be opened during the gameby the datafile routines. The setup program isa small hackable program that you include withyour game to set the Audio, Joystick and someother configuration of your game. This setupwill produce a configuration file "allegro.cfg"loaded automatically by allegro.

    In these days, most video games runs onWindows but who said that windows was the bestOS to run a game? On my point of view, the mul-titasking, instability and the permanent GUI en-

    vironment of this OS makes it the worst. This iswhy, allegro is not dependent to only one operat-ing system, it supports : Linux, Windows, DOS,BEos, Unix, MacOS, QNX and maybe more.Which means you compile on the OS you like andrecompile on all other OS to allow everybody toplay. Porting is not magical, there is a few adjust-ment and precautions to make but you can makethe same source code recompilable on many OS.Linux is the most picky OS, but if it runs on Linux

    without segmentation fault, you are almost surethat there is no memory bugs. By the way, DOShas been mentioned in the list. Yes, DOS stillexist and it is not obsolete. In fact, it is one ofmy favorite OS and I think that this should be theperfect OS to run Video games since it is is mono-tasking and the OS layer is very thin. When you

    compile under DOS, you should use DJGPP inorder to get a 32 bit protected mode application.You will have to include a driver called cwsdpmi6

    with your game in order to access protected mem-ory. This driver is normally used by most recentDOS application so it should normally already beinstalled on the users machine.

    About this book

    This book it primarily the target of C program-mer who know all the programming basics andmany programming concepts and algorithms like: Pointers, Chained lists, Recurrence, Sorting,etc. You must also know a bit about the com-puter internal like interrupt vectors, but still Illtry to give some basic information to make sureyou wont get lost. For those who knows littleabout C programming and computers, you will

    probably be able to use the first and second partof this book. It will allow you to draw pictures,play sound, make graphics, etc. It can still havesome uses to you but you wont be able to makea full professional video game.

    Most of the book covers 2D video game pro-gramming. In this age, 2D games seems to beforgotten. 3D games are not necessarily betterthat 2D games, they are just different. The logicbehind 2D and 3D games looks alike. Of course,

    some stuff in this book will be useless in a 3Dgame but I dont think it is a good idea to di-rectly start with 3D programming. Video gameprogramming is complex and 3D game program-ming is even more complex. I think we shouldstart with something simple, it will make it eas-ier for your to understand. Then if you wish,you can promote your knowledge to 3D program-ming. I will also take a lot of examples from

    6http://clio.rice.edu/cwsdpmi/

    vii

  • 8/2/2019 Allegro Game Programing Tutorial

    8/130

    the NES, SNES, SMS and Genesis video gameconsoles. These consoles make the golden age ofvideo games, there is a lot of interesting exam-ples that we can examine. When finished withthis book, you will easily find color palette anima-tions in the games you play and you will criticizethe collision detection when you die.

    This book is divided in 4 parts. The firstparts explain the basic concepts of the hardwareused in video games like the graphic card, thesound card and the various input devices, andit teach the various allegro routines to managethis hardware. The 2nd part explain other alle-gro function really useful but that does not neces-sarily manage some hardware. In the third part,we now enter deeply into video game program-ming. You will learn various concept and algo-

    rithms used in video games. These algorithmshave nothing to do with Allegro, but we will useAllegro to experiment them. Finally, the last sec-tion is reserved for the design of the game. Ittalk about many popular game engines, Artifi-cial intelligence and some ideas and guide lines tobuild a well balanced and interesting video game.Again, this section is not specific to Allegro andit can be implemented by using another library.

    Of course this will not cover all aspect of

    allegro but it should cover most aspect of videogames. The problem is just to get started, whenyou finally know the logic behind video games,you can start making your own algorithms andinnovations. Even if the book is missing somepoints, you will now have the required experienceto investigate yourself and this is what I want youto have.

    Video game structure

    What is a video game? It is a program wherethe main objectives is to have fun ( somethingforgotten by game companies in theses days whoinvest everything in the graphics ). This programuse much more resources than a normal programin order to make the game more interesting. Ituse Audio, Video, Input and Processing power allat the same time. The usage of all these resources,

    including the fact that it must run at a reasonablespeed, makes video game programming a bit morecomplex than a normal application.

    When you create a video game there arevarious areas to develop which does not neces-sarily require the same expertise. A video gamegenerally need more than one person in its staff.Some do the coding, some the artwork, anotherone is managing the teams, etc (take a look atany video game credits). What ever is the videogame, all the video games should have the sameconcept, take a look at this diagram below.

    Figure 1: Video Game Abstract

    Any video game can be represented by thisdiagram. All the entities located to the left side ofthe doted line requires some computer program-ming while all entities located on the right sidecan be done by non-programmers. To the right,we have the game data which includes all thelevels, maps, equipment, monster stats, etc. Itmostly contain information related to the design

    and the rules of the game. The artwork containsall the images, sounds, movies and other mediaused by the game to make it more beautiful andattractive.

    To the left, inside the big square, we havethe engines. Engine is the core of the game andits coding is generally small but complex. A gamecan use many engine : Menu engine, Side Scrollerengine, map engine, database engine, etc. Theseengines can also be subdivided into micro engines.

    viii

  • 8/2/2019 Allegro Game Programing Tutorial

    9/130

    Video Game Programming with allegro

    The advantage of engines is that you can reusethem in other video games with minor modifica-tions in order to reduce the coding time of thewhole game. The entity include the engines con-tains the code to make the engine communicateand the code specific to the design of the game. Itallows to implement the rules and the game-play

    of the game. This is the long but simple part ofvideo game programming. Reducing the the sizeof the games code by using more sophisticatedengine can reduce the development time of thegame. If you wish, you can find an engine madeby somebody else on the net and make a gamewith this engine.

    Finally, the controller entity contains all thecode that influence the action of the game. Userinput, artificial intelligence and network commu-

    nication are part of the controller entity.

    All these parts can be of different size ac-cording to the type of the game. For example aTetris game, will have no game data, a few art-work, The puzzle engine, little game code andalmost not controller code. For my wizardrylegacy game, there was few game data since I didnot supply any adventure, there was many art-work (textures and monsters), there was 3 engines(Maze, Windows and Database) a lot of game

    coding to implement the rules and interfaces andfew controller code since the AI was fairly easyand there was no network support.

    Just to make you see the difference betweenthe engine and the game code take a look at anyGrant Turismo game (Car race game on Play Sta-tion). The racing with your car in done by the en-gine of the game. This racing engine dont knowanything about if you are currently making a testrun, tournament or a drivers license test. The

    only things it knows is : Use this track with thiscar and these opponents, then return the result ofthe race when finished. When the race is over, thegame code will take the results and say Good,you finished 3rd, so you earn X points. Since youare in a tournament you must continue with a2nd race. Then it tells the engine : Play thistrack with this car. Which mean that the enginehas actually no idea of whats really going on inthe upper level of the game, it just follows orders.

    There is also the concept of micro enginewhich works for similar engines. For example, letstake a space shooter and a Z-Scroller (side scrollerwith a Z axis. Ex: Golden Axe). We divideour space shooter engine in three micro engines :Background (scroll and parallax), level(map andsprite), Foreground(effect and distortions). Since

    we need a background and maybe a foregroundengine in or Z-Scroller too, we reuse theses en-gines and we replace the level engine by a Z-LevelEngine. It can be some way to reduce develop-ment since we dont have to recode the back-ground and foreground. Still, a completely dif-ferent game engine, like a GUI, will not be ableto reuse theses micro-engines except maybe forthe foreground engine ( it could be cool to havesome mist hide the windows ).

    It is a good idea to plan in advance whatneeds to be done. It will allows you to know thesize of the project and if you need other people tothe the job you cans do. As a programmer, youcan be more interested in engine programmingthan game programming (which is currently mycase). You might not also be a good artist (be-sides doing stick mens). So planning, will let youknow where you are going and will prevent youto trace back your steps. Too much planning canslow you down too so find the balance.

    Now that you have seen the concept of avideo from high above, we will now start to gomore deeply into video game programming butfirst, you need to have the right tools to make agood job.

    ix

  • 8/2/2019 Allegro Game Programing Tutorial

    10/130 x

  • 8/2/2019 Allegro Game Programing Tutorial

    11/130

    Table of Contents

    Preface iii

    Introduction v

    Who am I . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v

    What is allegro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vi

    About this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii

    Vi de o game st r uc t ur e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v i i i

    I Technical Procedures and Harware control 1

    1 Installation and configuration 3

    1.1 Installation of allegro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

    1.2 Making an Allegro Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

    1.3 Overview of the Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

    2 User Input 9

    2.1 The Keyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

    2.2 The Mouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

    2.3 The Joystick . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

    3 Video Output 17

    3.1 Video Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

    3.2 True Color Video Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

    3.3 Palette Video Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

    xi

  • 8/2/2019 Allegro Game Programing Tutorial

    12/130

    TABLE OF CONTENTS TABLE OF CONTENTS

    4 Audio Output 23

    4.1 Basics of Sound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

    4.2 Sound Sampling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

    4.3 Instrumental Music . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

    4.4 Allegro Audio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

    4.5 Other Audio Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

    II Logical Procedures used in Video Game Programming 31

    5 Graphic Drawing Functions 33

    5.1 Drawing Primitives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

    5.2 Writing text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

    6 The Allegro Bitmaps 39

    6.1 Managing the Bitmaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

    6.2 Bitmap Blitting Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

    7 Translucency and Lighting 47

    7.1 Drawing Routines Alteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

    7.2 Color Blending . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

    8 3D Polygons 53

    8.1 Pre-calculated 3D Polygons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

    9 Allegro Configuration 57

    10 Allegro File System 59

    10.1 Allegro Datafiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5910.2 File and Compression Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

    III Video Game Logic and Algorithms 67

    11 Advanced User Input 69

    12 Advanced Video and Graphics 71

    xii

  • 8/2/2019 Allegro Game Programing Tutorial

    13/130

    Video Game Programming with allegro

    13 Special Effects 73

    14 Sprites 75

    15 Scrolling 77

    16 Game Objects 79

    17 Collision Detection 81

    18 The Main Game Loop 83

    19 Optimisations 85

    20 Fake movies and Sprite Theaters 87

    IV Video Game Design and Engines 89

    21 Artificial Intelligence 91

    22 Data Structure 93

    23 Popular Game Engines 95

    24 Game Conception and Design 97

    A Exercice : Gradius Duel 99

    B How its Made 101

    References 109

    Allegro Functions and Procedures Index 113

    Allegro Variables and Constants index 113

    Index 115

    xiii

  • 8/2/2019 Allegro Game Programing Tutorial

    14/130

    TABLE OF CONTENTS TABLE OF CONTENTS

    xiv

  • 8/2/2019 Allegro Game Programing Tutorial

    15/130

    Part I

    Technical Procedures and Harware control

    1

  • 8/2/2019 Allegro Game Programing Tutorial

    16/130

  • 8/2/2019 Allegro Game Programing Tutorial

    17/130

    Chapter1

    Installation and configuration

    In this chapter, you will learn how to setupyour library and compiler correctly in order tostart programming. If you cannot continue thisbook if you cant successfully compile an Allegroapplication. This is why we will make a test pro-

    gram to make sure you can compile correctly.

    1.1 Installation of allegro

    You need to install the compiler and the library.First you need to download the Allegro library at???AllegroDownloadpage and then a C compilerif you do not have any currently installed. The li-brary will not only give you the source code of the

    whole library but it will also give you all the doc-umentation to install and download the requiredfiles according to your operating system. Lookin the \docs\build directory of the library, youwill see a series of text files according to your op-erating system. I will recopy the most importantinformation in this book, you can always take alook at the original documentation. I am goingto describe the installation for each OS, so just

    jump to the OS you are using.

    1.1.1 DOS Installation

    There is only one compiler you can use for DOS :DJGPP. This compiler is a port from the UnixGCC. It allows you to make 32 bit protectedmode applications. The compiler can be down-loaded from either /pub/simtelnet/gnu/djgpp/or http://www.delorie.com/djgpp/ . I suggestyou download it from delorie since the web site

    come with a package manager and it allows youto download allegro from there. You will need thefollowing packages:

    DJGPP 2.01 or later (djdev*.zip).

    GCC compiler 2.91.x or later (gcc*b.zip).

    Binutils 2.9.x or later (bnu*b.zip).

    GNU make (mak*b.zip).

    Texinfo (txi*b.zip).

    Optional: rm (fil*b.zip).

    Optional: sed (sed*b.zip).

    I also strongly suggest you downloadRHIDE which is an Interactive development en-vironment for DJGPP. Most of the following in-formation can be found in the readme.1st of thedjgpp installation.

    First uncompress all the files in a directorythat does not contains a directory name \dev inthe path. Let just say you install it in c:\djgpp,

    unzip it there with the -d flag (pkunzip) in or-der to create subdirectories. In c:\djgpp, thereshould be a djgpp.env file. Make a environmentvariable in you autoexec.bat called DJGPP whichmust point to this file. Then you should adddjgpp\bin to your search path in order to com-pile from anywhere on your system. Here are thecommands to perform these operations.

    SET DJGPP=c:\djgpp\djgpp.env

    set PATH=C:\DJGPP\BIN;

    3

  • 8/2/2019 Allegro Game Programing Tutorial

    18/130

    Installation and configuration 1.1 Installation of allegro

    Reboot your computer. When you are back,execute "go32-v2" without argument and it willgive you the amount DPMI memory available.You can also run "gcc -v" to see if your com-piler works correctly. If it works, you are nowready to compile.

    Uncompress allegro in a separate directorywith the -d option (pkunzip) to create subdirec-tories. Go to the root directory of allegro andtype "fix djgpp" in order to fix the text files forthe compilation. Then run "make" to start thecompilation and do something else while waiting.Then run "make install" to install the librarywhere your compiler is located.

    There is two last things to note about thehardware support in DOS. First, if you have anold video card that does not support VESA 2 or

    above, you will have to download sci-tech displaydoctor 1 to correct a bug in the BIOS of the videocard. This will allow you to support high resolu-tion and high color modes correctly. This driveris not free but ... there is a way to hack the timelimit ... oops! did I say something? If you havea video card with acceleration routines and youwant them to be supported by DOS, you need toget the FreeBE/AF driver 2 which is a free ver-sion of VBE/AF. Download the driver and fol-

    low instructions. It will create a driver file called"vbeaf.drv" that you will have to copy in c:\ tomake it works. Allegro will automatically detectit.

    1.1.2 Linux Installation

    The installation procedure is close to Unix, so youcan take a look at linux.txt and unix.txt formore information. Generally, linux comes with

    development tools, so check you linux distributionand install the gcc compiler. Then you can installany development interface you wish, they are justso many of them so take the one you like. Oncethe compiler is set up, a "gcc -v" should workto test you installation.

    First you need to run the fix program tochange the text files.

    1http://www.scitechsoft.com/2http://www.talula.demon.co.uk/freebe/

    chmod +x fix.sh

    ./fix.sh unix

    Then you must run "./configure" to con-figure the makefiles according to your system.Then run "make" and go drink a coffee. Whenevery thing is compile you must install the libraryas root user. You can also install the help files asman pages or info pages. Here are all the com-mands to do the above :

    su -c "make install"

    su -c "make install-man"

    su -c "make install-info"

    By default, allegro will be installedto /usr/local so you should add a/usr/local/lib entry to your /etc/ld.so.conffile and then run ldconfig to add the path to

    the list.

    Some parts of allegro requires root privilegewhen executing the game. So you might need torun the game always as root, or modify the rightsof the game file as follow :

    chown root.allegro exhello

    chmod 4750 exhello

    This will set the group of the file to allegroand it will set the suid bit. All the users who wantto play the game will have to be part of the groupallegro. If you want to set the suid to all theprograms in the library, run "make suid" at theroot of the library.

    When distributing the game, make surethat the user receives in with the package of yourgame liballeg.so. Since linux programs arelinked dynamically, he need the allegro library inorder to be able to run the game.

    1.1.3 Windows Installation

    There is two compilers available for windows: Thefamous Visual C++ and Mingw32 which is theGCC port for windows. I strongly suggest thatyou use Mingw32 since it is compatible with GCCand because you do not need to supply addi-tional DLLs to make it work. There is a develop-ment environment for Mingw32 which is named

    4

  • 8/2/2019 Allegro Game Programing Tutorial

    19/130

    Video Game Programming with allegro

    dev-cpp. For the windows installation, you mustalso download from allegros web site the di-rect X support code. You can download it athttp://alleg.sourceforge.net/wip.html andthe name of the file is dx70 mgw.zip( you candownload a more recent direct X version sourceif you wish).

    You can chose to download the com-piler and the dev-cpp tool separately, or down-load the dev-cpp tool that includes the gcccompiler. The compiler is found here http://www.mingw.org and the development envi-ronment here http://www.bloodshed.net/dev/download.html. Since there is many files todownload on the mingw download page, it canbe confusing to know which file to download, soI strongly suggest you to download the develop-

    ment tool with the compiler included.

    Unzip you mingw32 compiler, or you dev-cpp package with the compiler, in a directory like"c:\mingw32" or "c:\dev-cpp". The path of thedirectory must not contain spaces or fancy char-acter which means no installations in ProgramFiles.

    Then unzip the direct X file into the samedirectory and overwrite all files. Then you need

    to add the c:\mingw32\bin folder to the begin-ning of your path. Add the path in your au-toexec.bat if you have windows 9x else use theGUI to change the path ( Control Panel System Advanced Environment ). You must then de-fine the MINGDIR environment variable. You canalso use the GUI or add the following line to yourautoexec.bat.

    set MINGDIR=c:\mingw32

    Reboot your computer and then run "gcc-v" at the command line, you should receive thecompiler information.

    To compile allegro, unzip the library in aseparate folder and use the command prompt inthe allegro root folder. Execute :

    fix.bat mingw32

    To adapt the source code to a mingw32 in-stallation. When you are ready to compile, run

    "make" and take a coffee. When its done, run"make install" to install the library.

    Since the Windows programs are compileddynamically, you must include the alleg40.dllfile with your games when you distribute them inorder to let the user support Allegro.

    1.2 Making an Allegro Program

    To get started, we will make an Hello Worldprogram. Then I will give some general expla-nations. I will also tell you how to compile thisprogram for each operating system. Take a texteditor or your compilers development environ-ment and type the listing 1 on page 8( You canalso find the sources on my web site ).

    1.2.1 Compiling under DOS

    To compile under DOS from the command line,you must first make an object like this :

    gcc -c allo.c -o allo.o

    Then you make the executable program byadding the allegro library :

    gcc allo.o -o allo.exe -lalleg

    This should make the allo.exe hello worldprogram. Take note that under the DOS operat-ing system, the allegro library is linked staticallyto the program. You cannot link it dynamicallylike on Windows and Linux. It has the disadvan-tage of raising the size of programs you make by500K to 800K.

    If you use the Rhide environment, you can

    set the allegro as a default library to include inyour projects compilation. Select the Options Libraries menu and add the alleg entry to the list.It is also a good idea to add the allegro functionhelp files in order to have some help on Allegrofunctions. To do so, select the menu help Syn-tax Help Files to Search and add "allegro" tothe line. Then go into the \docs\info directoryof the library, copy allegro.inf help file intoyour \c:\djgpp\info directory of your compiler.

    5

  • 8/2/2019 Allegro Game Programing Tutorial

    20/130

    Installation and configuration 1.3 Overview of the Library

    1.2.2 Compiling under Linux

    When you compile objects, you must add"allegro-config --libs" to the commandline:

    gcc allo.c -o allo allegro-config

    --libsThis allow to make some special complex

    configuration in order to make it work. Take notethat the character is not an apostrophe but aback quote.

    There is surely a way to add this optionline to your development environment, check yourtools documentation.

    1.2.3 Compiling under Windows

    To compile under windows, you must also add the-lalleg command during the linking.

    gcc -c allo.c -o allo.o

    gcc allo.o -o allo.exe -lalleg

    Of course, Dev-cpp can do this for you likeRhide does it. I am not familiar with dev-cppso I wont describe it in details. Check in the

    project configuration. Another thing is that thereis no .HLP help files for allegro functions. Thehelp can be still be accessed as html pages in the\docs\html folder of the allegro library.

    1.2.4 Quick view at the Hello world Program

    The Hello World program we have see aboveis a simple program that shows an hello worldstring on the screen and wait for the user to press

    enter. Here is a line by line description of theallegro functions. First we need to include theallegro header file.

    #include

    Then we start and ordinary main which canreturn either int or void, there is no restriction.We start our program with the allegro init func-tion. This is an initialization function required tostart using allegro, it is essential. Then we call

    install keyboard which will setup allegro to readthe user keyboard. This is essential if you wishto use keyboard functions or variable.

    set color depth allows to determine thecolor depth we wish, in this case it is 16 bitswhile set gfx mode actually configure and initi-

    ate the graphic mode. The first parameter of thisfunction is the video driver which in this case isGFX AUTODETECT. The video resolution isset 640x480 and the two other 0 are for virtualresolution which we dont use.

    The clear to color function allows to clearthe whole bitmap screen with the color blackgenerated by the function makecol which re-quires the red, green, blue values as parame-ters. textout centre is a text printing function

    which center text according to the X coordinates.We draw the text Hello World on the bitmapscreen with the system font named font. Thecenter X position is 320, the y position is 230 andthe color white is generated by makecol.

    Then there is a while who waits for theuser to press enter. readkey wait for a key tobe pressed and return the result. The bit shift-ing with the ">> 8" command allows us to getthe scan code from the result (you will see later).

    We compare this scan code with the code of thekey ENTER hold in the constant KEY ENTER.When the user press ENTER, it pass through al-legro exit which is the closing function of the li-brary.

    Finally, it is very important to addEND OF MAIN and the end of your main. Thisis a macro which magically convert your main()correctly according to the operating system youare compiling on. For example, main() will be

    converted to winmain() under windows.

    1.3 Overview of the Library

    There are various tools and examples includedwith this library which are available when the li-brary is compiled. Ill give an overview of thesesprograms in this section, it is a good idea to checkthem. The lists below contains the full path of the

    6

  • 8/2/2019 Allegro Game Programing Tutorial

    21/130

    Video Game Programming with allegro

    program file starting from the root of the library.Take note that the ".exe" wont appear underlinux systems and that the backslash are actuallyslashes.

    1.3.1 Allegro Tools

    Theses are various tools that can be useful duringthe development of your game.

    The Grabber (\tools\grabber.exe): This isa very useful program that allows you to cre-ate datafiles. Datafiles are file archive whereyou place all your images, music, sound,fonts, etc. The archive can also be com-pressed with a fast compression algorithm.All the data in this archive is already de-coded and is ready to use by allegro functionsonce loaded in memory.

    Testing Utility (\tests\test.exe): This isan interesting testing utility that allows youto evaluate the performance of allegro onyour computer. You can perform some teston many 2D and 3D routines available in al-

    legro.

    Command Line Test Programs (tests\):

    This directory contains also various smallcommand line utilities that allows you toidentify the features of many hardwaredevices.

    Setup Utility (\setup\setup.exe) This is thesetup utility which can be included with yougames to allow your users to configure your

    game according to their computer hardware.This setup program source can be modified.You can change the image drawn in the back-ground, the sound and musics used for soundtest, and you can also change the title of theprogram. This setup program can also befusion to your game program file for moreconvenience. Under DOS, it saves disk spacesince there is no need to include allegro inboth the game and the setup utility.

    1.3.2 Allegro Demonstration

    These are demos and examples program that youcan check for your pleasure. The source code issupplied if you want know how it has been made.

    The Demo Game (demo\demo.exe):This isa demo game made by Shawn Hargreaves. It

    is far from being the best game in the world.It is there to test you library and see whatcan be done in Allegro.

    Examples (examples\}: This directory con-tains all the examples with their source code.The examples covers almost all aspect of theallegro library : Video, Audio, Input, 3D,Unicode, Translucency, etc. An index file

    named examples.txt indicates what eachexample does. Try them all, it worth it.

    So this is it, now that you have a librarythat should be running correctly, we will startprogramming for real with allegro.

    7

  • 8/2/2019 Allegro Game Programing Tutorial

    22/130

    Installation and configuration 1.3 Overview of the Library

    Listing 1 Quick Start Hello World Program/***************************************************************************/

    /* Quick start Hello world */

    /* By Eric Pietrocupo */

    /***************************************************************************/

    #include

    int main ()

    {

    allegro_init();

    install_keyboard();

    set_color_depth ( 16 );

    set_gfx_mode (GFX_AUTODETECT, 640, 480, 0, 0 );

    clear_to_color ( screen, makecol( 0, 0, 0 ) );

    textout_centre ( screen, font, "Hello World",

    320, 230, makecol (250, 250, 250 ) );

    while ( ( readkey() >> 8 ) != KEY_ENTER );

    allegro_exit();

    return (0);

    }

    END_OF_MAIN();

    8

  • 8/2/2019 Allegro Game Programing Tutorial

    23/130

    Chapter2

    User Input

    In this chapter, we will learn how the vari-ous input device can be accessed with the allegrofunctions. The devices covered are the Keyboard,Mouse and Joystick.

    2.1 The Keyboard

    The keyboard allows us to read any key pressedby or text written by the user. When a key ispressed, the keyboard send a make code whichtell the computer that the key has been pressed.When the same key is released, it send a breakcode which indicates to the computer that thekey has been released.

    Figure 2.1: keyboard System

    As you can see on figure 2.1, the keyboardhardware communicates with a driver which com-municate with the software. The Interrupt han-dler on this figure is the place where you can hooka function to handle the keyboard yourself. Ifyou do not hook an handler, The driver will be

    hooked on the keyboard interrupt to interpret themake and break codes sent by the keyboard. Thedriver creates a buffer to hold the keys pressed,remember the states of the shift keys, and whoconvert the scan codes in ASCII characters ac-

    cording to the state keys. For example, if the akey is pressed and the caps lock is on, it will senda capital A to the software.

    First, in order to use the keyboard routines,you must call install keyboard with no parame-ters. Then you can use the allegro functions andvariables to read the keyboard. By default, thekeyboard is managed through interrupts, put youcan also read with the polling method.

    2.1.1 Keyboard Reading

    The keyboard does not send only ASCII char-acters to the user, it also send a scan code. Ascan code is unique for each key of the keyboard.Which mean a and capital A return the samescan code. Scan codes will allows you to read keyswhich does not send character: Insert, End, Ar-rows, Ctrl, etc. For each scan code, a series ofconstants has been made in order to compare the

    key pressed with these constants. Here is a fewexamples:

    KEY A KEY ENTER

    KEY INSERT KEY UP

    KEY ENTER PAD KEY LSHIFT

    KEY RSHIFT KEY 2 PAD

    The easiest way read the keyboard is withthe readkey function. This function wait for theuser to press a key and it then returns a pair

    9

  • 8/2/2019 Allegro Game Programing Tutorial

    24/130

    User Input 2.1 The Keyboard

    of scan code and ASCII character. The highest8 bits contains the scan code, the lowest 8 bitscontains the ASCII character.

    Figure 2.2: Scan Code and Ascii

    In order to get the Scan code, we simplyshift the result to the right by 8 bits. You canuse a simple shift operator (readkey() >> 8) todo the job. If you want to read the Ascii code,simply make an AND with a mask to eliminatethe scan code (ex: (readkey() \& 0xff) ).

    The problem with readkey is that it stop

    the program until a key is pressed. This is gen-erally not useful since we want to be able to dosomething else while the user does nothing (likemoving enemies). This is why you have access tothe key pressed by using a global array defined as:

    extern volatile char key [KEY MAX]

    The array key is ordered by scan codes, soyou can use the same scan codes constant to ac-cess the table. For example, to test if the enterkey has been pressed, you could write the follow-ing code :

    if (key[KEY_ENTER])

    printf("Enter is pressed\n");

    The shift states of the keyboard can be readthrough a variable defined as:

    extern volatile int key shifts ;

    This is a bit field where each bit set deter-mine that the key state is on. There is a seriesof constants mask that you can use to mask thebits you want to read. Here are a few of them:

    KB SHIFT FLAG

    KB CTRL FLAG

    KB ALT FLAG

    KB NUMLOCK FLAG

    KB CAPSLOCK FLAG

    Another useful function is keypressedwhich return true if a key is currently waitingin the keyboard variables. This function is theequivalent of kbhit() libc function.

    Here is an interesting function which can beused for demo playback. The following function

    simulate the key passed in parameter to the Al-legro keyboard system.

    void simulate keypress (int key)

    If you do not wish to read the key-board through interrupt, you can use the pollingmethod. This mean that you must call a func-tion to update the keyboard variables. Thepoll keyboard function set the keyboard in pollmode and will also update the keyboard vari-ables. When using the polling method, you must

    call this function each time you want to updatethe keyboard keys. Keyboard functions like read-key and keypressed automatically call this pro-cedure, so there is no need to call poll keyboardbefore calling theses.

    2.1.2 Keyboard interrupt handler

    For simple games, the material above can do a

    good job. But for some games, we need a last keysystem. The last key system can only be done byhooking our own interrupt handler. But first letstart to explain why we need the last key.

    Let say you are playing an RPG like dragonwarrior and you are walking on the world map.If you hold the left key in order to move left,you keyboard will read your keys much fasterthan the game since your character walk slowerthan your keyboard input. Which mean that your

    keyboard will accumulate left keys in the buffer.When you release the key, instead of stopping,your sprite will continue to move left until youbuffer is empty. And if your keyboard does notread the keys fast enough, you will even hear abeep when the buffer is full. This is somethingwe do not want to happen.

    So I have made what I call a last key system.Each time a key is pressed, this key is backed upin a separate variable and replaced by subsequent

    10

  • 8/2/2019 Allegro Game Programing Tutorial

    25/130

    Video Game Programming with allegro

    key press. When we read the keyboard, we readthe last key instead of the buffer and we clear thebuffer to make sure it does not overflow, since wewill never read the buffer. Figure 2.3 will illus-trate this.

    Figure 2.3: Last Key System

    You do not use this technique when readingthe keyboard for text input because you will losesome letters. Each time you read the last key, youshould clear the keyboard with the clear keybuffunction. If you do not read the keyboard fastenough to avoid a buffer overflow, you can alwayscall this function inside the interrupt handler butI am not sure if this function take a lot of timeto execute.

    The last key can only be made by an inter-

    rupt handler which will back up the key beforethe driver receives it. This handler must be smalland must not do time consuming operations be-cause each time a key is pressed the processor isinterrupted and it execute this routine. Here isthe last key keyboard handler:

    int Input_inspect_key ( int key )

    {

    Input_last_key = key;

    return ( key );

    }

    END_OF_FUNCTION ( Input_inspect_key );

    The keyboard interrupt handler must bedefined as an "int function (int)". Thekey variable is the key pressed on the key-board which is backed up in the global variableInput_last_ley. The "return (key)" allows

    to pass the key to the rest of the Allegro key-board system. Yes, it mean that you can changethe key pressed. For examples, you can make aninterrupt routines than changes all a keys toy.

    There are a few important things tonote. The END OF FUNCTION is like andEND OF MAIN. It is a macro which makes someconfiguration to make sure it can be used cor-rectly as an interrupt handler. Input last keymust be declared as volatile variable like this :

    volatile int Input last key;

    The volatile indicates that the variable canbe changed anytime during the process of thegame. The compiler will make sure the variablenever gets corrupted or transfered into a register

    variable.Then you must lock your variables and func-

    tions. Locking allows to prevent the memorymanager from caching to disk theses variables andfunctions since they always need to be availablein memory. You can lock them with the followingcommands:

    LOCK VARIABLE ( Input last key );

    LOCK FUNCTION ( Input inspect key );

    If is possible that you receive a compilererror with LOCK FUNCTION. You can castits parameter as a (void*) to solve the prob-lem. Then we need to tell allegro that thisis the keyboard handler that we want to use.Allegro has a function pointer variable namedkeyboard callback. We only need to give it theaddress of our function like this:

    keyboard callback = Input inspect key;

    When this is done, the routine will be called

    for each key pressed.

    2.2 The Mouse

    Like the keyboard, there is a driver who inter-pret the data sent by the mouse. Even if we canhook an interrupt on the mouse, it is not so use-ful because the Allegro mouse functions does cor-rectly the job. The mouse send its coordinates

    11

  • 8/2/2019 Allegro Game Programing Tutorial

    26/130

    User Input 2.2 The Mouse

    as Mickeys. This is a measurement unit indepen-dent from the resolution of the screen. You donot need to worry since Allegro will convert themfor you. First you need to call install mouse toinstall the mouse driver. When you are done, youcall the function :

    void show mouse (BITMAP *bmp);

    This function determines on which bitmapthe mouse must be shown. Most of the time,you will show it on screen, but you can draw itsomewhere else. When you blit an image on thescreen while the mouse pointer is show, it will pro-duce some kind of glitch. To solve this problem,you must hide the mouse pointer before drawingthe screen. Calling scare mouse will temporar-ily hide the mouse pointer. When the blitting

    is finished, you call unscare mouse to show thepointer. This will become more obvious whenyou will have learned double buffering and pageflipping.

    2.2.1 Reading the mouse

    The mouse is managed by interrupts, which meanthat the position is updated while the program

    is running. The current status of the mouse isstored in the following variables :

    extern volatile int mouse x ;

    extern volatile int mouse y ;

    exterm volatile int mouse z ;

    extern volatile int mouse b ;

    extern volatile int mouse pos ;

    mouse x and mouse y contains the X,Yposition of the mouse. These values range from 0to the bottom right corner of the screen. Whichmean that the values range depend on yourscreen resolution. The mouse z variable containsthe state of the wheel position of the mouse. Themouse b variable is a bit field where each bit rep-resent the status of a button. You can read themwith masks like in this example:

    if (mouse_b & 1)

    printf("Left button is pressed\n");

    Figure 2.4: mouse b bit field

    The mouse pos is a variable containingboth X and Y positions. This is useful for read-ing both value at the same time in case the mousechange position during the delay between X andY variable reading. The X position is containedin the highest 16 bit while the lower bit hold theY value.

    Figure 2.5: mouse pos variable

    If you wish, you can force yourself the move-ment of the mouse with the following function :

    void position mouse (int x, int y);

    The mouse can also be read with the pollingmethod. The poll mouse procedure set themouse driver in poll mode and will it will thestatus of the mouse. You must call the proce-dure each time if you want to update the mousevariables shown above.

    Another interesting feature is done by func-tion get mouse mickeys. Some time in videogames, like space shooter or an arkanoid, youwant the mouse to control the movement of

    a sprite. In this case, you do not want toknow the coordinates of the mouse, you onlywant to know if the mouse has moved left orright. get mouse mickeys will return how farthe mouse has moved since its last call. Themouse will continue to generate movement evenif the mouse pointer reach the end of the screen.Of course, it is a good idea to hide the pointersince you dont use it. Here is the definition ofthis function:

    12

  • 8/2/2019 Allegro Game Programing Tutorial

    27/130

    Video Game Programming with allegro

    void get mouse mickeys (int *mickeyx,

    int *mickeyy);

    2.2.2 Configuring the mouse

    It is possible to influence the behavior of the

    mouse. First, you can change the movementspeed of the mouse with function :

    void set mouse speed (xspeed, yspeed);

    The parameter of this function are vir-tual values which slowdown the movement of thespeed when the value is higher. The speed can beconfigured independently for each axis. Anotherinteresting function is:

    void set mouse range (x1, y1, x2, y2);

    Which defines an area of the bitmap wherethe mouse is allowed to move. This is useful ifyou want to mouse to stay locked in an area ofthe screen.

    Finally, you can change the mouse pointerimage according to the need of you game.You must first change the bitmap by callingset mouse sprite with the mouse pointer imagein parameter.

    void set mouse sprite (BITMAP *sprite);

    The you must set the focus point of themouse according to the bitmap. By default, thevalue is 0,0 since the mouse point to the top leftcorner of the bitmap. But for example, you couldmake a cross hair pointer, in this case the focuspoint will need to be in the center of your bitmap.The focus point can be set with:

    void set mouse sprite focus ( x, y);

    2.3 The Joystick

    The joystick does not use interrupts, so we needto use the polling method. The Joystick is notdependent from any driver (like the sound cardfor example), this is why the software must readthe joystick itself. Joystick can be either pluggedinto the midi port of the sound card or in the

    parallel port. Allegro now support console joy-stick wired for the parallel port. Note that USB

    joysticks are not joysticks, they redirect their in-put on the keyboard through a driver software. Ifyou use a usb joystick which is redirected to thekeyboard, simply read the keyboard.

    The Allegro joystick driver support up to4 joysticks ( you can plug many controllers onthe same parallel port ). This is why mostof all the joystick variable are arrays of 4 ele-ments. To install the joystick, you must call in-stall joystick with the joystick type in param-eter. To catch all joystick type you normallyuse is JOY TYPE AUTODETECT which willattempt to auto-detect the joystick installed onyour computer. Which mean you will normallycall it like this:

    install joystick (JOY TYPE AUTODETECT);

    To know how many joystick have been de-tected you can read the following variable to getthe results:

    extern int num joysticks ;

    2.3.1 Calibrating the joystick

    The reason why calibration is necessary is due tothe fact that all joysticks have a different rangesof values. This is why, the software must knowwhat are the limits values of you joystick and cal-culate the movement in proportions to theses val-ues. The best way to calibrate a joystick is byusing the Circle around, center and press but-ton technique. With this technique, you pushthe joystick to the maximum limit it can reach.Then Allegro convert this value in a standard pro-

    portional range. To calibrate a joystick you cancall the following function with the id number ofthe joystick in parameter ( 0 if you have only 1

    joystick ):

    int calibrate joystick (int n);

    This function does not show anything onthe screen. So you show on the screen circle

    joystick around and press a button and then youcall calibrate joystick.

    13

  • 8/2/2019 Allegro Game Programing Tutorial

    28/130

    User Input 2.3 The Joystick

    If you do not want the user to calibrate thejoystick each time he plays the game, you cancall the following function to save and load allthe joystick calibration data on the disk.

    int save joystick data (const char

    *filename);

    intload joystick data

    (const char*filename);

    You pass the filename of the configurationfile you want to save or load but you can also passa NULL value which will save or load the joystickconfiguration from the Allegro configuration file.

    2.3.2 Reading the Joystick

    The reading part is a bit more complicated. Firstyou need to call poll joystick each time you wantto read the joystick input else the joystick vari-ables wont change. The joystick variables arestored as a tree of structures. Sometimes youmust dig in very deep to get the variable youwant. Look at figure 2.6 to see the structure.

    Figure 2.6: Joystick variable structure

    The top level structure is defined as follow:

    extern JOYSTICK_INFO joy[n];

    typedef struct JOYSTICK_INFO

    {

    int flags;

    int num_sticks;

    int num_buttons;

    JOYSTICK_STICK_INFO stick[n];

    JOYSTICK_BUTTON_INFO button[n];

    } JOYSTICK_INFO;

    This is the structure array joy where N is

    the ID number of the joystick. If you only read1 joystick, it should always be 0. The joy ar-ray is made of the structure JOYSTICK INFOwhich contains come information about the joy-stick. You must read button to get the buttonstatus and stick to access the joystick position.You can also check how many buttons and sticksthere are with num sticks and num buttons.

    Let start with button.This variableis an array of structures called JOY-

    STICK BUTTON INFO which is defined asfollow:

    typedef struct JOYSTICK_BUTTON_INFO

    {

    int b;

    char *name;

    } JOYSTICK_BUTTON_INFO;

    The field which interest us is the b fieldwhich is a boolean indicating if the button ispressed. Each element of the button array repre-sent a button of the joystick. Which mean that ifwe want to read the 1st button of the 1st joystick,we will use the following code:

    if ( joy [ 0 ] . button [ 0 ] . b == true

    printf {"The first button is pressed"}

    Here is the code to read the 3rd button :

    if ( joy [ 0 ] . button [ 2 ] . b == true

    printf {"The first button is pressed"}

    For reading the joystick position, we mustgo deeper into the stick array which is defined asfollow:

    14

  • 8/2/2019 Allegro Game Programing Tutorial

    29/130

    Video Game Programming with allegro

    typedef struct JOYSTICK_STICK_INFO

    {

    int flags;

    int num_axis;

    JOYSTICK_AXIS_INFO axis[n];

    char *name;

    } JOYSTICK_STICK_INFO;

    The stick array has an element for eachstick of the keyboard. For example, an analogplay station controller will have 3 sticks: theDpad, the left analog and the right analog. Ifyou only have 1 stick, you will always use sick0. In the stick structure we have the axis arraywhere each element represent an axis. A normaldpad have 2 axis : the X and Y axis but a throt-tle stick will only have 1 axis. Axis 0 is used for

    X and axis 1 is used for Y. The axis structure isdefined as follow:

    typedef struct JOYSTICK_AXIS_INFO

    {

    int pos;

    int d1, d2;

    char *name;

    } JOYSTICK_AXIS_INFO;

    The pos variable is the analog value rep-resented by a value ranging from -128 to 128 orfrom 0 to 255 according to the type of stick (ex:throttle stick ). The d1 and d2 variables areused to know the digital direction of the joystick.These are boolean which are set when the joystickis pressed in this direction. Since an axis has 2directions, there is 1 variable for each direction.Which mean that if we want to read the analogvalue of the X position, on the 1st stick of the 1st

    joystick, we use the following code:

    x_pos = joy[0] .stick[0] .axis[0] .pos;

    The y position would have been read likethis :

    y_pos = joy[0] .stick[0] .axis[1] .pos;

    While If you want to test the digital direc-tions pressed on the joystick, you will use the fol-lowing code:

    if ( joy[0] .stick[0] .axis[0] .d1 > 0 )

    printf ("User pressed left");

    if ( joy[0] .stick[0] .axis[0] .d2 > 0 )

    printf ("User pressed right");

    if ( joy[0] .stick[0] .axis[1] .d1 > 0 )

    printf ("User pressed up");

    if ( joy[0] .stick[0] .axis[1] .d2 > 0 )

    printf ("User pressed down");

    As you can see, the joysticks structures arevery complex but it is essential to support all thespecial features and goodies available on the mar-ket.

    This is all there is to learn. There is a fewdetails I have not talked about yet that I willkeep for later. You can take a look at the alle-gro examples for managing the joystick and otherdevices if you wish. In the next chapter, we willtalk about the most important device, the videoscreen.

    15

  • 8/2/2019 Allegro Game Programing Tutorial

    30/130

    User Input 2.3 The Joystick

    16

  • 8/2/2019 Allegro Game Programing Tutorial

    31/130

    Chapter3

    Video Output

    In this chapter, you will learn how to man-age the video screen. We wont draw anythingyet, except for testing purposes. There is still alot of thing to talk about even if we dont reallydraw anything on the screen.

    3.1 Video Hardware

    The video card contains some memory in orderhold the information drawn on the screen. Thescreen monitor ask the video card to send the con-tent of its memory regularly in order to updateits screen. The screen refresh is called Verti-cal Synchronization. A monitor with a speed of70 Hz will refresh the screen 70 times per sec-

    ond. The video memory is interpreted differentlyaccording to the video modes you are in. For ex-ample, the text mode will represent the screenwith characters while the graphic mode will rep-resent it with pixels.

    The video card possess a series of registers.These registers allows to configure how the videocard will work. In the ROM of the video card,there are some Video Modes which is a pre-defined configuration of the video card register

    to get a specific video output. For example, thefamous 13h VGA video mode ( 320x200x256 col-ors ) can be configured automatically by callinga function from the BIOS. It prevents you fromknowing how to configure the registers. There areother video modes like the mode X ( 320x240x256colors ) which has been achieved by actuallytweaking the video card s registers.

    When many SVGA cards arrived on themarket, the Vesa standard has been adopted.

    Vesa is a standard BIOS in the card which al-lows to configure various video resolution ancolor depth without tweaking the register your-self. There are various version of Vesa, but mostrecent video cards should support Vesa 3. For

    version 1.x, you might need sci-tech s displaydoctor or use another driver system to configurethe registers correctly (see below).

    3.1.1 Initiating the Video Mode

    In allegro, initiating the video mode is just a mat-ter of resolutions and colors. The video buffer is

    just a big 2 dimensional table. Each element inthe table represent a pixel. The X coordinatesgoes from left to right while the Y coordinatesstart from the top to the bottom.

    Figure 3.1: Video Buffer

    Which mean that when you want to writeon the screen, you simply need to change a value

    17

  • 8/2/2019 Allegro Game Programing Tutorial

    32/130

    Video Output 3.2 True Color Video Mode

    in this table. The content of each element in thetable depends on the color depth you have se-lected. There are different kinds of video infor-mation. The allegro function which set the videomode is:

    int set gfx mode (card, w, h, v w, v h);

    The w and the h parameters is actu-ally the width and the height resolution of thescreen you want. What you ask, is not neces-sarily what you get. If you ask for non-standardvideo resolution or if your user does not supportthis resolution, due to his video hardware or tothe lack memory, you will either receive anotherresolution or a failure to execute this function.This function return a negative number on fail-ure else it return 0. There are 2 macros whichallows you to check the current resolution of the

    screen:

    SCREEN W

    SCREEN H

    The card parameter is the name of a driversystem to use. The driver is not a specific driverto a video card like in Windows. Some exam-ples of driver system are: Vesa, Vesa 3, Mode X,VBEAF, etc. It does not matter if you actuallyhave an ATI, S3 or any other model of video card.

    Normally, you will callGFX AUTODETECT

    which will take the best video driver avail-able according to Allegro. There is alsothe GFX AUTODETECT FULLSCREEN andGFX AUTODETECT WINDOWED constantsused for windowed OS.

    The v h and v w parameters are use for vir-tual screens. It allows you to allocate a videobuffer larger than the screen and use hardwarescrolling procedures to scroll the screen. Ofcourse, you cannot allocate more than the videomemory available on the card. One allocated, youcan scroll the screen with hardware routines withfunction :

    int scroll screen (int x, int y);

    Still, not all video cards support hardwarescrolling. When PC technology evolved, theyhave decided to implement some hardware rou-tines into the card in order to speed up the pro-cess like they do it in some video game consoles

    like the SNES. This allowed do to some commonvideo operation much more faster. When the 3Drevolution arrived, the video cards also added 3Droutines into their card to relieve the processorfrom excessive math calculation. When the videomode is set, there is a bit field containing a smalllist of hardware routines available in the system.

    This bit field is defines as:

    extern int gfx capabilities ;

    The are some mask constant to test the bitsof this variable, here is a few examples:

    GFX CAN SCROLL

    GFX HW HLINE

    GFX HW FILL

    GFX HW VRAM BLIT

    GFX HW MEM BLIT

    If you run in DOS, you might have touse the FreeBE/AF driver to take advantage oftheses. Take note that if you do not supportGFX HW MEM BLIT, you will have to copy theimages you want to draw into video memory, inorder to benefit from the hardware accelerationGFX HW VRAM BLIT. I have made a smalltest program which show all features of the card,this program should be available on my web sitewith its source code.

    3.2 True Color Video Mode

    As I have said before, beside the text mode, thereis 2 way to manage the video buffer: True Colorand palette video modes. In the true color videomode, you simply write the right color value intothe video buffer table. This color value is made of3 other values which each represent the primary

    light colors: Red, Green, and Blue. The numberrange of each value varies according to the colordepth of the video mode you want. Take a lookat figure 3.2:

    As you can see on figure 3.3, there is anRGB value for each element in the table. Thenumber of bit of each RGB value varies accordingto the color depth. Of example, in the 15 Bitvideo mode, 5 bit is reserved for each value. A 5bit value can range from 0 to 31, if we combine

    18

  • 8/2/2019 Allegro Game Programing Tutorial

    33/130

    Video Game Programming with allegro

    Figure 3.2: RGB values

    Figure 3.3: True Color video buffer

    the 3 values together we can make up to 32768colors (32x32x32). On the 24 bit video mode, wehave 3 values of 8 bit which each can range from0 to 256 giving up to 16777216 different colors.The alpha in the 32 bit video mode represent thetranslucency of the pixel in case you would wantto make some part of the image translucent. Wecan still perform complete translucency in anycolor depth.

    In allegro, the color depth is determined

    by set color depth which must be called beforeset gfx mode. You pass in parameter the colordepth you wish: 15, 16, 24, 32.

    void set color depth (int depth);

    Since the color depth have all differentranges of values, there is a standard functionnamed makecol which take 3 the RGB values asparameter. The values range from 0 to 255 what-ever is the current color depth and it will return

    the correct color value according to the currentactive color depth. You should always use thisfunction when you want a color for any drawingoperation in true color video mode.

    3.2.1 Calculating Resource Usage

    You might thought that more color and pixels isbetter, so why bother with low color depth or evenlow resolution. Let just use 32 bit colors witha 1280x1024 pixel video mode and show superbgraphics. As you will see, doing so might notbe possible on all computer. There is 2 majorlimitation: Memory, speed and hardware.

    First, lets calculate the video memory re-quired to allocate the video buffer above: 32bit is stored in 4 bytes. We need 4 bytes foreach element of the video buffer which makes4x1280x1024 for 5242800 bytes. 5 megs! not thatbad, my video card have 64 Megs. Still, you willsee later in this book that we need a temporarybuffer to draw our frames. Which mean that youneed to allocate another 5 meg of video memory.Then you must consider that all the images inthe game must also be bigger in order to fill thescreen. So a full screen image will also take 5Megs of memory and disk space. If you make an

    intro movie for your game at this resolution, I amcurious to see the size of your file.

    The second reason is the speed. A normalvideo game should run at 60 frames per seconds.What this mean is that you must draw all thesprites, images and special effect on the screenand repeat the whole process 60 times in a second.With the resolution defined above, this mean thatwe must at least draw 5242800 pixels for eachframe but since there is generally layers overlap-

    ping for the background, level and sprite, we willwrite at least 3 times more pixel than the screenresolution for a total 15728400 pixel in 1/60th ofsecond, multiply it by 60 for 1 second. Whichmean that we must draw 943704000 pixel in 1second. With that much pixels to draw, you willneed a lot of processing power.

    We can vaguely calculate the processingspeed required by dividing this number by 1 Mil-lion to get the number of MHz required. In this

    19

  • 8/2/2019 Allegro Game Programing Tutorial

    34/130

    Video Output 3.3 Palette Video Mode

    case, it would be 943 MHz but it is not a precisevalue since we exclude command operation, otherprocess to do in the game, the temporary buffercreation, and the fact that some processes liketranslucency takes much more time. We also donot consider Video card acceleration and MMXsupport for example. Still, this should be the

    speed required in order to simply transfer thedata without optimization.

    Yes, some computer can make it today butit is not every body that has the latest super com-puter on the market. It is even possible that theusers hardware cannot support the 32 bit res-olution. This is why you should select a moreconvenient resolution. Lets take the exampleabove and reduce the parameters by 1 rank: 24bit color and 1024x768 pixel. In this mode, We

    would require 2359296 bytes of video memory andwe would have needed to write 424673280 pix-els in a second. Which make a reduction of 55%for memory usage and processing power required.The best of it, is that the user will barely see adifference in the graphic output. Take note thatwhen you are doing 3D graphics, the resolutiondifference is even more difficult to perceive. I haveplayed Unreal Tournament in 400x300 and it wasstill playable. Here is a small table which indi-cates the video memory required for each resolu-tion versus color depth.

    Table 3.1: Video Buffer Memory Size

    15,16 24 32 Bit

    640x480 614 K 921 K 1.22 M800x600 960 K 1.44 M 1.92 M1024x768 1.57 M 2.35 M 3.14 M1280x1024 2.62 M 3.93 M 5.25 M

    3.3 Palette Video Mode

    The second type of video mode is the palettevideo mode. It is referred as the 8 bit video modeeven if it is not necessarily an 8 bit color depth.In a palette video buffer, we indicate an indexnumber which refer to an element of the colorpalette. The color palette is a table of 256 colordefined with RGB values. Instead of copying the

    RGB value in the video buffer, we copy the indexof the palette where the color is stored. Checkfigure 3.4.

    Figure 3.4: Video Buffer in Palette mode

    The first advantage of this mode is that it

    takes even less resources since there is only 1 byteper pixel. It can be an advantageous mode forlow processing machines like a Game park 32 ora Pocket PC. The second advantage is that youcan make palette animation effects or color vari-ation ( Use the same sprite but change the col-ors ). The disadvantage is that you must makecome palette management before drawing of thescreen, you are also limited to use 256 colors atonce and you must take some precautions whenmaking your images (See later). Take note that

    there is only one palette mode available which isreferred as 8 bit. So you cannot have anotherpalette mode with a larger palette for examplebut the palette video mode is supported by manyvideo resolutions.

    3.3.1 Managing the Color Palette

    The color palette is a table of 256 elements. Thistable of elements is defined as a PALETTE type.

    Each element of this table is an RGB structurewhich is defined below:

    typedef struct RGB

    {

    unsigned char r, g, b;

    } RGB;

    This structure contains the RGB value ofthe color. These values range from 0 to 63, in

    20

  • 8/2/2019 Allegro Game Programing Tutorial

    35/130

    Video Game Programming with allegro

    fact, they are 6 bit value. The palette video mode,could be considered as an 18 bit color depth sinceit can reach up to 626144 colors, but even if wehave more colors than the 15 bit video, we canstill only use 256 of them at the same time.

    Figure 3.5: Color Palette Entry

    You can change a color palette by modify-ing each value independently. To do so you useset color. You can also write the whole paletteat once with the set palette procedure. Here isthe definition of these two functions:

    void set color (int index, const RGB *p);

    void set palette (const PALETTE p);

    Reading the color from the palette is donethe same way with the 2 following functions whichare somewhat self explainable.

    void get color (int index, RGB *p);

    void get palette (PALETTE p);

    Just take note that the palette changes mustbe done while the screen is not being refreshed.Changing colors during the screen refresh can

    cause some flickering on the screen. set palettewill automatically wait for screen refresh to end,it is done with the vsync function which we willsee later.

    We will also see in a later chapter how tomake color sets in order to make sure that thepalette of various images does not overlap eachother. A popular technique consist to divide thepalette in 16 color sets of 16 colors and make eachimages use one color set with its own unique 16

    colors. These colors must be uploaded into thepalette before being used.

    3.3.2 8 Bit Video Mode Emulation

    Another way to solve the problem illustrated inthe paragraph above can be done my making thepalette video mode emulate a 8 bit video mode.By doing so, we will define a unique palette thatwill never change during the game. All the images

    will conform themselves to this palette. Allegrosupplies a function to generate a 8 bit set of colorsin the palette.

    Figure 3.6: 8 Bit color depth Emulation

    The idea is to generate all the possible col-ors which can be drawn in an 8 bit color depthand place them in the palette. You can callgenerate 332 palette to generate a 8 bit palettemade of 3 bits red, green and 2 bits blue.

    void generate 332 palette (PALETTE pal);

    You make a program that generate thispalette and make a screen shot of the screen withsave bmp or alegsave pcx. Then you load thisfile in your image editor. Save the palette of thisfile according to your software s format and eachtime you make a new image, load this palette. Ifyou proceed this way, all you images will have the3-3-2 palette and you will never bother changingor loading palette anymore, you just call gener-ate 332 palette.

    By the way there is also a demo, in theallegro examples, that shows how to make a 12bit video mode by tweaking the video card. Youmight want to take a look if you need more color.

    So this is it, there is still a lot of things tolearn about the video screen that we will see inthe following part. I have decided to make 2 smalltest program which each start the video mode anddraw a rectangle around the screen. On is donein true color and the other one in palette mode.

    I also use the function rect, which allows to drawa rectangle on the screen. You will learn it withthe drawing primitives.

    21

  • 8/2/2019 Allegro Game Programing Tutorial

    36/130

    Video Output 3.3 Palette Video Mode

    Listing 2 True Color Video Mode Usage/**************************************************************************/

    /* True Color Video Mode Initialisation and Usage */

    /* By Eric Pietrocupo */

    /**************************************************************************/

    #include

    int main ( void ){

    allegro_init();

    install_keyboard();

    set_color_depth (16);

    set_gfx_mode(GFX_AUTODETECT, 640, 480, 0, 0);

    rect( screen, 0, 0, 639, 479, makecol(255, 255, 255));

    while ( (readkey() >> 8) != KEY_ENTER );

    allegro_exit();

    return (0);

    }

    END_OF_MAIN();

    Listing 3 Palette Video Mode Usage/**************************************************************************/

    /* Palette Video Mode Initialisation and Usage */

    /* By Eric Pietrocupo */

    /**************************************************************************/

    #include

    int main ( void )

    {

    allegro_init();

    install_keyboard();

    RGB tmpcolor = { 63, 63, 63 }; // White Color

    set_color_depth (8);

    set_gfx_mode(GFX_AUTODETECT, 320, 240, 0, 0);

    set_color ( 1, &tmpcolor );

    rect( screen, 0, 0, 319, 239, 1);

    while ( (readkey() >> 8) != KEY_ENTER );

    allegro_exit();

    return (0);

    }

    END_OF_MAIN();

    22

  • 8/2/2019 Allegro Game Programing Tutorial

    37/130

    Chapter4

    Audio Output

    Playing sound in allegro is easy, in fact thereis just a few functions to learn. This is why I willalso cover in this chapter how the sound hardwareworks and explain the difference between SoundSampling and instrumental music.

    4.1 Basics of Sound

    Sound is made by waves which are sent in the air.The speaker is made of an electric magnet whichmust receive power variation to send these waves.The form of the power variation will influence thetype of sound generated. A basic beep sound canbe perform by a sinus wave type like on figure 4.1.

    Figure 4.1: A sound Wave

    The pointed line indicate 0 volt, when thewave drop below the pointed line, it has a neg-ative voltage. The height of the wave is calledamplitude, it somewhat determines the volumeof the sound. When listening to AM radio, ifthere is some interferences, the amplitude mightraise and produce some glitch. The y axis is thewave length which is actually the time where thesound is played. The longer the wave, the longerit last.

    A sound wave must actually go up and downto produce a flat line wont produce anything.But the wave form of the sound can be of differentshape to produce various output. The pitch ofthe sound is determined by the frequency of the

    wave. The frequency determine how many timesin a second does the wave actually goes up anddown. Figure 4.2 show the difference between alower and higher frequency wave.

    Figure 4.2: Frequency Variations

    An higher frequency will produce high

    pitched sounds, while lower frequency producelow ones. The frequency can be measured in Hz.An 1000 Hz sinus waves means that the wave goesup and down 1000 times per seconds.

    The Sound card is an independent devicethat will manage the sounds processing itself torelieve the processor. Since we want to play soundan music while doing something else in our game,we gives orders for sound and music playing to thesound card, and it will make sure that the audio

    23

  • 8/2/2019 Allegro Game Programing Tutorial

    38/130

    Audio Output 4.3 Instrumental Music

    automatically get updated while the processor isdoing something else. For process not managedautomatically by the sound cards, Allegro installa series of interrupt handler to update constantlythe sound card information. So the game willnever wait for the sound to end before continuingits process.

    4.2 Sound Sampling

    For sinus waves, we can easily make a math for-mula that will always produce the same soundwave anytime we want. But math cannot produceall the possible waves forms we will need. This iswhy sampling becomes necessary. A sound waveis an analog output, we need to convert it intoa numeric format in order to save it and use itby your computer. Sampling a sound wave con-sist to take samples of the wave at a certainrate which will allow us to reproduce the originalwave after. If we take more sample in a second,reproduction of the wave is more likely to looklike its original.Figure 4.3 show a low sampledsinus wave.

    Figure 4.3: Sampled Sound Wave

    The amplitude of the wave is recorded as anegative or positive value which is proportionalto the voltage of the wave. The value range is

    determined by the bit rate of the sample. An8 bit sample value will range from -127 to 127while a 16 bit sample will range from -32768 to32768. A higher bit rated samples will producehigher quality sound since the resolution data ishigher. The sampling frequency determines howmany times in a second does the wave has beensamples. A music CD use a sampling rate near to44100 Hz. Look on figure 4.4 to see the differencebetween lower and higher sampling frequency.

    Figure 4.4: Various Sampling Frequency

    An higher sampling rate will produce higherquality sound. Take note that some hardwaredoes not support all bit rate and frequencies. Alsoconsider that sampling sound take a lot of spaceand memory. A 44100 Hz 16 bit sample whichlast 1 second need 88200 Bytes. Not so badfor a sound, but you generally have more thanone sound in a game. Dropping the sampling22050 Hz can produce reasonable sound quality.If you are making stereo samples, you must recorda sample for each panning side. Which mean thatthe size of the samples is doubled. So a 1 second44100 Hz 16 bit stereo sample will require 176400bytes of memory and disk space.

    If you use sound sampling to produce musicstream, 2 minutes of music sampled at 44100 Hzin 16 bit stereo will use 20 meg of memory ordisk space. This is why the MP3 compressionhas been made. Still, generally audio streamingsystem load blocks of music to play them in orderto save memory usage. I wont talk about audiostreaming but there is a another way to producegood music with few resources.

    4.3 Instrumental Music

    A music is a series of instruments with generallysomebody who sing on the top of the music. AnMP3 music simply take the wave output of allthe instruments and the singer together, sampleit and then compress it. But we can do almostthe same thing in a different way.

    24

  • 8/2/2019 Allegro Game Programing Tutorial

    39/130

    Video Game Programming with allegro

    Let say, we do not have a singer, we onlyhave instruments. Each instrument will alwaysproduce the same wave form, the only thing thatchanges is the frequency of the wave produced forvarious notes. So instead or recording the waveoutput of all instruments, we record which notesare played by each instrument and when are they

    played.

    Figure 4.5: Music Partition

    We first divide the music in tracks, eachtrack represent an instrument. The track con-tains all the notes that must be played at a spe-cific time. All track are played simultaneously.When a note must be played, it use the instru-ment wave