580 lines
14 KiB
C
580 lines
14 KiB
C
/*
|
|
* matrix_ncurses.c - Matrix "digital rain" screensaver for terminal (UTF-8)
|
|
*
|
|
* Build (Ubuntu):
|
|
* sudo apt-get install build-essential libncursesw5-dev
|
|
* gcc -O2 -Wall -Wextra -std=c11 matrix_ncurses.c -o matrix -lncursesw
|
|
*
|
|
* Run:
|
|
* ./matrix # default settings
|
|
* ./matrix --speed 1.2 --density 0.35 --bold --no-fade
|
|
* ./matrix --help
|
|
*
|
|
* Notes:
|
|
* - Uses wide characters (ncursesw) and UTF-8 katakana set.
|
|
* - Handles terminal resize at runtime.
|
|
* - Press 'q' or ESC to quit. Press 'p' to pause/resume.
|
|
*/
|
|
|
|
#define _XOPEN_SOURCE 700
|
|
|
|
#include <errno.h>
|
|
#include <locale.h>
|
|
#include <ncursesw/ncurses.h>
|
|
#include <stdbool.h>
|
|
#include <stdint.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <time.h>
|
|
#include <wchar.h>
|
|
|
|
#ifndef ARRAY_SIZE
|
|
#define ARRAY_SIZE(a) (int)(sizeof(a) / sizeof((a)[0]))
|
|
#endif
|
|
|
|
#define DEFAULT_SPEED_MUL 1.0
|
|
#define DEFAULT_DENSITY 0.25
|
|
#define DEFAULT_FPS 45
|
|
#define MIN_FPS 10
|
|
#define MAX_FPS 240
|
|
|
|
#define TAIL_MIN 5
|
|
#define TAIL_RANGE 20
|
|
#define BASE_SPEED_MIN 24.0
|
|
#define BASE_SPEED_RANGE 72.0
|
|
#define TRAIL_DECAY_PER_SECOND 1.8f
|
|
#define MAX_FRAME_DT 0.25
|
|
#define IDLE_SPAWN_RATE 0.30
|
|
|
|
typedef struct {
|
|
double speed_mul;
|
|
double density;
|
|
bool bold_head;
|
|
bool fade_trail;
|
|
int target_fps;
|
|
} Options;
|
|
|
|
typedef struct {
|
|
double head_y;
|
|
int tail;
|
|
double speed;
|
|
bool active;
|
|
} Column;
|
|
|
|
typedef struct {
|
|
wchar_t ch;
|
|
float intensity;
|
|
} Cell;
|
|
|
|
typedef enum {
|
|
PARSE_OK,
|
|
PARSE_HELP,
|
|
PARSE_ERROR
|
|
} ParseResult;
|
|
|
|
// Random helper
|
|
static inline uint32_t rnd32(void) {
|
|
static uint64_t s = 0;
|
|
|
|
if (!s) {
|
|
s = ((uint64_t)time(NULL) ^ (uintptr_t)&s) | 1ULL;
|
|
}
|
|
|
|
s ^= s << 7;
|
|
s ^= s >> 9;
|
|
s ^= s << 8;
|
|
return (uint32_t)s;
|
|
}
|
|
|
|
static inline int irand(int n) {
|
|
return n > 0 ? (int)(rnd32() % (uint32_t)n) : 0;
|
|
}
|
|
|
|
static inline double drand_unit(void) {
|
|
return rnd32() / (double)UINT32_MAX;
|
|
}
|
|
|
|
static inline size_t cell_index(int x, int y, int maxx) {
|
|
return (size_t)y * (size_t)maxx + (size_t)x;
|
|
}
|
|
|
|
static inline int ifloor(double value) {
|
|
int truncated = (int)value;
|
|
|
|
return value < (double)truncated ? truncated - 1 : truncated;
|
|
}
|
|
|
|
static inline wchar_t random_glyph(void) {
|
|
static const wchar_t KATAKANA[] = {
|
|
L'ヲ', L'ァ', L'ィ', L'ゥ', L'ェ', L'ォ', L'ャ', L'ュ', L'ョ', L'ッ',
|
|
L'ア', L'イ', L'ウ', L'エ', L'オ', L'カ', L'キ', L'ク', L'ケ', L'コ',
|
|
L'サ', L'シ', L'ス', L'セ', L'ソ', L'タ', L'チ', L'ツ', L'テ', L'ト',
|
|
L'ナ', L'ニ', L'ヌ', L'ネ', L'ノ', L'ハ', L'ヒ', L'フ', L'ヘ', L'ホ',
|
|
L'マ', L'ミ', L'ム', L'メ', L'モ', L'ヤ', L'ユ', L'ヨ', L'ラ', L'リ',
|
|
L'ル', L'レ', L'ロ', L'ワ', L'ン', L'0', L'1', L'2', L'3', L'4',
|
|
L'5', L'6', L'7', L'8', L'9'};
|
|
|
|
return KATAKANA[irand(ARRAY_SIZE(KATAKANA))];
|
|
}
|
|
|
|
static void usage(const char *prog) {
|
|
fprintf(stderr,
|
|
"Usage: %s [--speed f] [--density 0..1] [--bold] [--no-fade] [--fps N]\n"
|
|
" --speed f Speed multiplier (> 0)\n"
|
|
" --density d Active column density in [0, 1]\n"
|
|
" --bold Bold white head\n"
|
|
" --no-fade Disable persistent fade buffer\n"
|
|
" --fps N Target refresh rate in [%d, %d]\n"
|
|
" --help Show this help\n",
|
|
prog,
|
|
MIN_FPS,
|
|
MAX_FPS);
|
|
}
|
|
|
|
static bool parse_double_value(const char *text, double min_value, double max_value, double *out) {
|
|
char *end = NULL;
|
|
double value;
|
|
|
|
errno = 0;
|
|
value = strtod(text, &end);
|
|
if (errno != 0 || end == text || *end != '\0') {
|
|
return false;
|
|
}
|
|
if (value < min_value || value > max_value) {
|
|
return false;
|
|
}
|
|
|
|
*out = value;
|
|
return true;
|
|
}
|
|
|
|
static bool parse_int_value(const char *text, int min_value, int max_value, int *out) {
|
|
char *end = NULL;
|
|
long value;
|
|
|
|
errno = 0;
|
|
value = strtol(text, &end, 10);
|
|
if (errno != 0 || end == text || *end != '\0') {
|
|
return false;
|
|
}
|
|
if (value < min_value || value > max_value) {
|
|
return false;
|
|
}
|
|
|
|
*out = (int)value;
|
|
return true;
|
|
}
|
|
|
|
static ParseResult parse_args(int argc, char **argv, Options *opts) {
|
|
*opts = (Options){
|
|
.speed_mul = DEFAULT_SPEED_MUL,
|
|
.density = DEFAULT_DENSITY,
|
|
.bold_head = false,
|
|
.fade_trail = true,
|
|
.target_fps = DEFAULT_FPS,
|
|
};
|
|
|
|
for (int i = 1; i < argc; ++i) {
|
|
if (!strcmp(argv[i], "--help")) {
|
|
usage(argv[0]);
|
|
return PARSE_HELP;
|
|
}
|
|
|
|
if (!strcmp(argv[i], "--bold")) {
|
|
opts->bold_head = true;
|
|
continue;
|
|
}
|
|
|
|
if (!strcmp(argv[i], "--no-fade")) {
|
|
opts->fade_trail = false;
|
|
continue;
|
|
}
|
|
|
|
if (!strcmp(argv[i], "--speed")) {
|
|
if (i + 1 >= argc || !parse_double_value(argv[i + 1], 0.05, 20.0, &opts->speed_mul)) {
|
|
fprintf(stderr, "Invalid value for --speed\n");
|
|
usage(argv[0]);
|
|
return PARSE_ERROR;
|
|
}
|
|
++i;
|
|
continue;
|
|
}
|
|
|
|
if (!strcmp(argv[i], "--density")) {
|
|
if (i + 1 >= argc || !parse_double_value(argv[i + 1], 0.0, 1.0, &opts->density)) {
|
|
fprintf(stderr, "Invalid value for --density\n");
|
|
usage(argv[0]);
|
|
return PARSE_ERROR;
|
|
}
|
|
++i;
|
|
continue;
|
|
}
|
|
|
|
if (!strcmp(argv[i], "--fps")) {
|
|
if (i + 1 >= argc || !parse_int_value(argv[i + 1], MIN_FPS, MAX_FPS, &opts->target_fps)) {
|
|
fprintf(stderr, "Invalid value for --fps\n");
|
|
usage(argv[0]);
|
|
return PARSE_ERROR;
|
|
}
|
|
++i;
|
|
continue;
|
|
}
|
|
|
|
fprintf(stderr, "Unknown option: %s\n", argv[i]);
|
|
usage(argv[0]);
|
|
return PARSE_ERROR;
|
|
}
|
|
|
|
return PARSE_OK;
|
|
}
|
|
|
|
static double elapsed_seconds(const struct timespec *start, const struct timespec *end) {
|
|
time_t sec = end->tv_sec - start->tv_sec;
|
|
long nsec = end->tv_nsec - start->tv_nsec;
|
|
|
|
return (double)sec + (double)nsec / 1000000000.0;
|
|
}
|
|
|
|
static int timespec_cmp(const struct timespec *lhs, const struct timespec *rhs) {
|
|
if (lhs->tv_sec != rhs->tv_sec) {
|
|
return lhs->tv_sec < rhs->tv_sec ? -1 : 1;
|
|
}
|
|
if (lhs->tv_nsec != rhs->tv_nsec) {
|
|
return lhs->tv_nsec < rhs->tv_nsec ? -1 : 1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static void advance_deadline(struct timespec *deadline, int target_fps) {
|
|
const long frame_nsec = 1000000000L / target_fps;
|
|
|
|
deadline->tv_nsec += frame_nsec;
|
|
deadline->tv_sec += deadline->tv_nsec / 1000000000L;
|
|
deadline->tv_nsec %= 1000000000L;
|
|
}
|
|
|
|
static void sleep_until_next_frame(struct timespec *deadline, int target_fps) {
|
|
struct timespec now;
|
|
|
|
advance_deadline(deadline, target_fps);
|
|
clock_gettime(CLOCK_MONOTONIC, &now);
|
|
if (timespec_cmp(deadline, &now) > 0) {
|
|
clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, deadline, NULL);
|
|
} else {
|
|
*deadline = now;
|
|
}
|
|
}
|
|
|
|
static void randomize_column(Column *col, int maxy, const Options *opts, bool active) {
|
|
const int spawn_rows = maxy > 0 ? maxy : 1;
|
|
|
|
col->active = active;
|
|
col->tail = TAIL_MIN + irand(TAIL_RANGE);
|
|
col->speed = (BASE_SPEED_MIN + drand_unit() * BASE_SPEED_RANGE) * opts->speed_mul;
|
|
col->head_y = -(double)irand(spawn_rows);
|
|
}
|
|
|
|
static void init_columns(Column *cols, int maxx, int maxy, const Options *opts) {
|
|
for (int x = 0; x < maxx; ++x) {
|
|
randomize_column(&cols[x], maxy, opts, drand_unit() < opts->density);
|
|
}
|
|
}
|
|
|
|
static void clear_cells(Cell *cells, size_t count) {
|
|
memset(cells, 0, count * sizeof(*cells));
|
|
}
|
|
|
|
static void decay_cells(Cell *cells, size_t count, double dt) {
|
|
const float decay = (float)(TRAIL_DECAY_PER_SECOND * dt);
|
|
|
|
if (decay <= 0.0f) {
|
|
return;
|
|
}
|
|
|
|
for (size_t i = 0; i < count; ++i) {
|
|
if (cells[i].intensity <= decay) {
|
|
cells[i].intensity = 0.0f;
|
|
cells[i].ch = L' ';
|
|
continue;
|
|
}
|
|
|
|
cells[i].intensity -= decay;
|
|
}
|
|
}
|
|
|
|
static void stamp_cell(Cell *cells, int maxx, int maxy, int x, int y, wchar_t ch, float intensity) {
|
|
Cell *cell;
|
|
|
|
if (x < 0 || x >= maxx || y < 0 || y >= maxy || intensity <= 0.0f) {
|
|
return;
|
|
}
|
|
|
|
if (intensity > 1.0f) {
|
|
intensity = 1.0f;
|
|
}
|
|
|
|
cell = &cells[cell_index(x, y, maxx)];
|
|
if (intensity >= cell->intensity) {
|
|
cell->ch = ch;
|
|
cell->intensity = intensity;
|
|
}
|
|
}
|
|
|
|
static void update_columns(Column *cols, int maxx, int maxy, Cell *cells, const Options *opts, double dt) {
|
|
const size_t cell_count = (size_t)maxx * (size_t)maxy;
|
|
|
|
if (opts->fade_trail) {
|
|
decay_cells(cells, cell_count, dt);
|
|
} else {
|
|
clear_cells(cells, cell_count);
|
|
}
|
|
|
|
for (int x = 0; x < maxx; ++x) {
|
|
Column *col = &cols[x];
|
|
|
|
if (col->active) {
|
|
col->head_y += col->speed * dt;
|
|
if (col->head_y - (double)col->tail > (double)maxy) {
|
|
randomize_column(col, maxy, opts, drand_unit() < opts->density);
|
|
}
|
|
} else if (drand_unit() < opts->density * IDLE_SPAWN_RATE * dt) {
|
|
randomize_column(col, maxy, opts, true);
|
|
}
|
|
|
|
if (!col->active) {
|
|
continue;
|
|
}
|
|
|
|
{
|
|
const int head = ifloor(col->head_y);
|
|
const int tail_start = head - col->tail;
|
|
|
|
for (int y = tail_start; y < head; ++y) {
|
|
const int dist = head - y;
|
|
const double ratio = 1.0 - (double)dist / (double)(col->tail + 1);
|
|
const float intensity = (float)(0.15 + 0.75 * ratio);
|
|
|
|
stamp_cell(cells, maxx, maxy, x, y, random_glyph(), intensity);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
static void draw_trails(const Cell *cells, int maxx, int maxy) {
|
|
for (int y = 0; y < maxy; ++y) {
|
|
for (int x = 0; x < maxx; ++x) {
|
|
const Cell *cell = &cells[cell_index(x, y, maxx)];
|
|
attr_t attrs = 0;
|
|
|
|
if (cell->intensity <= 0.0f) {
|
|
continue;
|
|
}
|
|
|
|
if (cell->intensity < 0.30f) {
|
|
attrs |= A_DIM;
|
|
} else if (cell->intensity > 0.75f) {
|
|
attrs |= A_BOLD;
|
|
}
|
|
|
|
attr_set(attrs, 1, NULL);
|
|
mvaddnwstr(y, x, &cell->ch, 1);
|
|
}
|
|
}
|
|
}
|
|
|
|
static void draw_heads(const Column *cols, int maxx, int maxy, bool bold_head) {
|
|
for (int x = 0; x < maxx; ++x) {
|
|
const Column *col = &cols[x];
|
|
const int head = ifloor(col->head_y);
|
|
wchar_t glyph;
|
|
attr_t attrs = 0;
|
|
|
|
if (!col->active || head < 0 || head >= maxy) {
|
|
continue;
|
|
}
|
|
|
|
if (bold_head) {
|
|
attrs |= A_BOLD;
|
|
}
|
|
|
|
glyph = random_glyph();
|
|
attr_set(attrs, 2, NULL);
|
|
mvaddnwstr(head, x, &glyph, 1);
|
|
}
|
|
}
|
|
|
|
static void render_frame(const Column *cols, const Cell *cells, int maxx, int maxy, const Options *opts) {
|
|
erase();
|
|
draw_trails(cells, maxx, maxy);
|
|
draw_heads(cols, maxx, maxy, opts->bold_head);
|
|
attrset(A_NORMAL);
|
|
refresh();
|
|
}
|
|
|
|
static bool resize_state(Column **cols_ptr, Cell **cells_ptr, int *maxx_ptr, int *maxy_ptr, const Options *opts) {
|
|
int new_maxy;
|
|
int new_maxx;
|
|
Column *new_cols;
|
|
Cell *new_cells;
|
|
const int old_maxx = *maxx_ptr;
|
|
const int old_maxy = *maxy_ptr;
|
|
|
|
getmaxyx(stdscr, new_maxy, new_maxx);
|
|
if (new_maxx == *maxx_ptr && new_maxy == *maxy_ptr) {
|
|
return true;
|
|
}
|
|
|
|
new_cols = calloc((size_t)new_maxx, sizeof(*new_cols));
|
|
new_cells = calloc((size_t)new_maxx * (size_t)new_maxy, sizeof(*new_cells));
|
|
if (!new_cols || !new_cells) {
|
|
free(new_cols);
|
|
free(new_cells);
|
|
return false;
|
|
}
|
|
|
|
{
|
|
const int shared_maxx = new_maxx < old_maxx ? new_maxx : old_maxx;
|
|
const int shared_maxy = new_maxy < old_maxy ? new_maxy : old_maxy;
|
|
|
|
for (int x = 0; x < shared_maxx; ++x) {
|
|
new_cols[x] = (*cols_ptr)[x];
|
|
}
|
|
for (int x = shared_maxx; x < new_maxx; ++x) {
|
|
randomize_column(&new_cols[x], new_maxy, opts, drand_unit() < opts->density);
|
|
}
|
|
for (int y = 0; y < shared_maxy; ++y) {
|
|
memcpy(&new_cells[cell_index(0, y, new_maxx)],
|
|
&(*cells_ptr)[cell_index(0, y, old_maxx)],
|
|
(size_t)shared_maxx * sizeof(*new_cells));
|
|
}
|
|
}
|
|
|
|
free(*cols_ptr);
|
|
free(*cells_ptr);
|
|
*cols_ptr = new_cols;
|
|
*cells_ptr = new_cells;
|
|
*maxx_ptr = new_maxx;
|
|
*maxy_ptr = new_maxy;
|
|
clear();
|
|
return true;
|
|
}
|
|
|
|
static bool handle_input(bool *paused, bool *needs_resize) {
|
|
int ch;
|
|
|
|
while ((ch = getch()) != ERR) {
|
|
if (ch == 'q' || ch == 27) {
|
|
return false;
|
|
}
|
|
if (ch == 'p' || ch == 'P') {
|
|
*paused = !*paused;
|
|
continue;
|
|
}
|
|
if (ch == KEY_RESIZE) {
|
|
*needs_resize = true;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
static bool init_screen(void) {
|
|
if (initscr() == NULL) {
|
|
return false;
|
|
}
|
|
|
|
if (has_colors()) {
|
|
start_color();
|
|
use_default_colors();
|
|
init_pair(1, COLOR_GREEN, -1);
|
|
init_pair(2, COLOR_WHITE, -1);
|
|
}
|
|
|
|
cbreak();
|
|
noecho();
|
|
curs_set(0);
|
|
keypad(stdscr, TRUE);
|
|
nodelay(stdscr, TRUE);
|
|
return true;
|
|
}
|
|
|
|
int main(int argc, char **argv) {
|
|
Options opts;
|
|
ParseResult parse_result;
|
|
Column *cols = NULL;
|
|
Cell *cells = NULL;
|
|
int maxy;
|
|
int maxx;
|
|
bool paused = false;
|
|
bool running = true;
|
|
struct timespec prev_tick;
|
|
struct timespec frame_deadline;
|
|
|
|
parse_result = parse_args(argc, argv, &opts);
|
|
if (parse_result == PARSE_HELP) {
|
|
return 0;
|
|
}
|
|
if (parse_result == PARSE_ERROR) {
|
|
return 1;
|
|
}
|
|
|
|
setlocale(LC_ALL, "");
|
|
if (!init_screen()) {
|
|
fprintf(stderr, "Failed to initialize ncurses\n");
|
|
return 1;
|
|
}
|
|
|
|
getmaxyx(stdscr, maxy, maxx);
|
|
cols = calloc((size_t)maxx, sizeof(*cols));
|
|
cells = calloc((size_t)maxx * (size_t)maxy, sizeof(*cells));
|
|
if (!cols || !cells) {
|
|
endwin();
|
|
free(cols);
|
|
free(cells);
|
|
fprintf(stderr, "OOM\n");
|
|
return 1;
|
|
}
|
|
|
|
init_columns(cols, maxx, maxy, &opts);
|
|
clock_gettime(CLOCK_MONOTONIC, &prev_tick);
|
|
frame_deadline = prev_tick;
|
|
|
|
while (running) {
|
|
struct timespec now;
|
|
bool needs_resize = false;
|
|
double dt;
|
|
int current_maxy;
|
|
int current_maxx;
|
|
|
|
running = handle_input(&paused, &needs_resize);
|
|
|
|
clock_gettime(CLOCK_MONOTONIC, &now);
|
|
dt = elapsed_seconds(&prev_tick, &now);
|
|
if (dt > MAX_FRAME_DT) {
|
|
dt = MAX_FRAME_DT;
|
|
}
|
|
prev_tick = now;
|
|
|
|
getmaxyx(stdscr, current_maxy, current_maxx);
|
|
if (needs_resize || current_maxx != maxx || current_maxy != maxy) {
|
|
if (!resize_state(&cols, &cells, &maxx, &maxy, &opts)) {
|
|
running = false;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (!paused) {
|
|
update_columns(cols, maxx, maxy, cells, &opts, dt);
|
|
}
|
|
|
|
render_frame(cols, cells, maxx, maxy, &opts);
|
|
sleep_until_next_frame(&frame_deadline, opts.target_fps);
|
|
}
|
|
|
|
endwin();
|
|
free(cols);
|
|
free(cells);
|
|
return 0;
|
|
}
|