FifeGUI 0.2.0
A C++ GUI library designed for games.
backends/opengl/imageloader.hpp
1// SPDX-License-Identifier: LGPL-2.1-or-later OR BSD-3-Clause
2// SPDX-FileCopyrightText: 2004 - 2008 Olof Naessén and Per Larsson
3// SPDX-FileCopyrightText: 2013 - 2026 Fifengine contributors
4
5#ifndef INCLUDE_FIFECHAN_BACKENDS_OPENGL_SDLIMAGELOADER_HPP_
6#define INCLUDE_FIFECHAN_BACKENDS_OPENGL_SDLIMAGELOADER_HPP_
7
8#include <fifechan/backends/opengl/image.hpp>
9#include <fifechan/backends/sdl2/imageloader.hpp>
10#include <fifechan/exception.hpp>
11
12#include <algorithm>
13#include <span>
14#include <string>
15#include <vector>
16
17namespace fcn::opengl
18{
23 {
24 public:
25 fcn::Image* load(std::string const & filename, bool convertToDisplayFormat) override
26 {
27 SDL_Surface* loadedSurface = loadSDLSurface(filename);
28
29 if (loadedSurface == nullptr) {
30 std::string const msg = "Unable to load image file: " + filename;
31 throwException(msg);
32 }
33
34 SDL_Surface* surface = convertToStandardFormat(loadedSurface);
35 SDL_FreeSurface(loadedSurface);
36
37 if (surface == nullptr) {
38 std::string const msg = "Not enough memory to load: " + filename;
39 throwException(msg);
40 }
41
42 std::vector<unsigned int> packedPixels(static_cast<size_t>(surface->w) * static_cast<size_t>(surface->h));
43 unsigned int const * srcPixels = static_cast<unsigned int const *>(surface->pixels);
44 size_t const srcPitchPixels =
45 static_cast<size_t>(static_cast<size_t>(surface->pitch) / sizeof(unsigned int));
46
47 std::span<unsigned int const> const srcSpan(srcPixels, srcPitchPixels * static_cast<size_t>(surface->h));
48 std::span<unsigned int> const dstSpan(packedPixels.data(), packedPixels.size());
49
50 for (int y = 0; y < surface->h; ++y) {
51 size_t const rowIndex = static_cast<size_t>(y);
52 auto srcIt = srcSpan.begin() + (rowIndex * srcPitchPixels);
53 auto dstIt = dstSpan.begin() + (rowIndex * static_cast<size_t>(surface->w));
54 std::copy_n(srcIt, static_cast<size_t>(surface->w), dstIt);
55 }
56
57 fcn::Image* image = new fcn::opengl::Image(packedPixels, surface->w, surface->h, convertToDisplayFormat);
58 SDL_FreeSurface(surface);
59
60 return image;
61 }
62 };
63} // namespace fcn::opengl
64
65#endif // INCLUDE_FIFECHAN_BACKENDS_OPENGL_SDLIMAGELOADER_HPP_
Abstract holder for image data.
Definition image.hpp:32
OpenGL ImageLoader that loads images with SDL.
fcn::Image * load(std::string const &filename, bool convertToDisplayFormat) override
Loads an image, optionally converting it to display format.
OpenGL-specific implementation of Image.
SDL2-specific implementation of ImageLoader.
virtual SDL_Surface * convertToStandardFormat(SDL_Surface *surface)
Convert a surface to a standard internal format (internal).
virtual SDL_Surface * loadSDLSurface(std::string const &filename)
Load an SDL_Surface from disk (internal).