宝爷Debug小记——Cocos2d-x(3.13以前的版本)底层BUG致使Spine渲染花屏

最近在工做中碰到很多棘手的BUG,其中的一个是Spine骨骼的渲染花屏,在战斗中派发出大量士兵以后有几率出现花屏闪烁(以下图所示),这种莫名奇妙且难以重现的BUG最为蛋疼。node


 
前段时间为了提升Spine骨骼动画的加载速度,将Spine库进行了升级,新的Spine库支持skel二进制格式,二进制格式的加载速度比json格式要快5倍以上。
 
这是一个大工程,游戏中全部的骨骼动画都须要使用更高版本的Spine编辑器从新导出,因为部分美术没有对源文件进行版本管理,丢失了源文件,致使部分骨骼动画要从新制做,浪费了很多时间。咱们对代码进行了严格的版本管理,而且大受裨益,但美术的源文件管理确实很容易被忽视,因此在这里吃了一个大亏。升级版本以后,部分使用了翻转的骨骼出现了一些问题,须要美术逐个检查,从新设置翻转以后再导出。
 
使用了新版本的Spine库,除了二进制格式的支持外,渲染方面也进行了一个优化,使用TriangleCommand替换了原先的CustomCommand,这使得多个骨骼动画的渲染能够被合并,原来的版本每一个骨骼至少占用一个drawcall。另外新Spine使用的顶点Shader也发生了变化,致使以前使用的旧Shader也须要跟着调整顶点Shader。
 
接下来,让咱们开始Debug,首先排查一下骨骼动画的问题,同一个关卡,我让测试人员帮忙以很高的频率出兵,可是只出一种兵,看看花屏是否是某种兵的渲染致使的。结果是每种兵出到必定的数量以后都会出现这个问题,可是不一样的兵种出问题的时间不一样,其中的大树人兵种在派出了6个以后就会出现花屏的问题,而其余兵种则比较难出现。
 
那么大树的骨骼和其余几个骨骼有什么不一样呢?询问美术人员以后,得知大树这个骨骼动画使用了较多的Mesh,也就是Spine中的网格功能,这个功能可让2D的图片实现柔顺的扭曲效果,例如毛发、衣物的飘扬效果。
 
既然是Spine的网格出问题,那么是否由于Spine的版本问题致使?编辑器导出的版本与Spine运行库的版本不匹配致使的,根据文档让美术使用了3.3.07,3.5.35和3.5.51版本的Spine编辑器导出骨骼,并使用了3.5.35和3.5.51的运行库进行测试,都存在这个问题。
 
接下来我开始对比Spine的渲染代码,对比上一版本(升级前的Spine,也就是Cocos2d-x3.13.1以前的Spine库),上一版本使用的是本身的批渲染,而最新版本是TriangleCommand,尝试改回去,但代码和数据结构已经发生了较大的改动,强制改回去以后发现渲染效果更加糟糕了。
 
阅读了Spine的渲染代码以后,尝试跳过spine的网格渲染,我添加了一个测试用的静态变量,而后在运行中打断点,以后动态修改这个变量的值,来控制程序的运行流程,逐个跳过Spine的渲染类型,最后定位到只要把网格渲染跳掉,出再多的大树人也不会致使花屏。我想或许有些没有程序员精神的程序员到这里就会结案,而后通知美术人员去除全部网格,从新导出资源。但我决定认真分析下为何这个网格渲染会致使花屏。
 1 static int skiptype = 0;  2  
 3 void SkeletonRenderer::draw (Renderer* renderer, const Mat4& transform, uint32_t transformFlags) {
 4     SkeletonBatch* batch = SkeletonBatch::getInstance();
 5  
 6     for (auto t : _curTriangles)
 7     {
 8         TrianglesMgr::getInstance()->freeTriangles(t);
 9     }
10     _curTriangles.clear();
11     _triCmds.clear();
12  
13     Color3B nodeColor = getColor();
14     _skeleton->r = nodeColor.r / (float)255;
15     _skeleton->g = nodeColor.g / (float)255;
16     _skeleton->b = nodeColor.b / (float)255;
17     _skeleton->a = getDisplayedOpacity() / (float)255;
18  
19     Color4F color;
20     AttachmentVertices* attachmentVertices = nullptr;
21     for (int i = 0, n = _skeleton->slotsCount; i < n; ++i) {
22         spSlot* slot = _skeleton->drawOrder[i];
23         if (!slot->attachment) continue;
24         if (slot->attachment->type == skiptype) continue; 25  
26         switch (slot->attachment->type) {
27         case SP_ATTACHMENT_REGION: {
28             spRegionAttachment* attachment = (spRegionAttachment*)slot->attachment;
29             spRegionAttachment_computeWorldVertices(attachment, slot->bone, _worldVertices);
30             attachmentVertices = getAttachmentVertices(attachment);
31             color.r = attachment->r;
32             color.g = attachment->g;
33             color.b = attachment->b;
34             color.a = attachment->a;
35             break;
36         }
37         case SP_ATTACHMENT_MESH: {
38             spMeshAttachment* attachment = (spMeshAttachment*)slot->attachment;
39             spMeshAttachment_computeWorldVertices(attachment, slot, _worldVertices);
40             attachmentVertices = getAttachmentVertices(attachment);
41             color.r = attachment->r;
42             color.g = attachment->g;
43             color.b = attachment->b;
44             color.a = attachment->a;
45             break;
46         }
47         default:
两种渲染最后的处理都同样,不一样的地方就在于上面这个switch中的顶点计算部分,阅读了一下旧版本Spine的Mesh顶点计算代码,再看看新的Mesh顶点计算,直接吐血,本来的几行代码,新版本使用了几百行代码,都是各类复杂的计算,可读性很糟糕...,尝试把旧的Mesh顶点计算代码应用到新的Spine,结果也是很是糟糕。
 
接下来我决定换一个简单点的环境来定位问题,这 样能够排除其余的干扰!我修改了一下Cocos2d-x3.13版本的TestCpp中的SpineTest进行简单的测试,结果发现了一个有意思的现象,当我添加到第十二个树人时渲染出现了一些奇怪的现象(美术给个人是小树人,顶点较少,因此到第十二个才出问题)
  
再次检查了一下渲染的代码后忽然注意到左下角的顶点数,当我添加第12个树人的时候,顶点数突破了65535!记得在Cocos2d-x底层渲染中,65535是VBO顶点缓存区的最大值,接下来把目标锁定在Cocos2d-x的渲染中。再次阅读了一下Render的代码,特别是TriangleCommand的渲染,调试了一下,发现渲染的顶点是2W多个,而Index索引是7W多个,难道是index的限制不能超过65535?因而把代码中的INDEX_VBO_SIZE替换为VBO_SIZE,这样一次渲染中Index和Vertex都不能超过65535,改完以后,问题果真解决了。那这就结案了吗?我以为还得再深刻探讨一下,把问题的根源完全肯定。
 1 void Renderer::processRenderCommand(RenderCommand* command)
 2 {
 3     auto commandType = command->getType();
 4     if( RenderCommand::Type::TRIANGLES_COMMAND == commandType)
 5     {
 6         // flush other queues
 7         flush3D();
 8  
 9         auto cmd = static_cast<TrianglesCommand*>(command);
10  
11         // flush own queue when buffer is full
12         if(_filledVertex + cmd->getVertexCount() > VBO_SIZE || _filledIndex + cmd->getIndexCount() > INDEX_VBO_SIZE)
13         {
14             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");
15             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");
16             drawBatchedTriangles();
17         }
18  
19         // queue it
20         _queuedTriangleCommands.push_back(cmd);
21         _filledIndex += cmd->getIndexCount();
22         _filledVertex += cmd->getVertexCount();
23     }
24  
难道IndexCount真的不能超过65535吗?google查阅了很多资料,glGet获取GL_MAX_ELEMENTS_INDICES,发现其值是10W+,仔细阅读了OpenGL超级宝典关于缓存区部分的介绍,也没有说Index不能超过65535。Cocos2d-x底层的VBO也分配了足够的空间。难道是顶点或者索引错位了之类的问题致使的,因而我把动画中止,把全部的树人都限定在同一个位置,而后在Render的最底层,打印出每一个树人渲染时的全部顶点和索引信息,而后对比一下只有一个树人、11个树人以及12个树人渲染的顶点和索引信息有何不一样。
 
 1 // 增长一些调试用的静态变量  2 static bool __dbg = false;  3 static bool __deepDbg = false;  4 static int __cmdCount = 68;  5 static int __curCmdCount = 0;  6 static int __idxCount = 0;  7 static int __vexCount = 0;  8 static int __maxidx = 0;   9  
 10 void Renderer::fillVerticesAndIndices(const TrianglesCommand* cmd)
 11 {
 12     memcpy(&_verts[_filledVertex], cmd->getVertices(), sizeof(V3F_C4B_T2F) * cmd->getVertexCount());
 13  
 14     // fill vertex, and convert them to world coordinates
 15     const Mat4& modelView = cmd->getModelView();
 16     for(ssize_t i=0; i < cmd->getVertexCount(); ++i)
 17     {
 18         modelView.transformPoint(&(_verts[i + _filledVertex].vertices));
 19 // 打印全部顶点的xyz和纹理uv  20 if(__dbg && __deepDbg)  21  {  22 CCLOG("vertex %d is xyz %.2f,%.2f,%.2f uv %.2f,%.2f", i + _filledVertex - __vexCount,_verts[i + _filledVertex].vertices.x,  23 _verts[i + _filledVertex].vertices.y, _verts[i + _filledVertex].vertices.z,  24 _verts[i + _filledVertex].texCoords.u, _verts[i + _filledVertex].texCoords.v);  25  }  26     }
 27  
 28     // fill index
 29     const unsigned short* indices = cmd->getIndices();
 30     for(ssize_t i=0; i< cmd->getIndexCount(); ++i)
 31     {
 32         _indices[_filledIndex + i] = _filledVertex + indices[i];
 33 if (__dbg)  34  {  35 if (__maxidx < _indices[_filledIndex + i])  36  {  37 __maxidx = _indices[_filledIndex + i];  38  }  39 if (__deepDbg)  40  {  41 CCLOG("index %d is %d", _filledIndex + i - __idxCount, _indices[_filledIndex + i] - __vexCount);  42  }  43  }  44     }
 45  
 46     _filledVertex += cmd->getVertexCount();
 47     _filledIndex += cmd->getIndexCount();
 48 }
 49  
 50 void Renderer::drawBatchedTriangles()
 51 {
 52     if(_queuedTriangleCommands.empty())
 53         return;
 54  
 55     CCGL_DEBUG_INSERT_EVENT_MARKER("RENDERER_BATCH_TRIANGLES");
 56  
 57 if (__dbg)  58  {  59 __vexCount = 0;  60 __idxCount = 0;  61 __curCmdCount = 0;  62  }  63  
 64     _filledVertex = 0;
 65     _filledIndex = 0;
 66  
 67     /************** 1: Setup up vertices/indices *************/
 68  
 69     _triBatchesToDraw[0].offset = 0;
 70     _triBatchesToDraw[0].indicesToDraw = 0;
 71     _triBatchesToDraw[0].cmd = nullptr;
 72  
 73     int batchesTotal = 0;
 74     int prevMaterialID = -1;
 75     bool firstCommand = true;
 76  
 77     for(auto it = std::begin(_queuedTriangleCommands); it != std::end(_queuedTriangleCommands); ++it)
 78     {
 79         const auto& cmd = *it;
 80         auto currentMaterialID = cmd->getMaterialID();
 81         const bool batchable = !cmd->isSkipBatching();
 82 if (__dbg)  83  {  84 if (__curCmdCount % __cmdCount == 0)  85  {  86 CCLOG("begin %d =====================================", __curCmdCount / __cmdCount);  87 __vexCount = _filledVertex;  88 __idxCount = _filledIndex;  89  }  90 ++__curCmdCount;  91  }  92  
 93         fillVerticesAndIndices(cmd);
 94  
 95         // in the same batch ?
 96         if (batchable && (prevMaterialID == currentMaterialID || firstCommand))
 97         {
 98             CC_ASSERT(firstCommand || _triBatchesToDraw[batchesTotal].cmd->getMaterialID() == cmd->getMaterialID() && "argh... error in logic");
 99             _triBatchesToDraw[batchesTotal].indicesToDraw += cmd->getIndexCount();
100             _triBatchesToDraw[batchesTotal].cmd = cmd;
101         }
102         else
103         {
104             // is this the first one?
105             if (!firstCommand) {
106                 batchesTotal++;
107                 _triBatchesToDraw[batchesTotal].offset = _triBatchesToDraw[batchesTotal-1].offset + _triBatchesToDraw[batchesTotal-1].indicesToDraw;
108             }
109  
110             _triBatchesToDraw[batchesTotal].cmd = cmd;
111             _triBatchesToDraw[batchesTotal].indicesToDraw = (int) cmd->getIndexCount();
112  
113             // is this a single batch ? Prevent creating a batch group then
114             if (!batchable)
115                 currentMaterialID = -1;
116         }
117  
118         // capacity full ?
119         if (batchesTotal + 1 >= _triBatchesToDrawCapacity) {
120             _triBatchesToDrawCapacity *= 1.4;
121             _triBatchesToDraw = (TriBatchToDraw*) realloc(_triBatchesToDraw, sizeof(_triBatchesToDraw[0]) * _triBatchesToDrawCapacity);
122         }
123  
124         prevMaterialID = currentMaterialID;
125         firstCommand = false;
126     }
127     batchesTotal++;
128 if (__dbg) 129  { 130 CCLOG("MAX IDX %d", __maxidx); 131  } 132 __dbg = false; 133  
在添加第一个树人后,打断点,并将__dbg和__deepDbg开启,它会打印出本次渲染的树人详情,添加到第十一和第十二个的时候,再各打印一次,经过Beyond Compare对比结果,发现这些信息彻底正确,每一个树人的全部顶点和索引都是彻底同样的,渲染的内容并无被修改或发生错位。那正确的内容为何渲染不出正确的结果呢?因而继续分析接下来的glDrawElements方法,在十二个树人渲染的时候,断点检查了一下该函数的全部参数,发现了第二个参数的值出现了问题!这个值表示要渲染的顶点索引数量,在只渲染一次的状况下, _triBatchesToDraw[i].indicesToDraw应该等同于_filledIndex才对,而断点看到的值却远小于_filledIndex,查找了一下indicesToDraw的全部引用,发现这个值在每合并一个Command的时候会加上该Command的IndexCount,而这个变量的类型是GLushort!结果终于真相大白,这个变量在不断增长的过程当中溢出了,从而致使渲染的Index出现问题,最终致使的花屏。
1     for (int i=0; i<batchesTotal; ++i)
2     {
3         CC_ASSERT(_triBatchesToDraw[i].cmd && "Invalid batch");
4         _triBatchesToDraw[i].cmd->useMaterial();
5         glDrawElements(GL_TRIANGLES, (GLsizei) _triBatchesToDraw[i].indicesToDraw, GL_UNSIGNED_SHORT, (GLvoid*) (_triBatchesToDraw[i].offset*sizeof(_indices[0])) );
6         _drawnBatches++;
7         _drawnVertices += _triBatchesToDraw[i].indicesToDraw;
8     }
最终的改法应该是将indicesToDraw的类型修改成GLsizei,测试经过后,开开心心地打算提交一个pull request,结果却发现,在下一个版本3.14中,该BUG已被修复...,想一想仍是应该多升级一下引擎啊....
 
最后反思一下这个Bug,有些千奇百怪的Bug,处理到最后每每是那么一两行代码的事情,整个解决Bug的流程看上去虽然很绕,但其实是先肯定并重现我呢体,再从出问题的地方——Spine一点点排查,一直到最底层的渲染逻辑。若是是用逆向思惟,可能一会儿就定位到问题了,但一开始根本没怀疑Cocos2d-x的渲染有问题,由于Cocos2d-x的版本已经有段时间没有升级过了,而Spine则是最近升级的。
 
因此呢,就算不升级引擎,也应该多关心一下引擎的更新日志,了解修改了哪些BUG。除了程序的缘由,美术过量使用了网格,也是这个BUG的一大诱因,过量使用网格,会致使Spine骨骼动画加载变慢,资源文件变大,并影响性能。
 
在分析Spine渲染代码的时候,发现一个可优化的点,就是每次添加一个渲染命令,都会从新分配一块内存用于存储顶点信息,为何不直接使用传入的顶点信息指针呢?多是由于后面对顶点进行了坐标转换,这样同一个顶点可能被转换屡次,那么在这里使用一个简易的内存池也能够起到很好的优化做用。
相关文章
相关标签/搜索