Вы находитесь на странице: 1из 2

03 01 2013

Payla

Game Programming Snippets: How to use BufferStrategy in Java


0

Dier

Sonraki Blog

Blog Olutur

Giri Yapn

Game Programming Snippets


Place to find helpful snippets of code to use in making your own games.
CATEGORIES

Animation
Timed Animation

Graphics
Toggle Fullscreen Mode Fullscreen & ScreenModes in Jav a Games Double Buffering and Timed Rendering Draw ing an Image How to use BufferStrategy in Jav a

Input
Keyboad Polling

Code Structure
Resource Manager Game State Machine

Collision Detection
Bounding Box Collision Detection

Movement
THURSDAY, OCTOBER 14, 2010
Basic Character Mov ement Character 8-Directional Mov ement Angular Character Mov ement Enhancment: Smoother Mov ement 2D Vector

How to use BufferStrategy in Java


One of the things I didn't know when starting Java programming was the state of the hardware acceleration support. Java does provide hardware acceleration. In earlier version the double buffering was a bit buggy but since jre6 it works very well in swing. It also uses DirectX and Opengl under the hood which you can enable/disable. Hardware accelerated drawing is enabled by default on most systems where it is properly installed. To take advantage of this hardware acceleration you want to use a java.awt.Canvas component. You can let swing do the double buffering which entails simply repainting the screen and not worrying about using the BufferStrategy class. It seems to perform well, so you should test both methods out and see which works best for you. In this snippet I will not mix swing and awt so I use a Frame instead of a JFrame. I noticed from an early access release of jdk7 that if you use a Canvas component inside a JFrame nothing will draw, unlike jre6 and below where it doesn't present an issue. I do not know whether this is intentional to try and keep native resources and lightweight resource from conflicting or some other such implementation detail but it did cause me a headache for a little while. VSync Improving Visuals or Triple Buffering This is a minor annoyance when running in windowed mode for a game. Occasionally the display and the drawing of the window will become out of sync and cause some tearing or jittering of the constantly refreshing window. It happens due to not being able to refresh the window contents at the exact same rate the display is actually refreshing the entire screen. This isn't too noticeable with such high refresh rates on monitors, but just in case you need to be able to do this, there is a function. I didn't really know about it till recently, it's in the java.awt.Toolkit called sync(). You can also create a buffer strategy with 3 buffers, or triple buffering, which is known to almost eliminate the need for the sync so that your program isn't in the middle of drawing to the buffer while the display is drawing from the buffer. EDIT: Use java.awt.Toolkit called sync() to update the display buffer (whatever that really is) to be the most current drawing surface in the buffer strategy. Should help ensure the user sees the latest and greatest from the application. Other Useful Options A number of different options are also available as System Properties for java2d. For instance the trace property which tells you how long and specifically which drawing functions are called. This will let you know whether the hardware acceleration drawing layer in Java is being called at all. java -Dsun.java2d.trace=log Setting System Properties in the code A nice thing to be able to do is to use a configuration file loaded by your program to save/load these types of graphics options or other kinds of options that your program may allow the user to change but are used by the Java API before the application starts. I like to use static initialization blocks for this. So I will have something like the following in my main class. / efrac etns 1/ promnestig. 2 ttc 3sai { Sse.ePoet(snjv2.rnacl,"re) ytmstrpry"u.aadtasce" Tu"; 4 / Sse.ePoet(snjv2.rc" "ietm,o,on"; / ytmstrpry"u.aadtae, tmsaplgcut) 5 6 / Sse.ePoet(snjv2.pnl,"re) / ytmstrpry"u.aadoeg" Tu"; 7 Sse.ePoet(snjv2.3" "re) ytmstrpry"u.aaddd, Tu"; 8 Sse.ePoet(snjv2.docva" "re) ytmstrpry"u.aaddfrerm, Tu"; 9

Maps
Rendering Basic Tiled Maps Rendering Multi-layered Maps Scrolling Multi-layered Map

Jogl
Draw ing HTML w ith JOGL Part 1: Textures Draw ing HTML w ith JOGL Part 2: JComponent Jogl: Texture Transparency

Miscellaneous
Jav a Anti-Aliasing

POPULAR POSTS

Keyboard Input: Polling System In Java When I first started game programming and well into about 4 years of it. I always wondered the reason for wanting to use a polling system fo... How to use BufferStrategy in Java One of the things I didn't know when starting Java programming was the state of the hardware acceleration support. Java does provide hardwar... Toggle Fullscreen Mode Purpose To show how you can switch a window between being windowed and fullscreen with the press of a button. Diving Right In Ok, so ...

FOLLOWERS

Join this site


w ith Google Friend Connect

Members (4)

Already a member? Sign in

BLOGGERS UNITED

gpsnippets.blogspot.com/2010/10/how-to-use-bufferstrategy-in-java.html

1/4

03 01 2013
}

Game Programming Snippets: How to use BufferStrategy in Java


Quad-Core ARM Computer
www.torade x .com /e m be dde d-m odule s Dual Displ 3D-Graphic&Vide o 1GB R AM 2GB FLASH, from 89 - 125$

You can set it up however you like and even get complex with it, loading the settings from a config file like I mentioned above, or popup a nice little window with selectable options for d3d versus opengl. The trace line specifies the format of all output from java2d as described in the system properties link. Using BufferStrategy Use the createBufferStrategy(int numBuffers) in the canvas component only after the frame has been created and displayed. You can control how many buffers to use for rendering, the most I'd suggest would be 3 any more than that is overkill, imho. Creation of the strategy may cause a java.lang.IllegalStateException to be thrown if the canvas does not have a parent who is being displayed. Meaning you need to add the Canvas component to a Container and make sure that container is visible. / cet asrtg ta ue tobfes o i dul bfee. / rae taey ht ss w ufr, r s obe ufrd 1 ti.raeufrtaey2; hscetBfeSrtg() 2 3 / gtarfrnet tesrtg ojc,fruei orrne / e eeec o h taey bet o s n u edr 4 mto ehd 5 / ti intncsaybti eiiae acl drn rneig / hs s' eesr u t lmnts al uig edrn. 6 srtg =ti.eBfeSrtg(; taey hsgtufrtaey) To use the BufferStrategy for rendering you want to use the strategy's getDrawGraphics and show methods. The getDrawGraphics creates a Graphics2D object that will draw to one of the buffers, if you are using 2 or more buffers this will be an offscreen buffer, allowing you to draw everything completely before displaying it which eliminates flickering and allows you to clear the buffer without the user noticing, and being able to redraw everything. Clearing and redrawing is essential for animation as you want to redraw the entire screen when objects move or change. Example drawing code from the snippet: / tebc bfe gahc ojc / h ak ufr rpis bet Gahc2 bG=(rpisD srtg.eDaGahc(; rpisD k Gahc2) taeygtrwrpis) 1 2 / certebcbfe,ti cudb sbtttdfrabcgon / la h akufr hs ol e usiue o akrud 3 / iaeo atldbcgon. / mg r ie akrud 4 bGstan(akrudrdet; k.ePitbcgonGain) 5 bGflRc(,0 gtit(,gtegt); k.ilet0 , eWdh) eHih() 6 7 / TD:Da yu gm wrd o seeo ayhn es hr. / OO rw or ae ol, r cn r ntig le ee 8 9 / etnl2 s hp ucas n h rpis bet a 10 / R c a g e D i a s a e s b l s , a d t e g a h c o j c c n edr 11 r n e 12 / i , m k s t i g a l t l e s e . / t ae hns ite air 13 b G s t o o ( o o . r e . a k r ) ; k.eClrClrgendre() 14 b G f l ( a i B o k ; k.ilbsclc) 15 16 / p o e l d s o e o t e b c b f e g a h c o j c . R l a e / rpry ips f h akufr rpis bet ees 17 r s u c s eore 18 / a d c e n p / n lau. 19 b G d s o e ) k.ips(; 20 21 / fi/rwtebcbfe t tecna cmoet / lpda h akufr o h avs opnn. 22 srtg.hw) taeyso(; 23 24 / snhoiewt tedslyrfehrt. / ycrnz ih h ipa ers ae ToktgtealTokt)sn(; oli.eDfutoli(.yc) Precision and high frame rates To make a good game you really do not need more than 60 frames per second. There is a lot of discussion about the subject and many say that the human eye will always be able to see screen refreshes. I think that it has nothing to do with the frame rate as much as with the movement and update timing. As long as the animation in your game is smooth without noticeable and often glitches then it will still be professional. You can always try and aim for a higher frame rate I think I have seen suggestions about around 100fps and I don't know why it's that number, jumping from either 30 to 60 and then all the way to 100. That's 1 frame every 10 milliseconds. While you can do a lot in 10 milliseconds there is a lot you can't do, so find what works best for your game and try and keep the amount objects moved every frame to change at a steady rate relative to their speed. So if an object is moving really fast across the screen small fluctuations in the rate of change in position every frame will cause jittery and jerky movement. For this snippet I will not show the particulars of creating smooth movement that is for later snippets, where I will go through different kinds of movement. So at long last here it is: BufferStrategySnippet.java
Posted by MorbidMorvick at 8:00 AM

BLOG ARCHIVE

2012 (10) 2011 (18) 2010 (17) December (1) November (3) October (5) Morning Coffee: Fun Projects Angular Character Movement Character 8-Directional Movement Basic character movement How to use BufferStrategy in Java August (1) July (1) June (1) April (2) March (1) January (2) 2009 (4) 2008 (20) 2007 (7)

RECOMMENDED BLOGS

Chevy Ray Johnston


Common Questions, Answ ered 2 months ago

Coke and Code


Learning to make Game Art 10 months ago

SUBSCRIBE TO

Posts

PAGES

Home Examples Game Design

0
Recommend 0

gpsnippets.blogspot.com/2010/10/how-to-use-bufferstrategy-in-java.html

2/4

Вам также может понравиться