Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (499)
Games in Android Showcase (118)
games submitted by our members
Games in WIP (567)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
   Home   Help   Search   Login   Register   
  Show Posts
Pages: [1] 2
1  Game Development / Newbie & Debugging Questions / Re: Online high-score list on: 2007-10-26 11:36:28
I'm not exactly how you're writing to the URLStream...

When talking to the server, the 'writing' should be through either GET or POST args (GET are the ones that can be seen in the URL, POST are in the HTTP header).

I'd think Java would throw an exception there  Shocked

Way I'm parsing this, it's trying to write to a URL.  I'm a bit rusty on HTTP's exact format, but I was almost certain it was a one-way street  Wink

What I suggest is either adding the username and score to the GET arguements, or the POST arguements.

You could even do a simple cypher to discourage those that may want to post fake high scores.

Seeing that you already have multiple GET arguements there, I doubt I need to explain them.

I'm not sure how to do an HTTP POST with Java, but I'm sure there's a way somewhere  Smiley
2  Game Development / Networking & Multiplayer / Re: Lagtastic on: 2007-09-22 00:05:05
I'm only resistant for now. When I finish this project, I'll probably attempt one with a non-blocking approach. Then after that I'll probably just adopt some 3rd party code.

I have removed all the serialization and am just sending a String now, havn't tested it yet.

Will this be speed it up or do nothing?
1  
2  
DataOutputStream out = new DataOutputStream(myOtherStream);
out.writeUTF(myStringMessage);


and for reading
1  
2  
BufferedReader reader = new BufferedReader(new DataInputSream(myOtherStreams));
String message = reader.readLine();reader


Will those be faster than reading writing a stream or the same?


Well, for starters: You'll get garbled output using that setup.

DataOutputStream.writeUTF(String) writes 2 bytes for the string's length, then string data.

BufferedReader.readLine() reads in string data until it reachs a newline (potentially never with the current implementation).

If you change the BufferedReader.readLine() to DataInputStream.readUTF(), you'll be fine.

I'm not sure if you get the correct message with (ObjectOutputStream).writeUTF() because I experienced some errors on the beginning of serials with UTF and Strings. You better use writeByte() for Strings. And as well for reading readByte() should behave better, too.
One more word about bytes R/W'ing , try to init a byte array of size 512 "at the most" to get the faster results and to keep the system bus r/w channels sufficiently "fresh" ! There's more on the web about the byte arrays serialization process.

As for this, I think you were looking at the wrong stream  Tongue

But on a different note: Using writeByte() and readByte() instead of writeUTF() and readUTF() might not account for unicode characters that take 2 or more bytes (also, there's a writeBytes() in ObjectOutputStream for writing string bytes, but no readBytes() in ObjectInputStream).

I can't comment on the byte array size as I haven't actually looked into it.
3  Game Development / Networking & Multiplayer / Re: Lagtastic on: 2007-09-21 01:43:30
If you're resist to a 3rd party solution, you may want to move away from serialization.  It's much less efficent then implementing your own object->binary and binary->object algorithms (not to mention it's smaller, would help with the lag you're seeing  Grin).

Also, using binary data over strings would help too.

Look up java.io.DataOutputStream/java.io.DataInputStream.
4  Game Development / Performance Tuning / Re: Unloading/Reloading classes on: 2007-09-20 12:56:38
No, that doesn't put a kink in anything, surely?

1. The OBJECTS created from different classes can all still interact without problems. In fact, the only problems you will see are that newly instantiated objects will fail the "instanceof" check, and that typecasts to the class will typecast to the new version even if the instance is of the old version.

Ok, that they can interact is a relief. 
Now to ask for some clarification (taking part of this from cylab's post as well):
I'm going to be using this system (assuming I can get it to work  Wink) as a way to load different versions of plugins.  All plugins implement one interface, and depending on what functionality they provide, they implement one or more sub-interfaces (that extend the base plugin interface).
Assuming I load the interfaces with the bootstrap classloader, would different instances of the plugin class (loaded by custom classloaders, different instances for each version) still be castable to the plugin interface (and the relevant sub interfaces)?  Or would that cause a ClassCastException?

NB: this is one of my suspicions about autoboxing - surely inserting typecasts in code is not a good idea, generally speaking, in a language where typecasts themselves refer to something dynamic?

2. Just make sure all the classes that you AREN'T changing are visible in both classloaders. This is actually *trivial* because java's default behaviour is to have a chain of classlaoders so that you implement the custom loading for one class and you automaticallly inherit the loading of all other classes without having to write any code for it.

Yes, I was already planning on a custom classloader, so I don't see this being hard to implement.

Or ... I think, maybe (not sure here): you can create a custom classloader that returns a different class object at different times. This requires some mangling of the classloader chain as well, from memory - you need to make sure that the new class you're sending doesn't get cached when you want to replace it with a newer one.

(he says, from distant memories of how he did this last time).

I've certainly done it before, I just can't 100% remember how right now.

Well, if I understand the article correctly, when I want to unload a class, I need to de-reference all instances of classes loaded by a specific classloader, then de-reference the class loader itself.

Then (assuming the JVM actually unloads the classes and doesn't cache), I need wait for the class loader to be GC'd (to prevent caching of the classes), then create a new instance of the class loader and load up a different version of the class file.

At princec:

This is for a chat automaton I'm writing, it's going to be serving as a raid control "bot", so it needs maximum up-time.  I'd rather take the time to implement a complex solution like this, than listen to people whine at me for hours on end for a new version of a plugin crashing the bot and it not being able to work right, rather then being able to revert to an older plugin version  Roll Eyes Grin

:edit: fixed some abysmal spelling :/edit:
5  Game Development / Performance Tuning / Re: Unloading/Reloading classes on: 2007-09-19 23:47:11
So the JVM won't error out at me, I just won't be able to see it with classes loaded by another classloader...

Hrm, that puts a kink in things  Undecided

Thanks for the fast reply princec  Smiley
6  Game Development / Performance Tuning / Unloading/Reloading classes on: 2007-09-19 12:34:10
Ok, I know this is an odd question, but does anyone know if it's possible to unload one version of a class instance, and load a different version of the same class instance?

I've been reading the JLS, and it mentions Class Unloading, however as the JVM gives no guarantees about garbage collection, I'm a little hesitant to try and write code that depends explicitly on it.  This still doesn't get past if it's possible to eventually load 2 different versions of the same class.

Naturally, all instances of the inital version would be de-referenced before attempting to unload the class/classloader (I'd gladly write a custom one to do this Grin).

I'm more worried if the JVM prevents actions like this then the actual version details.


And no, restarting the process isn't an option here  Tongue  Wink
7  Game Development / Newbie & Debugging Questions / Re: OutOfMemoryError, how to catch? on: 2006-12-16 07:13:25
Try something like this:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
try
{
    File f = ....
    ...... //Load file in here
   ......
}
catch (OutOfMemoryError e)
{
    e.printStackTrace();
}
8  Games Center / Showcase / Re: Super Mario Whee on: 2006-08-04 02:55:46
Very nice.  I love the music  Grin.  Also, when a level is generated, if there are blocks over where Mario spawns, he will spawn on top of the blocks.  This means he can spawn off the screen if the top row of blocks is at the top of the screen (happened to me  Roll Eyes).  Still, very good game,
9  Games Center / Archived Projects / Re: JQuest Beta on: 2006-04-20 21:49:46
Ok, I played it a bit more.

A few things: the stats counter at the end doesn't seem to keep track of the number of planets conquered (0 for all in a 1 human vs 7 puters games).  Maybe improve the AI a tad?  They all went for the same 3 planets.
10  Games Center / Archived Projects / Re: JQuest Beta on: 2006-04-20 21:25:25
Looks amusing.

An exception occured after trying to send too many ships, got the error box, then correcting it to a valid number of ships.

Have fun:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at GameLogic.getShipCount(GameLogic.java:116)
        at GameLogic.actionPerformed(GameLogic.java:107)
        at javax.swing.JTextField.fireActionPerformed(JTextField.java:487)
        at javax.swing.JTextField.postActionEvent(JTextField.java:675)
        at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:7
90)
        at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1633)
        at javax.swing.JComponent.processKeyBinding(JComponent.java:2866)
        at javax.swing.JComponent.processKeyBindings(JComponent.java:2901)
        at javax.swing.JComponent.processKeyEvent(JComponent.java:2829)
        at java.awt.Component.processEvent(Component.java:5734)
        at java.awt.Container.processEvent(Container.java:1960)
        at java.awt.Component.dispatchEventImpl(Component.java:4365)
        at java.awt.Container.dispatchEventImpl(Container.java:2018)
        at java.awt.Component.dispatchEvent(Component.java:4195)
        at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.ja
va:1828)
        at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboard
FocusManager.java:693)
        at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeybo
ardFocusManager.java:952)
        at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeybo
ardFocusManager.java:824)
        at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFoc
usManager.java:657)
        at java.awt.Component.dispatchEventImpl(Component.java:4237)
        at java.awt.Container.dispatchEventImpl(Container.java:2018)
        at java.awt.Window.dispatchEventImpl(Window.java:2300)
        at java.awt.Component.dispatchEvent(Component.java:4195)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre
ad.java:273)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
java:183)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
ad.java:173)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)

        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)

        at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
11  Java Game APIs & Engines / Java 2D / Re: Copying (for the purpose of pre processed rotation) BufferedImages on: 2006-03-31 20:42:08
Took me 3 weeks to figure that out on my own  Roll Eyes

Anyways, good luck with your you project  Smiley
12  Java Game APIs & Engines / Java 2D / Re: Copying (for the purpose of pre processed rotation) BufferedImages on: 2006-03-31 03:28:55
I do something similar to what you're trying to do in a game I wrote.

Here's my rotation method (it returns a new BufferedImage for whatever rotation it is at):

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
public BufferedImage rotateImg(double theta)
    {
        BufferedImage ret = new BufferedImage(base.getWidth(), base.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE);
       
        Graphics2D bg = ret.createGraphics(); //Get the graphics
       
        AffineTransform s1 = AffineTransform.getRotateInstance(theta, ret.getWidth() / 2.0, ret.getHeight() / 2.0); //Get a transform to rotate the image
       
        bg.drawImage(base, s1, null); //Draw the image
       
        return ret;
    }


base is the image already loaded, theta is the amount to rotate the image (in radians, not degrees).

Looking between my code and your code, it seems that you aren't centering the origin you rotate about.  So it's rotating about the point (0, 0) when you want it to rotate about the poitn (50, 50).  Effectively it rotates however much 90 radians is, and that probably isn't in the range of your image.

And about the image type, the types don't have to be the same, the image data will be converted to the appropriate type.  It's just faster if they're the same.

Hope this solves your dilemma  Grin
13  Games Center / Archived Projects / Re: Stendhal: a free open source multiplayer adventures games on: 2006-03-25 20:25:31
Ok.  Makes sense, good strategy Smiley
14  Games Center / Archived Projects / Re: Stendhal: a free open source multiplayer adventures games on: 2006-03-24 23:57:22
Yes, I noticed the in development part.  Kinda plastered all over the page Tongue

Anyways, it looks really nice (I like the zelda graphics  Wink).  What really killed it for me was that I couldn't even move without the server verifying it.  Occasionally it'd take up to 5 seconds to move, and by then I'd have moved waaaay past where I wanted to go   Undecided

If you could get walking such that I can walk on a laggy connection, I'd be more than happy to play.  I'd love to actually Smiley

Just a suggestion that occured to me:  Maybe you could display the walking on the client side (two different sets of vars, one local (desired), and one from server (actual)), but keep the current turn system.  That way the player could gauge where he/she is (the desired would be shown until the actual are recieved back from the server), and know when to stop pushing the forward button.  I don't know how this would fit in with your current setup, because I haven't had much time to look over the engine, so just approach it as a suggestion.

Anyways, it looks great, and could be pretty fun to play Smiley
15  Games Center / Archived Projects / Re: Stendhal: a free open source multiplayer adventures games on: 2006-03-24 20:49:46
Looks pretty kewl from the screenshots.  Can't really play it (at skool...  Undecided)  I'll try it at home.
16  Game Development / Networking & Multiplayer / Re: Peer to Peer game networks on: 2006-03-08 06:02:20
Sounds cool.  I'll read (as much of it as I can) tomorrow during class.  Wink
17  Game Development / Newbie & Debugging Questions / Re: Component.setSize() : Borked? on: 2006-03-02 05:44:56
Ok, well I managed to find a way to fix it.

I headed back into the javadocs and found this cool little method validate().  I snuck that in before the repaint() and after the setSize(newWidth, newHeight), and now it works perfectly  Grin  Cool
18  Game Development / Newbie & Debugging Questions / Component.setSize() : Borked? on: 2006-03-02 05:23:14
Ok, so some background info before I get into my dilemma: I'm writing a game in Swing (stupid move, I know, however it's working well and I don't feel like moving it AWT).  It's contained in a JFrame window (not fullscreen).  I'm using Java 1.5 on Windows XP.

Now to my dilemma:

I have an option to resize the window to either a larger or a smaller size.  When I recieve the event to resize the window (I generate it through a custom UI), I use the code:

1  
2  
3  
frame.setSize(newWidth, newHeight);
setSize(newWidth, newHeight);
repaint();


Where frame = top level JFrame for my game.

This code has a tendency to not work.

It resizes the window, however does not paint/resize the component (I'm not sure which, only the part of the component which was visible before is painted after being resized).  I can force it to display the component/my game by resizing the window with the cursor, or by minimizing/restoring it.

When I initally create the window I use the following code:

1  
2  
3  
4  
5  
f.setVisible(true);

Insets i = f.getInsets(); //Get the window borders

f.setSize(Preferences.WIDTH + i.left + i.right, Preferences.HEIGHT + i.top + i.bottom); //Set to the size so that the entire playfield is shown


I have to show the window before I determine it's size so I can get the Insets (instead of useless garbage).  When I first start up my game, the window is resized to the proper size, however the component inside isn't.

I have tried adding a frame.pack() in the first code segment before the repaint() (I have also tried using frame.repaint()), however the pack() statement completely discards the size I give it and sets it to a little box (I think the minimum window size in XP).

I have looked/tried to use setMinimumSize() and setMaximumSize(), and wasn't able to get any results (well, actually, lack of change would be more accurate...  Undecided)

If someone could tell me what I've missed here, I would greatly appreciate it.

Also, I tried this exact code on 1.6, and it worked perfectly.  The javadocs mention no change in those methods from 1.5 to 1.6 (at least not that I could find).
19  Java Game APIs & Engines / Java 2D / Re: Using GIF animations on: 2006-01-17 20:56:04
I've had .gif's animate by loading them via ImageIcon.

I also had the component that drew the image (a JPanel) implement ImageObserver, and passed it to Graphics.drawImage() when drawing the ImageIcon.
20  Java Game APIs & Engines / Tools Discussion / Re: What 2D graphics packages are you using? on: 2006-01-17 20:43:55
GIMP 2.2  Grin

And mspaint.exe  Roll Eyes

I figure that since I already paid for Winsnore, I might as well use the free stuff that comes with it
21  Game Development / Newbie & Debugging Questions / Re: Loading files (images) from a JAR on: 2006-01-11 20:00:43
Well, "PNG" != "png".

Always use lowercase extensions.

I usually do.  Must have been a fluke with the image editing/creation program I was using (it defaults to upper.  I usually remember to change it to lower).  Thanks for pointing that out.  I am running Windows, so I'm used to case-insensitivity.  I'll try changing that when I get to my compiler (at school right now...).
22  Game Development / Newbie & Debugging Questions / Re: Loading files (images) from a JAR on: 2006-01-11 04:06:08
I got:

     0 Tue Jan 10 21:07:06 GMT-07:00 2006 META-INF/
   202 Tue Jan 10 21:07:04 GMT-07:00 2006 META-INF/MANIFEST.MF
     0 Tue Jan 10 20:43:00 GMT-07:00 2006 images/
     0 Tue Jan 10 20:43:00 GMT-07:00 2006 volatileimagetest/
 78425 Mon Jan 09 17:05:24 GMT-07:00 2006 images/img1.PNG
   238 Mon Jan 09 17:06:06 GMT-07:00 2006 images/img2.PNG
  4717 Tue Jan 10 21:07:06 GMT-07:00 2006 volatileimagetest/Form.class
   771 Tue Jan 10 21:07:06 GMT-07:00 2006 volatileimagetest/Main.class
23  Game Development / Newbie & Debugging Questions / Loading files (images) from a JAR on: 2006-01-11 03:48:56
Okay, here goes:

I'm trying to load two images from a .jar file that contains two folders (and the META-INF, but that doesn't matter in this situation), volatileimagetest (where the code is) and images (where the two images are).
When I run the code (below) before it's packaged into a .jar, it runs just fine.  I have two directories, volatileimagetest (where the code is) and images (where the two images are).  The directories are exactly the same as in the .jar, but not in a jar file.

Now I saw on http://weblogs.java.net/blog/chet/archive/2004/08/toolkitbuffered.html that to load images from within a .jar file, I should use the code (slightly modified of course):
1  
2  
URL url = getClass().getResource("/images/img1.png");
BufferedImage img = ImageIO.read(url);


This loads the images when running outside the .jar file.  I printed url to System.out, and got this: "file:/C:/Documents%20and%20Settings/Owner/My%20Documents/Java/VolatileImage/build/classes/images/img1.png".  I feel I should just say the directory volatileimagetest is located in the same directory as images, and contains all class files.

When I run this as a .jar, I get a NullPointException, and I narrowed it down to the line "URL url = getClass().getResource("/images/img1.png");", with getResource() returning null.

Has anyone experienced this, and if so could they please help  Huh
24  Game Development / Performance Tuning / Re: Volatile vs Buffered on: 2006-01-11 03:37:44
Ah.  Now it makes sense  Cheesy

Thanks for the very helpful link  Smiley
25  Game Development / Performance Tuning / Re: Volatile vs Buffered on: 2006-01-10 00:57:03
I just made a slight change to it to see if rendering an image multiple times (the small 20x20 100 times instead of 1) would have an effect.  It does:

Quote
Buffered draw took 159.936807 ms.
Volatile draw took 364.469227 ms.
Volatile was faster by -204.53242 ms.
Total volatile faster by -204.53242 ms.
Buffered draw took 1.946337 ms.
Volatile draw took 10.244318 ms.
Volatile was faster by -8.297981 ms.
Total volatile faster by -212.830401 ms.
Buffered draw took 1.737651 ms.
Volatile draw took 10.188725 ms.
Volatile was faster by -8.451074 ms.
Total volatile faster by -221.281475 ms.
Buffered draw took 1.739048 ms.
Volatile draw took 1.656356 ms.
Volatile was faster by 0.082692 ms.
Total volatile faster by -221.198783 ms.
Buffered draw took 2.647823 ms.
Volatile draw took 1.361904 ms.
Volatile was faster by 1.285919 ms.
Total volatile faster by -219.91286399999998 ms.
Buffered draw took 1.922311 ms.
Volatile draw took 1.377829 ms.
Volatile was faster by 0.544482 ms.
Total volatile faster by -219.368382 ms.
Buffered draw took 2.191898 ms.
Volatile draw took 1.339835 ms.
Volatile was faster by 0.852063 ms.
Total volatile faster by -218.516319 ms.

It seems now that the major time consuming task is copying the image data from the buffered images to the volatile image.
26  Game Development / Performance Tuning / Volatile vs Buffered on: 2006-01-10 00:41:31
I'm writing a small Asteroids clone (Stroids  Cool), and on my first slightly playable build, I noticed that my graphics were lagging something horrible.  So I logged on here, looked around, and noticed that VolatileImage is recommended for doing graphics.  I was using BufferedImage and Graphics.drawImage(buffered, x, y, null), so I thought the volatile might work better.

So I wrote a simple class today and tested it.  And much to my astonishment, BufferedImage is outperforming VolatileImage ( Shocked).  This doesn't make sense except that I have onboard video so there may be some hidden optimization.  What I'm wondering is if anyone can spot something I did wrong in this test.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
public class Form extends JFrame imple....
    ...
    private BufferedImage buffered1;
    private BufferedImage buffered2;
    private VolatileImage volatile1;
    private VolatileImage volatile2;
    private VolatileImage comp;
    private javax.swing.Timer timer;

public Form()
    {
        super();
       
        setSize(800, 800); //This is the same size Stroids uses
       
        setVisible(true);
       
        //Load the buffered images
       try {
            buffered1 = ImageIO.read(new File("img1.png"));
            buffered2 = ImageIO.read(new File("img2.png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        ...

        x = 0; //Initalize the scrolling variables
       y = 0;
        timer = new javax.swing.Timer(30, this); //Create a timer to cause a repaint every 30 ms
       
        timer.start(); //Start the timer
   }

/*
 * One or more of the VolatileImages needs to be re-created, or created the first time
*/

private void restoreVolatiles()
    {
        if (volatile1 == null) //No image
           volatile1 = createVolatileImage(800, 800); //Create the image
       
        if (volatile2 == null) //No image
           volatile2 = createVolatileImage(20, 20); //Create the image
       
        if (comp == null) //No image (used for off-screen rendering)
           comp = createVolatileImage(800, 800); //Create the image
       
        Graphics g;
        if (volatile1.validate(getGraphicsConfiguration()) != VolatileImage.IMAGE_OK) //Not ok, so redraw it
       {
            g = volatile1.getGraphics();
            g.drawImage(buffered1, 0, 0, this);
        }
       
        if (volatile2.validate(getGraphicsConfiguration()) != VolatileImage.IMAGE_OK) //Not ok, so redraw it
       {
            g = volatile2.getGraphics();
            g.drawImage(buffered2, 0, 0, this);
        }
    }

public void paintComponent(Graphics _g2)
    {
        Graphics2D g2 = (Graphics2D)_g2;
       
        long volatileDuration, bufferedDuration; //Used to determine how long rendering takes
       
        long startNano = System.nanoTime(); //Get the start time
       
        if (volatile1 == null || volatile2 == null ||
                volatile1.validate(getGraphicsConfiguration()) != VolatileImage.IMAGE_OK || volatile2.validate(getGraphicsConfiguration()) != VolatileImage.IMAGE_OK)
        { //Check if anything needs to be fixed (always runs on first time through: volatile1 == null)
           restoreVolatiles(); //Restore the volatiles
       }
       
        Graphics2D g = comp.createGraphics(); //Get the graphics to composite it
       
        g.drawImage(volatile1, 0, 0, this); //Draw the background (big, 800x800)
       
        g.drawImage(volatile2, x, y, this); //Draw the random image (small, 20x20)
       
        g2.drawImage(comp, 0, 0, this); //Copy to the screen (big 800x800)
       
        volatileDuration = System.nanoTime() - startNano; //Get the time taken
       
        startNano = System.nanoTime(); //Get the start time
       
        g2.drawImage(buffered1, 0, 0, this); //Draw the background
       
        g2.drawImage(buffered2, x, y, this); //Draw the random image
       
        bufferedDuration = System.nanoTime() - startNano; //Get the end time
       
        //Now print out the stats
       try
        { //writer is initalized in the constructor, and is a FileWriter
           System.out.println("Buffered draw took " + bufferedDuration / 1000000.0 + " ms.");
            writer.write("Buffered draw took " + bufferedDuration / 1000000.0 + " ms.\n");
            System.out.println("Volatile draw took " + volatileDuration / 1000000.0 + " ms.");
            writer.write("Volatile draw took " + volatileDuration / 1000000.0 + " ms.\n");
            System.out.println("Volatile was faster by " + (bufferedDuration - volatileDuration) / 1000000.0 + " ms.");
            writer.write("Volatile was faster by " + (bufferedDuration - volatileDuration) / 1000000.0 + " ms.\n");
           
            writer.flush();
           
        } catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }
}


The file that writer prints to gives this (only an excerpt):

Quote
Buffered draw took 0.058667 ms.
Volatile draw took 0.118451 ms.
Volatile was faster by -0.059784 ms.
Buffered draw took 0.060064 ms.
Volatile draw took 0.111466 ms.
Volatile was faster by -0.051402 ms.
Buffered draw took 0.059225 ms.
Volatile draw took 0.136889 ms.
Volatile was faster by -0.077664 ms.
Buffered draw took 0.059225 ms.
Volatile draw took 0.135213 ms.
Volatile was faster by -0.075988 ms.
Buffered draw took 0.056432 ms.
Volatile draw took 0.143874 ms.
Volatile was faster by -0.087442 ms.
Buffered draw took 0.059784 ms.
Volatile draw took 0.137168 ms.
Volatile was faster by -0.077384 ms.
Buffered draw took 0.062019 ms.
Volatile draw took 0.137168 ms.
Volatile was faster by -0.075149 ms.

I am missing something?  Is my rendering strategy off?  Or do I just need to render many more images per cycle to see the difference?  Huh
27  Game Development / Networking & Multiplayer / Re: Serialization without creating new Objects for the GC on: 2005-11-28 03:24:03
I noticed this thread earlier today, and thought that it may somewhat pertain to this discussion (more about GC and networking than Serialization):

http://www.java-gaming.org/forums/index.php?topic=1107.0

There's 4 chapters about networking an application, and and appedix on GC (letter C).

Just thought this may inspire a different approach, or get a better insight about GC.  Wink
28  Game Development / Shared Code / Re: Java 3D Games Programming Chapters online on: 2005-11-28 00:57:15
Great book!!!  Thanks for posting it online too!  Cheesy

Btw, the URL for HPjtune has moved.  Now it's http://www.hp.com/products1/unix/java/java2/hpjtune/index.html
29  Game Development / Networking & Multiplayer / Fixed it on: 2005-11-26 22:54:04
Nevermind, I figured out what was happening wrong.  In the method where I add a ByteBuffer to the outgoing queue, I flipped the buffer to record the length in the first 4 bytes, then FLIPPED it again to get back to the start.  That second flip made NIO see my buffer as 4 bytes long instead of however long it really was.  I just switched the method call from a .flip() to a .rewind() and it works beautifully now (turns out NIO DOES buffer un-read data for TCP socket channels).  Roll Eyes
30  Game Development / Networking & Multiplayer / What happens when not all data is read from a NIO.SocketChannel? on: 2005-11-26 04:34:53
I just wrote some code to try and implement a simple packet protocol using NIO.SocketChannel.  I'm having trouble with reading data from the channels though.   What I'm doing is reading in a certain number of bytes which form the header of my protocol during one selectNow() operation.  I do this so I can create a new ByteBuffer with the exact size of the packet.  That part works great.  But then I never get another SelectionKey.isReadable() event from any future selectNow() operations.  It's like NIO just discards the rest of the data.  Does anyone know why this would happen, or if there is a way to get the Selector to fire off another SelectionKey.isReadable() event?

Here's my code (trimmed down to the vital stuff):

Snippet from SMLIOManager (the class that contains the Selector and lets the SMLIOSocketPacket classes know when their SelectionKeys are ready):
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
/*
 * This is where the selector is checked for readiness
 */

void fire()
{
   //The timer has fired, so check for I/O readiness
  selector.selectedKeys().clear(); //Make sure the set is cleared
  try
   {
      selector.selectNow(); //Fill the set with ready keys
  }
   catch (Exception e) //Some not so nice happened, so log it
  {
      LogManager.getLogManager().getLogger("sml.io").info("Exception in SMLIOManager.fire: " + e);
   }
   Iterator i = selector.selectedKeys().iterator(); //Get an iterator
 
   if (selector.selectedKeys().size() > 0) //Log how many keys are ready (if there are any ready)
     LogManager.getLogManager().getLogger("sml.io").finer("SMLIOManager.fire.selector.selectNow returned " +
         selector.selectedKeys().size() + " of "
         selector.keys().size() + " keys.");
   
   while (i.hasNext()) //Go through all the keys in the set
  {
      SelectionKey key = (SelectionKey)i.next(); //Get the next SelectionKey
     
      ((SMLIO)key.attachment()).stateReady(); //Tell the protocol manager that there is some I/O readiness, and to process it
  }
}


Snippet from SMLIOSocketPacket (the class that implements the protocol) (and extends SMLIO)
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
void stateReady()
{
   LogManager.getLogManager().getLogger("sml.io").info(name + " entered stateReady"); //Log entrance into the method
 
   SocketChannel chan = (SocketChannel)key.channel(); //Get the channel
 
   if (key.isWritable()) //Is writable, so write as much as possible
  {
      LogManager.getLogManager().getLogger("sml.io").info(name + ".key.isWritable"); //Log is writable
     try
      {
         ByteBuffer out = (ByteBuffer)outQueue.getFirst(); //Get the first buffer in the queue of outgoing buffers
       
         if (out.position() == out.limit()) //Reached the end of the buffer
        {
            outQueue.removeFirst(); //Remove the buffer
           
            if (outQueue.size() > 0) //More buffers left in the queue, so use the next one
           {
               out = (ByteBuffer)outQueue.getFirst();
            }
            else //No more left
           {
               key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE); //Say we don't want to write anymore
              out = null; //Prevent errors
           }
         }
         
         if (out != null) //If the buffer exists
        {
            chan.write(out); //Write the buffer
        }
      }
      catch (Exception e) //Something happened :(
     {
         LogManager.getLogManager().getLogger("sml.io").info(name + ".stateReady: " + e);
      }
   }
   
   if (key.isReadable()) //Is readable, so read in as much as possible
  {
      LogManager.getLogManager().getLogger("sml.io").info(name + ".key.isReadable"); //Log readability
     try
      {
         if (inBuff.position() == inBuff.limit()) //The buffer has been filled, so act appropriately
        {
            if (isHeader == true) //A header, so process it
           {
               inBuff.flip(); //Flip it to read the header
             
               int len = inBuff.getInt(); //Get the length of the packet
             
               inBuff = ByteBuffer.allocate(len); //Make a buffer to hold the packet
             
               isHeader = false; //Not a header any more
           }
            else //The data itself
           {
               listener.recieveInput(inBuff, this); //Dispatch this packet (this is implemented in an outside class, but is yet to be called in pratice :( )
             
               inBuff = ByteBuffer.allocate(HEADER_LEN); //Make a buffer to hold the header
             
               isHeader = true; //Now a header
           }
         }
         
         int val = chan.read(inBuff); //Read as much as we can (non-blocking)
       
         LogManager.getLogManager().getLogger("sml.io").info(name + " read " + val + " bytes of data."); //Log how much has been written
     }
      catch (Exception e) //Something happened :(
     {
         LogManager.getLogManager().getLogger("sml.io").info("Exception in " + name + ".stateReady: " + e);
      }
   }
}


Looking at my log file, I noticed that only 1 "name read XXX bytes of data." is recorded, and it was the size of the header.  Also, there was only 1 "name.key.isReadable" in the log file as well.

Any suggestions?Huh[size=10pt][/size]
Pages: [1] 2
 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Pippogeek (39 views)
2014-09-24 16:13:29

Pippogeek (30 views)
2014-09-24 16:12:22

Pippogeek (19 views)
2014-09-24 16:12:06

Grunnt (44 views)
2014-09-23 14:38:19

radar3301 (27 views)
2014-09-21 23:33:17

BurntPizza (62 views)
2014-09-21 02:42:18

BurntPizza (32 views)
2014-09-21 01:30:30

moogie (39 views)
2014-09-21 00:26:15

UprightPath (50 views)
2014-09-20 20:14:06

BurntPizza (54 views)
2014-09-19 03:14:18
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!