105 lines
2.3 KiB
C++
105 lines
2.3 KiB
C++
#ifndef _ENGINE_H
|
|
#define _ENGINE_H
|
|
|
|
#include <SDL2/SDL.h>
|
|
#include <SDL2/SDL_image.h>
|
|
#include <iostream>
|
|
#include <string>
|
|
#include <unistd.h>
|
|
#include <limits.h>
|
|
|
|
class engine {
|
|
public:
|
|
SDL_Window *window;
|
|
SDL_Renderer *renderer;
|
|
SDL_Texture *font;
|
|
SDL_Event event;
|
|
|
|
int SCREEN_WIDTH;
|
|
int SCREEN_HEIGHT;
|
|
std::string title;
|
|
|
|
|
|
public:
|
|
engine(){}
|
|
|
|
~engine() {
|
|
SDL_DestroyWindow(window);
|
|
window = nullptr;
|
|
|
|
SDL_DestroyRenderer(renderer);
|
|
renderer = nullptr;
|
|
|
|
SDL_DestroyTexture(font);
|
|
font = nullptr;
|
|
|
|
SDL_Quit();
|
|
}
|
|
|
|
bool Init(std::string title, int width, int height) {
|
|
this->SCREEN_WIDTH = width;
|
|
this->SCREEN_HEIGHT = height;
|
|
this->title = title;
|
|
|
|
if (SDL_Init(SDL_INIT_VIDEO) < 0){
|
|
std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
|
|
return false;
|
|
}
|
|
|
|
window = SDL_CreateWindow(title.append(" | FPS: 0").c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_SHOWN);
|
|
if(window == nullptr) {
|
|
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
|
|
return false;
|
|
}
|
|
|
|
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
|
|
if(renderer == nullptr) {
|
|
std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
void Run() {
|
|
bool running = true;
|
|
|
|
if(!OnUserCreate()){
|
|
return;
|
|
}
|
|
|
|
unsigned long acumulatedTime = 0;
|
|
unsigned long tick1 = SDL_GetTicks();
|
|
unsigned long tick2 = SDL_GetTicks();
|
|
unsigned long fpsAcumulator = 0;
|
|
unsigned long fps = 0;
|
|
|
|
while(running){
|
|
tick2 = SDL_GetTicks();
|
|
Uint32 elapsedTime = tick2 - tick1;
|
|
tick1 = tick2;
|
|
|
|
fpsAcumulator++;
|
|
acumulatedTime += elapsedTime;
|
|
if(acumulatedTime >= 1000) {
|
|
acumulatedTime -= 1000;
|
|
fps = fpsAcumulator;
|
|
fpsAcumulator = 0;
|
|
|
|
std::ostringstream title;
|
|
title << this->title << " | FPS: " << fps;
|
|
SDL_SetWindowTitle(window, title.str().c_str());
|
|
}
|
|
|
|
running = OnUserUpdate(elapsedTime);
|
|
}
|
|
}
|
|
|
|
|
|
protected:
|
|
virtual bool OnUserCreate() = 0;
|
|
virtual bool OnUserUpdate(Uint32 elapsedTime) = 0;
|
|
};
|
|
|
|
#endif
|