Saturday, June 28, 2008

Loading Images From a Jar File

Something Cool To Do With Jar Files

It's pretty simple really, of course there are a few ways to do it. I have seen it done in the following way.
someclass.getClass().getClassLoader().
     getResource(myResourceFileName);
I have had a lot of problems with this type of loading and I prefer a more direct approach which many people don't either know about or care to recommend for one reason or another. Here is how I tend to load images:
private Image fetchImage( String path ) {
  try {
   URL imgUrl = 
    new URL("jar:"+getJarPath()+"!"+path);
   return (new ImageIcon(imgUrl)).getImage();
  } catch (MalformedURLException e) {
   e.printStackTrace();
   
  }
  return null;
 }
The main thing to note here is simply the "jar:" prefix to the jar file path string and the "!" suffix which indicates that anything after it is a location within the jar file itself.

Note: To get to subdirectories the path string must be something like this "/data/images/myimage.png". Therefore the entire URL would look something like the following: "jar:file:/C:MyProject/LoadingFromAJar/myJar.jar!/data/images/myimage.png"

The only downfall to using this method is that it requires you to know the name of the jar file that the image is within. The plus side to this is that your images can be located in any number of subdirectories within the jar file you can package all the contents of your jar file into separate directories without worrying about where they are located or if the Class Loader can find them or not.

Standalone versus Applets

So now that you can load resources from within a Jar file at runtime how can we make it easier to get the location of the Jar file because we need a complete and valid URL which means no relative paths.

So there are two situations we must account for separately. One is a jar file run using the command line or auto-executed as a standalone local application. For this we simply use a File instance:
String myJarFilePath = (new File("")).toURI().toURL().toExternalForm() + "MyJarFile.jar";
This works perfectly fine if you are running the jar file locally but in an Applet you will get a Security exception since you are not allowed to instantiate File class instances. But the Applet class gives you a way to determine the path.
String myJarFilePath = getCodeBase() + "MyJarFile.jar";
The above will only work in an Applet if it is done within or after the Applets init() method is called.

Package this all up into a nice ResourceManager and viola working code that you will never have to touch again and can reuse in any project at anytime. I will post a simple ImageManager class example for your use very soon.

Thursday, June 26, 2008

Building Your Own Image Loader

Images Needed
When programming games images are one of the things that just comes pretty standard. Whether its textures for 3D models, 2D background images, or even sprite sheets. There are a variety of formats for image files here are just a few, jpg (jpeg), gif, tga, pcx, png, and bmp. Some of the formats are compressed jpg & gif for example but their compression comes at the cost of accuracy. If you save an image in paint in either of these formats then reopen it you will see that the pixels color changed slightly. The bmp format or bitmap is uncompressed thus taking up a lot of space. The best format for both accuracy and compression is png. So for pretty much any graphics in game programming they tend to be used more often then not. Another nicety is pngs support an alpha channel useful for not fully transparent images.

Common ways of Loading Images
The most common way that I've seen to load images in Java is by using ImageIcon. It was also the first that I learned. It's very simple.
//substitute myImagePath for the relative or absolute path and file name
Image img = (new ImageIcon(myImagePath)).getImage();
AWT Toolkit provides another way of loading images
//substitute myImagePath for the relative or absolute path and file name
java.awt.Toolkit awtkit = Toolkit.getDefaultToolkit();

//this method might cause memory issues
Image img = awtkit.getImage(myImagePath);
//recommended to use this instead.
img = awtkit.createImage(myImagePath);
These two methods are about all you really need to load images. But both of these methods do not load BufferedImages but rather only images. I believe they are VolitileImages.

There is a third alternative for image loading javax.imageio package contains a ImageIO class that can be used to load BufferedImages.
//Load a buffered image.
BufferedImage bImg = ImageIO.read(myImagePath);
This class is useful because it provides a means of loading a buffered image. The use for a buffered image is that it provides a way to extract parts of the image itself as separate images which is very useful for sprite sheets and tilesets.


The Loader
The basics of a loader is to hold on to images that are currently loaded. There are many advantages to using an image loader. You can detect when an OutOfMemoryError occurs and release existing images to free memory. You can load arrays of BufferedImages or whole directories even load all resources in a given directory and its subdirectories.

One of the extremely useful things about a loader is you can configure it to load images from inside a jar file. Which I will explain how to do later?

Monday, June 23, 2008

Car Smoke trails using Particle Effects

I've been working on a Particle Effects engine during the last week or so and the results turned out quiet nice so far. It took a lot of tweaking and using some hacked together physics for the car movement but overall I think it is good enough to show off a little.

I'll be cleaning up the Particle Engine code and making a post explaining how to go about creating your own particle effects engine as well as providing a sample engine for people to work from.

You'll need at least Java 5 plugin for your browser in order to view the applet. Click on the applet and use the right and left arrow keys to move the car respectively. The responsiveness of the car isn't very good but it demonstrates a use for the particle effect.

Friday, June 13, 2008

Particle Effects

So I decided to fiddle around with Particle Effects and came up with a simple demo drawing simple spheres to the screen. The idea of a good Particle Effects engine is to be efficient and to not bog down imperative rendering operations.

You don't want your sprite animation to suffer speed slow downs because of your particle effects. You would rather want the particle effects engine to scale to meet the load requirements of your game.

I created a simple particle emitter for prototyping purposes. I packaged it into an applet so that I can embed it in this post. Speeds will differ depending on your browsers performance and CPU, graphics card, etc...


Get the latest version of java to see this applet Sun Java


Right now its just a simple demo that I hope to expand and integrate into the 2D engine that I have been developing.