Custom formats
Resource.of reads images, animations, vector images and videos from files, streams, URLs and the classpath (Images and media lists the supported formats).
When your images live somewhere else, or in a file type that JOID does not read, teach JOID where to find them and how to decode them: they then load, cache and draw like a PNG.
You will learn
- How JOID turns an input into a resource
- How to read resources from a source of your own
- How to decode a file type of your own
- How to build an animation from frames of your own
See how JOID loads a resource
Section titled “See how JOID loads a resource”Resource.of(input) goes through three registries, and in each one the last registered entry is asked first:
- A resource resolver turns an input that is already a texture or a
BufferedImageinto a resource (Images and media shows the textures of your application). - Otherwise, an asset locator of
AssetLocatorturns the input into anAsset: the bytes and a unique id. The built-in locators read aFile, anInputStream, and aStringthat is a URL with its scheme, a path in the classpath or a path on the disk. - A resource format of
ResourceFormatreads the first 4 096 bytes of the asset and returns the decoder that reads it. When no format recognizes them, the bundled image readers (ImageIO) try the file (Supported formats).
The decoder then reads the asset in the background, the first time a node draws the resource, and JOID uploads the pixels on the render thread. Resources with the same unique id share one decoded copy.
Here a locator of your own reads the prefix pack:, and a format of your own reads PPM images:
AssetLocator.register(new FormatsPackAssetLocator());ResourceFormat.register(new FormatsPpmResourceFormat());ResourceNode.create(100, 100, 192, 192).resource(Resource.of("pack:images/ring.ppm").nearest()).attach(this);pack: locator.
Register your locators and formats once, before the first Resource.of(...) that needs them: a static block of the UI that uses them, or the start of your application.
AssetLocator.unregister(...) and ResourceFormat.unregister(...) remove them.
Read resources from your own source
Section titled “Read resources from your own source”An IAssetLocator says which inputs it supports, then turns each one into an Asset:
public class FormatsPackAssetLocator implements IAssetLocator {
@Override public boolean supports(final Object handle) { return handle instanceof String && ((String) handle).startsWith("pack:"); }
@Override public Asset locate(final Object handle) { final String path = "formats/" + ((String) handle).substring(5); final URL url = FormatsPackAssetLocator.class.getClassLoader().getResource(path); if (url == null) { throw new IllegalArgumentException("The asset " + handle + " is not in the pack, check its path"); } return ClasspathAsset.of(path, url); }
}Full file: FormatsPackAssetLocator.java
supports(handle) decides from the input alone, without reading anything.
locate(handle) returns one of the built-in assets (ClasspathAsset, FileAsset, UrlAsset, StreamAsset) or an Asset of your own, which implements open() and passes its unique id to the constructor.
When a locator throws an IllegalArgumentException for a String, the resource fails like a missing file: its onError listeners receive the exception, and in dev mode it draws a magenta and black checkerboard.
Any other exception, and any exception for another input, reaches the caller of Resource.of(...).
Decode a file type of your own
Section titled “Decode a file type of your own”An IResourceFormat recognizes the file from its first bytes, then returns its decoder:
public class FormatsPpmResourceFormat implements IResourceFormat {
@Override public boolean supports(final byte[] header) { return header.length >= 3 && header[0] == 'P' && header[1] == '3' && Character.isWhitespace(header[2]); }
@Override public IResourceDecoder decoder(final Asset asset, final byte[] header) { return FormatsPpmResourceDecoder.create(asset); }
}Full file: FormatsPpmResourceFormat.java
supports(header) receives the first 4 096 bytes, or fewer for a smaller file: test only what your format starts with.
decoder(asset, header) returns a new IResourceDecoder for this asset.
When the file holds a plain image, a RasterResourceDecoder does the rest: return RasterResourceDecoder.create(image) with a BufferedImage that you build.
A decoder of your own implements four steps, each one on the ResourceData of the resource:
public class FormatsPpmResourceDecoder implements IResourceDecoder {
private final Asset asset;
protected FormatsPpmResourceDecoder(final Asset asset) { this.asset = asset; }
public static FormatsPpmResourceDecoder create(final Asset asset) { return new FormatsPpmResourceDecoder(asset); }
@Override public void prepare(final ResourceData resource) { resource.texture(ResourceData.placeholder()); }
@Override public void decode(final ResourceData resource) { final String text; try { text = new String(this.asset.read(), StandardCharsets.US_ASCII); } catch (final IOException exception) { throw new UncheckedIOException("The image " + this.asset.getUniqueId() + " cannot be read", exception); }
final String[] tokens = text.replaceAll("#[^\n]*", " ").trim().split("\\s+"); final int width = Integer.parseInt(tokens[1]); final int height = Integer.parseInt(tokens[2]); final int max = Integer.parseInt(tokens[3]); final int[] pixels = new int[width * height]; for (int i = 0; i < pixels.length; i++) { final int red = Integer.parseInt(tokens[4 + i * 3]) * 255 / max; final int green = Integer.parseInt(tokens[5 + i * 3]) * 255 / max; final int blue = Integer.parseInt(tokens[6 + i * 3]) * 255 / max; pixels[i] = 0xFF000000 | red << 16 | green << 8 | blue; } resource.width(width).height(height).data(new int[][] {pixels}); }
@Override public void upload(final ResourceData resource) { resource.uploadTextures(); }
@Override public void clear(final ResourceData resource) {}
}Full file: FormatsPpmResourceDecoder.java
| Step | JOID calls it | It must |
|---|---|---|
prepare(resource) | On the render thread, the first time the resource is drawn | Give the resource its textures, here one empty ResourceData.placeholder(). |
decode(resource) | In the background, unless the resource is blocking() | Read the asset and set width, height and data: one array of ARGB pixels per texture. |
upload(resource) | On the render thread, after decode | Send the pixels to the textures; uploadTextures() does it for one image per texture. |
clear(resource) | When the resource is released, after JOID deleted its textures | Release what the decoder holds on its own. |
An exception thrown by decode makes the resource fail, as a missing file does.
The other hooks of IResourceDecoder do nothing by default: update runs each time the resource is bound, for an animation that changes its texture; request receives the size the resource is drawn at, for a format that renders at any size; fork returns a copy that plays on its own, one per node; isMipmappable returns false when the texture changes too often for mipmaps.
Build an animation from your own frames
Section titled “Build an animation from your own frames”An animation needs no decoder of your own: an IResourceAnimationReader reads the frames, and an AnimatedResourceDecoder plays them like a GIF.
This reader cuts a sprite strip into frames of the same width:
public class FormatsStripAnimationReader implements IResourceAnimationReader {
private final int frameCount; private final long frameDuration;
public FormatsStripAnimationReader(final int frameCount, final long frameDuration) { this.frameCount = frameCount; this.frameDuration = frameDuration; }
@Override public ResourceAnimation read(final InputStream stream) throws IOException { final BufferedImage strip = ImageIO.read(stream); if (strip == null) { throw new IOException("The sprite strip is not an image that ImageIO can read"); }
final int width = strip.getWidth() / this.frameCount; final int height = strip.getHeight(); final List<ResourceAnimationFrame> frames = new ArrayList<>(); for (int i = 0; i < this.frameCount; i++) { final int[] pixels = strip.getRGB(i * width, 0, width, height, null, 0, width); frames.add(ResourceAnimationFrame.of(pixels, this.frameDuration)); } return ResourceAnimation.of(width, height, 0, frames); }
}Full file: FormatsStripAnimationReader.java
ResourceAnimationFrame.of takes the ARGB pixels of the whole frame and its duration in milliseconds.
ResourceAnimation.of takes the size, the number of plays (0 loops forever) and the frames.
A sprite strip has no header that a format could recognize, so the resource names its decoder itself.
ResourceBuilder.compute creates the resource from a ResourceData, once per unique id:
private static final Resource COIN = ResourceBuilder.create().nearest().compute("strip:coin", () -> ResourceData.create( "strip:coin", AnimatedResourceDecoder.create(Asset.of("pack:images/strip.png"), new FormatsStripAnimationReader(8, 80L))));ResourceNode.create(360, 100, 192, 192).resource(FormatsUI.COIN).attach(this);The animation plays, pauses and loops like any animated image (Images and media shows the playback).
When the frames of your format cover only part of the image, as in a GIF, compose them on a ResourceAnimationCanvas: compose(frame, x, y, width, height, blend, disposal) draws a partial frame over the previous ones and returns the whole image, with the ResourceAnimationCanvas.Blend and the ResourceAnimationCanvas.Disposal of the frame.
Resource.of(...)goes through the resolvers, the asset locators, then the resource formats; the last registered entry is asked first.- An
IAssetLocatorturns an input of your own into anAsset; anIllegalArgumentExceptionfor a string makes the resource fail like a missing file, and any other exception reaches the caller. - An
IResourceFormatrecognizes a file from its first 4 096 bytes and returns a decoder. - A decoder prepares its textures, decodes in the background, then uploads on the render thread.
- An
IResourceAnimationReaderturns a file into frames, played by anAnimatedResourceDecoder. ResourceBuilder.computecreates a resource with a decoder that no format can pick.
Try it
Section titled “Try it”A faster coin. Make the coin turn twice as fast.
Solution
Give each frame 40 milliseconds instead of 80:
new FormatsStripAnimationReader(8, 40L)A coin that stops. Make the coin turn once, then stop on its last frame.
Solution
In the reader, play the frames once:
return ResourceAnimation.of(width, height, 1, frames);