OpenGL Game Development By Example - Robert Madsen - E-Book

OpenGL Game Development By Example E-Book

Robert Madsen

0,0
51,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Design and code your own 2D and 3D games efficiently using OpenGL and C++

About This Book

  • Create 2D and 3D games completely, through a series of end-to-end game projects
  • Learn to render high performance 2D and 3D graphics using OpenGL
  • Implement a rudimentary game engine using step-by-step code

Who This Book Is For

If you are a prospective game developer with some experience using C++, then this book is for you. Both prospective and experienced game programmers will find nuggets of wisdom and practical advice as they learn to code two full games using OpenGL, C++, and a host of related tools.

What You Will Learn

  • Set up your development environment in Visual Studio using OpenGL
  • Use 2D and 3D coordinate systems
  • Implement an input system to handle the mouse and the keyboard
  • Create a state machine to handle complex changes in the game
  • Load, display, and manipulate both 2D and 3D graphics
  • Implement collision detection and basic physics
  • Discover the key components needed to complete a polished game
  • Handle audio files and implement sound effects and music

In Detail

OpenGL is one of the most popular rendering SDKs used to develop games. OpenGL has been used to create everything from 3D masterpieces running on desktop computers to 2D puzzles running on mobile devices. You will learn to apply both 2D and 3D technologies to bring your game idea to life.

There is a lot more to making a game than just drawing pictures and that is where this book is unique! It provides a complete tutorial on designing and coding games from the setup of the development environment to final credits screen, through the creation of a 2D and 3D game.

The book starts off by showing you how to set up a development environment using Visual Studio, and create a code framework for your game. It then walks you through creation of two games–a 2D platform game called Roboracer 2D and a 3D first-person space shooter game–using OpenGL to render both 2D and 3D graphics using a 2D coordinate system. You'll create sprite classes, render sprites and animation, and navigate and control the characters. You will also learn how to implement input, use audio, and code basic collision and physics systems. From setting up the development environment to creating the final credits screen, the book will take you through the complete journey of creating a game engine that you can extend to create your own games.

Style and approach

An easy-to-follow guide full of code examples to illustrate every concept and help you build a 2D and 3D game from scratch, while learning the key tools that surround a typical OpenGL project.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 359

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

OpenGL Game Development By Example
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Building the Foundation
Introducing the development environment
A quick look at Visual Studio
Start screen
The Solution Explorer panel
The Standard Toolbar panel
The code window
The output window
Starting your project
The game loop
The game structure
Initialization
The game loop
Shutdown
Creating the game structure
Port of access
The Windows message loop
Introducing OpenGL
What is OpenGL?
The other GL
Downloading OpenGL
Adding OpenGL to the project
Linking to the OpenGL library
Summary
2. Your Point of View
Plotting your revenge
The OpenGL coordinate system
Making your point
Understanding the code
Header files
Initializing OpenGL
The main entry point
The update function
Drawing the points
Running the program
Stretching your point
Getting primitive
A triangle by any other name
A primitive example
From triangles to models
Introducing textures
Using textures to fill the triangles
A matter of reference
Hanging out in the quad
Coding the quad
Rendering a texture
Loading the texture
Texture wrapping
Creating a textured quad
Putting the pieces together
Summary
3. A Matter of Character
Spritely speaking
Sprites versus non-sprites
Flipbook animation
Framed animation
Creating sprites
Working with PNGs
Linking to the SOIL library
Including the SOIL header file
Opening an image file
Coding a sprite class
Creating sprite frames
Saving each frame
Loading a sprite from individual textures
Creating a sprite sheet
Loading a sprite sheet
Loading our sprites
Rendering
Adding a render to the game loop
Implementing the main Render function
Implementing Render in the Sprite class
UV mapping
One more detail
A moving example
Adding update to the game loop
Implementing the main Update call
Implementing Update in the Sprite class
Character movement
Using delta time
Calculating delta time
Flipping
Scrolling the background
Using an atlas
Summary
4. Control Freak
A penny for your input
The keyboard input
Using the mouse
Touch
Other inputs
Someone is listening
The WndProc event listener
Handling the message queue
Handling mouse and keyboard inputs
Creating the Input class
Virtual key codes
Querying for input
Implementing the Input class
Adding input to the game loop
Processing our input
Changes to the Sprite class
Graphical User Interface
Creating a button
Enhancing the Input class
Adding UI elements to the list
Checking each UI element
Pushing your buttons
Adding our pauseButton
State management
Creating a state manager
Pausing the game
Summary
5. Hit and Run
Out of bounds!
Getting anchored
Collision rectangles
Embedding
Fixing the background
Collideables
Ready to score
A friend indeed
Time to spawn
Circular collision detection
The Pythagorean Theorem
Adding the circular collision code
Why use circular collision detection?
Wiring in the collision detection
Rectangular collision detection
The enemy within
Spawning the enemy
Adding the rectangular collision code
Wiring continued
Summary
6. Polishing the Silver
The state of the game
State machines
Why do we need a state machine?
Planning for state
Defining the new state
Implementing the state machine
Making a splash
Creating the splash screen
Defining the splash screen
Loading our resources
What's on the menu?
Creating the menu
Defining the menu buttons
Getting some credit
Creating the credits screen
Getting back to the main menu
Working with fonts
Creating the font
Drawing text
Wiring in the font support
Level up!
Displaying the score
Game progression
Defining game levels
Game stats
The next level screen
Continuing the game
Game over
The game over screen
Replaying the game
Summary
7. Audio Adrenaline
Bits and bytes
A sound by any other name
Making noise
Revving up your engine
Accessing the FMOD .dll file
Linking to the library
Point to the include files
Initializing FMOD
Virtual channels
Channel priority
Bleeps and bloops
Sound effects
Setting up the sounds
Playing sounds
UI feedback
The sound of music
Cleaning up the house
Release sprites
Release input
Releasing fonts
Releasing audio
Summary
8. Expanding Your Horizons
Into the third dimension!
Simulating 3D
Real 3D
3D Coordinate Systems
The camera
Remember those home movies?
Steady as she goes!
The viewport
Entering the matrix
Vectors
Combining vectors
Identity matrix
Coding in 3D
Creating the project
Retrieving OpenGL files
Linking projects to OpenGL libraries
Setting up the OpenGL window
Including header files
Defining global variables
Creating a function to create the OpenGL window
Sizing the OpenGL window
Initializing the OpenGL window
Creating a function to remove the OpenGL window
Creating the OpenGL window
Creating the Windows event handler
The Game loop
The finale
Summary
9. Super Models
New Space
A computer in a computer
Drawing your weapons
Getting primitive
Drawing primitives
Making your point
Gl_Points
Getting in line
Gl_Lines
Gl_Line_Strip
Gl_Line_Loop
Triangulation
Gl_Triangles
Gl_Triangle_Strip
Gl_Triangle_Fan
Being square
Gl_Quads
Gl_Quad_Strip
Saving face
Back to Egypt
A modeling career
Blending in
Blender overview
Building your spaceship
Exporting the object
Getting loaded
Summary
10. Expanding Space
Creation 101
Preparing the project
Loading game objects
The Model class header
Implementing the Model class
Modifying the game code
Taking control
Implementing input
Asteroid slalom
Setting up collision detection
Turning on collision
Summary
11. Heads Up
Mixing things up
The saving state
Push and pop
Two state rendering
A matter of state
Adding the state machine
Getting ready for a splash
Creating the user interface
Defining the text system
Defining textures
Wiring in render, update, and the game loop
Summary
12. Conquer the Universe
A fun framework
Setting up the Visual Studio project
Setting up the Windows environment
Setting up the OpenGL environment
Setting up the game loop
Texture mapping
Loading the texture
Rendering the cube
Mapping operations
Let there be light!
Defining a light source
The skybox
Advanced topics
Game physics
AI
The future
Summary
Index

OpenGL Game Development By Example

OpenGL Game Development By Example

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: March 2016

Production reference: 1010316

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78328-819-9

www.packtpub.com

Credits

Authors

Robert Madsen

Stephen Madsen

Reviewers

Artemis Tsouflidou

Simon W. J. Vanhauwaert

Pantelis Lekakis

Commissioning Editor

Julian Ursell

Acquisition Editor

Shaon Basu

Content Development Editor

Siddhesh Salvi

Technical Editor

Parag Topre

Copy Editor

Priyanka Ravi

Project Coordinator

Paushali Desai

Proofreader

Safis Editing

Indexer

Monica Ajmera Mehta

Graphics

Disha Haria

Production Coordinator

Nilesh Mohite

Cover Work

Nilesh Mohite

About the Authors

Robert Madsen is an accomplished game programmer, with dozens of published games to his credit. He started programming in 1979, and he has been a programmer for all of his professional life. He entered the game industry in 2004, and he founded SynapticSwitch, LLC in 2010. As studio director, he continues to code while also managing the broader needs of an independent game development studio.

Stephen Madsen completed his degree in game development from Full Sail Real World Education in 2007, beginning his first job as a game programmer in 2008. He then joined SynapticSwitch, LLC as the lead software engineer in 2012. He has developed and published many titles on the mobile, console, and personal computer platforms with OpenGL being the foundational rendering technology for most of these platforms.

About the Reviewers

Artemis Tsouflidou is a game developer based in London, and she has experience in gameplay programming. She studied computer engineering at the University of Thessaly in Greece, and she continued her studies at Goldsmiths University where she earned a master's degree in computer games. She is interested in programming and game development.

Simon W. J. Vanhauwaert is a Belgian game development programmer. He graduated in digital arts and entertainment, and he is currently professionally employed in the UK.

Pantelis Lekakis has been in the game industry for 4 years now, and he has been actively programming and developing his own projects since 2002.

His experience lies in rendering and game engines, and he has worked with various versions of Direct3D and OpenGL.

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

Preface

Welcome to OpenGL Game Development Blueprints! We are excited that you chose this book as your guide to both OpenGL and game development. This section will provide you with a brief preview of each chapter, followed by the technologies that are required to complete the work that is presented in the book. Finally, we will discuss the target audience for this book so that you will know whether this book is right for you.

What this book covers

Chapter 1, Building the Foundation, guides you through creating the code framework for the game. Games use a particular structure that is known as the game loop. By the end of this chapter, you will understand and have created the game loop for the game as well as initialized the required OpenGL elements.

Chapter 2, Your Point of View, introduces you to the first project in the book—creating a 2D platform game. The first step in this project will be to define the type of view that is required by OpenGL, and render the background of the game.

Chapter 3, A Matter of Character, covers the creation of sprites that move on the screen. 2D frame-based animations are the core of any 2D game, and you will learn how to create simple graphics and render them to the screen.

Chapter 4, Control Freak, teaches you how to build an input system that will allow you to control the main character and other aspects of the game. You will also create a basic user interface that allows you to start the game and navigate to various options.

Chapter 5, Hit and Run, covers collision detection. You will learn how to stop the character from falling through the ground, how to land on objects, and how to detect whether enemies have hit you or have been hit by player weapons. By the end of this chapter, you will be able to play the game for the first time.

Chapter 6, Polishing the Silver, covers the topics that make a game presentable (but are often overlooked by novice developers). You will learn how to implement a scoring system, game over and game won scenarios, and simple level progression. This chapter will conclude the 2D project of the book.

Chapter 7, Audio Adrenaline, guides you through implementing sound effects and music in the game. We will provide links to some audio files that you can use in your game.

Chapter 8, Expanding Your Horizons, will start the second project of the book—a 3D first-person space shooter. At the end of this chapter you will have created a new project, starting the framework for a 3D game.

Chapter 9, Super Models, introduces you to the concepts of 3D art and modeling, and then guides you through the process of loading 3D models into the game environment. Although you will be able try your hand at creating a 3D model, the resources that are required for the game will be provided online.

Chapter 10, Expanding Space, expands on many of the concepts that were covered in the 2D segment of the book and applies them to a 3D world. Movement and collision detection are revamped to take this new dimension into consideration. An input scheme to move in 3D space is implemented. By the end of this chapter, you will be able to control a 3D model in 3D space.

Chapter 11, Heads Up, guides you through creating a 2D user interface on top of the 3D world. You will create a menu system to start and end the game, as well as a heads-up-display (HUD) that shows the score and stats in game. By the end of this chapter, you will have created a playable 3D shooter game.

Chapter 12, Conquer the Universe, introduces you to some of the more advanced concepts that were beyond the scope of the book, and it gives you some direction to advance your skills.

What you need for this book

Each chapter in the book will have exercises that you will need to code. Each exercise is a building block toward creating your first game using OpenGL. It is vitally important that you actually write the code. In our experience, you can't learn any kind of computer programming without actually writing code. Don't just read the book, do the book!

The first chapter of the book will go through the details of setting up a development environment so that you can code the examples in the book. In general, you will need the following:

A Windows-based personal computer: You could use a Mac, but the examples used in the book are based on a Windows 10 operating system.A copy of Visual Studio: We will show you how to obtain and install this for free in chapter one, or you can go to http://www.visualstudio.com/downloads/download-visual-studio-vs right now. Again, you could use another development tool and compiler, but you are on your own to set it up.A 2D image editor program: We recommend GIMP, which you can download for free at http://www.gimp.org/.A 3D modeling program: We recommend Blender, which you can download for free at http://www.blender.org/.An Internet connection: You could complete the exercises without this, but an Internet connection is very useful for looking up additional resources.Some free time and dedication!

That's it! The good news is that as long as you have a personal computer, the technology and tools that are used to create games using OpenGL are completely free!

Who this book is for

If you are reading this book, it is pretty obvious that you are interested in game development. You have either heard of OpenGL or perhaps even used it, and you want to learn more. Finally, you are already a programmer in some computer language or you want to be.

Does this sound like you? Read on!

This book assumes that you have some familiarity with computer programming in the C++ computer language. If you have programmed in some other language, such as C#, Java, JavaScript, or PHP, then you are pretty familiar with the constructs of the C++ language. Nevertheless, if have never programmed in C++ then you may need to brush up on your skills. You can try Microsoft Visual C++ Windows Applications by Example, also published by Packt Publishing. If you feel comfortable with programming in general, but have not coded in C++, you can look at the free online C++ tutorials at http://www.cplusplus.com/doc/tutorial/.

We don't assume that you have any knowledge of OpenGL—that is what this book is going to give you. We start by explaining the basic concepts of OpenGL and move through more advanced concepts by example. As you learn, you will also code, providing you with the opportunity to put what you have learned into practice. This book won't make you an OpenGL expert overnight, but it will give you the foundation to understand and use OpenGL. At the end of this book, we will give you some pointers to other resources that will allow you to learn even more about OpenGL.

We also don't assume that you have any experience developing games. This book is rather unique in that it provides you with a primer to learn OpenGL and a primer to learn game development. There are many books out there that teach OpenGL, but most do so within a more academic or theoretical framework. We felt that it was better to teach you OpenGL while you were using it to create an actual game. Actually, you will code two games: one in 2D, and one in 3D. Two for the price of one!

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Building the Foundation

Building a game is like building a house. Except this is a crazy house with rooms sticking out everywhere, and at any time someone might decide to add another room just here, and remove a room over there. You had better have a good foundation!

This chapter will take you through the process of setting up the foundation to build your game. You will learn, how to set up a development environment using Visual Studio. Next, you will set up the game loop, which is the foundation for every game ever created. Finally, you will set up the development environment to use OpenGL as your rendering engine.

Introducing the development environment

The development environment is the set of tools that you use to edit, compile, and run your program. There are many development tools out there; some tools are glorified text editors, while others are entire suites of tools that are integrated into a single application. These more advanced suites are known as Integrated Development Environments (IDEs).

Microsoft's Visual Studio is by far the most widely used IDE, and the good news is that you can obtain and use it for free. Go to https://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx and follow the links to download the latest version of Visual Studio Community, previously known as Visual Studio Express. Visual Studio Community is not a trial version and will not expire. You will probably see trial versions of Visual Studio being offered, so make sure you download the free version of Visual Studio Community.

Visual Studio offers several languages to program in. We will be using C++ throughout this book. When you first use Visual Studio, you may be asked which language you want to set up the development environment for. I recommend that you choose the C++ settings. However, you will still be able to use Visual Studio for C++ even if you choose a different default programming language.

Visual Studio Community 2013 was the current version at the time this book was written. All of the screenshots you see in the book are from that version. It is quite likely that a later version of Visual Studio will have come out by the time you get your hands on this book. The general functionality stays the same from one version to another, so this should not be a problem. If you are using a different version of Visual Studio, then the exact location of some commands may not be the same as in the screenshots in this book.

Tip

Microsoft differentiates between programs written for Windows Desktop and those written for Windows Universal. Ensure that you download Visual Studio Community Express for Desktop.

When you first start Visual Studio, you will be asked for a few options, so I thought I'd cover them here:

If you are asked which programming language you would like to set up as your default development environment, it really doesn't matter which language you choose. If you think you will be using C++ a lot, then pick C++. If you pick another language as your default you will still be able to code in C++.You will be asked to sign into your Microsoft account. If you have ever used MSN, Hotmail, or Windows Messenger, then you already have a Microsoft account. At any rate, if you don't have a Microsoft account you can use your own e-mail address to create one, and it doesn't cost anything.You may be asked to set up a developer license for Windows. Just click I Agree and it will be done. Again, no charge!

A quick look at Visual Studio

As Visual Studio can do so many things, it may be a bit intimidating the first time you use it. I have been using Visual Studio for over 20 years and there are still parts of it that I have never needed! Let's take a look at the key components, in the following screenshot, that you will use every day:

Start screen

The start screen, as shown in the preceding screenshot, allows you to quickly start a new project or open an existing project. The most recent projects that you have worked with can be quickly accessed from the list of recent projects.

The Solution Explorer panel

The Solution Explorer panel allows you to navigate and work with all of the code and other resources in your project. If you do not see the Solution Explorer window on your screen, click View | Solution Explorer.

From this window you can:

Double-click on any item to open itRight-click to add existing items to the projectRight-click to add new items to the projectCreate folders to organize your code

The Standard Toolbar panel

The Standard Toolbarpanel contains buttons for the most common tasks:

Save the current fileSave all modified filesUndo and RedoRun the program

Tip

There are basically two ways to run your program. You can run the program with or without debugging. Debugging mode allows you to set checkpoints that stop the program and let you view the state of variables, and perform other operations while the code is running. If you run the program without debugging, you will not be able to do these things.

The code window

The center of the IDE is dominated by the code window. This is where you type and edit your code. You can have several code windows open at once. Each code window will add a tab across the top, allowing you to switch from one piece of code to another with a single click:

You will notice that the text is color-coded. This allows you to easily see different types of code. For example, the comments in the code in the preceding screenshot are in green, while the C++ objects are in blue. You can also zoom in and out of the code by holding down the Ctrl button and using the scroll wheel on the mouse.

The output window

The output window is typically at the bottom of the IDE. This window is where you will look at to see the status of the current run, and where you will find errors when you try to compile run your program.

If you see an error in the output window, you can usually double-click on it, and Visual Studio will take you to the line in code that caused the error:

Starting your project

It's time to stop reading and start doing! We are going to use Visual Studio to start our game project.

Open Visual Studio and click the New Project link in the start window.Navigate to the left-hand side panel and select Win32 under the Visual C++ branch of Templates.Select Win32 Project in the center area.Give the project a name. The first game we will be working on is a 2D robot racing game that we'll call RoboRacer2D.Choose a folder location to store the project, or just leave the default location.The solution name is almost always the same as the project name, so leave that as it is.Leave Create directory for solution checked.Click OK.On the next screen click Finish.

We need to tell Visual Studio how to work with Unicode characters. Right-click on the project name in the Solution Explorer panel and choose Properties. Then select General. Change the Character Set property to Not Set.

Congratulations! You have now created your Windows application and set up your development environment. It's time to move on to creating the framework for your game.

Introducing OpenGL

We have spent a lot of time so far talking about game loops and Visual Studio. We are finally going to discuss the main topic of this book: OpenGL!

What is OpenGL?

OpenGL makes it possible to render sophisticated 2D and 3D graphics on your computer screen. In fact, OpenGL is also the technology behind most mobile devices and tablet devices.

OpenGL works in conjunction with your device's graphics device to draw graphics on the screen. Most modern computing devices have two processors: the Central Processing Unit (CPU) and theGraphics Processing Unit (GPU).

Drawing modern 2D and 3D graphics is a very processor intensive task. In order to free the computer's main processor (the CPU) to do its job, the GPU takes on the task of rendering to the screen. OpenGL is a language that tells the GPU what to do and how to do it.

Tip

Technically, OpenGL is an API, or application programming interface. Another way to understand this is that OpenGL is a library of code that you can access once you have included the proper headers in your code. There are different versions of OpenGL. This book uses OpenGL 1.1. Although this is the very first version of OpenGL, it is included in all versions of Windows and provides the building blocks for all future versions.

The other GL

By the way, you have probably heard of the "other" graphics engine—Microsoft's DirectX. Similar to OpenGL, DirectX allows programmers to talk to the GPU. A lot of people want to know the differences between OpenGL and DirectX, and which is the best choice.

Although there are certainly going to be fans and defenders of both technologies, the only real difference between DirectX and OpenGL is the specific way that you code them. Both technologies are about the same when it comes to features and abilities.

There is one advantage that OpenGL has over DirectX. DirectX only works on Microsoft technologies, while OpenGL works on Microsoft technologies and many others, including most modern cell phones, and the Apple Mac line of computers.

Downloading OpenGL

I remember when I was first learning OpenGL. I searched in vain, looking for the link to download the OpenGL SDK. It turns out that you don't have to download the OpenGL SDK because it is already installed when you install Visual Studio.

You do want to make sure that you have the latest OpenGL driver for your video card. To do that, go to http://www.opengl.org/wiki/Getting_started#Downloading_OpenGL and follow the appropriate link.

Adding OpenGL to the project

In order to use OpenGL in our program, we will need to add some code. Open the RoboRacer2D project that we have been working on, and let's do this!

Linking to the OpenGL library

Everything that you need to use OpenGL is found in the OpenGL32.dll lib file. It's up to you to tell Visual Studio that you want to use the OpenGL library in your project.

Right-click on Project | RoboRacer2D properties.

Tip

By the way, Visual Studio first creates a solution, and then puts a project in the solution. The solution is the top entry in the Solution Explorer hierarchy, and the project is the first child. In this case, make sure you right-click on the project, not the solution.

For the Configuration drop-down box, make sure you select All Configurations.Open the Configuration Properties branch, then the Linker branch.Select theInput option.Click the dropdown for Additional Dependencies and choose <Edit…>.Enter OpenGL32.lib into the dialog window and click OK.Close the Property Pages window.

Even if you are writing a 64 bit application, you will use the OpenGL 32 bit library.

Next, we need to tell Visual Studio that you want to include the OpenGL headers in your program. If you take a look at the top of your code, you will see several headers already being loaded:

#include "stdafx.h" #include "RoboRacer2D.h"

Just below these lines, add the following:

#include <Windows.h> #include <gl\GL.h> #include <gl\GLU.h>

Tip

GL.h is the main header for the OpenGL library. GLU.h stands for GL Utility and is an additional library of features that make OpenGL a little easier to use. These headers correspond to the OpenGL32.lib and Glu32.lib libraries that we added to the project.

Congratulations! You have set up the development environment to use OpenGL and you are now ready to program your first game.

Summary

We covered a lot of ground in this chapter. We learned how to set up your development environment by downloading and installing Visual Studio. Next, we created a C++ Windows Desktop application.