Search code examples
c#unity-game-engineprocedural-generationuv-mapping

Procedural texture uv error


I am creating a game with procedural generated plane and uv, it works mostly fine, but there is one place where the uv seems distorted in a very confusing way.

Intro: the uv is mapped in a "Global" uv coordinates, instead of a local one, because the texture has to be aligned with adjacent planes. Each texture has a tiling of 2*2, I introduce a uv scale of 2 which means each plane "v" coordinates will be mapped in range [0, 0.5] of the texture vertically, to make sure horizontally "u" coordinates do not go out of range [0, 1]. (horizontally the noise is unpredictable to some extend). code:

     Vector2[] CalculateU(float[] leftXMap, float[] rightXMap) {
         int length = leftXMap.Length;
         float totalHeight = (length - 1) * 1;       // distance between two vertices vertically is 1
         float uvheight = totalHeight * uvScale;     // uvScale is 2, purpose is to map a plane's v(vertically), into a range of [0, 0.5]..
         Vector2[] UMap = new Vector2[length * 2];
         for(int i = 0; i < length; i++) {
             float left = leftXMap[i];
             float right = rightXMap[i];
             // make left and right positive.
             while (left < 0) {
                 left += uvheight;
             }
             while(right < 0) {
                 right += uvheight;
             }
             float leftu = (left % uvheight) / uvheight;
             float leftv = (i / (float)(length-1)) / uvScale;
             float rightu = (right % uvheight) / uvheight;
             float rightv = leftv; //(i / (float)length) / 2f;
             UMap[i * 2] = new Vector2(leftu, leftv);
             UMap[i * 2 + 1] = new Vector2(rightu, rightv);

         }
     }

explain: the parameters for the function, are the noise maps for the generated plane. the noise is the x coordinates. while the y coordinates are simple value of 0, 1, 2, .... (length-1).

Distorted texture:

enter image description here

Zoomed in:

enter image description here


Solution

  • I managed to solved the problem, the UV map gets messed where the left noise map values are negative, and right noise map is positive values.

    Since I always try to map all negative values to positive values, so left noise map, which is also be my left vertex x coordinates, will be mapped to positive values. but then it will be larger than right noise map (right vertex x coordinates). then it messed up the UV.

    I solved it by not mapping at all, and suddenly realize that UV map values can be negative, I don't have to map at all!