#include "DmgNum.h"
#include "MyView.h"
#include "main.h"

void DmgNum::Init(MyDX11Renderer* pRenderer, MyView* pView)
{
	this->pRenderer = pRenderer;
	this->pView = pView;
}

void DmgNum::Reset()
{
	numList.clear();
	qmList.clear();
}

void DmgNum::Step()
{
	//伤害数值
	for (auto& e : numList)
	{
		if (e.timecounter > 0)
		{
			e.timecounter--;
			e.last_x = e.x;
			e.last_y = e.y;
			e.y -= 0.1f;
		}
	}
	numList.remove_if([](const auto& e)
	{
		return e.timecounter <= 0;
	});
	//问号
	for (auto& e : qmList)
	{
		if (e.timecounter > 0)
		{
			e.timecounter--;
			e.last_x = e.x;
			e.last_y = e.y;
			if (e.timecounter < e.disappear)
				e.y -= 0.2f;
		}
	}
	qmList.remove_if([](const auto& e)
	{
		return e.timecounter <= 0;
	});
}

void DmgNum::Draw(float delteTime)
{
	//伤害数值
	char numbuff[16];
	auto& tas = *GetSysTexture(DMGNUM_TEXTURE);
	pRenderer->SetTPenDraw(tas.pSRV);

	MyRect src, dst;
	float srcX, srcY, srcW, srcH;
	float dstX, dstY, dstW, dstH;
	int time = 0;
	DWORD c;
	for (auto& e : numList)
	{
		sprintf_s(numbuff, "%d", e.num);
		int len = (int)strlen(numbuff);
		time = 0;

		srcY = 0 + e.style * 5.0f;
		srcW = 3;
		srcH = 5;
		dstW = srcW * pView->scale;
		dstH = srcH * pView->scale;
		float draw_x = lerp(e.last_x, e.x, delteTime);
		float draw_y = lerp(e.last_y, e.y, delteTime);
		for (int i = 0; i < len; i++)
		{
			srcX = (numbuff[i] - '0') * 3.0f;
			dstX = (time + draw_x - len * 4.0f / 2) * pView->scale - floorf(pView->offX * pView->scale);
			dstY = draw_y * pView->scale - floorf(pView->offY * pView->scale);
			c = RGBA(0xff, 0xff, 0xff, e.timecounter * 0xff / e.timecounter_max);
			src.Set1(srcX, srcY, srcW, srcH);
			dst.Set1(dstX, dstY, dstW, dstH);
			pRenderer->AddRenderCopy(&src, &dst, c);
			time += 4;
		}
	}
	//问号
	src.Set1(30, 0, 5, 10);
	for (auto& e : qmList)
	{
		float draw_x = lerp(e.last_x, e.x, delteTime);
		float draw_y = lerp(e.last_y, e.y, delteTime);
		UINT8 alpha = (UINT8)min(e.timecounter * 0xff / e.disappear, 0xff);
		c = RGBA(0xff, 0xff, 0xff, alpha);
		dst.Set1((draw_x - 2) * pView->scale - floorf(pView->offX * pView->scale),
			draw_y * pView->scale - floorf(pView->offY * pView->scale),
			5 * pView->scale,
			10 * pView->scale);
		pRenderer->AddRenderCopy(&src, &dst, c);
	}
	pRenderer->DrawRenderCopy();
}

void DmgNum::SetNum(int val, float x, float y, int style, std::weak_ptr<Entity> e)
{
	if (val <= 0)
		return;
	NumEntity num;
	num.num = val;
	num.style = style;
	num.last_x = num.x = x;
	num.last_y = num.y = y;
	numList.push_back(num);
}

void DmgNum::SetQuestionMark(float x, float y)
{
	QuestionMarkEntity qm;
	qm.last_x = qm.x = x;
	qm.last_y = qm.y = y;
	qmList.push_back(qm);
}
