Sign in to follow this  
spek

3D direction to array index conversion

Recommended Posts

Allright, I have some Batman riddle here. I'm planning to code some sort of low-res cubemap into a simple 1D array. Thus, 6 faces, each face 4x4 values = array with 96 elements. I'm not sure how to order yet, but that might depend on the answer on the next question.

For a certain direction, I like to find the corresponding cubemap array index. Thus:

function getSample( sourcePosition, targetPosition ) : single;
dir = normalize( targetPosition - sourcePosition );
result = cubemap[ directionToCubeMapIndex( dir ) ];

Now the question is, how to make such a conversion function?

By the way, I'm not doing anything graphical or with shaders. Just want to store data from all directions in a cubemap like structure, then access it in a quick & simple way. This function will be called many many times, so speed is the key.

Rick

Share this post


Link to post
Share on other sites
You could use some tests like this to see which side the direction is facing:

+X -> (v.y < v.x) && (v.y > -v.x)
-X -> (v.y > v.x) && (v.y < -v.x)
+Y -> (v.x < v.y) && (v.x > -v.y)
-Y -> (v.x > v.y) && (v.x < -v.y)
+Z -> (v.x < v.z) && (v.x > -v.z)
-Z -> (v.x > v.z) && (v.x < -v.z)


And assign each side an index. You can then extend or shrink the vector onto the unit cube:

±X -> 0.5 * v / abs(v.x)
±Y -> 0.5 * v / abs(v.y)
±Z -> 0.5 * v / abs(v.z)


The other two dimensions can then be used to index into a flattened 4x4 array. So if the direction faces the +Y face, you'd use the XZ coordinates within the unit square centered at (0,0), i.e. if v.x = 0.4 and v.z = -0.4, then i = (0.4 + 0.5) * 4 = 3 and j = (-0.4 + 0.5) * 4 = 0. The final index would be (2 * 16) + (0 * 4) + 3 = 35.

Disclaimer: Late, off the top of my head :)

Share this post


Link to post
Share on other sites
Thank you! I didn't have time to try it yet, but these directions can surely help me. By the way, would a videocard use a similar method when working with cubemaps

float3 direction = reflection or something
float3 pixel = texCUBE( myCubeMap, direction.xyz );

I thought GPU's were bad at branching, which made me think it's using a method without if/else's... Or maybe a cubemap lookup is hardware accelerated?

Cheers,
Rick

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this