其他分享
首页 > 其他分享> > cocos2d-x 渲染机制简介

cocos2d-x 渲染机制简介

作者:互联网

简介

Cocos2d 3.x之后,渲染从UI树进行了分离,想比较2.x而言,新的设计更优雅,灵活,易于拓展。

其特点有:

1.UI遍历 2.渲染 Director::mainLoop Scene::render Node::visit Renderer::render Application::run Director::drawScene Label::draw Sprite::draw ... Renderer::addCommand RenderQueue Renderer::visitRenderQueue Renderer::processRenderCommand CustomCommand BatchCommand TrianglesCommand drawBatchedTriangles GroupCommand cmd::execute cmd::execute

简单的理解其流程就是:

mainLoop

Cocos2d-x 默认的是每秒60帧(fps)对屏幕进行刷新,主要运行接口为:Director::mainLoop()

void Director::mainLoop()
{
    if (! _invalid)
    {
        // 绘制场景
        drawScene();
        // 内存管理相关
        PoolManager::getInstance()->getCurrentPool()->clear();
    }
}

关于内存管理相关,可参考:cocos2d-x 内存管理机制

绘制屏幕

通过drawScene最后会进入到Scene::render中,绘制的流程简要分为两步:

void Scene::render(Renderer* renderer, const Mat4* eyeTransforms, const Mat4* eyeProjections, unsigned int multiViewCount)
{
    auto director = Director::getInstance();
    Camera* defaultCamera = nullptr;
    // 转换坐标系,将ui元素相对坐标转换为世界坐标,原因在于OpenGL ES坐标系与cocos世界坐标系一致
    const auto& transform = getNodeToParentTransform();

    for (const auto& camera : getCameras())
    {
        if (!camera->isVisible())
            continue;

        Camera::_visitingCamera = camera;
        if (Camera::_visitingCamera->getCameraFlag() == CameraFlag::DEFAULT)
        {
            defaultCamera = Camera::_visitingCamera;
        }
        // 遍历场景中UI树,会进入到Node::visit中,进行UI树遍历
        visit(renderer, transform, 0);
        // 绘制,会进入到Renderer::render中,执行绘制
        renderer->render();
        // 
        camera->restore();
        //
        for (unsigned int i = 0; i < multiViewCount; ++i)
            director->popProjectionMatrix(i);
    }
    Camera::_visitingCamera = nullptr;
}

UI树遍历

UI树节点的遍历,其规则采用的是中序(in-order)深度优先算法,也就是:

void Node::visit(Renderer* renderer, const Mat4 &parentTransform, uint32_t parentFlags)
{
    // 如果不可见,则不再绘制
    if (!_visible)
    {
        return;
    }

    uint32_t flags = processParentFlags(parentTransform, parentFlags);
    _director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
    _director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
    // 
    bool visibleByCamera = isVisitableByVisitingCamera();
    int i = 0;
    if(!_children.empty())
    {
        // 该接口会根据节点的localZOrder进行排序
        sortAllChildren();
        // 遍历localZOrder < 0
        for(auto size = _children.size(); i < size; ++i)
        {
            auto node = _children.at(i);

            if (node && node->_localZOrder < 0)
                node->visit(renderer, _modelViewTransform, flags);
            else
                break;
        }
        // 绘制自身
        if (visibleByCamera)
            this->draw(renderer, _modelViewTransform, flags);
		// 遍历localZOrder > 0
        for(auto it=_children.cbegin()+i, itCend = _children.cend(); it != itCend; ++it)
            (*it)->visit(renderer, _modelViewTransform, flags);
    }
    else if (visibleByCamera)
    {
        // 添加到绘制命令中
        this->draw(renderer, _modelViewTransform, flags);
    }
    //
    _director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
}

而针对于于UI树的遍历,主要接口为:

void Node::sortAllChildren()
{
    if (_reorderChildDirty)
    {
        sortNodes(_children);
        _reorderChildDirty = false;
        _eventDispatcher->setDirtyForNode(this);
    }
}

// 以localZOrder进行遍历
static void sortNodes(cocos2d::Vector<_T*>& nodes)
{
    std::sort(std::begin(nodes), std::end(nodes), [](_T* n1, _T* n2) {
        return (n1->_localZOrder < n2->_localZOrder);
    });
}

生成绘制命令

draw在3.x之后不再执行绘制,而是生成绘制命令,以Sprite::draw为例:

void Sprite::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
{
    // 检测纹理是否合法
    if (_texture == nullptr)
    {
        return;
    }

#if CC_USE_CULLING
    // Don't calculate the culling if the transform was not updated
    auto visitingCamera = Camera::getVisitingCamera();
    auto defaultCamera = Camera::getDefaultCamera();
    if (visitingCamera == nullptr) {
        _insideBounds = true;
    }
    else if (visitingCamera == defaultCamera) {
        _insideBounds = ((flags & FLAGS_TRANSFORM_DIRTY) || visitingCamera->isViewProjectionUpdated()) ? renderer->checkVisibility(transform, _contentSize) : _insideBounds;
    }
    else
    {
        // XXX: this always return true since
        _insideBounds = renderer->checkVisibility(transform, _contentSize);
    }

  	// 检测渲染的纹理是否在视窗区域内
    if(_insideBounds)
#endif
    {
        /*
        @func: 添加绘制命令
        */
        _trianglesCommand.init(_globalZOrder,
                               _texture,
                               getGLProgramState(),
                               _blendFunc,
                               _polyInfo.triangles,
                               transform,
                               flags);
        renderer->addCommand(&_trianglesCommand);
    }
}

通过addCommand添加的绘制命令队列RenderQueue中。

void Renderer::addCommand(RenderCommand* command)
{
    int renderQueueID =_commandGroupStack.top();
    addCommand(command, renderQueueID);
}

void Renderer::addCommand(RenderCommand* command, int renderQueueID)
{
    // std::vector<RenderQueue> _renderGroups;    绘制命令栈
    _renderGroups[renderQueueID].push_back(command);
}

绘制命令排序

等UI元素遍历结束后,会开始执行绘制命令相关

void Renderer::render()
{
    _isRendering = true;
    
    if (_glViewAssigned)
    {
        for (auto &renderqueue : _renderGroups)
        {
            // 绘制命令遍历,主要针对的是globalZOrder
            renderqueue.sort();
        }
        visitRenderQueue(_renderGroups[0]);
    }
    clean();
    _isRendering = false;
}

绘制前,会对绘制栈中的命令进行遍历

void RenderQueue::sort()
{
    // 遍历globalZOrder小于0的
    std::stable_sort(std::begin(_commands[QUEUE_GROUP::GLOBALZ_NEG]), std::end(_commands[QUEUE_GROUP::GLOBALZ_NEG]), compareRenderCommand);
    // 遍历globalZOrder大于0的
    std::stable_sort(std::begin(_commands[QUEUE_GROUP::GLOBALZ_POS]), std::end(_commands[QUEUE_GROUP::GLOBALZ_POS]), compareRenderCommand);
}

static bool compareRenderCommand(RenderCommand* a, RenderCommand* b)
{
    return a->getGlobalOrder() < b->getGlobalOrder();
}

针对于globalZOrder的遍历没有等于0的情况原因在于:

UI元素默认就是globalZOrder为0,而在前面的visit遍历中,已经对localZOrder执行了排序。

因此RenderQueue仅需要关注globalZOrder不为0的排序即可。

另外,关于RenderQueue的排序,让我们可以认识到globalZOrder的优劣:

执行绘制命令

在遍历完成后,会通过visitRenderQueue进入到processRenderCommand

void Renderer::processRenderCommand(RenderCommand* command)
{
    auto commandType = command->getType();
    if( RenderCommand::Type::TRIANGLES_COMMAND == commandType)
    {
        flush3D();
        auto cmd = static_cast<TrianglesCommand*>(command);
        if(_filledVertex + cmd->getVertexCount() > VBO_SIZE || _filledIndex + cmd->getIndexCount() > INDEX_VBO_SIZE)
        {
            drawBatchedTriangles();
        }
    }
    else if(RenderCommand::Type::GROUP_COMMAND == commandType)
    {
        flush();
        int renderQueueID = ((GroupCommand*) command)->getRenderQueueID();
        CCGL_DEBUG_PUSH_GROUP_MARKER("RENDERER_GROUP_COMMAND");
        visitRenderQueue(_renderGroups[renderQueueID]);
        CCGL_DEBUG_POP_GROUP_MARKER();
    }
    else if(RenderCommand::Type::CUSTOM_COMMAND == commandType)
    {
        flush();
        auto cmd = static_cast<CustomCommand*>(command);
        CCGL_DEBUG_INSERT_EVENT_MARKER("RENDERER_CUSTOM_COMMAND");
        cmd->execute();
    }
    else if(RenderCommand::Type::BATCH_COMMAND == commandType)
    {
        flush();
        auto cmd = static_cast<BatchCommand*>(command);
        CCGL_DEBUG_INSERT_EVENT_MARKER("RENDERER_BATCH_COMMAND");
        cmd->execute();
    }
}

不同的UI元素会选择对应的命令执行执行OpenGL ES的渲染,最后将效果绘制到屏幕中
End

标签:遍历,渲染,简介,localZOrder,UI,renderer,cocos2d,auto,绘制
来源: https://blog.csdn.net/qq_24726043/article/details/122224974