Spielerando

Lektion 24 von 24Der ganze Bildschirm10 Min.Kostenlos

Die Reihenfolge der Shader-Effekte in einem Pixel-Art-Spiel

Ein Spiel lässt viele Effekte auf dasselbe Bild los, und ihre Reihenfolge entscheidet, was du siehst. Diese letzte Lektion steckt drei davon in eine Regel: eine Spiegelung im Wasser, das Licht einer Laterne und die Nacht. In der falschen Reihenfolge verpasst die Spiegelung das Licht.

Ein Fluss bei Nacht als Pixel Art. Links ein grasiges Ufer mit zwei Bienenstöcken und einem Stapel Kisten; ein Holzsteg läuft am Wasser entlang vor einem Bootshaus, mit einer Laterne auf einem Pfosten; am anderen Ufer stehen Bäume. Unter dem Steg spiegelt das Wasser alles kopfüber, eine Stufe dunkler und mit Wellen. Die Laterne erhellt einen runden Fleck auf den Brettern des Bootshauses, und derselbe helle Fleck leuchtet aus dem Wasser. Die Imkerin geht den Steg entlang ins Licht, bleibt dort stehen und geht zurück, und ihr Spiegelbild geht mit.

Eine Regel in drei Schritten: die Welt (welchen Platz jeder Pixel zeigt, unter der Wasserlinie gespiegelt), dann das Licht (von der Laterne, für den gezeigten Platz), dann die Tönung (die Nacht, weniger das Licht). So trägt das Spiegelbild das Licht der Laterne.

Auch in dieser Lektion 4 Lesetipps zum Vertiefen 3 Fragen zum Selbsttest

Die Idee

Ein Spiel nutzt viele Regeln dieses Kurses gleichzeitig, jede auf dem Bild, das die vorige übrig gelassen hat. Im Rückblick funktioniert diese Reihenfolge:

  1. Effekte an einzelnen Sprites kommen zuerst: das Aufblitzen bei einem Treffer, der Farbtausch, die Umrandung, das Zerbröseln, der Schatten unter einer Figur. Sie gehören zur Figur und reisen mit ihr, also sieht jede spätere Regel die Figur so, wie sie jetzt aussieht: Ihr Spiegelbild blitzt mit, und die Nacht dunkelt ihre Umrandung mit ab.
  2. Die Welt kommt als Nächstes: Gras im Wind, Wasser, das spiegelt, Hitzeflimmern, Regen. Diese Regeln verschieben oder kopieren Pixel, also zeigt danach jeder Pixel seinen endgültigen Platz in der Welt.
  3. Licht fällt auf die Welt, wie sie jetzt dasteht: Die Laterne beleuchtet, was jeder Pixel zeigt, die Spiegelung eingeschlossen.
  4. Die Tönung des ganzen Bildes, die Nacht oder die Tageszeit, kommt zuletzt vor dem Bildschirm. Sie arbeitet auf fertigen Farben. Ist eine Farbe einmal bis zur Nacht abgedunkelt, weiß niemand mehr, was sie war: Tinte, Schiefer, dunkles Holz und das dunkelste Blau enden alle in derselben Nachtfarbe, und ein Licht nach der Tönung könnte sie nicht zurückgeben.
  5. Das Vergrößern auf den Bildschirm kommt ganz am Ende. Jede Regel hier arbeitet auf ganzen Pixeln des kleinen Bildes; vergrößerst du zuerst, wird das Dithering feiner als die Pixel der Zeichnung. Nur was den Bildschirm selbst nachahmt, wie Scanlines, gehört zum Vergrößern dazu: Es hängt an den Zeilen des Bildschirms.

So funktioniert es

Die Regel im Bild ist als drei Schritte geschrieben, damit deine KI die Reihenfolge sieht.

Schritt 1, die Welt. Welchen Platz der Welt zeigt dieser Pixel? Über der Wasserlinie (Zeile 100) seinen eigenen. Darunter den Platz, der so weit über der Linie liegt wie dieser Pixel darunter, seitlich verschoben durch „Wellen“ (0 ist stilles Wasser), wie in der Lektion über Spiegelungen im Wasser.

Schritt 2, das Licht. Wie viele Stufen der Nacht nimmt die Laterne weg, für den Platz, den der Pixel zeigt? Wie in der Lektion übers Laternenlicht: volles Licht für „Reichweite des vollen Lichts“ (16 Pixel, die um einen flackern, bis du einen Regler anfasst), dann Ringe von 9 Pixeln Breite mit gerasterten Rändern. Weil das Licht für den gezeigten Platz ausgerechnet wird, ist das Spiegelbild der Laterne so hell wie die Laterne.

Schritt 3, die Tönung. „Stufen Nacht“ (4), weniger das, was das Licht weggenommen hat, und eine Stufe mehr fürs Wasser. Nur hier wird die Farbe dunkler gemacht, alle Stufen auf einmal, über die Tabelle der Palette.

Zeichnet dein Spiel sein Licht als eigene Ebene nach der Welt, spiegle diese Ebene mit dem Wasser mit, oder gib jeder Lampe einen Zwilling unter der Wasserlinie, so weit darunter, wie die Lampe darüber steht.

Was schiefgeht

Eine KI rechnet das Licht oft zuerst aus, weil der eigene Platz des Pixels das Erste ist, was ein Shader bekommt. Oder sie baut die Spiegelung in eine Regel ein, die die Szene schon beleuchtet. So oder so wird das Licht am eigenen Platz des Pixels gemessen, und die Spiegelung ändert nur, woher die Farbe kommt.

Über dem Wasser sieht nichts falsch aus. Aber das Wasser wird jetzt für seinen eigenen Platz unter der Wasserlinie beleuchtet, nicht für das, was es nahe der Laterne spiegelt. Also liegen das Spiegelbild der Laterne und die beleuchteten Bretter im Wasser im Dunkeln. Schalte das Bild auf „Mit dem Fehler“, während die Imkerin unter der Laterne steht: Über dem Wasser ist sie beleuchtet, und ihr Spiegelbild ist weg.

Zwei Tests fangen das: „the lantern's reflection is as lit as the lantern, less the water's one step“ (das Spiegelbild der Laterne ist so hell wie die Laterne, eine Stufe weniger fürs Wasser) und „the water shows the lit picture above it“ (das Wasser zeigt das beleuchtete Bild darüber), der jeden gespiegelten Pixel genau eine Stufe dunkler verlangt als den beleuchteten Pixel, den er spiegelt.

Der Fehler, Zeile für Zeile

Zeilen mit - sind die Regel mit dem Fehler, Zeilen mit + die Regel, wie sie sein soll.

- /* The order of effects, with the mistake: the same three steps, but the light comes first. At that
-    point the world has not yet said which place the pixel shows, so the light is worked out for the
-    pixel's own place. Above the water nothing changes. In the water, the reflection gets the light of
-    the water's own place instead of the light of what it mirrors, and the water's own place lies further
-    below a lantern than what it mirrors: the lantern's reflection, and the lit boards around it, lie in
-    the dark.
+ /* The order of effects: night, a lantern and a reflection in water in one rule, as three small steps in
+    the order that is right. First the world: which place of the world this pixel shows (below the
+    waterline, the place mirrored above it, moved by the ripples). Then the light: how much of the night
+    the lantern takes away, for the place the pixel shows, so that a reflection carries the light of what
+    it mirrors. Last the grade of the whole picture: the night, less the light, and one step for the water.

+    The pixel art way: a picture is a grid of whole numbers, 0 where nothing is and 1 to 25 for the
+    palette's colours. Distances are compared squared; the ripples come from a table of whole pixels.
+
     From the course "Shaders for pixel art" on spielerando.com.
     SPDX-License-Identifier: MIT */
…
  }

- /** The rule, wrong: the light first, then the world, then the grade. */
+ /** The rule: the world, then the light, then the grade. */
  export function shade(x: number, y: number, tick: number, src: Frame, p: Params = DEFAULTS): number {
-   // 1. The light, too early: the world has not said yet which place this pixel shows, so the light is
-   //    worked out for the pixel's own place.
-   const dx = x - p.lanternX;
-   const dy = y - p.lanternY;
-   const far = dx * dx + dy * dy;
-   const jitter = (BAYER[(y & 3) * 4 + (x & 3)] * p.edge) >> 4;
-   let lit = 0;
-   for (let k = 0; k < p.night; k++) {
-     const reach = p.radius + k * p.ring + jitter;
-     if (far <= reach * reach) lit++;
-   }
-
-   // 2. The world: which place of the world does this pixel show? Above the waterline its own. Below it,
+   // 1. The world: which place of the world does this pixel show? Above the waterline its own. Below it,
    //    the place as far above the line as this one is below, moved sideways by the ripple; the water
    //    will take one step of light.
…
    if (n === 0) n = at(src, x, fromY);

+   // 2. The light: how many of the night's steps the lantern takes away, worked out for the place the
+   //    pixel shows, so that a reflection gets the light of what it mirrors.
+   const dx = fromX - p.lanternX;
+   const dy = fromY - p.lanternY;
+   const far = dx * dx + dy * dy;
+   const jitter = (BAYER[(y & 3) * 4 + (x & 3)] * p.edge) >> 4;
+   let lit = 0;
+   for (let k = 0; k < p.night; k++) {
+     const reach = p.radius + k * p.ring + jitter;
+     if (far <= reach * reach) lit++;
+   }
+
    // 3. The grade of the whole picture: the night, less what the light took away, and the water's step.
    return darker(n, p.night - lit + water);

Was der Test zum Fehler sagt

✔ above the water and far from the lantern, a colour is as many steps darker as `night` says
✔ at the lantern a colour is its own, and each ring further out is one step darker
✔ below the waterline the picture is the place mirrored above it, one step darker
✖ the lantern's reflection is as lit as the lantern, less the water's one step
    got 24, expected 9
✖ the water shows the lit picture above it: every reflected pixel is one step darker than the pixel it mirrors
    at 3, 5
    got 24, expected 21
✔ the ripple moves the reflection sideways by whole pixels and leaves the world above the water alone
✔ no pixel of the water is left empty where the ripple reaches past the picture's edge
7 tests: 5 passed, 2 failed

Das sagst du deiner KI

Schreib einen einzigen Shader für den ganzen Bildschirm meines Pixel-Art-Spiels, der eine Spiegelung im Wasser, das Licht einer Laterne und die Nacht macht, in dieser Reihenfolge, als drei nummerierte Schritte mit je einem Kommentar.

- Arbeite mit ganzen Pixeln und nur mit den Farben meiner Palette. Die nächstdunklere Farbe zu jeder Farbe: [eine Tabelle, oder jede Farbreihe meiner Palette von hell nach dunkel].
- Schritt 1, die Welt: Unter der Wasserlinie bei Zeile [100] zeig den Platz, der über der Linie gespiegelt liegt, seitlich verschoben durch eine Welle aus ganzen Pixeln aus einer Tabelle.
- Schritt 2, das Licht: Zähl, wie viele Stufen der Nacht die Laterne an [ihrem Platz] wegnimmt, mit vollem Licht für [16] Pixel und Ringen von [9] Pixeln, für den Platz, den der Pixel zeigt, nicht für den eigenen Platz des Pixels.
- Schritt 3, die Tönung: Mach die Farbe [4] Stufen dunkler, weniger das Licht, plus eine Stufe im Wasser. Dunkle nur in diesem Schritt ab.
- Schreib die Reihenfolge aller Effekte meines Spiels als Liste in einen Kommentar ganz oben: Effekte an einzelnen Sprites, dann die Welt, dann Licht, dann die Tönung, dann das Vergrößern auf den Bildschirm.

Bevor du den Shader schreibst, schreib dieselbe Regel als kleine, einfache Funktion. Sie bekommt ein Raster aus ganzen Zahlen (0 = leer, 1 bis N = meine Farben), einen Platz, die Zeit und die Einstellungen und gibt die Zahl für diesen einen Pixel zurück. Teste sie: Das Spiegelbild der Laterne ist so hell wie die Laterne, eine Stufe weniger; jeder gespiegelte Pixel ist eine Stufe dunkler als der beleuchtete Pixel, den er spiegelt; weit weg von der Laterne ist eine Farbe [4] Stufen dunkler. Zeig mir die Ausgabe des Tests. Schreib dann den Shader so, dass er genau das tut, was die Funktion tut.

Der Code

Dreimal dieselbe Regel. Die erste ist die, die wir testen; die beiden Shader sind diese Regel in einer Shader-Sprache, und die läuft in deinem Spiel.

Die Regel, getestet: shader.ts

TypeScript, klein, und sie braucht nichts sonst. Deine KI kann sie lesen und dieselbe Regel für das schreiben, womit dein Spiel gebaut ist.

/* The order of effects: night, a lantern and a reflection in water in one rule, as three small steps in
   the order that is right. First the world: which place of the world this pixel shows (below the
   waterline, the place mirrored above it, moved by the ripples). Then the light: how much of the night
   the lantern takes away, for the place the pixel shows, so that a reflection carries the light of what
   it mirrors. Last the grade of the whole picture: the night, less the light, and one step for the water.

   The pixel art way: a picture is a grid of whole numbers, 0 where nothing is and 1 to 25 for the
   palette's colours. Distances are compared squared; the ripples come from a table of whole pixels.

   From the course "Shaders for pixel art" on spielerando.com.
   SPDX-License-Identifier: MIT */

export interface Frame {
  width: number;
  height: number;
  index: Uint8Array;
}

export const DEFAULTS = {
  /** The first row of water: below it, the picture is the reflection of what stands above it. */
  waterline: 100,
  /** How far the ripples move the reflection sideways: 0 is still water. */
  ripple: 1,
  /** Where the lantern is, in pixels from the left. */
  lanternX: 150,
  /** Where the lantern is, in pixels from the top. */
  lanternY: 74,
  /** How far the lantern's full light reaches, in pixels. */
  radius: 16,
  /** How wide each ring of less light is, in pixels. */
  ring: 9,
  /** How many pixels at the outside of each ring are dithered. */
  edge: 3,
  /** How many steps darker the night is where no light reaches. */
  night: 4,
};
export type Params = typeof DEFAULTS;

/** A wave in whole pixels, 16 steps long. */
const WAVE = [0, 1, 1, 2, 2, 2, 1, 1, 0, -1, -1, -2, -2, -2, -1, -1];
/** The 4 by 4 pattern for dithering: 0 to 15, each once.  BAYER[(y & 3) * 4 + (x & 3)] */
const BAYER = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];
/** The next darker colour of the palette for each number. [0] is nothing. */
const DARKER = [0, 24, 25, 2, 3, 15, 7, 20, 9, 20, 21, 10, 13, 25, 12, 16, 14, 25, 17, 18, 21, 24, 25, 22, 24, 24];

/** The number at a place of the picture; outside the picture nothing is. */
export function at(src: Frame, x: number, y: number): number {
  if (x < 0 || y < 0 || x >= src.width || y >= src.height) return 0;
  return src.index[y * src.width + x];
}

/** A colour made darker by the table, `steps` times. */
function darker(n: number, steps: number): number {
  let c = n;
  for (let i = 0; i < steps; i++) c = DARKER[c];
  return c;
}

/** The rule: the world, then the light, then the grade. */
export function shade(x: number, y: number, tick: number, src: Frame, p: Params = DEFAULTS): number {
  // 1. The world: which place of the world does this pixel show? Above the waterline its own. Below it,
  //    the place as far above the line as this one is below, moved sideways by the ripple; the water
  //    will take one step of light.
  let fromX = x;
  let fromY = y;
  let water = 0;
  if (y >= p.waterline) {
    const below = y - p.waterline;
    fromY = p.waterline - 1 - below;
    fromX = x + WAVE[(below + (tick >> 3)) & 15] * p.ripple;
    water = 1;
  }
  let n = at(src, fromX, fromY);
  // where the ripple reaches past the picture's edge, the place straight above is taken
  if (n === 0) n = at(src, x, fromY);

  // 2. The light: how many of the night's steps the lantern takes away, worked out for the place the
  //    pixel shows, so that a reflection gets the light of what it mirrors.
  const dx = fromX - p.lanternX;
  const dy = fromY - p.lanternY;
  const far = dx * dx + dy * dy;
  const jitter = (BAYER[(y & 3) * 4 + (x & 3)] * p.edge) >> 4;
  let lit = 0;
  for (let k = 0; k < p.night; k++) {
    const reach = p.radius + k * p.ring + jitter;
    if (far <= reach * reach) lit++;
  }

  // 3. The grade of the whole picture: the night, less what the light took away, and the water's step.
  return darker(n, p.night - lit + water);
}

Dieselbe Regel als Shader: GLSL

Für WebGL 2 und OpenGL ES 3.0. Nur der als Regel markierte Teil gehört zu dieser Lektion; der Rest ist in jeder Lektion gleich.

#version 300 es
// A shader the pixel art way: a pixel is a whole number, 0 where nothing is, 1 to 25 for the
// palette's colours. The rule is shade(): it is asked for every pixel and answers with a number.
// Everything outside the marked part is the same for every rule. Put your own palette in PALETTE.
precision highp float;
precision highp int;

uniform sampler2D SRC;   // the picture, sampled without smoothing (nearest)
uniform sampler2D OTHER; // a second picture, where the rule uses one
uniform int TICK;        // the time in ticks, 60 a second, counted by the game

const vec3 PALETTE[26] = vec3[26](
  vec3(0.0),
  vec3(31.0, 33.0, 66.0) / 255.0, // 1: k
  vec3(75.0, 78.0, 112.0) / 255.0, // 2: n
  vec3(120.0, 123.0, 152.0) / 255.0, // 3: m
  vec3(198.0, 199.0, 227.0) / 255.0, // 4: e
  vec3(255.0, 255.0, 255.0) / 255.0, // 5: w
  vec3(246.0, 241.0, 233.0) / 255.0, // 6: c
  vec3(214.0, 205.0, 189.0) / 255.0, // 7: d
  vec3(242.0, 193.0, 78.0) / 255.0, // 8: y
  vec3(224.0, 138.0, 46.0) / 255.0, // 9: o
  vec3(194.0, 65.0, 45.0) / 255.0, // 10: r
  vec3(244.0, 163.0, 160.0) / 255.0, // 11: p
  vec3(47.0, 98.0, 240.0) / 255.0, // 12: b
  vec3(35.0, 83.0, 214.0) / 255.0, // 13: u
  vec3(157.0, 184.0, 255.0) / 255.0, // 14: s
  vec3(234.0, 240.0, 255.0) / 255.0, // 15: a
  vec3(207.0, 224.0, 255.0) / 255.0, // 16: i
  vec3(15.0, 138.0, 76.0) / 255.0, // 17: g
  vec3(124.0, 207.0, 154.0) / 255.0, // 18: l
  vec3(226.0, 244.0, 234.0) / 255.0, // 19: f
  vec3(138.0, 90.0, 60.0) / 255.0, // 20: t
  vec3(92.0, 59.0, 40.0) / 255.0, // 21: h
  vec3(109.0, 76.0, 230.0) / 255.0, // 22: v
  vec3(201.0, 187.0, 255.0) / 255.0, // 23: q
  vec3(18.0, 20.0, 43.0) / 255.0, // 24: x
  vec3(39.0, 43.0, 82.0) / 255.0 // 25: z
);

// Which colour of the palette is this? 0 where nothing is drawn.
int number(vec4 c) {
  if (c.a < 0.5) return 0;
  int best = 1;
  float least = 9.0;
  for (int i = 1; i <= 25; i++) {
    vec3 d = c.rgb - PALETTE[i];
    float away = dot(d, d);
    if (away < least) {
      least = away;
      best = i;
    }
  }
  return best;
}

// The number at a place of the picture; outside the picture nothing is.
int at(ivec2 p) {
  ivec2 size = textureSize(SRC, 0);
  if (p.x < 0 || p.y < 0 || p.x >= size.x || p.y >= size.y) return 0;
  return number(texelFetch(SRC, p, 0));
}

// The same for the second picture.
int otherAt(ivec2 p) {
  ivec2 size = textureSize(OTHER, 0);
  if (p.x < 0 || p.y < 0 || p.x >= size.x || p.y >= size.y) return 0;
  return number(texelFetch(OTHER, p, 0));
}

// a wrapped into 0 .. n-1, also for a below zero (the % sign is not safe there)
int wrap(int a, int n) {
  return a - n * int(floor(float(a) / float(n)));
}

// ---- the rule ----
uniform int waterline; // the first row of water: below it, the picture is the reflection of what stands above it
uniform int ripple;    // how far the ripples move the reflection sideways: 0 is still water
uniform int lanternX;  // where the lantern is, in pixels from the left
uniform int lanternY;  // where the lantern is, in pixels from the top
uniform int radius;    // how far the lantern's full light reaches, in pixels
uniform int ring;      // how wide each ring of less light is, in pixels
uniform int edge;      // how many pixels at the outside of each ring are dithered
uniform int night;     // how many steps darker the night is where no light reaches

// a wave in whole pixels, 16 steps long
const int WAVE[16] = int[16](0, 1, 1, 2, 2, 2, 1, 1, 0, -1, -1, -2, -2, -2, -1, -1);
// the 4 by 4 pattern for dithering: 0 to 15, each once.  BAYER[(y & 3) * 4 + (x & 3)]
const int BAYER[16] = int[16](0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5);
// the next darker colour of the palette for each number. [0] is nothing.
const int DARKER[26] = int[26](0, 24, 25, 2, 3, 15, 7, 20, 9, 20, 21, 10, 13, 25, 12, 16, 14, 25, 17, 18, 21, 24, 25, 22, 24, 24);

// a colour made darker by the table, steps times
int darker(int n, int steps) {
  int c = n;
  for (int i = 0; i < steps; i++) c = DARKER[c];
  return c;
}

// the world, then the light, then the grade
int shade(ivec2 p) {
  // 1. The world: which place of the world does this pixel show? Above the waterline its own. Below it,
  //    the place as far above the line as this one is below, moved sideways by the ripple; the water
  //    will take one step of light.
  int fromX = p.x;
  int fromY = p.y;
  int water = 0;
  if (p.y >= waterline) {
    int below = p.y - waterline;
    fromY = waterline - 1 - below;
    fromX = p.x + WAVE[(below + (TICK >> 3)) & 15] * ripple;
    water = 1;
  }
  int n = at(ivec2(fromX, fromY));
  // where the ripple reaches past the picture's edge, the place straight above is taken
  if (n == 0) n = at(ivec2(p.x, fromY));

  // 2. The light: how many of the night's steps the lantern takes away, worked out for the place the
  //    pixel shows, so that a reflection gets the light of what it mirrors.
  int dx = fromX - lanternX;
  int dy = fromY - lanternY;
  int far = dx * dx + dy * dy;
  int jitter = (BAYER[(p.y & 3) * 4 + (p.x & 3)] * edge) >> 4;
  int lit = 0;
  for (int k = 0; k < night; k++) {
    int reach = radius + k * ring + jitter;
    if (far <= reach * reach) lit++;
  }

  // 3. The grade of the whole picture: the night, less what the light took away, and the water's step.
  return darker(n, night - lit + water);
}
// ---- end of the rule ----

out vec4 FRAGMENT;

void main() {
  // the pixel's place, counted from the top left as in the picture
  ivec2 p = ivec2(int(gl_FragCoord.x), textureSize(SRC, 0).y - 1 - int(gl_FragCoord.y));
  int n = shade(p);
  FRAGMENT = n == 0 ? vec4(0.0) : vec4(PALETTE[n], 1.0);
}

Dieselbe Regel für Godot 4

Der geprüfte Shader mit Godots Namen darum herum. Diesen haben wir nicht ausgeführt: Godot gehört noch nicht zu unseren Prüfungen. Lass deine KI sein Bild mit dem auf dieser Seite vergleichen.

shader_type canvas_item;
// A shader the pixel art way: a pixel is a whole number, 0 where nothing is, 1 to 25 for the
// palette's colours. The rule is shade(): it is asked for every pixel and answers with a number.
// Everything outside the marked part is the same for every rule. Put your own palette in PALETTE.
//
// Put this on a ColorRect that covers the screen, above everything it should change.
// The rule counts pixels as this shader sees them. Let the game draw at the size of its art and
// enlarge the finished picture (the project's stretch mode "viewport"), or it counts window pixels.
uniform sampler2D SRC : hint_screen_texture, filter_nearest; // what is on the screen behind it
uniform sampler2D OTHER : filter_nearest; // a second picture, where the rule uses one
// The time in ticks, 60 a second. The game counts it itself: add 1 in the _physics_process of a
// node that pauses with the game, and set it there, so a paused game pauses its shaders:
//   tick += 1
//   material.set_shader_parameter("TICK", tick)
uniform int TICK;

const vec3 PALETTE[26] = vec3[26](
  vec3(0.0),
  vec3(31.0, 33.0, 66.0) / 255.0, // 1: k
  vec3(75.0, 78.0, 112.0) / 255.0, // 2: n
  vec3(120.0, 123.0, 152.0) / 255.0, // 3: m
  vec3(198.0, 199.0, 227.0) / 255.0, // 4: e
  vec3(255.0, 255.0, 255.0) / 255.0, // 5: w
  vec3(246.0, 241.0, 233.0) / 255.0, // 6: c
  vec3(214.0, 205.0, 189.0) / 255.0, // 7: d
  vec3(242.0, 193.0, 78.0) / 255.0, // 8: y
  vec3(224.0, 138.0, 46.0) / 255.0, // 9: o
  vec3(194.0, 65.0, 45.0) / 255.0, // 10: r
  vec3(244.0, 163.0, 160.0) / 255.0, // 11: p
  vec3(47.0, 98.0, 240.0) / 255.0, // 12: b
  vec3(35.0, 83.0, 214.0) / 255.0, // 13: u
  vec3(157.0, 184.0, 255.0) / 255.0, // 14: s
  vec3(234.0, 240.0, 255.0) / 255.0, // 15: a
  vec3(207.0, 224.0, 255.0) / 255.0, // 16: i
  vec3(15.0, 138.0, 76.0) / 255.0, // 17: g
  vec3(124.0, 207.0, 154.0) / 255.0, // 18: l
  vec3(226.0, 244.0, 234.0) / 255.0, // 19: f
  vec3(138.0, 90.0, 60.0) / 255.0, // 20: t
  vec3(92.0, 59.0, 40.0) / 255.0, // 21: h
  vec3(109.0, 76.0, 230.0) / 255.0, // 22: v
  vec3(201.0, 187.0, 255.0) / 255.0, // 23: q
  vec3(18.0, 20.0, 43.0) / 255.0, // 24: x
  vec3(39.0, 43.0, 82.0) / 255.0 // 25: z
);

// Which colour of the palette is this? 0 where nothing is drawn.
int number(vec4 c) {
  if (c.a < 0.5) return 0;
  int best = 1;
  float least = 9.0;
  for (int i = 1; i <= 25; i++) {
    vec3 d = c.rgb - PALETTE[i];
    float away = dot(d, d);
    if (away < least) {
      least = away;
      best = i;
    }
  }
  return best;
}

// The number at a place of the picture; outside the picture nothing is.
int at(ivec2 p) {
  ivec2 size = textureSize(SRC, 0);
  if (p.x < 0 || p.y < 0 || p.x >= size.x || p.y >= size.y) return 0;
  return number(texelFetch(SRC, p, 0));
}

// The same for the second picture.
int otherAt(ivec2 p) {
  ivec2 size = textureSize(OTHER, 0);
  if (p.x < 0 || p.y < 0 || p.x >= size.x || p.y >= size.y) return 0;
  return number(texelFetch(OTHER, p, 0));
}

// a wrapped into 0 .. n-1, also for a below zero (the % sign is not safe there)
int wrap(int a, int n) {
  return a - n * int(floor(float(a) / float(n)));
}

// ---- the rule ----
uniform int waterline; // the first row of water: below it, the picture is the reflection of what stands above it
uniform int ripple;    // how far the ripples move the reflection sideways: 0 is still water
uniform int lanternX;  // where the lantern is, in pixels from the left
uniform int lanternY;  // where the lantern is, in pixels from the top
uniform int radius;    // how far the lantern's full light reaches, in pixels
uniform int ring;      // how wide each ring of less light is, in pixels
uniform int edge;      // how many pixels at the outside of each ring are dithered
uniform int night;     // how many steps darker the night is where no light reaches

// a wave in whole pixels, 16 steps long
const int WAVE[16] = int[16](0, 1, 1, 2, 2, 2, 1, 1, 0, -1, -1, -2, -2, -2, -1, -1);
// the 4 by 4 pattern for dithering: 0 to 15, each once.  BAYER[(y & 3) * 4 + (x & 3)]
const int BAYER[16] = int[16](0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5);
// the next darker colour of the palette for each number. [0] is nothing.
const int DARKER[26] = int[26](0, 24, 25, 2, 3, 15, 7, 20, 9, 20, 21, 10, 13, 25, 12, 16, 14, 25, 17, 18, 21, 24, 25, 22, 24, 24);

// a colour made darker by the table, steps times
int darker(int n, int steps) {
  int c = n;
  for (int i = 0; i < steps; i++) c = DARKER[c];
  return c;
}

// the world, then the light, then the grade
int shade(ivec2 p) {
  // 1. The world: which place of the world does this pixel show? Above the waterline its own. Below it,
  //    the place as far above the line as this one is below, moved sideways by the ripple; the water
  //    will take one step of light.
  int fromX = p.x;
  int fromY = p.y;
  int water = 0;
  if (p.y >= waterline) {
    int below = p.y - waterline;
    fromY = waterline - 1 - below;
    fromX = p.x + WAVE[(below + (TICK >> 3)) & 15] * ripple;
    water = 1;
  }
  int n = at(ivec2(fromX, fromY));
  // where the ripple reaches past the picture's edge, the place straight above is taken
  if (n == 0) n = at(ivec2(p.x, fromY));

  // 2. The light: how many of the night's steps the lantern takes away, worked out for the place the
  //    pixel shows, so that a reflection gets the light of what it mirrors.
  int dx = fromX - lanternX;
  int dy = fromY - lanternY;
  int far = dx * dx + dy * dy;
  int jitter = (BAYER[(p.y & 3) * 4 + (p.x & 3)] * edge) >> 4;
  int lit = 0;
  for (int k = 0; k < night; k++) {
    int reach = radius + k * ring + jitter;
    if (far <= reach * reach) lit++;
  }

  // 3. The grade of the whole picture: the night, less what the light took away, and the water's step.
  return darker(n, night - lit + water);
}
// ---- end of the rule ----

void fragment() {
  ivec2 p = ivec2(SCREEN_UV * vec2(textureSize(SRC, 0)));
  int n = shade(p);
  COLOR = n == 0 ? vec4(0.0) : vec4(PALETTE[n], 1.0);
}
Der Test: shader.test.ts
import assert from "node:assert/strict";
import { test } from "node:test";
import { DEFAULTS, type Frame, shade } from "./shader.ts";

/** A tiny picture from rows of digits: 0 is nothing, 1 to 9 are colours. */
function picture(rows: string[]): Frame {
  return { width: rows[0].length, height: rows.length, index: Uint8Array.from(rows.join(""), Number) };
}

// above the water, rows 0 to 4: a white wall (5) with the lantern's honey flame (8) at 3, 1 and a cream
// jetty (6) in row 4. Rows 5 to 9 are the water as it came (4); the reflection takes their place.
const POND = picture([
  "5555555",
  "5558555",
  "5555555",
  "5555555",
  "6666666",
  "4444444",
  "4444444",
  "4444444",
  "4444444",
  "4444444",
]);

// still water from row 5; the lantern at the flame, full light 1 pixel far, rings 1 pixel wide, 3 steps of night
const STILL = { ...DEFAULTS, waterline: 5, ripple: 0, lanternX: 3, lanternY: 1, radius: 1, ring: 1, edge: 0, night: 3 };

// the next darker colour of each colour in this picture, from the palette's table
const NEXT: Record<number, number> = { 5: 15, 15: 16, 16: 14, 14: 12, 12: 13, 6: 7, 7: 20, 20: 21, 21: 24, 8: 9, 9: 20, 24: 24 };

test("above the water and far from the lantern, a colour is as many steps darker as `night` says", () => {
  // white goes darker as the palest blue, sky, light blue (14)
  assert.equal(shade(0, 3, 0, POND, STILL), 14);
  assert.equal(shade(6, 0, 0, POND, STILL), 14);
});

test("at the lantern a colour is its own, and each ring further out is one step darker", () => {
  assert.equal(shade(3, 1, 0, POND, STILL), 8);
  assert.equal(shade(4, 1, 0, POND, STILL), 5);
  assert.equal(shade(5, 1, 0, POND, STILL), 15);
  assert.equal(shade(6, 1, 0, POND, STILL), 16);
});

test("below the waterline the picture is the place mirrored above it, one step darker", () => {
  // with no night at all only the world's step is left: the mirror and the water's one step
  const day = { ...STILL, night: 0 };
  assert.equal(shade(0, 5, 0, POND, day), 7);
  assert.equal(shade(0, 6, 0, POND, day), 15);
  assert.equal(shade(3, 8, 0, POND, day), 9);
  assert.equal(shade(0, 9, 0, POND, day), 15);
});

test("the lantern's reflection is as lit as the lantern, less the water's one step", () => {
  assert.equal(shade(3, 8, 0, POND, STILL), 9);
});

test("the water shows the lit picture above it: every reflected pixel is one step darker than the pixel it mirrors", () => {
  for (let below = 0; below < 5; below++) {
    for (let x = 0; x < POND.width; x++) {
      const above = shade(x, 4 - below, 0, POND, STILL);
      assert.equal(shade(x, 5 + below, 0, POND, STILL), NEXT[above], `at ${x}, ${5 + below}`);
    }
  }
});

test("the ripple moves the reflection sideways by whole pixels and leaves the world above the water alone", () => {
  const rippled = { ...STILL, ripple: 1 };
  // in the second row of water the wave's step at tick 0 is 1 pixel: each pixel shows its right neighbour's reflection
  for (let x = 0; x < POND.width - 1; x++) assert.equal(shade(x, 6, 0, POND, rippled), shade(x + 1, 6, 0, POND, STILL));
  for (const tick of [0, 8, 40, 77]) {
    for (let y = 0; y < 5; y++) for (let x = 0; x < POND.width; x++) assert.equal(shade(x, y, tick, POND, rippled), shade(x, y, 0, POND, STILL));
  }
});

test("no pixel of the water is left empty where the ripple reaches past the picture's edge", () => {
  const rough = { ...STILL, ripple: 2 };
  for (let tick = 0; tick < 128; tick += 8) {
    for (let y = 5; y < POND.height; y++) for (let x = 0; x < POND.width; x++) assert.notEqual(shade(x, y, tick, POND, rough), 0, `at ${x}, ${y}, tick ${tick}`);
  }
});
Was wir geprüft haben
  • 7 Tests bestehen mit der Regel.
  • Mit dem eingebauten Fehler schlagen 2 davon fehl: "the lantern's reflection is as lit as the lantern, less the water's one step", "the water shows the lit picture above it: every reflected pixel is one step darker than the pixel it mirrors".
  • Der Fehler ist im Bild oben zu sehen: Schalte auf „Mit dem Fehler“.
  • Der Shader lief in einem Browser (Chrome/158.0.8127.37) auf 14 Bildern und ergab in 453.600 von 453.600 Pixeln das Bild der Regel.

Ausgeführt von pnpm courses:check am 2026-11-28 mit Node v24.15.0.

Probier es aus

Zum Nachlesen

Wo es tiefer geht: unsere Seiten, auf denen diese Lektion aufbaut, und was andere zu ihrem Punkt geschrieben haben.

Teste dich: drei Fragen

Jede Antwort wird sofort geprüft und erklärt. Die Fragen gehören zum Quiz und zählen für deinen Game Coder IQ wie jede andere.

Frage 1 von 3Leicht

Warum kommt die Nacht, die Tönung des ganzen Bildes, nach dem Licht der Laterne und nicht davor?

Alle Fragen dieses Kurses · Das Quiz und der Game Coder IQ

Gib deiner KI die ganze Lektion

Der Knopf kopiert, was du ihr sagst, zusammen mit der getesteten Regel, ihrem Test und beiden Shadern. So hat deine KI alles, um das in dein Spiel zu bauen und dir zu zeigen, dass es funktioniert.

Wie hilfreich war diese Seite?

Diese Seite hat noch niemand bewertet.

Ein Klick, ohne Konto. So sehen wir, welche Seiten wir als Nächstes verbessern.

Stand: 2026-11-27