LWJGL 2 - Lightweight Java Game Library
Other Articles in the Series
· Lesson 1: Single Static Source
· Lesson 2: Looping and Fade-away
· Lesson 3: Multiple Sources
· Lesson 4: A Closer Look at ALC
· Lesson 5: Sources Sharing Buffers
· Lesson 6: Advanced Loading and Error Handles
· Lesson 7: The Doppler Effect

Advanced Loading and Error Handles: Lesson 6

Author: Jesse Maurais | From: devmaster.net
Modified for LWJGL by: Brian Matzon

We've been doing some pretty simple stuff up until now that didn't require us to be very precise in the way we've handled things. The reason for this is that we have been writing code for simplicity in order to learn easier, rather that for robustness. Since we are going to move into some advanced stuff soon we will take some time to learn the proper ways. Most importantly we will learn a more advanced way of handling errors. We will also reorganize the way we have been loading audio data. There wasn't anything wrong with our methods in particular, but we will need a more organized and flexible approach to the process.

We will first consider a few functions that will help us out a lot by the time we have finished.

  /**
   * 1) Identify the error code.
   * 2) Return the error as a string.
   */  
  public static String getALErrorString(int err);

  /**
   * 1) Identify the error code.
   * 2) Return the error as a string.
   */  
  public static String getALCErrorString(int err);

  /**
   * 1) Creates a buffer.
   * 2) Loads a wav file into the buffer.
   * 3) Returns the buffer id.
   */  
  public static int loadALBuffer(String path);

  /**
   * 1) Checks if file has already been loaded.
   * 2) If it has been loaded already, return the buffer id.
   * 3) If it has not been loaded, load it and return buffer id.
   */  
  public static int getLoadedALBuffer(String path);

  /**
   * 1) Checks if file has already been loaded.
   * 2) If it has been loaded already, return the buffer id.
   * 3) If it has not been loaded, load it and return buffer id.
   */  
  public static int loadALSample(String path, boolean loop);

  /**
   * 1) Releases temporary loading phase data.
   */  
  public static void killALLoadedData();

  /**
   * 1) Loads all buffers and sources for the application.
   */  
  public static void loadALData();

  /**
   * 1) Releases all buffers.
   * 2) Releases all sources.
   */  
  public static void killALData();

  /** List of loaded files */
  private static ArrayList loadedFiles = new ArrayList();

  /** List of buffers */
  private static ArrayList buffers = new ArrayList();

  /** List of sources */
  private static ArrayList sources = new ArrayList();

Take a close look at the functions and try to understand what we are going to be doing. Basically what we are trying to create is a system in which we no longer have to worry about the relationship between buffers and sources. We can call for the creation of a source from a file and this system will handle the buffer's creation on it's own so we don't duplicate a buffer (have two buffers with the same data). This system will handle the buffers as a limited resource, and will handle that resource efficiently.

  /**
   * 1) Identify the error code.
   * 2) Return the error as a string.
   */
  public static String getALErrorString(int err) {
    switch (err) {
      case AL10.AL_NO_ERROR:
        return "AL_NO_ERROR";
      case AL10.AL_INVALID_NAME:
        return "AL_INVALID_NAME";
      case AL10.AL_INVALID_ENUM:
        return "AL_INVALID_ENUM";
      case AL10.AL_INVALID_VALUE:
        return "AL_INVALID_VALUE";
      case AL10.AL_INVALID_OPERATION:
        return "AL_INVALID_OPERATION";
      case AL10.AL_OUT_OF_MEMORY:
        return "AL_OUT_OF_MEMORY";
      default:
        return "No such error code";
    }
  }

This function will convert an OpenAL error code to a string so it can be read on the console (or some other device). The OpenAL sdk says that the only exception that needs be looked for in the current version is the 'AL_OUT_OF_MEMORY' error. However, we will account for all the errors so that our code will be up to date with later versions.

  /**
   * 1) Identify the error code.
   * 2) Return the error as a string.
   */  
  public static String getALCErrorString(int err) {
    switch (err) {
      case ALC.ALC_NO_ERROR:
        return "AL_NO_ERROR";
      case ALC.ALC_INVALID_DEVICE:
        return "ALC_INVALID_DEVICE";
      case ALC.ALC_INVALID_CONTEXT:
        return "ALC_INVALID_CONTEXT";
      case ALC.ALC_INVALID_ENUM:
        return "ALC_INVALID_ENUM";
      case ALC.ALC_INVALID_VALUE:
        return "ALC_INVALID_VALUE";
      case ALC.ALC_OUT_OF_MEMORY:
        return "ALC_OUT_OF_MEMORY";
      default:
        return "no such error code";
    }
  }

This function will perform a similar task as the previous one accept this one will interpret Alc errors. OpenAL and Alc share common id's, but not common enough and not dissimilar enough to use the same function for both.

One more note about the function 'alGetError': The OpenAL sdk defines that it only holds a single error at a time (i.e. there is no stacking). When the function is invoked it will return the first error that it has received, and then clear the error bit to 'AL_NO_ERROR'. In other words an error will only be stored in the error bit if no previous error is already stored there.

  /**
   * 1) Creates a buffer.
   * 2) Loads a wav file into the buffer.
   * 3) Returns the buffer id.
   */
  public static int loadALBuffer(String path) {
    int result;
    IntBuffer buffer = BufferUtils.createIntBuffer(1);

    // Load wav data into a buffers.
    AL10.alGenBuffers(buffer);

    if ((result = AL10.alGetError()) != AL10.AL_NO_ERROR) {
      throw new OpenALException(getALErrorString(result));
    }

    WaveData waveFile = WaveData.create(path);
    if (waveFile != null) {
      AL10.alBufferData(buffer.get(0), waveFile.format, waveFile.data, waveFile.samplerate);
      waveFile.dispose();
    } else {
      throw new RuntimeException("No such file: " + path);
    }

    // Do another error check and return.
    if ((result = AL10.alGetError()) != AL10.AL_NO_ERROR) {
      throw new OpenALException(getALErrorString(result));
    }

    return buffer.get(0);
  }

As you can see we do an error check at every possible phase of the load. Any number of things can happen at this point which will cause an error to be thrown. There could be no more system memory either for the buffer creation or the data to be loaded, the wav file itself may not even exist, or an invalid value can be passed to any one of the OpenAL functions which will generate an error.

  /**
   * 1) Checks if file has already been loaded.
   * 2) If it has been loaded already, return the buffer id.
   * 3) If it has not been loaded, load it and return buffer id.
   */
  public static int getLoadedALBuffer(String path) {
    int count = 0;
    for (Iterator i = loadedFiles.iterator(); i.hasNext(); count++) {
      if (i.equals(path)) {
      	return ((Integer) buffers.get(count)).intValue();
      }
    }

    int buffer = loadALBuffer(path);

    buffers.add(new Integer(buffer));
    loadedFiles.add(path);

    return buffer;
  }

This will probably be the piece of code most people have trouble with, but it's really not that complex. We are doing a search through a list which contains the file paths of all the wav's we have loaded so far. If one of the paths matches the one we want to load, we will simply return the id to the buffer we loaded it into the first time. This way as long as we consistently load our files through this function, we will never have buffers wasted due to duplication. Every file loaded this way must also be kept track of with it's own list. The 'buffers' list is parallel to the 'loadedFiles' list. What I mean by this is that every buffer in the index of 'buffers', is the same path of the index in 'loadedFiles' from which that buffer was created.

   /**
    * 1) Creates a source.
    * 2) Calls 'GetLoadedALBuffer' with 'path' and uses the
    *    returned buffer id as it's sources buffer.
    * 3) Returns the source id.
    */
   public static int loadALSample(String path, boolean loop) {
      IntBuffer source = BufferUtils.createIntBuffer(1);
      int buffer;
      int result;

      // Get the files buffer id (load it if necessary).
      buffer = getLoadedALBuffer(path);

      // Generate a source.
      AL10.alGenSources(source);

      if ((result = AL10.alGetError()) != AL10.AL_NO_ERROR)
          throw new OpenALException(getALErrorString(result));

      // Setup the source properties.
      AL10.alSourcei(source.get(0), AL10.AL_BUFFER,   buffer    );
      AL10.alSourcef(source.get(0), AL10.AL_PITCH,    1.0f      );
      AL10.alSourcef(source.get(0), AL10.AL_GAIN,     1.0f      );
      AL10.alSource (source.get(0), AL10.AL_POSITION, sourcePos );
      AL10.alSource (source.get(0), AL10.AL_VELOCITY, sourceVel );
      AL10.alSourcei(source.get(0), AL10.AL_LOOPING,  (loop ? AL10.AL_TRUE : AL10.AL_FALSE));

      // Save the source id.
      sources.add(new Integer(source.get(0)));

      // Return the source id.
      return source.get(0);
  }

Now that we have created a system which will handle the buffers for us, we just need an extension to it that will get the sources. In this code we obtain the result of a search for the file, which is the buffer id that the file was loaded into. This buffer is bound to the new source. We save the source id internally and also return it.

  /**
   * 1) Releases temporary loading phase data.
   */
  public static void killALLoadedData() {
      loadedFiles.clear();
  }

The global arraylist 'loadedFiles' stored the file path of every wav file that was loaded into a buffer. It doesn't make sense to keep this data lying around after we have loaded all of our data, so we will dispose of it.

  //Source id's.
  static int phaser1;
  static int phaser2;

  public static void loadALData()   {
    // Anything for your application here. No worrying about buffers.
    phaser1 = loadALSample("phaser.wav", false);
    phaser2 = loadALSample("phaser.wav", true);

    killALLoadedData();
  }

We have seen the function in previous tutorials. It will represent the part of a program which loads all wav's used by the program. In it we can see why our system is useful. Even though we have made a call to load the same wav file into two distinct sources, the buffer for the file 'phaser.wav' will only be created once, and the sources 'gPhaser1' and 'gPhaser2' will both use that buffer for playback. There is no more concern for handling buffers because the system will handle them automatically.

  /**
   * 1) Releases all buffers.
   * 2) Releases all sources.
   */
  public static void killALData() {
    IntBuffer scratch = BufferUtils.createIntBuffer(1);

    // Release all buffer data.
    for (Iterator iter = buffers.iterator(); iter.hasNext();) {
    	scratch.put(0, ((Integer) iter.next()).intValue());
      AL10.alDeleteBuffers(scratch);
    }

    // Release all source data.
    for (Iterator iter = sources.iterator(); iter.hasNext();) {
      scratch.put(0, ((Integer) iter.next()).intValue());
      AL10.alDeleteSources(scratch);
    }

    // Destroy the lists.
    buffers.clear();
    sources.clear();
  }

All along we have been storing the buffer and source id's into array lists. We free all the buffers and sources by going through them and releasing them individually. After which we destroy the lists themselves. All we need to do now is catch the OpenAL errors that we have thrown.

  try {
      InitOpenAL();
      loadALData();
    } catch (Exception e) {
      e.printStackTrace();
    }

If something has gone wrong during the course of the load we will be notified of it right away. When we catch the error it will be reported on the console. We can use this for debugging or general error reporting.

That's it. A more advanced way of reporting errors, and a more robust way of loading your wav files. We may find we need to do some modifications in the future to allow for more flexibility, but for now we will be using this source for basic file loading in future tutorials. Expect future tutorials to expand on this code.

 
content © by lwjgl.org - design © by Daniel Leinich