Saturday, 23 November 2013

SDL/SDL2 Fundamentals C++

Unfortunately, even on the official wiki is almost impossible to find any examples of SDL2.

Trying to understand, I found only a couple of items which are not covered and the third of my questions. 
SDL 2.x differs significantly from 1.x and even if in the past you had to work with it - now you do not understand the risk. Today we will write a simple program to output a screen background and a zoom sprite character moves using WASD and arrow keys. + Understand how to work with SDL mouse.



For work, we need :
  • SDL2.h
  • SDL2_image.h
  • SDL2_mixer.h

All this can be easily found on the Internet. To begin at the beginning:



Initialize SDL


Let's start by creating a class object SDL_DisplayMode . 
It is very useful for us if we want to have an application on the screen. 
This object should be to create the initialization of the SDL.

SDL_DisplayMode displayMode;


Then you need to initialize itself SDL:
if (SDL_Init (SDL_INIT_EVERYTHING)! = 0 ) {
     STD :: cout << "Error SDL_Init:" << SDL_GetError () << STD :: endl;
     return  1 ;
}


Flag SDL_INIT_EVERYTHING subsystem initializes all SDL. If you only need something specific, it can be found on the wiki full listing.Now we need to get the monitor settings with which we work. To do this we create Screwed variable in which to return 0 if all went well, and equate its functions SDL_GetDesktopDisplayMode (int * displayIndex, SDL_DisplayMode * mode) . If the first argument is written 0, then turn to the main monitor. All the parameters we can assume from the object displayMode .




    int Request SDL_GetDesktopDisplayMode = ( 0 , & displayMode);


It's time to do our window ! 
Everything is very simple, create a pointer to the class object SDL_Window and call the function
SDL_Window SDL_CreateWindow * ( const  char * title, int x, int y, int w, int H, Uint32 Flags)


It's all so clear, and of course, but just in case, explain what's what.
  • title - the name of the window.
  • x, y - coordinates of the window. If you want to open up the whole screen, then you need to put 0.0
  • w, h - window size. To open to the message screen to access the object displayMode .
  • flags - flags here exhibited in the window initialization. You can say that I'm stupid and wrong exists flagSDL_WINDOW_FULLSCREEN , and I'm here to reinvent the wheel its DisplayMode , but no!
    By scientific spear productive experiments, I noticed that this method is much faster and it does not react antivirusniki. At the same SDL_WINDOW_FULLSCREEN avast shouted that I was trying to crack.

SDL_WINDOW_SHOWN - makes the window visible. As a result, the output we get the following code:


SDL_Window * Win = SDL_CreateWindow ( "Hello World!" , 0 , 0 , displayMode . w , displayMode . H , SDL_WINDOW_SHOWN) ;
if (win == nullptr) {
    STD :: cout << "Error SDL_CreateWindow:" << SDL_GetError () << STD :: endl ; 
    return 1 ; 
}


Now we need to create a renderer :
* SDL_Renderer SDL_CreateRenderer (SDL_Window * window,
                                  int          Index ,
                                 Uint32 flags)

  • window - a window in which we work.
  • index - the index of the driver that will be used to render. If you put -1 , the renderer will use the first suitable driver.
  • flags - flags render. Full list on the wiki as always.
    I will use SDL_RENDERER_ACCELERATED responsible for hardware acceleration and SDL_RENDERER_PRESENTVSYNC responsible for vertical sync.

Putting it all together and get:
SDL_Renderer * ren = SDL_CreateRenderer (win, - 1 , SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
 if (ren == nullptr ) {
     STD :: cout << "Error SDL_CreateRenderer:" << SDL_GetError () << STD :: endl;
     return  1 ;
}

SDL is now ready to cooperate with us!

Display


It's time to take pictures. 
First we need to create an object of class 2 SDL_Rect . 
This object will contain the physical parameters of our textures, such as width, height and position of the window.
SDL_Rect player_RECT ; 
        player_RECT . x = 0 / / Offset blades for X 
        player_RECT . y = 0 / / Offset blades for Y 
        player_RECT . w = 333 / / widths 
        player_RECT . H = 227 / / height blade

SDL_Rect background_RECT ; 
        background_RECT . x = 0 ; 
        background_RECT . y = 0 ; 
        background_RECT . w = displayMode . w ; 
        background_RECT . H = displayMode . H ;

And a few lines later that we were able to zumirovat our character:
const  int player_WIGHT = 333 ;    / / Width iskhodngo image 
const  int player_HEIGH = 227 ;    / / Height of the original image 
Double TESTtexture_SCALE = 1.0 ; / / Mnozhetel for zooming


And so we got to load the textures. 
2 ways I will show: But first, a brief digression! think those who have worked with SDL1.x explanations do not need, but I still tell of how arranged SDL, suddenly (well, you never know) here who is not familiar with it. in SDL has 4 main classes / structures involved in displaying the image on the screen: SDL_Texture , SDL_Surface , SDL_Rect , SDL_Render . About the last two we have talked, let's briefly discuss the remaining.






  • SDL_Surface - working with SDL_mixer.h about it you can forget. But silly with something to work without having the slightest idea of how it works.
    Details
  • SDL_Texture - creating an object structure SDL_Surface , we should turn it into a texture that would render her unable to do.

After that, the object is sent to the renderer:
SDL_RenderCopy (SDL_Renderer * Renderer, SDL_Texture * texture ,   const SDL_Rect srcrect *,   const * SDL_Rect dstrect)
SDL_RenderPresent (SDL_Renderer * renderer)


Well, the theory sorted out, it's time to practice! Option number one: This method is tied to the libraries SDL_mixer.h andSDL_Image.h , so do not orite at me surprised when you pour down the error connecting only SDL2. His feature is it transmits a bike without an alpha channel.





* = Player SDL_Texture IMG_LoadTexture (ren, ".. \ \ res \ \ player.png ");

Now we have the texture of the character is ready to show on the screen. But before that, we still have to create a background.Option number two: we will create a background using pure SDL. Just because we can!



Code mulberries!
SDL_Surface * BMP_background SDL_LoadBMP = ( ".. \ \ res \ \ Background.bmp" );
 if (BMP_background == nullptr ) {
     STD :: cout << "Error SDL_LoadBMP:" << SDL_GetError () << STD :: endl ;
     return  1 ;
}

SDL_Texture * background = SDL_CreateTextureFromSurface (ren, BMP_background);
SDL_FreeSurface (BMP_background); / / Cleansing memory surface 
if (Player == nullptr ) {
     STD :: cout << "Error SDL_CreateTextureFromSurface:" << SDL_GetError () << STD :: endl;
     return  1 ;
}

Working with pure SDL must never forget to do error checking! And finally, hooray, it's time to bring it to the screen!


SDL_RenderClear (ren); / / Clean render 
SDL_RenderCopy (ren, background, NULL , & background_RECT); / / Copy to render background 
SDL_RenderCopy (ren, Player, NULL , & player_RECT); / / Copy to render character 
SDL_RenderPresent (ren); / / Let's go!


Developments


I think it is not necessary to explain that of 2 pictures games will not work. 
Time to add some dynamics to our miracle! To start you need to create a couple of infinite loops that run as long as there is no way out and events:


SDL_Event Event ;
 bool Quit = false ;
 while (! Quit)
     while (SDL_PollEvent (& Event ))
    {
        SDL_PumpEvents (); / / event handler. 
    }


It's time to go directly to the events. 
In SDL there are 2 ways to read events from the controllers:
  • The first way we realize working with a mouse.
    But first, add a couple of lines before the cycles:
    SDL_Texture ARRAY_textures * [ 2 ] = {background, Player} ;
    SDL_Rect ARRAY_rect * [ 2 ] = {& background_RECT, player_RECT &} ;
    int ARRAY_texturesState [ 2 ] = { 1 , 1 } ;

    This is useful for us to be able to display or not to display a particular texture.
    Now insert this code in the inner loop.
    The code does not cake, it's true here!

    I think it is self-explanatory, if you read carefully and do more programming 21 days , but still I will specify thatevent.button.button waiting SDLya special flag, which you can easily find on the wiki, event.type waiting flag event type full list of which is still there! We can already close window click on the top left corner of the screen! And even more, we can remove and return the character whenever you want just by clicking on it! Yeah, I feel like the feeling of power begins engulfing us, but not the time to stop, there is still a keyboard!
  • The second method is
    to start before the cycle we need to create one constant:
    const * Uint8 KeyboardState SDL_GetKeyboardState = ( NULL );

    It is needed that would track the state of the buttons. More is our primary function, you need to add lots and lots of code that will make our program more structured. (I see someone has already started to write about the need to use classes and libraries, but I want to remind you that tutorial and it will not be good if people get confused collecting code, so we will write everything as simple. My apologies to those whose feelings I hurt!)




    Lots and lots of code
    void move_UP (SDL_Renderer * render, SDL_Texture * texture , SDL_Rect & destRect, int Offset = 5 )
    {
        destrect.y - = offset;
        SDL_RenderClear (render);
        SDL_RenderCopy (render, texture , NULL, & destRect);
    }
    void move_DOWN (SDL_Renderer * render, SDL_Texture * texture , SDL_Rect & destRect, int Offset = 5 )
    {
        destrect.y + = offset;
        SDL_RenderClear (render);
        SDL_RenderCopy (render, texture , NULL, & destRect);
    }
    void move_LEFT (SDL_Renderer * render, SDL_Texture * texture , SDL_Rect & destRect, int Offset = 5 )
    {
        destrect.x - = offset;
        SDL_RenderClear (render);
        SDL_RenderCopy (render, texture , NULL, & destRect);
    }
    void move_RIGHT (SDL_Renderer * render, SDL_Texture * texture , SDL_Rect & destRect, int Offset = 5 )
    {
        destrect.x + = offset;
        SDL_RenderClear (render);
        SDL_RenderCopy (render, texture , NULL, & destRect);
    }
    
    void render_UPDATE (SDL_Renderer * render, SDL_Texture * texture [], SDL_Rect destRect * [], int states [])
    {
        SDL_RenderClear (render);
        if (states [ 0 ]) SDL_RenderCopy (render, texture [ 0 ], NULL, destrect [ 0 ]);
         if (states [ 1 ]) SDL_RenderCopy (render, texture [ 1 ], NULL, destrect [ 1 ]);
    }


    And now back to the inner loop and add many more code:
    Lots and lots of code
    if((keyboardState[SDL_SCANCODE_UP])||(keyboardState[SDL_SCANCODE_W]))
        move_UP(ren,player,player_RECT);
                    
    if((keyboardState[SDL_SCANCODE_DOWN])||(keyboardState[SDL_SCANCODE_S]))
        move_DOWN(ren,player,player_RECT);
    
    if((keyboardState[SDL_SCANCODE_LEFT])||(keyboardState[SDL_SCANCODE_A]))
        move_LEFT(ren,player,player_RECT);
    
    if((keyboardState[SDL_SCANCODE_RIGHT])||(keyboardState[SDL_SCANCODE_D]))
        move_RIGHT(ren,player,player_RECT);
    
    
    //ZOOM----------------------------------------------------------------
    if(keyboardState[SDL_SCANCODE_KP_PLUS])
    {
        TESTtexture_SCALE += 0.02;
        player_RECT.h = player_HEIGH * TESTtexture_SCALE;
        player_RECT.w = player_WIGHT * TESTtexture_SCALE;
    }
    if(keyboardState[SDL_SCANCODE_KP_MINUS])
    {
        TESTtexture_SCALE -= 0.02;
        player_RECT.h = player_HEIGH * TESTtexture_SCALE;
        player_RECT.w = player_WIGHT * TESTtexture_SCALE;
    }

    Especially there is nothing new. The only thing to add this design KeyboardState [Flag] .
    Such a construction returns true if the button is pressed and false to draw.
    Flag list ... YOU ALREADY SAID MANY TIMES!


Remaining display the result on the screen. To add to this cycle:
render_ UPDATE (ren, ARRAY_textures, ARRAY_rect, ARRAY_texturesState); 	/ / Written update function render us
SDL_RenderPresent (ren);	

Close the loop! 
And in the end we only need to complete our program.

Curtain!


Before you finish everything we need to remove our textures from memory.
SDL_DestroyTexture (Player) ; 
SDL_DestroyTexture (background) ;


And now you can safely shut down SDL and programs:
SDL_DestroyRenderer (ren) ; 
SDL_DestroyWindow (Win) ; 
SDL_Quit () ;	 
return 1 ;

Final, applause! We wrote the first program on SDL2! From what I congratulate us!

PS


To create an elementary program took me 2 days. The Internet is so small manual on SDL2, it is easier to shoot than it is to find. 
really hope that you enjoy this article has been helpful and this monster can take away from you as much time as I have.

Sample




#include <SDL2\SDL.h>
#include <SDL2\SDL_image.h>
#include <SDL2\SDL_mixer.h>
#include <GL\glut.h>
#include <iostream>
  
  
  
  
//SDL OVERLOAD------------------------------------------------------------------------------------------------------------------------------------------
void move_UP   (SDL_Renderer* render, SDL_Texture* texture, SDL_Rect &destrect, int offset = 5)
{
    destrect.y -= offset;
    SDL_RenderClear(render);
    SDL_RenderCopy(render, texture,NULL,&destrect);
}
void move_DOWN (SDL_Renderer* render, SDL_Texture* texture, SDL_Rect &destrect, int offset = 5)
{
    destrect.y += offset;
    SDL_RenderClear(render);
    SDL_RenderCopy(render, texture,NULL,&destrect);
}
void move_LEFT (SDL_Renderer* render, SDL_Texture* texture, SDL_Rect &destrect, int offset = 5)
{
    destrect.x -= offset;
    SDL_RenderClear(render);
    SDL_RenderCopy(render, texture,NULL,&destrect);
}
void move_RIGHT(SDL_Renderer* render, SDL_Texture* texture, SDL_Rect &destrect, int offset = 5)
{
    destrect.x += offset;
    SDL_RenderClear(render);
    SDL_RenderCopy(render, texture,NULL,&destrect);
}
  
void render_UPDATE(SDL_Renderer* render, SDL_Texture* texture[], SDL_Rect* destrect[], int states[])
{
    SDL_RenderClear(render);
    if(states[0]) SDL_RenderCopy(render, texture[0],NULL,destrect[0]);
    if(states[1]) SDL_RenderCopy(render, texture[1],NULL,destrect[1]);
}
  
  
//---------------------------------------------------------------------------------------------------------------------------------------------------------
  
  
  
  
int main( int argc, char* args[])
{
  
  
//INIT OF KEYBOAR LISTENER---------------------------------------------------------------------------------------------------------------------------------
    const Uint8 *keyboardState = SDL_GetKeyboardState(NULL);
//---------------------------------------------------------------------------------------------------------------------------------------------------------
  
  
  
  
//SDL INIT-------------------------------------------------------------------------------------------------------------------------------------------------
    SDL_DisplayMode displayMode;
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
        std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
        return 1;
    }   
    int request = SDL_GetDesktopDisplayMode(0,&displayMode);
      
//---------------------------------------------------------------------------------------------------------------------------------------------------------
  
  
//WINDOW INIT----------------------------------------------------------------------------------------------------------------------------------------------
    SDL_Window *win = SDL_CreateWindow("Hello World!", 0, 0, displayMode.w, displayMode.h, SDL_WINDOW_SHOWN);
    if (win == nullptr){
        std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
        return 1;
    }   
//---------------------------------------------------------------------------------------------------------------------------------------------------------
  
  
//RENDER INIT----------------------------------------------------------------------------------------------------------------------------------------------
    SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (ren == nullptr){
        std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
        return 1;
    }
//---------------------------------------------------------------------------------------------------------------------------------------------------------
  
      
  
  
  
//---------------------------------------------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------------------------------------------------------
  
//---------------------------------------------------------------------------GRAPHICS----------------------------------------------------------------------
  
//---------------------------------------------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------------------------------------------------------
  
  
  
  
  
  
  
//INIT OF TEXTURE AREAS------------------------------------------------------------------------------------------------------------------------------------
    SDL_Rect player_RECT;
        player_RECT.x = 0;  
        player_RECT.y = 0;  
        player_RECT.w = 333;
        player_RECT.h = 227;
    const int player_WIGHT = 333;
    const int player_HEIGH = 227;
    double TESTtexture_SCALE = 1.0;   
  
  
    SDL_Rect background_RECT;
        background_RECT.x = 0;
        background_RECT.y = 0;
        background_RECT.w = displayMode.w;
        background_RECT.h = displayMode.h;
    const int background_WIGHT = 1600;
    const int background_HEIGH = 900;
    double background_SCALE = 1.0;
      
  
//---------------------------------------------------------------------------------------------------------------------------------------------------------
  
  
  
  
//LOAD PLAYER IMAGE------------------------------------------------------------------------------------------------------------------------------------------
  
    SDL_Texture *player =  IMG_LoadTexture(ren,"..\res\player.png");
  
//---------------------------------------------------------------------------------------------------------------------------------------------------------
  
  
    SDL_Surface *BMP_background = SDL_LoadBMP("C:\\Users\\Cripos\\Desktop\\sdl4\\Debug\\res\\background.bmp");
    if (BMP_background == nullptr){
        std::cout << "SDL_LoadBMP Error: " << SDL_GetError() << std::endl;
        return 1;
    }
  
    SDL_Texture *background = SDL_CreateTextureFromSurface(ren, BMP_background);
    SDL_FreeSurface(BMP_background);
    if (player == nullptr){
        std::cout << "SDL_CreateTextureFromSurface Error: " << SDL_GetError() << std::endl;
        return 1;
    }   
//---------------------------------------------------------------------------------------------------------------------------------------------------------
  
  
//TEXTURES ARRAYS------------------------------------------------------------------------------------------------------------------------------------------
    SDL_Texture* ARRAY_textures[2] = {background, player};
    SDL_Rect* ARRAY_rect[2] = {&background_RECT, &player_RECT};
    int ARRAY_texturesState[2] = {1,1};
  
//---------------------------------------------------------------------------------------------------------------------------------------------------------
  
  
  
//FIRST SHOW-----------------------------------------------------------------------------------------------------------------------------------------------
    SDL_RenderClear(ren);
    SDL_RenderCopy(ren,background,NULL,&background_RECT);
    SDL_RenderCopy(ren, player, NULL, &player_RECT);
    SDL_RenderPresent(ren);
//---------------------------------------------------------------------------------------------------------------------------------------------------------
  
  
//SDL_Delay(2000);
  
  
//GAME CYCLE INIT------------------------------------------------------------------------------------------------------------------------------------------
    SDL_Event event;
    bool quit = false;
    while(!quit)
        while(SDL_PollEvent(&event))
        {
  
  
  
  
//MOUSE EVENTS---------------------------------------------------------------------------------------------------------------------------------------------
            SDL_PumpEvents();
            if(event.type == SDL_QUIT)
                quit=true;
                  
            if(event.type == SDL_MOUSEBUTTONDOWN)
            {
                if(event.button.button == SDL_BUTTON_LEFT && event.button.x <=10 && event.button.y <=10)
                    quit = true;
                if(event.button.button == SDL_BUTTON_RIGHT)
                    ARRAY_texturesState[1] = 1;
                if((event.button.button == SDL_BUTTON_LEFT) && (event.button.x >= player_RECT.x) && (event.button.y >= player_RECT.y) && (event.button.x <= player_RECT.w + player_RECT.x) && (event.button.y <= player_RECT.h + player_RECT.y))
                    ARRAY_texturesState[1] = 0;
            }
//---------------------------------------------------------------------------------------------------------------------------------------------------------
  
              
  
  
  
  
//KEYBOARD EVENTS------------------------------------------------------------------------------------------------------------------------------------------
  
            //MOVE-----------------------------------------------------------------------------------------------------------------------------------------
            if((keyboardState[SDL_SCANCODE_UP])||(keyboardState[SDL_SCANCODE_W]))
                move_UP(ren,player,player_RECT);
                  
            if((keyboardState[SDL_SCANCODE_DOWN])||(keyboardState[SDL_SCANCODE_S]))
                move_DOWN(ren,player,player_RECT);
  
            if((keyboardState[SDL_SCANCODE_LEFT])||(keyboardState[SDL_SCANCODE_A]))
                move_LEFT(ren,player,player_RECT);
  
            if((keyboardState[SDL_SCANCODE_RIGHT])||(keyboardState[SDL_SCANCODE_D]))
                move_RIGHT(ren,player,player_RECT);
              
            //---------------------------------------------------------------------------------------------------------------------------------------------
  
            //ZOOM-----------------------------------------------------------------------------------------------------------------------------------------
            if(keyboardState[SDL_SCANCODE_KP_PLUS])
            {
                TESTtexture_SCALE += 0.02;
                player_RECT.h = player_HEIGH * TESTtexture_SCALE;
                player_RECT.w = player_WIGHT * TESTtexture_SCALE;
            }
            if(keyboardState[SDL_SCANCODE_KP_MINUS])
            {
                TESTtexture_SCALE -= 0.02;
                player_RECT.h = player_HEIGH * TESTtexture_SCALE;
                player_RECT.w = player_WIGHT * TESTtexture_SCALE;
            }
            //---------------------------------------------------------------------------------------------------------------------------------------------
  
  
//---------------------------------------------------------------------------------------------------------------------------------------------------------
          
            render_UPDATE(ren, ARRAY_textures, ARRAY_rect, ARRAY_texturesState);    
            SDL_RenderPresent(ren); 
        }       
//END OF GAME CYCLE----------------------------------------------------------------------------------------------------------------------------------------
  
  
  
  
  
//TEXTURE DELETE-------------------------------------------------------------------------------------------------------------------------------------------
    SDL_DestroyTexture(player);
    SDL_DestroyTexture(background);
//---------------------------------------------------------------------------------------------------------------------------------------------------------
  
  
  
  
//ENDING---------------------------------------------------------------------------------------------------------------------------------------------------
    SDL_DestroyRenderer(ren);
    SDL_DestroyWindow(win);
    SDL_Quit(); 
    return 1;
  

}

No comments:

Post a Comment