axmol/core/renderer/CCRenderer.cpp

1025 lines
30 KiB
C++
Raw Normal View History

2019-11-23 20:27:39 +08:00
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
2020-02-23 21:27:14 +08:00
Copyright (c) 2020 c4games.com.
2019-11-23 20:27:39 +08:00
2022-01-04 12:36:20 +08:00
https://adxeproject.github.io/
2019-11-23 20:27:39 +08:00
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "renderer/CCRenderer.h"
#include <algorithm>
#include "renderer/CCTrianglesCommand.h"
#include "renderer/CCCustomCommand.h"
#include "renderer/CCCallbackCommand.h"
#include "renderer/CCGroupCommand.h"
#include "renderer/CCMeshCommand.h"
#include "renderer/CCMaterial.h"
#include "renderer/CCTechnique.h"
#include "renderer/CCPass.h"
#include "renderer/CCTexture2D.h"
#include "base/CCConfiguration.h"
#include "base/CCDirector.h"
#include "base/CCEventDispatcher.h"
#include "base/CCEventListenerCustom.h"
#include "base/CCEventType.h"
#include "2d/CCCamera.h"
#include "2d/CCScene.h"
#include "xxhash.h"
#include "renderer/backend/Backend.h"
#include "renderer/backend/RenderTarget.h"
2019-11-23 20:27:39 +08:00
NS_CC_BEGIN
// helper
static bool compareRenderCommand(RenderCommand* a, RenderCommand* b)
{
return a->getGlobalOrder() < b->getGlobalOrder();
}
static bool compare3DCommand(RenderCommand* a, RenderCommand* b)
{
2021-12-25 10:04:45 +08:00
return a->getDepth() > b->getDepth();
2019-11-23 20:27:39 +08:00
}
// queue
2021-12-25 10:04:45 +08:00
RenderQueue::RenderQueue() {}
2019-11-23 20:27:39 +08:00
void RenderQueue::push_back(RenderCommand* command)
{
float z = command->getGlobalOrder();
2021-12-25 10:04:45 +08:00
if (z < 0)
2019-11-23 20:27:39 +08:00
{
_commands[QUEUE_GROUP::GLOBALZ_NEG].push_back(command);
}
2021-12-25 10:04:45 +08:00
else if (z > 0)
2019-11-23 20:27:39 +08:00
{
_commands[QUEUE_GROUP::GLOBALZ_POS].push_back(command);
}
else
{
2021-12-25 10:04:45 +08:00
if (command->is3D())
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
if (command->isTransparent())
2019-11-23 20:27:39 +08:00
{
_commands[QUEUE_GROUP::TRANSPARENT_3D].push_back(command);
}
else
{
_commands[QUEUE_GROUP::OPAQUE_3D].push_back(command);
}
}
else
{
_commands[QUEUE_GROUP::GLOBALZ_ZERO].push_back(command);
}
}
}
ssize_t RenderQueue::size() const
{
ssize_t result(0);
2021-12-25 10:04:45 +08:00
for (int index = 0; index < QUEUE_GROUP::QUEUE_COUNT; ++index)
2019-11-23 20:27:39 +08:00
{
result += _commands[index].size();
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
return result;
}
void RenderQueue::sort()
{
// Don't sort _queue0, it already comes sorted
2021-12-25 10:04:45 +08:00
std::stable_sort(std::begin(_commands[QUEUE_GROUP::TRANSPARENT_3D]),
std::end(_commands[QUEUE_GROUP::TRANSPARENT_3D]), compare3DCommand);
std::stable_sort(std::begin(_commands[QUEUE_GROUP::GLOBALZ_NEG]), std::end(_commands[QUEUE_GROUP::GLOBALZ_NEG]),
compareRenderCommand);
std::stable_sort(std::begin(_commands[QUEUE_GROUP::GLOBALZ_POS]), std::end(_commands[QUEUE_GROUP::GLOBALZ_POS]),
compareRenderCommand);
2019-11-23 20:27:39 +08:00
}
RenderCommand* RenderQueue::operator[](ssize_t index) const
{
2021-12-25 10:04:45 +08:00
for (int queIndex = 0; queIndex < QUEUE_GROUP::QUEUE_COUNT; ++queIndex)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
if (index < static_cast<ssize_t>(_commands[queIndex].size()))
2019-11-23 20:27:39 +08:00
return _commands[queIndex][index];
else
{
index -= _commands[queIndex].size();
}
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
CCASSERT(false, "invalid index");
return nullptr;
}
void RenderQueue::clear()
{
2021-12-25 10:04:45 +08:00
for (int i = 0; i < QUEUE_GROUP::QUEUE_COUNT; ++i)
2019-11-23 20:27:39 +08:00
{
_commands[i].clear();
}
}
void RenderQueue::realloc(size_t reserveSize)
{
2021-12-25 10:04:45 +08:00
for (int i = 0; i < QUEUE_GROUP::QUEUE_COUNT; ++i)
2019-11-23 20:27:39 +08:00
{
_commands[i] = std::vector<RenderCommand*>();
_commands[i].reserve(reserveSize);
}
}
//
//
//
static const int DEFAULT_RENDER_QUEUE = 0;
//
// constructors, destructor, init
//
Renderer::Renderer()
{
2021-12-08 00:11:53 +08:00
_groupCommandManager = new GroupCommandManager();
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
_commandGroupStack.push(DEFAULT_RENDER_QUEUE);
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
RenderQueue defaultRenderQueue;
_renderGroups.push_back(defaultRenderQueue);
_queuedTriangleCommands.reserve(BATCH_TRIAGCOMMAND_RESERVED_SIZE);
// for the batched TriangleCommand
2021-12-25 10:04:45 +08:00
_triBatchesToDraw = (TriBatchToDraw*)malloc(sizeof(_triBatchesToDraw[0]) * _triBatchesToDrawCapacity);
2019-11-23 20:27:39 +08:00
}
Renderer::~Renderer()
{
_renderGroups.clear();
_groupCommandManager->release();
2021-12-25 10:04:45 +08:00
for (auto clearCommand : _clearCommandsPool)
2020-10-16 01:41:36 +08:00
delete clearCommand;
_clearCommandsPool.clear();
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
free(_triBatchesToDraw);
2021-12-25 10:04:45 +08:00
CC_SAFE_RELEASE(_depthStencilState);
2019-11-23 20:27:39 +08:00
CC_SAFE_RELEASE(_commandBuffer);
CC_SAFE_RELEASE(_renderPipeline);
CC_SAFE_RELEASE(_defaultRT);
2019-11-23 20:27:39 +08:00
}
void Renderer::init()
{
// Should invoke _triangleCommandBufferManager.init() first.
_triangleCommandBufferManager.init();
_vertexBuffer = _triangleCommandBufferManager.getVertexBuffer();
2021-12-25 10:04:45 +08:00
_indexBuffer = _triangleCommandBufferManager.getIndexBuffer();
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
auto device = backend::Device::getInstance();
2019-11-23 20:27:39 +08:00
_commandBuffer = device->newCommandBuffer();
// @MTL: the depth stencil flags must same render target and _dsDesc
_dsDesc.flags = DepthStencilFlags::ALL;
2021-12-25 10:04:45 +08:00
_defaultRT = device->newDefaultRenderTarget(TargetBufferFlags::COLOR | TargetBufferFlags::DEPTH_AND_STENCIL);
_currentRT = _defaultRT;
2019-11-23 20:27:39 +08:00
_renderPipeline = device->newRenderPipeline();
_commandBuffer->setRenderPipeline(_renderPipeline);
_depthStencilState = device->newDepthStencilState();
_commandBuffer->setDepthStencilState(_depthStencilState);
2019-11-23 20:27:39 +08:00
}
void Renderer::addCommand(RenderCommand* command)
{
2021-12-25 10:04:45 +08:00
int renderQueueID = _commandGroupStack.top();
2019-11-23 20:27:39 +08:00
addCommand(command, renderQueueID);
}
void Renderer::addCommand(RenderCommand* command, int renderQueueID)
{
CCASSERT(!_isRendering, "Cannot add command while rendering");
2021-12-25 10:04:45 +08:00
CCASSERT(renderQueueID >= 0, "Invalid render queue");
2019-11-23 20:27:39 +08:00
CCASSERT(command->getType() != RenderCommand::Type::UNKNOWN_COMMAND, "Invalid Command Type");
_renderGroups[renderQueueID].push_back(command);
}
void Renderer::pushGroup(int renderQueueID)
{
CCASSERT(!_isRendering, "Cannot change render queue while rendering");
_commandGroupStack.push(renderQueueID);
}
void Renderer::popGroup()
{
CCASSERT(!_isRendering, "Cannot change render queue while rendering");
_commandGroupStack.pop();
}
int Renderer::createRenderQueue()
{
RenderQueue newRenderQueue;
_renderGroups.push_back(newRenderQueue);
return (int)_renderGroups.size() - 1;
}
void Renderer::processGroupCommand(GroupCommand* command)
{
flush();
2021-12-25 10:04:45 +08:00
int renderQueueID = ((GroupCommand*)command)->getRenderQueueID();
2019-11-23 20:27:39 +08:00
pushStateBlock();
2021-12-25 10:04:45 +08:00
// apply default state for all render queues
2019-11-23 20:27:39 +08:00
setDepthTest(false);
setDepthWrite(false);
setCullMode(backend::CullMode::NONE);
visitRenderQueue(_renderGroups[renderQueueID]);
popStateBlock();
}
void Renderer::processRenderCommand(RenderCommand* command)
{
auto commandType = command->getType();
2021-12-25 10:04:45 +08:00
switch (commandType)
{
case RenderCommand::Type::TRIANGLES_COMMAND:
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
// flush other queues
flush3D();
auto cmd = static_cast<TrianglesCommand*>(command);
// flush own queue when buffer is full
if (_queuedTotalVertexCount + cmd->getVertexCount() > VBO_SIZE ||
_queuedTotalIndexCount + cmd->getIndexCount() > INDEX_VBO_SIZE)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
CCASSERT(cmd->getVertexCount() >= 0 && cmd->getVertexCount() < VBO_SIZE,
"VBO for vertex is not big enough, please break the data down or use customized render command");
CCASSERT(cmd->getIndexCount() >= 0 && cmd->getIndexCount() < INDEX_VBO_SIZE,
"VBO for index is not big enough, please break the data down or use customized render command");
drawBatchedTriangles();
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
_queuedTotalIndexCount = _queuedTotalVertexCount = 0;
2019-11-23 20:27:39 +08:00
#ifdef CC_USE_METAL
2021-12-25 10:04:45 +08:00
_queuedIndexCount = _queuedVertexCount = 0;
_triangleCommandBufferManager.prepareNextBuffer();
_vertexBuffer = _triangleCommandBufferManager.getVertexBuffer();
_indexBuffer = _triangleCommandBufferManager.getIndexBuffer();
2019-11-23 20:27:39 +08:00
#endif
2021-12-25 10:04:45 +08:00
}
// queue it
_queuedTriangleCommands.push_back(cmd);
2019-11-23 20:27:39 +08:00
#ifdef CC_USE_METAL
2021-12-25 10:04:45 +08:00
_queuedIndexCount += cmd->getIndexCount();
_queuedVertexCount += cmd->getVertexCount();
2019-11-23 20:27:39 +08:00
#endif
2021-12-25 10:04:45 +08:00
_queuedTotalVertexCount += cmd->getVertexCount();
_queuedTotalIndexCount += cmd->getIndexCount();
}
break;
case RenderCommand::Type::MESH_COMMAND:
flush2D();
drawMeshCommand(command);
break;
case RenderCommand::Type::GROUP_COMMAND:
processGroupCommand(static_cast<GroupCommand*>(command));
break;
case RenderCommand::Type::CUSTOM_COMMAND:
flush();
drawCustomCommand(command);
break;
case RenderCommand::Type::CALLBACK_COMMAND:
flush();
static_cast<CallbackCommand*>(command)->execute();
break;
default:
assert(false);
break;
2019-11-23 20:27:39 +08:00
}
}
void Renderer::visitRenderQueue(RenderQueue& queue)
{
//
2021-12-25 10:04:45 +08:00
// Process Global-Z < 0 Objects
2019-11-23 20:27:39 +08:00
//
doVisitRenderQueue(queue.getSubQueue(RenderQueue::QUEUE_GROUP::GLOBALZ_NEG));
//
2021-12-25 10:04:45 +08:00
// Process Opaque Object
2019-11-23 20:27:39 +08:00
//
pushStateBlock();
2021-12-25 10:04:45 +08:00
setDepthTest(true); // enable depth test in 3D queue by default
2019-11-23 20:27:39 +08:00
setDepthWrite(true);
setCullMode(backend::CullMode::BACK);
doVisitRenderQueue(queue.getSubQueue(RenderQueue::QUEUE_GROUP::OPAQUE_3D));
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
//
2021-12-25 10:04:45 +08:00
// Process 3D Transparent object
2019-11-23 20:27:39 +08:00
//
setDepthWrite(false);
doVisitRenderQueue(queue.getSubQueue(RenderQueue::QUEUE_GROUP::TRANSPARENT_3D));
popStateBlock();
//
2021-12-25 10:04:45 +08:00
// Process Global-Z = 0 Queue
2019-11-23 20:27:39 +08:00
//
doVisitRenderQueue(queue.getSubQueue(RenderQueue::QUEUE_GROUP::GLOBALZ_ZERO));
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
//
2021-12-25 10:04:45 +08:00
// Process Global-Z > 0 Queue
2019-11-23 20:27:39 +08:00
//
doVisitRenderQueue(queue.getSubQueue(RenderQueue::QUEUE_GROUP::GLOBALZ_POS));
}
void Renderer::doVisitRenderQueue(const std::vector<RenderCommand*>& renderCommands)
{
for (const auto& command : renderCommands)
{
processRenderCommand(command);
}
flush();
}
void Renderer::render()
{
2021-12-25 10:04:45 +08:00
// TODO: setup camera or MVP
2019-11-23 20:27:39 +08:00
_isRendering = true;
2021-12-25 10:04:45 +08:00
// if (_glViewAssigned)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
// Process render commands
// 1. Sort render commands based on ID
for (auto& renderqueue : _renderGroups)
2019-11-23 20:27:39 +08:00
{
renderqueue.sort();
}
visitRenderQueue(_renderGroups[0]);
}
clean();
_isRendering = false;
}
bool Renderer::beginFrame()
2019-11-23 20:27:39 +08:00
{
return _commandBuffer->beginFrame();
2019-11-23 20:27:39 +08:00
}
void Renderer::endFrame()
{
_commandBuffer->endFrame();
#ifdef CC_USE_METAL
_triangleCommandBufferManager.putbackAllBuffers();
_vertexBuffer = _triangleCommandBufferManager.getVertexBuffer();
2021-12-25 10:04:45 +08:00
_indexBuffer = _triangleCommandBufferManager.getIndexBuffer();
2019-11-23 20:27:39 +08:00
#endif
2021-12-25 10:04:45 +08:00
_queuedTotalIndexCount = 0;
2019-11-23 20:27:39 +08:00
_queuedTotalVertexCount = 0;
}
void Renderer::clean()
{
// Clear render group
2021-12-25 10:04:45 +08:00
for (size_t j = 0, size = _renderGroups.size(); j < size; j++)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
// commands are owned by nodes
// for (const auto &cmd : _renderGroups[j])
// {
// cmd->releaseToCommandPool();
// }
2019-11-23 20:27:39 +08:00
_renderGroups[j].clear();
}
// Clear batch commands
_queuedTriangleCommands.clear();
}
void Renderer::setDepthTest(bool value)
{
2021-12-25 10:04:45 +08:00
if (value)
{
_currentRT->addFlag(TargetBufferFlags::DEPTH);
_dsDesc.addFlag(DepthStencilFlags::DEPTH_TEST);
}
2021-12-25 10:04:45 +08:00
else
{
_currentRT->removeFlag(TargetBufferFlags::DEPTH);
_dsDesc.removeFlag(DepthStencilFlags::DEPTH_TEST);
}
}
void Renderer::setStencilTest(bool value)
{
2021-12-25 10:04:45 +08:00
if (value)
{
_currentRT->addFlag(TargetBufferFlags::STENCIL);
_dsDesc.addFlag(DepthStencilFlags::STENCIL_TEST);
}
2021-12-25 10:04:45 +08:00
else
{
_currentRT->removeFlag(TargetBufferFlags::STENCIL);
_dsDesc.removeFlag(DepthStencilFlags::STENCIL_TEST);
}
2019-11-23 20:27:39 +08:00
}
void Renderer::setDepthWrite(bool value)
{
2021-12-25 10:04:45 +08:00
if (value)
_dsDesc.addFlag(DepthStencilFlags::DEPTH_WRITE);
else
_dsDesc.removeFlag(DepthStencilFlags::DEPTH_WRITE);
2019-11-23 20:27:39 +08:00
}
void Renderer::setDepthCompareFunction(backend::CompareFunction func)
{
_dsDesc.depthCompareFunction = func;
2019-11-23 20:27:39 +08:00
}
backend::CompareFunction Renderer::getDepthCompareFunction() const
{
return _dsDesc.depthCompareFunction;
2019-11-23 20:27:39 +08:00
}
bool Renderer::Renderer::getDepthTest() const
{
return bitmask::any(_dsDesc.flags, DepthStencilFlags::DEPTH_TEST);
2019-11-23 20:27:39 +08:00
}
bool Renderer::getStencilTest() const
2019-11-23 20:27:39 +08:00
{
return bitmask::any(_dsDesc.flags, DepthStencilFlags::STENCIL_TEST);
2019-11-23 20:27:39 +08:00
}
bool Renderer::getDepthWrite() const
2019-11-23 20:27:39 +08:00
{
return bitmask::any(_dsDesc.flags, DepthStencilFlags::DEPTH_WRITE);
2019-11-23 20:27:39 +08:00
}
void Renderer::setStencilCompareFunction(backend::CompareFunction func, unsigned int ref, unsigned int readMask)
{
_dsDesc.frontFaceStencil.stencilCompareFunction = func;
2021-12-25 10:04:45 +08:00
_dsDesc.backFaceStencil.stencilCompareFunction = func;
2019-11-23 20:27:39 +08:00
_dsDesc.frontFaceStencil.readMask = readMask;
2021-12-25 10:04:45 +08:00
_dsDesc.backFaceStencil.readMask = readMask;
2019-11-23 20:27:39 +08:00
_stencilRef = ref;
}
void Renderer::setStencilOperation(backend::StencilOperation stencilFailureOp,
2021-12-25 10:04:45 +08:00
backend::StencilOperation depthFailureOp,
backend::StencilOperation stencilDepthPassOp)
2019-11-23 20:27:39 +08:00
{
_dsDesc.frontFaceStencil.stencilFailureOperation = stencilFailureOp;
2021-12-25 10:04:45 +08:00
_dsDesc.backFaceStencil.stencilFailureOperation = stencilFailureOp;
2019-11-23 20:27:39 +08:00
_dsDesc.frontFaceStencil.depthFailureOperation = depthFailureOp;
2021-12-25 10:04:45 +08:00
_dsDesc.backFaceStencil.depthFailureOperation = depthFailureOp;
2019-11-23 20:27:39 +08:00
_dsDesc.frontFaceStencil.depthStencilPassOperation = stencilDepthPassOp;
2021-12-25 10:04:45 +08:00
_dsDesc.backFaceStencil.depthStencilPassOperation = stencilDepthPassOp;
2019-11-23 20:27:39 +08:00
}
void Renderer::setStencilWriteMask(unsigned int mask)
{
_dsDesc.frontFaceStencil.writeMask = mask;
2021-12-25 10:04:45 +08:00
_dsDesc.backFaceStencil.writeMask = mask;
2019-11-23 20:27:39 +08:00
}
backend::StencilOperation Renderer::getStencilFailureOperation() const
{
return _dsDesc.frontFaceStencil.stencilFailureOperation;
2019-11-23 20:27:39 +08:00
}
backend::StencilOperation Renderer::getStencilPassDepthFailureOperation() const
{
return _dsDesc.frontFaceStencil.depthFailureOperation;
2019-11-23 20:27:39 +08:00
}
backend::StencilOperation Renderer::getStencilDepthPassOperation() const
{
return _dsDesc.frontFaceStencil.depthStencilPassOperation;
2019-11-23 20:27:39 +08:00
}
backend::CompareFunction Renderer::getStencilCompareFunction() const
{
return _dsDesc.depthCompareFunction;
2019-11-23 20:27:39 +08:00
}
unsigned int Renderer::getStencilReadMask() const
{
return _dsDesc.frontFaceStencil.readMask;
2019-11-23 20:27:39 +08:00
}
unsigned int Renderer::getStencilWriteMask() const
{
return _dsDesc.frontFaceStencil.writeMask;
2019-11-23 20:27:39 +08:00
}
unsigned int Renderer::getStencilReferenceValue() const
{
return _stencilRef;
}
void Renderer::setDepthStencilDesc(const backend::DepthStencilDescriptor& dsDesc)
{
_dsDesc = dsDesc;
}
const backend::DepthStencilDescriptor& Renderer::getDepthStencilDesc() const
{
return _dsDesc;
}
2019-11-23 20:27:39 +08:00
void Renderer::setViewPort(int x, int y, unsigned int w, unsigned int h)
{
_viewport.x = x;
_viewport.y = y;
_viewport.w = w;
_viewport.h = h;
}
void Renderer::fillVerticesAndIndices(const TrianglesCommand* cmd, unsigned int vertexBufferOffset)
{
size_t vertexCount = cmd->getVertexCount();
memcpy(&_verts[_filledVertex], cmd->getVertices(), sizeof(V3F_C4B_T2F) * vertexCount);
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
// fill vertex, and convert them to world coordinates
const Mat4& modelView = cmd->getModelView();
2021-12-25 10:04:45 +08:00
for (size_t i = 0; i < vertexCount; ++i)
2019-11-23 20:27:39 +08:00
{
modelView.transformPoint(&(_verts[i + _filledVertex].vertices));
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
// fill index
const unsigned short* indices = cmd->getIndices();
2021-12-25 10:04:45 +08:00
size_t indexCount = cmd->getIndexCount();
2019-11-23 20:27:39 +08:00
for (size_t i = 0; i < indexCount; ++i)
{
_indices[_filledIndex + i] = vertexBufferOffset + _filledVertex + indices[i];
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
_filledVertex += vertexCount;
_filledIndex += indexCount;
}
void Renderer::drawBatchedTriangles()
{
2021-12-25 10:04:45 +08:00
if (_queuedTriangleCommands.empty())
2019-11-23 20:27:39 +08:00
return;
2021-12-25 10:04:45 +08:00
/************** 1: Setup up vertices/indices *************/
2019-11-23 20:27:39 +08:00
#ifdef CC_USE_METAL
unsigned int vertexBufferFillOffset = _queuedTotalVertexCount - _queuedVertexCount;
2021-12-25 10:04:45 +08:00
unsigned int indexBufferFillOffset = _queuedTotalIndexCount - _queuedIndexCount;
2019-11-23 20:27:39 +08:00
#else
unsigned int vertexBufferFillOffset = 0;
2021-12-25 10:04:45 +08:00
unsigned int indexBufferFillOffset = 0;
2019-11-23 20:27:39 +08:00
#endif
2021-12-25 10:04:45 +08:00
_triBatchesToDraw[0].offset = indexBufferFillOffset;
2019-11-23 20:27:39 +08:00
_triBatchesToDraw[0].indicesToDraw = 0;
2021-12-25 10:04:45 +08:00
_triBatchesToDraw[0].cmd = nullptr;
int batchesTotal = 0;
uint32_t prevMaterialID = 0;
2021-12-25 10:04:45 +08:00
bool firstCommand = true;
2019-11-23 20:27:39 +08:00
_filledVertex = 0;
2021-12-25 10:04:45 +08:00
_filledIndex = 0;
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
for (const auto& cmd : _queuedTriangleCommands)
2019-11-23 20:27:39 +08:00
{
auto currentMaterialID = cmd->getMaterialID();
2021-12-25 10:04:45 +08:00
const bool batchable = !cmd->isSkipBatching();
2019-11-23 20:27:39 +08:00
fillVerticesAndIndices(cmd, vertexBufferFillOffset);
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
// in the same batch ?
if (batchable && (prevMaterialID == currentMaterialID || firstCommand))
{
2021-12-25 10:04:45 +08:00
CC_ASSERT((firstCommand || _triBatchesToDraw[batchesTotal].cmd->getMaterialID() == cmd->getMaterialID()) &&
"argh... error in logic");
2019-11-23 20:27:39 +08:00
_triBatchesToDraw[batchesTotal].indicesToDraw += cmd->getIndexCount();
_triBatchesToDraw[batchesTotal].cmd = cmd;
}
else
{
2020-02-23 21:31:55 +08:00
// is this the first one?
if (!firstCommand)
{
batchesTotal++;
2021-12-25 10:04:45 +08:00
_triBatchesToDraw[batchesTotal].offset =
_triBatchesToDraw[batchesTotal - 1].offset + _triBatchesToDraw[batchesTotal - 1].indicesToDraw;
2020-02-23 21:31:55 +08:00
}
2021-12-25 10:04:45 +08:00
_triBatchesToDraw[batchesTotal].cmd = cmd;
_triBatchesToDraw[batchesTotal].indicesToDraw = (int)cmd->getIndexCount();
2019-11-23 20:27:39 +08:00
// is this a single batch ? Prevent creating a batch group then
if (!batchable)
2021-12-25 10:04:45 +08:00
currentMaterialID = 0;
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
// capacity full ?
if (batchesTotal + 1 >= _triBatchesToDrawCapacity)
{
_triBatchesToDrawCapacity *= 1.4;
2021-12-25 10:04:45 +08:00
_triBatchesToDraw =
(TriBatchToDraw*)realloc(_triBatchesToDraw, sizeof(_triBatchesToDraw[0]) * _triBatchesToDrawCapacity);
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
prevMaterialID = currentMaterialID;
2021-12-25 10:04:45 +08:00
firstCommand = false;
2019-11-23 20:27:39 +08:00
}
batchesTotal++;
#ifdef CC_USE_METAL
_vertexBuffer->updateSubData(_verts, vertexBufferFillOffset * sizeof(_verts[0]), _filledVertex * sizeof(_verts[0]));
2021-12-25 10:04:45 +08:00
_indexBuffer->updateSubData(_indices, indexBufferFillOffset * sizeof(_indices[0]),
_filledIndex * sizeof(_indices[0]));
2019-11-23 20:27:39 +08:00
#else
_vertexBuffer->updateData(_verts, _filledVertex * sizeof(_verts[0]));
2021-12-25 10:04:45 +08:00
_indexBuffer->updateData(_indices, _filledIndex * sizeof(_indices[0]));
2019-11-23 20:27:39 +08:00
#endif
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
/************** 2: Draw *************/
beginRenderPass();
2021-06-17 22:22:41 +08:00
_commandBuffer->setVertexBuffer(_vertexBuffer);
_commandBuffer->setIndexBuffer(_indexBuffer);
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
for (int i = 0; i < batchesTotal; ++i)
{
auto& drawInfo = _triBatchesToDraw[i];
_commandBuffer->updatePipelineState(_currentRT, drawInfo.cmd->getPipelineDescriptor());
auto& pipelineDescriptor = drawInfo.cmd->getPipelineDescriptor();
2019-11-23 20:27:39 +08:00
_commandBuffer->setProgramState(pipelineDescriptor.programState);
2021-12-25 10:04:45 +08:00
_commandBuffer->drawElements(backend::PrimitiveType::TRIANGLE, backend::IndexFormat::U_SHORT,
drawInfo.indicesToDraw, drawInfo.offset * sizeof(_indices[0]));
2019-11-23 20:27:39 +08:00
_drawnBatches++;
_drawnVertices += _triBatchesToDraw[i].indicesToDraw;
}
2021-12-25 10:04:45 +08:00
endRenderPass();
2019-11-23 20:27:39 +08:00
/************** 3: Cleanup *************/
_queuedTriangleCommands.clear();
#ifdef CC_USE_METAL
2021-12-25 10:04:45 +08:00
_queuedIndexCount = 0;
2019-11-23 20:27:39 +08:00
_queuedVertexCount = 0;
#endif
}
2021-12-25 10:04:45 +08:00
void Renderer::drawCustomCommand(RenderCommand* command)
2019-11-23 20:27:39 +08:00
{
auto cmd = static_cast<CustomCommand*>(command);
2021-12-25 10:04:45 +08:00
if (cmd->getBeforeCallback())
cmd->getBeforeCallback()();
2019-11-23 20:27:39 +08:00
beginRenderPass();
_commandBuffer->setVertexBuffer(cmd->getVertexBuffer());
_commandBuffer->updatePipelineState(_currentRT, cmd->getPipelineDescriptor());
2019-11-23 20:27:39 +08:00
_commandBuffer->setProgramState(cmd->getPipelineDescriptor().programState);
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
auto drawType = cmd->getDrawType();
_commandBuffer->setLineWidth(cmd->getLineWidth());
if (CustomCommand::DrawType::ELEMENT == drawType)
{
_commandBuffer->setIndexBuffer(cmd->getIndexBuffer());
2021-12-25 10:04:45 +08:00
_commandBuffer->drawElements(cmd->getPrimitiveType(), cmd->getIndexFormat(), cmd->getIndexDrawCount(),
2019-11-23 20:27:39 +08:00
cmd->getIndexDrawOffset());
_drawnVertices += cmd->getIndexDrawCount();
}
else
{
2021-12-25 10:04:45 +08:00
_commandBuffer->drawArrays(cmd->getPrimitiveType(), cmd->getVertexDrawStart(), cmd->getVertexDrawCount());
2019-11-23 20:27:39 +08:00
_drawnVertices += cmd->getVertexDrawCount();
}
_drawnBatches++;
2021-06-17 22:22:41 +08:00
endRenderPass();
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
if (cmd->getAfterCallback())
cmd->getAfterCallback()();
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
void Renderer::drawMeshCommand(RenderCommand* command)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
// MeshCommand and CustomCommand are identical while rendering.
2019-11-23 20:27:39 +08:00
drawCustomCommand(command);
}
void Renderer::flush()
{
flush2D();
flush3D();
}
void Renderer::flush2D()
{
flushTriangles();
}
void Renderer::flush3D()
{
2021-12-25 10:04:45 +08:00
// TODO 3d batch rendering
2019-11-23 20:27:39 +08:00
}
void Renderer::flushTriangles()
{
drawBatchedTriangles();
}
// helpers
2021-12-25 10:04:45 +08:00
bool Renderer::checkVisibility(const Mat4& transform, const Vec2& size)
2019-11-23 20:27:39 +08:00
{
auto director = Director::getInstance();
2021-12-25 10:04:45 +08:00
auto scene = director->getRunningScene();
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
// If draw to Rendertexture, return true directly.
// only cull the default camera. The culling algorithm is valid for default camera.
2019-11-23 20:27:39 +08:00
if (!scene || (scene && scene->_defaultCamera != Camera::getVisitingCamera()))
return true;
Rect visibleRect(director->getVisibleOrigin(), director->getVisibleSize());
// transform center point to screen space
2021-12-25 10:04:45 +08:00
float hSizeX = size.width / 2;
float hSizeY = size.height / 2;
2019-11-23 20:27:39 +08:00
Vec3 v3p(hSizeX, hSizeY, 0);
transform.transformPoint(&v3p);
Vec2 v2p = Camera::getVisitingCamera()->projectGL(v3p);
// convert content size to world coordinates
2021-12-25 10:04:45 +08:00
float wshw = std::max(fabsf(hSizeX * transform.m[0] + hSizeY * transform.m[4]),
fabsf(hSizeX * transform.m[0] - hSizeY * transform.m[4]));
float wshh = std::max(fabsf(hSizeX * transform.m[1] + hSizeY * transform.m[5]),
fabsf(hSizeX * transform.m[1] - hSizeY * transform.m[5]));
2019-11-23 20:27:39 +08:00
// enlarge visible rect half size in screen coord
visibleRect.origin.x -= wshw;
visibleRect.origin.y -= wshh;
visibleRect.size.width += wshw * 2;
visibleRect.size.height += wshh * 2;
bool ret = visibleRect.containsPoint(v2p);
return ret;
}
2021-12-25 10:04:45 +08:00
void Renderer::readPixels(backend::RenderTarget* rt,
std::function<void(const backend::PixelBufferDescriptor&)> callback)
2020-09-13 11:11:48 +08:00
{
assert(!!rt);
2021-12-25 10:04:45 +08:00
if (rt ==
_defaultRT) // read pixels from screen, metal renderer backend: screen texture must not be a framebufferOnly
backend::Device::getInstance()->setFrameBufferOnly(false);
_commandBuffer->readPixels(rt, std::move(callback));
2020-09-13 11:11:48 +08:00
}
void Renderer::beginRenderPass()
2019-11-23 20:27:39 +08:00
{
_commandBuffer->beginRenderPass(_currentRT, _renderPassDesc);
_commandBuffer->updateDepthStencilState(_dsDesc);
_commandBuffer->setStencilReferenceValue(_stencilRef);
_commandBuffer->setViewport(_viewport.x, _viewport.y, _viewport.w, _viewport.h);
_commandBuffer->setCullMode(_cullMode);
_commandBuffer->setWinding(_winding);
2021-12-25 10:04:45 +08:00
_commandBuffer->setScissorRect(_scissorState.isEnabled, _scissorState.rect.x, _scissorState.rect.y,
_scissorState.rect.width, _scissorState.rect.height);
2021-06-17 22:22:41 +08:00
}
2021-12-25 10:04:45 +08:00
void Renderer::endRenderPass()
2021-06-17 22:22:41 +08:00
{
_commandBuffer->endRenderPass();
2019-11-23 20:27:39 +08:00
}
void Renderer::clear(ClearFlag flags, const Color4F& color, float depth, unsigned int stencil, float globalOrder)
{
_clearFlag = flags;
2021-12-25 10:04:45 +08:00
2020-10-16 01:41:36 +08:00
CallbackCommand* command = nextClearCommand();
command->init(globalOrder);
command->func = [=]() -> void {
backend::RenderPassDescriptor descriptor;
2020-10-16 01:41:36 +08:00
descriptor.flags.clear = flags;
2021-12-25 10:04:45 +08:00
if (bitmask::any(flags, ClearFlag::COLOR))
{
_clearColor = color;
descriptor.clearColorValue = {color.r, color.g, color.b, color.a};
2020-10-16 01:41:36 +08:00
}
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
if (bitmask::any(flags, ClearFlag::DEPTH))
2020-10-16 01:41:36 +08:00
descriptor.clearDepthValue = depth;
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
if (bitmask::any(flags, ClearFlag::STENCIL))
2020-10-16 01:41:36 +08:00
descriptor.clearStencilValue = stencil;
2021-12-25 10:04:45 +08:00
2020-10-16 01:41:36 +08:00
_commandBuffer->beginRenderPass(_currentRT, descriptor);
_commandBuffer->endRenderPass();
2019-11-23 20:27:39 +08:00
2020-10-16 01:41:36 +08:00
// push to pool for reuse
_clearCommandsPool.push_back(command);
};
addCommand(command);
}
2019-11-23 20:27:39 +08:00
2020-10-16 01:41:36 +08:00
CallbackCommand* Renderer::nextClearCommand()
{
2021-12-25 10:04:45 +08:00
if (!_clearCommandsPool.empty())
{
2020-10-16 01:41:36 +08:00
auto clearCommand = _clearCommandsPool.back();
_clearCommandsPool.pop_back();
return clearCommand;
}
2021-12-25 10:04:45 +08:00
2020-10-16 01:41:36 +08:00
return new CallbackCommand();
2019-11-23 20:27:39 +08:00
}
const Color4F& Renderer::getClearColor() const
{
return _clearColor;
}
float Renderer::getClearDepth() const
{
return _renderPassDesc.clearDepthValue;
2019-11-23 20:27:39 +08:00
}
unsigned int Renderer::getClearStencil() const
{
return _renderPassDesc.clearStencilValue;
2019-11-23 20:27:39 +08:00
}
ClearFlag Renderer::getClearFlag() const
{
return _clearFlag;
}
RenderTargetFlag Renderer::getRenderTargetFlag() const
{
return _currentRT->getTargetFlags();
2019-11-23 20:27:39 +08:00
}
void Renderer::setScissorTest(bool enabled)
{
_scissorState.isEnabled = enabled;
}
bool Renderer::getScissorTest() const
{
return _scissorState.isEnabled;
}
const ScissorRect& Renderer::getScissorRect() const
{
return _scissorState.rect;
}
void Renderer::setScissorRect(float x, float y, float width, float height)
{
2021-12-25 10:04:45 +08:00
_scissorState.rect.x = x;
_scissorState.rect.y = y;
_scissorState.rect.width = width;
2019-11-23 20:27:39 +08:00
_scissorState.rect.height = height;
}
// TriangleCommandBufferManager
Renderer::TriangleCommandBufferManager::~TriangleCommandBufferManager()
{
for (auto& vertexBuffer : _vertexBufferPool)
vertexBuffer->release();
for (auto& indexBuffer : _indexBufferPool)
indexBuffer->release();
}
void Renderer::TriangleCommandBufferManager::init()
{
createBuffer();
}
void Renderer::TriangleCommandBufferManager::putbackAllBuffers()
{
_currentBufferIndex = 0;
}
void Renderer::TriangleCommandBufferManager::prepareNextBuffer()
{
if (_currentBufferIndex < (int)_vertexBufferPool.size() - 1)
{
++_currentBufferIndex;
return;
}
createBuffer();
++_currentBufferIndex;
}
backend::Buffer* Renderer::TriangleCommandBufferManager::getVertexBuffer() const
{
return _vertexBufferPool[_currentBufferIndex];
}
backend::Buffer* Renderer::TriangleCommandBufferManager::getIndexBuffer() const
{
return _indexBufferPool[_currentBufferIndex];
}
void Renderer::TriangleCommandBufferManager::createBuffer()
{
auto device = backend::Device::getInstance();
#ifdef CC_USE_METAL
// Metal doesn't need to update buffer to make sure it has the correct size.
2021-12-25 10:04:45 +08:00
auto vertexBuffer = device->newBuffer(Renderer::VBO_SIZE * sizeof(_verts[0]), backend::BufferType::VERTEX,
backend::BufferUsage::DYNAMIC);
2019-11-23 20:27:39 +08:00
if (!vertexBuffer)
return;
2021-12-25 10:04:45 +08:00
auto indexBuffer = device->newBuffer(Renderer::INDEX_VBO_SIZE * sizeof(_indices[0]), backend::BufferType::INDEX,
backend::BufferUsage::DYNAMIC);
2019-11-23 20:27:39 +08:00
if (!indexBuffer)
{
vertexBuffer->release();
return;
}
#else
auto tmpData = malloc(Renderer::VBO_SIZE * sizeof(V3F_C4B_T2F));
if (!tmpData)
return;
2021-12-25 10:04:45 +08:00
auto vertexBuffer = device->newBuffer(Renderer::VBO_SIZE * sizeof(V3F_C4B_T2F), backend::BufferType::VERTEX,
backend::BufferUsage::DYNAMIC);
2019-11-23 20:27:39 +08:00
if (!vertexBuffer)
{
free(tmpData);
return;
}
vertexBuffer->updateData(tmpData, Renderer::VBO_SIZE * sizeof(V3F_C4B_T2F));
2021-12-25 10:04:45 +08:00
auto indexBuffer = device->newBuffer(Renderer::INDEX_VBO_SIZE * sizeof(unsigned short), backend::BufferType::INDEX,
backend::BufferUsage::DYNAMIC);
if (!indexBuffer)
2019-11-23 20:27:39 +08:00
{
free(tmpData);
vertexBuffer->release();
return;
}
indexBuffer->updateData(tmpData, Renderer::INDEX_VBO_SIZE * sizeof(unsigned short));
free(tmpData);
#endif
_vertexBufferPool.push_back(vertexBuffer);
_indexBufferPool.push_back(indexBuffer);
}
void Renderer::pushStateBlock()
{
StateBlock block;
2021-12-25 10:04:45 +08:00
block.depthTest = getDepthTest();
2019-11-23 20:27:39 +08:00
block.depthWrite = getDepthWrite();
2021-12-25 10:04:45 +08:00
block.cullMode = getCullMode();
2019-11-23 20:27:39 +08:00
_stateBlockStack.emplace_back(block);
}
void Renderer::popStateBlock()
{
2021-12-25 10:04:45 +08:00
auto& block = _stateBlockStack.back();
2019-11-23 20:27:39 +08:00
setDepthTest(block.depthTest);
setDepthWrite(block.depthWrite);
setCullMode(block.cullMode);
_stateBlockStack.pop_back();
}
NS_CC_END