Skip to content

Modulo Repetition

a % n counts 0, 1, 2 ... n − 1 and starts again: the simplest way to repeat anything, and with floor the way to split a picture into tiles.

How it works

a % n is the remainder after dividing a by n. As a grows, the remainder climbs to n − 1 and drops back to 0, over and over. Compare it with half of n and you get stripes.

floor(x / s) is the other half of the idea: it gives the number of the cell a pixel is in, counting from 0, where x % s gives the position inside that cell. Cell numbers make grids and checkerboards (add the column and row numbers and look at whether the total is odd or even); positions inside the cell let every tile draw the same thing.

In C, % is for whole numbers and fmodf(a, n) is the same thing for floats. The C is for the raylib pixels starter.

Stripes

static RGB shade(float x, float y, float t)
{
    return grey(fmodf(x, 40) < 20 ? 1 : 0);
}
function shade(x, y, t) {
  return grey(fmodf(x, 40) < 20 ? 1 : 0);
}

A checkerboard: which cell is this?

static RGB shade(float x, float y, float t)
{
    return grey(((int)floorf(x / 30) + (int)floorf(y / 30)) % 2);
}
function shade(x, y, t) {
  return grey((floorf(x / 30) + floorf(y / 30)) % 2);
}

The same gradient in every tile

static RGB shade(float x, float y, float t)
{
    return grey((fmodf(x, 60) + fmodf(y, 60)) / 120);
}
function shade(x, y, t) {
  return grey((fmodf(x, 60) + fmodf(y, 60)) / 120);
}

Stripes that slide

Add time before the modulo and the pattern moves; the stripes wrap round for ever.

static RGB shade(float x, float y, float t)
{
    return grey(fmodf(x + y + t * 20, 40) < 20 ? 1 : 0);
}
function shade(x, y, t) {
  return grey(fmodf(x + y + t * 20, 40) < 20 ? 1 : 0);
}