summaryrefslogtreecommitdiff
path: root/source/modules/asura-core/graphics/stb_decoder.cpp
blob: 9a141415de0fbeffe8a3918f1746fe5437277c35 (plain)
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
#include <asura-utils/exceptions/exception.h>

#include "stb_decoder.h"
#include "stb/stb_image.h"

namespace AsuraEngine
{
	namespace Graphics
	{

		bool STBDecoder::CanDecode(IO::DataBuffer& buffer)
		{
			int w = 0;
			int h = 0;
			int comp = 0;

			int status = stbi_info_from_memory((const stbi_uc*)buffer.GetData(), buffer.GetSize(), &w, &h, &comp);

			return status == 1 && w > 0 && h > 0;
		}

		void STBDecoder::Decode(IO::DataBuffer& db, ImageData& imageData)
		{
			const stbi_uc *buffer = (const stbi_uc *)db.GetData();
			// databufferݳ
			int bufferlen = db.GetSize();

			int width, height;
			int comp = 0;
			byte* data = nullptr;
			ColorFormat format = COLOR_FORMAT_UNKNOWN;
			std::size_t size = 0;

			if (stbi_is_hdr_from_memory(buffer, bufferlen))
			{
				// 4channelfloat
				data = (byte*)stbi_loadf_from_memory(buffer, bufferlen, &width, &height, &comp, STBI_rgb_alpha);
				format = COLOR_FORMAT_RGBA32F;
				size = width * height * 4 * sizeof(float);
			}
			else
			{
				data = (byte*)stbi_load_from_memory(buffer, bufferlen, &width, &height, &comp, STBI_rgb_alpha);
				format = COLOR_FORMAT_RGBA8;
				size = width * height * 4;
			}
			if (data)
			{
				imageData.Lock();

				if (imageData.pixels)
					delete[] imageData.pixels;
				imageData.pixels = (byte*)data;
				imageData.format = format;
				imageData.width = width;
				imageData.height = height;

				imageData.Unlock();
			}
			else
			{
				const char *err = stbi_failure_reason();
				if (err == nullptr)
					err = "unknown error";
				throw Exception("Could not decode image with stb_image (%s).", err);
			}
		}

	}
}