CCDrawNode / DrawNode中的drawDot的Cocos2D / Cocos2d-x内部实现

时间:2014-06-20 15:58:53

标签: cocos2d-x cocos2d-x-3.0

对于OpenGL ES问题,我正在追踪Cocos2D 3.1.0源代码。我专注于drawDot中的CCDrawNode,这是内部实施:

-(void)drawDot:(CGPoint)pos radius:(CGFloat)radius color:(CCColor *)color;
{
    GLKVector4 color4 = Premultiply(color.glkVector4);

    GLKVector2 zero2 = GLKVector2Make(0, 0);

    CCRenderBuffer buffer = [self bufferVertexes:4 andTriangleCount:2];
    CCRenderBufferSetVertex(buffer, 0, (CCVertex){GLKVector4Make(pos.x - radius, pos.y - radius, 0, 1), GLKVector2Make(-1, -1), zero2, color4});
    CCRenderBufferSetVertex(buffer, 1, (CCVertex){GLKVector4Make(pos.x - radius, pos.y + radius, 0, 1), GLKVector2Make(-1,  1), zero2, color4});
    CCRenderBufferSetVertex(buffer, 2, (CCVertex){GLKVector4Make(pos.x + radius, pos.y + radius, 0, 1), GLKVector2Make( 1,  1), zero2, color4});
    CCRenderBufferSetVertex(buffer, 3, (CCVertex){GLKVector4Make(pos.x + radius, pos.y - radius, 0, 1), GLKVector2Make( 1, -1), zero2, color4});

    CCRenderBufferSetTriangle(buffer, 0, 0, 1, 2);
    CCRenderBufferSetTriangle(buffer, 1, 0, 2, 3);
}

我记得drawDot允许我们用radius绘制一个圆圈。根据我对使用OpenGL绘制圆的知识,我们使用许多三角形来形成圆,算法就像http://slabode.exofire.net/circle_draw.shtml。请有人解释为什么Cocos2D只使用2个三角形?或者它不只是两个三角形,我只是想念一些东西?

作为参考,Cocos2d-x代码是:

void DrawNode::drawDot(const Vec2 &pos, float radius, const Color4F &color)
{
    unsigned int vertex_count = 2*3;
    ensureCapacity(vertex_count);

    V2F_C4B_T2F a = {Vec2(pos.x - radius, pos.y - radius), Color4B(color), Tex2F(-1.0, -1.0) };
    V2F_C4B_T2F b = {Vec2(pos.x - radius, pos.y + radius), Color4B(color), Tex2F(-1.0,  1.0) };
    V2F_C4B_T2F c = {Vec2(pos.x + radius, pos.y + radius), Color4B(color), Tex2F( 1.0,  1.0) };
    V2F_C4B_T2F d = {Vec2(pos.x + radius, pos.y - radius), Color4B(color), Tex2F( 1.0, -1.0) };

    V2F_C4B_T2F_Triangle *triangles = (V2F_C4B_T2F_Triangle *)(_buffer + _bufferCount);
    V2F_C4B_T2F_Triangle triangle0 = {a, b, c};
    V2F_C4B_T2F_Triangle triangle1 = {a, c, d};
    triangles[0] = triangle0;
    triangles[1] = triangle1;

    _bufferCount += vertex_count;

    _dirty = true;
}

由于

1 个答案:

答案 0 :(得分:0)

drawDot只使用2个三角形来绘制圆点(圆圈)。但它也使用特定的片段着色器绘制圆圈。

https://github.com/cocos2d/cocos2d-iphone/blob/v3.1/cocos2d/CCDrawNode.m#L43

gl_FragColor = cc_FragColor*smoothstep(0.0, length(fwidth(cc_FragTexCoord1)), 1.0 - length(cc_FragTexCoord1));

供进一步参考:http://people.freedesktop.org/~idr/OpenGL_tutorials/03-fragment-intro.html