Lecture20 Java Game Programming III – Rate Control, Simple Animation and Display Mode.

Slides:



Advertisements
Similar presentations
More Java Drawing in 2D Animations with Timer. Drawing Review A simple two-dimensional coordinate system exists for each graphics context or drawing surface.
Advertisements

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.
Chapter 101 Cleaning Policy When should a modified page be written out to disk?  Demand cleaning write page out only when its frame has been selected.
1 Chapter 5 Threads 2 Contents  Overview  Benefits  User and Kernel Threads  Multithreading Models  Solaris 2 Threads  Java Threads.
COSC 4126 images - D Goforth Images, Buffering and Animation controlling full screen graphics.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
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.
Tools for Investigating Graphics System Performance
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Memory Management (II)
Graphics Programming. In this class, we will cover: The difference between AWT and Swing Creating a frame Frame positioning Displaying information in.
Lecture18 Java Game Programming I – An Example. Introduction We will look at the following We will look at the following Accelerated Mode GraphicsAccelerated.
Lecture 17: Animation Yoni Fridman 7/27/01 7/27/01.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
Java2D Graphics Summary Images,. Full-Screen Exclusive Mode -Full-screen exclusive mode is a powerful feature of J2SE TM version 1.4 that allows the programmer.
INTRODUCTION TO SCRATCH. About Me Resources Scratch Website Learn Scratch Washington-Lee Computer.
Games and Simulations O-O Programming in Java The Walker School
Chapter 51 Threads Chapter 5. 2 Process Characteristics  Concept of Process has two facets.  A Process is: A Unit of resource ownership:  a virtual.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
XP Tutorial 7 New Perspectives on Microsoft Windows XP 1 Microsoft Windows XP Working with Graphics Tutorial 7.
1 Lecture 4: Threads Operating System Fall Contents Overview: Processes & Threads Benefits of Threads Thread State and Operations User Thread.
Welcome to CIS 083 ! Events CIS 068.
 Refers to sampling the gray/color level in the picture at MXN (M number of rows and N number of columns )array of points.  Once points are sampled,
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
CSE 219 Computer Science III Images. HW1 Has been posted on Blackboard Making a Game of Life with limited options.
Images. The Element To place an image on our web page, we use the self-closing element: The src attribute ("source") is required and supplies the name.
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 7 The Game Loop and Animation Starting Out with Games & Graphics.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Omer Boyaci. Resources  
CE Operating Systems Lecture 11 Windows – Object manager and process management.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Simulated Pointers Limitations Of Java Pointers May be used for internal data structures only. Data structure backup requires serialization and deserialization.
1 Web Based Programming Section 8 James King 12 August 2003.
Games Development 2 Concurrent Programming CO3301 Week 9.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 13 : Swing I King Fahd University of Petroleum & Minerals College of Computer Science.
Programming Video Games
High Performance Java Swing Animation David Wallace Croft Presented to the Plano Java Users Group Plano, TX Copyright 2004 David Wallace Croft.
2.1. T HE G AME L OOP Central game update and render processes.
“The perfect project plan is possible if one first documents a list of all the unknowns.” Bill Langley.
Creating Windows. How can we use Java to create programs that use windows (GUI applications)? How can we use Java to create programs that use windows.
Operating Systems Lecture 14 Segments Adapted from Operating Systems Lecture Notes, Copyright 1997 Martin C. Rinard. Zhiqing Liu School of Software Engineering.
ITCS 3181 Logic and Computer Systems 2015 B. Wilkinson Slides4-2.ppt Modification date: March 23, Procedures Essential ingredient of high level.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
Java Thread and Memory Model
CE Operating Systems Lecture 2 Low level hardware support for operating systems.
Memory management.
CE Operating Systems Lecture 2 Low level hardware support for operating systems.
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 –
GAM666 – Introduction To Game Programming ● DirectDraw, the 2D component of DirectX, uses the term “surface” to mean an area of memory in which pixel data.
Time Management.  Time management is concerned with OS facilities and services which measure real time.  These services include:  Keeping track of.
Java Applets Adding Animation. Import Files You still need to include the same files: –import java.applet.*; –import java.awt.*;
Software Design and Development Storing Data Part 2 Text, sound and video Computing Science.
Memory management The main purpose of a computer system is to execute programs. These programs, together with the data they access, must be in main memory.
Reference: What is it? A multimedia python library – Window Management – Graphics geometric shapes bitmaps (sprites) – Input Mouse Keyboard.
Tutorial 2: Homework 1 and Project 1
2D Graphics Optimizations
Sprites (Images) and Sounds
Graphical Output Basic Images.
Memory Management.
MOM! Phineas and Ferb are … Aims:
Pixels, Colors and Shapes
Computer Graphics Lecture 3 Computer Graphics Hardware
Threads II IS
Learning Objective LO: We’re learning to understand when it is appropriate to use particular data types.
Game Loop Update & Draw.
Threads Chapter 4.
CSE 153 Design of Operating Systems Winter 19
Chapter 13: I/O Systems “The two main jobs of a computer are I/O and [CPU] processing. In many cases, the main job is I/O, and the [CPU] processing is.
Presentation transcript:

Lecture20 Java Game Programming III – Rate Control, Simple Animation and Display Mode

Timing Issues In Java the simplest way to get hold of the time is to use System.currentTimeMillis(). In Java the simplest way to get hold of the time is to use System.currentTimeMillis(). The resolution of this timer is sometimes not good enough to get a consistent frame rate.The resolution of this timer is sometimes not good enough to get a consistent frame rate. Timer resolution, or granularity, is the amount of time that must separate two timer calls so that different values are returned. For instance, what is the value of diff in the code fragment below?Timer resolution, or granularity, is the amount of time that must separate two timer calls so that different values are returned. For instance, what is the value of diff in the code fragment below? long t1 = System.currentTimeMillis(); long t2 = System.currentTimeMillis(); long diff = t2 – t1; // in ms

Timing Issues In Windows 95/98, the resolution is 55ms, which means that repeated calls to currentTimeMillis() will only return different values roughly every 55ms. In Windows 95/98, the resolution is 55ms, which means that repeated calls to currentTimeMillis() will only return different values roughly every 55ms. In the animation loop, the overall effect of poor resolution is to cause the animation to run slower than intended, The elapsed value between iterations will be set to 0 if the game update and rendering time is less than 55ms.In the animation loop, the overall effect of poor resolution is to cause the animation to run slower than intended, The elapsed value between iterations will be set to 0 if the game update and rendering time is less than 55ms. This causes each iteration to sleep longer than necessary.This causes each iteration to sleep longer than necessary. To try to combat this, the minimum iteration period in Game loop should be greater than 55ms, indicating an upper limit of about 18 FPS.To try to combat this, the minimum iteration period in Game loop should be greater than 55ms, indicating an upper limit of about 18 FPS. On Windows 2000, NT, and XP, currentTimeMillis() has a resolution of 10-15ms, making it possible to obtain FPS. On Windows 2000, NT, and XP, currentTimeMillis() has a resolution of 10-15ms, making it possible to obtain FPS. The Mac OS X and Linux have timer resolutions of 1ms, which is excellent. The Mac OS X and Linux have timer resolutions of 1ms, which is excellent.

Timing Issues Java 1.5 has a better timer Java 1.5 has a better timer System.nanoTime()System.nanoTime() Third party timer libraries are also available. Third party timer libraries are also available. Most of these timing problems are to do with Java on windows platforms. Most of these timing problems are to do with Java on windows platforms. One of the things directly dependent upon accurate timing is any form of animation. One of the things directly dependent upon accurate timing is any form of animation. An upper bound for a good FPS value is the monitor refresh rate. This is typically 70-90Hz (i.e FPS). An upper bound for a good FPS value is the monitor refresh rate. This is typically 70-90Hz (i.e FPS).

Rate Control One way to deal with the inconsistency of timing on Windows is to average the change in time between frames. One way to deal with the inconsistency of timing on Windows is to average the change in time between frames. 1.Each game loop record the render time between frames. 2.Average the last 5 frame times 3.Use the average to move and update game elements

Animation Animation adds the dimension of time to computer graphics. Animation adds the dimension of time to computer graphics. To animate something, the animator has to be able to control, either directly or indirectly, how the thing is to move through time and space as well as how it might change its own shape or appearance over time. To animate something, the animator has to be able to control, either directly or indirectly, how the thing is to move through time and space as well as how it might change its own shape or appearance over time.

Animating the Aliens Instead of the entity maintaining just a single sprite we'll add a few sprites and flip between them over time, i.e. Animation. Instead of the entity maintaining just a single sprite we'll add a few sprites and flip between them over time, i.e. Animation. We need additional variables to our AlienEntity: We need additional variables to our AlienEntity: /** The animation frames */ private Sprite[] frames = new Sprite[4]; /** The time since the last frame change took place */ private long lastFrameChange; /** The frame duration in milliseconds, i.e. how long any given frame of animation lasts */ private long frameDuration = 250; /** The current frame of animation being displayed */ private int frameNumber;

AlienEntity Class – Constructor public AlienEntity(Game game,int x,int y) { super("sprites/alien.gif",x,y); // setup the animatin frames frames[0] = sprite; frames[1] = SpriteStore.get().getSprite("sprites/alien2.gif"); frames[2] = sprite; frames[3] = SpriteStore.get().getSprite("sprites/alien3.gif"); this.game = game; dx = -moveSpeed; }

AlienEntity Class – move() method public void move(long delta) { // since the move tells us how much time has passed // by we can use it to drive the animation lastFrameChange += delta; // if we need to change the frame, update the frame number // and flip over the sprite in use if (lastFrameChange > frameDuration) { // reset our frame change time counter lastFrameChange = 0; // update the frame frameNumber++; if (frameNumber >= frames.length) { frameNumber = 0; } sprite = frames[frameNumber]; }...}

Full-Screen Exclusive Mode (FSEM) Full-screen exclusive mode (FSEM) suspends most of Java's windowing environment, bypassing the Swing and AWT graphics layers to offer almost direct access to the screen. It allows graphics card features, such as page flipping, to be exploited, and permits the screen’s resolution and bit depth to be adjusted. The graphics hardware acceleration used by FSEM has a disadvantage: it utilizes video memory (VRAM) which may be 'grabbed back’ by the OS when, for example, it needs to draw another window, display a screensaver, or change the screen's resolution. The application's image buffer, which is stored in the VRAM, will then have to be reconstructed from scratch. A related issue is that VRAM is not an infinite resource, and trying to place too many images there may cause the OS to start swapping them in and out of memory, causing a slowdown in the rendering.

Setting up JFrame to Full-Screen Exclusive Mode (FSEM) GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = ge.getDefaultScreenDevice(); setUndecorated(true); // no menu bar, borders, etc. setIgnoreRepaint(true); // turn off paint events since doing active rendering setResizable(false); if (!gd.isFullScreenSupported()) { System.exit(0); } gd.setFullScreenWindow(this); // switch on FSEM

BufferStrategy try { EventQueue.invokeAndWait( new Runnable() { public void run() { createBufferStrategy(2); } }); } catch (Exception e) { System.out.println("Error while creating buffer strategy"); System.exit(0); } try { // sleep to give time for buffer strategy to be done Thread.sleep(500); // 0.5 sec } catch (InterruptedException ex){} bufferStrategy = getBufferStrategy(); // store for later

BufferStrategy invokeAndWait() is employed to avoid a possible deadlock between the createBufferStrategy() call and the event dispatcher thread (this issue should be fixed in J2SE 1.5) createBufferStrategy() is an asynchronous operation, so the sleep() call delays execution a little time so that the getBufferStrategy() call will get the correct details. Other asynchronous methods include setDisplayMode(), show(), and setFullScreenWindow().

Rendering onto Frame Buffers Graphics g = bufferStrategy.getDrawGraphics(); // Write rendering commands with g // … g.dispose();

Page Flipping if (!bufferStrategy.contentsLost()) bufferStrategy.show(); else System.out.println("Contents Lost");

Page Flipping The amount of copying required to display even a single frame is substantial. The amount of copying required to display even a single frame is substantial. For example, a display of 1024 by 768 pixels, with 32 bit depth, will need a 3MB sized copy.For example, a display of 1024 by 768 pixels, with 32 bit depth, will need a 3MB sized copy. Page flipping avoids these overheads by using a video pointer (if one is available). Page flipping avoids these overheads by using a video pointer (if one is available). The video pointer tells the graphics card where to look in VRAM for the image to be displayed during the next refresh.The video pointer tells the graphics card where to look in VRAM for the image to be displayed during the next refresh. Page flipping involves two buffers, which are used alternatively as the primary surface for the screen. While the video pointer is pointing at one buffer, the other is updated.Page flipping involves two buffers, which are used alternatively as the primary surface for the screen. While the video pointer is pointing at one buffer, the other is updated. When the next refresh cycle comes around, the pointer is changed to refer to the second buffer, and the first is updated.When the next refresh cycle comes around, the pointer is changed to refer to the second buffer, and the first is updated. With more than two frame buffers, a flip chain is created. The video pointer cycles through the buffers while rendering is carried out to the other buffers in the chain. With more than two frame buffers, a flip chain is created. The video pointer cycles through the buffers while rendering is carried out to the other buffers in the chain.

Setting the display mode A smaller screen resolution and bit depth reduces the amount of data transferred when the back buffer is copied to the screen. A smaller screen resolution and bit depth reduces the amount of data transferred when the back buffer is copied to the screen. For example, a display of 1024 by 768 pixels, with 32 bit depth, will need a 3MB sized copy.For example, a display of 1024 by 768 pixels, with 32 bit depth, will need a 3MB sized copy. However, this advantage is irrelevant if the rendering is carried out by page flipping with video pointer manipulation.However, this advantage is irrelevant if the rendering is carried out by page flipping with video pointer manipulation. A game can run more quickly if its images share the same bit depth as the screen. This is easier to do if we fix the bit depth inside the application. A game can run more quickly if its images share the same bit depth as the screen. This is easier to do if we fix the bit depth inside the application. A known screen size may make drawing operations simpler, especially for images which would normally have to be scaled to fit different display sizes. A known screen size may make drawing operations simpler, especially for images which would normally have to be scaled to fit different display sizes.

Setting the display mode GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = ge.getDefaultScreenDevice(); if (gd.isDisplayChangeSupported()) { DisplayMode dm = new DisplayMode(width, height, bitDepth, DisplayMode.REFRESH_RATE_UNKNOWN); // any refresh rate try { gd.setDisplayMode(dm); } catch (IllegalArgumentException e) { System.out.println("Error setting Display mode"); } try { // sleep to give time for the display to be changed Thread.sleep(1000); // 1 sec } catch(InterruptedException ex){} }

Checking whether a display mode is available private boolean isDisplayModeAvailable( GraphicsDevice gd, int width, int height, int bitDepth) DisplayMode[] modes = gd.getDisplayModes(); for(int i = 0; i < modes.length; i++) { if ( width == modes[i].getWidth() && height == modes[i].getHeight() && bitDepth == modes[i].getBitDepth() ) return true; } return false; }

Accessing the video memory for images Use the VolatileImage class. E.g. Use the VolatileImage class. E.g. // image creation VolatileImage vImg = createVolatileImage(w, h); // rendering to the image void renderOffscreen() { do { if (vImg.validate(getGraphicsConfiguration()) == VolatileImage.IMAGE_INCOMPATIBLE) { // old vImg doesn't work with new GraphicsConfig; re-create it vImg = createVolatileImage(w, h); } Graphics2D g = vImg.createGraphics(); // // miscellaneous rendering commands... //g.dispose(); } while (vImg.contentsLost()); } Note: createVolatileImage() is a method of Component class or otherwise you may want to use createCompatibleVolatileImage() method of a GraphicsConfiguration object.

VolatileImage – Restoring the contents // copying from the image (here, ghs is a Graphics // object for a frame buffer possibly in the video memory) do { int returnCode = vImg.validate(getGraphicsConfiguration()); if (returnCode == VolatileImage.IMAGE_RESTORED) { // Contents need to be restored renderOffscreen(); // restore contents } else if (returnCode == VolatileImage. IMAGE_INCOMPATIBLE ) { // old vImg doesn't work with new GraphicsConfig; re-create it vImg = createVolatileImage(w, h); renderOffscreen();} ghs.drawImage(vImg, 0, 0, this); } while (vImg.contentsLost());

References Space invaders tutorial available at Space invaders tutorial available at