Mes Top 5 Ouvrages
Termes les plus recherchés
Java Gaming & Graphics Programming
Killer Game Programming in Java
For many years, Java programmers who have wanted to dabble, develop, or dive head
first into game programming have been frustrated — by a lack of support in Java for
high-end graphics and acceptable frame rates; by sparse documentation and silly “Hello
World’’ examples; and by a platform that seems disinterested in gaming at best and
outright hostile at worst. As a result, Java has become a second-class citizen to C, C++, and assembly
language when it comes to hardcore game programming.
Killer Game Programming in Java changes all that. This wide-ranging book on Java game program-
ming blows the doors off what even experienced developers previously thought was possible on
the Java platform. Beginning with a look at why Java can be a great gaming platform, the book
quickly dispels tile common myths about Java’s speed and suitability for real-time, networked, and
graphics-intensive games. You’ll then get an A-to-Z look at 2D graphics programming, ranging
from a simple animation framework to extensive coverage of partial- and full-screen games, image
management and manipulation, creating and playing sound and audio effects, and working with
side-scroller and isometric tile games.
But gaming in today's market must go far beyond 2D, and this book takes on 3D gaming as well.
Moving beyond a flat landscape, you’ll learn how to code sprites, lathes, and rotating shapes; develop
flocking and particle systems; and render fully textured terrains. And no 3D-programming text would
be complete without a working first-person shooter game, along with guns that shoot.
This intensive text concludes with a section that deals specifically with networked games. Both 2D and
3D games are examined with networking in mind, and you’ll quickly be writing full-blown 3D multi-
player games, with amazing graphics and sound, all in Java. There’s nothing on the market or online
that comes close to the depth and range you'll find in Killer Game Programming in Java. So what
are you waiting for? Pick up this book and get started today. You and your friends won’t regret it.
US $44.95 CAN $62.95
Killer Game Programming
w w w . alii tebooks .com
Other Java™ resources from O'Reilly
Head First Java™ Physics for Game Developers
Hardcore Java” Gaming Hacks
J2ME in a Nutshell AI for Game Developers
Java” in a Nutshell Java” 2D Graphics
QuickTime for Java":
A Developer’s Notebook
java.oreilly.com is a complete catalog of O’Reilly’s books on
Java and related technologies, including sample chapters and
S 0 f ilava.com
The Independent Source for Enterprise Java
OnJava.com is a one-stop resource for enterprise Java develop-
ers, featuring news, code recipes, interviews, weblogs, and
O’Reilly brings diverse innovators together to nurture the ideas
that spark revolutionary industries. We specialize in document-
ing the latest tools and systems, translating the innovator’s
knowledge into useful skills for those in the trenches. Visit con-
ferences. oreilly.com for our upcoming events.
9 O’REILLY NETWORK
Safari Bookshelf ( safari.oreilly.com ) is the premier online refer-
ence library for programmers and IT professionals. Conduct
searches 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.
w w w . alii tebooks .com
Killer Game Programming
O REILLY 8
Beijing • Cambridge • Farnham • Koln • Sebastopol • Taipei • Tokyo
w w w . alii tebooks .com
Killer 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 corporate/insti-
tutional sales department: (800) 998-9938 or firstname.lastname@example.org.
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
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
w w w . alii tebooks .com
Table of Contents
1. Why Java for Games Programming? 1
Java Is Too Slow for Games Programming 2
Java Has Memory Leaks 3
Java Is Too High-level 4
Java Application Installation Is a Nightmare 5
Java Isn’t Supported on Games Consoles 5
No One Uses Java to Write Real Games 7
Sun Microsystems Isn’t Interested in Supporting Java Gaming 10
2. An Animation Framework 13
Animation as a Threaded Canvas 14
Adding User Interaction 20
Converting to Active Rendering 21
FPS and Sleeping for Varying Times 22
Sleeping Better 31
FPS and UPS 34
Pausing and Resuming 37
Other Animation Approaches 39
3. Worms in Windows and Applets 46
Preliminary Considerations 47
Class Diagrams for the WormChase Application 48
The Worm-Chasing Application 48
The Game Panel 50
Storing Worm Information 59
w w w . alii tebooks .com
Worm Obstacles 67
Application Timing Results 68
WormChase as an Applet 70
Compilation in J2SE 5.0 73
4. Full-Screen Worms 76
An Almost Full-Screen (AFS) Worm 77
An Undecorated Full-Screen (UFS) Worm 82
A Full-Screen Exclusive Mode (FSEM) Worm 89
Timings at 80 to 85 FPS 103
5. An Introduction to Java Imaging 105
Image Formats 105
The AWT Imaging Model 106
An Overview of Java 2D 110
Buffering an Image 1 13
Managed Images 120
Java 2D Speed 122
Portability and Java 2D 122
6. Image Loading, Visual Effects, and Animation 124
Loading Images 126
Applying Image Effects 134
Displaying Image Sequences 144
Visual Effects for ‘o’ Images 147
Packaging the Application as a JAR 175
7. Introducing Java Sound 178
Applet Playing 178
The AudioClip Class 179
The Sound Player 182
The Java Sound API 185
Sampled Audio 185
Java Sound API Compared with JMF and JOAL 202
Java Sound API Resources 202
Audio Resources 204
vi | Table of Contents
w w w . alii tebooks .com
8. Loading and Playing Sounds 205
Loader Design and Implementation Issues 207
Testing the Loaders 209
The Sounds Panel 213
The Clips Loader 214
Storing Clip Information 216
The Midi Sequences Loader 219
Storing Midi Information 223
LoadersTests as a JAR File 225
9. Audio Effects 226
Audio Effects on Sampled Audio 226
Audio Effects on MIDI Sequences 236
10. Audio Synthesis 249
Sampled Audio Synthesis 249
MIDI Synthesis 255
Audio Synthesis Libraries 268
11. Sprites 270
Bats, Balls, and Sprites 270
Class Diagrams for BugRunner 272
The Bug Starts Running 273
The Animation Framework 274
Defining a Sprite 279
Coding a Sprite 280
Specifying a Sprite with a Statechart 284
The Ball Sprite 287
Defining the Bat 293
12. A Side-Scroller 298
JumpingJack in Layers 299
Class Diagrams for JumpingJack 300
Start Jack Jumping 303
The Animation Framework 303
Managing the Ribbons 3 13
Wraparound Ribbons 314
Managing the Bricks 320
Storing Brick Information 333
Table of Contents | vii
w w w . alii tebooks .com
The Fireball 334
The Jumping Sprite 336
Other Side-Scroller Examples 343
Tiling Software 344
13. An Isometric Tile Game 345
Isometric Tiles 346
Class Diagrams for AlienTiles 350
The Animation Framework 352
Managing the World 356
Managing Worldltems 363
The Tile Occupier 366
A Sprite on a Tile 368
The Player Sprite 370
The Alien Sprite 373
The Quadrant-Based Alien Sprite 376
The A* -Based Alien Sprite 378
Storing Tile Details 383
Further Reading 384
14. Introducing Java 3D 387
Java 3D 387
Java 3D Strengths 392
Criticisms of Java 3D for Games Programming 394
Alternatives to Java 3D 402
15. A 3D Checkerboard: Checkers3D 407
Class Diagrams for Checkers3D 408
Integrating Java 3D and Swing 409
Scene Graph Creation 410
Floating Spheres 413
The Floor 415
Viewer Positioning 419
Viewer Movement 420
Viewing the Scene Graph 421
16. Loading and Manipulating External Models 424
An Overview of LoaderInfo3D 426
Loaders in Java 3D 428
viii | Table of Contents
w w w . alii tebooks .com
Displaying a Model 430
Examining a Model’s Scene Graph 433
Adjusting a Model’s Shape Attributes 435
An Overview of Loader3D 444
Using Loader3D 446
Creating the Scene 449
Managing the Model 450
Building the Model’s Scene Graph 45 1
17. Using a Lathe to Make Shapes 459
Class Diagrams for Lathe3D 461
Creating the Scene 462
The Lathe Curve 468
The Lathe Shape 474
Subclassing the Lathe Shape 482
18. 3D Sprites 487
Class Diagrams for Tour3D 488
Creating the Scene 489
The Basic 3D Sprite 495
The User’s Touring Sprite 500
The Alien Sprite 500
Behaviors in Java 3D 502
Controlling the Touring Sprite 504
Updating the Alien Sprite 510
19. Animated 3D Sprites 512
Class Diagrams for AnimTour3D 513
Creating the Scene 514
The Animated 3D Sprite 515
Controlling the Sprite 520
Animating the Sprite 520
Full-Screen Exclusive Mode (FSEM) 525
A Full-Screen Version of the Application 525
Pros and Cons of Keyframe Animation 530
20. An Articulated, Moveable Figure 531
The Articulated Figure Application 531
Forward and Inverse Kinematics 535
Table of Contents | ix
Class Diagrams for Mover3D
Creating the Scene
Processing User Input
The Commands Panel
Making and Moving the Figure
Modeling a Limb
Moving a Limb
Other Articulated Figures
Articulation and Mesh Deformation
Articulation and Skinning
Articulation and Morphing
Particle Systems in Java 3D
Class Diagrams for Particles3D
Creating the Scene
A Fountain of Points
A Fountain of Lines
A Fountain of Quads
More Particle Systems
Other Java 3D Approaches
Non-Java 3D Approaches
A Flocking Application
Types of Boids
Grouping the Boids
Shooting a Gun
Class Diagrams for Shooter3D
The Sound of Shooting
Picking Scene Objects
Controlling the Gun
Preparing the Laser Beam
x | Table of Contents
Causing an Explosion
Picking with a Mouse Click
Firing the Beam
More on Picking
A First-Person Shooter
Class Diagrams for FPShooter3D
Setting Up the Target
Positioning and Moving the User’s Viewpoint
Initializing the User’s Viewpoint
Adding an Image to the Viewpoint
Managing the Ammunition
Managing a Laser Beam
Moving the Viewpoint
A 3D Maze
Class Diagrams for Maze3D
Making a Maze Plan
The User Interface
Managing the Maze
Tiling the Floor
The Back Facing Camera
Moving the Viewpoint
The Bird’s-Eye View
Related Approaches to Scene Generation
Class Diagrams for the Fractal Land
Building the Fractal Land
Creating the Landscape
Constructing the Ground
Generating a Fractal Landscape
Responding to Key Presses
Terrain Following and Collision Avoidance
Placing Objects in the Scene
Other Fractal Landscapes
Table of Contents | xi
27. Terrain Generation with Terragen 711
Class Diagrams for Terra3D 712
Scenery Creation 720
Building the Landscape 722
Making 3D Scenery 728
Adding Landscape Walls 731
Creating Ground Cover 734
Moving over the Surface 739
Finding the Surface Height 741
Accelerating Terrain Following 743
More on Terrain Generation 745
28. Trees That Grow 749
Class Diagrams for Trees3D 751
Creating the Scene 752
Building a Tree Limb 755
Executing the Rules 761
Displaying Leaves 764
Comparison with L-Systems 766
29. Networking Basics 769
The Elements of Network Communication 770
The Client/Server Model 776
The Peer-to-Peer Model 778
Client/Server Programming in Java 780
P2P Programming in Java 805
Other Kinds of Java Networking 816
30. Network Chat 817
Threaded TCP Clients and Server 818
UDP Multicasting Clients and a Name Server 824
Clients Using a Servlet as a Server 831
31. A Networked Two-Person Game 844
The Standalone Tic-Tac-Toe Game 846
The Networked Tic-Tac-Toe Game 858
xii | Table of Contents
32. A Networked Virtual Environment 878
Background on NVEs 879
An Overview of NetTour3D 884
Scene Creation on the Client 887
Defining Sprites 888
Local Sprites 890
Watching the Server 893
Server Activities 899
Other Java NVEs 902
A. Installation Using install4j 905
B. Installation Using Java Web Start 921
Table of Contents | xiii
Who Are You?
Yes, you. Sit up straight, and stop slouching. (Don’t you just love this assertive writ-
You’re a programmer who wants to apply your abilities to 2D, 3D, and network
games programming, for entertainment or as the first step in becoming a games
programming 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 need
information 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, because
they’re the coolest. They are hard to code, but this book will get you up to speed on
how to build one.
You don’t want to reinvent the wheel since Java is about abstraction, information hid-
ing, and reuse. That translates into building games with existing libraries/classes/tools.
What This Book Is About
This book describes modern (i.e., fast and efficient) Java programming techniques
for 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 different
approaches to animation.
Several chapters on network games build to an example where users move sprites
around a networked 3D arena.
I focus on J2SE 1.4.2, J2SE 5.0 and Java 3D 1.3.1. Under the hood, Java 3D utilizes
OpenGL or Direct3D, which means that it’ll work on all current versions of Win-
dows, various flavors of Linux and Unix, and the Mac. Java 3D requires no special
graphics hardware and is compatible with all modern graphics cards.
J2SE 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/.
Which Software Versions?
My Java code is designed to compile and run in J2SE 5.0 and J2SE 1.4, which means
that 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) Java
versions. The main areas where I lose out are in the availability of type-safe collections
and 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 Java
3D nanosecond timer instead of nanoTime( ) to achieve the same timing accuracy. In
Chapter 2, 1 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 regularly
updated. I decided to employ Version 1.3.1 since it’s stable and well-documented. In
Chapter 14, 1 talk about Java 3D in more detail.
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 here
along with the source code.
What This Book Is Not About
I’m not going to spend 200 pages explaining classes and objects, inheritance, excep-
tion handling, and threads. Many books do that already. A good Java introduction is
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 fan-
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
xvi | Preface
loaders, and algorithms such as A* pathfinding). Shooting in a 3D world is
described in Chapters 23 and 24, and Chapter 32 explains a simple multiuser 3D
I’ve reduced the quantity of code listings; you won’t find page after page of undocu-
mented code here. The documentation uses modern visual aids, including UML class
diagrams, sequence diagrams, state charts, and 3D scene graphs.
The 3D material concentrates on Java 3D, because it’s a high-level 3D API using a
stable and well-documented scene graph. Java has alternative ways of programming
3D applications, including JOGL, LWJGL, Xith3D, jME OpenMind, and more. I’ll
discuss 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 excit-
ing subject, especially now that a mobile 3D API is available (for example, in the
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 written
several chapters on the API, which can be downloaded from this book’s web site at
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,
• 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, net-
work programming, and two appendixes on installation. The following figures give
more details about each one in a visual way. Each oval is a chapter, and the arrows
show the main dependencies between the chapters. Chapters on a common theme
are grouped inside dotted, rounded gray squares.
Figure P-1 shows the 2D-programming chapters.
Preface | xvii
Figure P-1. 2D -programming chapters
Chapter 1 is a defense of Java for gaming, which Java zealots can happily skip. The
animation 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 these
Chapters 5 and 6 are about imaging, mostly concentrating on Java 2D. Chapter 6 has
three main topics: classes for loading images, visual effects, and animation.
Chapters 7 through 10 are about Java Sound: Chapter 8 develops classes for loading
and playing WAV and MIDI audio, and Chapters 9 and 10 are on sound effects and
A reader who isn’t much interested in visual and audio special effects can probably
skip the latter half of Chapter 6, and all of Chapters 9 and 10. However, the classes
for loading images and audio developed in the first half of Chapter 6 and in
Chapter 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).
The 3D-programming chapters are shown in Figure P-2.
xviii | Preface
w w w . alii tebooks .com
Figure P-2. 3D-programming chapters
Java 3D is introduced in Chapter 14, followed by the Checkers3D example in
Chapter 15; its checkerboard floor, lighting, and background appear in several later
There are five main subtopics covered in the 3D material: models, animation, parti-
cle systems, shooting techniques, and landscape and scenery.
Chapter 16 develops two applications, LoaderInfo3D and Loader3D, which show how
to load and manipulate externally created 3D models. The PropManager class used in
Loader3D is employed in other chapters when an external model is required as part of
the scene. Chapter 17 develops a LatheShape class, which allows complex shapes to
be generated using surface revolution.
A 3D sprite class is described in Chapter 18, leading to a Tour3D application that
allows 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 keyframe
sequences, and Chapter 20 develops an articulated figure whose limbs can be moved
Preface | xix
Particle systems are a widely used technique in 3D games (e.g., for waterfalls, gush-
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 (the
particles) more complex behavioral rules and is often used to animate large groups
such as crowds, soldiers, and flocks of birds.
Lots of games are about shooting things. Chapter 23 shows how to fire a laser beam
from 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 of
The dotted arrow from Chapters 24 to 28 indicates a less pronounced dependency; I
only reuse the code for moving the user’s viewpoint.
Figure P-3 shows the network-programming chapters.
Figure P-3. Network programming chapters
Chapter 29 supplies information on networking fundamentals (e.g., the client/server
and 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/server
model, one employing multicasting, and one chatting with servlets.
Chapter 31 describes a networked version of the FourByFour application, a turn-based
game demo in the Java 3D distribution. It requires a knowledge of Java 3D. Chapter 32
revisits the Tour3D application 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
xx | Preface
advanced issues concerning networked virtual environments (NVEs), of which
NetTour3D is an example.
The appendixes are shown in Figure P-4.
© Sprites (BugRunner) © Checkers3D Example
n k k n
Q Installation using instalHj
Q Installation using JWS
Figure P-4. The appendixes
Appendix A describes install4j, a cross-platform tool for creating native installers
for Java applications. Appendix B is about Java Web Start (JWS), a web-enabled
installer 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 the HDTimer class from Java
3D. Checkers3D, from Chapter 15, is my first Java 3D example.
Conventions Used in This Book
The following typographical conventions are used in this book:
Indicates menu titles, menu options, menu buttons, and keyboard accelerators
(such as Alt and Ctrl).
Indicates new terms, URLs, email addresses, filenames, file extensions, path-
names, directories, and Unix utilities.
Emphasizes important text.
Indicates commands, options, switches, variables, attributes, keys, functions,
types, classes, namespaces, methods, modules, properties, parameters, values,
objects, events, event handlers, XML tags, HTML tags, macros, the contents of
files, and the output from commands.
Preface | xxi
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 in
this book in your programs and documentation. You do not need to contact O’Reilly
for 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 not
require 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. Incorporating a significant amount of
example code from this book into your product’s documentation does require
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 email@example.com.
All the code examples can be downloaded from the book’s web site at http://fivedots.
Comments and Questions
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Flighway North
Sebastopol, CA 95472
(800) 998-9938 (in the United States or Canada)
(707) 829-0515 (international or local)
(707) 829-0104 (fax)
xxii | Preface
O’Reilly maintains a web page for this book that lists errata, examples, and any addi-
tional information. You can access this page at:
To comment or ask technical questions about this book, send email to:
You can also contact me at:
For more information about O’Reilly books, conferences, Resource Centers, and the
O’Reilly Network, see O’Reilly’s web site at:
- .. When you see a Safari® Enabled icon on the cover of your favorite tech-
OMlMI I nology book, it means the book is available online through the O’Reilly
SSI: asaS Network Safari Bookshelf.
Safari offers a solution that’s better than e-books. It’s a virtual library that lets you
easily 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.
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 to
the Land of Nod and viewers worldwide start channel hopping. “Oh my God, I love
you 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 my
back 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 to
Preface [ xxiii
Greetings to the numerous students who have suffered as guinea pigs for various
parts 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 use-
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 few
bug reports. I credit those people at the relevant places in the text.
Finally, my best regards to O’Reilly and my editor Brett McLaughlin and figures
illustrator Chris Reilly, who have knocked this book into better shape. Any remain-
ing rough edges are due to me.
xxiv | Preface
Why Java for Games Programming?
One of my assumptions is that the reader (that’s you) has had an introductory
knowledge of Java, the sort of stuff gleaned from a semester’s course at college. Near
the start of that course, you were probably regaled with Java’s many advantages: an
object-oriented paradigm, cross-platform support, code reuse, ease of development,
tool availability, reliability and stability, good documentation, support from Sun
Microsystems, 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 discuss
Java’s suitability for games programming in terms of the typical misconceptions and
complaints 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 more
direct 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-
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-
Ha* where” language. Things may be changing in this category, as I’ll
A general point about these objections is that they had more validity in the late 1990s
when the language and its libraries were less sophisticated and slower. Java’s user
and developer communities are burgeoning and have produced a plethora of useful
tools, online help, and code examples. The games forums dedicated to Java barely
existed 2 to 3 years ago. Java is a great language for games programming, as I hope
this 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 lan-
guages for games programming.” This argument was valid when Java first appeared
(around 1996) but has become increasingly ridiculous with each new release. Some
figures put JDK 1.0, that first version of the language, at 20 to 40 times slower than
C++. 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 be
good programmers to utilize Java efficiently, but that’s true of any language. Jack
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. The
Hotspot technology introduced in J2SE 1.3 enables the runtime system to identify
crucial 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.5
times 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
ffi,' and compiled.
Swing Is Slow
Swing often comes under attack for being slow. Swing GUI components are created
and controlled from Java, with little OS support; this increases their portability and
makes them more controllable from within a Java program. Speed is supposedly
2 | Chapter 1: Why Java for Games Programming?
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 Win-
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 require
complex 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’t
needed, and mouse and keyboard processing is dealt with by the AWT. The latest
versions of Java offer an efficient full-screen mode by suspending the normal 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 or
software outside of Java. For example, Java 3D passes its rendering tasks down to
OpenGL or DirectX, which may emulate hardware capabilities such as bump map-
ping. Often the performance bottleneck in network games is the network and not the
Java Has Memory Leaks
When C/C++ programmers refer to memory leaks in Java, they probably don’t
understand how Java works. Java doesn’t offer pointer arithmetic; typical C-style
memory 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 by
the program are not being garbage collected. This becomes an issue if the program
keeps creating new objects and requiring more memory, and eventually crashes
when 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.htmI), can help identify code
using excessive amounts of memory.
d 4 ,
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 at
poorly timed intervals, causing the application to halt for seconds as the collector
sweeps 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
Java Has Memory Leaks | 3
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/Iibrary/j-perf06304/. Another possibility is GC Portal (http://
java.sun.com/developer/technicalArticles/Pmgramming/GCPortal / ).
Java Is Too High-level
This complaint is the age-old one of abstraction versus speed and control. The
details of the argument often include the following statements:
1. Java’s use of classes, objects, and inheritance add too much overhead without
enough coding benefit.
2. Java’s machine independence means that low-level, fast operations, e.g., direct
Video RAM I/O are impossible.
Statement 1 ignores the obvious benefits of reusing and extending Java’s large class
library, which includes high-speed I/O, advanced 2D and 3D graphics, and many
networking techniques, from lowly sockets to distributed agents. Also forgotten are
the advantages of object-oriented design, typified by UML, which makes complex,
large, real-world systems more manageable during development, implementation,
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 applica-
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 image
depth. The principal aim of FSEM is to speed up graphics-intensive applications,
such as games.
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 new
game controller API.
An interesting historical observation is that the gaming community used to think
that C and C++ were too high-level for fast, efficient games programming when
compared 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 sup-
ported C, such as RenderWare.
4 [ Chapter 1: Why Java for Games Programming?
w w w . alii tebooks .com
Java Application Installation Is a Nightmare
The naysayers claim that the user needs to be a Java expert to install and execute a
Java application, whereas most game players want to point and click on a few dialog
boxes 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 will
2. Code bloat since even small programs require a 15 MB JRE. Downloading this
can be slow.
3. Frequently changing JVMs make it hard to write code that will work for every
possible version of Java.
4. Nonstandard components are often required — e.g., Java 3D, causing even more
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 a
JAR to get it to start.
7. The JRE is slower to start up compared to a native compiled application.
All these problems
Lire la suite
- 7.65 MB