Оглавление
§ Файл main.cc
- Создается новое окно
- Запускается в работу, по выходу удаляется контекст
#include "main.cc"
int main(int argc, char** argv)
{
App app(640,400);
return app.main();
}
§ Файл app.h
#include <SDL2/SDL.h>
class App
{
protected:
SDL_Surface* screen_surface;
SDL_Window* sdl_window;
SDL_Renderer* sdl_renderer;
SDL_PixelFormat* sdl_pixel_format;
SDL_Texture* sdl_screen_texture;
SDL_Event evt;
Uint32* screen_buffer;
int width, height, scale;
public:
App(int _width, int _height, int _scale);
~App();
int main();
void pset(int x, int y, Uint32 cl);
};
§ Файл app.cc
#include "app.h"
App::App(int _width = 640, int _height = 400, int _scale = 2)
{
scale = _scale;
width = _width;
height = _height;
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO)) {
exit(1);
}
SDL_ClearError();
sdl_window = SDL_CreateWindow("SDL2: Application", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, scale*width, scale*height, SDL_WINDOW_SHOWN);
sdl_renderer = SDL_CreateRenderer(sdl_window, -1, SDL_RENDERER_PRESENTVSYNC);
screen_buffer = (Uint32*) malloc(width*height*sizeof(Uint32));
sdl_screen_texture = SDL_CreateTexture(sdl_renderer, SDL_PIXELFORMAT_BGRA32, SDL_TEXTUREACCESS_STREAMING, width, height);
SDL_SetTextureBlendMode(sdl_screen_texture, SDL_BLENDMODE_NONE);
}
App::~App()
{
free(screen_buffer);
SDL_DestroyTexture(sdl_screen_texture);
SDL_FreeFormat(sdl_pixel_format);
SDL_DestroyRenderer(sdl_renderer);
SDL_DestroyWindow(sdl_window);
SDL_Quit();
}
int App::main()
{
SDL_Rect dstRect;
dstRect.x = 0;
dstRect.y = 0;
dstRect.w = scale * width;
dstRect.h = scale * height;
Uint32 prev = 0;
for (;;) {
while (SDL_PollEvent(& evt)) {
switch (evt.type) { case SDL_QUIT: return 0; }
}
Uint32 ticks = SDL_GetTicks();
if (ticks - prev >= 16) {
SDL_UpdateTexture (sdl_screen_texture, NULL, screen_buffer, width * sizeof(Uint32));
SDL_SetRenderDrawColor (sdl_renderer, 0, 0, 0, 0);
SDL_RenderClear (sdl_renderer);
SDL_RenderCopy (sdl_renderer, sdl_screen_texture, NULL, & dstRect);
SDL_RenderPresent (sdl_renderer);
prev = ticks;
}
SDL_Delay(1);
}
}
void App::pset(int x, int y, Uint32 cl)
{
if (x < 0 || y < 0 || x >= width || y >= height) {
return;
}
screen_buffer[width*y + x] = cl;
}
§ Файл makefile
all: app
./main
app:
g++ main.cc -lSDL2 -o main
clean:
rm -r main