aboutsummaryrefslogtreecommitdiff
path: root/View.cpp
blob: 5671c1f2fcf6899fa6fa607ed18417c7f4e9fa84 (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
#include <SDL2/SDL.h>
#include <thread>

#include "View.h"

View::View() {
	SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS);
	this->window = SDL_CreateWindow(
			"dpa",
			SDL_WINDOWPOS_UNDEFINED,
			SDL_WINDOWPOS_UNDEFINED,
			this->width,
			this->height,
			SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL
	);
	this->renderer = SDL_CreateRenderer(this->window, -1, SDL_RENDERER_ACCELERATED);
	this->worker = new std::thread(&View::work, this);
}

View::~View() {
	if (this->renderer != nullptr)
		SDL_DestroyRenderer(this->renderer);
	if (this->window != nullptr)
		SDL_DestroyWindow(this->window);
	if (this->worker != nullptr) {
		this->open = false;
		this->worker->join();
	}
	SDL_Quit();
}

void View::set_size(unsigned int width, unsigned int height) {
	if (this->width == width && this->height == height) return;

	SDL_SetWindowSize(this->window, width, height);
	this->width = width;
	this->height = height;
}

void View::work() {
	while (this->open) {
		SDL_Event e;
		while (SDL_PollEvent(&e))
			if (e.type == SDL_QUIT) this->open = false;
	}
}

void View::draw_begin() {
	SDL_RenderClear(this->renderer);
}

void View::draw_end() {
	SDL_SetRenderDrawColor(this->renderer, 0, 0, 0, 255);
	SDL_RenderPresent(this->renderer);
}

void View::draw_rect(Rectangle r, Color c) {
	SDL_SetRenderDrawColor(this->renderer, c.red, c.green, c.blue, 255);
	SDL_Rect rect = {
		.x = static_cast<int>(r.x),
		.y = static_cast<int>(r.y),
		.w = static_cast<int>(r.width),
		.h = static_cast<int>(r.height),
	};
	SDL_RenderFillRect(this->renderer, &rect);
}