BLOG

Notes from the KAYAC hyper-casual team

I Don't Get B-Spline Curves at All

Takashi Hirayama

Screenshot of the sample app

Click the screenshot to go to the sample app. This time the sample is in HTML5, so the page itself is the source code, but I've also put it on GitHub, just in case. There are comments inside saying "library from here to here", so if you take just that part, you can use it as a library.

Hello. I'm Hirayama from the Technology Department.

Today I'll write about how to interpolate points and generate curves using B-spline curves. I read several explanatory articles and couldn't understand them at all, so in the end I had to come up with an explanation myself. Having gone to that trouble, I figured I might as well make it a blog post.

Motivation

Just recently, while prototyping a game, I found myself wanting to generate curves. I could have had an artist model them, but the shape of the curves is directly tied to the gameplay, so I wanted to first generate the curves as part of the game design work and test the game, and only then ask for modeling.

Ultimately the curves get passed to Unity's EdgeCollider2D and used for collision detection, so the data needs to be a set of short straight lines. But placing lots of points by hand to make something curve-like is far too much of a hassle, so I absolutely needed a feature that makes the curve for me when I roughly place a few points.

You might think "Why not just use vector drawing software?", but this time, as I introduced in an earlier article, I want to access a real smartphone from a browser, edit the shape, and have it reflected in the game immediately. The placement of other game elements is done with the same tool, so using a separate tool alongside it is far too much hassle. That's why this code is in JavaScript.

Three common kinds of interpolation

There are three major techniques that look suitable for generating a nice curve when you place a few points.

Each has its own characteristics. Roughly:

  • Bézier
    • With N points, it approximates with a polynomial of degree N-1. It doesn't pass through any points except the end points.
  • Spline
    • Generates several cubic polynomials (not necessarily cubic, but usually) that pass through all the points.
  • B-spline
    • Generates several quadratic polynomials (not necessarily quadratic) that aren't guaranteed to pass through any of the points.

First, Bézier doesn't fit. With 10 points you get a polynomial of degree 9. High-degree curves are hard to compute, and my impression is that they wobble around and don't come out very pretty. You could split the points into groups of a few and make each a Bézier, but that looks like a bit of a hassle (maybe it's doable).

Next, splines: "passing through all the points" doesn't suit this use, because what I want is something like "when I place 4 points, I want to generate a roundish shape that fits inside them".

A shape that fits inside four points, versus one passing through them

Passing through the points makes a shape that bulges outside, so you'd have to take that into account when placing the points. There's also the drawback that the computation is quite a hassle (simultaneous equations come up).

And lastly, B-splines: these can be generated with quadratics, "the lowest degree that makes a curve", so the computation looks easy, and they also have the property of not going outside the placed points, so they seemed ideal. And they actually worked well.

Unfortunately, though, I don't really understand the theory. So I decided to come up with an explanation that even I can understand. I'll describe it below.

The idea of "mixing points to make a line"

When you have several points, there are various ways to connect them. The simplest is linear interpolation.

As you vary the blend ratio of two neighboring points, you get points between the two, and connecting them gives a line.

Linear interpolation between two neighboring points

Here, note that:

  • The number of points being mixed is two.
  • The blend ratios add up to 1.

If the blend ratios of the two points don't add up to 1, you get points outside the segment connecting the two points. So the blend ratios must always add up to 1.

And since we're only mixing two points, we can't get a point off the straight line through the two points.

So how do we extend this to make a curve?

Going up to three points

Let's increase the number of points being blended.

If you mix three points so that the blend ratios add up to 1, you get some point inside the triangle formed by the three points.

Mixing three points gives a point inside their triangle

If you mix three neighboring points so that the blend ratios add up to 1, while gradually making the blend ratio of the later points higher, the point should gradually advance and trace a line. And if at some point you can shift the three points you use by one and move to a different triangle, you should get a single curve even with many points.

Seven points forming five triangles from neighboring triples

There are 7 points in the figure, and each run of three neighboring points forms a triangle, five in all. We walk from triangle to triangle, keeping the sum of the blend ratios at 1 in each triangle.

Functions that change the blend ratio

Now the question becomes "how do we change the blend ratios?" First, let's see how the blend ratios behave with simple linear interpolation.

At first, point 0's ratio is 1 and point 1's is 0. That gives the same point as vertex 0. Gradually decrease point 0's ratio, increase point 1's by the same amount, and eventually point 1's ratio reaches 1 and point 0's contribution reaches 0. This is where we switch lines. Instead of making the line from 0 and 1, we switch to making it from 1 and 2. After this, the contribution of point 1 decreases and the contribution of point 2 increases.

As a graph it looks like this. The horizontal axis is the point number (0,1,2,3...), and the vertical axis is the blend ratio.

Blend ratios for linear interpolation: overlapping triangular peaks of width 2

The green line near the left end is the blend ratio of point 0. As it goes down, the blend ratio of point 1 in blue goes up. Once that has risen all the way, the blend ratio of point 2, in yellow, starts to rise, and point 1, in blue, goes down. The horizontal black line at the height of the top of each peak is the sum. One square of the grid is 0.25, so the black line being at a height of 4 squares shows that the sum is 1. The width of each blend function's peak is 2 (8 grid squares).

Now, let's do something similar with three points. The conditions to satisfy are:

  • Each peak has a width of 3
  • Everywhere, three peaks overlap, and their heights add up to 1

Simple triangular peaks like those for linear interpolation can't achieve this.

Triangular peaks widened to 3: the sum is not constant

Here I just tried stretching them to 1.5 times the width, but the sum (the black line) doesn't come to 1. Evidently we need something with a more elaborate shape.

Bringing in quadratic functions

So let's try using quadratic functions. To make a peak with a quadratic, you make the coefficient of the squared term negative. But simply lining up quadratics of width 3 isn't going to make the sum 1, so we join an upward-convex quadratic with ones flipped upside down to be downward-convex. Over the width of 3, the middle 1 is convex upward, and the 1 at each end is convex downward. If the shape of this peak isn't smooth, the curve made with it won't be smooth either and will have kinks, so we tune the coefficients so they join without kinks. Then we adjust the overall size so the sum is 1, and the result is this:

Quadratic blend functions of width 3 whose sum is constant

The black line representing the sum is now straight: happily, the sum is constant. You can also see that each peak has a width of 3.

In fact, if you use this to mix three neighboring points, you get a quadratic B-spline curve. The function that computes the mixing weights looks like this.

var calculateBasisWeight2 = function (basisT, t) {
    var ret = 0;
    var nt;
    if (t < (basisT - 1.5)) {
        // do nothing
    } else if (t < (basisT - 0.5)) {
        nt = (t - (basisT - 1.5));
        ret = 0.5 * nt * nt;
    } else if (t < (basisT + 0.5)) {
        nt = (t - basisT);
        ret = 0.75 - (nt * nt);
    } else if (t < (basisT + 1.5)) {
        nt = (t - (basisT + 1.5));
        ret = 0.5 * nt * nt;
    }
    return ret;
};

basisT is "the point whose blend ratio we want", and t is the coordinate where the location of point 0 is 0 and the location of point 1 is 1. 0.1 would be the point 10% of the way from point 0 to point 1. It's also easy to think of it as time: "passes point 0 at time 0, passes point 1 at time 1..." and so on.

It's split into three intervals, and you can see that at both ends the coefficient of the squared term is positive, so it's convex downward, and in the middle it's negative, so it's convex upward.

When drawing the curve, you increase this t little by little from 0 (say by 0.01), and for each step call the function above with the numbers of the three points to mix, get the blend ratios, and mix the points.

For a given t, the numbers of the three points to mix are easy to find. For example, if t is 2.4, the peak width is 3, so subtract half of that, 1.5, giving 0.9. Point 0 isn't included, so it starts from the next one. In other words, ceil(t - 1.5) is the first number. From there, you know you just mix three points.

This seems totally different from other explanations

Everything up to this point is the explanation I came up with after reading more than five explanations on other sites, including English ones, and understanding nothing. There is no mathematical rigor whatsoever.

Normally when it comes to B-splines, something called a knot vector shows up, and you build things called basis functions with a recursive algorithm. Don't you have to implement complicated formulas with i, j and k all mixed together?

Actually, this implementation and explanation only deal with a special case of B-splines. That's why it's simple.

  • The parameter t, sort of the time at which a given point is mixed in the most, is simply taken to be "the same as the point's number".
    • Since the knot vector can't be adjusted, you can't express things like "this interval is long".
  • Only quadratics are handled.
    • Making blend functions (called basis functions elsewhere) of degree 3 or higher by hand is hard work.
    • The proper formulas on other sites can make any degree.

But I think that once you've got the picture with this, explanations of the general method are easier to take in. If you think "quadratic B-splines are just mixing three points with blend functions of width 3", it's simple, no hard formulas come up, and you can put it to use for the time being.

However, that's only a simplified story; for example, the "width of 3" here comes from setting "the time at which point k is mixed in the most is t=k". You can also set point 1 at t=2, point 2 at t=5 and so on, and then the width is different. If you need it, it's better to understand the more general theory. Unfortunately, I'm bad at math, so I'll stop here until the need arises.

Handling the ends

A quadratic B-spline "always mixes three points", so you can't make a point by mixing only one or two points: if the blend functions don't add up to 1, the point ends up somewhere strange. If the first point is at t=0, until t exceeds 1.5 you're not within the range of point 2's blend function, so you can't have three blend functions. In other words, no points can be made in the region t<1.5.

So in this implementation, I make up points -1 and -2, and compute blend functions there too.

There are two options for how to make them up.

  • Everything before point 0 is point 0
  • The point before point 0 is the last point. In other words, it loops.

In the former case, at t=0 all three points to mix are point 0, so at t=0 you get point 0 itself. That is, the curve starts from point 0.

In the latter case, it interpolates toward the last point, so it becomes a ring.

The same processing is done at the end too: with N points, you can choose either

  • Everything after point N-1 is point N-1
  • After point N-1 comes point 0

In the sample, this is provided as a checkbox called "Loop". The code isn't that hard either. It's what comes up when you search for cyclic.

In closing

Math really is hard. The despair after spending half a day reading various explanations and having none of them click...

At first you mean to understand it before writing any code, but it's so incomprehensible that you end up transcribing the formulas into code exactly as written. And it does work. It certainly does.

But with i, j and k all over the place, it was buggy for a while. I was very late to notice that "you can't make a curve at the ends" and got stuck on that, and then came "I want it to loop, how do I do that?" It was a real mess.

Now that I can make shapes, I plan to move on to generating a mesh from them by computation and turning it into an asset. Even if I do have an artist model it, handing over a mesh asset would be better than handing over a dimensioned drawing.

I'll probably blog about that at some point too.

References

  • Japanese Wikipedia
    • Has all the information needed for implementation, but the theory is completely incomprehensible.
  • English Wikipedia
    • Much more detailed than the Japanese one, but I don't really get it. I'm lost at the level of "why are the indices 1-based under Definition but 0-based under Properties below?"
  • Tajima Robotics
    • Quite easy to understand, and has the information needed for implementation.
  • Musashi System
    • Makes it easy to get a geometric picture. But I didn't really understand what "at least one on-curve point is included" means. As shown in the sample, you can generate a B-spline that doesn't pass through any of the points.
  • Shoichi Midorikawa's personal page
    • Gave the biggest hint for how to make the blend functions.
  • MIT's site
    • Probably the most proper explanation. The figures helped me get the picture.

None of the sites directly answered questions like "where did the knot vector come from?" or "how should the ends be handled?", but that's probably just because I couldn't pick the answers out of them.

Interview with the author, Hirayama

An interview with the author of this article, Hirayama, is published on the Kayac site. Please take a look!

A career philosophy of getting over walls by deliberately resetting your career so far | KAYAC Inc.