""

Category: Opengl

2D Rain Effect

Hola Everyone.
I am working on a level for 2d game where i needed to add a rain effects. I am using Slick 2D library for making my 2d game. Before i started working on making 2D rain effect , i discussed this topic on slick 2d forum for how to get started ? Here is the forum thread. You can check it out.
So i wrote a simple code to create a rain effect:
1) Make a Rain Drop, i wrote a class for Rain Drop that extends Polygon class. Yes i m creating rain drops with polygons.
2) Create number of drops at random coordinates and simulate it across the screen i.e make them fall. You can use wind factor also for providing bit more interesting.


So this is the way i started.

Here is the Rain Drop class:


import org.newdawn.slick.geom.Polygon;

public class RainDrop extends Polygon{
public RainDrop(int size){
super();

/** coordinates of vertices of polygon(rain drop) */
this.addPoint(0, 0);
this.addPoint(0, size);
}
}

This is the main class where we are using rain drops and simulating it to create a simple rain effect, nothing fancy.


import java.util.logging.Level;
import java.util.logging.Logger;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;

public class Rainy extends BasicGame{

private RainDrop[] drops;
private Image background;

public Rainy(){
super("");
}

public static void main(String[] args){
try {
AppGameContainer app = new AppGameContainer(new Rainy());
app.setDisplayMode(1024, 768, true);
app.setTargetFrameRate(100);
app.setShowFPS(false);
app.start();
} catch (SlickException ex) {
Logger.getLogger(Rainy.class.getName()).log(Level.SEVERE, null, ex);
}
}

@Override
public void init(GameContainer gc) throws SlickException {
background=new Image("data/jungle.jpg");

/** creating 700 rain drops and placing it on random location across the screen */
initializeRain(900);
}

@Override
public void update(GameContainer gc, int delta) throws SlickException {

for(int i=0;i768){

drops[i].setX((float) ((Math.random() * 2000)+30));

drops[i].setY((float) ((Math.random() * 5)));

}

}

}

public void render(GameContainer gc, Graphics g) throws SlickException {
g.drawImage(background, 0, 0);
g.setColor(new Color(188.0f,227.0f,229.0f,0.3f));
for(int i=0;i

So what i am doing :
1) initializeRain(int num_of_drops) takes an int parameter which denotes the number of rain drops. This function creates a number of rain drops(instance of raindrop class) and assigns the random x and y position to each rain drops.
2) Then we simply iterate the array of rain drops and translate them across the screen. When drops reaches the bottom of screen then we simply restore back to random initial starting postion. This keeps going on and gives the impression of rainy effect.

This is very simple 2d effect that i started with. You can write your own optimized version and can add more feature to give fancy impression like adding alpha values for each rain drop etc.

Gracias.


box

Hola everyone.

I am currently working on my own two game projects: one project is of mobile phone game and other is 2.5 or side-scrolling 3d game, not much sure. So for second project i am making an small engine that will be used to make 2.5D game or side scrolling 3d game, Just simple and fun game. I have chosen LWJGL, which is a java binding for Opengl to make my game. So first thing i need to work on loading images.texture mapping in lwjgl. I found some pretty much useful tutorials and great help from lwjgl forums. But atlast i got something that i was looking for from the forum.

I came to know about slick-util which is free and open source lib to load images and play sounds. Its very easy to pick up and implement it. Its just worked flawlessly and smoothly for me. You can download the slick-util from here. PNG, GIF, JPG, TGA are supported and WAV, OGG, XM sounds are supported by slick-util.

So here i’l show u how easily i loaded images and mapped to a 3D BOX. First u have to setup lwjgl and slick-util with netbeans. Yeah i am using netbeans to write my program. You can see my post to setup lwjgl with netbeans. Now we will set up slick-util, its a continuation to the steps that we did to setup lwjgl.

Continued…

Step 1: We just have to configure the project properties so that project can find the lib to compile and run.

1

2

Ok that was it. Now slick-util lib has been set up.Now first i’l show u how to load image and bind it , full source will be at the end.

Texture texture;

Texture is an interface having description of texture which will be loaded.

texture = TextureLoader.getTexture(“PNG”, new FileInputStream(“Data/Crate.png”));

now we are loading the texture using TextureLoader utility class. Just smooth and simple.

texture.bind();

Now we are binding the texture.

So thats what u need to load the image and map them to objects. Download this image to use it in this program.

Crate

Full Code:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package com.gaanza.engine.test2;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.glu.GLU;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;

/**
*
* @author Java Guy
*/
public class EngineTest {

private static boolean gameRunning=true;
private static int targetWidth = 800;
private static int targetHeight = 600;

private float xrot=0.1f;
private float yrot=0.1f;
private float zrot=0.1f;

/** The texture that's been loaded */
private Texture texture;

public static void main(String[] args){
EngineTest app=new EngineTest();
initDisplay(false);
initGL();
app.init();
app.run();
}

private static void initDisplay(boolean fullscreen){

DisplayMode chosenMode = null;

try {
DisplayMode[] modes = Display.getAvailableDisplayModes();

for (int i=0;i

Gracias.

On Forums, people keeps asking about setting up lwjgl library with netbeans. So here i am going to show the steps to do that.

STEP 1: Go to Tools-> Libariries.Now create new library. Give it a name say “lwjgl21”.

step1

STEP 2: Now we have to configure the library. Click the classpath tab, then click add jars, and add all the jars shown below:

step2

STEP 3: If u want to add java doc than click the javadoc tab, and then add the javadoc folder. Then finally click oK and lwjgl21 library that we have just created is done.

STEP 4: Now create a empty java project.

step3

STEP 5: Now we have to set the properties so that our newly created project can find the lwjgl library and jar files. So Right-Click the project-> Properties. Now check the image carefully and configure accordingly. So first select libraries on the categories section and then click compile tab, and then add jar file for compilation step. This step is very important so check image properly below.

step4

STEP 6: Okie now click run tab, and add the library that we had just created. Check the image very properly.

step5

STEP 7: Now the final step. We have to provide the argument so that project cud find the necessary dll files. So first select the Run at caregories section then go to vm-options. Check the image properly and follow.

step6

Okie thats it. Now click ok. So you have just set up lwjgl with your netbeans ide. So now you can compile and run your lwjgl app. I am using netbeans ide 6.7.

Gracias

Alpha Blending using OpenGL with SDL

sdl_opengl

Alpha Blending is a convex combination of two colors allowing for transparency effects in computer graphics. Blending is used to combine the color of a given pixel that is about to be drawn with the pixel that is already on the screen. How the colors are combined is based on the alpha value of the colors, and/or the blending function that is being used. Alpha is a 4th color component usually specified at the end.

Alpha Blending in SDL is slow because its not a hardware accelerated. To get a better performance there is OpenGL which is hardware accelerated. So here i’l show you how to use alpha blending using opengl with sdl.


glColor4f(1.0f,1.0f,1.0f,alpha); // full Brightness, Alpha

glBlendFunc(GL_SRC_ALPHA,GL_ONE); // Blending Function for  translucency based on source alpha value>

First line set the color to full brightness with alpha value. An alpha value of 0.0 would mean that the material is completely transparent . A value of 1.0 would be totally opaque. The primitive’s opacity is specified using glColor4*(). RGB specifies the color, and the alpha parameter specifies the opacity.


glEnable(GL_BLEND);                      // Turn Blending on

glDisable(GL_DEPTH_TEST);        //Turn Depth Testing off

So this is it what you will required to achieve alpha blending.

Below code is a simple FADE IN/FADE OUT program. When UP arow key is pressed then 2d sprite will fade out and when DOWN key is pressed then 2d sprite will fade in.

alpha

Here is the full Source Code:

#include "SDL.h"
#include "SDL_image.h"
#include "SDL_opengl.h"

#include <stdio.h>

GLuint texture=NULL;     //this is a handle to our texture object
GLenum texture_format=NULL;
GLint nofcolors;

SDL_Event event;

float alpha=1.0f;
bool UP=false;         //Up key is pressed/released
bool DOWN=false;       //DOWN key is pressed/released

int loadImage()
{
SDL_Surface *surface; // this surface will tell us the details of the image

if ( (surface = IMG_Load("flower.png")) ) {

// Check that the image's width is a power of 2
if ( (surface->w & (surface->w - 1)) != 0 ) {
printf("warning: image.bmp's width is not a power of 2\n");
}

// Also check if the height is a power of 2
if ( (surface->h & (surface->h - 1)) != 0 ) {
printf("warning: image.bmp's height is not a power of 2\n");
}

//get number of channels in the SDL surface
nofcolors=surface->format->BytesPerPixel;

//contains an alpha channel
if(nofcolors==4)
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGBA;
else
texture_format=GL_BGRA;
}
else if(nofcolors==3) //no alpha channel
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGB;
else
texture_format=GL_BGR;
}
else
{
printf("warning: the image is not truecolor...this will break ");
}

// Have OpenGL generate a texture object handle for us
glGenTextures( 1, &texture );

// Bind the texture object
glBindTexture( GL_TEXTURE_2D, texture );

// Set the texture's stretching properties
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

glTexImage2D( GL_TEXTURE_2D, 0, nofcolors, surface->w, surface->h, 0,
texture_format, GL_UNSIGNED_BYTE, surface->pixels );
}
else {
printf("SDL could not load image.bmp: %s\n", SDL_GetError());
SDL_Quit();
return 1;
}

// Free the SDL_Surface only if it was successfully created
if ( surface ) {
SDL_FreeSurface( surface );
}
}

void drawImage()
{
glClear( GL_COLOR_BUFFER_BIT );   // Clear the screen before drawing

glTranslatef(300.0,200.0,0.0);

glBindTexture( GL_TEXTURE_2D, texture );   // Bind the texture to which subsequent calls refer to

glColor4f(1.0f,1.0f,1.0f,alpha);            // Full Brightness, Alpha
glBlendFunc(GL_SRC_ALPHA,GL_ONE);           // // Blending Function For Translucency Based On Source Alpha Value

glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2i( 0, 0 );
glVertex3f( -64, -64, 0 );

// Bottom-left vertex (corner)
glTexCoord2i( 1, 0 );
glVertex3f( 64, -64, 0 );

// Bottom-right vertex (corner)
glTexCoord2i( 1, 1 );
glVertex3f( 64, 64, 0 );

// Top-right vertex (corner)
glTexCoord2i( 0, 1 );
glVertex3f( -64, 64, 0 );
glEnd();
glLoadIdentity();

SDL_GL_SwapBuffers();
}

int init()
{
SDL_Surface *screen;

// Slightly different SDL initialization
if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
printf("Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}

SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL);
if ( !screen ) {
printf("Unable to set video mode: %s\n", SDL_GetError());
return 1;
}
}

void init_GL()
{
// Set the OpenGL state after creating the context with SDL_SetVideoMode

glClearColor( 0, 0, 0, 0 );

glEnable( GL_TEXTURE_2D );        // Need this to display a texture
glEnable(GL_BLEND);                  // Turn Blending On
glDisable(GL_DEPTH_TEST);         //Turn Depth Testing Off

glViewport( 0, 0, 640, 480 );

glMatrixMode( GL_PROJECTION );
glLoadIdentity();

glOrtho( 0, 640, 480, 0, -1, 1 );

glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}

void clean_up()
{
glDeleteTextures( 1, &texture );

SDL_Quit();
}

int main(int argc, char *argv[])
{
//Make sure the program waits for a quit
bool quit = false;

init();
init_GL();
loadImage();
drawImage();

while( quit == false )
{
if( SDL_PollEvent( &event ) )
{
//If a key was pressed
if( event.type == SDL_KEYDOWN )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_UP:
UP=true;
break;
case SDLK_DOWN:
DOWN=true;
break;
case SDLK_ESCAPE:
quit=true;
break;
}
}
//If a key was released
else if( event.type == SDL_KEYUP )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_UP:
UP=false;
break;
case SDLK_DOWN:
DOWN=false;
break;
}
}
}

// If UP key is pressed

if(UP==true){
if(alpha<1.0f)         // make sure alpha value is not greater than maximum value 1.0
alpha+=0.01f;       //increase the alpha value, fade out
drawImage();
}

else if(DOWN==true){    //If DOWN key is pressed
if(alpha>0.0f)       // make sure value of alpha is not less than 0.0f
alpha-=0.01f;      // decrease the alpha value, fade in
drawImage();
}

}

clean_up();
return 0;
}

So thats it. Now you are off to fly.

Gracias.


Rotating 2D Sprite: In my previous post i showed how to move a 2D sprite in two dimensional screen using Opengl with SDL. Now in this post i’l show how to rotate a 2D sprite using Opengl with SDL.

In Opengl, rotation can be made about x axis, y axis and z axis. In different axis rotation occurs differently like:

about X axis: like closing your laptop

about Y axis: like turning a page in a book

about Z axis: like the hands of a clock

So to rotate our 2D sprite we use glRotatef(angle,x,y,z). If you want to rotate about x axis the the value of x will be 1.0, y and z will be 0.0. How much angle do you want to rotate your sprite is determined by the value of angle to glRotatef() parameter.

So here is the drawImage() function to draw and rotate the 2D sprite:

void drawImage()
{
// Clear the screen before drawing
glClear( GL_COLOR_BUFFER_BIT );

glTranslatef(300.0,200.0,0.0);

// Bind the texture to which subsequent calls refer to
glBindTexture( GL_TEXTURE_2D, texture );

glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2i( 0, 0 );

// Bottom-left vertex (corner)
glTexCoord2i( 1, 0 );

// Bottom-right vertex (corner)
glTexCoord2i( 1, 1 );

// Top-right vertex (corner)
glTexCoord2i( 0, 1 );

glEnd();
glLoadIdentity();
SDL_GL_SwapBuffers();
}

In opengl, rotation happens about origin of the screen i.e(0,0). But we want rotation to happen about the centre of the 2D sprite. So instead of drawing the top left vertex at 0,0 you draw it at -imgWidth / 2, -imgHeight / 2, you draw the bottom right vertex at imgWidth / 2, imgHeight / 2, etc, etc. Our size of the quad is 128*128 as we are mapping the texture of size 128*128 to quad. So we’ll draw our quad as (-64,-64) to (64,64) so that (0,0) is directly at the center of the 2D sprite and when we rotate our sprite then rotation will happen about the center of the 2D sprite.


while( quit == false )
{
if( SDL_PollEvent( &event ) )
{
//If a key was pressed
if( event.type == SDL_KEYDOWN )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_LEFT:
LEFT=true;
break;
case SDLK_RIGHT:
RIGHT=true;
break;
case SDLK_ESCAPE:
quit=true;
break;
}
}
//If a key was released
else if( event.type == SDL_KEYUP )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_LEFT:
LEFT=false;
break;
case SDLK_RIGHT:
RIGHT=false;
break;
}
}
}

if(LEFT==true){
spin=spin+2;
if(spin>360.0)
spin=spin-360.0;
drawImage();
}
else if(RIGHT==true){
spin=spin-2;
if(spin>360.0)
spin=spin-360.0;
drawImage();
}

In while loop inside main function we are handling key event. As user presses left arrow key then we increment the angle and redraw the 2D sprite. I have used the same style as in previous posts i.e i have used two bool state variables(LEFT and RIGHT), when user presses left arrow key then LEFT becomes TRUE then angle is updated and 2D sprite is redrawn with rotation.

In this program, when left arrow key is pressed then sprite rotates towards east and when right arrow key is pressed then sprite rotates towards west.

 2D Sprite after rotation

2D Sprite after rotation

Here is the full source code

#include "SDL.h"
#include "SDL_image.h"
#include "SDL_opengl.h"

#include <stdio.h>

GLuint texture=NULL; //this is a handle to our texture object
GLenum texture_format=NULL;
GLint nofcolors;

SDL_Event event;

static GLfloat spin=0.0;
float x=100,y=100;
bool LEFT=false;
bool RIGHT=false;

int loadImage()
{
SDL_Surface *surface; // this surface will tell us the details of the image

if ( (surface = IMG_Load("flower.png")) ) {

// Check that the image's width is a power of 2
if ( (surface->w & (surface->w - 1)) != 0 ) {
printf("warning: image.bmp's width is not a power of 2\n");
}

// Also check if the height is a power of 2
if ( (surface->h & (surface->h - 1)) != 0 ) {
printf("warning: image.bmp's height is not a power of 2\n");
}

//get number of channels in the SDL surface
nofcolors=surface->format->BytesPerPixel;

//contains an alpha channel
if(nofcolors==4)
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGBA;
else
texture_format=GL_BGRA;
}
else if(nofcolors==3) //no alpha channel
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGB;
else
texture_format=GL_BGR;
}
else
{
printf("warning: the image is not truecolor...this will break ");
}

// Have OpenGL generate a texture object handle for us
glGenTextures( 1, &texture );

// Bind the texture object
glBindTexture( GL_TEXTURE_2D, texture );

// Set the texture's stretching properties
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

glTexImage2D( GL_TEXTURE_2D, 0, nofcolors, surface->w, surface->h, 0,
texture_format, GL_UNSIGNED_BYTE, surface->pixels );
}
else {
printf("SDL could not load image.bmp: %s\n", SDL_GetError());
SDL_Quit();
return 1;
}

// Free the SDL_Surface only if it was successfully created
if ( surface ) {
SDL_FreeSurface( surface );
}
}

void drawImage()
{
// Clear the screen before drawing
glClear( GL_COLOR_BUFFER_BIT );

glTranslatef(300.0,200.0,0.0);
glRotatef( spin, 0.0, 0.0, 1.0 );

// Bind the texture to which subsequent calls refer to
glBindTexture( GL_TEXTURE_2D, texture );

glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2i( 0, 0 );
glVertex3f( -64, -64, 0 );

// Bottom-left vertex (corner)
glTexCoord2i( 1, 0 );
glVertex3f( 64, -64, 0 );

// Bottom-right vertex (corner)
glTexCoord2i( 1, 1 );
glVertex3f( 64, 64, 0 );

// Top-right vertex (corner)
glTexCoord2i( 0, 1 );
glVertex3f( -64, 64, 0 );
glEnd();
glLoadIdentity();

SDL_GL_SwapBuffers();
}

int init()
{
SDL_Surface *screen;

// Slightly different SDL initialization
if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
printf("Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}

SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL|SDL_FULLSCREEN);
if ( !screen ) {
printf("Unable to set video mode: %s\n", SDL_GetError());
return 1;
}
}

void init_GL()
{
// Set the OpenGL state after creating the context with SDL_SetVideoMode

glClearColor( 0, 0, 0, 0 );

glEnable( GL_TEXTURE_2D ); // Need this to display a texture

glViewport( 0, 0, 640, 480 );

glMatrixMode( GL_PROJECTION );
glLoadIdentity();

glOrtho( 0, 640, 480, 0, -1, 1 );

glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}

void clean_up()
{
glDeleteTextures( 1, &texture );

SDL_Quit();
}

int main(int argc, char *argv[])
{
//Make sure the program waits for a quit
bool quit = false;

init();
init_GL();
loadImage();
drawImage();

while( quit == false )
{
if( SDL_PollEvent( &event ) )
{
//If a key was pressed
if( event.type == SDL_KEYDOWN )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_LEFT:
LEFT=true;
break;
case SDLK_RIGHT:
RIGHT=true;
break;
case SDLK_ESCAPE:
quit=true;
break;
}
}
//If a key was released
else if( event.type == SDL_KEYUP )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_LEFT:
LEFT=false;
break;
case SDLK_RIGHT:
RIGHT=false;
break;
}
}
}

if(LEFT==true){
spin=spin+2;
if(spin>360.0)
spin=spin-360.0;
drawImage();
}
else if(RIGHT==true){
spin=spin-2;
if(spin>360.0)
spin=spin-360.0;
drawImage();
}

}

clean_up();
return 0;
}

So Thats it. I hope this of any help to you and gives u some idea on rotation of 2D sprite using opengl and sdl.

Gracias.



Moving 2D Sprite: SO on my previous post i showed you the code to display a 2D sprite using OpenGl with SDL. Now i’ll show how to move a 2D Sprite using opengl with sdl. There will be some minor changes in the code and rest will be the same.

I’ll write the new changes in black and bold and rest are the same as in previous code on my previous post.

Here is the full code:


#include "SDL.h"

#include "SDL_image.h"

#include "SDL_opengl.h"

#include <stdio.h>

GLuint texture=NULL; //this is a handle to our texture object

GLenum texture_format=NULL;

GLint nofcolors;

SDL_Event event;

bool LEFT=false;

bool RIGHT=false;

float x=100.0,y=100.0;

int loadImage()

{

SDL_Surface *surface; // this surface will tell us the details of the image

if ( (surface = IMG_Load("flower.png")) ) {

// Check that the image's width is a power of 2

if ( (surface->w & (surface->w - 1)) != 0 ) {

printf("warning: image.bmp's width is not a power of 2\n");

}

// Also check if the height is a power of 2

if ( (surface->h & (surface->h - 1)) != 0 ) {

printf("warning: image.bmp's height is not a power of 2\n");

}

//get number of channels in the SDL surface

nofcolors=surface->format->BytesPerPixel;

//contains an alpha channel

if(nofcolors==4)

{

if(surface->format->Rmask==0x000000ff)

texture_format=GL_RGBA;

else

texture_format=GL_BGRA;

}

else if(nofcolors==3) //no alpha channel

{

if(surface->format->Rmask==0x000000ff)

texture_format=GL_RGB;

else

texture_format=GL_BGR;

}

else

{

printf("warning: the image is not truecolor...this will break ");

}

// Have OpenGL generate a texture object handle for us

glGenTextures( 1, &texture );

// Bind the texture object

glBindTexture( GL_TEXTURE_2D, texture );

// Set the texture's stretching properties

glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

glTexImage2D( GL_TEXTURE_2D, 0, nofcolors, surface->w, surface->h, 0,

texture_format, GL_UNSIGNED_BYTE, surface->pixels );

}

else {

printf("SDL could not load image.bmp: %s\n", SDL_GetError());

SDL_Quit();

return 1;

}

// Free the SDL_Surface only if it was successfully created

if ( surface ) {

SDL_FreeSurface( surface );

}

}

void drawImage()

{

// Clear the screen before drawing

glClear( GL_COLOR_BUFFER_BIT );

glTranslatef( x, y, 0 );

// Bind the texture to which subsequent calls refer to

glBindTexture( GL_TEXTURE_2D, texture );

glBegin( GL_QUADS );

// Top-left vertex (corner)

glTexCoord2i( 0, 0 );

glVertex3f( 100, 100, 0 );

// Bottom-left vertex (corner)

glTexCoord2i( 1, 0 );

glVertex3f( 228, 100, 0 );

// Bottom-right vertex (corner)

glTexCoord2i( 1, 1 );

glVertex3f( 228, 228, 0 );

// Top-right vertex (corner)

glTexCoord2i( 0, 1 );

glVertex3f( 100, 228, 0 );

glEnd();

glLoadIdentity();

SDL_GL_SwapBuffers();

}

int init()

{

SDL_Surface *screen;

// Slightly different SDL initialization

if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {

printf("Unable to initialize SDL: %s\n", SDL_GetError());

return 1;

}

SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL|SDL_FULLSCREEN);

if ( !screen ) {

printf("Unable to set video mode: %s\n", SDL_GetError());

return 1;

}

}

void init_GL()

{

// Set the OpenGL state after creating the context with SDL_SetVideoMode

glClearColor( 0, 0, 0, 0 );

glEnable( GL_TEXTURE_2D ); // Need this to display a texture

glViewport( 0, 0, 640, 480 );

glMatrixMode( GL_PROJECTION );

glLoadIdentity();

glOrtho( 0, 640, 480, 0, -1, 1 );

glMatrixMode( GL_MODELVIEW );

glLoadIdentity();

}

void clean_up()

{

glDeleteTextures( 1, &texture );

SDL_Quit();

}

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

{

//Make sure the program waits for a quit

bool quit = false;

init();

init_GL();

loadImage();

drawImage();

while( quit == false )

{

if( SDL_PollEvent( &event ) )

{

//If a key was pressed

if( event.type == SDL_KEYDOWN )

{

switch( event.key.keysym.sym )

{

case SDLK_LEFT:

LEFT=true;

break;

case SDLK_RIGHT:

RIGHT=true;

break;

case SDLK_ESCAPE:

quit=true;

break;

}

}

//If a key was released

else if( event.type == SDL_KEYUP )

{

switch( event.key.keysym.sym )

{

case SDLK_LEFT:

LEFT=false;

break;

case SDLK_RIGHT:

RIGHT=false;

break;

}

}

}

if(LEFT==true){

x-=2;

drawImage();

}

else if(RIGHT==true){

x+=2;

drawImage();

}

}

clean_up();

return 0;

}

In above code i have used two bool variable(LEFT and RIGHT) and two float variables(x and y) to store the position of  sprite. In the main function inside the loop we are taking the key input from the user. So when the user press left arrow key “LEFT bool variable is assigned TRUE” and when user releases the left arrow key ” LEFT bool variable is assigned FALSE”. Same applies for pressing right arrow key. So in this code :

if(LEFT==true){

x-=2;

drawImage();

}

else if(RIGHT==true){

x+=2;

drawImage();

}

when left arrow key is pressed “LEFT bool variable becomes TRUE” and x position of sprite is incremented by 2. Then we draw the sprite again. And when left arrow key is released “LEFT bool variable becomes FALSE” which means x position of sprite should not be updated. Same concept applies for moving right.

Now we have code to update the x and y position of  sprite. But how to render the sprite with updated x and y coordinates. This is done by gTranslatef(x,y,z) function. It translates the position of sprite. So we’ll be updating x and y to move the sprite, and z will be zero. So in this code:

void drawImage()

{

// Clear the screen before drawing

glClear( GL_COLOR_BUFFER_BIT );

glTranslatef( x, y, 0 );

// Bind the texture to which subsequent calls refer to

glBindTexture( GL_TEXTURE_2D, texture );

glBegin( GL_QUADS );

// Top-left vertex (corner)

glTexCoord2i( 0, 0 );

glVertex3f( 100, 100, 0 );

// Bottom-left vertex (corner)

glTexCoord2i( 1, 0 );

glVertex3f( 228, 100, 0 );

// Bottom-right vertex (corner)

glTexCoord2i( 1, 1 );

glVertex3f( 228, 228, 0 );

// Top-right vertex (corner)

glTexCoord2i( 0, 1 );

glVertex3f( 100, 228, 0 );

glEnd();

glLoadIdentity();

SDL_GL_SwapBuffers();

}

when we update the position of x and y then we call the above function where we have included new code glTranslatef(x,y,z) which will make the sprite to be drawn in given x.y and z location.

So thats it. I hope this will give u some pretty basic idea. Now you can write your own code for moving 2d Sprite.

Gracias.


In many forums, i have seen people asking about making 2D games using OpenGl and there weren’t any satisfactory answers. So i searched the google on doing 2D graphics using Opengl. Surprisingly there were not many results on that, there were very very few info on doing 2D graphics using OpenGl.

So i did some research on this and came up with this code. I hope this will be of some use to those who wants to get started making 2D games using OpenGl. I don’t claim that this code is efficient way to do it. I am still learning OpenGl. But this code will give you a base to start off.

Here i’ll be using SDL with OpenGL. I’l be using SDL for creating the window, taking input, and loading texture data. And I’ll be using SDL_image extension library to load images(BMP, PNM, XPM, LBM, PCX, GIF, JPEG, TGA and PNG files.). Lastly, Opengl wiil be used for rendering the graphics.

If you don’t know how to set up libraries then here is the guide to set up SDL, guide to setup SDL_image extension library and guide to set up OpenGl.

This code has been tested on windows using visual studio 2005.

So lets start:

#include "SDL.h"
#include "SDL_image.h"
#include "SDL_opengl.h"

#include <stdio.h>

First we will include the necessary header files.


GLuint texture=NULL; //this is a handle to our texture object
GLenum texture_format=NULL;
GLint nofcolors;

SDL_Event event;

texture is the handle to our texture object. texture_format will store the information about the image loaded. A SDL_Event structure stores event data for us to handle.


int loadImage()
{
SDL_Surface *surface; // this surface will tell us the details of the image

if ( (surface = IMG_Load("flower.png")) ) {

// Check that the image's width is a power of 2
if ( (surface->w & (surface->w - 1)) != 0 ) {
printf("warning: image.bmp's width is not a power of 2\n");
}

// Also check if the height is a power of 2
if ( (surface->h & (surface->h - 1)) != 0 ) {
printf("warning: image.bmp's height is not a power of 2\n");
}

//get number of channels in the SDL surface
nofcolors=surface->format->BytesPerPixel;

//contains an alpha channel
if(nofcolors==4)
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGBA;
else
texture_format=GL_BGRA;
}
else if(nofcolors==3) //no alpha channel
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGB;
else
texture_format=GL_BGR;
}
else
{
printf("warning: the image is not truecolor...this will break ");
}

// Have OpenGL generate a texture object handle for us
glGenTextures( 1, &texture );

// Bind the texture object
glBindTexture( GL_TEXTURE_2D, texture );

// Set the texture's stretching properties
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

glTexImage2D( GL_TEXTURE_2D, 0, nofcolors, surface->w, surface->h, 0,
texture_format, GL_UNSIGNED_BYTE, surface->pixels );
}
else {
printf("SDL could not load image.bmp: %s\n", SDL_GetError());
SDL_Quit();
return 1;
}

// Free the SDL_Surface only if it was successfully created
if ( surface ) {
SDL_FreeSurface( surface );
}
}

This is the loadImage() function to load the image. First we’ll use Img_Load() function to load an image. Then we’ll check whether the height and width of an image is power of 2. If its not a power of 2 then program will terminate. Then we’ll check the information of image i.e if image contains alpha channel or not. So according to that we’ll use our texture_format. Lastly we’l map the image to the texture object. glBindTexture(GL_TEXTURE_2D, &texture) tells OpenGL to bind the named texture texture to a texture target. The main function of glBindTexture is to assign a texture name to texture data. In this case we’re telling OpenGL there is memory available at &texture. When we create the texture, it will be stored in the memory that &texture references.


void drawImage()
{

// Clear the screen before drawing
glClear( GL_COLOR_BUFFER_BIT );

// Bind the texture to which subsequent calls refer to
glBindTexture( GL_TEXTURE_2D, texture );

glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2i( 0, 0 );
glVertex3f( 100, 100, 0 );

// Bottom-left vertex (corner)
glTexCoord2i( 1, 0 );
glVertex3f( 228, 100, 0 );

// Bottom-right vertex (corner)
glTexCoord2i( 1, 1 );
glVertex3f( 228, 228, 0 );

// Top-right vertex (corner)
glTexCoord2i( 0, 1 );
glVertex3f( 100, 228, 0 );
glEnd();
glLoadIdentity();
SDL_GL_SwapBuffers();
}

This is the drawImage() function. As name suggest this will render our 2D sprite. There is nothing to explain here. We are creating a quad and mapping our texture to the quad and rendering that quad.

To properly map a texture onto a quad, you have to make sure the top right of the texture is mapped to the top right of the quad. The top left of the texture is mapped to the top left of the quad, the bottom right of the texture is mapped to the bottom right of the quad, and finally, the bottom left of the texture is mapped to the bottom left of the quad. If the corners of the texture do not match the same corners of the quad, the image may appear upside down, sideways, or not at all.

The first value of glTexCoord2i is the X coordinate. 0 is the left side of the texture  and 1 is the right side of the texture. The second value of glTexCoord2f is the Y coordinate 0 is the bottom of the texture and 1 is the top of the texture.


int init()
{
SDL_Surface *screen;

// Slightly different SDL initialization
if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
printf("Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}

SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL);
if ( !screen ) {
printf("Unable to set video mode: %s\n", SDL_GetError());
return 1;
}
}

This is a  init() function to set up the window.We create our OpenGL window. When we want to use OpenGL we pass the SDL_OPENGL flag to SDL_SetVideoMode() instead of SDL_SWSURFACE. Now the window will use OpenGL’s hardware accelerated rendering instead of SDL’s software rendering.


void init_GL()
{
// Set the OpenGL state after creating the context with SDL_SetVideoMode

glClearColor( 0, 0, 0, 0 );

glEnable( GL_TEXTURE_2D ); // Need this to display a texture

glViewport( 0, 0, 640, 480 );

glMatrixMode( GL_PROJECTION );
glLoadIdentity();

glOrtho( 0, 640, 480, 0, -1, 1 );

glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}

This function will set up out Opengl world. The first thing we do is set the clear color.When we clear the screen, we want it to be black. So we set the clear color to be black (R, G, B, A) with glClearColor(). Then we set the matrix mode to projection using glMatrixMode(). Then we intialize the projection matrix by calling glLoadIdentity(). glLoadIdentity() essentially resets the matrix by setting it to be the identity matrix.We are using Orthographic projection for projecting two-dimensional image onto a two-dimensional screen. Above code glOrtho( 0, 640, 480, 0, -1, 1 ); will create two-dimensional screen with top left(0,0) and bottom right(640,480).

void clean_up()
{
glDeleteTextures( 1, &texture );

SDL_Quit();
}

The above function will clean up the resource and then terminate the window.

int main(int argc, char *argv[])
{
//Make sure the program waits for a quit
bool quit = false;

init();
init_GL();
loadImage();
drawImage();

while( quit == false )
{
if( SDL_PollEvent( &event ) )
{
//If a key was pressed
if( event.type == SDL_KEYDOWN )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_ESCAPE:
quit=true;
break;
}
}

}
}

clean_up();
return 0;
}

This is the main function. We’ll be calling all the function i.e setting up window and OpenGl; loading Sprite and rendering it.

So thats it. Now your are off.

program

displaying 2D sprite(PNG) using OpenGl with SDL

You can save this image(flower.png) for testing.

flower

So here is the full code:


#include "SDL.h"
#include "SDL_image.h"
#include "SDL_opengl.h"

#include <stdio.h>

GLuint texture=NULL; //this is a handle to our texture object
GLenum texture_format=NULL;
GLint nofcolors;

SDL_Event event;

int loadImage()
{
SDL_Surface *surface; // this surface will tell us the details of the image

if ( (surface = IMG_Load("flower.png")) ) {

// Check that the image's width is a power of 2
if ( (surface->w & (surface->w - 1)) != 0 ) {
printf("warning: image.bmp's width is not a power of 2\n");
}

// Also check if the height is a power of 2
if ( (surface->h & (surface->h - 1)) != 0 ) {
printf("warning: image.bmp's height is not a power of 2\n");
}

//get number of channels in the SDL surface
nofcolors=surface->format->BytesPerPixel;

//contains an alpha channel
if(nofcolors==4)
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGBA;
else
texture_format=GL_BGRA;
}
else if(nofcolors==3) //no alpha channel
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGB;
else
texture_format=GL_BGR;
}
else
{
printf("warning: the image is not truecolor...this will break ");
}

// Have OpenGL generate a texture object handle for us
glGenTextures( 1, &texture );

// Bind the texture object
glBindTexture( GL_TEXTURE_2D, texture );

// Set the texture's stretching properties
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

glTexImage2D( GL_TEXTURE_2D, 0, nofcolors, surface->w, surface->h, 0,
texture_format, GL_UNSIGNED_BYTE, surface->pixels );
}
else {
printf("SDL could not load image.bmp: %s\n", SDL_GetError());
SDL_Quit();
return 1;
}

// Free the SDL_Surface only if it was successfully created
if ( surface ) {
SDL_FreeSurface( surface );
}
}

void drawImage()
{

// Clear the screen before drawing
glClear( GL_COLOR_BUFFER_BIT );

// Bind the texture to which subsequent calls refer to
glBindTexture( GL_TEXTURE_2D, texture );

glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2i( 0, 0 );
glVertex3f( 100, 100, 0 );

// Bottom-left vertex (corner)
glTexCoord2i( 1, 0 );
glVertex3f( 228, 100, 0 );

// Bottom-right vertex (corner)
glTexCoord2i( 1, 1 );
glVertex3f( 228, 228, 0 );

// Top-right vertex (corner)
glTexCoord2i( 0, 1 );
glVertex3f( 100, 228, 0 );
glEnd();
glLoadIdentity();
SDL_GL_SwapBuffers();
}

int init()
{
SDL_Surface *screen;

// Slightly different SDL initialization
if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
printf("Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}

SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL);
if ( !screen ) {
printf("Unable to set video mode: %s\n", SDL_GetError());
return 1;
}
}

void init_GL()
{
// Set the OpenGL state after creating the context with SDL_SetVideoMode

glClearColor( 0, 0, 0, 0 );

glEnable( GL_TEXTURE_2D ); // Need this to display a texture

glViewport( 0, 0, 640, 480 );

glMatrixMode( GL_PROJECTION );
glLoadIdentity();

glOrtho( 0, 640, 480, 0, -1, 1 );

glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}

void clean_up()
{
glDeleteTextures( 1, &texture );

SDL_Quit();
}

int main(int argc, char *argv[])
{
//Make sure the program waits for a quit
bool quit = false;

init();
init_GL();
loadImage();
drawImage();

while( quit == false )
{
if( SDL_PollEvent( &event ) )
{
//If a key was pressed
if( event.type == SDL_KEYDOWN )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_ESCAPE:
quit=true;
break;
}
}

}
}

clean_up();
return 0;
}

So i hope this will give u a base to start off. On the next post i’l tell you how to move the 2d Sprite in the screen. I’ll show u how to handle the key events in my next post.

Gracias.