SDL2 Access violation multiple windows - c++

I am developing SDL2 application which needs to have multiple windows on multiple monitors. And I am getting access violation when drawing string with SDL_ttf library. I should also mention that Application is opening windows in separate threads and is working ok if there is no SDL_ttf used.
I get this for exception when using SDL_ttf:
Unhandled exception at 0x0F2BC191 (SDL2.dll) in SDLMultipleWindows.exe: 0xC0000005: Access violation writing location 0x0100000C.
And access violation is happening in this function:
bool loadFromRenderedText( std::string textureText, SDL_Color textColor )
{
SDL_Surface* textSurface = TTF_RenderText_Solid( gFont, textureText.c_str(), textColor );
SDL_Texture * mTexture = NULL;
int w, h;
if( textSurface != NULL )
{
mTexture = SDL_CreateTextureFromSurface( renderer, textSurface );
w = textSurface->w;
h = textSurface->h;
SDL_FreeSurface( textSurface );
}
else
{
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
}
SDL_Rect renderQuad = { 250, 300, w, h };
int result = SDL_RenderCopyEx( renderer, mTexture, NULL, &renderQuad, 0.0, NULL, SDL_FLIP_NONE );
OutputDebugString(SDL_GetError());
return true;
}
Exception happens on SDL_CreateTextureFromSurface(renderer, textSurface);
This is stack trace from Visual studio:
SDL2.dll!SDL_malloc_REAL(unsigned int bytes) Line 4206 C
SDL2.dll!SDL_calloc_REAL(unsigned int n_elements, unsigned int elem_size) Line 4406 C
SDL2.dll!SDL_CreateRGBSurface_REAL(unsigned int flags, int width, int height, int depth, unsigned int Rmask, unsigned int Gmask, unsigned int Bmask, unsigned int Amask) Line 53 C
SDL2.dll!SDL_ConvertSurface_REAL(SDL_Surface * surface, const SDL_PixelFormat * format, unsigned int flags) Line 840 C
SDL2.dll!SDL_CreateTextureFromSurface_REAL(SDL_Renderer * renderer, SDL_Surface * surface) Line 536 C
SDL2.dll!SDL_CreateTextureFromSurface(SDL_Renderer * a, SDL_Surface * b) Line 342 C
SDLMultipleWindows.exe! loadFromRenderedText(std::basic_string<char,std::char_traits<char>,std::allocator<char> > textureText, SDL_Color textColor) Line 162 C++
Am I doing something wrong or SDL_ttf or SDL2 cannot work on multiple threads?
Is there another way to draw string in SDL2?
Thanks!
Edit:
Adding part of existing code:
ClientWindows::ClientWindows(void)
{
SDL_Init(SDL_INIT_EVERYTHING);
IMG_Init(IMG_INIT_PNG);
TTF_Init();
}
Tread function:
void ClientWindows::WindowThread(int i)
{
AppWindow* rWindow = new AppWindow(i * 1024, 0);
Windows.push_back(rWindow);
rWindow->InitScreen();
}
Start graphics function:
void ClientWindows::StartGraphics(int number)
{
for(int i= 0; i<number; i++)
{
std::thread* wTread = new std::thread(&ClientWindows::WindowThread,this , i);
Threads.push_back(wTread);
}
.
.
.
Client window Constructor:
AppWindow::AppWindow(int x, int y)
{
quit = false;
SCREEN_WIDTH = 1024;
SCREEN_HEIGHT = 768;
imagePositionX = 50;
imagePositionY = 50;
speed_x = 10;
speed_y = 10;
moveX = 10;
moveY = 10;
std::ostringstream convert;
convert << "Graphics";
convert << x;
string name = convert.str();
window = SDL_CreateWindow(name.c_str(), x,
y, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL);
if (window == nullptr){
std::cout << SDL_GetError() << std::endl;
}
opengl3_context = SDL_GL_CreateContext(window);
SDL_assert(opengl3_context);
mt.lock();
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == nullptr){
std::cout << SDL_GetError() << std::endl;
}
mt.unlock();
background = nullptr,image = nullptr;
background = SDLLoadImage("../res/Image1024x768.png");
image = SDLLoadImage("../res/Image1024Classic.png");
animeImage = SDLLoadImage("../res/32_80x80.png");
gFont = TTF_OpenFont("../res/sample.ttf", 28);
}
Client window startGraphics function:
void AppWindow::InitScreen(void)
{
Clear();
Render();
Present();
//Init fps
countedFrames = 0;
fpsTimer.start();
//For tracking if we want to quit
Uint32 frameRate = 0;
while (!quit)
{
if (fpsTimer.getTicks() > frameRate + 15)
{
frameRate = fpsTimer.getTicks();
Clear();
Render();
Present();
}
SDL_Delay(5);
}
}
Function in question:
bool AppWindow::loadFromRenderedText(std::string textureText, SDL_Color textColor)
{
SDL_Surface* textSurface = TTF_RenderText_Solid( gFont, textureText.c_str(), textColor );
SDL_Texture * mTexture = NULL;
int w, h;
if( textSurface != NULL )
{
mTexture = SDL_CreateTextureFromSurface( renderer, textSurface );
w = textSurface->w;
h = textSurface->h;
SDL_FreeSurface( textSurface );
}
else
{
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
}
SDL_Rect renderQuad = { 250, 300, w, h };
int result = SDL_RenderCopyEx( renderer, mTexture, NULL, &renderQuad, 0.0, NULL, SDL_FLIP_NONE );
OutputDebugString(SDL_GetError());
return true;
}

You can't use SDL2 functions from other threads than the one in which the rendering context was created, SDL2 guarantees no thread safety for drawing functions.
If I recall correctly, the only thread safe part of SDL2 is pushing custom events to the event queue.
So I'm guessing the AccessViolation occurs because you're trying to use the renderering context from another thread than from on the one which it was created on.

Related

How to load multiple images in SDL_image and SDL2?

I've been trying to load 2 images in a SDL window, like a player and an enemy, but SDL2_image loads only one image at a time
here's my code :
#include<iostream>
#define SDL_MAIN_HANDLED
#include<SDL2/SDL.h>
#include<SDL2/SDL_image.h>
using namespace std;
SDL_Texture* load(SDL_Renderer* ren, const char* path, SDL_Rect rect)
{
SDL_Texture* img = IMG_LoadTexture(ren, path);
if (img == NULL)
cout << SDL_GetError() << endl;
SDL_RenderClear(ren);
SDL_RenderCopy(ren, img, NULL, &rect);
SDL_RenderPresent(ren);
return img;
}
int main()
{
SDL_Init(SDL_INIT_EVERYTHING);
IMG_Init(IMG_INIT_PNG);
SDL_Window* window = SDL_CreateWindow("SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 460, 380, SDL_WINDOW_RESIZABLE);
SDL_Surface* icon = IMG_Load("sdl.png");
SDL_SetWindowIcon(window, icon);
SDL_Renderer* ren = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_Rect rect,r2;
rect.x = 0; r2.x = 65;
rect.y = 0; r2.y = 80;
rect.w = 64; r2.w = 64;
rect.h = 64; r2.h = 64;
SDL_Texture* img = load(ren, "player.png", rect);
SDL_Delay(2000);
SDL_Texture* tex = load(ren, "enemy.png", r2);
SDL_Event events; bool running = true;
while (running == true)
{
if (SDL_PollEvent(&events))
{
if (events.type == SDL_QUIT)
{
running = false;
break;
}
}
}
IMG_Quit();
SDL_Quit();
return 0;
}
I used SDL_Delay to demonstrate what happens
it loads "player.png" first and then after 2 seconds, it loads "enemy.png"
I wanted to load both at the same time but I couldn't
Please help!
solved, it was due to SDL_RenderClear

Inconsistent C26496 warning

I recently refactored my SDL2 C++ code using structs. It compiles and runs fine (using Visual Studio 2019), but is now throwing out an inconsistent warning:
C26496 Variable 'Graphic::X' is uninitialized. Always initialize a member variable.
This repeats for X = h, w, x, and y for the lines of code representing the renderTexture function. However, the warning does not show up for the mouseOverRect function that comes prior, both of which use Graphic struct variables in the exact same way.
I have included the relevant parts of my code below. I'm trying to figure out what caused the warning and why it didn't repeat for both functions?
header file
int mouse_x;
int mouse_y;
struct Graphic
{
std::string name;
std::string type;
int x;
int y;
int h;
int w;
};
source file
//Initialization
SDL_Window* window = NULL;
SDL_Renderer* renderer = NULL;
SDL_Rect* clip = NULL;
//Log Error Function
void logSDLError(std::ostream &os, const std::string &msg)
{
os << msg << " error: " << SDL_GetError() << std::endl;
}
//Mouse Over Rectangle Function
bool mouseOverRect(int x, int y, Graphic &graphic)
{
if ((x <= graphic.x + graphic.w) && (x > graphic.x) &&
(y <= graphic.y + graphic.h) && (y > graphic.y))
return true;
else
return false;
//Render Texture at Destination Function
void renderTexture(SDL_Texture* texture, SDL_Renderer* renderer, Graphic &graphic,
SDL_Rect *clip = nullptr)
{
SDL_Rect dest;
dest.x = graphic.x;
dest.y = graphic.y;
dest.h = graphic.h;
dest.w = graphic.w;
SDL_RenderCopy(renderer, texture, clip, &dest);
}
// Main Function
int main(int, char**)
{
//Start up SDL
if (SDL_Init(SDL_INIT_VIDEO) != 0)
{
logSDLError(std::cout, "Cannot initialize SDL video.");
}
//Setup window and renderer
SDL_Window *window = SDL_CreateWindow("Dragon Hunt", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, Screen_Width, Screen_Height, SDL_WINDOW_RESIZABLE);
if (window == nullptr)
{
logSDLError(std::cout, "Cannot create window.");
}
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == nullptr)
{
logSDLError(std::cout, "Cannot create renderer.");
}
struct Graphic createbutton;
createbutton.name = "Create Forest";
createbutton.type = "longbutton";
createbutton.x = 0;
createbutton.y = 1 * (Screen_Width / 5) + 5;
createbutton.h = Screen_Width / 10;
createbutton.w = Screen_Width / 5;
SDL_Event e;
//For tracking if we want to quit
bool quit = false;
while (!quit) {
while (SDL_PollEvent(&e))
{
switch (e.type)
{
case SDL_MOUSEMOTION:
mouse_x = e.motion.x;
mouse_y = e.motion.y;
if (mouseOverRect(mouse_x, mouse_y, createbutton))
useCreate_Clip = CREATE_HOVER;
else
useCreate_Clip = CREATE_DEFAULT;
break;
}
renderTexture(longbutton_image, renderer, createbutton, &create_clips[useCreate_Clip]);
}
None of your structure's members are initialized. They are assigned to after initialization would have been done.
Initialize your structure when you declare it, something like
Graphic createbutton {
"Create Forest",
"longbutton",
0,
1 * (Screen_Width / 5) + 5,
Screen_Width / 10,
Screen_Width / 5
};
Note that you don't need the struct keyword here.

Error to pixel manipulation SDL2 c++

i'm trying to create a manual color key with pixel manipulation in SDL2, but when i execute the program, the color key doesn't work, these pixels become white, but not transparent.
I tried to Lock the surface and set the surface blendmode, but doesn't work too.
Code:
// IO includes
#include <iostream>
// String includes
#include <string>
// SDL includes
#include <SDL.h>
#include <SDL_image.h>
// Screen constants
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
using namespace std;
// Window variables
SDL_Window *window = NULL;
SDL_Surface *windowSurface = NULL;
// Image surfaces
SDL_Surface *background = NULL;
SDL_Surface *image = NULL;
// Functions
bool initializeSDL();
SDL_Surface *loadSurfaceFromFile(string path);
void SetColorKey(SDL_Surface *surface, Uint32 color);
bool LoadFiles();
void FreeMemory();
// SDL_main
int main(int argc, char* argv[]){
// Try to initialize and load files
if(initializeSDL() == false){
FreeMemory();
return -1;
}
if(LoadFiles() == false){
FreeMemory();
return -1;
}
// Blit images
SDL_BlitSurface(background, NULL, windowSurface, NULL);
SDL_BlitSurface(image, NULL, windowSurface, new SDL_Rect(70, 277, image->w, image->h));
// Update screen
SDL_UpdateWindowSurface(window);
// Loop
SDL_Event ev;
while(true){
if(SDL_PollEvent(&ev) && ev.type == SDL_QUIT) break;
}
return 0;
}
bool initializeSDL(){
// Try to initialize the video
if( SDL_Init(SDL_INIT_VIDEO) < 0 ){
// Print error
cout << "Error to initialize the video: " << SDL_GetError() << endl;
return false;
}
// Try to create the window
window = SDL_CreateWindow("Surface", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if(window == NULL){
// Print error
cout << "Error to create the window: " << SDL_GetError() << endl;
return false;
}
// Try to initialize PNG format
int imgFlags = IMG_INIT_PNG;
if(! (IMG_Init(imgFlags) &imgFlags) ) return false;
// Get the window surface
windowSurface = SDL_GetWindowSurface(window);
// If everything is fine, return true
return true;
}
SDL_Surface* loadSurfaceFromFile(string path){
// Create a temporary surface
SDL_Surface *tmpSurface = NULL;
// Create an optimized surface
SDL_Surface *optimizedSurface = NULL;
// Try to load the tmpSurface
tmpSurface = IMG_Load(path.c_str());
if(tmpSurface == NULL){
// Print error
cout << "Error to load the image: " << SDL_GetError() << endl;
return NULL;
}
// Try to optimize the surface
optimizedSurface = SDL_ConvertSurface(tmpSurface, windowSurface->format, NULL);
SDL_FreeSurface(tmpSurface); // Free tmpSurface memory
delete tmpSurface; // Delete the tmpSurface
if(optimizedSurface == NULL){
// Print error
cout << "Error to optimize the image: " << SDL_GetError() << endl;
}
return optimizedSurface;
}
void SetColorKey(SDL_Surface *surface, Uint32 color){
Uint32 *pixels = (Uint32*)surface->pixels;
int pixelCount = (surface->pitch/4) * surface->h;
Uint32 transparent = SDL_MapRGBA(image->format, 255, 255, 255, 0);
for(int i=0;i<pixelCount;i++){
if(pixels[i] == color){
pixels[i] = transparent;
}
}
}
bool LoadFiles(){
// Try to load the background
background = loadSurfaceFromFile("background.bmp");
if(background == NULL) return false;
// Try to load the image
image = loadSurfaceFromFile("image.png");
if(image == NULL) return false;
// Set manual color key to image
SetColorKey(image, SDL_MapRGB(image->format, 0, 255, 255));
return true;
}
void FreeMemory(){
SDL_FreeSurface(background);
SDL_FreeSurface(image);
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();
}

IMG_Load doesn't work

I was watching this series = https://www.youtube.com/watch?v=2NVgHrOFneg
and for some reason for the guy in the video the code works but for me it compiles fine but doesn't load an image. I really don't know what to do.
#include "SDL.h"
#include <iostream>
#include "SDL_image.h"
SDL_Texture *LoadTexture(std::string filePath, SDL_Renderer *renderTarget) //texture optimization function
{
SDL_Texture *texture = nullptr;
SDL_Surface *surface = IMG_Load(filePath.c_str());
if (surface == NULL)
std::cout << "Error 1" << std::endl;
else
{
texture = SDL_CreateTextureFromSurface(renderTarget, surface);
if (texture == NULL)
std::cout << "Error 2" << std::endl;
}
SDL_FreeSurface(surface);
return texture;
}
int main(int, char *argv[])
{
const int FPS = 144;
int frameTime = 0;
SDL_Window *window = nullptr;
SDL_Texture *currentImage= nullptr;
SDL_Renderer *renderTarget = nullptr;
SDL_Rect playerRect;
int frameWidth, frameHeight;
int textureWidth, textureHeight;
SDL_Init(SDL_INIT_VIDEO );
int imgFlags = IMG_INIT_PNG | IMG_INIT_JPG;
if (!(IMG_Init(imgFlags) != imgFlags))
{
std::cout << "Error: " << IMG_GetError() << std::endl;
}
window = SDL_CreateWindow("SDL Pong", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1024, 720, SDL_WINDOW_SHOWN);
renderTarget = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
currentImage = LoadTexture("Untitled.jpg", renderTarget);
SDL_QueryTexture(currentImage, NULL, NULL, &textureWidth, &textureHeight);
SDL_SetRenderDrawColor(renderTarget, 0xFF, 0, 0, 0xFF);
frameWidth = textureWidth / 3;
frameHeight = textureHeight / 4;
playerRect.x = playerRect.y = 0;
playerRect.y = frameWidth;
playerRect.h = frameHeight;
bool isRunning = true; //game loop
SDL_Event ev;
while (isRunning)
{
while (SDL_PollEvent(&ev) != 0)
{
if (ev.type == SDL_QUIT)
isRunning = false;
}
frameTime++;
if (FPS / frameTime == 4)
{
frameTime = 0;
playerRect.x += frameWidth;
if (playerRect.x >= textureWidth)
playerRect.x =0;
}
SDL_RenderClear(renderTarget);
SDL_RenderCopy(renderTarget, currentImage, &playerRect, NULL);
SDL_RenderPresent(renderTarget);
}
SDL_DestroyWindow(window);
SDL_DestroyTexture(currentImage);
SDL_DestroyRenderer(renderTarget);
window = nullptr;
renderTarget = nullptr;
currentImage = nullptr;
SDL_Quit();
return 0;
}
This is the error message: http://imgur.com/LHMdt5F
IMG_Init returns bitfield of formats that was initialised. If resulting bitfield doesn't contain every format that was requested in flags, something gone wrong.
if (!(IMG_Init(imgFlags) != imgFlags)) checks if there is no error. Then you're trying to get error message, but there were no errors. Remove negation operator.
When you create the .exe and run it from an IDE it often stores the executable in a ../bin/.. directory. If Untitled.jpg is in the same directory as your source files, it will not find it.
SDL_GetBasePath(); will return the base path to your files. Check it out docs for it.
The string from SDL_GetBasePath() + "Untitled.jpg" will find and open the file.

Linking SDL_image in make file

My Makefile -
all:
g++ main.cpp -I/usr/local/include -L/usr/local/lib -lSDL2 -lSDL_image
My Code I am using as taken from a tutorial -
/*This source code copyrighted by Lazy Foo' Productions (2004-2013) */
//Using SDL, SDL_image, standard IO, and strings
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <stdio.h>
#include <string>
//Screen dimension constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
//Texture wrapper class
class LTexture
{
public:
//Initializes variables
LTexture();
//Deallocates memory
~LTexture();
//Loads image at specified path
bool loadFromFile( std::string path );
#ifdef _SDL_TTF_H
//Creates image from font string
bool loadFromRenderedText( std::string textureText, SDL_Color textColor );
#endif
//Deallocates texture
void free();
//Set color modulation
void setColor( Uint8 red, Uint8 green, Uint8 blue );
//Set blending
void setBlendMode( SDL_BlendMode blending );
//Set alpha modulation
void setAlpha( Uint8 alpha );
//Renders texture at given point
void render( int x, int y, SDL_Rect* clip = NULL, double angle = 0.0, SDL_Point* center = NULL, SDL_RendererFlip flip = SDL_FLIP_NONE );
//Gets image dimensions
int getWidth();
int getHeight();
private:
//The actual hardware texture
SDL_Texture* mTexture;
//Image dimensions
int mWidth;
int mHeight;
};
//The application time based timer
class LTimer
{
public:
//Initializes variables
LTimer();
//The various clock actions
void start();
void stop();
void pause();
void unpause();
//Gets the timer's time
Uint32 getTicks();
//Checks the status of the timer
bool isStarted();
bool isPaused();
private:
//The clock time when the timer started
Uint32 mStartTicks;
//The ticks stored when the timer was paused
Uint32 mPausedTicks;
//The timer status
bool mPaused;
bool mStarted;
};
//The dot that will move around on the screen
class Dot
{
public:
//The dimensions of the dot
static const int DOT_WIDTH = 20;
static const int DOT_HEIGHT = 20;
//Maximum axis velocity of the dot
static const int DOT_VEL = 10;
//Initializes the variables
Dot();
//Takes key presses and adjusts the dot's velocity
void handleEvent( SDL_Event& e );
//Moves the dot
void move();
//Shows the dot on the screen
void render();
private:
//The X and Y offsets of the dot
int mPosX, mPosY;
//The velocity of the dot
int mVelX, mVelY;
};
//Starts up SDL and creates window
bool init();
//Loads media
bool loadMedia();
//Frees media and shuts down SDL
void close();
//The window we'll be rendering to
SDL_Window* gWindow = NULL;
//The window renderer
SDL_Renderer* gRenderer = NULL;
//Scene textures
LTexture gDotTexture;
LTexture::LTexture()
{
//Initialize
mTexture = NULL;
mWidth = 0;
mHeight = 0;
}
LTexture::~LTexture()
{
//Deallocate
free();
}
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
{
//Color key image
SDL_SetColorKey( loadedSurface, SDL_TRUE, SDL_MapRGB( loadedSurface->format, 0, 0xFF, 0xFF ) );
//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;
}
#ifdef _SDL_TTF_H
bool LTexture::loadFromRenderedText( std::string textureText, SDL_Color textColor )
{
//Get rid of preexisting texture
free();
//Render text surface
SDL_Surface* textSurface = TTF_RenderText_Solid( gFont, textureText.c_str(), textColor );
if( textSurface != NULL )
{
//Create texture from surface pixels
mTexture = SDL_CreateTextureFromSurface( gRenderer, 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 );
}
else
{
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
}
//Return success
return mTexture != NULL;
}
#endif
void LTexture::free()
{
//Free texture if it exists
if( mTexture != NULL )
{
SDL_DestroyTexture( mTexture );
mTexture = NULL;
mWidth = 0;
mHeight = 0;
}
}
void LTexture::setColor( Uint8 red, Uint8 green, Uint8 blue )
{
//Modulate texture rgb
SDL_SetTextureColorMod( mTexture, red, green, blue );
}
void LTexture::setBlendMode( SDL_BlendMode blending )
{
//Set blending function
SDL_SetTextureBlendMode( mTexture, blending );
}
void LTexture::setAlpha( Uint8 alpha )
{
//Modulate texture alpha
SDL_SetTextureAlphaMod( mTexture, alpha );
}
void LTexture::render( int x, int y, SDL_Rect* clip, double angle, SDL_Point* center, SDL_RendererFlip flip )
{
//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;
}
//Render to screen
SDL_RenderCopyEx( gRenderer, mTexture, clip, &renderQuad, angle, center, flip );
}
int LTexture::getWidth()
{
return mWidth;
}
int LTexture::getHeight()
{
return mHeight;
}
Dot::Dot()
{
//Initialize the offsets
mPosX = 0;
mPosY = 0;
//Initialize the velocity
mVelX = 0;
mVelY = 0;
}
void Dot::handleEvent( SDL_Event& e )
{
//If a key was pressed
if( e.type == SDL_KEYDOWN && e.key.repeat == 0 )
{
//Adjust the velocity
switch( e.key.keysym.sym )
{
case SDLK_UP: mVelY -= DOT_VEL; break;
case SDLK_DOWN: mVelY += DOT_VEL; break;
case SDLK_LEFT: mVelX -= DOT_VEL; break;
case SDLK_RIGHT: mVelX += DOT_VEL; break;
}
}
//If a key was released
else if( e.type == SDL_KEYUP && e.key.repeat == 0 )
{
//Adjust the velocity
switch( e.key.keysym.sym )
{
case SDLK_UP: mVelY += DOT_VEL; break;
case SDLK_DOWN: mVelY -= DOT_VEL; break;
case SDLK_LEFT: mVelX += DOT_VEL; break;
case SDLK_RIGHT: mVelX -= DOT_VEL; break;
}
}
}
void Dot::move()
{
//Move the dot left or right
mPosX += mVelX;
//If the dot went too far to the left or right
if( ( mPosX < 0 ) || ( mPosX + DOT_WIDTH > SCREEN_WIDTH ) )
{
//Move back
mPosX -= mVelX;
}
//Move the dot up or down
mPosY += mVelY;
//If the dot went too far up or down
if( ( mPosY < 0 ) || ( mPosY + DOT_HEIGHT > SCREEN_HEIGHT ) )
{
//Move back
mPosY -= mVelY;
}
}
void Dot::render()
{
//Show the dot
gDotTexture.render( mPosX, mPosY );
}
bool init()
{
//Initialization flag
bool success = true;
//Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Enable VSync
if( !SDL_SetHint( SDL_HINT_RENDER_VSYNC, "1" ) )
{
printf( "Warning: VSync not enabled!" );
}
//Set texture filtering to linear
if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
{
printf( "Warning: Linear texture filtering not enabled!" );
}
//Create window
gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
if( gWindow == NULL )
{
printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Create renderer for window
gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED );
if( gRenderer == NULL )
{
printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Initialize renderer color
SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
//Initialize PNG loading
int imgFlags = IMG_INIT_PNG;
if( !( IMG_Init( imgFlags ) & imgFlags ) )
{
printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
success = false;
}
}
}
}
return success;
}
bool loadMedia()
{
//Loading success flag
bool success = true;
//Load dot texture
if( !gDotTexture.loadFromFile( "26_motion/dot.bmp" ) )
{
printf( "Failed to load dot texture!\n" );
success = false;
}
return success;
}
void close()
{
//Free loaded images
gDotTexture.free();
//Destroy window
SDL_DestroyRenderer( gRenderer );
SDL_DestroyWindow( gWindow );
gWindow = NULL;
gRenderer = NULL;
//Quit SDL subsystems
IMG_Quit();
SDL_Quit();
}
int main( int argc, char* args[] )
{
//Start up SDL and create window
if( !init() )
{
printf( "Failed to initialize!\n" );
}
else
{
//Load media
if( !loadMedia() )
{
printf( "Failed to load media!\n" );
}
else
{
//Main loop flag
bool quit = false;
//Event handler
SDL_Event e;
//The dot that will be moving around on the screen
Dot dot;
//While application is running
while( !quit )
{
//Handle events on queue
while( SDL_PollEvent( &e ) != 0 )
{
//User requests quit
if( e.type == SDL_QUIT )
{
quit = true;
}
//Handle input for the dot
dot.handleEvent( e );
}
//Move the dot
dot.move();
//Clear screen
SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
SDL_RenderClear( gRenderer );
//Render objects
dot.render();
//Update screen
SDL_RenderPresent( gRenderer );
}
}
}
//Free resources and close SDL
close();
return 0;
}
My Error -
g++ main.cpp -I/usr/local/include -L/usr/local/lib -lSDL2 -lSDL_image.lib
ld: library not found for -lSDL_image.lib
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [all] Error 1
I am unable to get this to load. I used brew to install SDL2_image and it appears to exist in usr/local/lib and such. I see libSDL_image.a and other assorted items.
Can someone please tell me how to edit my makefile for mac so that I can compile the code I am attempting to use. I am not sure why -lSDL_image would not work as it should do so.
To load SDL_image it should be
-lSDL_image
but your not using SDL 1.X your are using SDL 2 so it should be
-lSDL2_image
If it still says that it can't find it then you need to make sure it is in a path that ld searches in.
-L/Path/To/SDL_image
If that still doesn't work make sure that you have the development library and not just the runtime binaries
You can grab the development libraries for SDL_image here : http://www.libsdl.org/projects/SDL_image/