Files
XCEngine/MVS/Music fluctuations/source/gpu/Gpu.cpp

113 lines
2.4 KiB
C++

#include "Gpu.h"
GPU::GPU() {}
GPU::~GPU() {
if (mFrameBuffer) {
delete mFrameBuffer;
}
}
void GPU::initGL(const uint32_t& width, const uint32_t& height, void* buffer) {
m_screenWidth = width;
m_screenHeight = height;
mFrameBuffer = new FrameBuffer(width, height, buffer);
}
void GPU::clear() {
std::fill_n(mFrameBuffer->mColorBuffer, mFrameBuffer->mPixelSize, RGBA(0, 0, 0, 0));
std::fill_n(mFrameBuffer->mDepthBuffer, mFrameBuffer->mPixelSize, FLT_MAX);
}
void GPU::drawPoint(const int& x, const int& y, const RGBA& color, const float& depth) {
//从窗口左下角开始算起
if (x < 0 || x >= m_screenWidth || y < 0 || y >= m_screenHeight) { return; }
uint32_t pixelPos = y * mFrameBuffer->mWidth + x;
/*depth-test*/
if (depth > mFrameBuffer->mDepthBuffer[pixelPos]) { return; }
mFrameBuffer->mColorBuffer[pixelPos] = color;
mFrameBuffer->mDepthBuffer[pixelPos] = depth;
}
void GPU::drawVerticalLine(const int& x, const int& y_min, const int y_max, const RGBA& color, const float& depth)
{
for (int i = std::max(y_min,0); i <= std::min(y_max,SCREEN_HEIGHT); i++)
{
drawPoint(x, i, color, depth);
}
}
void GPU::drawRect(const int& x_min, const int x_max, const int y_min, const int y_max, const RGBA& color, const float& depth)
{
for (int i = x_min; i <= x_max; i++)
{
drawVerticalLine(i, y_min, y_max, color, depth);
}
}
void GPU::drawLine(const int& x_from, const int& y_from, const int& x_to, const int& y_to, const RGBA& color, const float& depth)
{
int disX = abs((int)(x_to - x_from));
int disY = abs((int)(y_to - y_from));
int xNow = x_from;
int yNow = y_from;
int stepX = 0;
int stepY = 0;
stepX = (x_to > x_from) ? 1 : ((x_to < x_from) ? -1 : 0);
stepY = (y_to > y_from) ? 1 : ((y_to < y_from) ? -1 : 0);
bool useXStep = true;
if (disX < disY)
{
useXStep = false;
SWAP_INT(disX, disY);
}
int sumStep = disX;
int p = 2 * disY - disX;
for (int i = 0; i < sumStep; i++)
{
float _scale = 0;
if (useXStep)
{
if (x_to != x_from)
{
_scale = (float)(xNow - x_from) / (float)(x_to - x_from);
}
}
else
{
if (y_to != y_from)
{
_scale = (float)(yNow - y_from) / (float)(y_to - y_from);
}
}
drawPoint(xNow, yNow, color);
if (p >= 0)
{
if (useXStep)
{
yNow += stepY;
}
else
{
xNow += stepX;
}
p -= 2 * disX;
}
if (useXStep)
{
xNow += stepX;
}
else
{
yNow += stepY;
}
p += 2 * disY;
}
}