82 lines
2.1 KiB
C++
82 lines
2.1 KiB
C++
#include <SDL2/SDL_image.h>
|
|
#include <iostream>
|
|
#include "Sprite.hpp"
|
|
#include "GameRenderer.hpp"
|
|
|
|
GameRenderer::GameRenderer(const std::string &title, const int screen_width, const int screen_height)
|
|
: title(title), screen_width(screen_width), screen_height(screen_height)
|
|
{
|
|
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
|
|
std::cerr << "Unable to initialize SDL" << std::endl;
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
SDL_SetHint(SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR, "0");
|
|
|
|
window = SDL_CreateWindow(
|
|
title.c_str(),
|
|
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
|
|
screen_width, screen_height,
|
|
SDL_WINDOW_SHOWN
|
|
);
|
|
|
|
if (!window) {
|
|
std::cerr << "Could not create window" << std::endl;
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
|
|
|
|
if (!renderer) {
|
|
std::cerr << "Could not create renderer" << std::endl;
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
}
|
|
|
|
GameRenderer::~GameRenderer()
|
|
{
|
|
SDL_DestroyRenderer(renderer);
|
|
SDL_DestroyWindow(window);
|
|
}
|
|
|
|
Sprite GameRenderer::load_sprite(const std::string &file, const int width, const int height) const
|
|
{
|
|
return Sprite {
|
|
.texture = IMG_LoadTexture(renderer, file.c_str()),
|
|
.width = width,
|
|
.height = height
|
|
};
|
|
}
|
|
|
|
void GameRenderer::draw_sprite(const Sprite sprite, const int x, const int y) const
|
|
{
|
|
const SDL_Rect rect = { .x = x, .y = y, .w = sprite.width, .h = sprite.height };
|
|
SDL_RenderCopy(renderer, sprite.texture, nullptr, &rect);
|
|
}
|
|
|
|
void GameRenderer::draw_sprite_rotated(const Sprite sprite, const int x, const int y, const double angle) const
|
|
{
|
|
const SDL_Rect rect = { .x = x, .y = y, .w = sprite.width, .h = sprite.height };
|
|
SDL_RenderCopyEx(renderer, sprite.texture, nullptr, &rect, angle, nullptr, SDL_FLIP_NONE);
|
|
}
|
|
|
|
void GameRenderer::clear_screen(const uint8_t r, const uint8_t g, const uint8_t b, const uint8_t a) const
|
|
{
|
|
SDL_SetRenderDrawColor(renderer, r, g, b, a);
|
|
SDL_RenderClear(renderer);
|
|
}
|
|
|
|
void GameRenderer::flush() const
|
|
{
|
|
SDL_RenderPresent(renderer);
|
|
}
|
|
|
|
void GameRenderer::redraw() const
|
|
{
|
|
SDL_Event event;
|
|
event.type = SDL_WINDOWEVENT;
|
|
event.window.event = SDL_WINDOWEVENT_EXPOSED;
|
|
event.window.windowID = SDL_GetWindowID(window);
|
|
SDL_PushEvent(&event);
|
|
}
|