Search code examples
androidopengl-estexture-mappingtexture2drender-to-texture

Android Opengl Circle Texture


I have been trying to add texture but the texture looks like below:

texture image

Desire Output

Here's my code to add coordinate and add texture coordinate.

for(int i=0; i<outerVertexCount; i++) {
    float percent=(i/(float)(outerVertexCount));
    float rad= (float) (percent*2*Math.PI);
    float outerX= (float) (centerX+radius*Math.cos(rad));
    float outerY=(float)(centerY+radius*Math.sin(rad));

    int previous=idx;
    circleCoordinates[idx++]=outerX;
    circleCoordinates[idx++]=outerY;
    circleCoordinates[idx++]=(circleCoordinates[previous])/(radius*2);
    circleCoordinates[idx++] = (circleCoordinates[previous+1])/(radius*2);
}

Please help me out.


Solution

  • You are drawing a circle and using 'normalized' almost same coordinates to take texture coordinates. So what you need to do is to normalize texture coordinates to the texture space [0, 1]. Easiest way is to check if texture coordinate of top and left should be (0.5, 0.0) and (0.0, 0.5) respectively. Also bottom and right should be (0.5, 1.0) and (1.0, 0.5) respectively. (Points that touches the edges).

    The problem in your code is:

      circleCoordinates[idx++] = (circleCoordinates[previous])/(radius*2);
      circleCoordinates[idx++] = (circleCoordinates[previous+1])/(radius*2);
    

    As you are creating the points in the circle these will go below 0, in some quadrants which will take wrong texture points. Also you offset your circle by centerX and centerY which also moves your texture.

    The working code should be:

      circleCoordinates[idx++] = (circleCoordinates[previous])/(radius*2) + 0.5 -  centerX / (radius * 2);
      circleCoordinates[idx++] = (circleCoordinates[previous+1])/(radius*2) + 0.5 - centerY / (radius * 2);
    

    0.5 is due to you have normalized it using radius * 2 without centerPoint addition it will map to [-0.5, 0.5] however you also added your center point and also normalized it so you have to subtract center(XY) / (radius * 2) to remove the artifact.

    TLDR; Your (0,0) is the white intersection in your first image you want it top,left. Normalize accordingly.