Every line in the cloth simulation is technically called a constraint and every point is a point mass (an object with no dimension, just location and mass). All the constraints do is control the distance between each point mass. If two points move too far apart, it will pull them closer. If two points are too close together, it will push them apart. The cloth is really then just a collection of constraints and point masses in a never ending struggle.
Click and drag to move points. Hold down any key to pin them.
Draw Lines Draw Points
The most computationally expensive part is trying to satisfy the constraints. To do this requires the calculation of distance between two points. This is easy to do with a little math, but that often involves an expensive square root. This is something that cannot simply be thrown out either, so what do you do? You approximate it. There are lots of mathematical tools for approximating functions, in this case I chose the first couple terms of a taylor expansion.
"Boring!" you say.
No. Not boring. Beautiful...
Another pretty neat thing about this simulation is how all the constraints are satisfied. As I mentioned above, a constraint is basically a rule that controls the distance between two points. So for example if a point has moved too far away from its constrained counterpart, the constraint will suck it back in. What makes this a little trickier is the fact that we have several constraints attached to a single point. This means that this point is going to be constantly jerked around when the constraint satisfaction process begins to execute. In terms of visuals, the cloth would become really springy, jittery and all around unnatural looking.
As it turns out there is a really simple solution to this problem. Instead of satisfying all the constraints just once, you simply satisfy them several times before updating the screen. In the case of this cloth simulation all I needed to do was try satisfying the constraints twice. But for things like simple rope simulations it may be necessary to satisfy several times (maybe 4 or 5). The more times you satisfy, the more rigid the constraint becomes. This process is known as relaxation and is pretty darn cool.
If you're interested here are some links: