Last active
April 22, 2017 22:40
-
-
Save thai-ng/7f180bffbb1fa32f19a9ecd274c34b9a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "SDLDrawable.hpp" | |
SDLDrawable::SDLDrawable(int w, int h) : width(w), height(h) | |
{ | |
SDL_Init(SDL_INIT_VIDEO); | |
screen = SDL_SetVideoMode(width, height, 32, SDL_SWSURFACE); | |
if (SDL_MUSTLOCK(screen)) | |
SDL_LockSurface(screen); | |
} | |
SDLDrawable::~SDLDrawable() | |
{ | |
SDL_Quit(); | |
} | |
struct ColorTriplet | |
{ | |
unsigned char r; | |
unsigned char g; | |
unsigned char b; | |
}; | |
// Assume ARGB order | |
ColorTriplet getColorTriplet(unsigned int color) | |
{ | |
return ColorTriplet { | |
static_cast<unsigned char>(color << 8 >> 24), | |
static_cast<unsigned char>(color << 16 >> 24), | |
static_cast<unsigned char>(color << 24 >> 24) | |
}; | |
} | |
// Assume ARGB order | |
unsigned int getColor(const ColorTriplet& color) | |
{ | |
return 0xff000000 | (color.r << 16) | (color.g << 8) | color.b; | |
} | |
void SDLDrawable::updateScreen() | |
{ | |
if (SDL_MUSTLOCK(screen)) | |
SDL_UnlockSurface(screen); | |
SDL_Flip(screen); | |
if (SDL_MUSTLOCK(screen)) | |
SDL_LockSurface(screen); | |
} | |
unsigned int SDLDrawable::getPixel(int x, int y) | |
{ | |
auto pixel = *(reinterpret_cast<Uint32*>(screen->pixels) + y * width + x); | |
ColorTriplet color; | |
unsigned char alpha = 0; | |
SDL_GetRGBA(pixel, screen->format, &color.r, &color.g, &color.b, &alpha); | |
return getColor(color); | |
}; | |
void SDLDrawable::setPixel(int x, int y, unsigned int color) | |
{ | |
auto colorTriplet = getColorTriplet(color); | |
auto pixelPtr = reinterpret_cast<Uint32*>(screen->pixels) + y * width + x; | |
*pixelPtr = SDL_MapRGBA(screen->format, colorTriplet.r, colorTriplet.g, colorTriplet.b, 255); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment