Intrinsics1 min read

inverse

Computes the inverse of a matrix.

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

Test inverse in a live shader

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

Open Playground

Live Demo

The inverse function computes the multiplicative inverse of a matrix, such that m * inverse(m) equals the identity matrix.

Signature

bwsl
inverse :: (matNxN m) -> matNxN {...}

Where matNxN can be float2x2, float3x3, or float4x4.

Parameters

ParameterTypeDescription
mmatNxNA square matrix to invert

Return Value

Returns the inverse of the matrix.

Example

bwsl
pipeline WorldToLocal {
fragment {
// Transform world position to object local space
float4x4 invModel = inverse(modelMatrix);
float3 localPos = (invModel * float4(input.worldPos, 1.0)).xyz;
// Use local position for procedural texturing
float3 localUV = localPos * 0.5 + 0.5;
float pattern = fract(localUV.x * 10.0);
output.color = float4(float3(pattern), 1.0);
}
}

Common Use Cases

Reverse Transform

bwsl
// Convert from world space back to object space
float4x4 worldToObject = inverse(objectToWorld);
float3 localPos = (worldToObject * float4(worldPos, 1.0)).xyz;

Normal Matrix

bwsl
// Correct normal transformation for non-uniform scaling
float3x3 normalMatrix = transpose(inverse(float3x3(modelMatrix)));
float3 worldNormal = normalize(normalMatrix * objectNormal);

Screen to World Ray

bwsl
// Unproject screen coordinates to world ray
float4x4 invViewProj = inverse(viewProjection);
float4 worldPos = invViewProj * float4(screenPos, depth, 1.0);
worldPos /= worldPos.w;

Shadow Map Transform

bwsl
// Inverse light view-projection for shadow mapping
float4x4 invLightMatrix = inverse(lightViewProj);

Bone Transform

bwsl
// Calculate bind pose inverse for skinning
float4x4 invBindPose = inverse(bindPoseMatrix);
float4x4 skinMatrix = currentPose * invBindPose;

Singular Matrices

If the matrix is singular (determinant = 0), it cannot be inverted. Results are undefined for singular matrices.

Performance

Matrix inversion is expensive. When possible:

  • Cache inverse matrices if used multiple times
  • For rotation-only matrices, use transpose instead (much faster)
  • Consider passing pre-inverted matrices as uniforms

HLSL Note

HLSL doesn't have a built-in inverse function. BWSL emits a custom implementation when targeting HLSL.

Compiled Output

When compiled to GLSL:

glsl
inverse(m)

When compiled to HLSL:

hlsl
// Custom inverse implementation emitted

When compiled to Metal:

metal
// Uses SIMD matrix inverse functions

See Also

  • transpose - Matrix transpose (cheaper inverse for orthonormal matrices)
  • determinant - Matrix determinant