Skip to content

Instantly share code, notes, and snippets.

@zaucy
Created November 4, 2014 21:45
Show Gist options
  • Save zaucy/bd21f990ced0a3505380 to your computer and use it in GitHub Desktop.
Save zaucy/bd21f990ced0a3505380 to your computer and use it in GitHub Desktop.
sdl test
#define SDL_MAIN_HANDLED
#include <SDL2/SDL.h>
#include <vector>
#include <array>
SDL_Renderer* renderer;
std::vector<SDL_Point> points;
std::vector<std::pair<SDL_Point, float>> fadingPoints;
SDL_Point mousePos;
Uint32 lastTick = 0;
Uint32 deltaTime = 0;
void draw() {
deltaTime = SDL_GetTicks() - lastTick;
lastTick = SDL_GetTicks();
float fdeltaTime = static_cast<float>(deltaTime) / 1000.f;
const Uint8 lineColor[3] = { 255, 255, 255 };
SDL_SetRenderDrawColor(renderer, lineColor[0], lineColor[1], lineColor[2], 255);
for(SDL_Point point : points) {
SDL_RenderDrawLine(renderer, point.x, point.y, mousePos.x, mousePos.y);
}
for(auto it = fadingPoints.begin(); it != fadingPoints.end(); it++) {
std::pair<SDL_Point, float>& fadingPoint = *it;
Uint8 alpha = static_cast<float>(fadingPoint.second);
SDL_SetRenderDrawColor(renderer, alpha, alpha, alpha, alpha);
SDL_RenderDrawLine(renderer, fadingPoint.first.x, fadingPoint.first.y, mousePos.x, mousePos.y);
if(fadingPoint.second > 0) {
fadingPoint.second -= 255.f * fdeltaTime;
} else {
it = fadingPoints.erase(it);
it--;
}
}
SDL_RenderPresent(renderer);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
}
int main() {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window = SDL_CreateWindow("sdl-test",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
960, 540, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN );
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
for(;;) {
SDL_Event e;
if(SDL_PollEvent(&e) != 0) {
switch(e.type) {
case SDL_QUIT:
SDL_Quit();
exit(0);
break;
case SDL_KEYDOWN:
switch(e.key.keysym.sym) {
case SDLK_ESCAPE:
SDL_Quit();
exit(0);
break;
}
break;
case SDL_MOUSEBUTTONDOWN:
if(e.button.button == 1) {
points.push_back({e.button.x, e.button.y});
} else
if(e.button.button == 3) {
if(points.begin() != points.end()) {
fadingPoints.push_back(std::make_pair<SDL_Point, Uint8>(SDL_Point(*points.begin()), 255.f));
points.erase(points.begin());
}
}
break;
case SDL_MOUSEWHEEL:
if(e.wheel.y > 0) {
points.push_back({rand() % 960, rand() % 540});
} else
if(e.wheel.y < 0) {
if(points.begin() != points.end()) {
fadingPoints.push_back(std::make_pair<SDL_Point, Uint8>(SDL_Point(*points.begin()), 255.f));
points.erase(points.begin());
}
}
break;
case SDL_MOUSEMOTION:
mousePos.x = e.motion.x;
mousePos.y = e.motion.y;
break;
}
}
draw();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment