Оглавление
§ Файл main.cc
- Создается новое окно
- Запускается в работу, по выходу удаляется контекст
#include <SDL2/SDL.h> // ----------------------------------------------------------------------------- #define WIDTH 640 #define HEIGHT 400 #define SCALE 2 // ----------------------------------------------------------------------------- SDL_Surface* surface; SDL_Window* window; SDL_Renderer* renderer; SDL_Texture* texture; SDL_Event evt; SDL_Rect dstRect; Uint32* screen; // ----------------------------------------------------------------------------- void pset(int, int, Uint32); void line(int, int, int, int, int); void cls(int); // ----------------------------------------------------------------------------- int main(int argc, char** argv) { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO)) { exit(1); } dstRect.x = 0; dstRect.y = 0; dstRect.w = SCALE*WIDTH; dstRect.h = SCALE*HEIGHT; SDL_ClearError(); window = SDL_CreateWindow("Demoscene2", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, dstRect.w, dstRect.h, SDL_WINDOW_SHOWN); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC); screen = (Uint32*) malloc(WIDTH * HEIGHT * sizeof(Uint32)); texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_BGRA32, SDL_TEXTUREACCESS_STREAMING, WIDTH, HEIGHT); SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_NONE); Uint32 pticks = 0; for (;;) { // Прием событий while (SDL_PollEvent(& evt)) { // Событие выхода switch (evt.type) { case SDL_QUIT: free(screen); SDL_DestroyTexture(texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; } } // Обновление 60 раз в секунду Uint32 nticks = SDL_GetTicks(); if (nticks - pticks >= 16) { SDL_UpdateTexture (texture, NULL, screen, WIDTH * sizeof(Uint32)); SDL_SetRenderDrawColor (renderer, 0, 0, 0, 0); SDL_RenderClear (renderer); SDL_RenderCopy (renderer, texture, NULL, & dstRect); SDL_RenderPresent (renderer); pticks = nticks; } SDL_Delay(1); } } // Установка точки void pset(int x, int y, Uint32 cl) { if (x < 0 || y < 0 || x >= WIDTH || y >= HEIGHT) { return; } screen[WIDTH*y + x] = cl; }
§ Файл makefile
all: app ./main app: g++ main.cc -lSDL2 -o main clean: rm -r main
§ Дополнения
Различные графические рутины.Рисование линии
void line(int x1, int y1, int x2, int y2, int color) { // Инициализация смещений int signx = x1 < x2 ? 1 : -1; int signy = y1 < y2 ? 1 : -1; int deltax = x2 > x1 ? x2 - x1 : x1 - x2; int deltay = y2 > y1 ? y2 - y1 : y1 - y2; int error = deltax - deltay; int error2; pset(x2, y2, color); while ((x1 != x2) || (y1 != y2)) { pset(x1, y1, color); error2 = 2 * error; if (error2 > -deltay) { error -= deltay; x1 += signx; } if (error2 < deltax) { error += deltax; y1 += signy; } } }Очистка экрана
void cls(int cl = 0) { for (int i = 0; i < WIDTH*HEIGHT; i++) screen[i] = cl; }
02 июн 2025, 16:52
© 2011-2025 Гнал простой кот