Sign in to follow this  
corntown

Sprite's background

Recommended Posts

corntown    122
Hey everyone,Im new to game programming and i've been trying to create a 2d game. In my game there's a character but when I put it on the screen it comes with a background.. is there any way for me to create a sprite with no background? btw Im programming with c++(directx 9) thx

Share this post


Link to post
Share on other sites
Crypter    748
You can use transparency to not render the background.

As long as the background color is a single color, simply
render each pixel, and skip each pixel with the color of
the sprites background. Doing this, the background will not
be rendered.

Alot of APIs provide routined to do this. What API are you using?

*edit: I apologize, didnt realize you are using DX 9

Share this post


Link to post
Share on other sites
Ezbez    1164
Sure are.

We'll tell you more, if you tell us more. How you do this depends largely on what you're using to draw them.

Share this post


Link to post
Share on other sites
corntown    122
here's my code:



// Include the Windows header file that’s needed for all Windows applications
#include <windows.h>
#include <d3d9.h>
#include <d3dx9.h>
#include <iostream>
using namespace std;

#define letterW 65
#define letterH 61


typedef struct sprite_struct
{
//size
RECT size;

//location
long x;
long y;

//movement
float moveX;
float moveY;

//animations
int numframes;
int curframe;


} sprite;



HINSTANCE hInst; // global handle to hold the application instance
HWND wndHandle; // global variable to hold the window handle
// forward declarations

LPDIRECT3D9 pD3D; // the Direct3D object
LPDIRECT3DDEVICE9 pd3dDevice; // the Direct3D device

IDirect3DSurface9* surface; //personal surface pointer
IDirect3DSurface9* character_sur;

LARGE_INTEGER timeStart; // holds the starting count
LARGE_INTEGER timeEnd; // holds the ending count
LARGE_INTEGER timerFreq; // holds the frequency of the counter

float anim_rate;
RECT src,des;
RECT src2,des2;
sprite character;





//-------------------------------------------------
bool initWindow( HINSTANCE hInstance );
LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM );

bool initDirect3D(void);
void render(void);
void cleanUp (void);

IDirect3DSurface9* getSurfaceFromBitmap(std::string filename);
void init_background();
void init_character();

//-------------------------------------------------




// This is winmain, the main entry point for Windows applications
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow )
{



// Initialize the window
if ( !initWindow( hInstance ) )
return false;

if ( !initDirect3D( ) )
return false;


surface=getSurfaceFromBitmap("test.bmp");
character_sur=getSurfaceFromBitmap("char5.bmp");


if ((surface==NULL)||(character_sur==NULL))
return false;


//init_background();
init_character();







QueryPerformanceFrequency(&timerFreq);



// main message loop:
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );

while( msg.message!=WM_QUIT )
{
if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
{
TranslateMessage ( &msg );
DispatchMessage ( &msg );
}
else
{


QueryPerformanceCounter(&timeStart);

render( );
QueryPerformanceCounter(&timeEnd);
anim_rate =((float)timeEnd.QuadPart - (float)timeStart.QuadPart ) /timerFreq.QuadPart;


}
}
cleanUp ();
return (int) msg.wParam;

}



/******************************************************************************
* bool initWindow( HINSTANCE hInstance )
* initWindow registers the window class for the application, creates the window
******************************************************************************/

bool initWindow( HINSTANCE hInstance )
{
WNDCLASSEX wcex;
// Fill in the WNDCLASSEX structure. This describes how the window
// will look to the system
wcex.cbSize = sizeof(WNDCLASSEX); // the size of the structure
wcex.style = CS_HREDRAW | CS_VREDRAW; // the class style
wcex.lpfnWndProc = (WNDPROC)WndProc; // the window procedure callback
wcex.cbClsExtra = 0; // extra bytes to allocate for this class
wcex.cbWndExtra = 0; // extra bytes to allocate for this instance
wcex.hInstance = hInstance; // handle to the application instance
wcex.hIcon = 0; // icon to associate with the application
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);// the default cursor
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); // the background color
wcex.lpszMenuName = NULL; // the resource name for the menu
wcex.lpszClassName = "DirectXExample"; // the class name being created
wcex.hIconSm = 0; // the handle to the small icon
RegisterClassEx(&wcex);


// Create the window
wndHandle = CreateWindow(
"DirectXExample",
"DirectXExample",
WS_EX_TOPMOST | WS_POPUP | WS_VISIBLE,
// the window class to use
// the title bar text
// the window style
CW_USEDEFAULT, // the starting x coordinate
CW_USEDEFAULT, // the starting y coordinate
640, // the pixel width of the window
480, // the pixel height of the window
NULL, // the parent window; NULL for desktop
NULL, // the menu for the application; NULL for
// none
hInstance, // the handle to the application instance
NULL); // no values passed to the window
// Make sure that the window handle that is created is valid

if (!wndHandle)
return false;

// Display the window on the screen
ShowWindow(wndHandle, SW_SHOW);
UpdateWindow(wndHandle);
return true;
}


/******************************************************************************
* LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam,
* LPARAM lParam)
* The window procedure
******************************************************************************/

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
// Check any available messages from the queue
switch (message)
{
case WM_DESTROY:
{
MessageBox(NULL,"Window has ended","End",MB_OK);
PostQuitMessage(0);
}
break;

case WM_KEYDOWN:
{
switch( wParam )
{
case VK_ESCAPE:
PostQuitMessage(0);
break;
}


}
break;

}

return DefWindowProc(hWnd, message, wParam, lParam);
}

/*********************************************************************
* initDirect3D
*********************************************************************/

bool initDirect3D(void)
{
pD3D = NULL;
pd3dDevice = NULL;


if( NULL == ( pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
{
return false;
}




D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof( d3dpp ) );
d3dpp.Windowed = FALSE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
d3dpp.BackBufferCount = 1;
d3dpp.BackBufferHeight = 480;
d3dpp.BackBufferWidth = 640;
d3dpp.hDeviceWindow = wndHandle;



if( FAILED( pD3D->CreateDevice( D3DADAPTER_DEFAULT,D3DDEVTYPE_REF,wndHandle,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,&d3dpp,&pd3dDevice ) ) )
{
return false;
}
return true;
}

void render(void)
{

static counter=0;
IDirect3DSurface9* backbuffer = NULL;
if( NULL == pd3dDevice )
return;








pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET,
D3DCOLOR_XRGB( 0,50,100 ), 1.0f, 0 );

pd3dDevice->GetBackBuffer( 0,0,D3DBACKBUFFER_TYPE_MONO,&backbuffer );

pd3dDevice->StretchRect(character_sur,&src2,backbuffer,&des2,D3DTEXF_NONE);
// pd3dDevice->StretchRect(surface,&src,backbuffer,&des,D3DTEXF_NONE);//background niceling






// Present the back buffer contents to the display
pd3dDevice->Present( NULL, NULL, NULL, NULL );




}


void cleanUp (void)
{
// Release the device and the Direct3D object
if( pd3dDevice != NULL )
pd3dDevice->Release( );
if( pD3D != NULL )
pD3D->Release( );
}



/**********************************************************
* getSurfaceFromBitmap
**********************************************************/

IDirect3DSurface9* getSurfaceFromBitmap(std::string filename)
{
HRESULT hResult;
IDirect3DSurface9* surface = NULL;
D3DXIMAGE_INFO imageInfo; // holds details concerning this bitmap

// Get the width and height info from this bitmap
hResult = D3DXGetImageInfoFromFile(filename.c_str(), &imageInfo);
// Make sure that the call to D3DXGetImageInfoFromFile succeeded
if FAILED (hResult)
return NULL;

// Create the offscreen surface that will hold the bitmap
hResult = pd3dDevice->CreateOffscreenPlainSurface( 640,
480,
D3DFMT_X8R8G8B8,
D3DPOOL_DEFAULT,
&surface,
NULL );

// Make sure that this function call did not fail; if it did,
// exit this function
if ( FAILED( hResult ) )
return NULL;

// Load the bitmap into the surface that was created earlier
hResult = D3DXLoadSurfaceFromFile( surface,
NULL,
NULL,
filename.c_str( ),
NULL,
D3DX_DEFAULT,
0,
NULL );
if ( FAILED( hResult ) )
return NULL;
return surface;
}


void init_background()
{
src.top=50;
src.left=140;
src.bottom=250;
src.right=520;

des.top=50;
des.left=140;
des.bottom=250;
des.right=520;
}



void init_character()
{
//size
src2.top=87;
src2.left=9;
src2.bottom=165;
src2.right=39;

//location
character.x=0;
character.y=0;

//dest
des2.top=character.y;
des2.left=character.x;
des2.bottom=character.y+(src2.bottom-src2.top)-0;
des2.right=character.x+(src2.right-src2.left)-0;





}




The character's background is black :)

Share this post


Link to post
Share on other sites
corntown    122
Quote:
Original post by Crypter
You can use transparency to not render the background.

As long as the background color is a single color, simply
render each pixel, and skip each pixel with the color of
the sprites background. Doing this, the background will not
be rendered.

Alot of APIs provide routined to do this. What API are you using?


can you tell me how do I tell my device not to render black pixels please? and isn't this problematic if what Im trying to render consists of black pixels?

Share this post


Link to post
Share on other sites
Crypter    748
Quote:

can you tell me how do I tell my device not to render black pixels please? and isn't this problematic if what Im trying to render consists of black pixels?

Pick a color that you will never use as the background color.

I can show you how to do it in DirectDraw, but I dont know Direct3D.
If I find any resources/tutorial for Direct3D, Ill post it[smile]

Share this post


Link to post
Share on other sites
speedie    140
what art program are you using, lots of them support alpha channels letting you to leave the background blank (i.e. no color), then you'd just have to save the image as a PNG or a TARGA format.

Share this post


Link to post
Share on other sites
corntown    122
Quote:
Original post by speedie
what art program are you using, lots of them support alpha channels letting you to leave the background blank (i.e. no color), then you'd just have to save the image as a PNG or a TARGA format.



Adobe photoshop and photoimpact
but I couldn't manage to make a picture without a background.. it always leaves me with a white background .


**I understand I need to save my sprite somehow as .png file which supports alpha channels and then tell me device not to render it somehow.. can anyone tell me how? I searched google and I only found methods which use vertex buffers but I think there's another way.

[Edited by - corntown on May 6, 2007 3:37:07 AM]

Share this post


Link to post
Share on other sites
Sc4Freak    643
Keep in mind that .png alpha channels are broken on many versions of Photoshop. I don't know if they've fixed it yet on the newest versions.

Share this post


Link to post
Share on other sites
speedie    140
Quote:
Original post by Sc4Freak
Keep in mind that .png alpha channels are broken on many versions of Photoshop. I don't know if they've fixed it yet on the newest versions.


true, same with TARGA. but updateing the correct plugins can solve it.

but what version of photoshop are you using? if version 7 uses TGA's and if version CS2 use PNG (TARGA plugin removed the ability to save as transparent, so you have to update the plugins)

To get the background to be transparent in photo shop :: When you make a new image, it asks you what demensions you want it, it also asks what color you want the background, set it to transparent.

as for color keying, heres a few snipets from my engine that uses the color RGB(255, 0, 255) as the color key to set as transparent. It's bright pink, a color that is rarely ever used in games.


D3DXCreateTextureFromFileEx(
(*m_d3ddev),
filename.c_str(),
info.Width,
info.Height,
1,
D3DPOOL_DEFAULT,
D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,
D3DX_DEFAULT,
D3DX_DEFAULT,
D3DCOLOR_XRGB(255,0,255), // color key
&info,
NULL,
&texture.texture);



Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this