#include "SimpleMotionRenderer.h"

#include "GLExtensions.h"

#include <algorithm>
#include <cmath>

bool SimpleMotionRenderer::InitializeGl(unsigned width, unsigned height)
{
	mWidth = width;
	mHeight = height;
	return mWidth > 0 && mHeight > 0;
}

void SimpleMotionRenderer::RenderFrame(uint64_t frameIndex)
{
	const float t = static_cast<float>(frameIndex) / 60.0f;
	const float red = 0.1f + 0.4f * (0.5f + 0.5f * std::sin(t));
	const float green = 0.1f + 0.4f * (0.5f + 0.5f * std::sin(t * 0.73f + 1.0f));
	const float blue = 0.15f + 0.3f * (0.5f + 0.5f * std::sin(t * 0.41f + 2.0f));

	glViewport(0, 0, static_cast<GLsizei>(mWidth), static_cast<GLsizei>(mHeight));
	glDisable(GL_SCISSOR_TEST);
	glClearColor(red, green, blue, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT);

	const int boxWidth = (std::max)(1, static_cast<int>(mWidth / 6));
	const int boxHeight = (std::max)(1, static_cast<int>(mHeight / 5));
	const float phase = 0.5f + 0.5f * std::sin(t * 1.7f);
	const int x = static_cast<int>(phase * static_cast<float>(mWidth - static_cast<unsigned>(boxWidth)));
	const int y = static_cast<int>((0.5f + 0.5f * std::sin(t * 1.1f + 0.8f)) * static_cast<float>(mHeight - static_cast<unsigned>(boxHeight)));

	glEnable(GL_SCISSOR_TEST);
	glScissor(x, y, boxWidth, boxHeight);
	glClearColor(1.0f - red, 0.85f, 0.15f + blue, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT);

	const int stripeWidth = (std::max)(1, static_cast<int>(mWidth / 80));
	const int stripeX = static_cast<int>((frameIndex % 120) * (mWidth - static_cast<unsigned>(stripeWidth)) / 119);
	glScissor(stripeX, 0, stripeWidth, static_cast<GLsizei>(mHeight));
	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT);
	glDisable(GL_SCISSOR_TEST);
}

void SimpleMotionRenderer::ShutdownGl()
{
	mWidth = 0;
	mHeight = 0;
}
