5. The Cross Product

The dot product from chapter 4 takes two vectors and gives back a number.
The cross product takes two vectors and gives back a new vector that sticks out at a right angle from both of them.

That sounds like an odd thing to want, but it solves one of the most common problems in 3D graphics: "which way is this surface facing?"
Every triangle normal, every camera "right" vector and every winding-order check comes from the cross product.
It also tells us the area of a triangle, and in 2D it tells us whether a point is to the left or right of a line, which is how a GPU decides which pixels a triangle covers.

5.1 The idea: an arrow standing up from a surface

Put two pencils on a table, both starting at the same point, pointing in different directions.
Together they define the flat surface of the table.
Now hold a third pencil straight up from the point where they meet, perpendicular to both of them.
That third pencil is the direction of the cross product.

a and b lying flat on a table, with a × b standing straight up from them

Two questions remain: does the third pencil point up or down, and how long is it?
The answers are "the right-hand rule" and "the area of the parallelogram spanned by a and b".
We'll get to both.

One important limitation first: the cross product only exists in 3D.
In 2D there is no third direction to stick out into, and in 4D there are infinitely many directions perpendicular to two vectors, so there is no single answer.
(As a mathematical curiosity, a similar product exists in 7D, but you'll never need it for graphics.)

5.2 What the formula is

For 𝐚=(ax,ay,az) and 𝐛=(bx,by,bz), the cross product 𝐚×𝐛 (read "a cross b") is:

𝐚×𝐛=[aybz−azbyazbx−axbzaxby−aybx]

Its length is:

‖𝐚×𝐛‖=‖𝐚‖‖𝐛‖sinθ

where θ is the angle between 𝐚 and 𝐛 (between 0 and 180°).
Compare with the dot product, which had cosθ instead: the dot product measures how much two vectors agree, the cross product measures how much they disagree.

5.2.1 Remembering the formula

Nobody remembers this formula by staring at it.
Here is the trick I use, sometimes called "xyzzy".
The x component uses only y and z, and it reads "y z minus z y":

cx=aybz−azby(x: yz−zy)

For the next component, shift every letter one step forward in the cycle x → y → z → x:

cy=azbx−axbz(y: zx−xz)

And once more:

cz=axby−aybx(z: xy−yx)

So you only need to remember "x = yz − zy" and keep rotating the letters.
In each line, the component you are computing never appears on the right side.

If you already know determinants, you may have seen the cross product written as a 3×3 determinant with 𝐢,𝐣,𝐤 in the top row. That's only a memory aid, not a real determinant (the top row contains vectors, not numbers). We'll learn determinants properly in chapter 10, so if this note means nothing to you yet, just skip it.

5.3 How it works

5.3.1 A worked example

Let 𝐚=(1,2,3) and 𝐛=(4,5,6).

cx=aybz−azby=2×6−3×5=12−15=−3cy=azbx−axbz=3×4−1×6=12−6=6cz=axby−aybx=1×5−2×4=5−8=−3

So 𝐚×𝐛=(−3,6,−3).

Is it really perpendicular to both?
In chapter 4 we learned the test: perpendicular vectors have a dot product of 0.

(−3,6,−3)⋅(1,2,3)=−3+12−9=0(−3,6,−3)⋅(4,5,6)=−12+30−18=0

Both zero.
It's always worth doing this check when you compute a cross product by hand; it catches almost every mistake.

5.3.2 Why it is perpendicular

This isn't luck.
Let's take the dot product of 𝐚 with 𝐚×𝐛 using letters instead of numbers:

𝐚⋅(𝐚×𝐛)=ax(aybz−azby)+ay(azbx−axbz)+az(axby−aybx)=axaybz−axazby+ayazbx−ayaxbz+azaxby−azaybx

Look at the six terms.
axaybz (first) and ayaxbz (fourth) are the same product with opposite signs, so they cancel.
The second and fifth cancel, and the third and sixth cancel.
Everything adds up to 0, for any vectors.
The same thing happens with 𝐛.
The formula was built exactly so that this cancellation happens.

5.3.3 The basis vectors

Let's cross the basis vectors from chapter 2, 𝐢=(1,0,0), 𝐣=(0,1,0) and 𝐤=(0,0,1):

𝐢×𝐣=(0×0−0×1,0×0−1×0,1×1−0×0)=(0,0,1)=𝐤

In the same way you can check:

𝐢×𝐣=𝐤,𝐣×𝐤=𝐢,𝐤×𝐢=𝐣

Going the other way around the cycle gives the negative:

𝐣×𝐢=−𝐤,𝐤×𝐣=−𝐢,𝐢×𝐤=−𝐣

The cycle i, j, k: products along the arrows are positive, against the arrows negative

And any vector crossed with itself gives zero: 𝐢×𝐢=𝟎.

5.3.4 Which way it points: the right-hand rule

Two vectors have two perpendicular directions: "up" and "down" from their plane.
The formula always picks the one given by the right-hand rule:

  1. Point the fingers of your right hand along 𝐚.
  2. Curl them towards 𝐛 (the short way around).
  3. Your thumb points along 𝐚×𝐛.

Right-handed axes: x = i to the right, y = j up and z = k = i × j out of the screen

Try it with 𝐢×𝐣: fingers to the right along x, curl them up towards y, and your thumb points out of the screen towards you, which is +Z in our right-handed system.
That matches 𝐢×𝐣=𝐤.
This is not a coincidence: a coordinate system is called right-handed exactly because 𝐢×𝐣=𝐤 follows your right hand.

A warning for later: the formula itself is the same in every engine, but in a left-handed system (DirectX convention, Unity, Unreal) the result visually follows the left hand. If you port code between engines and your normals come out inside-out, this is often why.

5.3.5 Order matters

Swap 𝐚 and 𝐛 and your hand has to curl the other way, so the thumb flips:

𝐚×𝐛=−(𝐛×𝐚)

This is called anti-commutative.
With our numbers: 𝐛×𝐚=(4,5,6)×(1,2,3)=(5×3−6×2,6×1−4×3,4×2−5×1)=(3,−6,3), exactly the negative of (−3,6,−3).

This is very different from ordinary multiplication and from the dot product, where order doesn't matter.
In graphics, swapping the two arguments of a cross product turns a normal inside-out, and that is one of the most common bugs there is.

5.3.6 The length: area of a parallelogram

Now the length.
There is an identity (called Lagrange's identity) that you can check by multiplying everything out, if you are patient:

‖𝐚×𝐛‖2=‖𝐚‖2‖𝐛‖2−(𝐚⋅𝐛)2

Let's at least check it with our example.
‖(−3,6,−3)‖2=9+36+9=54.
On the right side: ‖𝐚‖2=1+4+9=14, ‖𝐛‖2=16+25+36=77, 𝐚⋅𝐛=4+10+18=32, so 14×77−322=1078−1024=54. It matches.

Now replace the dot product with its geometric form from chapter 4, 𝐚⋅𝐛=‖𝐚‖‖𝐛‖cosθ:

‖𝐚×𝐛‖2=‖𝐚‖2‖𝐛‖2−‖𝐚‖2‖𝐛‖2cos2θ=‖𝐚‖2‖𝐛‖2(1−cos2θ)

From the unit circle in chapter 1 we know sin2θ+cos2θ=1 (that's Pythagoras on the unit circle), so 1−cos2θ=sin2θ.
Taking the square root (for θ between 0 and 180°, sinθ is never negative):

‖𝐚×𝐛‖=‖𝐚‖‖𝐛‖sinθ

What does that number mean?
Draw the parallelogram with sides 𝐚 and 𝐛.
Its area is base times height.
The base is ‖𝐚‖, and the height is how far the tip of 𝐛 is above the base line, which is ‖𝐛‖sinθ:

The parallelogram spanned by a = 3, 0, 0 and b = 2, 2, 0 with height 2 and area 6

So the length of the cross product is the area of the parallelogram spanned by 𝐚 and 𝐛.
A triangle with sides 𝐚 and 𝐛 is half of that parallelogram, so its area is 12‖𝐚×𝐛‖.

Worked example: 𝐚=(3,0,0) and 𝐛=(2,2,0).

𝐚×𝐛=(0×0−0×2,0×2−3×0,3×2−0×2)=(0,0,6)

The length is 6.
Check with the picture: the base is 3 long and the tip of 𝐛 is 2 above the x axis, so the parallelogram has area 3×2=6.
Check with the formula: ‖𝐚‖=3, ‖𝐛‖=22, θ=45°, sin45°=22, so 3×22×22=3×2=6.
The triangle O, a, b has area 3.

5.3.7 Parallel vectors give zero

If 𝐚 and 𝐛 point in the same (or exactly opposite) direction, θ is 0 or 180°, sinθ=0, and the cross product is the zero vector.
That makes sense: two parallel pencils don't define a table, so there is no "up".

(1,2,3)×(2,4,6)=(2×6−3×4,3×2−1×6,1×4−2×2)=(0,0,0)

Remember this, because it causes a real bug in camera code (section 5.4.3).

5.3.8 What about 2D?

In 2D there is no real cross product, but there is a very useful leftover.
Put two 2D vectors into 3D with z=0 and cross them:

(ax,ay,0)×(bx,by,0)=(ay×0−0×by,0×bx−ax×0,axby−aybx)=(0,0,axby−aybx)

Only the z component survives.
That single number is often called the "2D cross product" (or perp-dot product):

𝐚×𝐛=axby−aybx(2D, a scalar)

Its sign says which way you turn to get from 𝐚 to 𝐛: positive means counter-clockwise (left turn), negative means clockwise (right turn), zero means parallel.
We'll use it in section 5.4.5.

5.4 Use in graphics programming

5.4.1 The face normal of a triangle

A triangle is given by three points 𝐩0,𝐩1,𝐩2.
Two of its edges, both starting at 𝐩0, lie flat in the triangle's surface:

𝐞1=𝐩1−𝐩0,𝐞2=𝐩2−𝐩0

Their cross product is perpendicular to the surface: that's the face normal.
Normalize it (chapter 3) and you have the unit normal needed for lighting (chapter 4):

𝐧^=𝐞1×𝐞2‖𝐞1×𝐞2‖

Worked example: 𝐩0=(1,0,0), 𝐩1=(0,1,0), 𝐩2=(0,0,1).
This triangle cuts diagonally across the corner of the positive octant, like the corner of a box being sliced off.

𝐞1=(0,1,0)−(1,0,0)=(−1,1,0)𝐞2=(0,0,1)−(1,0,0)=(−1,0,1)𝐞1×𝐞2=(1×1−0×0,0×(−1)−(−1)×1,(−1)×0−1×(−1))=(1−0,0+1,0+1)=(1,1,1)

Check: (1,1,1)⋅(−1,1,0)=0 and (1,1,1)⋅(−1,0,1)=0. Perpendicular to both edges.
The length is 3≈1.7321, so:

𝐧^=13(1,1,1)≈(0.5774,0.5774,0.5774)

It points away from the origin, out of the "box corner", as you'd expect.
And as a bonus, the triangle's area is half the length of the cross product: 32≈0.8660.
(Each side of this triangle is 2 long, and an equilateral triangle with side s has area 34s2=34×2=32. It matches.)

5.4.2 Winding order and backface culling

Which of the two sides of a triangle is the "front"?
The cross product decides it from the order of the vertices.
If you look at the triangle and its vertices go around counter-clockwise, then (𝐩1−𝐩0)×(𝐩2−𝐩0) points towards you (right-hand rule: fingers along the first edge, curl towards the second, thumb towards you).

A triangle p0, p1, p2 in counter-clockwise order with its normal pointing out of the screen

If you list the same three points in the other order, 𝐩0,𝐩2,𝐩1, the cross product flips (anti-commutative!) and the normal points away from you.
With our example triangle: 𝐞2×𝐞1=(−1,−1,−1).

This order is called the winding order, and 3D models are usually exported so that every triangle is counter-clockwise when seen from the outside.
The GPU uses this to skip the triangles facing away from the camera (backface culling), which in a closed model are always hidden behind the front side, so roughly half the triangles never need to be shaded.

  • In OpenGL, the front face is counter-clockwise by default (glFrontFace(GL_CCW)), and culling is enabled with glEnable(GL_CULL_FACE) plus glCullFace(GL_BACK).
  • In Vulkan, you set frontFace and cullMode in the pipeline's rasterization state. With the y-flipping Vulkan projection from chapter 12, VK_FRONT_FACE_COUNTER_CLOCKWISE gives the same convention as OpenGL.

The GPU does this test on screen, in 2D, after projection, using the 2D cross product from section 5.3.8: the sign of the triangle's screen-space area tells it the winding.
If your model suddenly looks "inside-out" (you see the inner walls and not the outer ones), the winding order is reversed somewhere: in the exporter, in a mirrored transform (chapter 10 explains why mirroring flips the winding), or in a swapped cross product.

5.4.3 Building a basis: right and up from forward

A camera (or a character, or a missile) needs three perpendicular unit vectors: forward, right and up.
Usually we only know where it should look, the forward direction 𝐟^, and which way is roughly "up" in the world, 𝐮world=(0,1,0).
The cross product builds the rest:

𝐫^=𝐟^×𝐮world‖𝐟^×𝐮world‖,𝐮^=𝐫^×𝐟^

The first line gives a "right" vector perpendicular to forward and to world up.
The second line gives the camera's own "up", which is perpendicular to forward and right (if the camera looks a bit down, its up tilts forward, unlike the world's up).
Since 𝐫^ and 𝐟^ are perpendicular unit vectors, sin90°=1 and their cross product already has length 1, so no second normalization is needed.
Three perpendicular unit vectors like these are called an orthonormal basis.

Worked example: the camera looks along 𝐟^=(0.6,0,−0.8) (mostly into the screen, a bit to the right).

𝐟^×𝐮world=(0×0−(−0.8)×1,(−0.8)×0−0.6×0,0.6×1−0×0)=(0.8,0,0.6)‖(0.8,0,0.6)‖=0.64+0.36=1,so 𝐫^=(0.8,0,0.6)𝐮^=𝐫^×𝐟^=(0×(−0.8)−0.6×0,0.6×0.6−0.8×(−0.8),0.8×0−0×0.6)=(0,0.36+0.64,0)=(0,1,0)

That makes sense: the camera isn't tilted up or down, so its up is the world's up.
For the plain case 𝐟^=(0,0,−1) (looking straight down −Z) you get 𝐫^=(1,0,0), the +X axis, exactly as our coordinate system says.

Top view of the camera basis: forward f = 0.6, 0, −0.8 and right r = 0.8, 0, 0.6 at a right angle

This is the core of the lookAt function, which builds the view matrix in chapter 11.

What goes wrong when forward is parallel to up.
If the camera looks straight up, 𝐟^=(0,1,0), then forward and world up are parallel, and from section 5.3.7 we know the cross product is (0,0,0).
There is no "right" anymore: if you look straight up at the sky, any direction could be your right, depending on how you turned.
Our normalize returns the zero vector (shaders would give NaN), the basis collapses, and the screen shows garbage or nothing.
The usual fixes are to stop the camera from ever looking exactly straight up or down (clamp the pitch to something like ±89°, chapter 11), or to switch to a different helper "up" vector, such as (0,0,1), when forward gets too close to world up.

5.4.4 Triangle areas

Because half the length of the cross product is a triangle's area, it's handy whenever area matters:

  • Scattering things on a mesh: to place grass, particles or random sample points evenly over a model, you pick each triangle with a probability proportional to its area. If a mesh has two triangles with areas 3 and 1, the first should get 75% of the points and the second 25%. Otherwise small triangles get crowded and large ones look empty.
  • Surface area of a whole model is the sum of all triangle areas.
  • Weighted normals: a smooth vertex normal is often the sum of the unnormalized face normals around the vertex. Since an unnormalized cross product is "normal times twice the area", bigger triangles automatically get more say, for free.
  • Mesh cleanup: triangles with (almost) zero area are degenerate; they have no usable normal and should usually be removed.

5.4.5 Left or right of a line, and inside a triangle

Take a line going from point 𝐚 to point 𝐛 in 2D.
Is a point 𝐩 to its left or its right?
Compute the 2D cross product of the line direction 𝐛−𝐚 with 𝐩−𝐚:

s=(bx−ax)(py−ay)−(by−ay)(px−ax)

Positive means left, negative means right, zero means on the line.

Worked example: the line from 𝐚=(1,1) to 𝐛=(5,3), so 𝐛−𝐚=(4,2).

Point 𝐩−𝐚 s Result
(2,4) (1,3) 4×3−2×1=10 left
(4,1) (3,0) 4×0−2×3=−6 right
(3,2) (2,1) 4×1−2×2=0 on the line

Points to the left of, to the right of and on the line from a = 1, 1 to b = 5, 3

Do this for all three edges of a counter-clockwise triangle, and a point is inside the triangle exactly when it is on the left of all three edges.
For the triangle (0,0),(4,0),(0,4) the point (1,1) gives 4,8,4 (all positive, inside), while (3,3) gives 12,−8,12 (one negative, outside).
This is, in essence, how GPUs rasterize: for every pixel near a triangle they evaluate these three "edge functions" and fill the pixel if all three agree.
Games use the same test for "is the mouse over this 2D shape?", for AI steering ("is the target to my left or right, so which way do I turn?") and for checking whether a polygon is convex.

5.4.6 Flat shading in a shader

Sometimes you want the faceted, low-poly look where every triangle has one flat color.
One elegant way to do it needs no normals at all in the mesh: the fragment shader reconstructs the face normal with a cross product.

The functions ddx/ddy (Slang and HLSL) and dFdx/dFdy (GLSL) tell you how much a value changes from this pixel to its neighbor one pixel to the right, and one pixel row further.
GPUs can compute this because they always shade pixels in small 2×2 blocks.
If the value is the world position, both differences are small steps along the triangle's surface, so their cross product is the face normal.

struct Scene {
  float3 lightDir;  // unit vector towards the light
  float3 cameraPos;
  float3 albedo;
};
ConstantBuffer<Scene> scene;

[shader("fragment")]
float4 fragmentMain(float3 worldPos : TEXCOORD0) : SV_Target {
  // two steps along the surface -> their cross product is the face normal
  float3 n = normalize(cross(ddx(worldPos), ddy(worldPos)));
  // the sign depends on the window's y direction, so make n face the camera
  if (dot(n, scene.cameraPos - worldPos) < 0.0) n = -n;
  float diffuse = max(dot(n, scene.lightDir), 0.0);
  return float4(scene.albedo * diffuse, 1.0);
}
#version 450

layout(location = 0) in vec3 worldPos;
layout(location = 0) out vec4 outColor;

layout(set = 0, binding = 0) uniform Scene {
  vec3 lightDir;  // unit vector towards the light
  vec3 cameraPos;
  vec3 albedo;
};

void main() {
  // two steps along the surface -> their cross product is the face normal
  vec3 n = normalize(cross(dFdx(worldPos), dFdy(worldPos)));
  // the sign depends on the window's y direction, so make n face the camera
  if (dot(n, cameraPos - worldPos) < 0.0) n = -n;
  float diffuse = max(dot(n, lightDir), 0.0);
  outColor = vec4(albedo * diffuse, 1.0);
}
struct Scene {
  float3 lightDir;  // unit vector towards the light
  float3 cameraPos;
  float3 albedo;
};
ConstantBuffer<Scene> scene;

float4 fragmentMain(float3 worldPos : TEXCOORD0) : SV_Target {
  // two steps along the surface -> their cross product is the face normal
  float3 n = normalize(cross(ddx(worldPos), ddy(worldPos)));
  // the sign depends on the window's y direction, so make n face the camera
  if (dot(n, scene.cameraPos - worldPos) < 0.0) n = -n;
  float diffuse = max(dot(n, scene.lightDir), 0.0);
  return float4(scene.albedo * diffuse, 1.0);
}

Why the if?
In OpenGL the window's y axis points up, but in Vulkan the framebuffer's y axis points down, so "one pixel row further" goes in opposite directions and the cross product flips sign between the two APIs.
Instead of remembering which is which, I simply flip the normal towards the camera using the dot-product facing test from chapter 4.
The other common way to get flat shading is to compute face normals on the CPU with triangleNormal (below) and pass them without interpolation (the nointerpolation modifier in Slang and HLSL, the flat qualifier in GLSL).

5.5 Other uses

The cross product was used in physics long before computer graphics existed.

  • Torque: turning a wrench. If you push with force 𝐅 at a point 𝐫 from the bolt, the torque is 𝝉=𝐫×𝐅. Its direction is the axis the bolt turns around (right-hand rule) and its length is how hard it turns. A wrench 𝐫=(0.5,0,0) meters long, pushed with 𝐅=(0,10,0) newtons, gives 𝝉=(0,0,0.5×10−0×0)=(0,0,5) newton-meters: a counter-clockwise turn around the z axis. The sinθ explains why pushing at a right angle to the wrench works best, and pushing along it does nothing.
  • Angular momentum 𝐋=𝐫×𝐩 and the velocity of a point on a spinning object 𝐯=𝝎×𝐫 (𝝎, omega, is the rotation axis scaled by the spinning speed). Physics engines use both every frame for rigid bodies.
  • Lorentz force: a charged particle moving with velocity 𝐯 through a magnetic field 𝐁 feels the force q𝐯×𝐁. The force is always perpendicular to the motion, so the particle moves in circles. Electric motors, particle accelerators and old CRT televisions all rely on this.
  • GIS and maps: the area of a polygon (a country, a field, a building footprint) is half the sum of the 2D cross products of consecutive corner points, the "shoelace formula". For the rectangle (0,0),(4,0),(4,3),(0,3): 0+12+12+0=24, half of it is 12, which is indeed 4×3. The sign tells you whether the corners are listed counter-clockwise (positive) or clockwise (negative), which many map file formats care about.
  • Robotics: each joint of a robot arm turns around an axis, and how fast the hand moves when a joint turns is (joint axis) × (vector from joint to hand).
  • Navigation and aviation: the "right wing" direction of an aircraft is forward × up, exactly like our camera basis.

5.6 Code

The cross product goes into linalg.hh, after normalize:

// 外積 / cross product (chapter 5)
inline Vec3 cross(Vec3 a, Vec3 b) {
  return {
    a.y * b.z - a.z * b.y,
    a.z * b.x - a.x * b.z,
    a.x * b.y - a.y * b.x,
  };
}

It's the formula, line by line: "yz − zy", "zx − xz", "xy − yx".
Only a Vec3 version exists, because the cross product only exists in 3D.

The triangle helpers and the 2D side test are small enough to define in the test program:

#include "linalg.hh"
#include <cstdio>

// Unit normal of the triangle abc (counter-clockwise = front side).
Vec3 triangleNormal(Vec3 a, Vec3 b, Vec3 c) {
  return normalize(cross(b - a, c - a));
}

// Area of the triangle abc.
float triangleArea(Vec3 a, Vec3 b, Vec3 c) {
  return 0.5f * length(cross(b - a, c - a));
}

// 2D: > 0 if p is left of the line a->b, < 0 if right, 0 if on it.
float side(Vec2 a, Vec2 b, Vec2 p) {
  Vec2 ab = b - a;
  Vec2 ap = p - a;
  return ab.x * ap.y - ab.y * ap.x;
}

void print(const char *name, Vec3 v) {
  printf("%-16s = (%g, %g, %g)\n", name, v.x, v.y, v.z);
}

int main() {
  Vec3 a{1.0f, 2.0f, 3.0f};
  Vec3 b{4.0f, 5.0f, 6.0f};
  Vec3 c = cross(a, b);
  print("cross(a, b)", c);
  print("cross(b, a)", cross(b, a));
  printf("dot(c, a), dot(c, b) = %g, %g\n", dot(c, a), dot(c, b));
  print("i x j", cross({1.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f}));
  print("a x 2a", cross(a, 2.0f * a));

  // Triangle with counter-clockwise vertices seen from (1, 1, 1)
  Vec3 p0{1.0f, 0.0f, 0.0f};
  Vec3 p1{0.0f, 1.0f, 0.0f};
  Vec3 p2{0.0f, 0.0f, 1.0f};
  Vec3 n = triangleNormal(p0, p1, p2);
  printf("normal           = (%.4f, %.4f, %.4f)\n", n.x, n.y, n.z);
  Vec3 nf = triangleNormal(p0, p2, p1); // swapped winding
  printf("swapped winding  = (%.4f, %.4f, %.4f)\n", nf.x, nf.y, nf.z);
  printf("area             = %.4f\n", triangleArea(p0, p1, p2));

  // Right and up vectors from a forward vector
  Vec3 forward{0.6f, 0.0f, -0.8f};
  Vec3 worldUp{0.0f, 1.0f, 0.0f};
  Vec3 right = normalize(cross(forward, worldUp));
  Vec3 up = cross(right, forward);
  print("right", right);
  print("up", up);
  print("right if f = up", normalize(cross(worldUp, worldUp)));

  // Left or right of the line from (1, 1) to (5, 3)?
  Vec2 l0{1.0f, 1.0f};
  Vec2 l1{5.0f, 3.0f};
  printf("side (2, 4)      = %g\n", side(l0, l1, {2.0f, 4.0f}));
  printf("side (4, 1)      = %g\n", side(l0, l1, {4.0f, 1.0f}));
  printf("side (3, 2)      = %g\n", side(l0, l1, {3.0f, 2.0f}));
  return 0;
}

Expected output:

cross(a, b)      = (-3, 6, -3)
cross(b, a)      = (3, -6, 3)
dot(c, a), dot(c, b) = 0, 0
i x j            = (0, 0, 1)
a x 2a           = (0, 0, 0)
normal           = (0.5774, 0.5774, 0.5774)
swapped winding  = (-0.5774, -0.5774, -0.5774)
area             = 0.8660
right            = (0.8, -0, 0.6)
up               = (0, 1, 0)
right if f = up  = (0, 0, 0)
side (2, 4)      = 10
side (4, 1)      = -6
side (3, 2)      = 0

Yes, that says -0.
Floating-point numbers have a separate "negative zero": the y component of right is computed as (−0.8)×0−0.6×0, and (−0.8)×0 is −0 in floating point.
It is equal to 0 in every comparison (-0.0f == 0.0f is true), so it's harmless; printf just shows the sign.

5.7 Summary

  • The cross product 𝐚×𝐛 of two 3D vectors is a new vector perpendicular to both. It only exists in 3D.
  • Formula: (aybz−azby,azbx−axbz,axby−aybx). Remember "x = yz − zy" and rotate the letters.
  • Check your result: its dot product with both inputs must be 0.
  • Direction: right-hand rule. 𝐢×𝐣=𝐤, 𝐣×𝐤=𝐢, 𝐤×𝐢=𝐣.
  • Order matters: 𝐚×𝐛=−(𝐛×𝐚). Swapping the arguments flips normals.
  • Length: ‖𝐚‖‖𝐛‖sinθ = area of the parallelogram; half of it is the triangle area. Parallel vectors give the zero vector.
  • In 2D, axby−aybx tells left from right (counter-clockwise from clockwise).
  • Graphics: face normals, winding order and backface culling, right/up vectors for cameras (watch out when forward is parallel to up), triangle areas, point-in-triangle tests, flat shading.

5.8 Challenges

  1. ★ Compute (2,0,1)×(1,3,0) and check that the result is perpendicular to both vectors.
  2. ★ Using only the rules for 𝐢,𝐣,𝐤 and the distributive rule (𝐚+𝐛)×𝐜=𝐚×𝐜+𝐛×𝐜 (it holds for the cross product too), compute (𝐢+𝐣)×𝐤. Then check your answer with the component formula.
  3. ★ Find the area of the triangle with corners (0,0,0), (4,0,0) and (0,3,0) with the cross product, then check it with "base times height divided by 2".
  4. ★ Is the point (1,5) to the left or right of the line from (0,0) to (3,3)? And the point (4,2)?
  5. ★★ Use triangleNormal on the triangle (0,0,0), (2,0,0), (0,0,−2). Which way does this floor triangle face? It should print (0, 1, 0) (some zeros may show as -0, see section 5.6). Then swap the last two vertices and confirm it prints (0, -1, 0).
  6. ★★ Write bool pointInTriangle(Vec2 p, Vec2 a, Vec2 b, Vec2 c) using the side function (assume a, b, c are counter-clockwise). For the triangle {0, 0}, {4, 0}, {0, 4}, the points {1, 1}, {3, 3} and {0.5, 3} should give true, false, true.
  7. ★★★ The function pointInTriangle from challenge 6 fails if the triangle is given clockwise. How can you use the 2D cross product of the triangle's own edges to detect the winding and make the function work for both orders? What should it do for a triangle whose three points lie on one line?


コメント(0)

まだコメントはありません。