Cg Tips – Swizzle Operator

 

Intended Audience – Newbies of Graphics Programming.

nVidia Cg has a swizzle operator (.) that allows the components of a vector to be rearranged to form a new vector. Cg has different packed data types called vectors like float2,float4, color, color3, color4 etc. Okay giving example will make things a bit more clear.

float3(a,b,c).zyx; – This will initialize a float3 vector as float( c, b, a ). the values given are just reversed.
float4(a,b,c,d).zzyx; – This will initialize a float4 vector as float( c, c, b, a ).
float4(a,b,c,d).w; – This will initialize vector with d

Which means that you can repeat or omit the elements and just create a new one with the given order and values. The characters x,y,z and w represent the first, second, third and fourth components of the original vector respectively(You can also use r,g,b and a for the same purpose). You wont suffer with any performance hit as it’s brilliantly implemented in the hardware. It can be also used to convert a scalar to vector.

color.xxxx  – Initalizes a float4(a,a,a,a);

OK let’s take a simple fragment program. The original image is as follows. Let’s make this a bit more pale with swizzle.

Let’s pass throgh the following cg program which uses the swizzle.

struct Output {
float4 color : COLOR;
};

Output texture_frag(float2 texCoord : TEXCOORD0,
uniform sampler2D decal : TEX0)
{
Output OUT;

OUT.color = tex2D(decal,texCoord).xyyz; // Use swizzle
return OUT;
}

OK Just have a try!

 
This entry was posted in Uncategorized. Bookmark the permalink.
  • http://www.cheapbootsforsale.us ugg boots

    “Here air jordan 21 products xx, has fashion model, superior quality and service, cheap price and updates quickly.I support strongly always! I want to buy XX, I hesitate to select which style more better.Hope your unique recommends.