aboutsummaryrefslogtreecommitdiff
path: root/src/sdl/sprites.c
blob: 9b9b42f4e9624072827e568b499b712e8796fa4e (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
#include <SDL.h>
#define STB_IMAGE_IMPLEMENTATION
#define STB_ASSERT(x)
#define STB_ONLY_PNG
#include "stb_image.h"
#include "util.h"
#include "sprites.h"

void
sprites_init(
  SDL_Renderer * const renderer,
  const char * const png_path,
  SDL_Texture **sprites
) {
  // load image
  int im_w, im_h;
  unsigned char *im_data = stbi_load(png_path, &im_w, &im_h, NULL, 4);
  if (!im_data) {
    die("stbi_load(): %s", stbi_failure_reason());
  }

  // create surface
  SDL_Surface * const src = SDL_CreateRGBSurfaceWithFormatFrom(im_data, im_w, im_h, 32, 4 * im_w, SDL_PIXELFORMAT_RGBA32);
  if (!src) {
    die("SDLCreateRGBSurfaceFrom(): %s", SDL_GetError());
  }

  // create sprite textures
  for (size_t i = 0; i < SPRITE_LAST; i++) {
    // create surface
    SDL_Surface *s = SDL_CreateRGBSurfaceWithFormat(0, 32, 32, 32, SDL_PIXELFORMAT_RGBA32);
    if (!s) {
      die("SDL_CreateRGBSurfaceWithFormat(): %s", SDL_GetError());
    }

    // copy from main surface
    const SDL_Rect src_rect = { i * 32, 0, 32, 32 };
    if (SDL_BlitScaled(src, &src_rect, s, NULL)) {
      die("SDL_BlitScaled(): %s", SDL_GetError());
    }

    // create texture
    sprites[i] = SDL_CreateTextureFromSurface(renderer, s);
    if (!sprites[i]) {
      die("SDLCreateTextureFromSurface(): %s", SDL_GetError());
    }

    // free surface
    SDL_FreeSurface(s);
  }

  // free main surface
  SDL_FreeSurface(src);

  // free image data
  stbi_image_free(im_data);
}

SDL_Rect
sprites_get_rect(
  const sprite_t sprite
) {
  const int x = ((sprite < SPRITE_LAST) ? sprite : SPRITE_NONE) * 32;
  return (SDL_Rect) { .x = x, .y = 0, .w = 32, .h = 32 };
}