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