1 Java Is Too Slow for Games Programming 2 Java Application Installation Is a Nightmare 5Java Isn’t Supported on Games Consoles 5 No One Uses Java to Write Real Games 7Sun Microsystems I
Trang 3Killer Game Programming
Trang 4Other Java resources from O’Reilly
Related titles Head First Java™
Hardcore Java™
J2ME in a NutshellJava™ in a NutshellQuickTime for Java™:
java.oreilly.com is a complete catalog of O’Reilly’s books on
Java and related technologies, including sample chapters andcode examples
OnJava.com is a one-stop resource for enterprise Java
develop-ers, featuring news, code recipes, interviews, weblogs, andmore
Conferences O’Reilly brings diverse innovators together to nurture the ideas
that spark revolutionary industries We specialize in ing the latest tools and systems, translating the innovator’s
document-knowledge into useful skills for those in the trenches Visit
con-ferences.oreilly.com for our upcoming events.
Safari Bookshelf (safari.oreilly.com) is the premier online
refer-ence library for programmers and IT professionals Conductsearches across more than 1,000 books Subscribers can zero in
on answers to time-critical questions in a matter of seconds.Read the books on your Bookshelf from cover to cover or sim-ply flip to the page you need Try it today with a free trial
Trang 5Killer Game Programming
Andrew Davison
Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo
Trang 6Killer Game Programming in Java
by Andrew Davison
Copyright © 2005 O’Reilly Media, Inc All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472 O’Reilly books may be purchased for educational, business, or sales promotional use Online editions
are also available for most titles (safari.oreilly.com) For more information, contact our tutional sales department: (800) 998-9938 or corporate@oreilly.com.
Production Editor: Matt Hutchinson
Production Services: GEX, Inc.
Cover Designer: Emma Colby
Interior Designer: David Futato
Printing History:
May 2005: First Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc Killer Game Programming in Java, the image of a jungle cat, and related trade dress
are trademarks of O’Reilly Media, Inc.
Java™ and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries O’Reilly Media, Inc., is independent of Sun Microsystems.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and O’Reilly Media, Inc was aware of a trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author assume
no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.
ISBN: 978-0-596-00730-0
Trang 7Table of Contents
Preface xv
1 Why Java for Games Programming? 1
Java Is Too Slow for Games Programming 2
Java Application Installation Is a Nightmare 5Java Isn’t Supported on Games Consoles 5
No One Uses Java to Write Real Games 7Sun Microsystems Isn’t Interested in Supporting Java Gaming 10
2 An Animation Framework 13
Animation as a Threaded Canvas 14
Converting to Active Rendering 21FPS and Sleeping for Varying Times 22
3 Worms in Windows and Applets 46
Class Diagrams for the WormChase Application 48The Worm-Chasing Application 48
Trang 8An Almost Full-Screen (AFS) Worm 77
An Undecorated Full-Screen (UFS) Worm 82
A Full-Screen Exclusive Mode (FSEM) Worm 89
Visual Effects for ‘o’ Images 147Packaging the Application as a JAR 175
7 Introducing Java Sound 178
Java Sound API Compared with JMF and JOAL 202
Trang 9Table of Contents | vii
8 Loading and Playing Sounds 205
Loader Design and Implementation Issues 207
Class Diagrams for BugRunner 272
Specifying a Sprite with a Statechart 284
12 A Side-Scroller 298
Class Diagrams for JumpingJack 300
Trang 10viii | Table of Contents
Other Side-Scroller Examples 343
13 An Isometric Tile Game 345
Class Diagrams for AlienTiles 350
The Quadrant-Based Alien Sprite 376
16 Loading and Manipulating External Models 424
An Overview of LoaderInfo3D 426
Trang 11Building the Model’s Scene Graph 451
17 Using a Lathe to Make Shapes 459
Subclassing the Lathe Shape 482
18 3D Sprites 487
Controlling the Touring Sprite 504
19 Animated 3D Sprites 512
Class Diagrams for AnimTour3D 513
Full-Screen Exclusive Mode (FSEM) 525
A Full-Screen Version of the Application 525Pros and Cons of Keyframe Animation 530
20 An Articulated, Moveable Figure 531
The Articulated Figure Application 531Forward and Inverse Kinematics 535
Trang 12x | Table of Contents
Making and Moving the Figure 543
Articulation and Mesh Deformation 562
Trang 13Class Diagrams for FPShooter3D 643
Positioning and Moving the User’s Viewpoint 645Initializing the User’s Viewpoint 647Adding an Image to the Viewpoint 648
25 A 3D Maze 656
Related Approaches to Scene Generation 685
26 Fractal Land 686
Class Diagrams for the Fractal Land 688
Generating a Fractal Landscape 701
Terrain Following and Collision Avoidance 706Placing Objects in the Scene 707
Trang 14xii | Table of Contents
27 Terrain Generation with Terragen 711
Accelerating Terrain Following 743
28 Trees That Grow 749
29 Networking Basics 769
The Elements of Network Communication 770
Client/Server Programming in Java 780
31 A Networked Two-Person Game 844
The Standalone Tic-Tac-Toe Game 846The Networked Tic-Tac-Toe Game 858
Trang 15Table of Contents | xiii
32 A Networked Virtual Environment 878
A Installation Using install4j 905
B Installation Using Java Web Start 921 Index 953
Trang 17Preface
Who Are You?
Yes, you Sit up straight, and stop slouching (Don’t you just love this assertive ing style?)
writ-You’re a programmer who wants to apply your abilities to 2D, 3D, and networkgames programming, for entertainment or as the first step in becoming a gamesprogramming professional You want to write a game that uses the latest Java tech-nology, not an applet showing a penguin waving its flipper
You’ve done an introductory course on Java, so you understand about classes,objects, inheritance, exception handling, threads, and basic graphics But you needinformation about more advanced stuff like the APIs for Java 2D, Java Sound, net-working, and Java 3D
You’re probably most interested in multiplayer 3D games programming, becausethey’re the coolest They are hard to code, but this book will get you up to speed onhow to build one
You don’t want to reinvent the wheel since Java is about abstraction, information ing, and reuse That translates into building games with existing libraries/classes/tools
hid-What This Book Is About
This book describes modern (i.e., fast and efficient) Java programming techniquesfor writing a broad range of games, including 2D arcade-style, isometric (2.5D), 3D,and network games, with a strong emphasis on 3D programming using Java 3D.The 3D topics include loading externally produced 3D models, 3D sprites, first per-son shooters (FPS), terrain generation, particle systems and flocking, and differentapproaches to animation
Trang 18J2SE 5.0 (or 1.4.2) and Java 3D 1.3.1 can be downloaded from http://www.java.com:80/
en/download/manual.jsp and http://java.sun.com/products/java-media/3D/.
This Book (and More) Is Online
This book has been growing for a long time, with chapters and code appearing
regu-larly at http://fivedots.coe.psu.ac.th/~ad/jg/ I’ve found it a useful way of gaining lots of
feedback The site is still worth visiting since a few chapters didn’t make it in herealong with the source code
What This Book Is Not About
I’m not going to spend 200 pages explaining classes and objects, inheritance, tion handling, and threads Many books do that already A good Java introduction is
excep-Thinking in Java by Bruce Eckel It’s won awards and can be downloaded at http:// www.mindview.net/Books/TIJ/.
You won’t find any large games here, such as a complete FPS or a multiplayer tasy world Describing one of those in detail would require hundreds of pages.Instead, I focus on the building blocks for games (e.g., reusable elements such as
fan-Which Software Versions?
My Java code is designed to compile and run in J2SE 5.0 and J2SE 1.4, which meansthat I avoid using new language features and API introduced in J2SE 5.0 The main rea-son is to allow my code to be backward compatible with older (and still popular) Javaversions The main areas where I lose out are in the availability of type-safe collectionsand the nanosecond time method,System.nanoTime( ), introduced in J2SE 5.0
However, my code uses the J2SE 1.4 collections in type-safe ways, and I utilize the Java3D nanosecond timer instead ofnanoTime( )to achieve the same timing accuracy InChapter 2, I discuss these issues in more detail
I use Java 3D 1.3.1 although there is a bug release version, 1.3.2, which is regularlyupdated I decided to employ Version 1.3.1 since it’s stable and well-documented InChapter 14, I talk about Java 3D in more detail
Trang 19Preface | xvii
loaders, and algorithms such as A* pathfinding) Shooting in a 3D world isdescribed in Chapters 23 and 24, and Chapter 32 explains a simple multiuser 3Dspace
I’ve reduced the quantity of code listings; you won’t find page after page of mented code here The documentation uses modern visual aids, including UML classdiagrams, sequence diagrams, state charts, and 3D scene graphs
undocu-The 3D material concentrates on Java 3D, because it’s a high-level 3D API using astable and well-documented scene graph Java has alternative ways of programming3D applications, including JOGL, LWJGL, Xith3D, jME OpenMind, and more I’lldiscuss them in Chapter 14, at the start of the Java 3D coverage
I won’t be talking about J2ME games programming on mobile devices It’s an ing subject, especially now that a mobile 3D API is available (for example, in the
excit-J2ME Wireless Toolkit v2.2, http://java.sun.com/products/j2mewtoolkit/)
Unfortu-nately, this book is groaning at the seams, and something has to be left out For
those interested in J2ME games programming, I suggest J2ME Games with MIDP2
by Carol Hamer (but, it doesn’t cover the 3D API, which is too new) I’ve writtenseveral chapters on the API, which can be downloaded from this book’s web site at
http://fivedots.coe.psu.ac.th/~ad/jg/.
This is not a games design text, a topic deserving its own book or two Two I like are
Game Architecture and Design: A New Edition by Andrew Rollings and Dave Morris,
and Chris Crawford on Game Design by Chris Crawford.
If you prefer online sources, the following sites are full of gaming articles, reviews,and opinions:
• Gamasutra (http://www.gamasutra.com/)
• GameDev.net (http://www.gamedev.net/)
• flipCode (http://www.flipcode.com/)
• IGDA, the International Game Developers forum (http://www.igda.org/Forums/)
A Graphical View of This Book
This book has four parts: 2D programming, 3D programming with Java 3D, work programming, and two appendixes on installation The following figures givemore details about each one in a visual way Each oval is a chapter, and the arrowsshow the main dependencies between the chapters Chapters on a common themeare grouped inside dotted, rounded gray squares
net-2D Programming
Figure P-1 shows the 2D-programming chapters
Trang 20xviii | Preface
Chapter 1 is a defense of Java for gaming, which Java zealots can happily skip Theanimation framework used in the 2D examples is explained in Chapter 2, followed
by two chapters applying it to a simple Worms example, first as a windowed
applica-tion, then as an applet, then using full screen mode, and almost full screen mode.Chapters 3 and 4 contain timing code for comparing the frame rate speeds of theseapproaches
Chapters 5 and 6 are about imaging, mostly concentrating on Java 2D Chapter 6 hasthree main topics: classes for loading images, visual effects, and animation
Chapters 7 through 10 are about Java Sound: Chapter 8 develops classes for loadingand playing WAV and MIDI audio, and Chapters 9 and 10 are on sound effects andmusic synthesis
A reader who isn’t much interested in visual and audio special effects can probablyskip the latter half of Chapter 6, and all of Chapters 9 and 10 However, the classesfor loading images and audio developed in the first half of Chapter 6 and inChapter 8 are utilized later
Chapter 11 develops a 2D Sprite class, and applies it in a BugRunner game
Chapter 12 is about side scrollers (as immortalized by Super Mario Bros.), and Chapter 13 is about isometric tile games (Civilization is an example of that genre).
3D Programming
The 3D-programming chapters are shown in Figure P-2
Figure P-1 2D-programming chapters
7
Sound Loading and Playing
8
Audio Synthesis
10
Audio Effects
9
Trang 21Preface | xix
Java 3D is introduced in Chapter 14, followed by the Checkers3D example inChapter 15; its checkerboard floor, lighting, and background appear in several laterchapters
There are five main subtopics covered in the 3D material: models, animation, cle systems, shooting techniques, and landscape and scenery
parti-Chapter 16 develops two applications,LoaderInfo3DandLoader3D, which show how
to load and manipulate externally created 3D models ThePropManagerclass used in
Loader3Dis employed in other chapters when an external model is required as part ofthe scene Chapter 17 develops aLatheShapeclass, which allows complex shapes to
be generated using surface revolution
A 3D sprite class is described in Chapter 18, leading to a Tour3D application thatallows the user to slide and rotate a robot around a scene Chapters 19 and 20 exam-ine two approaches for animating the parts of a figure: Chapter 19 uses keyframesequences, and Chapter 20 develops an articulated figure whose limbs can be movedand rotated
Figure P-2 3D-programming chapters
20
Landscape and Scenery
Trees That Grow
24
Trang 22xx | Preface
Particle systems are a widely used technique in 3D games (e.g., for waterfalls, ing blood, and explosions to name a few) Chapter 21 explains three different parti-cle systems in Java 3D Flocking (Chapter 22) gives the individual elements (theparticles) more complex behavioral rules and is often used to animate large groupssuch as crowds, soldiers, and flocks of birds
gush-Lots of games are about shooting things Chapter 23 shows how to fire a laser beamfrom a gun situated on a checkerboard floor Chapter 24 places the gun in your hand(i.e., an FPS)
The 3D chapters end with landscape and scenery creation Chapter 25 describes how
to generate a 3D maze from a text file specification Chapter 26 generates landscapes
using fractals, and Chapter 27 uses a popular terrain generation package, Terragen,
to create a landscape, which is then imported into the Java 3D application.Chapter 27 discusses two techniques for filling the landscape with scenery (e.g.,bushes, trees, and castles)
Chapter 28 concentrates on how to make trees grow realistically over a period oftime
The dotted arrow from Chapters 24 to 28 indicates a less pronounced dependency; Ionly reuse the code for moving the user’s viewpoint
Network Programming
Figure P-3 shows the network-programming chapters
Chapter 29 supplies information on networking fundamentals (e.g., the client/serverand peer-to-peer models), and explains basic network programming with sockets,URLs, and servlets Chapter 30 looks at three chat variants: one using a client/servermodel, one employing multicasting, and one chatting with servlets
Chapter 31 describes a networked version of theFourByFourapplication, a turn-basedgame demo in the Java 3D distribution It requires a knowledge of Java 3D Chapter 32revisits theTour3Dapplication of Chapter 18 (the robot moving about a checkerboard)and adds networking to allow multiple users to share the world I discuss some of the
Figure P-3 Network programming chapters
Trang 23Preface | xxi
advanced issues concerning networked virtual environments (NVEs), of which
NetTour3D is an example
The Appendixes
The appendixes are shown in Figure P-4
Appendix A describes install4j, a cross-platform tool for creating native installersfor Java applications Appendix B is about Java Web Start (JWS), a web-enabledinstaller for Java applications
Both appendixes use the same two examples.BugRunner(from Chapter 11, which
dis-cusses 2D sprites) uses the standard parts of J2SE and theJ3DTimerclass from Java3D.Checkers3D, from Chapter 15, is my first Java 3D example
Conventions Used in This Book
The following typographical conventions are used in this book:
Figure P-4 The appendixes
Installation using install4j
Trang 24xxii | Preface
Constant width bold
Shows commands or other text that should be typed literally by the user
Constant width italic
Shows text that should be replaced with user-supplied values
This icon signifies a tip, suggestion, or general note.
This icon indicates a warning or caution.
Using Code Examples
This book is here to help you get your job done In general, you may use the code inthis book in your programs and documentation You do not need to contact O’Reillyfor permission unless you’re reproducing a significant portion of the code For exam-ple, writing a program that uses several chunks of code from this book does notrequire permission Selling or distributing a CD-ROM of examples from O’Reilly
books does require permission Answering a question by citing this book and
quot-ing example code does not require permission Incorporatquot-ing a significant amount of
example code from this book into your product’s documentation does require
permission
We appreciate, but do not require, attribution An attribution usually includes the
title, author, publisher, and ISBN For example: “Killer Game Programming with
Java by Andrew Davison Copyright 2005 O’Reilly Media, Inc., 0-596-00730-2.”
If you feel your use of code examples falls outside fair use or the permission given
above, feel free to contact us at permissions@oreilly.com.
All the code examples can be downloaded from the book’s web site at http://fivedots.
coe.psu.ac.th/~ad/jg.
Comments and Questions
Please address comments and questions concerning this book to the publisher:O’Reilly Media, Inc
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the United States or Canada)
(707) 829-0515 (international or local)
(707) 829-0104 (fax)
Trang 25tech-Safari offers a solution that’s better than e-books It’s a virtual library that lets youeasily search thousands of top technology books, cut and paste code samples, down-load chapters, and find quick answers when you need the most accurate, current
information Try it for free at http://safari.oreilly.com.
Acknowledgments
Time to climb up on stage, grab the microphone, and tearfully thank every relative,friend, and acquaintance I’ve ever known, while the audience gradually slips off tothe Land of Nod and viewers worldwide start channel hopping “Oh my God, I loveyou all, I really do.”
First, I should thank you for buying this book, which will mean that I can buy a
Tivoli chocolate-like bar when I go for lunch If you haven’t bought this book, then
why are reading this bit? Are you desperate or something?
My wife, Supatra, and son, John, have been a constant support, especially when myback is causing problems
Thanks to my current and past department heads, Ajarns Pichaya, Sinchai, Amnuay,and Weerapant, and many other staff and colleagues, who have let me potter about
on this mighty edifice But why does my office have the word “Broom Cupboard”stenciled on the door? But seriously, Prince of Songkla University is a great place towork
Trang 26xxiv | Preface
Greetings to the numerous students who have suffered as guinea pigs for variousparts of this book Your looks of incredulity and boredom were a wondrous spur:
“Goodbye Mr Chips” should be banned
Special thanks to the hundreds of people who have sent me emails saying how ful the online book has been; their kind words have been a great source of encour-agement I’ve also received suggestions about how to improve the book and a fewbug reports I credit those people at the relevant places in the text
use-Finally, my best regards to O’Reilly and my editor Brett McLaughlin and figuresillustrator Chris Reilly, who have knocked this book into better shape Any remain-ing rough edges are due to me
Trang 27Why Java for Games Programming?
One of my assumptions is that the reader (that’s you) has had an introductoryknowledge of Java, the sort of stuff gleaned from a semester’s course at college Nearthe start of that course, you were probably regaled with Java’s many advantages: anobject-oriented paradigm, cross-platform support, code reuse, ease of development,tool availability, reliability and stability, good documentation, support from SunMicrosystems, low development costs, the ability to use legacy code (e.g., C, C++),and increased programmer productivity
Rather than explain each of these again, I will take a different approach and discussJava’s suitability for games programming in terms of the typical misconceptions andcomplaints wheeled out by people who think that games must be implemented in C,C++, assembler, or whatever (just so long as it’s not Java)
Here’s the list of objections to Java:
• Java is too slow for games programming
• Java has memory leaks
• Java is too high-level
• Java application installation is a nightmare
• Java isn’t supported on games consoles
• No one uses Java to write real games
• Sun Microsystems isn’t interested in supporting Java gaming
It’s worth saying that I think almost all of these objections are substantially wrong.Java is roughly the same speed as C++ Memory leaks can be avoided with good pro-gramming and techniques like profiling Yes, Java is high-level, but it offers moredirect access to graphics hardware and external devices Installation isn’t a night-mare if you use decent installation software There’s a growing number of excellent,fun Java games, and an enormous amount of support available from Sun and Sun-sponsored sites
Trang 282 | Chapter 1: Why Java for Games Programming?
If you’re keeping count, I haven’t disagreed with the lack of a games
consoles port, which is a tad embarrassing for a “write once, run
any-where” language Things may be changing in this category, as I’ll
explain later.
A general point about these objections is that they had more validity in the late 1990swhen the language and its libraries were less sophisticated and slower Java’s userand developer communities are burgeoning and have produced a plethora of usefultools, online help, and code examples The games forums dedicated to Java barelyexisted 2 to 3 years ago Java is a great language for games programming, as I hopethis book demonstrates Now, back to the criticisms
Java Is Too Slow for Games Programming
This is better rephrased as “Java is slow compared to C and C++, the dominant guages for games programming.” This argument was valid when Java first appeared(around 1996) but has become increasingly ridiculous with each new release Somefigures put JDK 1.0, that first version of the language, at 20 to 40 times slower thanC++ However, J2SE 5.0, the current release, is typically only 1.1 times slower.These numbers depend greatly on the coding style used Java programmers must begood programmers to utilize Java efficiently, but that’s true of any language Jack
lan-Shirazi’s Java Performance Tuning site (http://www.javaperformancetuning.com/) is a
good source for performance tips, with links to tools and other resources A recent
benchmarking of Java vs C++ by Keith Lea caused quite a stir (http://www.
theserverside.com/news/thread.tss?thread_id=26634) He found that Java may
some-times be faster than C++ The response from the C++ crowd was typically vitriolic.The speed-up in Java is mostly due to improvements in compiler design TheHotspot technology introduced in J2SE 1.3 enables the runtime system to identifycrucial areas of code that are utilized many times, and these are aggressively com-piled Hotspot technology is relatively new, and it’s quite likely that future versions
of Java will yield further speed-ups For example, J2SE 5.0 is reportedly 1.2 to 1.5times faster than its predecessor (Version 1.4)
Hotspot technology has the unfortunate side effect that program
exe-cution is often slow at the beginning until the code has been analyzed
and compiled.
Swing Is Slow
Swing often comes under attack for being slow Swing GUI components are createdand controlled from Java, with little OS support; this increases their portability andmakes them more controllable from within a Java program Speed is supposedly
Trang 29Java Has Memory Leaks | 3
compromised because Java imposes an extra layer of processing above the OS This
is one reason why some games applications still utilize the original Abstract dowing Toolkit (AWT) since it’s mostly simple wrapper methods around OS calls.Even if Swing is slow (and I’m not convinced of that), most games don’t requirecomplex GUIs; full-screen game play with mouse and keyboard controls is the norm.GUI elements maintained by Swing, such as menu bars, button, and text fields aren’tneeded, and mouse and keyboard processing is dealt with by the AWT The latestversions of Java offer an efficient full-screen mode by suspending the normal win-dowing environment
Win-My Program Is Slow Because of Java
A crucial point about speed is knowing what to blame when a program runs slowly.Typically, a large part of the graphics rendering of a game is handled by hardware orsoftware outside of Java For example, Java 3D passes its rendering tasks down toOpenGL or DirectX, which may emulate hardware capabilities such as bump map-ping Often the performance bottleneck in network games is the network and not theJava language
Java Has Memory Leaks
When C/C++ programmers refer to memory leaks in Java, they probably don’tunderstand how Java works Java doesn’t offer pointer arithmetic; typical C-stylememory leaks, such as out-of-bounds array accesses, are caught by the Java compiler.However, these programmers may mean that objects that are no longer needed bythe program are not being garbage collected This becomes an issue if the programkeeps creating new objects and requiring more memory, and eventually crasheswhen the maximum memory allocation is exceeded
This kind of problem is a consequence of bad programming style, since the garbage
collector can only do its job when an object is completely dereferenced, meaning the program no longer refers to the object A good profiling tool, such as JProfiler (http://
www.ej-technologies.com/products/jprofiler/overview.html), can help identify code
using excessive amounts of memory
JProfiler is a commercial product; many open source profilers are
listed at http://java-source.net/.
Another memory-related complaint is that the Java garbage collector is executing atpoorly timed intervals, causing the application to halt for seconds as the collectorsweeps and cleans The Java Virtual Machine (JVM) comes with several different gar-bage collectors, which collect in various ways and can be selected and fine-tuned
Trang 304 | Chapter 1: Why Java for Games Programming?
from the command line Information on the performance of the chosen collector can
be gathered and analyzed A good hands-on explanation of this topic, centered
around the JTune visualization tool, can be found at http://www-106.ibm.com/
developerworks/java/library/j-perf06304/ Another possibility is GC Portal (http:// java.sun.com/developer/technicalArticles/Programming/GCPortal/).
Java Is Too High-level
This complaint is the age-old one of abstraction versus speed and control Thedetails of the argument often include the following statements:
1 Java’s use of classes, objects, and inheritance add too much overhead withoutenough coding benefit
2 Java’s machine independence means that low-level, fast operations, e.g., directVideo RAM I/O are impossible
Statement 1 ignores the obvious benefits of reusing and extending Java’s large classlibrary, which includes high-speed I/O, advanced 2D and 3D graphics, and manynetworking techniques, from lowly sockets to distributed agents Also forgotten arethe advantages of object-oriented design, typified by UML, which makes complex,large, real-world systems more manageable during development, implementation,and maintenance
Statement 2 impacts gaming when we consider high-speed graphics, but it’s been
addressed in recent versions of Java J2SE 1.4 introduced a full-screen exclusive mode
(FSEM), which suspends the normal windowing environment and allows an tion to access the underlying graphics hardware more directly It permits techniques,e.g., page flipping, and provides control over the screen’s resolution and imagedepth The principal aim of FSEM is to speed up graphics-intensive applications,such as games
applica-Statement 2 comes into play for game peripherals, e.g., joysticks and game pads;machine independence seems to suggest that nonstandard I/O devices won’t be use-able Java games requiring these types of devices can utilize the Java Native Interface(JNI) to link to C or C++ and, therefore, to the hardware There’s also JInput, a newgame controller API
An interesting historical observation is that the gaming community used to thinkthat C and C++ were too high-level for fast, efficient games programming whencompared to assembly language Opinions started to change only after the obvious
success of games written in C, such as Doom and Dungeon Master, in the mid-1980s.
Also important was the appearance of cross-platform development tools that ported C, such as RenderWare
Trang 31sup-Java Isn’t Supported on Games Consoles | 5
Java Application Installation Is a Nightmare
The naysayers claim that the user needs to be a Java expert to install and execute aJava application, whereas most game players want to point and click on a few dialogboxes to get a game up and running More specific comments include the following:
1 Java (specifically, the JRE) has to be on the machine before the application willrun
2 Code bloat since even small programs require a 15 MB JRE Downloading thiscan be slow
3 Frequently changing JVMs make it hard to write code that will work for everypossible version of Java
4 Nonstandard components are often required—e.g., Java 3D, causing even moreinstallation problems
5 It’s impossible to compile the application for a specific platform
6 The jar extension is commonly hijacked by other software (e.g., by
compres-sion programs) at execution time, meaning that the user can’t double-click on aJAR to get it to start
7 The JRE is slower to start up compared to a native compiled application
All these problems, aside from perhaps 2 and 7, can be solved by using good tion software I have two appendixes dedicated to installation: Appendix A is aboutinstall4j, a cross-platform tool for creating native installers for Java applications, andAppendix B is about Java Web Start (JWS), a web-enabled installer
installa-The code bloat comment is increasingly irrelevant, with many games weighing in atover 100 MB and many graphics and sound card drivers being made larger than 15
MB Network speeds are a problem, especially overseas, but broadband usage isgrowing rapidly
Sun Microsystems estimates that more than 50 percent of all new PCs come with apre-installed JRE, though a game installer must still cater to the other 50 percent.There’s some truth to point 7, but the slow startup time is fairly negligible compared
to the total running time of an average game
I was interested in what other Java games programmers had to say about this
criti-cism, so posted it to the Java Games Forum as thread
http://www.javagaming.org/cgi-bin/JGNetForums/YaBB.cgi?board=announcements;action=display;num=1092970902.
The responses are similar to mine, though often phrased somewhat more stridently
Java Isn’t Supported on Games Consoles
Unfortunately, this criticism has some justification Video gaming is a dollar industry, with estimates placing revenues at $29 billion by 2007 with the market
Trang 32multi-billion-6 | Chapter 1: Why Java for Games Programming?
catering to over 235 million gamers PCs and game consoles account for almost all theincome, but only about 10–20 percent of it is from PCs, the majority coming fromthree consoles: Sony’s PlayStation 2 (PS2), Microsoft’s Xbox, and Nintendo’sGameCube Sony is the dominant console maker, having nearly twice as many units inhomes compared to Microsoft and Nintendo combined Microsoft accounts for about
95 percent of the desktop PC market Arguably, two important games platforms exist,the PS2 and Windows, and Java isn’t available on the PlayStation
This problem has long been recognized by Sun Back at the JavaOne conference in
2001, Sony and Sun announced their intention to port the JVM to the PS2 Nothinghas been released, but there are persistent rumors about a JVM on the PlayStation 3,earmarked to appear in 2006
In the future, Java may have a better chance of acceptance into the closed world ofconsole makers because of two trends: consoles mutating into home media devicesand the meteoric rise of online gaming Both trends require consoles to offer com-plex networking and server support, strong areas for Java and Sun
The Phantom console from Infinium Labs was announced at JavaOne in 2004 (http://
www.phantom.net/index.php) It’s essentially a PC running an embedded Windows
XP installation, with an nVidia graphics card, a hard drive, and a broadband tion Most importantly for Java gaming, the Phantom will come with a completeJRE It was demoed during Electronic Entertainment Exposition (E3) in 2004, where
connec-it was shown running Law and Order: Dead on the Money (which uses Java 3D).
Die-hard programmers may point out that it’s possible to get Java running on a PS2.One approach is to install Kaffe, an open source, non-Sun JVM, on top of PlaySta-
tion Linux Kaffe can be obtained from http://www.kaffe.org/; details on Linux for the PlayStation are at http://playstation2-linux.com/ The gallant programmer will need a Java-to-bytecode translator, such as Jikes (http://www-124.ibm.com/developerworks/
oss/jikes/).
The Linux kit adds a hard disk to the PS2, so this development strategy won’t workfor ordinary PlayStations Configuring the software looks to be far beyond the capa-bilities (or desires) of ordinary console owners, and I couldn’t find any documenta-tion about using Jikes or Kaffe on a PS2 The PlayStation only comes with 32 MB ofRAM, while a typical JVM and its libraries requires 5 to 10 MB, so how much would
be left for a game once Linux was up and running?
The difficulties of this approach should be contrasted to the availability of
feature-rich C/C++ tools and engines for consoles, such as RenderWare (http://www.
renderware.com/) and Gamebryo (http://www.ndl.com/) They have a track record of
best-selling games and can port games across the PS2, Xbox, GameCube, and PCs.The lack of Java on consoles is a serious issue, but the remaining PC market is large.Microsoft estimates that there are 600 million Windows PCs, growing to more than
1 billion by 2010 Games on PCs benefit from superior hardware—such as video
Trang 33No One Uses Java to Write Real Games | 7
cards, RAM, and Internet connections—and can offer more exciting game play.There are many more PC games, particularly in the area of multiplayer online games.It’s estimated that 40 percent of all gamers will start playing online in 2005 Reve-nues may reach $1.1 billion by 2008
Another rapidly expanding market is the one for mobile games, with sales of $530million in 2003, potentially rising to $1.93 billion in 2006 There are perhaps 200million Java-enabled phones at the moment
No One Uses Java to Write Real Games
The word “real” here probably means commercial games The number of cial Java games is small compared to ones coded in C or C++, but the number isgrowing and many have garnered awards and become bestsellers:
commer-Puzzle Pirates by Three Rings (http://www.puzzlepirates.com/)
This is a multiplayer pirate game that includes Tetris-like or Columns-like zles at various points The client and server are written in Java It won severalawards during 2004, including the Technical Excellence and Audience Choiceprizes at the Game Developers Conference
puz-Chrome by Techland (http://www.chromethegame.com/en/show.php)
Chrome is a futuristic multiplayer FPS (first person shooter) made up of 14
dif-ferent missions, in an amazing variety of landscapes It received a Duke’s ChoiceAward from Sun Microsystems in 2004 for the most innovative product usingJava technology
Law and Order II by Legacy Interactive (http://www.lawandordergame.com/index2.htm)
This is a detective game written in Java, Java 3D, and QuickTime for Java The
first Law and Order sold over 100,000 units.
Kingdom of Wars by Abandoned Castle Studios (http://www.abandonedcastle.com/)
This is a fantasy game set in the world of Jairon
Alien Flux by Puppy Games (http://www.puppygames.net/info.php?game=Alien_Flux) Alien Flux is an exciting arcade shoot-em-up.
War! Age of Imperialism by Eagle Games (http://www.eaglegames.net/products/ WAR_AOI/wai.shtml)
War! is a computer version of the award-winning board game from Eagle
Games
Runescape by Jagex (http://www.runescape.com)
Runescape is a massive 3D multiplayer fantasy adventure game Clients can use a
Java applet to play or download a Windows-based client application
Star Wars Galaxies by LucasArts (http://www.lucasarts.com/products/galaxies/)
This one has its game logic coded in Java
Trang 348 | Chapter 1: Why Java for Games Programming?
IL-2 Sturmovik by Ubi-Soft (http://www.il2sturmovik.com/)
Award winning WW II aerial combat using Java and C++, this and the new
ver-sion (IL2-Forgotten Battles) are great examples of Java in games.
Pernica by Starfire Research (http://www.starfireresearch.com/pernica/pernica.html) Pernica is an online fantasy role-playing game first implemented in Java 3D Cosm by Navtools, Inc (http://www.cosm-game.com/)
Cosm is another fun online fantasy-based role-playing game.
C&C Attack Copter by Electronic Arts (http://www.eagames.com/free/home.jsp)
This is a free online action game based on the Command & Conquer series.
Roboforge by Liquid Edge Games (http://www.roboforge.com)
Train a 3D robot to fight in online tournaments It was given an “Excellent
87%” by PC Gamer Magazine.
Galactic Village by Galactic Village Games (http://www.galactic-village.com)
Galactic Village is a massively multiplayer strategy game, written entirely in Java.
Not yet finished though alpha versions have been appearing
Wurm Online by Mojang Specifications (http://www.wurmonline.com/)
This is another massively multiplayer fantasy game, written in Java It’s still inthe alpha stages of development, but the screenshots look great
Jellyvision (http://www.jellyvision.com/)
Jellyvision used a mix of Java and C++ in their popular Who Wants to Be a lionaire (2000) and You Don’t Know Jack (1995) games They employed Java for
Mil-the game logic, an approach used in Majestic (2001) by Electronic Arts.
Vampire the Masquerade: Redemption (2000) by Nihilistic software istic.com/).
(http://www.nihil-Java was utilized as a scripting language in this highly acclaimed game
Tom Clancy’s Politika (1997) by Red Storm Entertainment (http://www.redstorm.com/)
This game was written in almost pure Java Shadow Watch (2000) and Tom
Clancy’s ruthless.com (1998) mixed Java and C/C++.
A good source for nontechnical lists of Java games, both commercial and
free-ware/shareware, can be found on the Java games pages at java.com (http://www.
java.com/en/games/) The pages divide games into several categories: action,
adventure, strategy, puzzle, cards, sports, and so on
Freeware/Shareware Games
Many Java games are out on the Web, but finding a game that’s written well requires
a careful search Many applets date from the late 1990s and were designed using theoutdated JDK 1.0 and 1.1 with their feeble media APIs (e.g., graphics, sounds) Theinitial Java euphoria produced some less than exciting games, more concerned with
Trang 35No One Uses Java to Write Real Games | 9
technical trickery than quality This large pool of useless applets got Java labeled as atoy language
Recent versions of Java are different The speed has improved and APIs crucial togaming—such as graphics and audio—are of a high quality There’s been a moveaway from applets towards the downloading of client-side applications using JWS.Java’s backward compatibility allows the applets from 1996 to 1998 to be executed,and they’ll often run quicker than the original applets However, it’s probably best tosteer clear of these Java dinosaurs and look for more modern code
Numerous web sites use Java games The emphasis of the following list is on tions/applets for playing:
applica-Java Games Factory (JGF) (http://grexengine.com/sections/externalgames/)
There aren’t many games at this site (about 50), but they’re all high quality Theaim is to show off various modern Java game technologies
ArcadePod.com (http://www.arcadepod.com/java/)
Over 750 Java games, nicely categorized
Java 4 Fun (http://www.java4fun.com/java.html)
Similar in style to ArcadePod, with a good set of links to other sites
jars.com (http://www.jars.com)
A general Java site with a ratings scheme There are many games, but a lot ofthem are old applets
Java Shareware (http://www.javashareware.com/)
Another general site: look under the categories applications/games andapplets/games
Java Games Central (http://www.mnsi.net/~rkerr/)
A personal web site that lists games with ratings and links It was last updated in2001
Some of my favorite freeware/shareware games are:
Super Elvis; also known as Hallucinogenesis (http://www.puppygames.net/downloads/ hallucinogenesis/hallucinogenesis.jnlp)
This game won the Sun Microsystems 2004 Technology Game DevelopmentContest Super Elvis can be downloaded from the puppygames web site usingJWS
FlyingGuns (http://www.flyingguns.com/)
A 3D multiplayer WWI fighter plane game/simulator This came second in thecontest but is my favorite
Cosmic Trip (http://www.mycgiserver.com/~movegaga/cosmictrip.html)
An arcade-style 3D game with striking graphics
Squareheads (http://home.halden.net/tombr/squareheads/squareheads.html)
A multiplayer FPS (it came third in the developer contest)
Trang 3610 | Chapter 1: Why Java for Games Programming?
SourceForge acts as a repository and management tool for software projects,
many with source code A recent search for (java + game) returned over 70 projectsthat had 40 percent or greater activity One of the drawbacks of SourceForge isthat deciding if a project is vaporware is difficult Good projects that have beencompleted will show low activity after a time, dropping down the list of searchresults
FreshMeat.com (http://freshmeat.net/)
FreshMeat maintains thousands of applications, most released under open
source licenses The search facilities are excellent and can be guided by game egory terms The results include rating, vitality, and popularity figures for eachpiece of software A recent search for Java in the Games/Entertainment category
cat-returned nearly 70 hits Many applications turn up at SourceForge and FreshMeat.
The “Your Games Here” Java Games Forum (http://www.javagaming.org/cgi-bin/ JGNetForums/YaBB.cgi?board=Announcements)
Implementers can post links to their games, and (perhaps more importantly)users can post their opinions as follow-ups
Code Beach (http://www.codebeach.com)
CodeBeach has a searchable subsection for Java games that contains nearly 90
examples
Programmers Heaven (http://www.programmersheaven.com/zone13/)
It has a “Java zone” containing some games
Sun Microsystems Isn’t Interested
in Supporting Java Gaming
The games market isn’t a traditional one for Sun, and it’ll probably never have thedepth of knowledge of a Sony or Nintendo However, the last few years have demon-strated Sun’s increasing commitment to gaming
J2SE has strengthened its games support through successive versions: Version 1.3improved its graphics and audio capabilities, and Version 1.4 introduced full-screenmode and page flipping in hardware Faster I/O, memory mapping, and support fornonblock sockets, which is especially useful in client/server multiplayer games, alsoappeared first in 1.4 Version 5.0 has a decent nanosecond timer at last Java extension
Trang 37Sun Microsystems Isn’t Interested in Supporting Java Gaming | 11
libraries, such as Java 3D, the Java Media Framework (JMF), the Java CommunicationsAPI, Jini, and JAXP (Java’s peer-to-peer API) offer something to games programmers.Sun started showing an interest in gaming back in 2001, with its announcement ofthe Java Game Profile, a collaboration with several other companies, including Segaand Sony, to develop a Java gaming API The profile was perhaps too ambitious, andwas abandoned at the end of 2003 However, it did produce three game-focusedtechnologies: a Java binding for OpenGL called JOGL, a binding for OpenAL (a 3Daudio library) called JOAL, and JInput
Part of the 2001 initiative was the creation of the JavaGaming.org web site (http://
www.javagaming.org), initially manned by volunteers In 2003, the Game
Technol-ogy Group was formed, and JavaGaming.org received a substantial makeover as part
of the creation of the new java.net portal (http://www.java.net) aimed at the
techni-cal promotion of Java Java.net hosts many discussion forums, user groups, projects,communities, and news The communities include: Java Desktop, Java Educationand Learning, Java Enterprise, and Java Games
The Java Games community pages can be accessed through http://www.javagaming.org
or http://community.java.net/games/ The site includes Java games forums, projects, news, weblogs, a wiki (http://wiki.java.net/bin/view/Games/WebHome), and links to
games affiliates
Numerous Java game forums can be accessed from http://www.javagaming.org/cgi-bin/
JGNetForums/YaBB.cgi These are probably the best sources of technical advice on
Java gaming on the Web, with over 4,500 opinionated registered users Discussiontopics include Java 3D, Java 2D, Java Sound, J2ME, networking, online games devel-opment, performance tuning, JOGL, JOAL, and JInput There are also sections onprojects and code examples
The project sections (https://games.dev.java.net/) mostly concentrate on JOGL,
JOAL, and JInput, but the games middleware and games forge sections are widerranging The games forge projects include Chinese chess, jbantumi (a strategic gamefrom Africa), and an online fantasy football management system
The most relevant Java user group for gaming is GameJUG (https://gamejug.dev.java.net/
) Its sections include online and downloadable Java games, presentations and articles,lists of Java game programming web sites, and a collaborative web page and mailing listfor teachers of Java game programming
I’m a former GameJUG president, a role that sounds grander than it
really was The real work was done by David Wallace Croft and James
Richards.
Sun’s substantial presence at http://community.java.net/games/ is mostly as a host for
community forums and open source projects (or projects with licenses very close to
Trang 3812 | Chapter 1: Why Java for Games Programming?
open source) The projects include JOGL, JOAL, JInput, and Java 3D Sun is relying
on community involvement to move these projects forward, since the Game nology Group is quite small
Tech-One in-house product is a server architecture for massively multiplayer online games,the Sun Game Server, first demoed at the Game Developers Conference in 2004 Thisfocus isn’t surprising since Sun makes its money from selling server hardware.Online multiplayer gaming is a potential growth area for its servers
Trang 39I distinguish between windowed and full-screen applications because
J2SE 1.4 introduced full-screen exclusive mode (FSEM) It suspends the
normal windowing environment and allows an application to access
the underlying graphics hardware more directly FSEM permits
tech-niques such as page flipping and provides control over the screen’s
res-olution and image depth The principal aim of FSEM is to accelerate
graphics-intensive applications, such as games.
The common ground between windowed and full-screen application is the game’sanimation algorithm, which is the subject of this chapter
The algorithm is embedded in aJPanel subclass (calledGamePanel), which acts as acanvas for drawing 2D graphics (e.g., lines, circles, text, images) The animation ismanaged by a thread, which ensures that it progresses at a consistent rate, as inde-pendent of the vagaries of the hardware and OS as possible The rate is measured in
terms of frames per second (FPS), where a frame corresponds to a single rendering of
the application to the canvas
GamePanel is gradually refined and expanded through the chapter, introducing thefollowing notions:
• The{update, render, sleep} animation loop
• Starting and terminating an animation
• Double buffering
• User interaction
• Active rendering
Trang 4014 | Chapter 2: An Animation Framework
• Animation control based on a user’s requested FPS
• The management of inaccuracies in the timer and sleep operations
• Combining FPS and game state updates per second (UPS)
• Game pausing and resumption
Though most of this chapter is about theGamePanelanimation loop, I will considertwo other popular approaches to implementing animation: using the Swing timerand the utility timer injava.util.timer
The example programs used in this chapter can be found in the
Tim-ings/ directory All the code directories mentioned in the chapters can
be downloaded from the book’s web site at http://fivedots.coe.psu.ac.th/
~ad/jg.
In Chapters 3 and 4, I develop applet, windowed, and full-screen applications for a
WormChasegame using the final version ofGamePanel(with minor variations) As a sideeffect of the game play, statistics are gathered, including the average FPS and UPS, toshow thatGamePanel supports consistently high-speed animation
Animation as a Threaded Canvas
inside a thread local to the panel The loop consists of three stages: game update,rendering, and a short sleep
The code in Example 2-1 shows the main elements ofGamePanel, including therun( )
method containing the animation loop As the chapter progresses, additional ods and global variables will be added toGamePanel, and some of the existing meth-ods (especiallyrun( )) will be changed and extended
meth-Example 2-1 The GamePanel class (initial version)
public class GamePanel extends JPanel implements Runnable
{
private static final int PWIDTH = 500; // size of panel
private static final int PHEIGHT = 400;
private Thread animator; // for the animation
private volatile boolean running = false; // stops the animation
private volatile boolean gameOver = false; // for game termination
// more variables, explained later
// :
public GamePanel( )
{