Recently I have been trying to make a button using the lazyfoo.net tutorials. The button example they code didn't fit what I needed (especially since I modified the LTexture class) so I modified it... and, of course, it didn't work.
So here is the modified LTexture class(now dubbed Texture):
#pragma once
//Using SDL, SDL_image, standard IO, and strings
#include <xstring>
#include <SDL.h> //SDL header file
#include <SDL_image.h> //SDL image file
#include <stdio.h> //standard C ouput
#include <string> //standard c++ string
#include <map>
#include <SDL_ttf.h>
using namespace std;
typedef Uint8 u8;
//Texture wrapper class (originally from lazyfoo.net)
class Texture
{
public:
//Initializes variables
Texture();
//Deallocates memory
~Texture();
//Loads image at specified path
bool loadFromFile(std::string path);
//Deallocates texture
void free();
//Renders texture at given point
void render();
//Sets the size of the image
void setSize(int width, int height);
//Adds a clip to the clips map
void addClip(string name, SDL_Rect* aclip);
//Sets the clip
void setClip(string name);
void setNullClip();
//Sets the placement of the object
void setPos(int newx, int newy);
//Moves the position of the object
void movePos(int addx, int addy);
//Gets image dimensions
int getWidth();
int getHeight();
//Sets the color
void setColor(Uint8 red, u8 green, u8 blue);
//Set blending
void setBlendMode(SDL_BlendMode blending);
//Set alpha modulation
void setAlpha(Uint8 alpha);
//Creates image from font string
bool loadFromRenderedText(std::string textureText, SDL_Color textColor);
protected:
//The actual hardware texture
SDL_Texture* mTexture;
//Image dimensions
int mWidth;
int mHeight;
//Image bottom left coordinates
int x;
int y;
//Current clip of image
SDL_Rect* clip;
//Available image clips
map<string, SDL_Rect*> clips;
};
And the function definitions:
#include "Texture.h"
#include "Univar.h"
extern SDL_Renderer* Renderer;
extern TTF_Font* Font;
Texture::Texture()
{
//Initialize
mTexture = NULL;
mWidth = 0;
mHeight = 0;
}
Texture::~Texture()
{
//Deallocate
free();
}
bool Texture::loadFromFile(std::string path)
{
//Get rid of preexisting texture
free();
//The final texture
SDL_Texture* newTexture = NULL;
//Load image at specified path
SDL_Surface* loadedSurface = IMG_Load(path.c_str());
if (loadedSurface == NULL)
{
printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError());
}
else
{
//Color key image
SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, 0, 0xFF, 0xFF));
//Create texture from surface pixels
newTexture = SDL_CreateTextureFromSurface(Renderer, loadedSurface);
if (newTexture == NULL)
{
printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError());
}
else
{
//Get image dimensions
mWidth = loadedSurface->w;
mHeight = loadedSurface->h;
}
//Get rid of old loaded surface
SDL_FreeSurface(loadedSurface);
}
//Return success
mTexture = newTexture;
return mTexture != NULL;
}
void Texture::free()
{
//Free texture if it exists
if (mTexture != NULL)
{
SDL_DestroyTexture(mTexture);
mTexture = NULL;
mWidth = 0;
mHeight = 0;
}
}
void Texture::render()
{
//Set rendering space and render to screen
SDL_Rect renderQuad = { x, y, mWidth, mHeight };
//Set clip rendering dimensions
if (clip != NULL)
{
renderQuad.w = clip->w;
renderQuad.h = clip->h;
}
SDL_RenderCopy(Renderer, mTexture, clip, &renderQuad);
}
void Texture::setSize(int width, int height)
{
mWidth = width;
mHeight = height;
}
void Texture::addClip(string name, SDL_Rect * aclip)
{
clips[name] = aclip;
}
void Texture::setClip(string name)
{
clip = clips[name];
}
void Texture::setNullClip()
{
clip = NULL;
}
void Texture::setPos(int newx, int newy)
{
x = newx;
y = newy;
}
void Texture::movePos(int addx, int addy)
{
x += x;
y += y;
}
int Texture::getWidth()
{
return mWidth;
}
int Texture::getHeight()
{
return mHeight;
}
void Texture::setColor(Uint8 red, u8 green, u8 blue)
{
//Modulate texture
SDL_SetTextureColorMod(mTexture, red, green, blue);
}
void Texture::setBlendMode(SDL_BlendMode blending)
{
//Set blending function
SDL_SetTextureBlendMode(mTexture, blending);
}
void Texture::setAlpha(Uint8 alpha)
{
//Modulate texture alpha
SDL_SetTextureAlphaMod(mTexture, alpha);
}
bool Texture::loadFromRenderedText(std::string textureText, SDL_Color textColor)
{
//Get rid of preexisting texture
free();
//Render text surface
SDL_Surface* textSurface = TTF_RenderText_Solid(Font, textureText.c_str(), textColor);
if (textSurface == NULL)
{
printf("Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError());
}
else
{
//Create texture from surface pixels
mTexture = SDL_CreateTextureFromSurface(Renderer, textSurface);
if (mTexture == NULL)
{
printf("Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError());
}
else
{
//Get image dimensions
mWidth = textSurface->w;
mHeight = textSurface->h;
}
//Get rid of old surface
SDL_FreeSurface(textSurface);
}
//Return success
return mTexture != NULL;
}
Then here is the button class:
#pragma once
#include "Texture.h"
enum MouseState {
Out,
Hover
};
enum Press {
LClick,
RClick,
None
};
class Button : public Texture{
int w;
int h;
int x;
int y;
public:
//Inits the variables
Button(int aw, int ah);
//Handles events
Press handleEvent(SDL_Event* e);
};
And the function definitions:
#include "Button.h"
Button::Button(int aw, int ah) : w(aw), h(ah)
{
setSize(aw, ah);
}
Press Button::handleEvent(SDL_Event * e)
{
//If mouse event happened
if (e->type == SDL_MOUSEMOTION || e->type == SDL_MOUSEBUTTONDOWN || e->type == SDL_MOUSEBUTTONUP)
{
//Get mouse position
int ax, ay;
SDL_GetMouseState(&ax, &ay);
//Check if mouse is in button
bool inside = true;
//Mouse is left of the button
if (ax < x)
{
inside = false;
}
//Mouse is right of the button
else if (ax > x + w)
{
inside = false;
}
//Mouse above the button
else if (ay < y)
{
inside = false;
}
//Mouse below the button
else if (ay > y + h)
{
inside = false;
}
//Mouse is outside button
if (!inside)
{
setClip("out");
return None;
}
//Mouse is inside button
else
{
setClip("Hover");
//Set mouse over sprite
switch (e->button.button)
{
case SDL_BUTTON_LEFT:
return LClick;
break;
case SDL_BUTTON_RIGHT:
return RClick;
break;
default:
return None;
break;
}
}
}
else {
return None;
}
}
And when I run this, I get nothing (well I get a window but without the button in it)! If the button class seams barebones, that's because I'm pretty sure I've narrowed down the error to handleEvent(). I looked through it and couldn't find the error.
I figured out the error. The reason is I'm not used to SDL's coordinate system.
In SDL, the top left is 0,0.
In regular coordinate grids, the bottom left is 0,0.
:(P
Related
I was making a little program to practice pointer usage and rendering.
I was trying to debug an Illegal memory access, and my program crashed.
The problem, is that it crashed and I had to force-quit the debugging session by pressing shift-f5
because my program was taking mouse focus, and I could not click anything.
Now my screen is constantly brighter than before, probably due to an draw operation that was supposed to draw a fullscreen white rectangle.
This will probably be fixed when I restart my PC.... but it is still a problem if this stacks, since I will have to restart every 3 debugging sessions to not burn my eyes.
Any advice on how to ENSURE my program releases resources?
Edit for reproducible example:
#include "SDL.h"
#include "SDL_render.h"
#include <stdio.h>
#include <iostream>
#include <list>
#include <string>
#include <ft2build.h>
#include <SDL_ttf.h>
#include <functional>
#include <memory>
#include FT_FREETYPE_H
struct element {
SDL_Rect* area;
SDL_Texture* texture;
SDL_Surface* surface;
std::string name = "";
std::function<void()> functionPointer;
element(SDL_Rect* rect, SDL_Texture* tex, SDL_Surface* surf, std::string elementName, std::function<void()> fp) {
area = rect;
texture = tex;
surface = surf;
name = elementName;
functionPointer = fp;
}
~element() {
SDL_FreeSurface(surface);
SDL_DestroyTexture(texture);
area = nullptr;
surface = nullptr;
texture = nullptr;
name = "";
functionPointer = nullptr;
}
};
struct screenVariables {
std::list<SDL_Texture*> textureList;
std::list<element*>& elementList;
SDL_Renderer* renderer;
std::list<SDL_Surface*> surfaceList;
screenVariables(std::list<SDL_Texture*> tex, std::list<element*> rec, SDL_Renderer* render,std::list<SDL_Surface*> surf) :
textureList(tex),elementList(rec), renderer(render),surfaceList(surf) {};
};
class gameHandler{
private:
SDL_Window* screen;
SDL_Renderer* renderer;
SDL_Texture* mainBlock;
bool saveAvailable = false;
bool quit = false;
std::list<SDL_Texture*> textureList;
std::list<element*> elementList;
std::list<SDL_Surface*> surfaceList;
screenVariables screenInfo{ textureList, elementList, renderer, surfaceList };
void nothing() {};
void continuePressed() {};
void newGame() {};
public:
gameHandler() {
SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_EVENTS);
TTF_Init();
screen = SDL_CreateWindow("Game Window",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
1920, 1080,
SDL_WINDOW_FULLSCREEN | SDL_WINDOW_OPENGL);
renderer = SDL_CreateRenderer(screen, -1, 0);
mainBlock = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ABGR8888,
SDL_TEXTUREACCESS_TARGET, 1920, 1080);
}
//All methods that do operations on elements will operate on the LAST ADDED ELEMENT. Always create a new element and use push_back() to add it to the end.
//Everything commented out is not nessesary for reproduction, but
//will be left for reference.
/*bool showFirstElement(screenVariables& arg, const char* imgPath, SDL_Rect* area) {
SDL_Renderer* renderRef = arg.renderer;
//The following line means: end() returns an iterator, take the iterator and make it go back once, then deference it to get the value.
//This gets the value of the last added surface.
SDL_Surface* newSurface = *(--(arg.surfaceList.end()));
newSurface = SDL_LoadBMP(imgPath);
SDL_Texture* newTexture = *(--(arg.textureList.end()));
newTexture = SDL_CreateTextureFromSurface(renderRef, newSurface);
std::function<void()> nothingWrapper = [&]() { nothing(); };
element* toBeModified = *(--(arg.elementList.end()));
toBeModified->element::area = area;
toBeModified->texture = newTexture;
toBeModified->surface = newSurface;
toBeModified->name = imgPath;
toBeModified->functionPointer = nothingWrapper;
arg.elementList.push_back(toBeModified);
SDL_RenderCopy(renderRef, newTexture, NULL, area);
return true;
}
bool textOnElement(screenVariables& arg, const char* text,int points, element* el) {
SDL_Renderer* renderRef = arg.renderer;
TTF_Font* font = NULL;
SDL_Color textColor = { 0,0,0 };
font = TTF_OpenFont("TravelingTypewriter.ttf", points);
SDL_Surface* newSurface = *(--(arg.surfaceList.end()));
newSurface = TTF_RenderText_Solid(font,text,textColor);
SDL_Texture* newTexture = *(--(arg.textureList.end()));
newTexture = SDL_CreateTextureFromSurface(renderRef, newSurface);
el->surface = newSurface;
el->texture = newTexture;
SDL_RenderCopy(renderRef, newTexture, NULL, el->area);
return true;
}
element* checkClickedElement(screenVariables& arg, SDL_Point pos) {
for (element* i : arg.elementList) {
if (SDL_PointInRect(&pos, i->area)) {
return i;
}
return nullptr;
}
}
bool fillWithColor(screenVariables& arg, Uint32 red, Uint32 green, Uint32 blue, Uint32 alpha) {
SDL_Renderer* renderRef = arg.renderer;
SDL_Surface* surface = SDL_CreateRGBSurface(0, 1920, 1080, 8, red, green, blue, alpha);
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderRef, surface);
SDL_Rect fullScreen = { 1920,1080 };
std::string name = "R" + std::to_string(red) + "G" + std::to_string(green) + "B" + std::to_string(blue);
std::function<void()> nothingWrapper = [&]() { nothing(); };
element newElement = element(&fullScreen, texture, surface, name, nothingWrapper);
SDL_RenderCopy(renderRef, texture, NULL, NULL);
return true;
}
bool fillElementPointer(screenVariables& arg, SDL_Point leftTop, SDL_Point rightBottom, std::function<void()> fp,std::string name,element* newElement) {
SDL_Rect newRect;
newRect.x = (leftTop.x + rightBottom.x) / 2;
newRect.y = (leftTop.y + rightBottom.y) / 2;
newRect.w = (rightBottom.x - leftTop.x);
newRect.h = (leftTop.y - rightBottom.y);
newElement = &element(&newRect, nullptr, nullptr, name, fp);
arg.elementList.push_back(newElement);
return true;
}
//This allows me to create pointers that will not go out of scope when methods return. Always use this method if the element you will create needs to presist through functions.
element* createElementPointer(){
element* newPointer = nullptr;
return newPointer;
}
int showMenu(screenVariables& arg) {
fillWithColor(arg, 255, 255, 255, 255);
SDL_Point leftTop = { 200,700 };
SDL_Point rightBottom = { 600,200 };
std::function<void()> nothingWrapper = [&]() { nothing(); };
element* titleText = createElementPointer();
if (!fillElementPointer(screenInfo, leftTop, rightBottom, nothingWrapper, "titleText", titleText)) {
std::cout << "createElement failed in showMenu()";
}
leftTop.y = 100;
rightBottom.x = 0;
element* continueOrStart = createElementPointer();
if (saveAvailable) {
std::function<void()> continueWrapper = [&]() { continuePressed(); };
if (!fillElementPointer(screenInfo, leftTop, rightBottom, continueWrapper, "continueButton", continueOrStart)) {
std::cout << "createElement failed in showMenu() saveAvailable.";
}
textOnElement(arg, "Continue", 16, continueOrStart);
}
else {
std::function<void()> newGameWrapper = [&]() { newGame(); };
if (!fillElementPointer(screenInfo, leftTop, rightBottom, newGameWrapper, "newGameButton", continueOrStart)) {
std::cout << "createElement failed in showMenu() !saveAvailable.";
}
textOnElement(arg, "New Game", 16, continueOrStart);
}
return 0;
}
void mainLoop() {
SDL_Event event;
showMenu(screenInfo);
while (!quit) {
SDL_RenderClear(renderer);
while (SDL_PollEvent(&event) != 0) {
switch (event.type)
{
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == SDL_BUTTON_LEFT) {
SDL_Point position = { event.button.x,event.button.y };
element* result = checkClickedElement(screenInfo, position);
if (result == nullptr) {
break;
}
else {
result->functionPointer();
}
}
break;
case SDL_QUIT:
quit = true;
break;
}
}
SDL_RenderPresent(renderer);
}
}
void clearResources() {
int index{ 0 };
for (element* i : screenInfo.elementList) {
delete i;
}
SDL_DestroyRenderer(renderer);
SDL_Quit();
} */
};
int main(int argc, char* argv[]) {
gameHandler handler; //This alone makes my screen brighter.
//Uncomment every function and let mainLoop() run, and it crashes.
//Although many attempts at making this exception safe, it did not work.
//handler.mainLoop();
return 0;
}
Im constantly getting a redefinition of default argument parameter 1 error and its preventing from building the project successfully to test code as I include it. Im relatively new to C++ and this form of building a game, having multiple header and cpp files referencing eachother.
Texture2D.cpp:
#include <iostream>
#include <SDL_image.h>
#include <string>
#include "Texture2D.h"
#include "Constants.h"
#include "Commons.h"
using namespace::std;
Texture2D::Texture2D(SDL_Renderer* renderer)
{
SDL_Renderer* mRenderer = NULL;
SDL_Texture* mTexture = NULL;
mWidth = 0;
mHeight = 0;
}
Texture2D::~Texture2D()
{
Free();
mRenderer = NULL;
}
bool Texture2D::LoadFromFile(string path)
{
//remove the memory used for a previous texture
Free();
SDL_Texture* mTexture = NULL;
//load the image
SDL_Surface* pSurface = IMG_Load(path.c_str());
mWidth = pSurface->w;
mHeight = pSurface->h;
if (pSurface != NULL)
{
mTexture = SDL_CreateTextureFromSurface(mRenderer, pSurface);
if (mTexture == NULL)
{
cout << "Unable to create texture from surface. Error: " << SDL_GetError() << endl;
}
//Color key the image - The color to be transparent
SDL_SetColorKey(pSurface, SDL_TRUE, SDL_MapRGB(pSurface->format, 0, 0xFF, 0xFF));
SDL_FreeSurface(pSurface);
return mTexture;
}
else
{
cout << "Unable to create texture from surface. Error: " << IMG_GetError() << endl;
}
}
void Texture2D::Render(Vector2D newPosition, SDL_RendererFlip flip, double angle = 0.0f)
{
//clear the screen
SDL_SetRenderDrawColor(mRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(mRenderer);
//set where to render the texture
SDL_Rect renderLocation = { 0, 0, mWidth, mHeight };
//render to screen
SDL_RenderCopyEx(mRenderer, mTexture, NULL, &renderLocation, 0, NULL, SDL_FLIP_NONE);
SDL_RenderPresent(mRenderer);
}
void Texture2D::Free()
{
if (mTexture != NULL)
{
SDL_DestroyTexture(mTexture);
mTexture = NULL;
mWidth = 0;
mHeight = 0;
}
}
Texture2D.h:
#pragma once
#ifndef _TEXTURE2D_H
#define _TEXTURE2D_H
#include <SDL.h>
#include <SDL_image.h>
#include <map>
#include <string>
#include "Commons.h"
class Texture2D
{
public:
Texture2D(SDL_Renderer* renderer);
~Texture2D();
bool LoadFromFile(std::string path);
void Free();
void Render(Vector2D newPosition, SDL_RendererFlip flip, double angle = 0.0f);
int GetWidth() { return mWidth; }
int GetHeight() { return mHeight; }
private:
SDL_Renderer* mRenderer;
SDL_Texture* mTexture;
int mWidth;
int mHeight;
};
#endif //_TEXTURE2D_H
Commons.h:
#pragma once
#ifndef _COMMONS_H
#define _COMMONS_H
struct Vector2D
{
Vector2D()
{
x = 0.0f;
y = 0.0f;
}
float x;
float y;
};
struct InitialVector2D
{
InitialVector2D()
{
initialx = 0.0f;
initialy = 0.0f;
}
float initialx;
float initialy;
};
enum SCREENS
{
SCREEN_INTRO = 0,
SCREEN_MENU,
SCREEN_LEVEL1,
SCREEN_LEVEL2,
SCREEN_GAMEOVER,
SCREEN_HIGHSCORES
};
#endif //_COMMONS_H
When giving a default parameter, you should only add the default in the header declaration. So, changing:
void Texture2D::Render(Vector2D newPosition, SDL_RendererFlip flip, double angle = 0.0f)
to:
void Texture2D::Render(Vector2D newPosition, SDL_RendererFlip flip, double angle)
should fix the error.
Simply remove the default specification here: void Texture2D::Render(Vector2D newPosition, SDL_RendererFlip flip, double angle = 0.0f) As the compiler tells you, that was already given in the function declaration. – πάντα ῥεῖ 47 mins ago
I keep getting this issue when I run my program. My images fail to load in with the error: "Invalid texture". The program used to work fine. I'm working on it in linux ubuntu with all of my drivers updated. Here is the code where the renderer is made and the images are loaded.
//init.h
//#pragma once
#ifndef INIT_H
#define INIT_H
static const int SCREEN_WIDTH = 480;
static const int SCREEN_HEIGHT = 480;
static SDL_Surface* currentSurface = NULL;
static SDL_Window* window = NULL;
static SDL_Surface* screenSurface = NULL;
static SDL_Renderer* renderer = NULL;
//static SDL_Surface *SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 0, SDL_ANYFORMAT);
bool init();
void close();
//void SetColor(int value);
#endif // INIT_H
//init.cpp
//#include "stdafx.h"
#include <stdio.h>
#include "tchar.h"
#include <SDL2/SDL.h>
#include <iostream>
#include <SDL2/SDL_image.h>
#include "main.h"
#include "init.h"
#include "load.h"
//#include <conio.h>
//#include <Windows.h>
#include <string>
#include <SDL2/SDL_ttf.h>
#include <cmath>
bool init()
{
bool boot = 1;
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
//SetColor(4);
printf("SDL failed to initialize \n");
//SetColor(7);
boot = 0;
}
else {
printf("SDL initialized!\n");
window = SDL_CreateWindow("Light Development Project", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
if (window == NULL)
{
//SetColor(4);
printf("SDL failed to create the window \n");
//SetColor(7);
boot = 0;
}
else {
printf("Window created!\n");
//screenSurface = SDL_GetWindowSurface(window);
printf("Screen surface created!\n");
}
printf("Initializing SDL_image...\n");
int imgFlags = IMG_INIT_PNG;
if (!(IMG_Init(imgFlags) & imgFlags))
{
//SetColor(4);
printf("Failed to initialize SDL_image\n");
//SetColor(7);
boot = 0;
}
else {
printf("SDL_image initialized!\n");
}
printf("Initializing TTF...\n");
if (TTF_Init() == -1)
{
//SetColor(4);
printf("Failed to initialize TTF\n");
//SetColor(7);
boot = 0;
}
else {
printf("TTF initialized!\n");
}
printf("Creating renderer...\n");
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL)
{
//SetColor(4);
printf("Failed to create renderer. Error: %s\n", SDL_GetError());
//SetColor(7);
boot = 0;
} else
printf("Renderer created!\n");
printf("Setting render draw color...\n");
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
printf("Render draw color set!\n");
}
//printf("Done!\n");
return boot;
}
void close()
{
printf("\nShutting down...\nFreeing SDL surfaces...\nDetroying textures and renderers...\n");
SDL_DestroyTexture(texture);
texture = NULL;
SDL_DestroyRenderer(renderer);
renderer = NULL;
printf("SDL surfaces, textures, and renderers freed from memory!\nDestroying SDL window...\n");
SDL_DestroyWindow(window);
//TTF_CloseFont(font);
//font = NULL;
window = NULL;
printf("SDL window detroyed!\nQuitting SDL subsystems...\n");
IMG_Quit();
SDL_Quit();
//TTF_Quit();
printf("All SDL subsystems shutdown!\n");
}
/*void SetColor(int value) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), value);
/*
1: Blue
2: Green
3: Cyan
4: Red
5: Purple
6: Yellow (Dark)
7: Default white
8: Gray/Grey
9: Bright blue
10: Brigth green
11: Bright cyan
12: Bright red
13: Pink/Magenta
14: Yellow
15: Bright white
}
*/
//load.h
//#pragma once
#ifndef LOAD_H
#define LOAD_H
enum KeyPressSurfacese
{
KEY_PRESS_SURFACE_DEFUALT,
KEY_PRESS_SURFACE_UP,
KEY_PRESS_SURFACE_DOWN,
KEY_PRESS_SURFACE_LEFT,
KEY_PRESS_SURFACE_RIGHT,
KEY_PRESS_SURFACE_TOTAL
};
class cTexture {
public:
cTexture();
~cTexture();
bool loadFromFile(std::string path);
void free();
void render(int x, int y, SDL_Rect* clip = NULL, double angle = 0.0, SDL_Point* center = NULL, SDL_RendererFlip flip = SDL_FLIP_NONE);
void loadFromRenderedText(std::string text, SDL_Color color);
void setColor(Uint8 red, Uint8 green, Uint8 blue);
void setBlendMode(SDL_BlendMode blending);
void setAlpha(Uint8 alpha);
int getWidth();
int getHeight();
private:
SDL_Texture * hTexture;
int hWidth;
int hHeight;
};
static cTexture keyPresses[KEY_PRESS_SURFACE_TOTAL];
static cTexture sprite;
static cTexture text;
static SDL_Texture* loadTexture(std::string path);
static SDL_Rect spriteClips[4];
//TTF_Font* font = NULL;
static SDL_Color textColor = { 0, 0, 0 };
void loadAssets();
#endif //LOAD_H
//load.cpp
//#include "stdafx.h"
#include <stdio.h>
#include "tchar.h"
#include <SDL2/SDL.h>
#include <iostream>
#include <SDL2/SDL_image.h>
#include "main.h"
#include "init.h"
#include "load.h"
//#include <conio.h>
//#include <Windows.h>
#include <string>
#include <SDL2/SDL_ttf.h>
#include <cmath>
cTexture::cTexture()
{
//printf("Constructing texture wrapper class...\n");
hTexture = NULL;
hWidth = 0;
hHeight = 0;
}
cTexture::~cTexture()
{
//printf("Destroying texture wrapper class...\n");
free();
}
void cTexture::free()
{
//if (hTexture != NULL)
SDL_DestroyTexture(hTexture);
hTexture = NULL;
hWidth = 0;
hHeight = 0;
}
bool cTexture::loadFromFile(std::string path)
{
free();
SDL_Texture* newTexture = NULL;
SDL_Surface* loadedSurface = IMG_Load(path.c_str());
newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface);
if(newTexture == NULL)
//printf("fail. error: %s\n", SDL_GetError());
hWidth = loadedSurface->w;
hHeight = loadedSurface->h;
SDL_FreeSurface(loadedSurface);
hTexture = newTexture;
return hTexture != NULL;
}
void cTexture::render(int x, int y, SDL_Rect * clip, double angle, SDL_Point * center, SDL_RendererFlip flip)
{
//SDL_Rect renderQuad = { x, y, hWidth, hHeight };
SDL_Rect renderQuad = { x, y, 480, 480 };
if (clip != NULL)
{
renderQuad.w = clip->w;
renderQuad.h = clip->h;
}
SDL_RenderCopyEx(renderer, hTexture, clip, &renderQuad, angle, center, flip);
}
/*
void cTexture::loadFromRenderedText(std::string text, SDL_Color color)
{
free();
SDL_Surface* textSurface = TTF_RenderText_Solid(font, text.c_str(), textColor);
hTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
hWidth = textSurface->w;
hHeight = textSurface->h;
SDL_FreeSurface(textSurface);
}
*/
void cTexture::setColor(Uint8 red, Uint8 green, Uint8 blue)
{
SDL_SetTextureColorMod(hTexture, red, green, blue);
}
void cTexture::setBlendMode(SDL_BlendMode blending)
{
SDL_SetTextureBlendMode(hTexture, blending);
}
void cTexture::setAlpha(Uint8 alpha)
{
SDL_SetTextureAlphaMod(hTexture, alpha);
}
int cTexture::getWidth() { return hWidth; }
int cTexture::getHeight() { return hHeight; }
void loadAssets()
{
printf("Loading image assets in loadAssets()...\n");
if (!keyPresses[KEY_PRESS_SURFACE_DEFUALT].loadFromFile("carrot.png"))
{
//SetColor(4);
printf("Failed to load image. Error: %s\n", SDL_GetError());
//SetColor(7);
} else
printf("Image loaded\n");
if(!keyPresses[KEY_PRESS_SURFACE_UP].loadFromFile("smIamLU.jpg"))
{
//SetColor(4);
printf("Failed to load image\n");
//SetColor(7);
}
else {
//keyPresses[KEY_PRESS_SURFACE_UP].setBlendMode(SDL_BLENDMODE_BLEND);
printf("Image loaded\n");
}
if(!keyPresses[KEY_PRESS_SURFACE_DOWN].loadFromFile("down.bmp"))
{
//SetColor(4);
printf("Failed to load image\n");
//SetColor(7);
} else
printf("Image loaded\n");
if(!keyPresses[KEY_PRESS_SURFACE_LEFT].loadFromFile("left.bmp"))
{
//SetColor(4);
printf("Failed to load image\n");
//SetColor(7);
}else
printf("Image loaded\n");
if(!keyPresses[KEY_PRESS_SURFACE_RIGHT].loadFromFile("right.bmp"))
{
//SetColor(4);
printf("Failed to load image\n");
//SetColor(7);
}else
printf("Image loaded\n");
if (!sprite.loadFromFile("foo.png"))
{
//SetColor(4);
printf("Failed to load image\n");
//SetColor(7);
}else
printf("Image loaded\n");
spriteClips[0].x = 0;
spriteClips[0].y = 0;
spriteClips[0].w = 64;
spriteClips[0].h = 205;
spriteClips[1].x = 64;
spriteClips[1].y = 0;
spriteClips[1].w = 64;
spriteClips[1].h = 205;
spriteClips[2].x = 128;
spriteClips[2].y = 0;
spriteClips[2].w = 64;
spriteClips[2].h = 205;
spriteClips[3].x = 192;
spriteClips[3].y = 0;
spriteClips[3].w = 64;
spriteClips[3].h = 205;
//font = TTF_OpenFont("Ubuntu-L.ttf", 28);
//text.loadFromRenderedText("text", textColor);
printf("Done!\n");
}
With the renderer I've tried making it with differnt flags such as SDL_RENDERER_ACCELERATED or SDL_RENDERER_SOFTWARE but neither work. The error is specifically coming from the load.cpp file
newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface);
This is the line that fails. The error generated by SDL reads "Invalid texture". The renderer is declared correctly but I can't get it to work.
I'm so confused why it isn't working because it used to work fine. I abandoned the project for a few months and it was working when I stopped, came back, and now it doesn't work. Not to mention that I had a bunch of more problems that I already worked out, but this one I can't.
I figured it out and it's the strangest fix I've ever done. I added an error check for the renderer in the load function and it started working again. If I remove the error check if statement it goes back to not working. Seems like a strange bug but I'm glad it's working again.
I'm making a basic program using SDL to render graphics. I have two classes that deal with Rendering:
A Texture class (that loads and renders the SDL_textures)
//Texture warpper class
class LTexture
{
private:
//The actual texture
SDL_Texture* mTexture;
//Image demensions
int mWidth;
int mHeight;
public:
//Initializes/Deallocates variables
LTexture();
~LTexture();
LTexture(const LTexture &rhs);
//Loads image at specified path
bool loadFromFile(std::string path);
//Deallocates texture
void free();
//Renders texture at given point
void render(int x, int y);
//Gets image dimensions
int getWidth();
int getHeight();
};
LTexture::LTexture()
{
//Initialize
mTexture = NULL;
mWidth = 0;
mHeight = 0;
}
LTexture::~LTexture()
{
//Deallocate
free();
}
LTexture::LTexture(const LTexture &rhs)
{
mTexture = rhs.mTexture;
mWidth = rhs.mWidth;
mHeight = rhs.mHeight;
}
bool LTexture::loadFromFile(std::string path)
{
//Get rid of preexisting texture
free();
//The final texture
SDL_Texture* newTexture = NULL;
//Load image at specified path
SDL_Surface* loadedSurface = IMG_Load(path.c_str());
if (loadedSurface == NULL)
{
printf("Unable to load image %s! SDL_image error: %s\n", path.c_str(), IMG_GetError());
}
else
{
//Create texture from surface pixels
newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface);
if (newTexture == NULL)
{
printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError());
}
else
{
//Get image dimensions
mWidth = loadedSurface->w;
mHeight = loadedSurface->h;
}
//Get rid of old loaded surface
SDL_FreeSurface(loadedSurface);
}
//Return success
mTexture = newTexture;
return mTexture != NULL;
}
void LTexture::free()
{
//Free Texture if it exists
if (mTexture != NULL)
{
SDL_DestroyTexture(mTexture);
mTexture = NULL;
mWidth = 0;
mHeight = 0;
}
}
void LTexture::render(int x, int y)
{
//Set rendering space and render to screen
SDL_Rect renderQuad = { x, y, mWidth, mHeight };
SDL_RenderCopy(gRenderer, mTexture, NULL, &renderQuad);
printf("Rendering...\n");
if (mTexture == NULL)
{
printf("No texture loaded!\n");
}
else
{
printf("Texture loaded! %s\n", mTexture);
}
}
int LTexture::getWidth()
{
return mWidth;
}
int LTexture::getHeight()
{
return mHeight;
}
And a Button class(That is supposed to make it easier to switch between the different textures associated with the states of the buttons. Each object is supposed to have 3 texture objects within the button).
Declaration:
//Class for buttons and chips
class Button
{
public:
//Initializes internal variables
Button();
//Handles mouse events
void handleEvent(SDL_Event* e);
//Render buttons
void render();
//Sets top left position
void setPosition(int x, int y);
//Gets image dimensions
void setWidth(int w);
void setHeight(int h);
//Set button status
void setButtonAction(buttonAction action);
//Get button status
buttonStatus getButtonStatus();
//Perform button action !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!FIXME::HAVEN'T DEFINED!!!!!!!!!!!!!!!!!!!!!!!!!!!!1!!
void activateButton(buttonAction action);
void setTextures(LTexture out, LTexture over, LTexture down);
private:
//Top left position
SDL_Point mPosition;
//Currently used global image
buttonStatus mButtonStatus;
//What happens if button is pressed
buttonAction mButtonAction;
//Width and height
int mWidth;
int mHeight;
//Textures
LTexture mOut;
LTexture mOver;
LTexture mDown;
};
Button::Button()
{
mPosition.x = 0;
mPosition.y = 0;
mWidth = 0;
mHeight = 0;
mButtonStatus = MOUSE_OUT;
}
void Button::setPosition(int x, int y)
{
mPosition.x = x;
mPosition.y = y;
}
void Button::handleEvent(SDL_Event* e)
{
bool mInside = true;
//If mouse event happened
if (e->type == SDL_MOUSEBUTTONDOWN || e->type == SDL_MOUSEMOTION)
{
//Get mouse position
int x, y;
SDL_GetMouseState(&x, &y);
//Mouse is left of the button
if (x < mPosition.x)
{
mInside = false;
}
//Mouse is right of button
else if (x > mPosition.x + mWidth)
{
mInside = false;
}
//Mouse is above button
else if (y < mPosition.y)
{
mInside = false;
}
//Mouse is below button
else if (y > mPosition.y + mHeight)
{
mInside = false;
}
//Logic\\
//Mouse is outside of button
if (!mInside)
{
mButtonStatus = MOUSE_OUT;
}
//Mouse is inside of button
else
{
switch (e->type)
{
case SDL_MOUSEMOTION:
mButtonStatus = MOUSE_OVER;
break;
case SDL_MOUSEBUTTONDOWN:
mButtonStatus = MOUSE_BUTTON_DOWN;
break;
}
}
}
}
void Button::render()
{
switch (mButtonStatus)
{
case MOUSE_OUT:
mOut.render(mPosition.x, mPosition.y);
printf("Out rendered\n");
break;
case MOUSE_OVER:
mOver.render(mPosition.x, mPosition.y);
printf("Over rendered\n");
break;
case MOUSE_BUTTON_DOWN:
mDown.render(mPosition.x, mPosition.y);
printf("Down rendered\n");
break;
}
}
void Button::setWidth(int w)
{
mWidth = w;
}
void Button::setHeight(int h)
{
mHeight = h;
}
void Button::setButtonAction(buttonAction action)
{
mButtonAction = action;
}
buttonStatus Button::getButtonStatus()
{
return mButtonStatus;
}
void Button::setTextures(LTexture out, LTexture over, LTexture down)
{
mOut = out;
mOver = over;
mDown = down;
}
Unfortunately, when I try to use a copy constructor to pass the SDL_Texture value from the original Texture to the buttons Private texture, it doesn't pass any value, but still thinks that it's not "NULL"
There's two problems with this code that I can see.
The first is that in the LTexture copy constructor, you only copy the pointer to the SDL_Texture. This is called a shallow copy. Then, in the destructor of LTexture, you call free(), which deletes the SDL_Texture. This is bad, because it means that any duplicates of the LTexture now have pointers to textures that have been deleted, so they will no longer work. The best two solutions here are either to use a c++11 class called shared_ptr to store the texture, which will prevent it from being deleted, or actually make a copy of the texture and point to the new one (a deep copy). For testing, you could try just commenting out the call to SDL_DestroyTexture in free().
Additionally, you forgot to implement the assignment operator. Currently it behaves just like the copy constructor (since all you do is a shallow copy), but if you make it a deep copy, you'll have to implement that as well.
For some strange reason whenever I try to split a larger image file into (in my case) a 32x32 picture, but instead I get the entire picture that seems to be squished down into 32x32(the picture as a whole). Although after playing around with the values I realized that for some reason the SDL has completely ignored my request to use the SDL_Rect source(src).
Meaning that every value that I change the source(src) rectangle to doesn't change the actual image when I run the program (even a ridiculous value).
Sprite.h
#ifndef SPRITE_H_
#define SPRITE_H_
#pragma once
#include "Game.h"
struct Game;
struct Sprite
{
//Needs to be fixed :/
//Sprite(const std::string& filepath,int x,int y,int width, int height,Game*game);
Sprite();
~Sprite();
void Load(const std::string& filepath, int x, int y,int width,int height, Game*game);
void Draw(Game*game);
SDL_Rect*getDstRect(){ return &dst; }
SDL_Rect*getSrcRect(){ return &src; }
private:
SDL_Surface*surface = NULL;
SDL_Texture*texture = NULL;
SDL_Rect src;
SDL_Rect dst;
int img_width;
int img_height;
};
#endif // SPRITE_H_
Sprite.cpp
#include "Sprite.h"
Sprite::Sprite()
{
}
Sprite::~Sprite()
{
SDL_DestroyTexture(texture);
surface = NULL;
texture = NULL;
}
void Sprite::Load(const std::string& filepath, int x, int y, int width, int height, Game*game)
{
bool success = true;
surface = IMG_Load(filepath.c_str());
if (surface == NULL)
{
game->getConsole()->Error("SPRITE::Surface Is Not Loaded");
success = false;
}
else
game->getConsole()->Text("SPRITE::Surface Is Loaded");
texture = SDL_CreateTextureFromSurface(game->getRenderer(), surface);
if (texture == NULL)
{
game->getConsole()->Error("SPRITE::Texture Is Not Loaded");
success = false;
}
else
game->getConsole()->Text("SPRITE::Texture is Loaded");
dst.x = x;
dst.y = y;
dst.w = height;
dst.h = height;
src.x = 0;
src.y = 0;
src.w = 0;
src.h = 0;
SDL_QueryTexture(texture, NULL, NULL, &src.w, &src.h);
SDL_FreeSurface(surface);
if (success)
game->getConsole()->Text("Loaded Sprite at " + filepath);
else
game->getConsole()->Error("SPRITE::Failed To Load Sprite at " + filepath);
}
void Sprite::Draw(Game*game)
{
SDL_RenderCopy(game->getRenderer(), texture, &src,&dst);
}
Part of the Map Class
testPlayer.Load("bin/sprites/player.png", 200,200,32,32, game);
This is where I have tried to change the values of the destination(dst) rectangle after messing with the source(src) rectangle.
https://wiki.libsdl.org/SDL_RenderCopy
dstrect - the destination SDL_Rect structure or NULL for the entire rendering target. The texture will be stretched to fill the given rectangle.
Short version - adjust source rect to have the same width and height as destination rect, and {x, y} to have starting position of fragment you want to extract.