Intrinsics1 min read

length

Computes the magnitude of a vector.

Reading Time
1 min
Word Count
142
Sections
12
Try It Live

Test length in a live shader

Open the playground, start from a visual preset, and wire length into the fragment stage to see how it behaves with real values.

Open Playground

Live Demo

The length function returns the magnitude (Euclidean length) of a vector, computed as the square root of the sum of squared components.

Signature

bwsl
length :: (vecN v) -> float {...}

Where vecN can be float2, float3, or float4.

Parameters

ParameterTypeDescription
vvecNThe vector to measure

Return Value

Returns sqrt(v.x*v.x + v.y*v.y + ...) for all components.

Example

bwsl
pipeline PointLight {
fragment {
// Calculate distance to light
float3 toLight = lightPos - input.worldPos;
float dist = length(toLight);
// Attenuation based on distance
float attenuation = 1.0 / (1.0 + 0.1 * dist + 0.01 * dist * dist);
// Direction to light (normalized)
float3 lightDir = toLight / dist; // Same as normalize(toLight)
float diffuse = max(dot(input.normal, lightDir), 0.0);
output.color = float4(lightColor * diffuse * attenuation, 1.0);
}
}

Common Use Cases

Distance to Point

bwsl
// Calculate distance (use distance() for cleaner code)
float dist = length(pointB - pointA);

Light Attenuation

bwsl
// Distance-based light falloff
float dist = length(lightPos - fragPos);
float attenuation = 1.0 / (dist * dist);

Radial Effects

bwsl
// Distance from center for radial effects
float radius = length(input.uv - 0.5);
float vignette = 1.0 - smoothstep(0.3, 0.7, radius);

Velocity Magnitude

bwsl
// Get speed from velocity vector
float speed = length(velocity);

SDF Operations

bwsl
// Sphere distance field
float sphereDist = length(position - sphereCenter) - sphereRadius;

Performance

If you only need to compare lengths (not the actual value), compare squared lengths instead: dot(v, v) < threshold * threshold. This avoids the expensive sqrt operation.

Manual Calculation

length(v) is equivalent to sqrt(dot(v, v)). When you already have the dot product, you can compute length directly.

Compiled Output

When compiled to GLSL:

glsl
length(v)

When compiled to HLSL:

hlsl
length(v)

See Also