#include "cSprite.h"

cSprite::cSprite(){
	pDDS = NULL;
	xAdjust = 0;
	yAdjust = 0;
}

cSprite::~cSprite(){
	if(pDDS) pDDS->Release();
}

bool cSprite::BindScreen(LPDIRECTDRAW pDD){
	DDSURFACEDESC ddsd;

	ddsd.dwSize = sizeof(ddsd);
	ddsd.dwFlags = DDSD_CAPS;
	ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
	return pDD->CreateSurface(&ddsd, &pDDS, NULL) == DD_OK;
}

bool cSprite::CreateClone(LPDIRECTDRAW pDD, cSprite *pSprite){
	DDSURFACEDESC ddsd;

	ddsd.dwSize = sizeof(ddsd);
	if(pSprite->pDDS->GetSurfaceDesc(&ddsd) != DD_OK) 
		return false;
	ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
	ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
	if(pDD->CreateSurface(&ddsd, &pDDS, NULL) != DD_OK)
		return false;
	return true;
}

void cSprite::Release(){
	if(pDDS) pDDS->Release();
	pDDS = NULL;
}

bool cSprite::LoadBitmap(LPDIRECTDRAW pDD,
						  LPCSTR szBitmap){
	HBITMAP hBitmap; 
    BITMAP Bitmap;
	DDSURFACEDESC ddsd; 
	HDC hdcSurface;
	HDC hdcBitmap;

	// Win32 API로 비트맵을 읽어들임
	hBitmap = (HBITMAP)LoadImage(GetModuleHandle(NULL), szBitmap, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION);
	if (hBitmap == NULL) 
		hBitmap = (HBITMAP)LoadImage(NULL, szBitmap, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE|LR_CREATEDIBSECTION); 
	if (hBitmap == NULL)
		return NULL;

	// 비트맵의 크기를 얻어냄
	GetObject(hBitmap, sizeof(Bitmap), &Bitmap);  

    // 비트맵을 저장할 다이렉트 드로우 표면을 만듦
	ddsd.dwSize = sizeof(ddsd); 
    ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT |DDSD_WIDTH; 
    ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; 
    ddsd.dwWidth = Bitmap.bmWidth;
	ddsd.dwHeight = Bitmap.bmHeight;  
    if (pDD->CreateSurface(&ddsd, &pDDS, NULL) != DD_OK)
		return NULL;  

	// 비트맵을 표면으로 복사한다.
	if(pDDS->GetDC(&hdcSurface) != DD_OK){
		DeleteObject(hBitmap);
		return NULL;
	}
	hdcBitmap = CreateCompatibleDC(hdcSurface);
	SelectObject(hdcBitmap, hBitmap);
	BitBlt(hdcSurface, 0, 0, Bitmap.bmWidth, Bitmap.bmHeight, 
		hdcBitmap, 0, 0, SRCCOPY);
	DeleteDC(hdcBitmap);
	pDDS->ReleaseDC(hdcSurface);
	DeleteObject(hBitmap);

    return pDDS != NULL;
} 

HRESULT cSprite::BltAdjust(int x, int y,
						   cSprite *pSprite,DWORD dwFlags){
	DDSURFACEDESC ddsd;

	ddsd.dwSize = sizeof(ddsd);
	pSprite->GetDDS()->GetSurfaceDesc(&ddsd);

	RECT DestRect;
	DestRect.left = x + pSprite->xAdjust;
	DestRect.top = y + pSprite->yAdjust;
	DestRect.right = x + pSprite->xAdjust + ddsd.dwWidth;
	DestRect.bottom = y + pSprite->yAdjust + ddsd.dwHeight;
	return pDDS->Blt(&DestRect, pSprite->GetDDS(), NULL, dwFlags, NULL);
}

/*HRESULT cSprite::Blt(LPRECT lpDestRect,
		LPDIRECTDRAWSURFACE lpDDSrcSurface,
		LPRECT lpSrcRect, DWORD dwFlags,
		LPDDBLTFX lpDDBltFx){
	return pDDS->Blt(
}

*/
