Intrinsics1 min read

cross

Computes the cross product of two 3D vectors.

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

Test cross in a live shader

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

Open Playground

Live Demo

The cross function computes the cross product of two 3D vectors, returning a vector perpendicular to both inputs.

Signature

bwsl
cross :: (float3 a, float3 b) -> float3 {...}

Parameters

ParameterTypeDescription
afloat3First vector
bfloat3Second vector

Return Value

Returns a vector perpendicular to both a and b, with magnitude equal to |a| * |b| * sin(θ).

Example

bwsl
pipeline TangentSpace {
fragment {
// Calculate tangent space basis
float3 normal = normalize(input.normal);
float3 tangent = normalize(input.tangent);
// Compute bitangent using cross product
float3 bitangent = cross(normal, tangent);
// TBN matrix for normal mapping
float3x3 TBN = float3x3(tangent, bitangent, normal);
output.color = float4(normal * 0.5 + 0.5, 1.0);
}
}

Common Use Cases

Normal Calculation

bwsl
// Calculate face normal from triangle edges
float3 edge1 = v1 - v0;
float3 edge2 = v2 - v0;
float3 faceNormal = normalize(cross(edge1, edge2));

Tangent Space

bwsl
// Compute bitangent for TBN matrix
float3 bitangent = normalize(cross(normal, tangent)) * tangentSign;

Rotation Axis

bwsl
// Find axis to rotate from one direction to another
float3 from = normalize(fromDir);
float3 to = normalize(toDir);
float3 rotationAxis = normalize(cross(from, to));

Camera Right Vector

bwsl
// Calculate camera basis vectors
float3 forward = normalize(target - cameraPos);
float3 right = normalize(cross(forward, worldUp));
float3 up = cross(right, forward);

Surface Area

bwsl
// Parallelogram area from two edge vectors
float3 crossProd = cross(edge1, edge2);
float area = length(crossProd);

Right-Hand Rule

The cross product follows the right-hand rule: if your fingers curl from a to b, your thumb points in the direction of cross(a, b).

Order Matters

Cross product is anti-commutative: cross(a, b) = -cross(b, a). Swapping arguments reverses the result direction.

3D Only

The cross product is only defined for 3D vectors. For 2D, use the "perp dot product": a.x * b.y - a.y * b.x.

Compiled Output

When compiled to GLSL:

glsl
cross(a, b)

When compiled to HLSL:

hlsl
cross(a, b)

See Also