Jump to content

Loading Assets from Streams


Josh

1,158 views

 Share

Since the GLTF file format can pack textures into a single file with the model, I needed to implement asset loading directly from a stream:

auto stream = ReadFile("image.png");
auto tex = LoadTexture(stream);

This was interesting because I needed to add a check for each supported image type so the loader can determine the file type from the contents instead of the file path extension. Most file formats include a string or "magic number" at the beginning of the file format to indicate what type of file it is:

//BMP check
pos = stream->GetPos();
if (stream->GetSize() - pos >= 2)
{
	if (stream->ReadString(2) == "BM") isbmp = true;
}
stream->Seek(pos);

The TGA file format is weird though because it does not have one of these. It just launches straight into a header of information, already assuming the file is a TGA file. So what you have to do is read some of the values and see if they are reasonable. With a little help from the BlitzMax source code, I was able to do this:

//TGA check
pos = stream->GetPos();
tgahdr hdr;
if (stream->GetSize() - pos >= sizeof(hdr))
{
	const int TGA_NULL = 0;
	const int TGA_MAP = 1;
	const int TGA_RGB = 2;
	const int TGA_MONO = 3;
	const int TGA_RLEMAP = 9;
	const int TGA_RLERGB = 10;
	const int TGA_RLEMONO = 11;
	const int TGA_COMPMAP = 32;
	const int TGA_COMPMAP4 = 33;
	stream->Read(&hdr, sizeof(hdr));
	if (hdr.colourmaptype == 0)
	{
		if (hdr.imgtype == TGA_MAP or hdr.imgtype == TGA_RGB or hdr.imgtype == TGA_RLERGB)
		{
			if (hdr.psize == 15 or hdr.psize == 16 or hdr.psize == 24 or hdr.psize == 32)
			{
				if (hdr.width > 0 and hdr.width <= 163284 * 2)
				{
					if (hdr.height > 0 and hdr.height <= 163284 * 2) istga = true;
				}
			}
		}
	}
}
stream->Seek(pos);

In fact the whole idea of having a list of loaders that read the file contents to determine if they are able to load the file is an idea I pulled from the design of BlitzMax. It is strange that so many good tech products have fallen away yet we are growing.

  • Like 1
 Share

0 Comments


Recommended Comments

There are no comments to display.

Guest
Add a comment...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...