Apple 2 Rain

Schematic of Apple 2 Rain
// Three streams per column. Each slot stores a 10-bit start frame and 5-bit row.
// One is added to the packed value so zero can mark a free slot.
int streamState[120];
int streamStyle[120];
int streamSeed[120];
int rainFrame = 0;
int sweepSlot = 0;
int randomState = 17317;
unsigned long frameTime = 0;
int nextColumn = 0;
int spawnCredit = 0;
int effectFrame = 0;
int effectSeed = 0;

// Each rectangle packs glyph x, y, width minus one and height minus one.
int glyphStart[33] = {
  0, 7, 11, 18, 24, 30, 35, 41, 46, 53, 59, 63, 68, 72,
  75, 78, 83, 91, 93, 98, 103, 107, 114, 119, 122, 125, 134, 139,
  146, 149, 154, 156, 165
};
int glyphRects[165] = {
  2056, 2060, 129, 177, 19, 26, 33, 3074, 9, 49, 51, 304, 129, 524,
  8, 27, 34, 41, 192, 240, 524, 90, 548, 40, 3075, 160, 10, 17,
  24, 36, 256, 216, 240, 520, 548, 1552, 153, 177, 66, 548, 9, 256,
  1057, 12, 19, 26, 129, 153, 177, 520, 524, 544, 548, 1548, 129, 153,
  520, 113, 43, 2568, 2572, 129, 153, 2056, 129, 177, 12, 44, 3072, 193,
  241, 153, 3072, 193, 153, 3072, 3076, 153, 3074, 1, 3, 49, 51, 3072,
  4, 11, 18, 25, 34, 43, 52, 3072, 241, 3072, 3076, 530, 9, 11,
  3072, 3076, 521, 547, 26, 3072, 129, 153, 524, 3072, 129, 153, 524, 34,
  43, 52, 193, 240, 153, 520, 548, 3074, 64, 67, 2560, 2564, 177, 512,
  516, 552, 556, 17, 19, 26, 33, 35, 1562, 512, 516, 17, 19, 256,
  304, 12, 19, 26, 33, 40, 2058, 88, 91, 516, 552, 19, 26, 33,
  272, 288, 1169, 8, 10, 12, 24, 28, 40, 42, 44
};


int fontBits[96] = {
  20014, 18229, 14, 4484, 4228, 14, 1582, 8322, 31, 1086, 17446, 30,
  10434, 3058, 2, 16927, 1086, 30, 16646, 17982, 14, 2111, 8452, 8,
  17966, 17966, 14, 17966, 2095, 12, 17966, 17983, 17, 16942, 17936, 14,
  16927, 16926, 31, 16927, 16926, 16, 17969, 17983, 17, 4238, 4228, 14,
  21073, 19096, 17, 16912, 16912, 31, 22385, 17973, 17, 26417, 20085, 17,
  17982, 16926, 16, 17982, 19102, 17, 16911, 1070, 30, 4255, 4228, 4,
  17969, 17969, 14, 10801, 17732, 17, 10801, 4228, 4, 2111, 16644, 31,
  4224, 4255, 0, 2081, 16644, 16, 31744, 992, 0, 15008, 21983, 0
};


int nextRandom() {
  int feedback = (randomState ^ (randomState >> 1)) & 1;
  randomState = (randomState >> 1) | (feedback << 14);
  return randomState;
}

int persistence(int style) {
  return 48 + 6 * (style >> 11);
}

int stateAt(int i) {
  int tag = streamState[i];
  if (tag == 0) return 0;
  tag--;
  int age = (1024 + rainFrame - (tag >> 5)) & 1023;
  int firstRow = tag & 31;
  int style = streamStyle[i];
  int interval = style & 15;
  int stride = (style >> 4) & 3;
  int falling = ((23 - firstRow + stride - 1) / stride + 1) * interval;
  if (age >= falling) {
    int fade = age - falling;
    if (fade >= persistence(style)) return 0;
    return -1 - fade;
  }
  int row = firstRow + (age / interval) * stride;
  if (row > 23) row = 23;
  return 32 * (interval - age % interval) + row;
}

bool spawnDrop(int row) {
  int column = (nextColumn + nextRandom() % 5) % 40;
  for (int attempt = 0; attempt < 40; attempt++) {
    int start = 3 * column;
    for (int i = start; i < start + 3; i++) {
      if (stateAt(i) == 0) {
        int kind = nextRandom() % 10;
        int stride = 1;
        int interval = 1;
        if (kind < 5) stride = 2 + (nextRandom() & 1);
        else if (kind < 9) interval = 2 + nextRandom() % 4;
        else interval = 7 + nextRandom() % 8;
        int group = nextRandom() & 127;
        int length = 2;
        if (group < 100) length = 2 + nextRandom() % 3;
        else if (group < 119) length = 5 + nextRandom() % 6;
        else if (group < 127) length = 11 + nextRandom() % 13;
        else length = 24;
        streamStyle[i] = ((nextRandom() % 9) << 11) | (length << 6)
                       | (stride << 4) | interval;
        streamSeed[i] = nextRandom() & 8191;
        streamState[i] = 32 * rainFrame + row + 1;
        nextColumn = column + 1;
        return true;
      }
    }
    column++;
    if (column == 40) column = 0;
  }
  return false;
}

void setup() {
  chipName("Green Phosphor Monitor");
  logicFamily(CMOS);
  pin(19, "GND", GROUND);
  pin(20, "5V", POWER);
  for (int i = 0; i < 12; i++) spawnDrop(nextRandom() % 24);
  effectSeed = nextRandom() & 8191;
  frameTime = micros();
}

void loop() {
  unsigned long now = micros();
  unsigned long elapsed = now - frameTime;
  if (elapsed < 16667UL) return;
  frameTime = frameTime + 16667UL;
  if (elapsed >= 33334UL) frameTime = now;

  effectFrame = (effectFrame + 1) & 127;
  if (effectFrame == 0) effectSeed = nextRandom() & 8191;
  rainFrame = (rainFrame + 1) & 1023;
  // A drop lasts at most 432 ticks. Check all slots over the next 120
  // ticks so no stale drop survives the 1024-tick clock wrap.
  if (stateAt(sweepSlot) == 0) streamState[sweepSlot] = 0;
  sweepSlot++;
  if (sweepSlot == 120) sweepSlot = 0;
  spawnCredit = spawnCredit + 71;
  if (spawnCredit >= 120) {
    if (spawnDrop(0)) spawnCredit = spawnCredit - 120;
    else spawnCredit = 120;
  }
}

int dotY[8] = {0, 3, 6, 9, 13, 16, 19, 22};
int tableFirst[4] = {0, 10, 20, 28};
int tableLength[4] = {10, 10, 8, 4};
int bandLight[4] = {9, 5, 3, 1};
int layerGlyph[3];
int layerLight[3];
int currentLight = -1;

void selectLight(int light) {
  if (light > 12) light = 12;
  if (light == currentLight) return;
  setColor(4 + 10 * light, 17 + 19 * light, 8 + 10 * light);
  currentLight = light;
}

void paintGlyph(int x, int top, int code) {
  for (int i = glyphStart[code]; i < glyphStart[code + 1]; i++) {
    int rect = glyphRects[i];
    int a = (rect >> 3) & 7;
    int b = a + 1 + (rect >> 9);
    fillRect(x + 3 * (rect & 7), top + dotY[a],
             3 * (1 + ((rect >> 6) & 7)), dotY[b] - dotY[a] - 1);
  }
}

int layerFor(int i, int row, int age, int depth, int scale, int layers, int state) {
  int bits = streamSeed[i] + 977 * row;
  int code = (bits ^ (bits >> 5) ^ (bits >> 9)) & 31;
  int band = depth;
  if (age > 4 * scale) band = band + 3;
  else if (age > 2 * scale) band = band + 2;
  else if (age > 0) band++;
  if (band > 3) band = 3;
  int light = bandLight[band];

  // Stationary afterimages cycle at staggered intervals as they fade.
  if (state < 0 && (streamSeed[i] & 3) == 0) {
    int cycle = (-state - 1 + (bits & 15)) / 12;
    code = (code + 5 * cycle) & 31;
  }
  if (band != 0) {
    int flicker = bits ^ effectSeed;
    int phase = (effectFrame + ((flicker ^ (flicker >> 4)) & 127)) & 127;
    if (phase < 12) {
      int table = ((flicker >> 8) + phase / 3) & 3;
      code = tableFirst[table] + ((flicker & 31) + phase) % tableLength[table];
      light = light + 3;
    }
  }
  // Matching glyphs add as one shape, without composing the dots again.
  for (int j = 0; j < layers; j++) {
    if (layerGlyph[j] == code) {
      layerLight[j] = layerLight[j] + light;
      return layers;
    }
  }
  layerGlyph[layers] = code;
  layerLight[layers] = light;
  return layers + 1;
}

int mixedDots[35];

void paintMixed(int x, int top, int layers) {
  for (int y = 0; y < 7; y++) {
    int group = y / 3;
    int shift = 5 * (y % 3);
    int a = (fontBits[3 * layerGlyph[0] + group] >> shift) & 31;
    int b = (fontBits[3 * layerGlyph[1] + group] >> shift) & 31;
    int c = 0;
    if (layers == 3) c = (fontBits[3 * layerGlyph[2] + group] >> shift) & 31;
    for (int dot = 0; dot < 5; dot++) {
      int bit = 16 >> dot;
      int light = 0;
      if ((a & bit) != 0) light = light + layerLight[0];
      if ((b & bit) != 0) light = light + layerLight[1];
      if ((c & bit) != 0) light = light + layerLight[2];
      if (light > 12) light = 12;
      mixedDots[5 * y + dot] = light;
    }
  }
  // Merge equal-intensity pixels before drawing an overlapping glyph.
  for (int y = 0; y < 7; y++) {
    int start = 5 * y;
    for (int dot = 0; dot < 5; dot++) {
      int light = mixedDots[start + dot];
      if (light != 0) {
        int right = dot + 1;
        while (right < 5 && mixedDots[start + right] == light) right++;
        int bottom = y + 1;
        int checked = right;
        while (bottom < 7 && checked == right) {
          checked = dot;
          int next = 5 * bottom;
          while (checked < right && mixedDots[next + checked] == light) checked++;
          if (checked == right) bottom++;
        }
        for (int row = y + 1; row < bottom; row++) {
          int next = 5 * row;
          for (int i = dot; i < right; i++) mixedDots[next + i] = 0;
        }
        selectLight(light);
        fillRect(x + 3 * dot, top + dotY[y], 3 * (right - dot),
                 dotY[bottom] - dotY[y] - 1);
        dot = right - 1;
      }
    }
  }
}

int columnHead[3];
int columnState[3];
int columnShift[3];
int columnStart[3];
int columnFade[3];
int columnScale[3];

void paintRain(int left, int top) {
  currentLight = -1;
  for (int col = 0; col < 40; col++) {
    int first = 24;
    int last = -1;
    int slot = 3 * col;
    for (int j = 0; j < 3; j++) {
      int state = stateAt(slot + j);
      columnState[j] = state;
      columnHead[j] = -1;
      if (state != 0) {
        int style = streamStyle[slot + j];
        int length = (style >> 6) & 31;
        int row = state & 31;
        int fade = 0;
        int shift = 0;
        int retired = 0;
        if (state < 0) {
          int age = -state - 1;
          int duration = persistence(style);
          row = 23;
          fade = 1 + age * 3 / duration;
          if ((streamSeed[slot + j] & 3) != 0) {
            // Slide below the glass, leaving one faint glyph for the tail end.
            shift = 2 * age * (length - 1) / duration;
            if (shift >= length) shift = length - 1;
            row = row + shift;
          } else {
            // Retire the oldest stationary glyphs during their fade.
            retired = age * (length - 1) / duration;
          }
        }
        int start = row - length + 1 + retired;
        if (start < 0) start = 0;
        columnHead[j] = row;
        columnStart[j] = start;
        columnShift[j] = shift;
        columnFade[j] = fade;
        columnScale[j] = 1 + (length - 1) / 8;
        if (start < first) first = start;
        if (row > last) last = row;
      }
    }
    if (last > 23) last = 23;
    int x = left + 21 * col + 3;
    for (int row = first; row <= last; row++) {
      int layers = 0;
      for (int j = 0; j < 3; j++) {
        int head = columnHead[j];
        if (row <= head && row >= columnStart[j]) {
          layers = layerFor(slot + j, row - columnShift[j], head - row, columnFade[j], columnScale[j], layers, columnState[j]);
        }
      }
      int y = top + 26 * row + row / 4;
      if (layers == 1) {
        selectLight(layerLight[0]);
        paintGlyph(x, y, layerGlyph[0]);
      } else if (layers > 1) {
        paintMixed(x, y, layers);
      }
    }
  }
}

void draw() {
  int width = chipWidth();
  int height = chipHeight();
  if (width < 1008 || height < 824) return;
  int x = (width - 1008) / 2;
  int y = (height - 824) / 2;

  // Warm molded case, recessed tinted glass, and power indicator.
  setColor(107, 97, 79);
  fillRect(x + 12, y, 984, 824);
  fillRect(x, y + 12, 1008, 800);
  setColor(187, 173, 146);
  fillRect(x + 11, y + 8, 986, 799);
  setColor(209, 196, 169);
  fillRect(x + 11, y + 8, 986, 15);
  fillRect(x + 11, y + 23, 12, 784);
  setColor(133, 122, 101);
  fillRect(x + 23, y + 783, 974, 24);

  setColor(96, 89, 74);
  fillRect(x + 38, y + 31, 932, 710);
  setColor(40, 41, 32);
  fillRect(x + 48, y + 38, 912, 694);
  setColor(10, 22, 13);
  fillRect(x + 60, y + 49, 888, 666);
  setColor(7, 17, 10);
  fillRect(x + 76, y + 59, 856, 646);

  setColor(60, 55, 45);
  fillRect(x + 875, y + 753, 27, 13);
  fillRect(x + 913, y + 753, 27, 13);
  setColor(94, 82, 60);
  fillRect(x + 63, y + 753, 40, 13);
  setColor(126, 222, 65);
  fillRect(x + 69, y + 756, 28, 7);

  paintRain(x + 84, y + 67);
  setDefaultColor();
}