Learning Windows 8 Game Development - Michael Quandt - E-Book

Learning Windows 8 Game Development E-Book

Michael Quandt

0,0
39,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

With the recent success of a lot of smaller games, game development is quickly becoming a great field to get in to. Mobile and PC games are on the rise, and having a way to create a game for all types of devices without rewriting everything is a huge benefit for the new Windows 8 operating system. In this book, you will learn how to use cutting-edge technologies like DirectX and tools that will make creating a game easy. This book also allows you to make money by selling your games to the world.

Learning Windows 8 Game Development teaches you how to create exciting games for tablets and PC on the Windows 8 platform. Make a game, learn the techniques, and use them to make the games you want to play. Learn about graphics, multiplayer options, how to use the Proximity + Socket APIs to add local multiplayer, how to sell the game outright, and In-App Purchases.

Learning Windows 8 Game Development guides you from the start of your journey all the way to developing games for Windows by showing you how to develop a game from scratch and sell it in the store.With Learning Windows 8 Game Development, you will learn how to write the code required to set everything up, get some graphics on screen, and then jump into the fun part of adding gameplay to turn a graphics sample into a proper game. From there, you'll look at how to add awesome features to your game like networking, motion controls, and even take advantage of new Windows 8 features like live tiles and sharing to make your players want to challenge their friends and keep playing.

This book wraps up by covering the only way a good game can finish development: by shipping the game on the Windows Store. You'll look at the things to remember to make certification painless and some great tips on how to market and sell your game to the public.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 337

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

Learning Windows 8 Game Development
Credits
About the Author
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
NuGet and DirectXTK
MSDN
Languages and other resources
WinRT
Components
Threading
C++ Component Extensions
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Getting Started with Direct3D
Setting up the stage
Applications and windows
Structuring each frame
Initializing the Direct3D API
Graphics device
Device context
Swap chain
Render target, depth stencil, and viewport
Down the graphics pipeline
Understanding the game loop
Updating the simulation
Drawing the world
Clearing the screen
Presenting the back buffer
Summary
2. Drawing 2D Sprites
Installing DirectXTK
What a sprite is
Textures
File formats
Loading
Co-ordinate systems
Drawing the sprites
Sorting modes
Finishing the batch
Vectors
Text rendering
TTF versus BMP
Building the font
Drawing the font
Summary
3. Adding the Input
Input devices
Pointers
Keyboard input
GamePad input
Multiple controllers
Buttons
Deadzones and thumbsticks
Summary
4. Adding the Play in the Gameplay
Structuring a game
Traditional object-oriented design
Components and entities
Putting it all together
Subsystems
Refining the input system
Trigger
Action
InputManager
Triggers
Renderer
Resource management
Culling
Implementation
Collision detection
Rectangle collision
Fighting for score
Summary
5. Tilting the World
Orientation
Accelerometer
Shaking things up a bit
Spinning with gyros
Compass
Inclinometer
Orientation for games
Practice makes perfect
Other sensors
Light
Locking on with a GPS
Status
Position
Polling
Summary
6. Bragging Rights
Game state and progression
Sharing in Windows 8
WinRT components
Live tiles
Summary
7. Playing Games with Friends
A better menu system
Networking
Choosing between client/server and peer-to-peer models
The client/server model
The peer-to-peer model
Maybe a hybrid?
The first stage
Using the PeerFinder
Communicating the gameplay
TCP – StreamSocket
UDP – DatagramSocket
Reading and writing data
Side note – Async
The DataReader
The DataWriter
Summary
8. Getting into the Store
Getting into the store
Free accounts
Submitting your game
GDF Certificates
App packages
Capabilities
Adding a privacy policy
Declarations
Certification kit
Creating your app packages
Uploading and submitting
Certification tips
Privacy
Features
Legacy APIs
Debug
WACK
Summary
9. Monetization
Selling your games
Monetization models
The freemium model
The traditional model
The hybrid model
The trial mode
In-app purchases
The consumables
Testing with the simulator
Summary
A. Adding the Third Dimension
Vertices and triangles
Indices
Cameras
DirectXMath
Buffers
Building the vertex and index buffers
Setting the buffers
Using the buffers
Constant buffers
Updating the buffers
Mapping the buffer
The UpdateSubresource() method
Shaders
Vertex shaders
Pixel shaders
Compiling and loading
Input layouts
Drawing the model
Setting the buffers and drawing
Summary
Index

Learning Windows 8 Game Development

Learning Windows 8 Game Development

Copyright © 2013 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 author, 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: October 2013

Production Reference: 1181013

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-84969-744-6

www.packtpub.com

Cover Image by Suresh Mogre (<[email protected]>)

Credits

Author

Michael Quandt

Reviewers

Anthony E. Alvarez

Laurent Couvidou

Hexuan

Andrei Marukovich

Mark Sinnathamby

Acquisition Editor

Antony Lowe

Lead Technical Editor

Chalini Snega Victor

Technical Editors

Vrinda Nitesh Bhosale

Ritika Singh

Project Coordinator

Kranti Berde

Proofreaders

Lawrence A. Herman

Christopher Smith

Indexer

Monica Ajmera Mehta

Graphics

Ronak Dhruv

Yuvraj Mannari

Production Coordinator

Prachali Bhiwandkar

Cover Work

Prachali Bhiwandkar

About the Author

Michael Quandt has been working with games, from XNA to DirectX to Unity, as a hobbyist and professional for four years. He has spoken at local game development conferences and workshops while working with Microsoft Australia as a Technical Evangelist. Since then he has contributed to the translation of multiple major franchise games to the Windows Store platform, and continues to work with local developers and students to get them involved in game development and bringing their best to the Windows platform.

About the Reviewers

Anthony E. Alvarez is a native New Yorker. His hobbies include photography, singing, and cooking. He is a food activist and a political atheist. He loves the great outdoors and travelling.

Anthony has held positions such as Software Engineer, Webmaster, Unix Administrator, Customer Service Representative, Marketing Systems Manager, and Salesforce.com Database Administrator. He speaks three foreign languages: Chinese, Japanese, and Spanish.

After returning from a study abroad scholarship in Guangzhou, China, Anthony changed his major to Asian Studies. While attending university, he worked at IBM for three semesters where he developed presentation materials for field sales teams. After graduating CCNY with a Bachelors degree in Arts (BA), Anthony was hired as a computer consultant by a Japanese Architecture company. His clients included Tokyo Electric Power Company (TEPCO), IBM Japan, Taisei Construction, Nippon Telephone and Telegraph (NTT), Budweiser Japan, and Polaroid Japan.

After working three years in Tokyo, Anthony returned to the USA and settled in the Boston Metro area. He was employee number 3 of a startup company specializing in e-commerce projects. Anthony taught adult education courses on e-commerce.

Four years later, Anthony moved to Atlanta to become the first webmaster at Panasonic Wireless Research and Design Center (PMCDU). The company was designing a flagship smart phone for the American market.

Moving to New Jersey, he held the position of a web marketing manager at Casio America, Inc.

Currently a director at Pucho Web Solutions, Anthony specializes in marketing and e-commerce projects using Open Source Software. In order to manage business development issues at the firm, Anthony has completed Entrepreneurship training from Workshop in Business Opportunities (WIBO.org) and Kauffman FastTrac (Kauffman.org). Anthony is a Free Culture advocate using open source methods and tools. He is a volunteer copy editor for the Wikipedia project, an online encyclopedia.

One of his specialties at Pucho Web Solutions is video. He is a producer of both web and broadcast TV video. His programs have been broadcasted on stations in Manhattan, Brooklyn, Staten Island, and Queens Cable TV.

In the performing arts, Anthony has appeared on TV shows that are shot on location in New York City including White Collar, Law & Order, Nurse Jackie, Gossip Girl, Blue Bloods, and Girls.

For films, Anthony has played a role as a diplomat in Junji Sakamoto's upcoming financial thriller Human Trust (Jinrui Shikin), which is scheduled to debut in Japan on October 19, 2013. Human Trust, directed by Junji Sakamoto, is a story of an international financial conspiracy seeking to right the unfairness of the world, shot on location at United Nations (UN) General Assembly hall.

Follow Anthony at his blog: http://www.AnthonyAlvarez.us.

Pucho Web Solutions (http://www.PuchoWebsolutions.com) provides web marketing solutions to small businesses in Manhattan by showcasing multimedia-based content on your website using video, web photo albums, and audio. Pucho Web Solutions marketing services help you tell your story, engage your audience, and increase web traffic at your site.

Laurent Couvidou is a professional game developer with experiences at 10tacle Studios, Ubisoft Montpellier, and TriOviz, among others. Besides these daily jobs, he also participated in several amateur game jams.

Hexuan fell in love with video game programming in high school. After graduation, he worked in listed companies working on Android, iOS game development. He participated in cocos2dx for a Win8 open source project and has many years of game programming experience.

Hexuan loves technology, is curious about new technologies, and believes that technology makes human life better.

Thanks to my family. I love you.

Andrei Marukovich is a technical lead at AB SCIEX and Microsoft C# MVP. Andrei has been developing software professionally for over 15 years. During this time he has designed and developed applications in such diverse areas as life science, semiconductor device manufacturing, robotics, and game development. Andrei can be found online at http://lunarfrog.com. He lives in Toronto with his beautiful wife and daughter.

Mark Sinnathamby is a software engineer and .NET consultant, living and working in Singapore. He has developed many diverse types of software-intensive systems, and worked in a variety of technological domains. In his spare time, he loves to study game design and development, initially starting with OpenGL, and now experimenting and working with Microsoft DirectX technology.

www.PacktPub.com

Support files, eBooks, discount offers and more

You might want to visit www.PacktPub.com for support files and downloads related to your book.

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.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across 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 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 nine entirely free books. Simply use your login credentials for immediate access.

Preface

With the rising popularity of mobile platforms such as phones and tablets, the games industry has found a new market eager for more and more games. With the introduction of Windows 8, Microsoft has entered this market, bringing years of experience and widely-used game development technologies such as Direct3D. In this book, we will take a look at how you can get started making a game for Windows 8, so you can sell to both the desktop and tablet markets. Through this book you'll learn how to develop a simple side-scrolling space shooter, and enhance the game with Windows 8 features such as Share Charm integration and Live Tiles.

What this book covers

Chapter 1, Getting Started with Direct3D, looks at how we can initialize Direct3D in Windows 8 and prepare all of the resources to display something on the screen.

Chapter 2, Drawing 2D Sprites, is where we will take our first steps into drawing images on the screen. You'll learn about the different concepts involved in drawing 2D images, as well as some useful libraries to make 2D rendering even easier.

Chapter 3, Adding the Input, will teach you how to read from the touch screen, keyboard, mouse, and GamePad to implement the interactive element of your game.

Chapter 4, Adding the Play in the Gameplay, will show you how to structure your game and add the mechanics that make the game fun. We'll look at code structure and the subsystems you will need to complete the game.

Chapter 5, Tilting the World, is an introduction to the sensors on the device that will enable new gameplay genres and opportunities. You will learn about the different options available and how to easily work with them to get different types of input.

Chapter 6, Bragging Rights, will look at the Share Charm and Live Tiles in Windows 8. Here you will learn how to take advantage of these features to quickly add support for social media, and keep your players engaged outside of the game.

Chapter 7, Playing Games with Friends, looks at the networking options available in Windows 8, as well as how to add a user interface system to support this.

Chapter 8, Getting into the Store, will lift the lid on the Windows Store submission and certification process. We'll look at the important things to remember, as well as some tips and tricks to make certification painless.

Chapter 9, Monetization, investigates the different options and methods you can use to make some money from your game.

Appendix, Adding the Third Dimension, will give a light introduction to the next step in game development: 3D. You will learn the basic concepts involved so you know where to start when you want to add in another dimension to your game.

What you need for this book

You only need two pieces of software to get started with this book:

Windows 8Visual Studio 2012 (or higher)

Visual Studio 2012 is Microsoft's development environment, and is used for all forms of Windows development, from desktop to store. There are a few editions of Visual Studio with different prices; however, a free version, named Visual Studio 2012 Express Edition, can be downloaded from:

http://www.microsoft.com/visualstudio/eng/downloads#express-win8

If you have access to higher editions of Visual Studio 2012, you can use those as well, and most functions should be in the same place.

Note

This book has been written for Visual Studio 2012 and is correct at the time of writing. Future versions of Visual Studio as well as Windows 8 may be different.

NuGet and DirectXTK

NuGet is a development package manager. If you've used package managers in POSIX environments, you'll recognise the concept, only here it's for third-party libraries. NuGet officially supports C# and C++, and will quickly become an essential tool in your Windows development toolbox.

NuGet is integrated into all versions of Visual Studio from 2012 onwards, and adding a "package" to your project is as easy as right-clicking on your project in the Solution Explorer and selecting Manage NuGet Packages. From there you can search for packages and easily install them to your project with a single click. Any dependencies will be automatically installed, and if required your project will be configured to support the new library.

MSDN

The final resource that you might want to have access to is MSDN (www.msdn.com). MSDN (Microsoft Developer Network) is the one-stop shop for documentation on all Microsoft technology. This book will contain links to MSDN pages with documentation with for further reading. If you have any questions or need to know the details on an API, make this your first stop.

Languages and other resources

Although most of the book will be developed using standard C++11, some parts will require the use of the new C++ Component Extensions (C++/CX) from Microsoft. Alongside that we will avoid going into detail about the new WinRT platform outside of the APIs you need to develop your game, so if you want to learn more about these technologies, read through the quick summary that follows, and take a look at the provided reference links for further reading.

WinRT

WinRT is the new API layer used by Windows Store applications to replace Win32. This new API provides a cleaner and easier way to work with the operating system, and also enables cross-language library development using WinRT Components.

Note

When developing a Windows Store application, you do not need to include any headers; they are all automatically included during compile tile to save you the trouble.

For a detailed look at the WinRT type system and how it works, visit:

http://blogs.microsoft.co.il/blogs/sasha/archive/2011/09/17/under-the-covers-of-winrt-using-c.aspx

Components

WinRT Components allow you to share code between the three Windows Store languages: C++, C#, and JavaScript. All public code in a component must use the ref class from C++/CX. This is because the component needs to ensure it can communicate with the other languages, which do not support pointers and other C++ specific concepts. If you want to use plain C++ within the component, you need to specify the visibility as internal.

We will look at creating a WinRT component later in the book. However, for more information, visit:

http://msdn.microsoft.com/en-us/library/windows/apps/hh441569

Threading

WinRT uses a new threading model based on the concept of asynchronous development using futures and continuations. This means that instead of creating background code in a traditional manner, you can specify code to run asynchronously, and then append the code that "continues" after the original code finishes. This is done using Tasks, which represent code that runs asynchronously, and at some point in the future may return an object (or value).

For more information on the threading and async model used in WinRT, visit:

http://msdn.microsoft.com/en-us/magazine/hh781020.aspx

C++ Component Extensions

C++ Component Extensions are a set of keywords that Microsoft has added to C++ to make it easier to work with WinRT and COM. These extensions simply enhance the language. They are required for the WinRT APIs, but can be avoided everywhere else if desired.

For more information on C++/CX, including a language reference, visit:

http://msdn.microsoft.com/en-us/library/windows/apps/hh699871

Who this book is for

This book is intended for developers who already have a good grasp of C++ development. You should know the basic programming concepts such as object-oriented programming. Knowledge of older Windows technologies such as Component Object Model (COM) will be useful but is not required.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "To compile this you'll also need to ensure that any #include statements that previously pointed to CubeRenderer.h now point to Game.h."

A block of code is set as follows:

#pragma once #include "Direct3DBase.h" ref class Game sealed : public Direct3DBase { public: Game(); virtual void Render() override; void Update(float totalTime, float deltaTime); };

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: " You can find this project in the same window by navigating to New Project | Templates | Visual C++ | Windows Store".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

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

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via 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 on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt Publishing 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 for all Packt Publishing books you have purchased from your account at http://www.packtpub.com. 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 would 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 erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt Publishing, 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

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Getting Started with Direct3D

They say the first steps are the hardest, and beginning a new game is no exception. Therefore, we should use as much help as possible to make those first steps easier, and get into the fun parts of game development. To support the new WinRT platform, we need some new templates, and there are plenty to be had in Visual Studio 2012. Most important to us is the Direct3D App template, which provides the base code for a C++ Windows Store application, without any of the XAML that the other templates include.

The template that we've chosen will provide us with the code to create a WinRT window, as well as the code for the Direct3D components that will allow us to create the game world. This chapter will focus on explaining the code included so that you understand how it all works, as well as the changes needed to prepare the project for our own code.

In this chapter we will cover the following topics:

Creating the application windowInitialising Direct3DDirect3D devices and contextsRender targets and depth buffersThe graphics pipelineWhat a game loop looks likeClearing and presenting the screen

Setting up the stage

Let's begin by starting up Visual Studio 2012 (the Express Edition is fine) and creating a new Direct3D App project. You can find this project in the same window by navigating to New Project | Templates | Visual C++ | Windows Store. Once Visual Studio has finished creating the project, we need to delete the following files:

CubeRenderer.hCubeRenderer.cppSimpleVertexShader.hlslSimplePixelShader.hlsl

Once these files have been removed, we need to remove any references to the files that we just removed. Now create a new header (Game.h) and code (Game.cpp) file and add the following class declaration and some stub functions into Game.h and Game.cpp, respectively. Once you've done that, search for any references to CubeRenderer and replace them with Game. To compile this you'll also need to ensure that any #include statements that previously pointed to CubeRenderer.h now point to Game.h.

Note

Remember that Microsoft introduced the C++/CX (Component Extensions) to help you write C++ code that works with WinRT. Make sure that you're creating the right type of class.

#pragma once #include "Direct3DBase.h" ref class Game sealed : public Direct3DBase { public: Game(); virtual void Render() override; void Update(float totalTime, float deltaTime); };

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. 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.

Here we have the standard constructor, as well as an overridden Render() function from the Direct3DBase base class. Alongside, we have a new function named Update(), which will be explained in more detail when we cover the game loop later in this chapter.

We add the following stub methods in Game.cpp to allow this to compile:

#include "pch.h" #include "Game.h" Game::Game(void) { } void Game::Render() { } void Game::Update(float totalTime, float deltaTime) { }

Once these are in place you can compile to ensure everything works fine, before we move on to the rest of the basic game structure.

Applications and windows

Windows 8 applications use a different window system compared to the Win32 days. When the application starts, instead of describing a window that needs to be created, you provide an implementation of IFrameworkView that allows your application to respond to events such as resume, suspend, and resize.

When you implement this interface, you also have control over the system used to render to the screen, just as if you had created a Win32 window. In this book we will only use DirectX to create the visuals for the screen; however, Microsoft provides another option that can be used in conjunction with DirectX (or on its own). XAML is the user interface system that provides everything from controls to media to animations. If you want to avoid creating a user interface yourself, this would be your choice. However, because XAML uses DirectX for rendering, some extra steps need to be taken to ensure that the two work together properly. This is beyond the scope of the book, but I strongly recommend you look into taking those extra steps if you want to take advantage of an incredibly powerful user interface system.

The most important methods for us right now are Initialize, SetWindow, and Run, which can all be found in the Chapter1 class (Chapter1.h) if you're following along with the sample code. These three methods are where we will hook up the code for the game. As of now, the template has already included some code referring to the CubeRenderer. To compile the code we need to replace any references to CubeRenderer inside our Chapter1 class with a reference to Game.

Structuring each frame

All games start up, initialize, and run in a loop until it is time to close down and clean up. The big difference that games have over other applications is they will often load, reinitialize, and destroy content multiple times over the life of the process, as the player progresses through different levels or stages of the game.

Another difference lies in the interactive element of games. To create an immersive and responsive experience, games need to iterate through all of the subsystems, processing input and logic before presenting video and audio to the player at a high rate. Each video iteration presented to the player is called a Frame. The performance of games can be drawn from the number of frames that appear on the monitor in a second, which leads to the term Frames Per Second or FPS (not to be confused with First Person Shooter). Modern games need to process an incredible amount of data and repeatedly draw highly detailed objects 30-60 times per second, which means that they need to do all of the work in a short span of time. For modern games that claim to run at 60 FPS, this means that they need to complete all of the processing and rendering in under 1/60th of a second. Some games spread the processing across multiple frames, or make use of multithreading to allow intensive calculations, while still maintaining the desired frame rate. The key thing to ensure here is that the latency from user input to the result appearing on screen is minimized, as this can impact the player experience, depending on the type of game being developed.

The loop that operates at the frame rate of the game is called the game loop. In the days of Win32 games, there was a lot of discussion about the best way to structure the game loop so that the system would have enough time to process the operating system messages. Now that we have shifted from polling operating system messages to an event-based system, we no longer need to worry, and can instead just create a simple while loop to handle everything.

A modern game loop would look like the following:

while the game is running { Update the timer Dispatch Events Update the Game State Draw the Frame Present the Frame to the Screen }

Although we will later look at this loop in detail, there are two items that you might not expect. WinRT provides a method dispatch system that allows for the code to run on specific threads. This is important because now the operating system can generate events from different OS threads and we will only receive them on the main game thread (the one that runs the game loop). If you're using XAML, this becomes even more important as certain actions will crash if they are not run on the UI thread. By providing the dispatcher, we now have an easy way to fire off non-thread safe actions and ensure that they run on the thread we want them to.

The final item you may not have seen before involves presenting the frame to the screen. This will be covered in detail later in the chapter, but briefly, this is where we signal that we are done with drawing and the graphics API can take the final rendered frame and display it on the monitor.