ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
digital_rain.c
Go to the documentation of this file.
1
6
7#include "backends.h"
8#include <recast/defer.h>
12#include <ascii-chat/log/log.h>
14#include <math.h>
15#include <stdlib.h>
16#include <string.h>
17#include <stdio.h>
18
19/* ============================================================================
20 * Math Helpers
21 * ============================================================================ */
22
23#ifndef M_PI
24#define M_PI 3.14159265358979323846
25#endif
26
31static float random_float(float x, float y) {
32 float dt = x * 12.9898f + y * 78.233f;
33 float sn = fmodf(dt, (float)M_PI);
34 return fmodf(sinf(sn) * 43758.5453f, 1.0f);
35}
36
40static inline float fract(float x) {
41 return x - floorf(x);
42}
43
44/* ============================================================================
45 * Core Algorithm
46 * ============================================================================ */
47
60static float get_rain_brightness(digital_rain_t *rain, int col, int row, float sim_time, float *head) {
61 *head = 0.0f;
62 if (col < 0 || col >= rain->num_columns)
63 return 0.0f;
64 const digital_rain_column_t *column = &rain->columns[col];
65 float length = rain->raindrop_length * (0.75f + 0.5f * random_float((float)col + 0.3f, 0));
66 float gap = length * (0.25f + 0.65f * random_float((float)col + 0.4f, 0));
67 float period = length + gap;
68 float travel = column->time_offset + sim_time * rain->fall_speed * column->speed_multiplier;
69 travel += 0.35f * sinf(sim_time * 0.7f + column->phase_offset);
70 float distance = fract((travel - (float)row) / period) * period;
71 float head_distance = fminf(distance, period - distance);
72 *head = expf(-2.5f * head_distance * head_distance);
73 float tail = powf(fmaxf(0.0f, 1.0f - distance / length), 0.65f);
74 // Keep the source readable between streams; the head and tail add contrast.
75 return 0.45f + 0.55f * tail;
76}
77
78// Ordered by approximate ink coverage in a monospace terminal. Keeping mutations
79// within a group preserves the source image's shading and leaves spaces untouched.
80static const char *glyph_groups[] = {".,'`", ":;-_", "!|/\\()[]{}", "iltfrxnvczXYUJLC", "oahkbdpqwmZO0Q", "*+?%&$#@MWB8"};
81
83 if (codepoint > 126 || codepoint <= 32)
84 return -1;
85 for (size_t i = 0; i < sizeof(glyph_groups) / sizeof(glyph_groups[0]); i++)
86 if (strchr(glyph_groups[i], (int)codepoint))
87 return (int)i;
88 return -1;
89}
90
91static uint32_t mutate_glyph(uint32_t codepoint, int col, int row, float time) {
92 int group = digital_rain_glyph_group(codepoint);
93 if (group < 0)
94 return codepoint;
95 // Independent periods and phase offsets avoid synchronized full-grid flicker.
96 float seed = random_float((float)col + 1.3f, (float)row + 2.7f);
97 unsigned int cycle = (unsigned int)floorf(time * (1.2f + 2.0f * seed) + seed * 13.0f);
98 uint32_t hash = (uint32_t)((uint64_t)(col + 1) * UINT64_C(73856093) ^ (uint64_t)(row + 1) * UINT64_C(19349663) ^ (uint64_t)cycle * UINT64_C(83492791));
99 hash ^= hash >> 16;
100 hash = (uint32_t)((uint64_t)hash * UINT64_C(0x7feb352d));
101 hash ^= hash >> 15;
102 const char *choices = glyph_groups[group];
103 return (uint8_t)choices[hash % strlen(choices)];
104}
105
106/* ============================================================================
107 * Initialization and Cleanup
108 * ============================================================================ */
109
110digital_rain_t *digital_rain_init(int num_columns, int num_rows) {
111 if (num_columns <= 0 || num_rows <= 0) {
112 log_error("invalid dimensions %dx%d", num_columns, num_rows);
113 return NULL;
114 }
115
117 if (!rain) {
118 log_error("failed to allocate context");
119 return NULL;
120 }
121 defer_named(release_rain, SAFE_FREE(rain));
122
123 rain->num_columns = num_columns;
124 rain->num_rows = num_rows;
125
126 // Allocate column state array
127 rain->columns = SAFE_CALLOC((size_t)num_columns, sizeof(digital_rain_column_t), digital_rain_column_t *);
128 if (!rain->columns) {
129 log_error("failed to allocate column array");
130 return NULL;
131 }
132 defer_named(release_columns, SAFE_FREE(rain->columns));
133
134 // Allocate previous brightness array
135 size_t grid_size = (size_t)num_columns * (size_t)num_rows;
136 rain->previous_brightness = SAFE_CALLOC(grid_size, sizeof(float), float *);
137 if (!rain->previous_brightness) {
138 log_error("failed to allocate brightness array");
139 return NULL;
140 }
141
142 // Initialize per-column random offsets
143 for (int col = 0; col < num_columns; col++) {
144 digital_rain_column_t *column = &rain->columns[col];
145 column->time_offset = random_float((float)col, 0.0f) * 1000.0f;
146 column->speed_multiplier = random_float((float)col + 0.1f, 0.0f) * 0.5f + 0.5f;
147 column->phase_offset = random_float((float)col + 0.2f, 0.0f) * (float)M_PI * 2.0f;
148 }
149
150 // Set default parameters
159 rain->rainbow_mode = false;
160 rain->first_frame = true;
161 rain->time = 0.0f;
162
163 animation_init(&rain->animation, "digital_rain", (animation_config_t){.type = ANIMATION_DIGITAL_RAIN, .fps = 60, .speed = 1, .hidden_policy = ANIMATION_HIDDEN_CONTINUE});
164 animation_sample_t initial;
165 animation_update(&rain->animation, 0, &initial);
166 log_info("Digital rain initialized: %dx%d grid", num_columns, num_rows);
167 defer_cancel(release_columns);
168 defer_cancel(release_rain);
169 return rain;
170}
171
173 if (!rain) {
174 return;
175 }
176
178 SAFE_FREE(rain->columns);
180 SAFE_FREE(rain);
181}
182
184 if (!rain) {
185 return;
186 }
187
189 rain->animation_timestamp_ns = 0;
190 animation_sample_t initial;
191 animation_update(&rain->animation, 0, &initial);
192 rain->time = 0.0f;
193 rain->first_frame = true;
194
195 // Clear previous brightness
196 size_t grid_size = (size_t)rain->num_columns * (size_t)rain->num_rows;
197 memset(rain->previous_brightness, 0, grid_size * sizeof(float));
198}
199
200/* ============================================================================
201 * Parameter Adjustment
202 * ============================================================================ */
203
205 if (rain) {
206 rain->fall_speed = speed;
207 }
208}
209
211 if (rain) {
212 rain->raindrop_length = length;
213 }
214}
215
217 if (rain) {
218 rain->color_r = r;
219 rain->color_g = g;
220 rain->color_b = b;
221 }
222}
223
224void digital_rain_set_color_from_filter(digital_rain_t *rain, color_filter_t filter) {
225 if (!rain) {
226 return;
227 }
228
229 // If no filter is set, use default Matrix green
230 if (filter == COLOR_FILTER_NONE) {
231 rain->rainbow_mode = false;
233 return;
234 }
235
236 // Rainbow mode: enable dynamic color cycling
237 if (filter == COLOR_FILTER_RAINBOW) {
238 rain->rainbow_mode = true;
239 // Set initial color to red (will be overridden during rendering)
240 digital_rain_set_color(rain, 255, 0, 0);
241 return;
242 }
243
244 // Get color from filter metadata
245 rain->rainbow_mode = false;
246 const color_filter_def_t *filter_def = color_filter_get_metadata(filter);
247 if (filter_def) {
248 digital_rain_set_color(rain, filter_def->r, filter_def->g, filter_def->b);
249 }
250}
251
252/* ============================================================================
253 * Frame Processing
254 * ============================================================================ */
255
261static const char *parse_ansi_color(const char *str, int *r, int *g, int *b, bool *is_foreground) {
262 if (*str != '\033') {
263 return NULL;
264 }
265
266 const char *p = str + 1;
267 if (*p != '[') {
268 return NULL;
269 }
270 p++; // Skip [
271
272 // Check for foreground (38) or background (48) truecolor
273 if (*p == '3' && *(p + 1) == '8') {
274 *is_foreground = true;
275 p += 2;
276 } else if (*p == '4' && *(p + 1) == '8') {
277 *is_foreground = false;
278 p += 2;
279 } else {
280 return NULL;
281 }
282
283 // Expect ";2;" for RGB mode
284 if (*p != ';' || *(p + 1) != '2' || *(p + 2) != ';') {
285 return NULL;
286 }
287 p += 3;
288
289 // Parse R
290 *r = 0;
291 while (*p >= '0' && *p <= '9') {
292 *r = *r * 10 + (*p - '0');
293 p++;
294 }
295 if (*p != ';')
296 return NULL;
297 p++;
298
299 // Parse G
300 *g = 0;
301 while (*p >= '0' && *p <= '9') {
302 *g = *g * 10 + (*p - '0');
303 p++;
304 }
305 if (*p != ';')
306 return NULL;
307 p++;
308
309 // Parse B
310 *b = 0;
311 while (*p >= '0' && *p <= '9') {
312 *b = *b * 10 + (*p - '0');
313 p++;
314 }
315 if (*p != 'm')
316 return NULL;
317 p++;
318
319 return p;
320}
321
326static const char *skip_ansi_sequence(const char *str) {
327 if (*str != '\033') {
328 return str;
329 }
330
331 str++; // Skip ESC
332
333 if (*str == '[') {
334 str++; // Skip [
335 // Skip until we find a terminator (@ through ~)
336 while (*str && !(*str >= '@' && *str <= '~')) {
337 str++;
338 }
339 if (*str) {
340 str++; // Skip terminator
341 }
342 }
343
344 return str;
345}
346
347static int generate_rain_color(char *buf, size_t size, digital_rain_t *rain, float brightness, float head, float luminance, bool foreground) {
348 // Source luminance shapes both the saturated body and the pale leading glint.
349 float light = foreground ? 0.80f + 0.20f * sqrtf(luminance) : luminance;
350 // Limit whitening so even boosted heads retain the selected rain hue.
351 float white = fminf(0.40f, head * rain->cursor_brightness * 0.18f);
352 float level = fminf(1.0f, brightness + head * 0.25f) * light;
353 int r = (int)((rain->color_r + (255 - rain->color_r) * white) * level);
354 int g = (int)((rain->color_g + (255 - rain->color_g) * white) * level);
355 int b = (int)((rain->color_b + (255 - rain->color_b) * white) * level);
356 return snprintf(buf, size, "\033[%d;2;%d;%d;%dm", foreground ? 38 : 48, r, g, b);
357}
358
359char *digital_rain_apply(digital_rain_t *rain, const char *frame, float delta_time) {
360 if (!rain || !frame || !isfinite(delta_time) || delta_time < 0 || (double)delta_time * 1e9 >= (double)(UINT64_MAX - rain->animation_timestamp_ns))
361 return NULL;
363 return NULL;
364 uint64_t now = rain->animation_timestamp_ns + (uint64_t)((double)delta_time * 1e9);
365 animation_sample_t sample;
366 if (animation_update(&rain->animation, now, &sample) != ASCIICHAT_OK)
367 return NULL;
368 rain->animation_timestamp_ns = now;
369 char *output = NULL;
370 animation_target_t target = {.type = ANIMATION_TARGET_ANSI, .ansi = {.input = frame, .out = &output, .rain = rain}};
371 if (animation_apply(&sample, &target) != ASCIICHAT_OK)
372 return NULL;
373 return output;
374}
375
376char *digital_rain_render_at(digital_rain_t *rain, const char *frame, float seconds) {
377 if (!rain || !frame) {
378 log_error("NULL parameter");
379 return NULL;
380 }
381
382 if (!isfinite(seconds) || seconds < 0)
383 return NULL;
384 float elapsed = fmaxf(0.0f, seconds - rain->time);
385 rain->time = seconds;
386 float sim_time = seconds;
387 // brightness_decay retains its meaning as a blend factor at 60 Hz.
388 float decay = fminf(1.0f, fmaxf(0.0f, rain->brightness_decay));
389 float alpha = elapsed > 0 ? 1.0f - powf(1.0f - decay, elapsed * 60.0f) : 0.0f;
390
391 if (rain->rainbow_mode)
392 color_filter_calculate_rainbow(sim_time, &rain->color_r, &rain->color_g, &rain->color_b);
393
394 size_t input_len = strlen(frame);
395 if (input_len > (SIZE_MAX - 1024) / 48)
396 return NULL;
397 size_t output_capacity = input_len * 48 + 1024;
398 char *output = SAFE_MALLOC(output_capacity, char *);
399 if (!output)
400 return NULL;
401
402 const char *src = frame;
403 char *dst = output;
404 size_t remaining = output_capacity;
405 int col = 0, row = 0;
406 float foreground_luminance = 1.0f, background_luminance = 0.0f;
407 bool has_background = false;
408 bool colored = false;
409
410 while (*src && remaining > 100) {
411 if (*src == '\033') {
412 int r, g, b;
413 bool foreground;
414 const char *after = parse_ansi_color(src, &r, &g, &b, &foreground);
415 if (after) {
416 float luminance = fminf(1.0f, fmaxf(0.0f, (0.2126f * r + 0.7152f * g + 0.0722f * b) / 255.0f));
417 if (foreground)
418 foreground_luminance = luminance;
419 else {
420 background_luminance = luminance;
421 has_background = true;
422 }
423 src = after;
424 } else {
425 after = skip_ansi_sequence(src);
426 size_t count = (size_t)(after - src);
427 if ((count == 4 && memcmp(src, "\033[0m", 4) == 0) || (count == 3 && memcmp(src, "\033[m", 3) == 0)) {
428 foreground_luminance = 1.0f;
429 has_background = false;
430 }
431 memcpy(dst, src, count);
432 dst += count;
433 remaining -= count;
434 src = after;
435 }
436 continue;
437 }
438 if (*src == '\n' || *src == '\r') {
439 if (*src == '\n')
440 row++;
441 col = 0;
442 *dst++ = *src++;
443 remaining--;
444 continue;
445 }
446
447 float head;
448 float brightness = get_rain_brightness(rain, col, row, sim_time, &head);
449 // Update once per cell, independently of how many ANSI sequences precede it.
450 if (row < rain->num_rows && col < rain->num_columns) {
451 size_t idx = (size_t)row * (size_t)rain->num_columns + (size_t)col;
452 if (!rain->first_frame)
453 brightness = rain->previous_brightness[idx] + (brightness - rain->previous_brightness[idx]) * alpha;
454 rain->previous_brightness[idx] = brightness;
455 }
456 int count = generate_rain_color(dst, remaining, rain, brightness, head, foreground_luminance, true);
457 colored = true;
458 dst += count;
459 remaining -= (size_t)count;
460 if (has_background) {
461 count = generate_rain_color(dst, remaining, rain, brightness, head, background_luminance, false);
462 dst += count;
463 remaining -= (size_t)count;
464 }
465 uint32_t codepoint;
466 int bytes = utf8_decode((const uint8_t *)src, &codepoint);
467 if (bytes <= 0) {
468 bytes = 1;
469 codepoint = (uint8_t)*src;
470 }
471 if (bytes == 1 && codepoint > 32 && codepoint < 127) {
472 *dst++ = (char)mutate_glyph(codepoint, col, row, sim_time);
473 src++;
474 remaining--;
475 } else {
476 memcpy(dst, src, (size_t)bytes);
477 dst += bytes;
478 src += bytes;
479 remaining -= (size_t)bytes;
480 }
481 col++;
482 }
483 // Monochrome input has no trailing SGR reset to copy. The effect introduces
484 // colors itself, so every colored result must restore terminal attributes.
485 if (colored) {
486 const char reset[] = "\033[0m";
487 if (remaining < sizeof(reset)) {
488 SAFE_FREE(output);
489 return NULL;
490 }
491 memcpy(dst, reset, sizeof(reset));
492 } else {
493 *dst = '\0';
494 }
495 rain->first_frame = false;
496 return output;
497}
char * digital_rain_render_at(digital_rain_t *rain, const char *frame, float seconds)
Matrix-style digital rain effect for ASCII frames.
#define M_PI
Definition effects.c:6
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
unsigned char uint8_t
@ ASCIICHAT_OK
Definition error_codes.h:50
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
int utf8_decode(const uint8_t *s, uint32_t *codepoint)
Decode a UTF-8 sequence to a Unicode codepoint.
Definition utf8.c:27
void digital_rain_set_raindrop_length(digital_rain_t *rain, float length)
Set digital rain raindrop length.
void digital_rain_reset(digital_rain_t *rain)
Reset digital rain effect state.
#define DIGITAL_RAIN_DEFAULT_CURSOR_BRIGHTNESS
Cursor brightness multiplier.
#define DIGITAL_RAIN_DEFAULT_BRIGHTNESS_DECAY
Default brightness decay factor.
void digital_rain_set_color_from_filter(digital_rain_t *rain, color_filter_t filter)
Set digital rain color from color filter.
void digital_rain_set_fall_speed(digital_rain_t *rain, float speed)
Set digital rain fall speed.
void digital_rain_set_color(digital_rain_t *rain, uint8_t r, uint8_t g, uint8_t b)
Set digital rain color.
#define DIGITAL_RAIN_DEFAULT_COLOR_B
const color_filter_def_t * color_filter_get_metadata(color_filter_t filter)
Get color filter metadata by enum value.
#define DIGITAL_RAIN_DEFAULT_COLOR_R
Default Matrix green color (R, G, B).
int digital_rain_glyph_group(uint32_t codepoint)
#define DIGITAL_RAIN_DEFAULT_ANIMATION_SPEED
Default animation speed multiplier.
void digital_rain_destroy(digital_rain_t *rain)
Destroy digital rain effect context.
#define DIGITAL_RAIN_DEFAULT_FALL_SPEED
Default fall speed for raindrops.
char * digital_rain_apply(digital_rain_t *rain, const char *frame, float delta_time)
Apply digital rain effect to ASCII frame.
void color_filter_calculate_rainbow(float time, uint8_t *r, uint8_t *g, uint8_t *b)
Calculate rainbow color from time (3.5s cycle).
struct digital_rain digital_rain_t
Digital rain effect context.
#define DIGITAL_RAIN_DEFAULT_RAINDROP_LENGTH
Default raindrop length.
#define DIGITAL_RAIN_DEFAULT_COLOR_G
digital_rain_t * digital_rain_init(int num_columns, int num_rows)
Initialize digital rain effect context.
📝 Logging API with multiple log levels and terminal output control
🔢 Mathematical Utility Functions
🔤 String Manipulation and Shell Escaping Utilities
For animation config, this is the live record that ties type, fps, speed, hidden_policy together....
For color filter def, this is the live record that ties name, cli_name, r, g together....
uint8_t b
RGB color values for this filter.
digital rain column keeps the values that move through the subsystem: time_offset,...
float phase_offset
Phase offset for wobble variation.
float time_offset
Random time offset for this column (prevents synchronization).
float speed_multiplier
Speed variation multiplier (0.5 to 1.0).
uint8_t color_g
Matrix green G component.
float fall_speed
Base fall speed multiplier.
uint8_t color_b
Matrix green B component.
int num_rows
Number of rows in grid.
float brightness_decay
Brightness smoothing factor (0-1).
float time
Current simulation time (accumulated).
float raindrop_length
Length of each raindrop (in cells).
uint8_t color_r
Matrix green R component.
animation_t animation
Producer-owned animation clock.
float animation_speed
Overall animation speed multiplier.
bool first_frame
True if this is the first frame.
float cursor_brightness
Cursor brightness multiplier.
bool rainbow_mode
True if rainbow color cycling is enabled.
float * previous_brightness
Previous frame brightness (for smoothing).
uint64_t animation_timestamp_ns
int num_columns
Number of columns in grid.
digital_rain_column_t * columns
Per-column state array.
🔤 UTF-8 Encoding and Decoding Utilities
void animation_destroy(animation_t *a)
asciichat_error_t animation_update(animation_t *a, uint64_t now, animation_sample_t *out)
void animation_reset(animation_t *a)
asciichat_error_t animation_init(animation_t *a, const char *name, animation_config_t config)
asciichat_error_t animation_set_speed(animation_t *a, double speed)
asciichat_error_t animation_apply(const animation_sample_t *s, animation_target_t *t)
@ ANIMATION_TARGET_ANSI