I'm following this tutorial that teaches how to use SDL2 with the final goal of learning C++ in a more fun and interactive way.
For this, I only need to be able to draw lines, polygons and circles.
So, after reading part 1 that explains how to create a window on the screen and part 3 that introduces event handling, I headed torward part 7 and 8 that explain, respectively, how to create a renderer and how to draw a rectangle on the screen. This is the code I've got so far (it isn't exactly the same as the code on the tutorial: I've introduced a struct to pass SDL objects around and removed all the error handling which was confusing):
#include <SDL2/SDL.h>
//screen dimensions costants
#define SCREEN_WIDTH 540
#define SCREEN_HEIGHT 960
//data structure holding the objects needed to create a window and draw on it
struct interface {
SDL_Window * window = NULL;
SDL_Surface * surface = NULL;
SDL_Renderer * renderer = NULL;
};
//function which inits the sdl and creates an interface object
interface init() {
interface screen;
SDL_Init(SDL_INIT_VIDEO);
screen.window = SDL_CreateWindow("", 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
screen.surface = SDL_GetWindowSurface(screen.window);
screen.renderer = SDL_CreateRenderer(screen.window, -1, SDL_RENDERER_ACCELERATED);
return screen;
}
//function to free the memory and close the sdl application
void close(interface screen) {
SDL_DestroyRenderer(screen.renderer);
SDL_DestroyWindow(screen.window);
screen.renderer = NULL;
screen.window = NULL;
SDL_Quit();
}
int main(int argc, char* args[]) {
//start the application
interface screen = init();
//setup for event handling
bool quit = false;
SDL_Event event;
//the shape to render
SDL_Rect fillRect = { SCREEN_WIDTH / 4, SCREEN_HEIGHT / 4, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 };
//main loop which first handles events
while (!quit) {
while (SDL_PollEvent(&event) != 0) {
if (event.type == SDL_QUIT)
quit = true;
}
//should draw a red rectangle on the screen
SDL_SetRenderDrawColor(screen.renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(screen.renderer);
SDL_SetRenderDrawColor(screen.renderer, 0xFF, 0x00, 0x00, 0xFF);
SDL_RenderFillRect(screen.renderer, &fillRect);
}
//End the application
close(screen);
return 0;
}
The problem is that, as it is, the program draws nothing to the screen (which remains black), and if I remove the line screen.surface = SDL_GetWindowSurface(screen.window); it also begins lagging a lot in a manner I even find difficult to exit the application.
Note that I'm programming on Android using C4droid and the SDL Plugin for C4droid.
Why is that happening? What am I doing wrong?
EDIT Problem solved by renaming close to end and by including a call to SDL_RenderPresent(screen.renderer); at the end of the main loop. With this setup the screen surface has to be deleted or the program won't draw anything.
Thanks to #keltar and #Wutipong Wongsakuldej for answering the question in the comments
First of all I tested the code in Windows (MSYS2) rather than on Android as I don't have AIDE installed at the moment.
Basically I added 2 lines of code into the main loop :
//main loop which first handles events
while (!quit) {
while (SDL_PollEvent(&event) != 0) {
if (event.type == SDL_QUIT)
quit = true;
}
//should draw a red rectangle on the screen
SDL_SetRenderDrawColor(screen.renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(screen.renderer);
SDL_SetRenderDrawColor(screen.renderer, 0xFF, 0x00, 0x00, 0xFF);
SDL_RenderFillRect(screen.renderer, &fillRect);
/** below lines are added **/
SDL_RenderPresent(screen.renderer);
SDL_Delay(0);
}
SDL_RenderPresent draw whatever you've renderred so far to the screen. This make the output shows up.
SDL_Delay() this is added to give the cpu time back to the os. Without this your app might become unresponsive and the cpu utilization will be 100% (at one core) in some operating system (especially the very old one). I don't know if this is needed in Android or not anyway. Give it a try.
Related
Every time I attempt to run my application it creates a window perfectly fine but when moving the mouse about it becomes obvious that it freezes briefly for a few seconds. I also had this issue in a previous SDL project but didn't fix it as it wasn't very vital but I could never find a solution for it.
I tried looking up my issue but couldn't find anything that matches the issue I'm facing, despite this I attempted a few things that I felt could work like slightly different implementations of an event loop.
I'm not 100% sure on what EVERY line of SDL related code does but I took it from a previous project so I knew what it did at one point but it's not too hard to work out.
int width = 160;
int height = 144;
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window = SDL_CreateWindow("Window Title", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width * 4, height * 4, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_Texture* texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, width, height);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
bool quit = false;
while (!quit)
{
SDL_Event E;
while (SDL_PollEvent(&E))
{
if (E.type == SDL_QUIT)
quit = true;
}
}
I expect the window to display smoothly and not have this freezing occur every few seconds. I'm not sure if it only occurs when the mouse is moving or if it happens to freeze every few seconds despite this as the cursor is the only way I have to test it. I saw one post that talked about flooding the event queue but that solution didn't seem to work for me.
Any help is appreciated.
so I got the following code(piece):
_Bool create_new_window(rectanglestruct *rectangle, colorstruct *colorfill, char *winname)
{
....
log_printf("creating main renderer for window ( window : %s )\n", ptr->winname);
// Setup renderer
SDL_Renderer *renderer = SDL_CreateRenderer( ptr->window, -1, SDL_RENDERER_ACCELERATED);
ptr->renderer = renderer;
if (colorfill != NULL)
{
log_printf("\n - background color set r=%d g=%d b=%d with opacity of %d\n", colorfill->r,colorfill->g,colorfill->b, colorfill->opacity);
// Set render color to red ( background will be rendered in this color )
SDL_SetRenderDrawColor( ptr->renderer, colorfill->r,colorfill->g,colorfill->b, colorfill->opacity );
log_printf("background rendered\n");
}
// Clear window
SDL_RenderClear( ptr->renderer );
SDL_ShowWindow(ptr->window);
SDL_RenderPresent( ptr->renderer );
getchar();
with
typedef struct SDL_Window SDL_Window;
typedef struct windowstruct {
char *winname;
SDL_Window *window;
SDL_Renderer *renderer;
struct windowstruct *next;
struct windowstruct *previous;
} windowstruct;
static windowstruct *root = NULL;
and
typedef struct colorstruct {
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t opacity;
} colorstruct;
With in main:
_Bool start_SDL(void)
// scope this
{
//draw background
colorstruct *colorfill = malloc(sizeof(rectanglestruct));
colorfill->r = 0xFF;
colorfill->g = 0xFF;
colorfill->b = 0xFF;
colorfill->opacity = 0xFF;
rectanglestruct *winplace = malloc(sizeof(rectanglestruct));
winplace->x = 0;
winplace->y = 0;
winplace->w = 300;
winplace->h = 300;
create_new_window(winplace, colorfill, "appscreen");
free(colorfill);
free(winplace);
}
and
_Bool start_SDL(void)
{
//Initialization flag
_Bool success = true;
//Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
log_printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
success = false;
}
}
and I got the following output (after a couple of times):
The point is I thought that the renderer was just a copy of the screen like a buffer in which you can write and refresh on the screen. But I gues not?
No, SDL_Renderer implements SDL2 drawing, usually with hardware-accelerated backend. Your image is corrupt because you didn't issue redraw at appropriate time. If your window needs redraw (resized, overshadowed by other window or sceen borders) - you have to draw again and present result (this is in fact the same for every windowing library; even in GUI toolkits like Qt or GTK if your callback didn't return quickly, you can experience the same corruption). You can render to texture and then display it again if your image remains unchanged and calculations are heavy.
To do what you've said would require accumulating all data sent to renderer (may be high memory usage) and either calling update on regular intervals or on events, or taking away main loop from calling side (like most GUI toolkits do), which is against SDL design. Also, since SDL's main target are video games, scenes there are rarely static.
Before SDL2 there was no renderer and SDL only provided display surface to which you draw, but it is quite the same basic concept, it wouldn't update all by itself.
It doesn't mean it cannot be done with SDL, however - it gives you much more control. If you want to redraw only when it is really required - watch for SDL_WindowEvent.
I'm trying to display a texture onto the screen but all I'm getting is a black window.
No SDL Errors are being reported. There's a good chance that I'm missing something stupid, but I can't see it. Hopefully another set of eyes will help. Feel free to ask for more code/info.
main.cpp
SDL_Window * window;
SDL_Renderer * renderer;
SDL_Texture * grass;
SDL_Rect g_dst;
SDL_Event event;
Game app;
SDL_Init(SDL_INIT_EVERYTHING);
window = SDL_CreateWindow("tmp", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
g_dst.x = g_dst.y = 0;
g_dst.w = 640;
g_dst.h = 480;
grass = IMG_LoadTexture(renderer, "grass.bmp");
while (app.isRunning()) {
app.pollEvents(&event);
app.render_init();
app.render(grass, NULL, &g_dst);
app.render_end();
}
//SDL_Quit() is handled by the Game class' destructor
Game.cpp
//Only functions used for rendering are shown
void render_init(Uint8 red=0, Uint8 green=0, Uint8 blue=0, Uint8 alpha=255)
{
SDL_SetRenderDrawColor(renderer, red, green, blue, alpha);
SDL_RenderClear(renderer);
}
void render(SDL_Texture * texture, SDL_Rect * src, SDL_Rect * dest) {
SDL_RenderCopy(renderer, texture, src, dest);
}
void render_end() { SDL_RenderPresent(renderer); }
First of all, you're initializing everything? please don't do that frequently, mind you that you're also initializing MANY unnecessary stuffs like for game controllers, etc. if the app gets bigger then the efficiency and the possibility of this app running at a smoot speed is at stake.
I also noticed that you are declaring variables in the .cpp file, do that in the header file and just recall the header to the cpp file that will be using it.
You want to render the grass right? and render it as much as the screens size.
(I'll just assume that you used this in the game.cpp part, which is the very first file, thus, not regarding any classes made)
int winWidth = 680; //The reason for this is just in case you make the window resizable
int winHeight = 480; //then the texture would also resize along with the window
SDL_Window *window = window = SDL_CreateWindow("The Space Project", 100, 100, winWidth, winHeight, SDL_WINDOW_SHOWN);
SDL_Renderer *renderer = NULL; //I've set this to NULL so that we can know if
the reason as to why your image is not rendering is because the renderer is not properly working.
renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED);
if(renderer == NULL)
{
cout >> "Renderer is not working" >> endl;
//This shows a line at the command prompt that your renderer doesn't have any output, thus, only having a NULL as an equivalent
}
SDL_Texture* grass= NULL;
grass= IMG_LoadTexture(renderer, "grass.bmp"); //As you can see, I've set the grass to Null again
if(grass == NULL)
{
cout >> "Grass have failed to initialize" >> endl;
/*I don't normally do this but it's very important if you really need trouble shooting guides
but this time, were here to check IF the grass.bmp entered the SDL_Texture grass, so if the system can't find the .bmp file then it would show this error
since the grass (SDL_Texture) still doesn't have anything inside it (NULL)*/
}
SDL_Rect grass_rect;
grass_rect.x = 0;
grass_rect.y = 0;
grass_rect.w = winWidth;
grass_rect.h = winHeight;
//Loop part, I'll skip some of it
while (!quit && mainEvent->type != SDL_QUIT) //!quit is just an imaginary Boolean I've typed)
{
SDL_PollEvent(mainEvent); //Let's say you created the event already
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, grass, NULL, &grass_rect);
//The NULL part is also similar to a rect but it's a limiting type, we didn't assign anything to it
since I assumed that you wanted the whole image to be rendered
SDL_RenderPresent(renderer);
}
I revised the code and made it more efficient since your code called for useless extras which might result in lower performance.
I also notice that you tried calling for color changes?
use this
SDL_SetTextureColorMod(texture, red-value, green-value, blue-value);
and put it in the loops part under the render present of the same texture.
SDL_SetTextureColorMod(grass, 250, 250, 250);
Doing this would set all color values to 250, thus, having a white color, this change your texture color to white.
You're also wasting space on making the app.is running(), you could easily replace it with a boolean, which consumes much less space or you could omit it if you don't have an exit button inside the application and just make your loop read the SDL_QUIT, this saves space for the file, mind the efficiency.
If this still doesn't work then try replacing the image your using, make a simple one on paint name it something like "grass.png" or anything then try it again.
Don't forget to put the file in the proper folder, in the DEBUG folder if you haven't specified a folder, and also put it in the app folder so it would also read it when it executes as an .exe file and not as part of the debug command.
I'm attemting to load an image that I exported from flash CS3 it's a very cute face but it loads very weird it loads on a blueish way this is the code for the two files:
//main.cpp
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include "test.hpp"
int main(int argc, char *argv[])
{
SDL_Init(SDL_INIT_VIDEO);
// Activamos modo de video
screen = SDL_SetVideoMode(640,480,32,SDL_SWSURFACE | SDL_DOUBLEBUF);
image = IMG_Load("face.bmp");
dest.x = 200;
dest.y = 200;
//Main Loop
while(Abierto)
{
//We Draw
Draw();
//Events
while( SDL_PollEvent(&event))
{
if(event.type == SDL_QUIT)
Abierto = false;
}
}
// We free the image
SDL_FreeSurface(image);
SDL_Quit();
return 0;
}
Now the other one the;
//test.hpp
DL_Surface *image = NULL, *screen = NULL;
SDL_Rect dest;
SDL_Event event;
bool Abierto = true;
float PlaneX = 300, PlaneY = 200;
float velX = 0.1, velY = 0.1;
void Draw()
{
Uint32 color;
// Black Background is created
color = SDL_MapRGB (screen -> format, 0, 0, 0);
SDL_FillRect (screen, NULL, color);
SDL_DisplayFormatAlpha(image);
SDL_BlitSurface(image, NULL, screen, &dest);
// Flip the working image buffer with the screen buffer
SDL_Flip (screen);
}
I need help with this please Im not that experienced on SDL stuff oh and if you want to take a closer look I uplaoded the project here.
Oh my bad I must add the image is 32 pixels with alpha according to flash exporting options
According to docs, SDL_DisplayFormatAlpha returns a new image and keeps the original intact.
So, try in the first part, when you load the image:
SDL_Surface *origImage = IMG_Load("face.bmp");
image = SDL_DisplayFormatAlpha(origImage);
SDL_FreeSurface(origImage)
As there is no need to call SDL_DisplayFormatAlpha each frame.
Then in the second part, just blit image, without calling SDL_DisplayFormatAlpha.
UPDATE
I've just checked your picture, and it looks like it is a weird bmp. I've seen that before: BMP format is such a mess that if you don't keep to the basics chances are that different programs will interpret the data differently.
In your case:
display face.bmp shows correctly.
gthumb face.bmp shows nothing.
eog face.bmp says "bogus header data".
I strongly recommend using PNG files for all your game cartoon-like pictures and JPG for all the photo-like ones.
So run
$ convert face.bmp face.png
And use the PNG file. I'll will work better and you will have a file 20% the size of the original.
I wish to have a semi-transparent SDL background (nothing to do with sub-surfaces or images), such that instead of having a black background it is actually transparent, but the other things I draw are not. My current code is a slightly modified copy of Code::Blocks' SDL project, similar to how various applications have rounded borders or odd shapes besides rectangles.
#ifdef __cplusplus
#include <cstdlib>
#else
#include <stdlib.h>
#endif
#ifdef __APPLE__
#include <SDL/SDL.h>
#else
#include <SDL.h>
#endif
int main ( int argc, char** argv )
{
putenv("SDL_VIDEO_WINDOW_POS");
putenv("SDL_VIDEO_CENTERED=1");
// initialize SDL video
if ( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
printf( "Unable to init SDL: %s\n", SDL_GetError() );
return 1;
}
// make sure SDL cleans up before exit
atexit(SDL_Quit);
// create a new window
SDL_Surface* screen = SDL_SetVideoMode(640, 480, 16,
SDL_HWSURFACE|SDL_DOUBLEBUF|SDL_NOFRAME);
if ( !screen )
{
printf("Unable to set 640x480 video: %s\n", SDL_GetError());
return 1;
}
// load an image
SDL_Surface* bmp = SDL_LoadBMP("cb.bmp");
if (!bmp)
{
printf("Unable to load bitmap: %s\n", SDL_GetError());
return 1;
}
// centre the bitmap on screen
SDL_Rect dstrect;
dstrect.x = (screen->w - bmp->w) / 2;
dstrect.y = (screen->h - bmp->h) / 2;
// program main loop
bool done = false;
while (!done)
{
// message processing loop
SDL_Event event;
while (SDL_PollEvent(&event))
{
// check for messages
switch (event.type)
{
// exit if the window is closed
case SDL_QUIT:
done = true;
break;
// check for keypresses
case SDL_KEYDOWN:
{
// exit if ESCAPE is pressed
if (event.key.keysym.sym == SDLK_ESCAPE)
done = true;
break;
}
} // end switch
} // end of message processing
// DRAWING STARTS HERE
// clear screen
SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 0, 0));
// draw bitmap
SDL_BlitSurface(bmp, 0, screen, &dstrect);
// DRAWING ENDS HERE
// finally, update the screen :)
SDL_Flip(screen);
} // end main loop
// free loaded bitmap
SDL_FreeSurface(bmp);
// all is well ;)
printf("Exited cleanly\n");
return 0;
}
I think what you're trying to do is in fact a shaped window (parts of the window are transparent depending on a mask that you provide). It seems there's no way to do that with SDL 1.2, however there is a SDL_SetWindowShape function just for this in SDL 1.3 for which you can find a pre-release snapshot here but it's not even in beta yet so I suggest waiting until it's officialy released :)
this is a link to a pretty neat article about development of an older application for Mac OS 9, which did not have support for shaped windows, either.
It's actually a neat article in general about software development.
But the idea seems pretty smart, and I wonder if you might be able to get it working here, too. Instead of trying to make a transparent background, they actually take a screen-shot of the computer right where their window is going to go, and then use that screen shot for their background. When the user drags the window around on the screen, they continue to update the background with new screen-shots. I think this might be more complicated than you were hoping for, but it's certainly an interesting idea.