1 module gfm.sdl2.sdlimage; 2 3 import std.string; 4 5 import derelict.util.exception, 6 derelict.sdl2.sdl, 7 derelict.sdl2.image; 8 9 import std.experimental.logger; 10 11 import gfm.sdl2.sdl, 12 gfm.sdl2.surface; 13 14 /// Load images using SDL_image, a SDL companion library able to load various image formats. 15 final class SDLImage 16 { 17 public 18 { 19 /// Loads the SDL_image library. 20 /// SDL must be already initialized. 21 /// Throws: $(D SDL2Exception) on error. 22 this(SDL2 sdl2, int flags = IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF | IMG_INIT_WEBP) 23 { 24 _sdl2 = sdl2; // force loading of SDL first 25 _logger = sdl2._logger; 26 _SDLImageInitialized = false; 27 28 try 29 { 30 DerelictSDL2Image.load(); 31 } 32 catch(DerelictException e) 33 { 34 throw new SDL2Exception(e.msg); 35 } 36 37 int inited = IMG_Init(flags); 38 _SDLImageInitialized = true; 39 } 40 41 ~this() 42 { 43 close(); 44 } 45 46 /// Releases the SDL resource. 47 void close() 48 { 49 if (_SDLImageInitialized) 50 { 51 _SDLImageInitialized = false; 52 IMG_Quit(); 53 } 54 55 DerelictSDL2Image.unload(); 56 } 57 58 /// Load an image. 59 /// Returns: A SDL surface with loaded content. 60 /// Throws: $(D SDL2Exception) on error. 61 SDL2Surface load(string path) 62 { 63 immutable(char)* pathz = toStringz(path); 64 SDL_Surface* surface = IMG_Load(pathz); 65 if (surface is null) 66 throwSDL2ImageException("IMG_Load"); 67 68 return new SDL2Surface(_sdl2, surface, SDL2Surface.Owned.YES); 69 } 70 } 71 72 private 73 { 74 Logger _logger; 75 SDL2 _sdl2; 76 bool _SDLImageInitialized; 77 78 void throwSDL2ImageException(string callThatFailed) 79 { 80 string message = format("%s failed: %s", callThatFailed, getErrorString()); 81 throw new SDL2Exception(message); 82 } 83 84 const(char)[] getErrorString() 85 { 86 return fromStringz(IMG_GetError()); 87 } 88 } 89 }