2. Vectors

In chapter 1 we described positions with coordinates like (3,2) or (2,3,4).
In this chapter we'll start treating those lists of numbers as objects we can calculate with: vectors.
Vectors are the single most used thing in graphics programming.
Positions, movement, directions, colors, texture coordinates and surface normals are all vectors, and almost every line of shader code you'll ever write works with them.

2.1 Points and vectors

Before any math, let's separate two ideas that look the same on paper but mean different things.

A point is a location: "the treasure is at (5,4)".
A vector is a displacement, a movement: "walk 4 steps east and 3 steps north".
A point answers "where?", and a vector answers "which way, and how far?".

The vector 4, 3 from point A to point B

The trip from point A to point B is the vector (4,3): 4 to the right and 3 up.
The vector itself is the straight arrow from A to B; the "4 right" and "3 up" legs in the picture are its two parts.

Here's the important bit: a vector has no fixed starting place.
"Walk 4 east and 3 north" is the same instruction whether you start at your house or at the station.
So the same vector can be drawn anywhere, and every copy is equally valid:

The same vector v drawn from two different starting points

Confusingly, we write points and vectors the same way, as lists of numbers.
The trick is that a point's numbers are really the vector from the origin to that point.
The point (5,4) means "where you end up if you start at the origin and move by the vector (5,4)".
In code, both are usually stored in the same Vec3 type, and it's up to you to remember which is which.
That distinction will become important again in chapter 9, where points and directions behave differently under translation.

2.2 Vectors as lists of numbers

A vector is written as a bold lowercase letter, like 𝐯.
Its numbers are called its components, and we name them with subscripts: vx, vy and vz are the x, y and z components of 𝐯.
In this series, vectors are written as columns:

𝐯=[vxvyvz]=[312]

Columns take up a lot of space in a sentence, so inside text I'll write the same vector as 𝐯=(3,1,2).
It still means the column.
Why columns rather than rows matters once matrices appear in chapter 6; for now, it's just how we write them.

The number of components is the vector's dimension:

  • A 2D vector (x,y): positions on a screen, texture coordinates, movement on a flat map.
  • A 3D vector (x,y,z): positions and directions in a 3D world, or an RGB color.
  • A 4D vector (x,y,z,w): an RGBA color (red, green, blue and alpha, the opacity), or the special 4-component positions we'll meet in chapter 9.

When talking about vectors in general, I'll number the components instead: 𝐯=(v1,v2,…,vn) for a vector with n components.
Nothing in this chapter cares how many components there are; every operation works the same in 2D, 3D, 4D or 100D.

One vector deserves its own name: the zero vector, with every component 0:

𝟎=(0,0,0)

It's the "don't move at all" vector.
It has no direction, which will cause us some trouble in chapter 3.

2.3 What the formulas are

Here are all the operations of this chapter at once.
Take two 3D vectors 𝐚=(ax,ay,az) and 𝐛=(bx,by,bz), and a single number s.
A single ordinary number like s is called a scalar, because, as we'll see, it scales vectors.

Addition: add matching components.

𝐚+𝐛=[ax+bxay+byaz+bz]

Subtraction: subtract matching components.

𝐚−𝐛=[ax−bxay−byaz−bz]

Negation: flip the sign of every component.

−𝐚=[−ax−ay−az]

Scalar multiplication: multiply every component by the same number.

s𝐚=[saxsaysaz]

Linear interpolation (lerp): blend from 𝐚 to 𝐛 by an amount t between 0 and 1.

lerp(𝐚,𝐛,t)=𝐚+t(𝐛−𝐚)

Notice that everything works component by component.
The x components only ever talk to x components, the y components to y components, and so on.
That's what makes vectors so easy to compute with.

2.4 How it works

Addition: tip to tail

Adding two vectors means doing one movement after the other.
Walk along 𝐚, then from where you ended up, walk along 𝐛.
The shortcut from where you started to where you finished is 𝐚+𝐛:

Tip to tail: a followed by b gives a + b

This is called the tip-to-tail rule: put the tail of 𝐛 at the tip of 𝐚.
(The picture uses the vectors from the worked example below, but the rule is the same whichever way the arrows point.)
The horizontal moves add up with the horizontal moves, and the vertical moves add up with the vertical moves, which is exactly why addition is component-wise.

Worked example with 𝐚=(3,1) and 𝐛=(1,2):

𝐚+𝐛=[31]+[12]=[3+11+2]=[43]

Walking 3 right and 1 up, then 1 right and 2 up, leaves you 4 right and 3 up from where you started.
The same works in 3D with 𝐚=(3,1,2) and 𝐛=(1,2,−1):

𝐚+𝐛=[3+11+22+(−1)]=[431]

You can also add a vector to a point: a point plus a movement gives a new point.
Starting at the point (1,1) and moving by (4,3) lands you on (1+4,1+3)=(5,4), which is the picture from section 2.1.

Subtraction: the arrow from A to B

Subtraction answers the question "how do I get from here to there?".
If 𝐚 and 𝐛 are the positions of two points A and B, then 𝐛−𝐚 is the vector from A to B:

b − a is the arrow from A to B

Why?
Because to get from A to B you can go from A back to the origin O (that's −𝐚), then from O to B (that's 𝐛).
Together: −𝐚+𝐛=𝐛−𝐚.
A good way to remember the order: destination minus start.

Worked example: A is at (1,1) and B is at (5,4).

𝐛−𝐚=[5−14−1]=[43]

That's the same (4,3) we saw in section 2.1.
Check it by going back the other way: 𝐚+(𝐛−𝐚)=(1+4,1+3)=(5,4), which is B.
If you subtract in the wrong order, you get 𝐚−𝐛=(−4,−3): the arrow from B back to A.
Getting this order backwards is a classic bug: the enemy runs away from the player instead of towards them.

A 3D example: the player stands at 𝐩=(2,0,5) and an enemy at 𝐞=(6,0,2).
The vector from the player to the enemy is

𝐞−𝐩=[6−20−02−5]=[40−3]

So the enemy is 4 units to the right and 3 units further away from the viewer (remember, +Z points towards the viewer, so −3 means away).
In chapter 3 we'll find out how far that is, and turn it into a direction the player can aim along.

Negation: the same arrow, backwards

Negating a vector flips every component's sign, which flips the arrow around without changing its length:

−[40−3]=[−403]

If (4,0,−3) points from the player to the enemy, (−4,0,3) points from the enemy to the player.
Subtraction is really just adding the negation: 𝐚−𝐛=𝐚+(−𝐛).

Scalar multiplication: stretching and flipping

Multiplying a vector by a scalar s multiplies every component by s.
The effect on the arrow:

The vectors v, 2v, 0.5v, 0v, −v and −2v

  • If s>1, the arrow gets longer.
  • If 0<s<1, it gets shorter.
  • If s=0, it collapses into the zero vector.
  • If s<0, it flips around and points the other way.

The direction never changes other than flipping; only the length does.
That's where the word scalar comes from: it scales vectors.

Worked example with 𝐚=(3,1,2):

2𝐚=[2×32×12×2]=[624]0.5𝐚=[0.5×30.5×10.5×2]=[1.50.51]

Dividing a vector by a scalar is the same as multiplying by one over it: 𝐚2=12𝐚=0.5𝐚.
Negation is scalar multiplication by −1: −𝐚=(−1)𝐚.

Notice what we don't have: there's no standard "vector times vector" in this chapter.
Multiplying two vectors can mean several different things, and the two famous ones, the dot product and the cross product, get their own chapters (4 and 5).

Properties

Because every operation is just ordinary arithmetic on each component, vectors obey the rules you already know from numbers.
For any vectors 𝐚,𝐛,𝐜 and scalars s,t:

  • 𝐚+𝐛=𝐛+𝐚 (the order of adding doesn't matter)
  • (𝐚+𝐛)+𝐜=𝐚+(𝐛+𝐜) (neither does the grouping)
  • 𝐚+𝟎=𝐚 (adding the zero vector changes nothing)
  • 𝐚+(−𝐚)=𝟎 (a vector and its negation cancel out)
  • s(𝐚+𝐛)=s𝐚+s𝐛 (scaling a sum is the sum of the scaled vectors)
  • (s+t)𝐚=s𝐚+t𝐚
  • s(t𝐚)=(st)𝐚
  • 1𝐚=𝐚

Let's check one with numbers, 𝐚=(3,1), 𝐛=(1,2) and s=2:

2(𝐚+𝐛)=2[43]=[86]2𝐚+2𝐛=[62]+[24]=[86]

Same answer.
These rules are what let us rearrange vector formulas freely, just like ordinary algebra.

2.5 Linear combinations and the standard basis

Once you can scale vectors and add them, you can combine them: scale a few vectors, then add the results.
That's called a linear combination:

s𝐚+t𝐛

Worked example with 𝐚=(1,2), 𝐛=(3,−1), s=2 and t=3:

2[12]+3[3−1]=[24]+[9−3]=[111]

Now pick the simplest possible vectors to combine: arrows of length 1 pointing exactly along each axis.
In 3D there are three of them, and they have their own names:

𝐢=[100]𝐣=[010]𝐤=[001]

They are called the standard basis vectors: 𝐢 points along +X, 𝐣 along +Y and 𝐤 along +Z.
(Some books call them 𝐞1,𝐞2,𝐞3; same thing.)
In 2D we only need 𝐢=(1,0) and 𝐣=(0,1).

Here's the punchline: every vector is a linear combination of the basis vectors, and its components are the amounts:

[xyz]=x𝐢+y𝐣+z𝐤

In 2D, the vector (3,2) is literally "three steps of 𝐢, then two steps of 𝐣":

v = 3i + 2j as three steps of i and two steps of j

Let's verify it in 3D with (2,−1,3), writing out every step:

2𝐢+(−1)𝐣+3𝐤=[200]+[0−10]+[003]=[2+0+00−1+00+0+3]=[2−13]

This might look like a pointless way of saying the same thing twice.
It isn't: it's the seed of the most important idea in the whole series.
If you replace 𝐢, 𝐣 and 𝐤 with other vectors, the same recipe x𝐢+y𝐣+z𝐤 moves every vector somewhere new: it rotates, stretches or skews the whole space.
Writing those replacement vectors side by side gives you a matrix, and that's exactly how we'll introduce matrices in chapter 6.

2.6 Linear interpolation

Very often in graphics we want something in between two values: a position halfway along a path, a color 30% of the way from red to blue, a camera smoothly gliding to its target.
The tool for this is linear interpolation, almost always shortened to lerp:

lerp(𝐚,𝐛,t)=𝐚+t(𝐛−𝐚)

Read it with the tools from this chapter: 𝐛−𝐚 is the arrow from 𝐚 to 𝐛.
Scale it by t to walk only part of the way, and add it to 𝐚 to start from 𝐚.

Points between a and b for t = 0, 0.25, 0.5, 0.75 and 1

  • At t=0 you get 𝐚+0=𝐚.
  • At t=1 you get 𝐚+(𝐛−𝐚)=𝐛.
  • At t=0.5 you get the midpoint, the average of the two.

Worked example: 𝐚=(2,4,0), 𝐛=(10,0,4) and t=0.25.
First the arrow from 𝐚 to 𝐛:

𝐛−𝐚=[10−20−44−0]=[8−44]

Then a quarter of it:

0.25[8−44]=[2−11]

Then add it to the start:

[240]+[2−11]=[431]

With t=0.5 the same steps give (2,4,0)+(4,−2,2)=(6,2,2), the midpoint.

If you expand the formula, you get a second form that's just as common:

𝐚+t(𝐛−𝐚)=𝐚+t𝐛−t𝐚=(1−t)𝐚+t𝐛

This version reads as a weighted average: "take 1−t of 𝐚 and t of 𝐛".
Check it with our example: 0.75(2,4,0)+0.25(10,0,4)=(1.5,3,0)+(2.5,0,1)=(4,3,1).
Same answer.
The two forms are equal in exact math; with floating-point numbers, the second one is guaranteed to land exactly on 𝐛 at t=1, while the first can be off by a tiny rounding error.
For graphics, either is fine.

What happens outside 0 to 1?
With t=1.5 we get (2,4,0)+1.5(8,−4,4)=(2,4,0)+(12,−6,6)=(14,−2,6): a point past 𝐛, on the same line.
That's called extrapolation.
It's sometimes useful (predicting where a moving object will be), but usually it's a bug, so code often clamps t into the range 0 to 1 first.

The "linear" in lerp means t moves you along a straight line at a steady rate.
If you want motion that starts slowly and speeds up, you keep the lerp and change how t grows over time; that's what animation easing curves do.

2.7 Use in graphics programming

Positions and velocities

A moving object has a position 𝐩 (a point) and a velocity 𝐯 (a vector: how far it moves per second, and in which direction).
Each frame, the game moves it by its velocity times the time that has passed since the last frame, Δt (read "delta t"; Δ is the Greek capital delta, used for "a change in"):

𝐩←𝐩+𝐯Δt

The arrow ← means "replace the old value with the new one", like = in code.
It's a scalar multiplication followed by an addition, nothing more.

Worked example: an object starts at 𝐩=(1,2,0) with velocity 𝐯=(4,0,−2) units per second, and we step by Δt=0.5 seconds.

𝐩+𝐯Δt=[120]+0.5[40−2]=[120]+[20−1]=[32−1]

The next two steps give (5,2,−2) and (7,2,−3).

Three position updates, each moving by v Δt

Why multiply by Δt instead of adding 𝐯 every frame?
Because frame rates vary.
Say 𝐯=(6,0,0).
At 60 frames per second, Δt=160 and each frame moves the object by (0.1,0,0); after 60 frames it has moved 6 units.
At 30 frames per second, Δt=130, each frame moves it (0.2,0,0), and after 30 frames it has also moved 6 units.
One second of game time is the same distance regardless of how fast the computer is.

Acceleration works exactly the same way, one level up.
Gravity is the vector 𝐠=(0,−9.8,0) meters per second per second, and each frame we update the velocity first, then the position:

𝐯←𝐯+𝐠Δt𝐩←𝐩+𝐯Δt

That's a complete (if simple) physics simulation for a thrown ball, written with nothing but this chapter's operations.

Offsets

Many positions in a game are "somewhere relative to something else": the muzzle of a gun, the spot above a character's head where the name tag goes, the camera following behind the player.
These are a point plus an offset vector.
If the player stands at (10,0,4) and the name tag should float 2 units above them:

[1004]+[020]=[1024]

A name tag only needs "up", which doesn't change when the player turns.
A gun muzzle offset like "0.5 forward" does change when the player turns around; rotating offsets is what chapter 8 is for.

Colors as vectors

A color on screen is three numbers: how much red, green and blue light to emit, usually from 0 to 1.
That's a 3D vector, and our operations have direct visual meanings:

  • Adding colors adds light. A dim orange (0.2,0.1,0.0) plus a gray ambient light (0.3,0.3,0.3) gives (0.5,0.4,0.3). This is how the contributions of several lights are combined.
  • Scaling a color changes its brightness. 0.5×(0.8,0.6,0.4)=(0.4,0.3,0.2) is the same hue at half brightness.
  • Lerping fades between colors. From red (1,0,0) to blue (0,0,1) at t=0.25: (1,0,0)+0.25(−1,0,1)=(0.75,0,0.25), a reddish purple.

Shaders also use one more operation that isn't standard vector math: multiplying two vectors component by component.
For colors, it's called tinting or modulating, and it's how a texture color gets filtered by a light color or a tint:

[0.80.60.4] tinted by [1.00.50.5]=[0.8×1.00.6×0.50.4×0.5]=[0.80.30.2]

A tint of (1.0,0.5,0.5) keeps all the red but halves the green and blue, so the result looks redder.
Here is a small shader function that tints a sprite and then flashes it towards a color when it gets hit:

float3 shadeSprite(float3 texColor, float3 tint, float3 flashColor, float flash) {
  float3 tinted = texColor * tint; // 成分毎の掛け算 / component-wise multiplication
  return lerp(tinted, flashColor, saturate(flash));
}
vec3 shadeSprite(vec3 texColor, vec3 tint, vec3 flashColor, float flash) {
  vec3 tinted = texColor * tint; // 成分毎の掛け算 / component-wise multiplication
  return mix(tinted, flashColor, clamp(flash, 0.0, 1.0));
}
float3 shadeSprite(float3 texColor, float3 tint, float3 flashColor, float flash) {
  float3 tinted = texColor * tint; // 成分毎の掛け算 / component-wise multiplication
  return lerp(tinted, flashColor, saturate(flash));
}

Slang and HLSL call linear interpolation lerp and GLSL calls it mix, but they all compute exactly 𝐚+t(𝐛−𝐚).
saturate(x) in Slang and HLSL clamps a value into the range 0 to 1, which is what GLSL's clamp(x, 0.0, 1.0) does.
With the tinted color from above, a white flash (1,1,1) and flash = 0.5:

[0.80.30.2]+0.5([111]−[0.80.30.2])=[0.80.30.2]+0.5[0.20.70.8]=[0.90.650.6]

Animate flash from 1 down to 0 over a few frames and you get the classic "damage blink".

Texture coordinates

UV coordinates (chapter 1) are 2D vectors, so all of this applies to them too.
Adding a vector that grows with time makes a texture scroll, which is how a lot of water, lava and conveyor-belt effects are done:

float2 scrollUv(float2 uv, float2 speed, float time) {
  return frac(uv + speed * time);
}
vec2 scrollUv(vec2 uv, vec2 speed, float time) {
  return fract(uv + speed * time);
}
float2 scrollUv(float2 uv, float2 speed, float time) {
  return frac(uv + speed * time);
}

speed * time is a scalar multiplication, and adding it to uv shifts the texture.
frac (Slang and HLSL) and fract (GLSL) keep only the part after the decimal point, so the UV wraps around from 1 back to 0.
For example, 𝐮𝐯=(0.9,0.5), speed (0.1,0) and time 2 gives (0.9,0.5)+(0.2,0)=(1.1,0.5), which wraps to (0.1,0.5).

Vectors in shaders: swizzling and component-wise math

Shading languages have vectors built in: float2, float3, float4 in Slang and HLSL, and vec2, vec3, vec4 in GLSL.
Addition, subtraction and scalar multiplication work with the ordinary +, - and * operators.
On two vectors of the same size, * and / work component by component, as in the tint example above.

Shaders also let you pick, reorder and repeat components with a feature called swizzling.
The components are named x y z w, and for colors you can use r g b a instead (the same four slots under different names):

float3 swizzleDemo(float4 v) {
  float3 a = v.xyz; // the first three components
  float3 b = v.zyx; // reversed
  float3 c = v.xxy; // components may repeat
  return a + b + c;
}

float4 makeRedder(float4 color) {
  color.r = 1.0;   // write one component
  color.gb *= 0.5; // write two components at once
  return color;
}
vec3 swizzleDemo(vec4 v) {
  vec3 a = v.xyz; // the first three components
  vec3 b = v.zyx; // reversed
  vec3 c = v.xxy; // components may repeat
  return a + b + c;
}

vec4 makeRedder(vec4 color) {
  color.r = 1.0;   // write one component
  color.gb *= 0.5; // write two components at once
  return color;
}
float3 swizzleDemo(float4 v) {
  float3 a = v.xyz; // the first three components
  float3 b = v.zyx; // reversed
  float3 c = v.xxy; // components may repeat
  return a + b + c;
}

float4 makeRedder(float4 color) {
  color.r = 1.0;   // write one component
  color.gb *= 0.5; // write two components at once
  return color;
}

With 𝐯=(1,2,3,4): v.xyz is (1,2,3), v.zyx is (3,2,1) and v.xxy is (1,1,2).
Adding them component by component gives (1+3+1,2+2+1,3+1+2)=(5,5,6).

Two rules to remember.
First, don't mix the two naming sets in one swizzle: GLSL rejects v.xg with an error, and even where a compiler accepts it, it's confusing to read.
Second, when writing to a swizzle, a component can't appear twice: v.xx = ... is an error in all three languages, because which value would win?
Swizzles are free on the GPU, so use them as much as you like.

2.8 Other uses

Vectors appear wherever several numbers belong together and get added or scaled as a group:

  • Physics: forces. Forces are vectors, and when several act on an object, the total force is their sum. A box pushed with (10,0) newtons, pulled down by gravity with (0,−5), and dragged by a rope with (−4,2) feels a net force of (10+0−4,0−5+2)=(6,−3).
  • Wind and navigation. A plane flying at (200,0) km/h through the air, in a wind blowing at (−20,15) km/h, moves over the ground at (200−20,0+15)=(180,15) km/h. Pilots and sailors add these vectors every day.
  • Machine learning: feature vectors. A house can be described as (120,3,15): 120 m², 3 rooms, 15 years old. Data like this is stored as vectors, often with hundreds of components. The average of two houses (120,3,15) and (80,2,25) is a lerp with t=0.5: (100,2.5,20).
  • Shopping. A basket with 3 apples, 1 bread and 2 milk is the vector (3,1,2). Combining it with a friend's (2,0,1) is vector addition: (5,1,3). Doubling the order is scalar multiplication: (6,2,4). Working out the total price is the dot product of chapter 4.
  • Audio. A stereo sample is a 2D vector (left, right). Mixing two sounds adds their vectors, a volume knob is a scalar multiplication, and a crossfade between two songs is a lerp.

2.9 Code

Now let's add vectors to linalg.hh.
Put the following below the angle helpers from chapter 1:

//------------------------------------------
// ベクトル / Vectors (chapters 2–5)
//------------------------------------------

struct Vec2 {
  float x = 0.0f, y = 0.0f;
};

struct Vec3 {
  float x = 0.0f, y = 0.0f, z = 0.0f;
};

struct Vec4 {
  float x = 0.0f, y = 0.0f, z = 0.0f, w = 0.0f;
};

// 足し算・引き算 / addition and subtraction (chapter 2)
inline Vec2 operator+(Vec2 a, Vec2 b) { return {a.x + b.x, a.y + b.y}; }
inline Vec2 operator-(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.y}; }
inline Vec3 operator+(Vec3 a, Vec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
inline Vec3 operator-(Vec3 a, Vec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
inline Vec4 operator+(Vec4 a, Vec4 b) { return {a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w}; }
inline Vec4 operator-(Vec4 a, Vec4 b) { return {a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w}; }
inline Vec3 operator-(Vec3 v) { return {-v.x, -v.y, -v.z}; }

// スカラー倍 / scalar multiplication (chapter 2)
inline Vec2 operator*(float s, Vec2 v) { return {s * v.x, s * v.y}; }
inline Vec3 operator*(float s, Vec3 v) { return {s * v.x, s * v.y, s * v.z}; }
inline Vec4 operator*(float s, Vec4 v) { return {s * v.x, s * v.y, s * v.z, s * v.w}; }
inline Vec3 operator*(Vec3 v, float s) { return s * v; }
inline Vec3 operator/(Vec3 v, float s) { return {v.x / s, v.y / s, v.z / s}; }

// 線型補間 / linear interpolation (chapter 2)
inline Vec3 lerp(Vec3 a, Vec3 b, float t) { return a + t * (b - a); }

Some notes:

  • Each vector is a plain struct of floats. The = 0.0f defaults mean that Vec3 v; is the zero vector, and Vec3 a{3.0f, 1.0f, 2.0f}; sets the components in order.
  • The functions take vectors by value. A Vec3 is only 12 bytes, so copying it is as cheap as passing a pointer, and compilers optimize this very well.
  • inline lets us define functions in a header that's included from several .cc files without the linker complaining about duplicates.
  • Each operator is the formula from section 2.3, written out component by component. return {a.x + b.x, a.y + b.y}; builds the result vector directly.
  • Vec3 gets the most operators because it's the type we use most: unary minus, scalar multiplication from both sides (2.0f * v and v * 2.0f), and division by a scalar. For Vec2 and Vec4, write the scalar on the left.
  • lerp is the formula from section 2.6, built only from operators we already have. C++20 also has a std::lerp for single numbers in <cmath>; ours lives outside the std namespace and takes vectors, so the two never clash.

Here's a test program that runs through the examples of this chapter:

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

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

int main() {
  Vec3 a{3.0f, 1.0f, 2.0f};
  Vec3 b{1.0f, 2.0f, -1.0f};

  print("a + b", a + b);
  print("a - b", a - b);
  print("-a", -a);
  print("2 * a", 2.0f * a);
  print("a / 2", a / 2.0f);

  // 線型結合 / linear combination: 2i - j + 3k
  Vec3 i{1, 0, 0}, j{0, 1, 0}, k{0, 0, 1};
  print("2i - j + 3k", 2.0f * i - j + 3.0f * k);

  // 線型補間 / lerp
  Vec3 p0{2, 4, 0}, p1{10, 0, 4};
  print("lerp 0.25", lerp(p0, p1, 0.25f));
  print("lerp 0.5", lerp(p0, p1, 0.5f));

  // 位置の更新 / position update: p = p + v * dt
  Vec3 position{1, 2, 0};
  Vec3 velocity{4, 0, -2};
  float dt = 0.5f;
  for (int frame = 1; frame <= 3; ++frame) {
    position = position + dt * velocity;
    printf("frame %d: ", frame);
    print("position", position);
  }
  return 0;
}

Expected output:

a + b       = (4, 3, 1)
a - b       = (2, -1, 3)
-a          = (-3, -1, -2)
2 * a       = (6, 2, 4)
a / 2       = (1.5, 0.5, 1)
2i - j + 3k = (2, -1, 3)
lerp 0.25   = (4, 3, 1)
lerp 0.5    = (6, 2, 2)
frame 1: position    = (3, 2, -1)
frame 2: position    = (5, 2, -2)
frame 3: position    = (7, 2, -3)

Every line matches a worked example from this chapter.
%g prints a float in its shortest readable form, which is why we see 4 instead of 4.000000.

2.10 Summary

  • A point is a location; a vector is a displacement (a direction and a distance) that can be drawn anywhere.
  • A vector is a list of numbers called components, written as a column; 𝟎 is the zero vector.
  • Addition, subtraction, negation and scalar multiplication all work component by component.
  • 𝐛−𝐚 is the arrow from A to B: destination minus start.
  • Multiplying by a scalar stretches, shrinks or (if negative) flips a vector.
  • Every vector is a linear combination of the basis vectors: (x,y,z)=x𝐢+y𝐣+z𝐤. This becomes matrices in chapter 6.
  • lerp(𝐚,𝐛,t)=𝐚+t(𝐛−𝐚) blends between two vectors; it's lerp in Slang and HLSL and mix in GLSL.
  • Movement is 𝐩←𝐩+𝐯Δt; multiplying by Δt makes it independent of the frame rate.
  • Shaders add swizzling (.xyz, .rgb, .xxy) and component-wise multiplication for things like color tinting.

2.11 Challenges

  1. ★ With 𝐚=(2,−1,3) and 𝐛=(−4,5,1), compute 𝐚+𝐛, 𝐚−𝐛, 3𝐚, −𝐛 and 2𝐚−𝐛.
  2. ★ Point A is at (1,2,3) and point B is at (4,6,3). What is the vector from A to B? From B to A? What point do you reach if you start at B and move by the vector from A to B once more?
  3. ★ Write (5,−2,7) as a linear combination of 𝐢, 𝐣 and 𝐤. Then find the numbers s and t for which s(1,0)+t(1,1)=(5,3).
  4. ★ Compute lerp(𝐚,𝐛,0.75) for 𝐚=(0,10,−4) and 𝐛=(8,2,4), using both forms of the formula.
  5. ★ A ball starts at 𝐩=(0,10,0) with velocity 𝐯=(2,0,0), and gravity is 𝐠=(0,−10,0). Using Δt=0.5, update first the velocity and then the position, for two steps. Where is the ball, and what is its velocity, after each step?
  6. ★★ Add the missing operators to your copy of linalg.hh: unary minus for Vec2 and Vec4, and a lerp overload for Vec2. Test that lerp(Vec2{0, 0}, Vec2{10, 20}, 0.3f) prints (3, 6) and that -Vec4{1, -2, 3, 4} prints (-1, 2, -3, -4).
  7. ★★★ Adding two points, like (1,2)+(3,4), gives an answer that changes if you move the origin of the coordinate system, but their average 0.5(1,2)+0.5(3,4) doesn't. Show this by shifting the origin by (10,0) (add (10,0) to both points, compute both results, and compare). Can you explain why a combination of points is only meaningful when the scalars add up to 1?


コメント(0)

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