Skip to main content
GameDev.net gamedev.net
Using GameDev.net for your class this semester?
Learn more →
🔒 Locked

GLSL get vec4 component

Started by szalejot Nov 8, 2011 at 10:44 AM 3 replies 10k views
Original Post
szalejot
szalejot
Hi,

I'm wondering if I can extract component of vec4 (this is 4 numbers in fact), for example third number. It will optimize my memory usage. Now as vertex shader attributes I use two vec4: (x,y,z,1.0) and (1.0,1.0,1.0,s). If I can extract components of vec4 I can use (x,y,z,s) vector as attribute and extract components for calculations.
supermaximo93
supermaximo93
I'm not completely sure what you mean, but if I'm understanding correctly, this is what you want:

vec4 foo = vec4(1.0, 2.0, 3.0, 4.0); // Just an example vec4

float x = foo.x; // Get the x component of the vec4
float y = foo.y; // Get the y component of the vec4

// You can also get multiple components at once
vec2 xy = foo.xy;
vec3 xyz = foo.xyz;

Then obviously you can use this concept for more complex operations.
pcmaster
pcmaster
It's worth to mention that this (syntactic and hardware) feature of shading languages is called SWIZZLING - http://en.wikipedia.org/wiki/Swizzling.
Just in case since it isn't obvious what you're asking, according to my knowledge, you cannot index your built-in vector/matrix types' components by variables (nor literals) in current shading language (such as vec3 v; float x = v[2]).
sprite_hound
sprite_hound

It's worth to mention that this (syntactic and hardware) feature of shading languages is called SWIZZLING - http://en.wikipedia.org/wiki/Swizzling.
Just in case since it isn't obvious what you're asking, according to my knowledge, you cannot index your built-in vector/matrix types' components by variables (nor literals) in current shading language (such as vec3 v; float x = v[2]).


Actually, you can indeed use the subscript operator to index vector elements (at least, my GLSL v400 specs tell me so - I don't know what version this was introduced):



Array subscripting syntax can also be applied to vectors to provide numeric indexing. So in
vec4 pos;
pos[2] refers to the third element of pos and is equivalent to pos.z. This allows variable indexing into a
vector, as well as a generic way of accessing components. Any integer expression can be used as the
subscript. The first component is at index zero. Reading from or writing to a vector using a constant
integral expression with a value that is negative or greater than or equal to the size of the vector is illegal.
When indexing with non-constant expressions, behavior is undefined if the index is negative, or greater
than or equal to the size of the vector.
[/quote]
pcmaster
pcmaster
Wow, awesome, I didn't know, my info seems pretty outdated. I've just tried in HLSL5 and it seems to work too, awesome! :-D

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.