aboutsummaryrefslogtreecommitdiff
path: root/sources/TZR_DrawImage.c
blob: 862d94c69c9c1a1372946a54577b0689bf223ce5 (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
66
67
68
69
70
#include "TZR_render.h"
#include "TZR_resource.h"
#include "TZR_globals.h"
#include "sdl_error.h"
#include "sdl_rect_to_rect.h"
#include <SDL2/SDL_render.h>
#include <math.h>

int
_TZR_DrawImage(const TZR_DrawImageArgs *args)
{
	if (TZR_GetResourceType(args->id) != TZR_RES_IMAGE) {
		fprintf(stderr, "%u isn't an image\n", args->id);
		return -1;
	}
	TZR_Resource *const res = TZR_GetResourcePointer(args->id);
	const TZR_Image *const img = &res->image;

	if (SDL_SetTextureColorMod(img->ptr, ___tzr_color.r * 255,
	                           ___tzr_color.g * 255, ___tzr_color.b * 255))
		return sdl_error(-1);
	if (SDL_SetTextureAlphaMod(img->ptr, ___tzr_color.a * 255))
		return sdl_error(-1);

	float scale_x = args->sx;
	float scale_y = args->sy;

	int simg_width = (args->w == INT_MIN) ? img->width : args->w;
	if (simg_width < 0) {
		simg_width *= -1;
		scale_x *= -1;
	}
	if (simg_width + args->ix > img->width)
		simg_width = img->width - args->ix;

	int simg_height = (args->h == INT_MIN) ? img->height : args->h;
	if (simg_height < 0) {
		simg_height *= -1;
		scale_y *= -1;
	}
	if (simg_height + args->iy > img->height)
		simg_height = img->height - args->iy;

	const int flip = (SDL_FLIP_HORIZONTAL * (scale_x < 0.0f)) |
	                 (SDL_FLIP_VERTICAL * (scale_y < 0.0f));
	const SDL_Rect src = {
		args->ix,
		args->iy,
		simg_width,
		simg_height
	};

	const int width = simg_width * fabs(scale_x);
	const int height = simg_height * fabs(scale_y);
	const int x = args->x - (scale_x < 0.0f ? width : 0);
	const int y = args->y - (scale_y < 0.0f ? height : 0);

	const SDL_Rect dest = {
		x - (args->center ? (simg_width * scale_x / 2) : 0),
		y - (args->center ? (simg_height * scale_y / 2) : 0),
		width,
		height
	};
	if (SDL_RenderCopyEx(___tzr_renderer, img->ptr, &src, &dest,
	                     args->r * 360, NULL, flip) < 0)
		return sdl_error(-1);
	TZR_Rect area;
	TZR_RectFromSDLRect(&area, &dest);
	return 0;
}