1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
|
#include "Sprite.hpp"
void Sprite::LoadBMP(const std::string location)
{
std::ifstream file(location); // Attempt to open a file
BMPHeader header; // Object that holds bmp information
// If the file opened
if(file)
{
// Read in the header
file.read((char*)&header, sizeof(header));
// Check if the image is a bmp image
if(!(header.bf.id[0] == 'B' && header.bf.id[1] == 'M')) {throw "Unreadable image.";}
// I know I'm supposed to check for other stuff to be true, but I could care less about it
// Make some space for image data
pixels = std::vector<Uint8>(header.bi.imgSize);
file.seekg(header.bf.imgAddr); // Jump to location in file where pixel data starts
file.read((char*)&pixels[0], header.bi.imgSize); // Read in the data
// Now we have the image loaded into memory, generate the texture object
glGenTextures(1, &sprite); // Generate a texture
glBindTexture(GL_TEXTURE_2D, sprite); // Bind that texture temporarily
GLint mode = GL_RGB; // Set the mode
//pixels = ColorKey(pixels, w, h, img->pitch, key, mode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// Create the texture. We get the offsets from the image, then we use it with the image's
// pixel data to create it.
glTexImage2D(GL_TEXTURE_2D, 0, mode, w, h, 0, mode, GL_UNSIGNED_BYTE, pixels.data());
// Unbind the texture
glBindTexture(GL_TEXTURE_2D, 0);
}
else {throw "Failure opening file";}
}
void Sprite::Render(const Vec2 pos, FRect* rect)
{
if(sprite == 0) {throw "Sprite ID is equal to 0!";}
float tTop = 0.0f;
float tBottom = 1.0f;
float tLeft = 0.0f;
float tRight = 1.0f;
float qWidth = (float)w;
float qHeight = (float)h;
if(rect != nullptr)
{
tLeft = rect->x/w;
tRight = (rect->x + rect->w) / w;
tTop = rect->y / h;
tBottom = (rect->y + rect->h ) / h;
qWidth = rect->w;
qHeight = rect->h;
}
glPushMatrix();
// Move to desired position
glTranslatef(pos.x, pos.y, 0);
glBindTexture(GL_TEXTURE_2D, sprite);
glBegin(GL_QUADS);
glTexCoord2f(tLeft, tTop); glVertex2f(0.f, 0.0f);
glTexCoord2f(tRight, tTop); glVertex2f(qWidth, 0.0f);
glTexCoord2f(tRight, tBottom); glVertex2f(qWidth, qHeight);
glTexCoord2f(tLeft, tBottom); glVertex2f(0.f, qHeight);
glEnd();
glPopMatrix();
}
void Sprite::Render(float x, float y, FRect* rect)
{
Vec2 pos = {x, y};
Render(pos, rect);
}
|