渲染优化
之前有关渲染优化没写全,现在来把它补全。原理:把要渲染的quad,按纹理分,相同纹理一次性画出来。
void Renderer::visit()
{
int queueSize = _renderQueue.size();
float perZorder = (zFar - zNear)/(float)(queueSize+1) ;
//优化排序
for (int i = 0; i < queueSize; ++i)
{
QuadCommand* cmd = _renderQueue[i];
Quad* quad = cmd->getQuads();
int quadCount = cmd->getQuadCount();
float zOrder = perZorder * (i+1);
for (int j = 0; j < quadCount; ++j)
{
quad[j].tl._position.z = zOrder;
quad[j].bl._position.z = zOrder;
quad[j].tr._position.z = zOrder;
quad[j].br._position.z = zOrder;
}
}
std::sort( std::begin(_renderQueue), std::end(_renderQueue),quadComparisonLess);
//复制到批渲染队列
copyToBatchRender(queueSize);
}
void Renderer::copyToBatchRender( int queueSize )
{
for (int i = 0; i < queueSize; ++i)
{
QuadCommand* cmd = _renderQueue[i];
_batchedQuadCommands.push_back(cmd);
memcpy(_quads + _numQuads, cmd->getQuads(), sizeof(Quad) * cmd->getQuadCount());
convertToWorldCoordinates(_quads + _numQuads, cmd->getQuadCount(), cmd->getModel());
_numQuads += cmd->getQuadCount();
}
_renderQueue.clear();
}
void Renderer::convertToWorldCoordinates(Quad* quads, int quadNumber, const Mat4& modelView)
{
for(int i=0; i<quadNumber; ++i)
{
Quad *q = &quads[i];
Vec3 *vec1 = (Vec3*)&q->bl._position;
transformPoint(modelView,vec1,1);
Vec3 *vec2 = (Vec3*)&q->br._position;
transformPoint(modelView,vec2,1);
Vec3 *vec3 = (Vec3*)&q->tr._position;
transformPoint(modelView,vec3,1);
Vec3 *vec4 = (Vec3*)&q->tl._position;
transformPoint(modelView,vec4,1);
}
}
void Renderer::transformPoint(const Mat4& modelView,Vec3 *vertices,float w)
{
const float* m = &modelView[0][0];
vertices->x = vertices->x * m[0] + vertices->y * m[4] + vertices->z * m[8] + w * m[12];
vertices->y = vertices->x * m[1] + vertices->y * m[5] + vertices->z * m[9] + w * m[13];
vertices->z = vertices->x * m[2] + vertices->y * m[6] + vertices->z * m[10] + w * m[14];
}