Vector Math - Built-in functions - Shader Learning

Built-in functions

Vector Math

Task

Find the sum of three vectors in the program (blueChannel, redChannel, alphaChannel), and print the result

Theory

In both GLSL and HLSL, you can use math operators like +, -, *, and / on vectors - just like you do with single numbers (scalars). But here’s the key: these operations happen component-wise, meaning each element of one vector is combined with the matching element of the other:

$ a \cdot b = \begin{bmatrix}a_x \cdot b_x \ a_y \cdot b_y \ a_z \cdot b_z \end{bmatrix} $

Important Rule: to do math between two vectors, they must have the same number of components (e.g., both must be vec3 or float3).


GLSL Example

vec3 a = vec3(1.0, 2.0, 3.0);
vec3 b = vec3(4.0, 5.0, 6.0);

vec3 sum = a + b;        // (1+4, 2+5, 3+6) 
vec3 difference = a - b; // (1−4, 2−5, 3−6)

HLSL Example

float3 a = float3(1.0, 2.0, 3.0);
float3 b = float3(4.0, 5.0, 6.0);

float3 sum = a + b;        // (1+4, 2+5, 3+6)
float3 difference = a - b; // (1−4, 2−5, 3−6)