aboutsummaryrefslogtreecommitdiff
path: root/sources/TZR_DrawEnd.c
blob: ba379bec7a2199cffc953d68a6c3f8c924118ad1 (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
#include "TZR_render.h"
#include "TZR_globals.h"
#include "TZR_resource.h"
#include "sdl_error.h"
#include <SDL2/SDL_render.h>
#include <SDL2/SDL_timer.h>

int
TZR_DrawEnd(void)
{
	if (SDL_SetRenderTarget(___tzr_renderer, NULL) < 0)
		return sdl_error(-1);
	if (SDL_SetRenderDrawColor(___tzr_renderer, 0, 0, 0, 255) < 0)
		return sdl_error(-1);
	if (SDL_RenderClear(___tzr_renderer) < 0)
		return sdl_error(-1);

	int win_w, win_h;
	SDL_GetWindowSize(___tzr_window, &win_w, &win_h);
	win_w = win_w ? win_w : 1;
	win_h = win_h ? win_h : 1;

	const float ratio_w = win_w / (float)___tzr_config.width;
	const float ratio_h = win_h / (float)___tzr_config.height;
	float scale = (ratio_w < ratio_h) ? ratio_w : ratio_h;
	if (scale > 1.0f && ___tzr_config.pixel_perfect)
		scale = (int)scale;
	const int off_x = (win_w - ___tzr_config.width * scale) / 2;
	const int off_y = (win_h - ___tzr_config.height * scale) / 2;
	const SDL_Rect dest = {
		off_x,
		off_y,
		___tzr_config.width * scale,
		___tzr_config.height * scale
	};

	if (SDL_RenderCopy(___tzr_renderer, ___tzr_target, NULL, &dest) < 0)
		return sdl_error(-1);
	if (___tzr_config.target_fps > 0) {
		___tzr_next_time += ___tzr_min_dt;
		const unsigned long cur_time = SDL_GetTicks64();
		if (___tzr_next_time <= cur_time)
			___tzr_next_time = cur_time;
		else
			SDL_Delay(___tzr_next_time - cur_time);
	}
	SDL_RenderPresent(___tzr_renderer);
	___tzr_tick += 1;
	return 0;
}