浅解cocos2d-x中的CCSprite绘制原理

cocos2d-x版本为2.0.4

此画图调用的是opengl es 2.0版本,支持三角形画图。故必须有一个顶点数组。此定义定义在CCSprite.h中

ccV3F_C4B_T2F_Quad m_sQuad;

而这个顶点数组的定义为

//! 4 ccVertex3FTex2FColor4B
typedef struct _ccV3F_C4B_T2F_Quad
{
    //! top left
    ccV3F_C4B_T2F    tl;
    //! bottom left
    ccV3F_C4B_T2F    bl;
    //! top right
    ccV3F_C4B_T2F    tr;
    //! bottom right
    ccV3F_C4B_T2F    br;
} ccV3F_C4B_T2F_Quad;

顶点分布如图所示

浅解cocos2d-x中的CCSprite绘制原理

Cocos2d-x的画图均在自身节点的draw(void)下面。

 1 // m_pobTexture 为当前CCSprite绑定的纹理图
 2     if (m_pobTexture != NULL)
 3     {
 4         ccGLBindTexture2D( m_pobTexture->getName() );
 5     }
 6     else
 7     {
 8         ccGLBindTexture2D(0);
 9     }
10 
11 //启用顶点数组画图模式
12     ccGLEnableVertexAttribs( kCCVertexAttribFlag_PosColorTex );
13 //设置每个顶点数的大小
14 #define kQuadSize sizeof(m_sQuad.bl)
15     long offset = (long)&m_sQuad;
16 
17     // vertex
18     int diff = offsetof( ccV3F_C4B_T2F, vertices);
19     glVertexAttribPointer(kCCVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, kQuadSize, (void*) (offset + diff));
20 
21     // texCoods
22     diff = offsetof( ccV3F_C4B_T2F, texCoords);
23     glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (void*)(offset + diff));
24 
25     // color
26     diff = offsetof( ccV3F_C4B_T2F, colors);
27     glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (void*)(offset + diff));
28 
29     //这一步为确认画图,根据当前绑定的纹理图,然后根据当前的顶点数组进行画图
30     glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

GL_TRIANGLE_STRIP

 - OpenGL 的使用将最开始的两个顶点出发,然后遍历每个顶点,这些顶点将使用前2个顶点一起组成一个三角形。

所以画图的顺序为 V0-V1-V2 及 V1-V2-V3两个三角形,这样就画出我们想展示的图形

你可能感兴趣的:(cocos2d-x)