2 #include <msp/strings/format.h>
4 #include "devilloader.h"
10 unsigned char eof(void *handle)
12 return reinterpret_cast<Msp::IO::Seekable *>(handle)->eof();
17 return reinterpret_cast<Msp::IO::Seekable *>(handle)->get();
20 int read(void *buf, unsigned size, unsigned count, void *handle)
22 Msp::IO::Seekable *io = reinterpret_cast<Msp::IO::Seekable *>(handle);
23 char *cbuf = reinterpret_cast<char *>(buf);
27 unsigned len = io->read(cbuf, size);
35 int seek(void *handle, int offset, int il_type)
37 Msp::IO::SeekType type;
38 if(il_type==IL_SEEK_SET)
39 type = Msp::IO::S_BEG;
40 else if(il_type==IL_SEEK_CUR)
41 type = Msp::IO::S_CUR;
42 else if(il_type==IL_SEEK_END)
43 type = Msp::IO::S_END;
47 reinterpret_cast<Msp::IO::Seekable *>(handle)->seek(offset, type);
52 int tell(void *handle)
54 return reinterpret_cast<Msp::IO::Seekable *>(handle)->tell();
57 std::string error_string(ILenum err)
61 case IL_FORMAT_NOT_SUPPORTED: return "Format not supported";
62 case IL_INTERNAL_ERROR: return "DevIL internal error";
63 case IL_INVALID_FILE_HEADER: return "Invalid file header";
64 case IL_FILE_READ_ERROR: return "File read error";
65 case IL_LIB_PNG_ERROR: return "LibPNG error";
66 case IL_LIB_JPEG_ERROR: return "LibJPEG error";
67 default: return Msp::format("Unknown error (%04X)", err);
77 DevilLoader::DevilLoader(IO::Seekable &i):
80 static bool il_init_done = false;
85 ilEnable(IL_ORIGIN_SET);
86 ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
93 DevilLoader::~DevilLoader()
95 ilDeleteImages(1, &id);
98 bool DevilLoader::detect(const string &sig)
100 unsigned type = ilDetermineTypeL(sig.data(), sig.size());
101 return type!=IL_TYPE_UNKNOWN;
104 void DevilLoader::load(Image::Data &data)
106 ilSetRead(0, 0, eof, get, read, seek, tell);
110 if(!ilLoadF(IL_TYPE_UNKNOWN, &io))
111 throw bad_image_data(error_string(ilGetError()));
113 switch(ilGetInteger(IL_IMAGE_FORMAT))
115 case IL_COLOR_INDEX: data.fmt = COLOR_INDEX; break;
116 case IL_LUMINANCE: data.fmt = LUMINANCE; break;
117 case IL_LUMINANCE_ALPHA: data.fmt = LUMINANCE_ALPHA; break;
118 case IL_RGB: data.fmt = RGB; break;
119 case IL_RGBA: data.fmt = RGBA; break;
120 case IL_BGR: data.fmt = BGR; break;
121 case IL_BGRA: data.fmt = BGRA; break;
122 default: throw unsupported_image_format("unknown pixel format");
125 data.width = ilGetInteger(IL_IMAGE_WIDTH);
126 data.height = ilGetInteger(IL_IMAGE_HEIGHT);
127 data.stride = data.width*ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);
128 unsigned data_size = data.stride*data.height;
129 data.pixels = new char[data_size];
130 ILubyte *il_data = ilGetData();
131 copy(il_data, il_data+data_size, data.pixels);
137 } // namespace Graphics