How can I access the nth element in a texture2d from a pixel shader? For example if I wanted to get the 5th vector4 from 10 x 10 texture2d


2D textures usually aren't addressed in terms like the "nth element". The whole point of a 2D texture is that you want to access it using 2D coordinates. If you want to send a 1D array to the shader I'd use a 1D texture.

That being said, you can compute it by something like this:

int x = n % textureWidth;
int y = n / textureWidth;                            // integer division
float u = (float(x) + 0.5) / float(textureWidth);    // map into 0-1 range
float v = (float(y) + 0.5) / float(textureHeight);
float4 result = tex2D(sampler, float2(u, v));

(This assumes you already know how to set up a sampler parameter in the shader and bind a texture to it from the application side.)

| improve this answer | |
  • \$\begingroup\$ A 1d texture sounds perfect for my situation. How does use them in XNA? \$\endgroup\$ – Mr Bell Nov 16 '11 at 23:16
  • \$\begingroup\$ Shouldn't you add 0.5 to float(x) and float(y) before dividing? Otherwise you will get off-by-one errors, especially on a 10×10 texture. \$\endgroup\$ – sam hocevar Nov 17 '11 at 7:25
  • \$\begingroup\$ @SamHocevar, good catch! I'll edit to add that. \$\endgroup\$ – Nathan Reed Nov 17 '11 at 18:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.