Game Programming Patterns Game Loop

Slides:



Advertisements
Similar presentations
Chapter 6 Writing a Program
Advertisements

Computer Organization. The Nature of Data Spreadsheets give us a way to create processes that manipulate data We can think of a piece of data as a quantity.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Introduction to Programming using Matlab Session 2 P DuffourJan 2008.
Getting started with LEGO NXT Mindstorms software This is intended to be a short introduction to the LEGO Mindstorms software and programming the LEGO.
Repetition everywhere – comparing while in a method and as an event Susan Rodger Duke University July 2010 modified July 2011.
Grade 6 Hopewell Elementary You will read each slide, then try to think of the answer. When you think you know the answer, click ONCE on the mouse.
Microsoft® Small Basic
MA 1128: Lecture 06 – 2/15/11 Graphs Functions.
Sprites, User Input, and Collision COSC 315 Fall 2014 Bridget M. Blodgett.
Announcements You survived midterm 2! No Class / No Office hours Friday.
IS660Z Programming Games Using Visual Basic Overview of Cannonball.
Slide 2-1 Copyright © 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 2 Using the Operating System 2.
CS0007: Introduction to Computer Programming Console Output, Variables, Literals, and Introduction to Type.
Cosc 5/4730 Game Design. A short game design primer. A game or animation is built on an animation loop. – Instance variables of “objects” are updated.
1 Computer Graphics Chapter 2 Input Devices. RM[2]-2 Input Devices Logical Input Devices  Categorized based on functional characteristics.  Each device.
How do games work? Game Workshop July 4, Parts Sprites/pictures Map/background Music/sounds Player character Enemies Objects.
Cosc 5/4730 Game Design. A short game design primer. A game or animation is built on an animation loop. – Instance variables of “objects” are updated.
Wednesday, 9/4/02, Slide #1 1 CS 106 Intro to CS 1 Wednesday, 9/4/02  Today: Introduction, course information, and basic ideas of computers and programming.
Latency Compensating Methods in Client/Server In-game Protocol Design and Optimization I’m Curtis.
UC Berkeley 1 Time dilation in RAMP Zhangxi Tan and David Patterson Computer Science Division UC Berkeley.
CS320n –Visual Programming Interactive Programs Mike Scott (Slides 5-1)
Games Development Practices Semester 2 Overview CO2301 Games Development 1 Week 14.
AGD: 5. Game Arch.1 Objective o to discuss some of the main game architecture elements, rendering, and the game loop Animation and Games Development.
SE320: Introduction to Computer Games Week 8: Game Programming Gazihan Alankus.
Software design and development Marcus Hunt. Application and limits of procedural programming Procedural programming is a powerful language, typically.
PacMan by Midway, released 1980 CSE 380 – Computer Game Programming Real-Time Game Architecture.
CS 0004 –Lecture 1 Wednesday, Jan 5 th, 2011 Roxana Gheorghiu.
Input & Output: Console
.:::The EA FEAR Division Presents:. When you download FEAR you should be able to load it pretty quickly, so if it’s taking long consider the problems.
Introduction to Networked Graphics Part 3 of 5: Latency.
Event Driven Programming
Lecture 5: Interaction 1  Principles of Interactive Graphics  CMSCD2012  Dr David England, Room 711,  ex 2271 
Introduction to Arrays. definitions and things to consider… This presentation is designed to give a simple demonstration of array and object visualizations.
Moving Around in Scratch The Basics… -You do want to have Scratch open as you will be creating a program. -Follow the instructions and if you have questions.
4.1 Advanced Operating Systems Desktop Scheduling You are running some long simulations. In the mean time, why not watch an illegally downloaded Simpsons.
Programming Video Games
2.1. T HE G AME L OOP Central game update and render processes.
Game Programming Patterns Event Queue From the book by Robert Nystrom
Flash Another Look 21-Nov-15 Computing Engineering and Technology 1 Flash.
Reference: The Game Loop Animation / Game loop 1. Update variables 2. [Get input from the user] (GameLoop only) 3. Draw (using variables)
I Power Higher Computing Software Development Development Languages and Environments.
What is Programming? Computer programming is about telling the computer what it is we want it to do We tell the computer what we want it to do by sending.
Basic Systems and Software. Were we left off Computers are programmable (formal) machines. Digital information is stored as a series of two states (1.
11 General Game Programming Approach. The program is event-driven The program is event-driven –Messages = events –So as all windows system (for example.
An operating system is the software that makes everything in the computer work together smoothly and efficiently. What is an Operating System?
Game Programming Patterns Game Loop From the book by Robert Nystrom
Microprocessor and Interfacing Example: Writing a Game Need to Check Keyboard Input.
Lesson 2: Reading a program. Remember: from yesterday We learned about… Precise language is needed to program Actors and Classes Methods – step by step.
UW EXTENSION CERTIFICATE PROGRAM IN GAME DEVELOPMENT 2 ND QUARTER: ADVANCED GRAPHICS Game program main loop.
High Level Architecture Time Management. Time management is a difficult subject There is no real time management in DIS (usually); things happen as packets.
Introduction to Game Programming Pertemuan 11 Matakuliah: T0944-Game Design and Programming Tahun: 2010.
CRE Programming Club Class 8 Robert Eckstein and Robert Heard.
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
T HE G AME L OOP. A simple model How simply could we model a computer game? By separating the game in two parts: – the data inside the computer, and –
5 Event Handling Interactive Programming Suggested Reading Interaction: Events and Event Handling, Supplemental Text for CPSC 203 Distributed this term.
Introduction to: Python and OpenSesame FOR PROS. OpenSesame In OpenSesame you can add Python in-line codes which enables complex experiment. We will go.
Systems and User Interface Software. Types of Operating System  Single User  Multi User  Multi-tasking  Batch Processing  Interactive  Real Time.
Speedway Schools. A computer has many parts that make it work. Some of those parts we can see. Others are hidden inside where we can't see them. In this.
(More) Event handling. Input and Windowed-OS’s Windowed OS’s (Windows, OSX, GUI-linux’s) send messages (events) when the user does something “on” the.
Linear Motion. Speed & Velocity Acceleration Free Fall: Fast Free Fall: Far Graphs & Air Resistance.
Computer Control and Monitoring Today we will look at: What we mean by computer control Examples of computer control Sensors – analogue and digital Sampling.
Game Maker Tutorials Introduction Clickball IntroductionClickball Where is it? Shooting Where is it?Shooting.
Reference: What is it? A multimedia python library – Window Management – Graphics geometric shapes bitmaps (sprites) – Input Mouse Keyboard.
Information Technology (IT). Information Technology – technology used to create, store, exchange, and use information in its various forms (business data,
Game Loops + Part II Reference:
Frame Update, Level Representation & Graphics
Game Loop Update & Draw.
Year 10 Computer Science Hardware - CPU and RAM.
Presentation transcript:

Game Programming Patterns Game Loop From the book by Robert Nystrom http://gameprogrammingpatterns.com

A simple main loop for an interactive program: while (true) { char* command = readCommand(); // read text from keyboard handleCommand(command); }

A modern event-driven program such as your word processor is similar: while (true) { Event* event = waitForEvent(); dispatchEvent(event); } Events could be key presses, mouse clicks, system shutdown, window minimization, timer firing, or many other notifications.

We don’t want the game to run too fast or too slow. A game keeps moving even when the user isn’t providing input. This is the first, key part of a real game loop: it processes user input, but doesn’t wait for it. while (true) { processInput(); // doesn’t wait update(); // advances game simulation one step render(); // draws a frame on the screen } We want this to run at a fixed number of frames per second, no matter how many objects exist, no matter how complex the physics, and no matter what fast the CPU is. We don’t want the game to run too fast or too slow.

A simple fix: wait. If we want 60 FPS, then we have 16 milliseconds per frame. while (true) { double start = getCurrentTime(); processInput(); update(); render(); sleep(start + MS_PER_FRAME - getCurrentTime()); }

A simple fix: wait. If we want 60 FPS, then we have 16 milliseconds per frame. while (true) { double start = getCurrentTime(); processInput(); update(); render(); sleep(start + MS_PER_FRAME - getCurrentTime()); } Sleep() makes sure the game doesn’t run too fast. But it doesn’t help if the game runs too slowly.

Let’s try something a bit more sophisticated Let’s try something a bit more sophisticated. The problem we have basically boils down to: Each update advances game time by a certain amount. It takes a certain amount of real time to process that. If step two takes longer than step one, the game slows down. But if we can advance the game by more than 16ms of game time in a single step, then we can update the game less frequently and still keep up.

Choose a time step to advance based on how much real time passed since the last frame. double lastTime = getCurrentTime(); while (true) { double current = getCurrentTime(); double elapsed = current - lastTime; processInput(); update(elapsed); // here is the magic render(); lastTime = current; } Say you’ve got a bullet shooting across the screen. With a fixed time step, in each frame, you’ll move it according to its velocity. With a variable time step, you scale that velocity by the elapsed time.

The game plays at a consistent rate on different hardware. Looks good: The game plays at a consistent rate on different hardware. Players with faster machines are rewarded with smoother gameplay. But, alas, there’s a serious problem lurking ahead: we’ve made the game non-deterministic and unstable. Consider a two-player networked game, where one computer runs at 100 FPS and one runs at 50 FPS. A bullet travels across each screen for one second, at 100 meters (in game space) per second. Computer one: 100 meters/second * (100 * .01 seconds) = 100.00000007 Computer two: 100 meters/second * (50 * .02 seconds) = 100.00000004 Floating point rounding error! Also, many physics engines don’t handle changing time steps. To demo, in Javascript console: for (var i=0; i<50; i++) tot += 0.02

Better idea: fixed time steps and flexibility as to when we render: double previous = getCurrentTime(); double lag = 0.0; while (true) { double current = getCurrentTime(); double elapsed = current - previous; previous = current; lag += elapsed; processInput(); while (lag >= MS_PER_UPDATE) // not MS_PER_FRAME update(); // our old friend fixed update lag -= MS_PER_UPDATE; } render();

One issue is left, “residual lag” One issue is left, “residual lag”. Update happens at a fixed interval, but rendering is less frequent than updating, and not as steady. Potentially, motion looks jagged or stuttery. Conveniently, we actually know exactly how far between update frames we are when we render: it’s stored in lag. We bail out of the update loop when it’s less than the update time step, not when it’s zero. That leftover amount? That’s how far into the next frame we are. When we go to render, we’ll pass that in: render(lag / MS_PER_UPDATE);

Some additional thoughts. Who owns the game loop – the engine/platform or the game programmer? Is power consumption important? In particular, with mobile devices you might sacrifice some frame rate and “sleep” between frames. There are some trade-offs between more complex coding and greater adaptability to a range of CPU speeds.

Unity’s Mono Engine:

What about SDL? In Windows, the entry point is WinMain(), not main(). But didn’t you write a main() in your SDL programs??!! #include <iostream> #include <SDL.h> int main(int argc, char **argv) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; return 1; } SDL_Quit(); return 0;

From C:\...\SDL\src\main\windows\SDL_windows_main.c /* This is where execution begins [windowed apps] */ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw) { char **argv; int argc; char *cmdline; /* Grab the command line */ TCHAR *text = GetCommandLine(); cmdline = SDL_strdup(text); if (cmdline == NULL) { return OutOfMemory(); } /* Parse it into argv and argc */ argc = ParseCommandLine(cmdline, NULL); ParseCommandLine(cmdline, argv); /* Run the main program */ console_main(argc, argv); SDL_stack_free(argv); SDL_free(cmdline); return 0;

Also from C:\...\SDL\src\main\windows\SDL_windows_main.c /* This is where execution begins [console apps] */ int console_main(int argc, char *argv[]) { int status; SDL_SetMainReady(); /* Run the application main() code */ status = SDL_main(argc, argv); /* Exit cleanly, calling atexit() functions */ exit(status); /* Hush little compiler, don't you cry... */ return 0; } And in SDL_main.h (which is included by SDL.h) #define main SDL_main extern C_LINKAGE int SDL_main(int argc, char *argv[]);