Nidhoegger
Nidhoegger

Reputation: 5232

Convert sampler2D into samplerCube

Is there a way in a fragment shader that has a given sampler2D to convert this to a samplerCube? I want the Cube to have the sampler2D texture on all six sides. The application cannot be changed to pass a samplerCube to the shader, but I need one in my fragment shader.

Upvotes: 0

Views: 971

Answers (1)

Spektre
Spektre

Reputation: 51835

You can write your own function converting 3D cube map direction coordinate into 2D texture coordinate using vector math ...

this might help:

The function should do this:

  1. normalize input direction

  2. detect which side your direction is hitting

    by doing dot product of the input direction with the direction pointing to each cubemap face center. The maximum will identify hit face

  3. project the direction onto the hit face

    and doing dot product with basis vectors of the face you get your 2D coordinates. Beware each face has its rotation ...

Then just use that for access sampler2D with 3D direction as texture coordinate something like this:

uniform sampler2D txr;
...

vec2 mycubemap(vec3 dir)
 {
 vec2 tex;
 dir=normalize(dir);
 ...
 return tex;
 }

void main()
 {
 ...
 ???=texture2D(txr,mycubemap(???));
 ...
 }

When I put all together + some optimizations I got this:

vec2 mycubemap(vec3 t3)
    {
    vec2 t2;
    t3=normalize(t3)/sqrt(2.0);
    vec3 q3=abs(t3);
         if ((q3.x>=q3.y)&&(q3.x>=q3.z))
        {
        t2.x=0.5-t3.z/t3.x;
        t2.y=0.5-t3.y/q3.x;
        }
    else if ((q3.y>=q3.x)&&(q3.y>=q3.z))
        {
        t2.x=0.5+t3.x/q3.y;
        t2.y=0.5+t3.z/t3.y;
        }
    else{
        t2.x=0.5+t3.x/t3.z;
        t2.y=0.5-t3.y/q3.z;
        }
    return t2;
    }

Using it with the layout rendering from the linked QA I got this output:

preview

Using this as texture instead of cubemap:

texture

Note the lines in square boundaries so there might be some additional edge case handling needed but too lazy to analyze further ...

Upvotes: 2

Related Questions