Skip to main content
GameDev.net gamedev.net
🔒 Locked

2D Sprite Animation Speed Problem

Started by Gor435 Jan 17, 2010 at 2:28 AM 0 replies 2k views
Original Post
Gor435
Gor435
So I am working on a 2D game. I thought it would be a good idea to learn some DirectX and use it in my new game which is going to be a bit more complicated than what I have done in the past. Only problem is that I have had nothing but issues. I am trying to learn DirectX from reading Beginning DirectX 10 Game Programming. So either I am dumb or this book is jacked up (FYI: some of the code does not match in the book and on the CD and I have found that some things have been left out at times). Could be both but it does not matter at this time. Now to the point. My animation speed is really slow. I have checked everything and I cannot figure out why. I even pulled up the example from the CD and it runs like crazy fast. I have compared the code and still do not see anything that looks off. Only real differences between my code and the example is that I have my graphics in a class and I am only using one sprite where the example uses many. Now this may be a bad idea, with the graphics code in a class, but I would not think it would affect the speed in this way. I am pretty sure I was able to do this with OpenGL without problems. So if you have read this far and think you can help then below is my poor code. Just so you know I have tried a lot of things trying to figure out what was causing the speed issue. Oh and ignore the code to slow down the animation it is disabled by "frameDuration = 0.0;" so keep in mind I am not doing anything to slow the animation down.

// !?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?
//  Test                                                                                       
//  File: main.cpp                                                                                     
//  Created by Gor435                                                                                  
//  Description: Where it all begins     
// !?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?!?

#include "main.h"

//going to leave this all global
HINSTANCE hInst;
HWND wndHandle = NULL;

LARGE_INTEGER timeStart;
LARGE_INTEGER timeEnd;
LARGE_INTEGER timerFreq;
float anim_rate;

//create the game object
Game * pMage = new Game;

//This is pulling info from the settings file (test should be replaced with a file name at a later time.)
g_Settings Settings = pMage->GetGameSettings("test");

bool InitWindow(HINSTANCE hInstance, int width, int height);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);


int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
	if(!InitWindow(hInstance, Settings.Width, Settings.Height))
	{
		MessageBox (NULL, TEXT ("Could not initialize window"), TEXT ("Error"), MB_ICONERROR) ;
		return false;
	}

	//Game * pMage = new Game(wndHandle);

	if(!pMage->InitGame(Settings.Width, Settings.Height, &wndHandle))
	{
		MessageBox (NULL, TEXT ("Could not Initialize the game object"), TEXT ("Error"), MB_ICONERROR) ;
		return false;
	}

	MSG msg = {0};

	while (WM_QUIT != msg.message)
	{
		if(PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
		
			//game code here
			pMage->Drawframe();

		}
		
	}

	delete pMage;

	return(int) msg.wParam;
}

bool InitWindow(HINSTANCE hInstance, int width, int height)
{
	WNDCLASSEX Magegame;

Magegame.cbSize = sizeof(WNDCLASSEX);
Magegame.style = CS_HREDRAW | CS_VREDRAW;
Magegame.lpfnWndProc = (WNDPROC)WndProc;
Magegame.cbClsExtra = 0;
Magegame.cbWndExtra = 0;
Magegame.hInstance = hInstance;
Magegame.hIcon = 0;
Magegame.hCursor = LoadCursor(NULL, IDC_ARROW);
Magegame.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
Magegame.lpszMenuName = NULL;
Magegame.lpszClassName = TEXT("Test");
Magegame.hIconSm = 0;
RegisterClassEx(&Magegame);

RECT rect = { 0, 0, width, height };
AdjustWindowRect(▭, WS_OVERLAPPEDWINDOW, FALSE);

wndHandle = CreateWindow(TEXT("Test"),
						 TEXT("Test"),
						 WS_OVERLAPPEDWINDOW,
						 CW_USEDEFAULT,
						 CW_USEDEFAULT,
						 rect.right - rect.left,
						 rect.bottom - rect.top,
						 NULL,
						 NULL,
						 hInstance,
						 NULL);

	if(!wndHandle)
	{
		MessageBox (NULL, TEXT ("Could not create window"), TEXT ("Error"), MB_ICONERROR) ;
		return false;
	}

	ShowWindow(wndHandle, SW_SHOW);
	UpdateWindow(wndHandle);


return true;

}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch(message)
	{
		case WM_KEYDOWN:
			switch(wParam)
			{
				case VK_ESCAPE:
					PostQuitMessage(0);
					break;
			}
			break;

		case WM_DESTROY:
			PostQuitMessage(0);
			break;
	}

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

Game::Game()
{
	
	m_Graphics = new Graphics;

	m_Graphics->GetGraphicsSettings("test");

	anim_rate = 0;

}
Game::~Game()
{

	if(m_Graphics)
	{
		delete m_Graphics;
	}

}
bool Game::InitGame(int width, int height, HWND * window)
{

	m_Graphics->InitGraphics(width, height, window);
	m_Graphics->PrepareSprite( TEXT ("images\\testsprites.png"));

	return true;

}

void Game::Drawframe()
{
	QueryPerformanceCounter(&timeStart);

	m_Graphics->UpdateScene();
	m_Graphics->Drawframe();
	m_Graphics->UpdateSprites(anim_rate);

	QueryPerformanceCounter(&timeEnd);
			
	QueryPerformanceFrequency(&timerFreq);

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

}

g_Settings Game::GetGameSettings(std::string file)
{

	m_Settings.Width = 640;
	m_Settings.Height = 480;
	m_Settings.Fullscreen = false;

	return m_Settings;

}

Graphics::Graphics()
{

	//g_Settings Settings = pMage->GetGraphicsSettings("test");

	//m_Graphicsstate = LOADING;
	//m_SubState = LEVEL;

	m_Level = 0;
	m_Width = 100;
	m_Height = 150;
	m_PosX = 220;
	m_PosY = 20;
	m_MoveX = 0;
	m_MoveY = 0;
	m_Visible = true;
	m_CurFrame = 0;
	m_NumFrames = 3;

	anim_rate = 0;

	lastElapsedFrame = 0;
	frameDuration = 0.0;

	pD3DDevice = NULL;
	pSwapChain = NULL;
	pRenderTargetView = NULL;
	pTextureResource = NULL;
	pText2D = NULL;
	pSpriteTextureRV = NULL;
	pSpriteObject = NULL;
	pBlendState10 = NULL;
	pOrigBlend = NULL;
	m_CurrentSprites = 1;
	m_CurrentIndex = 0;
	m_Settings = new gr_Settings;
	m_Spriteinfo = new D3DX10_SPRITE;
	GetGraphicsSettings("test");

		m_Spriteinfo->pTexture = pSpriteTextureRV;
		m_Spriteinfo->TextureIndex = 0;

		m_Spriteinfo->TexCoord.x = 0;
		m_Spriteinfo->TexCoord.y = 0;

		m_Spriteinfo->TexSize.x = 0.5f;
		m_Spriteinfo->TexSize.y = 1.0f;

		m_Spriteinfo->ColorModulate = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);

}
Graphics::~Graphics()
{

	//release the rendertarget
	if(pRenderTargetView)
	{
		pRenderTargetView->Release();
		pRenderTargetView = NULL;
	}

	//release the swapchain
	if(pSwapChain)
	{
		pSwapChain->Release();
		pSwapChain = NULL;
	}

	if(pD3DDevice)
	{
		pD3DDevice->Release();
		pD3DDevice = NULL;
	}

	if(pText2D)
	{
		pText2D->Release();
		pText2D = NULL;
	}

		if(pSpriteTextureRV)
	{
		pSpriteTextureRV->Release();
		pSpriteTextureRV = NULL;
	}

	if(pSpriteObject)
	{
		pSpriteObject->Release();
		pSpriteObject = NULL;
	}

	delete m_Settings;
	delete m_Spriteinfo;
	
}
bool Graphics::InitGraphics(int width, int height, HWND * window)
{

	DXGI_SWAP_CHAIN_DESC swapChainDesc;
	ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

	swapChainDesc.BufferCount = 1;
	swapChainDesc.BufferDesc.Width = width;
	swapChainDesc.BufferDesc.Height = height;
	swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
	swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
	swapChainDesc.SampleDesc.Count = 1;
	swapChainDesc.SampleDesc.Quality = 0;
	swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	swapChainDesc.OutputWindow = *window;
	swapChainDesc.Windowed = TRUE;


	HRESULT hr = D3D10CreateDeviceAndSwapChain(NULL,	D3D10_DRIVER_TYPE_REFERENCE, NULL,	0,	D3D10_SDK_VERSION, &swapChainDesc,	&pSwapChain, &pD3DDevice);

	if(hr != S_OK)
	{
		MessageBox (NULL, TEXT ("Could not create the Direct3D device and/or Swap Chain"), TEXT ("Error"), MB_ICONERROR) ;
		return false;
	}

	//get the back buffer from the swapchain
	ID3D10Texture2D * pBackBuffer;
	hr = pSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)
		&pBackBuffer);

	if (hr != S_OK)
	{
		MessageBox (NULL, TEXT ("Getting the back buffer Failed"), TEXT ("Error"), MB_ICONERROR) ;
		return false;
	}

	//create the render target view
	hr = pD3DDevice->CreateRenderTargetView(pBackBuffer, NULL, &pRenderTargetView);

	//release the back buffer
	pBackBuffer->Release();

	//make sure the render target vew was created successfully
	if(hr != S_OK)
	{
		MessageBox (NULL, TEXT ("No render target available"), TEXT ("Error"), MB_ICONERROR) ;
		return false;
	}

	//set the render target
	pD3DDevice->OMSetRenderTargets(1, &pRenderTargetView, NULL);

	//create and set the viewport
	viewPort.Width = width;
	viewPort.Height = height;
	viewPort.MinDepth = 0.0f;
	viewPort.MaxDepth = 1.0f;
	viewPort.TopLeftX = 0;
	viewPort.TopLeftY = 0;
	pD3DDevice->RSSetViewports(1, &viewPort);

	//create the projection matrix
	D3DXMatrixOrthoOffCenterLH(&matProjection, (float)viewPort.TopLeftX, (float)viewPort.Width, (float)viewPort.TopLeftY, (float)viewPort.Height, 0.1f, 10);

	ZeroMemory(&StateDesc, sizeof(D3D10_BLEND_DESC));
	StateDesc.AlphaToCoverageEnable = FALSE;
	StateDesc.BlendEnable[0] = TRUE;
	StateDesc.SrcBlend = D3D10_BLEND_SRC_ALPHA;
	StateDesc.DestBlend = D3D10_BLEND_INV_SRC_ALPHA;
	StateDesc.BlendOp = D3D10_BLEND_OP_ADD;
	StateDesc.SrcBlendAlpha = D3D10_BLEND_ZERO;
	StateDesc.DestBlendAlpha = D3D10_BLEND_ZERO;
	StateDesc.BlendOpAlpha = D3D10_BLEND_OP_ADD;
	StateDesc.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL;

	pD3DDevice->CreateBlendState(&StateDesc, &pBlendState10);

	hr = D3DX10CreateSprite(pD3DDevice, 0, &pSpriteObject);

	if(hr != S_OK)
	{
		MessageBox (NULL, TEXT ("Could not create sprites"), TEXT ("Error"), MB_ICONERROR) ;
		return false;
	}

	pSpriteObject->SetProjectionTransform(&matProjection);

	hr = pSpriteObject->SetProjectionTransform(&matProjection);

	if(hr != S_OK)
	{
		MessageBox (NULL, TEXT ("WTF"), TEXT ("Error"), MB_ICONERROR) ;
		return false;
	}

	return true;
}

void Graphics::Drawframe()
{

	if(pD3DDevice != NULL)
	{
		//clear the target buffer
		pD3DDevice->ClearRenderTargetView(pRenderTargetView, D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.0f));

		//DrawBackground(TEXT("images\\tiger.jpg"));
		
		if(pSpriteObject != NULL)
		{

		pSpriteObject->Begin(D3DX10_SPRITE_SORT_TEXTURE);

		pSpriteObject->DrawSpritesBuffered(m_Spriteinfo, m_CurrentSprites);

		pD3DDevice->OMGetBlendState(&pOrigBlend, OriginalBlendFactor, &OriginalSampleMask);

		if(pBlendState10)
		{
			FLOAT NewBlendFactor[4] = {0, 0, 0, 0};
			pD3DDevice->OMSetBlendState(pBlendState10, NewBlendFactor, 0xffffffff);
		}

		pSpriteObject->Flush();
		pSpriteObject->End();

		}

		//Restore blend state to orig
		pD3DDevice->OMSetBlendState(pOrigBlend, OriginalBlendFactor, OriginalSampleMask);

		//display the next item in the swap chain
		pSwapChain->Present(0, 0);
	}

}

gr_Settings * Graphics::GetGraphicsSettings(std::string file)
{

	m_Settings->Width = 640;
	m_Settings->Height = 480;
	m_Settings->Fullscreen = false;

	sourceRegion.left = 0;
	sourceRegion.right = m_Settings->Width;
	sourceRegion.top = 0;
	sourceRegion.bottom = m_Settings->Height;
	sourceRegion.front = 0;
	sourceRegion.back = 1;

	return m_Settings;

}

void Graphics::SaveGraphicsSettings(std::string file)
{

}

ID3D10Texture2D * Graphics::LoadTexture(LPTSTR file)
{

	ID3D10Texture2D * pTex2D = NULL;
	HRESULT hr = D3DX10CreateTextureFromFile(pD3DDevice, file, NULL, NULL, &pTextureResource, NULL);

	if(hr != S_OK)
	{
		MessageBox (NULL, TEXT ("Bad texture data"), TEXT ("Error"), MB_ICONERROR) ;
		return NULL;
	}

	pTextureResource->QueryInterface(__uuidof(ID3D10Texture2D), (LPVOID*)&pTex2D);
	pTextureResource->Release();

	return pTex2D;

}

bool Graphics::DrawBackground(LPTSTR file)
{

	ID3D10Texture2D * pBackBuffer;
	HRESULT hr = pSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&pBackBuffer);

	if (hr != S_OK)
	{
		MessageBox (NULL, TEXT ("Getting the back buffer Failed"), TEXT ("Error"), MB_ICONERROR) ;
		return false;
	}

	pD3DDevice->CopySubresourceRegion(pBackBuffer, 0, 0, 0, 0, LoadTexture(file), 0, &sourceRegion);


	//release the back buffer
	pBackBuffer->Release();

	return true;

}

bool Graphics::DrawSprite()
{

	return true;

}

D3DX10_SPRITE * Graphics::PrepareSprite(LPTSTR file)
{

	pText2D = LoadTexture(file);

	if(pText2D != NULL)
	{

	//Get the texture details
	pText2D->GetDesc(&TextDetail);

	//Clear out the shader resource vew description structure
	ZeroMemory(&SRVDesc, sizeof(SRVDesc));

	//Set the format
	SRVDesc.Format = TextDetail.Format;
	//Set the type of resource
	SRVDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
	SRVDesc.Texture2D.MipLevels = TextDetail.MipLevels;
	
	}

	pD3DDevice->CreateShaderResourceView(pText2D, &SRVDesc, &pSpriteTextureRV);

	//this is just for testing
	float spritePosX = 70;
	float spritePosY = 180;
	float spriteWidth = 100;
	float spriteHeight = 100;

	//createthe translaton matrix
	D3DXMatrixTranslation(&matTranslation, spritePosX, ( m_Settings->Height - spritePosY), 0.1f);

	//Set the sprite's shader resource view
	m_Spriteinfo->pTexture = pSpriteTextureRV;

	//create the scaling matrix
	D3DXMatrixScaling(&matScaling, spriteWidth, spriteHeight, 1.0f);

	m_Spriteinfo->matWorld = (matScaling * matTranslation);

	return m_Spriteinfo;

}

void Graphics::UpdateScene()
{
	
	if(m_Visible)
	{

	//createthe translaton matrix
	D3DXMatrixTranslation(&matTranslation, (float)(m_PosX + 200/2), (float)(480 - m_PosY - (400/2)), 0.1f);
	//D3DXMatrixTranslation(&matTranslation, m_PosX , ( 480 - m_PosY), 0.1f);
	
	//create the scaling matrix
	D3DXMatrixScaling(&matScaling, m_Width, m_Height, 1.0f);

	m_Spriteinfo->TexCoord.x =  ((float)m_CurFrame)/((float)m_NumFrames);
	m_Spriteinfo->TexCoord.y = 0.0f;
	m_Spriteinfo->TexSize.x = 0.31f;
	m_Spriteinfo->matWorld =  (matScaling * matTranslation);

	}

}

void Graphics::UpdateSprites(float anim_rate)
{

	lastElapsedFrame += anim_rate;

	if(lastElapsedFrame < frameDuration)
	{
		return;
	}

	lastElapsedFrame = 0;
	
	if(m_Visible)
	{

		m_CurFrame++;
	
		if(m_CurFrame >= m_NumFrames)
		{
			m_CurFrame = 0;
		}

		
	}

}


Buckeye
Buckeye
First, I'm not a DX10 guy. But, from a logic standpoint:

1. If the CD code "runs like crazy fast," start with that code and modify it a step at a time to get what you want. Test at each step to see what the penalties/benefits of your changes are.

or

2. Profile your code to find out where the time is being taken up. There are profilers available (PIX, for instance), or you can sprinkle your code with timer queries and determine the length of time taken by each sequence.
Please don't PM me with questions. Post them in the forums for everyone's benefit, and I can embarrass myself publicly. You don't forget how to play when you grow old; you grow old when you forget how to play.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.