Graphics Reference
In-Depth Information
Individual components of a vector can be accessed using notation similar to access-
ing structures in C++. The members x, y, z, and w each correspond to the first, second,
third, and fourth components of the vector, respectively. Alternatively the members r, g,
b, and a can be used in the same manner. Vector components also support being accessed
using array index syntax, which can be useful for looping through components. Listing 6.5
demonstrates usage of these accessors.
float4 floatVector = 1.0f;
float firstComponent = floatVector. x;
float secondComponent = floatVector.g;
float thirdComponent = floatVector [2];
Listing 6.5. Vector component access syntax.
In addition to supporting single-component access, vectors also support accessing
multiple components simultaneously through the use of swizzles. A swizzle is an operation
that returns one or more components of a vector in an arbitrary ordering. Swizzles can also
replicate a component more than once, to create a new vector value with a greater number
of components than in the source vector. While there are no restrictions on the ordering of
components in swizzles, the notation used must be consistent. In other words, the xyzw no-
tation cannot be mixed with the rgba notation within a single swizzle. Listing 6.6 contains
sample code that uses swizzles in various ways.
float4 vec0 = float4(0.0f, 1.0f, 2.0f, 3.0f);
float3 vec1 = vec0.xyz;
float2 vec2 = vecl.rg;
float3 vec3 = vec0.zxy;
float4 vec4 = vec2.xyxy;
float4 vec5;
vec5.zyxw = vecS.xyzw;
Listing 6.6. Vector swizzle syntax.
If a vector value is assigned to a vector variable with a fewer number of components,
the value is implicitly truncated when the assignment is performed. Programmers should
always be careful not to inadvertently cause such a truncation, since values will be dis-
carded. To make the truncation explicit, a C++-style cast or a swizzle can be used. As a
convenience, the HLSL compiler will emit a warning when an implicit truncation occurs.
Vectors support the same set of mathematical, logical, and comparison operators sup-
ported by scalar variables. When these operators are used on vector types, the operation is
performed on a per-component basis and produces a vector result value with a number of
components equal to that of the operands.
Search WWH ::




Custom Search