Jump to content
  • Advertisement
Sign in to follow this  
hmcen

Cg: how to index a float4 vector?

This topic is 4168 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, In Cg shader, if we have an float4 vector, for example: float4 vec; //declare a float4 vector and i want to use a variable to index into vector's component, for example: int index=1; //variable index; float component = vec[index]; of course the Cg complier returns an error here. So i wonder if there are alternative methods in Cg to index specific component of an vector? (i don't expect the answer to be: create an array, convert vector to array, then index the array :) ), thanks!

Share this post


Link to post
Share on other sites
Advertisement
IIRC GLSL allows what you described, but again i may be wrong. Anyway, one way i can think of is by using a dot product in order to extract the correct component.
Something like that (extract the y component as in your example) :


float component = dot(vec, float4(0,1,0,0));


If 'index' is a uniform variable you can pass the mask vector (in the above example the float4(0,1,0,0)) as a uniform, instead of the index. If index is a vertex attribute you can get the correct mask vector from an array of 4 vectors. Something like this :


float4 mask[4] = {{1,0,0,0}, {0,1,0,0}, {0,0,1,0}, {0,0,0,1}};
float component = dot(vec, mask[vertex.index]);


I'm not sure if the array syntax is correct, but you get the idea.

Hope that helps.

HellRaiZer

Share this post


Link to post
Share on other sites
thanks HellRaiZer:) good method.
but still a problem when the indexed component is used as left value,
for example:
vec[index]= something
any other methods? (i hate to use "switch" in shaders...)

Share this post


Link to post
Share on other sites
I think something like this should work (again an example for the y-axis):


// vec[index] = something;
float4 mask = float4(0,1,0,0);
float4 inverseMask = float4(1,0,1,1);
vec = vec * inverseMask + mask * something;



HellRaiZer

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!