SDL Programming in Linux: Getting Started with OpenGL


SDL is the foundation on which a game could be built without much ado. However, SDL is not complete in itself. It just provides services using, which, interaction between various components of a game/simulation as well as the games interaction with OS becomes seamless. If there are no components to utilize these services, then these services become just proof of concept. In a gaming engine, most of the time, these services are required by the rendering and AI components. From this part onwards I would be concentrating on the rendering component and its interaction with SDL. I will be covering the AI component in the future. Though SDL supports other graphics libraries, its usage with OpenGL is more common. The reason is that SDL and OpenGL fits like parts of a puzzle. So most of the time, the rendering component, or the rendering sub-system (I would be using this term from now onwards) of a gaming engine is built upon OpenGL. Hence understanding OpenGL is a must to build a good rendering sub-system. This part and the articles coming in the near future would be detailing the different aspects of OpenGL along with how SDL helps in creating a good framework for future purposes. In this part I would be providing whys and wherefores of OpenGL. The first section would detail about the whys and wherefores, second section would detail the steps in creating a basic application whereas in the second section I would be creating a framework using SDL that can be used in the future. In the same section, I would also use simple OpenGL routines to test the framework. That is the agenda for this discussion.

OpenGL- What is it:

 

If this question is asked, then the most common answer one would get is that OpenGL is graphics library in C. However, this is a misconception. In fact, OpenGL is low-level graphics library specification. Just like J2EE, OpenGL is nothing but a set of platform neutral, language independent and vendor neutral APIs. These APIs are procedural in nature. In simple terms, this means a programmer does not describes the object and appearances instead he/she details the steps through which an effect or an appearance can be achieved. These steps comprises of many OpenGL commands that includes commands to draw graphic primitives such as point, line, polygon etc in the three dimensions. OpenGL also provides commands and procedures to work with lighting, textures, animations etc. One important aspect to keep in mind is that OpenGL is meant for rendering. Hence it does not provide any APIs for working with I/O management, window management etc. that’s where SDL comes into picture. To understand how OpenGL renders, it is important to understand how it interfaces between graphics application and graphics card. So here we go.

The interfacing works at three levels. They are:

1. Generic Implementation

2. Hardware Implementation

3. OpenGL pipeline

While the Generic deals with providing a rendering layer that sits on top of the OS specific rendering system whereas Hardware implementation provides direct hardware interfacing and pipeline works at taking the command and giving it to hardware after processing. Lets look at the details.

1. Generic Implementation:

The other word for Generic Implementation is Software rendering. If the system can display a generated graphics, then technically speaking Generic Implementation can run anywhere. The place occupied by the Generic implementation is between the program and the software rasterizer. Pictorially it would be:

It is clear from the diagram that the Generic implementation takes the help OS specific APIs to draw the generated graphics. For example on Windows it is GDI whereas on *nix systems it is XLib. The generic implementation on Windows is known as WOGL and that on Linux is MESA 3D.

2. Hardware Implementation:

The problem with Generic implementation is that it depends on the OS for rendering and hence the rendering speed and quality differs from OS to OS. This is where Hardware Implementation comes. In this case, the calls to the OpenGL APIs are passed directly to the device driver (typically the AGP card’s driver). The driver directly interfaces the graphics device instead of routing it through OS specific graphics system. Diagrammatically:

The functioning of Hardware Interfacing is totally different from that of Generic Implementation which is evident from the diagram. Since interfacing with the device driver directly enhances both the quality as well as speed of the rendered graphics.

3. OpenGL Pipeline:

In essence, the term pipeline is a process that is the finer steps of a conversion or transformation. In other words a process such as conversion can be broken down into finer steps. These steps together form the pipeline. In a graphics pipeline, each stage or step refines the scene. In case of OpenGL it is vertex data. Whenever an application makes an API call, it is placed at command buffer alongwith commands, texture, vertex data etc. On flushing of this buffer(either programmatically or by driver), the contained data is passed on to the next step where calculation intensive lighting and transformations are applied. Once this is completed the next step creates colored images from the geometric, color and texture data. The created image is placed in the frame buffer which is the memory of the graphic device that is the screen. Pictorially this would be:

Though this a simplified version of the actual process, yet the above detailed process provides an insight into the working of OpenGL. This brings this section to conclusion. However one question still remains- what are the basic steps in creating an OpenGL application. That is what next section is about.

OpenGL- Basic Steps towards Application:

Till now theory of OpenGL was discussed. Now lets see how to put it into use. To draw any shape onto the screen, there are three main steps. They are:

1. Clearing the screen

2. Resetting the view

3. Drawing the scene

Of these the third step consists of multiple sub-steps. Following are the details:

1. Clearing the Screen:

To set the stage for drawing, clearing the screen is a must. This can be done by using the glClear() command. This command clears the screen by setting the values of the bit plane area of the view port. glClear() takes a single argument that is the bitwise OR of several values indicating which buffer is to be cleared. The values of the parameter can be :

a. GL_COLOR_BUFFER_BIT

It indicates the buffers currently enabled for color writing have to be cleared.

b. GL_DEPTH_BUFFER_BIT

This is used to clear the depth buffer.

c. GL_ACCUM_BUFFER_BIT

If the accumulation buffer has to be cleared use this.

d. GL_STENCIL_BUFFER_BIT

This is passed as parameter when the stencil buffer has to be cleared.

Next the color to be used as the erasing color is specified. This can be done using glClearColor(). This command clears the color buffers specified. That means when the specified color buffers are cleared the screen is recreated accordingly. So to clear the depth buffer and set the clearing color to blue the statements would be:

glClear(GL_DEPTH_BUFFER_BIT);

glClearColor(0.0f,0.0f,1.0f,0.0f);

2. Resetting the View:

The back ground and the required buffers have been cleared. But the actual model of the image is based on the view. View can be considered as the matrix representation of the image. So to draw this matrix has to be set to identity matrix. This is done using glLoadIdentity(). The statement would be:

glLoadIdentity();

3. Drawing the Scene:

To draw the scene we to tell OpenGL two things:

a. Start and Stop the drawing:

These commands are issued through the calls to glBegin() and glEnd(). The glBegin() takes one parameter-the type of shape to be drawn. To draw using three points use GL_TRIANGLES, GL_QUADS to use four points and GL_POLYGON to use multiple points. The glEnd() tells OpenGL to stop the drawing. For example, to draw a triangle the statements would be:

glBegin(GL_TRIANGLES);                                                                                                  :

:

glEnd();                    

The drawing commands come between these commands.

b. Issue the drawing commands:

In the drawing commands, vertex data is specified. These commands are of the type glVertex*f() where * corresponds to the no. of parameters-2 or 3. Each call creates a point and then connects it with the point created with earlier call. So to create a triangle with the coordinates (0.0, 1.0, 0.0), (-1.0,-1.0, 0.0) and (1.0,-1.0, 0.0) the commands would be:

glBegin(GL_TRIANGLES);

glVertex3f( 0.0f, 1.0f, 0.0f);                                            

                        glVertex3f(-1.0f,-1.0f, 0.0f);                                                                                                       glVertex3f( 1.0f,-1.0f, 0.0f);

glEnd();

That’s all there about drawing objects with OpenGL. In the next section, these commands would be used to put the SDL based framework to test.

SDL Based framework- Creation & Testing:

Till now I have discussed various APIs of SDL. Now its time to put them together so that working with OpenGL. So here we go.

First the includes:

#include <stdio.h>//  Include the Standard IO Header

#include <stdlib.h>// and the standard lib header

#include <string.h>// and the string lib header

#include <GL/gl.h>// we’re including the opengl header

#include <GL/glu.h>// and the glu header

#include <SDL.h>//and the SDL header

 

The global variables:

bool isProgramLooping;//we’re using this one to know if the program   

                                       //must go on in the main Loop

SDL_Surface *Screen;

 

Now the common functionalities- initialization, termination, full-screen toggling.

bool Initialize(void)// Any Application & User Initialization Code Goes Here

{

            AppStatus.Visible= true;         // At The Beginning, Our App Is Visible

            AppStatus.MouseFocus= true;// And Have Both Mouse

            AppStatus.KeyboardFocus = true;// And Input Focus

 

            // Start Of User Initialization. These are just examples

            angle    = 0.0f;// Set The Starting Angle To Zero

            cnt1= 0.0f;// Set The Cos(for the X axis) Counter To Zero

            cnt2= 0.0f;// Set The Sin(for the Y axis) Counter To Zero

           

         

            {

                        printf(“Cannot load graphic: %s\n”, SDL_GetError() );

                        return false;

            }

 

           

            return true;                                                                                                                                          // Return TRUE (Initialization Successful)

}

 

 

void Deinitialize(void)                                                                                                                         // Any User Deinitialization Goes Here

{

            return;                                                                                                                                                             // We Have Nothing To Deinit Now

}

 

void TerminateApplication(void)// Terminate The Application

{

            static SDL_Event Q;// We’re Sending A SDL_QUIT Event

 

            Q.type = SDL_QUIT;// To The SDL Event Queue

 

            if(SDL_PushEvent(&Q) == -1)            // Try Send The Event

            {

            printf(“SDL_QUIT event can’t be pushed: %s\n”, SDL_GetError() );             exit(1);                                                                                                                                                                                    // And Exit

            }

 

            return; // We’re Always Making Our Funtions Return

}

 

void ToggleFullscreen(void)                                                                                                                                                    // Toggle Fullscreen/Windowed (Works On Linux/BeOS Only)

{

            SDL_Surface *S;                                                                                                                                                                                  // A Surface To Point The Screen

 

            S = SDL_GetVideoSurface();                                                                                                                                        // Get The Video Surface

 

            if(!S || (SDL_WM_ToggleFullScreen(S)!=1))                                                                                       // If SDL_GetVideoSurface Failed, Or We Can’t Toggle To Fullscreen

            {

                        printf(“Unable to toggle fullscreen: %s\n”, SDL_GetError() );                                  // We’re Reporting The Error, But We’re Not Exiting

            }

           

            return;                                                                                                                                                                                                 // Always Return

}

 

Next comes the OpenGL parts- Creating an OpenGL window. In other words initializing OpenGL. But initializing needs updating as it is created. Hence the reshape function  :

void ReshapeGL(int width, int height) // reshape the window when it’s moved or resized

{

            glViewport(0,0,(GLsizei)(width),(GLsizei)(height));                                                              // Reset The Current Viewport

            glMatrixMode(GL_PROJECTION);                                                                                                                                 // select the projection matrix

            glLoadIdentity();                                                                                                                                                                     // reset the projection matrix

 

            gluPerspective(45.0f,(GLfloat)(width)/(GLfloat)(height),1.0f,100.0f);          // calculate the aspect ratio of the window

            glMatrixMode(GL_MODELVIEW);          // select the modelview matrix

            glLoadIdentity();                                 // reset the modelview matrix

            return;                                                

}

 

bool CreateWindowGL(int W, int H, int B, Uint32 F)                                                                            // This Code Creates Our OpenGL Window

{

            SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );                                                                                               // In order to use SDL_OPENGLBLIT we have to

            SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );                                                                               // set GL attributes first

            SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );

            SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );

            SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );                                                                          // colors and doublebuffering

 

            if(!(Screen = SDL_SetVideoMode(W, H, B, F)))                                                                                    // We’re Using SDL_SetVideoMode To Create The Window

            {

                        return false;                                                                                                                                                                 // If It Fails, We’re Returning False

            }

 

            SDL_FillRect(Screen, NULL, SDL_MapRGBA(Screen->format,0,0,0,0));                                                                                                                                                                                                                                                         

            ReshapeGL(SCREEN_W, SCREEN_H);                                                                                                                           // we’re calling reshape as the window is created

 

            return true;                                                                                                                                                                              // Return TRUE (Initialization Successful)

}

           

I will be discussing the APIs used in resize function in the next issue. Next is the draw function. It also contains the test code:

void Draw3D(SDL_Surface *S)            // OpenGL drawing code here

{

            glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear screen and

                                                                      //depth buffer. Screen color has been cleared at init

            glLoadIdentity();                                                                                                                                 // reset the modelview matrix

            glBegin(GL_TRIANGLES);                                                                   

                        glVertex3f( 0.0f, 1.0f, 0.0f);                                       

                        glVertex3f(-1.0f,-1.0f, 0.0f);                                                                                                  glVertex3f( 1.0f,-1.0f, 0.0f);                                              

              glEnd();

 

 

            glFlush();                                                                                                                                                         // flush the gl rendering pipelines

 

            return;

}

Now the main(). It contains the keyboard handling code

int main(int argc, char **argv)          

{

            SDL_Event E;   // and event used in the polling process

            Uint8 *Keys; // a pointer to an array that will contain the keyboard snapshot

            Uint32  Vflags; // our video flags

           

           

            Screen = NULL;

            Keys = NULL;  

            Vflags = SDL_HWSURFACE|SDL_OPENGLBLIT;//a hardware surface and special  

                                                                                          //openglblit mode

                                                //so we can even blit 2d graphics in our opengl scene

 

            if(SDL_Init(SDL_INIT_VIDEO)<0)// init the sdl library, the video subsystem

            {

              printf(“Unable to open SDL: %s\n”, SDL_GetError() );// if sdl can’t be nitialized

              exit(1);

            }

 

            atexit(SDL_Quit);// sdl’s been init, now we’re making sure thet sdl_quit will be   

                                          //called in case of exit()

 

 

            if(!CreateWindowGL(SCREEN_W, SCREEN_H, SCREEN_BPP, Vflags))                                      //  Video Flags Are Set, Creating The Window

            {

                        printf(“Unable to open screen surface: %s\n”, SDL_GetError() );                

                        exit(1);                                                                                               

            }

 

           

 

            if(!InitGL(Screen))// we’re calling the opengl init function

            {

              printf(“Can’t init GL: %s\n”, SDL_GetError() );

               exit(1);                                                                                                                                 }

 

            if(!Initialize())                                                                                                                         {

                        printf(“App init failed: %s\n”, SDL_GetError() );                                                                              exit(1);                                                                                                                        }

 

            isProgramLooping = true;                                                                                                                                          

           while(isProgramLooping)// and while it’s looping

            {

                        if(SDL_PollEvent(&E))

                        {

                                    switch(E.type)// and processing it

                                    {

                                               

                                    case SDL_QUIT:// it’s a quit event?

                                                {

                                                            isProgramLooping = false;                                                                                         

                                                            break;                                                                                                                          }

 

                                    case SDL_VIDEORESIZE:// It’s a RESIZE Event?

                                                {

                                                            ReshapeGL(E.resize.w, E.resize.h);                                                                

                                                            break;                                                                                                                                                  // And Break

                                                }

 

                                    case SDL_KEYDOWN:// Someone Has Pressed A Key?

                                                {

                                                            Keys = SDL_GetKeyState(NULL);                                                                                             break;                                                                                                                          }

 

                                    }

                        }

                       

                         Draw3D(Screen);                                                                                                                                            // Do The Drawings!

                                                SDL_GL_SwapBuffers();                                                                                                                      // and swap the buffers (we’re double-buffering, remember?)

                                    }

                        }

            }

 

            Deinitialize();  

            exit(0);            // And finally we’re out, exit() will call sdl_quit

 

            return 0;// we’re standard: the main() must return a value

}

 

That brings us to the end of this discussion. This time it was a bit lengthy. But the framework that has been developed just will work as the foundation for developing functionalities like lighting, texture mapping, animation and so on. The next topic would be using timers in animating the triangle just drawn. Till next time.

Game Programming using SDL: Working with File I/O API


File Input / Output, also generally known as file I/O, is one of the essential components of any software. Games are no exception. The file I/O can be for loading a background, texture or a simple text indicating level or score. It can also be used for saving player’s current statistics, level details or the custom map of the level. Whatever be the scenario, without a good and optimized file I/O, the game play will not become a rewarding experience for the player. With so many platforms to target, optimization of an API and making it generic to be used on multiple platforms becomes an arduous task. That is where file I/O API of SDL comes into play. The APIs provided by SDL are not platform specific. The platform specific aspects are taken care by SDL under the hood. Hence, developer has to focus only on the logics of the game and not on the ‘logistics’ of file operations. The focus of this discussion will be on the File I/O provided by SDL. The first section will be about the whys and wherefores of the API. In the second section, the steps for using the API will be detailed. The last section will have an example that makes use of the API discussed in the first two sections. That is the outline for this discussion.

SDL File I/O API – the Whys and Wherefores

File I/O API is one of the lesser documented API of SDL. However, the features provided by the API eases many File I/O operations such as loading image from an archived (zip or gzip) files. The main aspect or component of the API that makes such operations to be performed easily is the structure named SDL_RWops. Since SDL_RWops structure forms the basis of file I/O, the file operations as well as the API is also known as RWops. So, in short, the RWops API consists of the following:

1. The SDL_RWops structure

2. The functions that operate upon the structure

The former takes the file handles as well as pointers to memory mapped files. Later provides ways to read from or write to the file handles and memory mapped files. Here are the details.

1. The SDL_RWops structure:

It is akin in functionality to the FILE structure provided by the standard C library. In other words, SDL_RWops is the read write operation structure. All the file I/O functions make use of this structure to keep track of file handlers, current position being accessed etc. To use the API, it is not necessary to know the internals or details of this structure. The main point to keep in mind is all the RWops API needs this structure to work. So, any exceptions encountered during running of an application that makes use of RWops API can be traced back to problems with initialization of this structure. One point to keep in mind is that it is also called as ‘RWops structure’.

2.  The functions that operate upon the structure

Most of the functions provided by the RWops API are similar in functionality to their counterparts found in standard library. The most commonly used functions of RWops are:

a. SDL_RWFromFile

It opens a file, the name of which has been passed as the argument. Apart from the filename, the second argument is the mode in which the file has to be opened. The function returns a pointer to SDL_RWops structure corresponding to the file opened. The following statement opens a file named “tux.bmp” in read mode and returns a pointer to SDL_RWops structure of the “tux.bmp”.

SDL_RWops *file;

file = SDL_RWFromFile(“tux.bmp”, “r”);

b. SDL_RWFromMem

It prepares or allocates memory area for RWops to use. In other words, it sets up the RWops structure based a memory area of a certain size. It takes two arguments – the memory (or pointer to the memory) to be allocated and size of the memory. One of the scenarios where this method comes handy is when one wants to save the current screen as a bitmap. The following example sets up RWops structure based on byte array.

char bitmap[310000];

SDL_RWops *rw;

rw = SDL_RWFromMem(bitmap, sizeof(bitmap));

c. SDL_FreeRW

It frees up the memory allocated to the structure. It takes pointer to the RWops structure as argument.

That brings us to the end of this section. Next section will be about the steps to use the API.

Using RWops API – Step-by-Step:

There are three basic steps to use RWops API. They are

1. Get/initialize the SDL_RWops structure

2. Perform operations on the structure

3. Free the structure

Even though the steps seem similar to that of using standard API, in the case of RWops, the same structure can be used to access memory, stream or a file handle. Here are the details.

1. Get or initialize the SDL_RWops structure

As discussed in the previous section SDL_RWops structure forms the basis of any file I/O operations in SDL. So, the first step is to get RWops structure. There are four ways to get the structure or initialize it. They are

a. Using a filename

In this case, the structure is initialized directly from the file whose name has been provided. To do so, SDL_RWFromFile function needs to be used. The following statement instantiates the structure from “texture.bmp” file

SDL_RWops *file;

file = SDL_RWFromFile(“texture.bmp”, “r”);

 

In the above statements, the structure is initialized from the filename passed as argument. The second argument is the mode in which the structure is initialized. In this case the mode is “r” i.e. read-only. Hence, the structure can be used only to read from “texture.bmp” file. Following are the acceptable values for mode argument

“r” – Open a file for reading. The file must exist.

“w” -Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.

“a” – Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist.

“r+” – Open a file for update both reading and writing. The file must exist.

“w+” – Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.

“a+” – Open a file for reading and appending. All writing operations are performed at the end of the file, protecting the previous content to be overwritten. One can reposition (fseek, rewind) the internal pointer to anywhere in the file for reading, but writing operations will move it back to the end of file. The file is created if it does not exist.

b. From file pointer using SDL_RWFromFP

In this case, a file pointer is used to initialize the RWops structure. The file pointer, in this case, is opened using file I/O of standard library. This function is not present in the latest version of SDL since Windows platform does not support using files opened in an application by the DLLs. And SDL libraries are loaded as DLLs.

c. From a pointer in memory using SDL_RWFromMem

As discussed in first section, SDL_RWFromMem allows one to create RWops structure from memory based on pointer to the memory. On one hand, this comes handy when working with file data placed in memory using other API such as gzip API. On the other hand if one has to write something to a specific memory location, which then can be transferred to file, then also this function can be handy. The following statements depict the second scenario where memory location has to be written to.

char bitmap[310000];

SDL_RWops *rw;

rw = SDL_RWFromMem(bitmap, sizeof(bitmap));

SDL_SaveBMP_RW(screen_bitmap, rw, 0);

 

where screen_bitmap is pointer to the SDL_Surface containing the current screen data.

d. Allocating and filling it in manually using SDL_AllocRW:

Using SDL_AllocRW, one can get an empty RWops structure, the fields of which, needs to be filled manually. Following statement creates an empty RWops structure

SDL_RWops *c=SDL_AllocRW();

Explaining how to fill the structure is beyond the scope of this discussion.

This brings us to the second step.

2. Perform operations on the structure

Once the RWops structure is initialized, it can be used for any kind of file I/O permitted by SDL. It can be to update the texture of a scene, save the current screen as a bitmap, get the contents of a zip file and update the screen with it. It can be used to save the current map or player statistics. Possibilities are many. For example, the following statements reads a bitmap file and displays it on the screen

SDL_RWops *file;

SDL_Surface *image;

 

file = SDL_RWFromFile(“myimage.bmp”, “rb”);

image = SDL_LoadBMP_RW(file, 1); // 1 means the file will be automatically closed

 

3. Free the RWops structure

The last step is to free the structure once its usage is complete. This step is mandatory if the structure is created/initialized using SDL_AllocRW. To free the structure, pass the variable containing RWops structure pointer to SDL_FreeRW method. The following statement frees a RWops structure named rw

SDL_RWops *rw=SDL_AllocRW();

if(rw)

{

            SDL_FreeRW(rw);

}

That completes the section on the steps to use RWops API.

3. RWops API – In the real world

In real world, the API is not used as standalone. Most of the time it is used in conjunction with some other API such as zlib that reads archived files (zip, gzip etc.). The example, I am about to discuss, makes use of zlib API to read a archived file. The example will be developed as a method that will

a. Accept the name/full path of the archive

b. Return the RWops structure corresponding to the archive

Let us start with the header file to be included.

#include “SDL.h”

#include <stdio.h>

#include <zlib.h>

The zlib.h header is required for zlib API. Next is the function. It takes archive name and the size of memory to be allocated for the file content as the arguments and returns the RWops structure

SDL_RWops* GetFromArchive( char *archive, int bufferSize)

{

}

Next step is to declare variables for the RWops structure and the gzFile. gzFile is the zlib equivalent of standard I/O’s FILE structure. It will also initialize an array of size specified by bufferSize argument.

SDL_RWops* GetFromArchive( char *archive, int bufferSize)

{

 /* gzFile is the Zlib equivalent of FILE from stdio */

  gzFile file;

 

 /* This is the RWops structure we’ll be using */

  SDL_RWops *rw;

 

 Uint8 buffer[bufferSize];

 

  /* We’ll need to store the actual size of the file when it comes in

   */

  int filesize;

}

Next, open the archive, fill the buffer with contents of the archive and create RWops structure from the buffer. It will also return the created RWops.

SDL_RWops* GetFromArchive( char *archive, int bufferSize)

{

/* This is the RWops structure we’ll be using */

SDL_RWops *rw;

/* gzFile is the Zlib equivalent of FILE from stdio */

gzFile file;

Uint8 buffer[bufferSize];

/* We’ll need to store the actual size of the file when it comes in

*/

int filesize;

 filesize = gzread(archive, buffer, 13000);

/* Create RWops from memory – SDL_RWFromMem needs to know where

     the data is, and how big it is (that is the file size was saved)

  */

  rw = SDL_RWFromMem(buffer, filesize);

 

return rw;

}

That completes the example. The example assumes knowledge of zlib API. Though RWops provides way to read and write to and from files, neither RWops nor SDL itself provide easy way to manipulate the loaded images. That is where SDL Image library comes into picture. Working with the SDL Image API will be the focus of next discussion. Till then…

Packt is celebrating the publication of its 1000th title


PRESS RELEASE
28th September 2012
Packt Publishing reaches 1000 IT titles and celebrates with an open invitation

Birmingham-based IT publisher Packt Publishing is about to publish its 1000th title. Packt books are renowned among developers for being uniquely practical and focused, but you’d be forgiven for not yet being in the know – Packt books cover highly specific tools and technologies which you might not expect to see a high quality book on.

Packt is certain that in its 1000 titles there is at least one book that everyone in IT will find useful right away, and are inviting anyone to choose and download any one of its eBooks for free over its celebration weekend of 28-30th Sep 2012. Packt is also opening its online library for a week for free to give customers an easy to way to research their choice of free eBook.

Packt supports many of the Open Source projects covered by its books through a project royalty donation, which has contributed over $400,000 to Open Source projects up to now. As part of the celebration Packt is allocating $30,000 to share between projects and authors as part of the weekend giveaway, allocated based on the number of copies of each title downloaded.

Dave Maclean, founder of Packt Publishing:

“At Packt we set out 8 years ago to bring practical, up to date and easy to use technical books to the specialist tools and technologies that had been largely overlooked by IT publishers. Today, I am really proud that with our authors and partners we have been able to make useful books available on over 1000 topics and make our contribution to the development community.”

More details can be found at

http://bit.ly/RXnAMc

SDL Programming in Linux SDL & OpenGL-Brothers in Gaming


In the world of gaming, SDL provides the entire necessary infrastructure. This would have become clear from the past parts of the series. But infrastructure is to a game what skeleton is to a human body. But without muscles, no locomotion is possible. So working with the analogy of body, SDL provides the skeletal structure to build up the game whereas the flesh, blood and skin are provided by 2D and 3D graphics libraries. In the current plethora of 3D libraries, OpenGL stands out on various accounts. The most significant of them is its compatibility with almost all the platforms and graphics cards. This even reflects in the architecture of SDL as SDL can create and use OpenGL contexts on several platforms. Such architecture helps the game programmer to use all the sub-systems of SDL seamlessly in conjunction with OpenGL to provide most effective games and gaming environments. In this article I will discuss how to use SDL and OpenGL together where gaming infrastructure is provided by SDL and animation as well as rendering is being handled by OpenGL. The first section would discuss the steps required to integrate OpenGL with SDL. The second section would utilize the pointers provided in the first section to create an application having animation(basic) using OpenGL. That is the agenda for the current discussion.

Initialization- Bringing OpenGL into Picture:

 

In SDL all the sub-systems are initialized via SDL_Init(). OpenGL, being a part of graphics subsystem, is not directly initialized in this manner. For initializing OpenGL following are the steps:

1. Set OpenGL Attributes

2. Specify use of Double Buffering

3. Set the Video Mode

Of these second one is optional as it is used only when double buffering is a requirement. Lets have a detailed look at all of them.

1. Setting the OpenGL Attributes:

Before initializing the video, it is better to set up the OpenGL. These attributes are passed to the OpenGL via SDL calling the SDL_GL_SetAttribute() function. The parameters are the OpenGL attribute and their values. The most common attributes passed to this function are:

i. SDL_GL_RED_SIZE:

It sets the size of the red component of the frame buffer. The value is in bits. The commonly used value is 5. Similar parameters exist for blue and green components which are SDL_GL_BLUE_SIZE and SDL_GL_GREEN_SIZE respectively. To set green component to a bit value of 4 the code would be:

SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 4 );

ii. SDL_GL_BUFFER_SIZE:

To set the size of the frame buffer this attribute is passed with the required Buffer size in bits. It is greater than or equal to the combined value i.e. sum of the red, green, blue and alpha components. If the requirement is 24 bit color depth and alpha channel of 32-bits then each color component must be given the size value as 8 and frame buffer must be given size as 32. In code it would be:

SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );

SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );

iii. SDL_GL_DEPTH_SIZE:

This attribute controls the size of depth buffer or Z buffers. Normally the graphics cards provide 16-bit or 24-bit depth. If the value is set more than what is available, the operation will fail. To make it more clear following is the code:

SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,16);

iv. SDL_GL_ACCUM_RED_SIZE:

To set the size of red component of accumulation buffer, this attribute is used.

The value is specified in bits. SDL_GL_ACCUM_BLUE_SIZE, SDL_GL_ACCUM_GREEN_SIZE controls the size of blue and green component of accumulation buffer. In code it would be:

SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE,5);

The question that would be arising in your mind would be that whether these attributes could be set after initializing the video mode. The answer is no. The reason is that these settings have to be initialized before invoking and configuring video mode. Next we have to setup the video mode.

2. Setting up double buffering:

This aspect has also to be covered before setting up the video mode as this     attribute goes as a flag parameter to the SDL_GL_SetAttribute. The attribute is     SDL_GL_DOUBLEBUFFER and the value is either 1 or 0. The point to be kept in     mind is that when working in conjunction with OpenGL, the flag specifying double     buffer must be passed as an attribute to the SDL_GL_SetAttribute function and not to the SDL_Set_VideoMode(). In code this would be:

SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);

would set the double buffering to one state.

3. Setting the Video Mode:

Once the OpenGL attributes are set, setting the video mode is similar to the     setting of video mode as described in last tutorials. For more details have a look     at Part-II of the tutorial. The only difference comes in flags being sent to the     SDL_Set_VideoMode(). Apart from other required flags the SDL_OPENGL would     also be set i.e.

int flags=0;

flags= SDL_OPENGL | SDL_FULLSCREEN;

setting the SDL_OPENGL flag is a must.

That’s all there about the required steps. Now let the OpenGL play.

OpenGL in Action:

The theory is over. Its now time to see some real action. The example application would render a rotating triangle. The includes will contain one more header file.

#include <SDL/SDL.h>

#include <gl/gl.h>

 

gl.h contains function declarations necessary to work with OpenGL.

Next comes the main() and OpenGL attributes.

int main(int argc, char *argv[])

{

  SDL_Event event;

  float theta = 0.0f;

  SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );

  SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );

  SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );       

  SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );

 

:

:

}

Next initialize the video and video mode

 

int main(int argc, char *argv[])

{

SDL_Event event;

float theta = 0.0f;

SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );

SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );

SDL_Init(SDL_INIT_VIDEO);

  SDL_SetVideoMode(600, 300, 0, SDL_OPENGL | SDL_HWSURFACE | 

                               SDL_NOFRAME);

:

:

}

 

The video is initialized to 600×300 resolutions. And the hardware rendering mode is being used. This is done by SDL_HWSURFACE flag. Hence OpenGL would write on the graphic card’s memory instead of mapping it to software memory. After this step, the territory of OpenGL starts.

 

int main(int argc, char *argv[])

{

SDL_Event event;

float theta = 0.0f;

SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );

SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );

SDL_Init(SDL_INIT_VIDEO);

SDL_SetVideoMode(600, 300, 0, SDL_OPENGL | SDL_HWSURFACE |

SDL_NOFRAME);

glViewport(0, 0, 600, 300);

  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

  glClearDepth(1.0);

  glDepthFunc(GL_LESS);

  glEnable(GL_DEPTH_TEST);

  glShadeModel(GL_SMOOTH);

  glMatrixMode(GL_PROJECTION);

  glMatrixMode(GL_MODELVIEW);

:

:

}

to start working with OpenGL, the view port is initialized. Then the screen is cleared or rendered with the specified background color. Since the triangle would be rotating in 3D space hence the depth has to be set and depth testing has to be enabled. If smooth shading is not used, then the edges would seem jagged. Hence smooth shading model is used. This completes the setting up of OpenGL parameters after SDL video initialization. Drawing and rotation is taken care by the following code in bold:

int main(int argc, char *argv[])

{

SDL_Event event;

float theta = 0.0f;

SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );

SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );

SDL_Init(SDL_INIT_VIDEO);

SDL_SetVideoMode(600, 300, 0, SDL_OPENGL | SDL_HWSURFACE |

SDL_NOFRAME);

glViewport(0, 0, 600, 300);

glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

glClearDepth(1.0);

glDepthFunc(GL_LESS);

glEnable(GL_DEPTH_TEST);

glShadeModel(GL_SMOOTH);

glMatrixMode(GL_PROJECTION);

glMatrixMode(GL_MODELVIEW);

int done;

  for(done = 0; !done;)

 {

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

 

    glLoadIdentity();

    glTranslatef(0.0f,0.0f,0.0f);

    glRotatef(theta, 0.0f, 0.0f, 1.0f);

   :

:

}

}

The focus is brought to the point of origin by translating it. Then rotation function is provided the theta value through which the triangle has to be rotated.

int main(int argc, char *argv[])

{

SDL_Event event;

float theta = 0.0f;

SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );

SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );

SDL_Init(SDL_INIT_VIDEO);

SDL_SetVideoMode(600, 300, 0, SDL_OPENGL | SDL_HWSURFACE |

SDL_NOFRAME);

glViewport(0, 0, 600, 300);

glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

glClearDepth(1.0);

glDepthFunc(GL_LESS);

glEnable(GL_DEPTH_TEST);

glShadeModel(GL_SMOOTH);

glMatrixMode(GL_PROJECTION);

glMatrixMode(GL_MODELVIEW);

int done;

for(done = 0; !done;)

{

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glLoadIdentity();

glTranslatef(0.0f,0.0f,0.0f);

glRotatef(theta, 0.0f, 0.0f, 1.0f);

glBegin(GL_TRIANGLES);

    glColor3f(1.0f, 0.0f, 0.0f);

    glVertex2f(0.0f, 1.0f);

    glColor3f(0.0f, 1.0f, 0.0f);

    glVertex2f(0.87f, -0.5f);

    glColor3f(0.0f, 0.0f, 1.0f);

    glVertex2f(-0.87f, -0.5f);

    glEnd();

 

    theta += .5f;

    SDL_GL_SwapBuffers();

   :

:

}

}

The triangle is drawn by specifying the vertices. Then the theta value is increased. Next event handling part cometh.

int main(int argc, char *argv[])

{

SDL_Event event;

float theta = 0.0f;

SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );

SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE,8 );

SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32 );

SDL_Init(SDL_INIT_VIDEO);

SDL_SetVideoMode(600, 300, 0, SDL_OPENGL | SDL_HWSURFACE |

SDL_NOFRAME);

glViewport(0, 0, 600, 300);

glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

glClearDepth(1.0);

glDepthFunc(GL_LESS);

glEnable(GL_DEPTH_TEST);

glShadeModel(GL_SMOOTH);

glMatrixMode(GL_PROJECTION);

glMatrixMode(GL_MODELVIEW);

int done;

for(done = 0; !done;)

{

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glLoadIdentity();

glTranslatef(0.0f,0.0f,0.0f);

glRotatef(theta, 0.0f, 0.0f, 1.0f);

 glBegin(GL_TRIANGLES);

glColor3f(1.0f, 0.0f, 0.0f);

glVertex2f(0.0f, 1.0f);

glColor3f(0.0f, 1.0f, 0.0f);

glVertex2f(0.87f, -0.5f);

glColor3f(0.0f, 0.0f, 1.0f);

glVertex2f(-0.87f, -0.5f);

glEnd();

theta += .5f;

SDL_GL_SwapBuffers();

SDL_PollEvent(&event);

    if(event.key.keysym.sym == SDLK_ESCAPE)

      done = 1;

}

}

That’s it. This is how SDL and OpenGL work together. The only piece missing in this puzzle is sound. It will be tackled in the next part which incidentally is the last part of this series. So till next time.

SDL Programming in Linux – Events And Raw Graphics


Graphics and handling user inputs- the combination that creates the symphony called game. A world (of game) where these two are out of phase ends in cacophony. In the last article I discussed about the various parameters that goes into creating a screen and loading bitmapped images on to the screen. That was pretty high-level as the work was done on structures that represent the actual screen and maps or sprites. But there are times when one has to get his/her hand dirty by working directly upon pixels. The creators of SDL had already anticipated this requirement and built the capacities to work at raw graphics level into the core itself. Thus developer is redeemed from understanding system, platform and architecture specific nitty-gritty about manipulating the pixels. The other aspect of gaming that gives sleepless nights to developers is handling the user input, as the handling of input devices changes from system to system. To remove this burden from the minds of the developers, SDL provides object-oriented approach in handling the events. In this article, I would be discussing these two aspects of SDL. In the first section, the discussion would focus on using pixel manipulation functions and their usages and the second section would focus on input handling. So now that the agenda for this article have been laid down lets get started.   Raw Graphics-Writing Directly onto the Display:  Though the SDL Graphics APIs provide pretty high level functionality abstracting off all the low-level details, yet, there are times when abstraction is not required. For this purpose also there are ways. These ways doesn’t exist as a library function but as separate functions that has to be embedded into your program. The functions are freely available. But for the completeness I am including them here. These functions are:

  1. getpixel():

This function is useful if pixel value have to be obtained from a given coordinates represented by X and Y values on the display. It works on a single pixel at a time. The first parameter is the surface from which the value has to be obtained. This is represented by a pointer to the SDL_Surface. The next two integer parameters represent the x and y coordinates from where the pixel value has to be obtained. The return value is an Uint32 representing the value of the pixel. Following is the code:   /*  * Return the pixel value at (x, y)  * NOTE: The surface must be locked before calling this!  */ Uint32 getpixel(SDL_Surface *surface, int x, int y) {     int bpp = surface->format->BytesPerPixel;     /* Here p is the address to the pixel we want to retrieve */     Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;       switch(bpp) {     case 1:         return *p;       case 2:         return *(Uint16 *)p;       case 3:         if(SDL_BYTEORDER == SDL_BIG_ENDIAN)             return p[0] << 16 | p[1] << 8 | p[2];         else             return p[0] | p[1] << 8 | p[2] << 16;       case 4:         return *(Uint32 *)p;       default:         return 0;       /* shouldn’t happen, but avoids warnings */     } }   The first thing to be done is to obtain the depth represented by BytesPerPixel. It is done by the first statement: int bpp = surface->format->BytesPerPixel;   Next statement is self explanatory. To get the address of the pixel, the pitch of the of the passed surface is multiplied by the value of Y- coordinate, the depth is multiplied by the X- coordinate and the resulting values are added with pixel data of the surface represented by pixels member of SDL_Surface. This calculation provides the actual address of the pixel. The SDL_Surface could be thought of as multi dimensional array. Hence the value could be accessed as row-major and column-major format. That is done in the second statement: Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;  As the value returned by BytesPerPixels ranges from 1-4 according to the bytes needed to represent the pixel, it can be used for returning the values in the corresponding format i.e. 8, 16, 24 or 32. this is achieved by the switch-case block. That’s all about getpixel function.

  1. putpixel():

This is same as getpixel(). Apart from the parameters accepted by getpixel() function, this accepts one parameter extra- the address where the value has to be put. Following is the code for putpixel():   /*  * Set the pixel at (x, y) to the given value  * NOTE: The surface must be locked before calling this!  */ void putpixel(SDL_Surface *surface, int x, int y, Uint32 pixel) {     int bpp = surface->format->BytesPerPixel;     /* Here p is the address to the pixel we want to set */     Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;       switch(bpp) {     case 1:         *p = pixel;         break;       case 2:         *(Uint16 *)p = pixel;         break;       case 3:         if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {             p[0] = (pixel >> 16) & 0xff;             p[1] = (pixel >> 8) & 0xff;             p[2] = pixel & 0xff;         } else {             p[0] = pixel & 0xff;             p[1] = (pixel >> 8) & 0xff;             p[2] = (pixel >> 16) & 0xff;         }         break;       case 4:         *(Uint32 *)p = pixel;         break;     } }   The working of putpixel() is almost opposite to that of getpixel(). In case of later, the returned value is pixel value corresponding to the coordinates whereas the later places the pixel value according the coordinates. For this first the BytesPerPixel of the passed SDL_Suface is extracted just like before. Then pixel’s address (or pixel value) is calculated and according to the value returned by BytesPerPixels the value is placed. Since the calculated value is address of the pixel, hence the passed pixel value can be directly assigned and the display will be getting the new value.   Now that both the functions have been explained, lets see how to put one them to use i.e. putpixel(). For this I am defining a method called putyellowpixel() that places a yellow pixel at the center of the screen. It doesn’t accept any parameter nor does it returns any value.   void putyellowpixel() {     int x, y;     Uint32 yellow;       /* Map the color yellow to this display (R=0xff, G=0xFF, B=0x00)        Note:  If the display is palettized, you must set the palette first.     */     yellow = SDL_MapRGB(screen->format, 0xff, 0xff, 0x00);       x = screen->w / 2;     y = screen->h / 2;       /* Lock the screen for direct access to the pixels */     if ( SDL_MUSTLOCK(screen) ) {         if ( SDL_LockSurface(screen) < 0 ) {             fprintf(stderr, “Can’t lock screen: %s\n”, SDL_GetError());             return;         }     }       putpixel(screen, x, y, yellow);       if ( SDL_MUSTLOCK(screen) ) {         SDL_UnlockSurface(screen);     }     /* Update just the part of the display that we’ve changed */     SDL_UpdateRect(screen, x, y, 1, 1);       return;   }   To get the yellow color, the SDL_MapRGB() has to be used. The SDL_PixelFormat is the first parameter. It stores surface format information. Next three parameters correspond to the red, blue and green components of the color. The return value is the actual color corresponding to the passed color components in hexadecimal format as follows: yellow = SDL_MapRGB(screen->format, 0xff, 0xff, 0x00);   Once the color has been retrieved, the next step is to get the required x and y coordinates which is achieved by the following statement: x = screen->w / 2; y = screen->h / 2; then screen surface is locked. If this is not done, then corruption of the SDL_Surface structure could get corrupted causing instability of the game as putpixel works on the address of pixel directly. This is done by:   SDL_MUSTLOCK(screen);   The next step is to call the putpixel. Once putpixel has returned, then unlock the surface and update the surface. That completes placing a pixel directly on to the surface. Next section would focus on even handling with reference to keyboard.   Handling the Key Board- the SDL way:Whatever has been discussed till now completes only one aspect of providing interactivity. Even now the application doesn’t have the ability to handle user gestures provided through different input devices such as keyboard, joy stick etc. So now the focus would be on the input handling. Two of the most common input devices are mouse and keyboard. SDL has wrappers for each of these. In this section I would be discussing about keyboard handling. Before entering the world of keyboard events, it is better to understand the most recurring structures in keyboard handling jargon. They are:

  1. SDLKey:

It is an enumerated type that represents various keys. For example SDLK_a represents lowercase ‘a’, SDLK_DELETE is for ‘delete’ key and so on.

  1. SDLMod:

SDLKey enumeration represents only keys. To represent key modifiers such as Shift and Ctrl, SDLMod enumeration is provided by the SDL. The KMOD_CAPS is one of the enumeration that can be used to find out whether caps key is down or not. Other modifiers also have representations in SDLMod.

  1. SDL_keysym:

It is a structure that contains the information of a key-press. The members of this structure include scan code in hardware dependent format, SDLKey value of the pressed key in sym field, the value of modifier key in mod field and the Unicode representation of the key in Unicode field.

  1. SDL_KeyboardEvent:

From the name itself it is obvious that this structure describes a keyboard event. The first member, type, tells that the event is key release or key press event. The second member gives the same info as the first but uses different values. The last member is a structure itself- the SDL_keysym structure.   Now that the structures have been brought into the picture, the next step is to use these in handling the keyboard events. For this the logic is simple. The SDL_PollEvent is used to read the events. This is placed within the while loop. Then the value of type member of SDL_Event variable, passed as the parameter to SDL_PollEvent, is checked to find the type of event and then event processing can be done. In code it is thus:   SDL_Event event;   .   .   /* Poll for events. SDL_PollEvent() returns 0 when there are no  */   /* more events on the event queue, our while loop will exit when */   /* that occurs.                                                  */   while( SDL_PollEvent( &event ) ){     /* We are only worried about SDL_KEYDOWN and SDL_KEYUP events */     switch( event.type ){       case SDL_KEYDOWN:         printf( “Key press detected\n” );         break;         case SDL_KEYUP:         printf( “Key release detected\n” );         break;         default:         break;     }   }   .   .   If this is used this in the program developed in last article, the exit condition of the program can be controlled. The new version would exit only at key press.     void display_bmp(char *file_name) { SDL_Surface *image;   /* Load the BMP file into a surface */ image = SDL_LoadBMP(file_name); if (image == NULL) { fprintf(stderr, “Couldn’t load %s: %s\n”, file_name, SDL_GetError()); return; }   /* * Palettized screen modes will have a default palette (a standard * 8*8*4 colour cube), but if the image is palettized as well we can * use that palette for a nicer colour matching */ if (image->format->palette && screen->format->palette) { SDL_SetColors(screen, image->format->palette->colors, 0, image->format->palette->ncolors); }   /* Blit onto the screen surface */ if(SDL_BlitSurface(image, NULL, screen, NULL) < 0) fprintf(stderr, “BlitSurface error: %s\n”, SDL_GetError());   SDL_UpdateRect(screen, 0, 0, image->w, image->h);   /* Free the allocated BMP surface */ SDL_FreeSurface(image); }   int main(int argc,char* argv[]) { /*variable to hold the file name of the image to be loaded *In real world error  handling  code would precede this                                                                          */ char* filename=”Tux.bmp”; /*The following code does the initialization for Audio and Video*/ int i_error=SDL_Init(SDL_INIT_VIDEO); /*If initialization is unsuccessful, then quit */ if(i_error==-1) exit(1); atexit(SDL_Quit); /* * Initialize the display in a 640×480 8-bit palettized mode, * requesting a software surface */ screen = SDL_SetVideoMode(640, 480, 8, SDL_SWSURFACE); if ( screen == NULL ) { fprintf(stderr, “Couldn’t set 640x480x8 video mode: %s\n”, SDL_GetError()); exit(1); }   /*Handle the keyboards events here. Catch the SDL_Quit event to exit*/ done = 0;              while (!done)             {                SDL_Event event;                 /* Check for events */         while (SDL_PollEvent (&event))              {             switch (event.type)             {                           case SDL_KEYDOWN:                 break;                           case SDL_QUIT:                             done = 1;                            break;             default:                           break;             }         } /* Now call the function to load the image and copy it to the screen surface*/ load_bmp(filename); }   If you run the above code the window wont be closed until the close button is pressed. Though, this code does nothing much in area of interactivity but it’s a beginning. So as you can see, it is really easy to handle keyboard events using SDL. It totally removes the dependence of developer on Operating System for event handling. Also working at raw graphics level is not that difficult.   This brings us to the end of the third part of SDL programming. The next part would cover using OpenGL with SDL. Also using timers would be covered. Till next time.

Sockets in Python: Into the world of Python Network Programming


“Code less ..Achieve more” is the prime philosophy behind the development of all the Very High Level Languages (or VHLL in short). But less no. of lines should not mean reduced flexibility in terms of choosing an approach in solving a problem. Though many of the VHLL or Scripting Languages as they are popularly known, does not keep in mind the flexibility, yet there area few that have the logic of flexibility and choice as their core. Python is one of them. This fact is evident if one tries to do network programming in Python. The choices are aplenty for the programmer. The choices range from low-level sockets or raw-sockets to a completely extensible and functional web-server. In this tutorial I will be discussing how to use raw sockets to create network oriented applications in Python. The first section will cover the basics of the socket module and by the end of the section a simple echo server will be coded. In the second section the echo server would be enhanced by making it capable of serving multiple clients using the concepts introduced in the first section.

 

Sockets and Ports- Doing it the Python way:

Sockets and ports form the core of any network oriented application. According to the formal definition a socket is “An endpoint of communication to which a name may be bound”. The concept (as well as implementation) comes from the BSD community. The 4.3BSD implementation defines three domains for the sockets:

  1. Unix Domain/ File-system Domain:

The sockets under this domain are used when two or more processes within a system have to communicate with each other. In this domain, the sockets are created within the file system. They are represented as strings that contains local path such as /var/lock/sock or /tmp/sock.

 

  1. Internet Domain:

This domain represents the processes that communicate over the TCP/IP. The sockets created for this domain are represented using a (host, port) tuple. Here host is a fully qualified Internet host name that can be represented using a string or in the dotted decimal format (or IP address).

  1. NS Domain:

This domain is the one used by the processes communicating over Xerox protocol which is now obsolete.

 

Of these only the first two are the most commonly used. Python supports all of these. My discussion would be limited to the Internet Domain. To create an application that uses TCP/IP sockets following are the steps:

 

  1. Creating a socket
  2. Connecting the socket
  3. Binding the socket to an address
  4. Listening and accepting connections
  5. Transferring data/receiving data.

 

But before creating a socket libraries have to be imported. The socket module contains all that is needed to work with sockets. The imports can be done in two ways:

import socket or from socket import *. If the first form is used then to access the methods of socket module, socket.methodname() would have to be used. If the later format is used, then the methods could be called without the fully qualified name. I will be using the second format for clarity of the code and ease. Now lets see the various provisions within socket module for the programmers.

 

  1. Creating a socket:

A socket can be created by making call to the socket() function. The socket() function returns a socket in the domain specified. The parameters to the function are:

 

a. family:

The family parameter specifies in which domain the socket has to be created.  The valid values are AF_UNIX for UNIX domain and AF_INET for internet domain.

b. type:

Type defines the type of the protocol to be used. The type can be                   connection oriented like TCP or connection less like UDP. These are defined by the constants SOCK_STREAM for TCP, SOCK_DGRAM for UDP. Other valid parameters are SOCK RAW, SOCK SEQPACKET and SOCK RDM.

c. protocol:

This generally left for default value. The default is 0.

 

So a socket for Internet domain is created thus:

testsocket=socket(AF_INET,SOCK_STREAM)

 

  1. Connecting the Socket:

Sockets thus created can be used on the server-side or client-side. To use the socket as client-socket it needs to be connected to a host. That can be done using the connect() method of the socket object. The connect() method accepts either the host name as the parameter or a tuple containing host name/address and port number as parameter. For example to connect to a host whose address is 192.168.51.100 and the port number 8080 the statement would be:

 

testsocket.connect((‘192.168.51.100’,8080))

 

  1. Binding the socket to an address:

If the socket has to be used on the server side, then the socket has to be bound to an address and a port, thus naming it. To bind a socket to an address, the bind() method of the socket object has to be used. The valid parameter is a tuple containing the address to which the socket has to be bound and the port at which it has to listen for incoming requests. To use the same socket i.e. testsocket on the server side the statement would be:

 

testsocket.bind((‘192.168.51.100’,8080))

  1. Listening and accepting connections:

Once a socket has been named, then it has to be instructed to listen at the given port for incoming requests. This can be done using the listen() method. The listen accepts a no. representing the maximum queued connection. The argument should be atleast 1. for example the following code sets the max queued connection to 2:

 

testsocket.listen(2)

The next thing to be done is to accept the incoming connection requests. This can be done by the accept() function. This function returns a tuple containing a new socket object representing the client and the address of the client. For example:

clientsock,address= testsocket.accept()

in the above statement clientsock would contains a new socket object and address would contain the address of the client.

 

  1. Transferring data/receiving data:

Data can be transferred using recv() and send() methods of socket object. Socket’s recv() method is used to receive the data send from the server or from the client. The parameters are a buffer size for the data , and flags. The flags parameter is optional. So to receive data the code would be:

buff=1024

testsocket.recv(buff)

 

To send the data, a call to the send method is in order. The parameters are the data to be send and the flags. To elucidate  further:

data=raw_input(‘>>’)

testsocket.send(data)

Now that the steps are clear, lets create a simple echo server. First the imports

from socket import *

Then the constants that defines the host, port, buffer size and the address tuple to be used with bind().

 

from socket import *

HOST = ‘localhost’

PORT = 21567

BUFSIZ = 1024

ADDR = (HOST, PORT)

 

Then create the server side socket and bind it to the host and the port. Then comes the max queue size to 2:

 

from socket import *

HOST = ‘localhost’

PORT = 21567

BUFSIZ = 1024

ADDR = (HOST, PORT)

serversock = socket(AF_INET, SOCK_STREAM)

serversock.bind(ADDR)

serversock.listen(2)

 

Now to make it listen for incoming requests continuously place the accept() method in a while loop. This is not the most preferable mode. The preferable way will be discussed in next section:

 

from socket import *

HOST = ‘localhost’

PORT = 21567

BUFSIZ = 1024

ADDR = (HOST, PORT)

serversock = socket(AF_INET, SOCK_STREAM)

serversock.bind(ADDR)

serversock.listen(2)

 

while 1:

print ‘waiting for connection…’

clientsock, addr = serversock.accept()

print ‘…connected from:’, addr

:

:

Next  receive the data from the client and echo it back. This has to continue till the client doesn’t send the null data or ctrl+c. to achieve this again use a while loop and then close the connection when done.

 

from socket import *

HOST = ‘localhost’

PORT = 21567

BUFSIZ = 1024

ADDR = (HOST, PORT)

serversock = socket(AF_INET, SOCK_STREAM)

serversock.bind(ADDR)

serversock.listen(2)

 

while 1:

print ‘waiting for connection…’

clientsock, addr = serversock.accept()

print ‘…connected from:’, addr

 

while 1:

data = clientsock.recv(BUFSIZ)

if not data: break

clientsock.send(‘echoed’, data)

 

clientsock.close()

serversock.close()

 

That’s all for the server. Now for the client. The only exception is that there is no bind(), accept() and listen().

 

from socket import *

HOST = ‘localhost’

PORT = 21567

BUFSIZ = 1024

ADDR = (HOST, PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM)

tcpCliSock.connect(ADDR)

while 1:

data = raw_input(‘> ‘)

if not data: break

tcpCliSock.send(data)

data = tcpCliSock.recv(1024)

if not data: break

print data

tcpCliSock.close()

Multi-Threaded Echo Server- Other Approach in Creating a Server:

 

In the above example the uses while loop to service different clients. For elucidations it is ok. But in the real world, it won’t work well. The reason is that more than one client cannot be served simultaneously by just while constructs. To overcome the limitations there are several strategies. One of them is making the server multi-threaded. There are two parts in the creation of a multi threaded server:

 

  1. Create threads for each accepted  connections:

This is the core of the multi-threaded server. For each accepted connection request, a different thread is created and the serving that particular client is carried out by an independent thread. Thus quick response time can be achieved.

 

  1. Create a handler:

It is the handler where the whole processing goes on. In our case transferring a file.

 

To make the echo server some changes have to be made. It starts with the accept part as shown below:

 

from socket import *

from threading import *

HOST = ‘localhost’

PORT = 21567

BUFSIZ = 1024

ADDR = (HOST, PORT)

serversock = socket(AF_INET, SOCK_STREAM)

serversock.bind(ADDR)

serversock.listen(2)

while 1:

print ‘waiting for connection…’

clientsock, addr = serversock.accept()

print ‘…connected from:’, addr

thread.start_new_thread(handler, (clientsock, addr))

 

 

 

serversock.close()

 

After accepting the request a new thread is created for the client. This is done for each connection request. The logic of handling the client is defined within the handler which goes thus:

 

from socket import *

from threading import *

def handler(clientsock,addr):

while 1:

data = clientsock.recv(BUFSIZ)

if not data: break

clientsock.send(‘echoed:..’, data)

 

clientsock.close()

if __name__==’__main__’:

HOST = ‘localhost’

PORT = 21567

BUFSIZ = 1024

ADDR = (HOST, PORT)

serversock = socket(AF_INET, SOCK_STREAM)

serversock.bind(ADDR)

serversock.listen(2)

 

while 1:

print ‘waiting for connection…’

clientsock, addr = serversock.accept()

print ‘…connected from:’, addr

thread.start_new_thread(handler, (clientsock, addr))

#some other cleanup code if necessary

 

The handler has to be defined before calling it. The handler contains the same code that was contained in the inner while loop previously. This example is not optimized. But it serves the purpose of providing a different approach for serving multiple clients. This brings us to the end of this section.

 

Parting Thoughts:

  1. The low level sockets can be mixed and matched with other modules such as threads and forks to create a server capable of serving multiple clients simultaneously.
  2. While using threading approach the locking and synchronization issues must be kept in mind.
  3. The security measures must be taken care of when creating FTP kind of servers.

 

This brings us to the end of this discussion. In the introductory section I mentioned flexibility as one of the core aspects of Python. Ability to work with low-level sockets is one of them. But at the other end of the spectrum are the pre-built yet extensible web-servers. These will be discussed in the near future. Till then…

2010 in review


The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here’s a high level summary of its overall blog health:

Healthy blog!

The Blog-Health-o-Meter™ reads This blog is on fire!.

Crunchy numbers

Featured image

A helper monkey made this abstract painting, inspired by your stats.

A Boeing 747-400 passenger jet can hold 416 passengers. This blog was viewed about 3,400 times in 2010. That’s about 8 full 747s.

In 2010, there were 7 new posts, growing the total archive of this blog to 65 posts.

The busiest day of the year was August 13th with 39 views. The most popular post that day was Bluetooth Programming in Python: Network Programming using RFCOMM.

Where did they come from?

The top referring sites in 2010 were note19.com, en.wordpress.com, yandex.ru, google.co.in, and packtpub.com.

Some visitors came searching, mostly for server_sock listen python, c# image memory intptr to bitmap, python bluetooth, steps for accessing camera using pys60, and operations on text in pys60.

Attractions in 2010

These are the posts and pages that got the most views in 2010.

1

Bluetooth Programming in Python: Network Programming using RFCOMM May 2010
2 comments

2

Image Manipulation using GDI+ – The C# Way: Thumbnails and Zooming July 2009
2 comments

3

Bluetooth Programming using Python April 2010
1 comment

4

Mobile Programming in Python using PyS60: UI Controls July 2009
3 comments

5

Mobile Programming using PyS60: Advanced UI Controls July 2009
1 comment