/*
 * Copyright (c) 2026 betterip (betterip.org)
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 * Program info:
 * 
 * Program generates colorful brownian movement-like traces in your terminal.
 * 
 * It can be compiled easily under Linux under gcc, clang, tcc, for example with:
 * "gcc main.c -o main -std=c89 -Wall -Wextra -pedantic -ansi -Ofast"
 * (might throw a warning, it should be fine to just ignore it.)
 * 
 * Precompiled binary can be had at "https://betterip.org/downloads/brownian-bin-1.tar.xz".
 * It targets i486 linux and is linked statically. Contains both stripped and unstripped versions.
 * It's presets are:
 * - 1000 for mem length
 * - 60 fps
 * - '@'as the "pixel" character
 *
 * This source code can be had at "https://betterip.org/downloads/brownian-1.tar.xz".
 * It is also mirrored on github at "https://github.com/betterip/brownian".
 *
 * Known issues:
 * - looks bad in default (light mode) xterm; will not fix - fix your vty.
 * - needs truecolor support; will not fix - it'd look shit, you can try that in the standard linux console.
 * - code can be better; will probably fix when i have time (and i decide to put in the effort).
 *
 * TODO:
 * make code more readable
 * make code more efficient
 * add+improve comments.
 */

#define _NETBSD_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#include <sys/select.h>
#include <string.h>

static const int length 	= 1000;
static const int fps		= 60;
static const char px_char	= '@';

struct Pixel  {
	uint8_t r, g, b;
	uint32_t x, y;
};

/* input must be non zero */
uint32_t xorshift32(uint32_t *state) {
	uint32_t x = *state;
	x ^= x << 13;
	x ^= x >> 17;
	x ^= x << 5;
	return *state = x;
}

void disable_canonical_and_echo(struct termios info) {
	/* refined from a couple of stackoverflow conversations */
	tcgetattr(0, &info);		/* get current term info, 0 is the fd fir stdin */
	info.c_lflag &= ~ICANON;	/* disable canonical */
	info.c_lflag &= ~ECHO;		/* disable echo */
	info.c_cc[VMIN] = 0;		/* make it so we wait for one keystroke or more */
	info.c_cc[VTIME] = 0;		/* no timeout */
	tcsetattr(0, TCSANOW, &info);	/* apply everything */
}

void enable_canonical_and_echo(struct termios info) {
	/* see function above */
	tcgetattr(0, &info);
	info.c_lflag |= ICANON;
	info.c_lflag |= ECHO;
	tcsetattr(0, TCSANOW, &info);
}

int kpress_noblock() {
	/* code stolen from internet, modified to MY liking */
	fd_set fds;				/* get ALL file descriptors (i think) */
	struct timeval tv = { 0L, 0L };		/* immediate return */
	FD_ZERO(&fds);				/* clear all of them */
	FD_SET(STDIN_FILENO, &fds);		/* select stdin */
	return select(
		STDIN_FILENO + 1,		/* check up to stdin (0) - "STDIN_FILENO + 1" is the limit we stay BELOW when we're checking */
		&fds,				/* are all file descriptors in "fds" readable? */
		NULL,				/* we don't care if they're writeable */
		NULL,				/* extra crap - not interested */
		&tv				/* our timeout (0 means immediate) */
	);

}

void draw_color_pixel(int x, int y, int r, int g, int b, char ch) {
	printf("\x1b[38;2;%d;%d;%dm\x1b[%d;%dH%c", r, g, b, y, x, ch);
}

void clrscr() {
	printf("\x1b[2J");
	printf("\x1b[H");
}

int main() {
	uint32_t state = (uint32_t)time(NULL);
	struct winsize w;
	struct termios info;
	int x, y, width, height, delta_t, i, j, r, g, b, erase;
	struct Pixel *px_mem = (struct Pixel*)malloc(length * sizeof(struct Pixel));
	uint8_t *px_mask = (uint8_t*)malloc(length);
	struct Pixel px;
	char ch;
	uint32_t rand;

	delta_t = 1000000/fps;
	setvbuf(stdout, NULL, _IONBF, 0);

	ioctl(0, TIOCGWINSZ, &w);
	height = w.ws_row;
	width  = w.ws_col;

	x = width / 2;
	y = height / 2;

	r = 0;
	g = 0;
	b = 0;

	px.x = x;
	px.y = y;
	px.r = r;
	px.g = g;
	px.b = b;	

	for (i = 0; i < length; i++) {
		px_mem[i] = px;
	}

	if (state == 0) {
		state = 69420;
	}

	if (px_mem == NULL) {
		printf("malloc fail!\n");
		return 1;
	}

	disable_canonical_and_echo(info);


	clrscr();
	printf("\x1b[?25l"); /* make cursor invisible */

	while (1) {
		memset(px_mask, 1, length);
		if (kpress_noblock()) {
			ch = getchar();
			if (ch == 'q') {
				break;
			}
		}


		rand = xorshift32(&state);

		r += ((rand >> 24) % 15) - 7;
		g += ((rand >> 16) % 15) - 7;
		b += ((rand >>  8) % 15) - 7;

		if (r < 0) {
			r = 0;
		}
		if (r > 255) {
			r = 255;
		}
		if (g < 0) {
			g = 0;
		}
		if (g > 255) {
			g = 255;
		}
		if (b < 0) {
			b = 0;
		}
		if (b > 255) {
			b = 255;
		}

		i = rand & 7;

		switch (i) {
			case 0:
				x --;
				y --;
				break;
			case 1:
				y --;
				break;
			case 2:
				x ++;
				y --;
				break;
			case 3:
				x --;
				break;
			case 4:
				x ++;
				break;
			case 5:
				x --;
				y ++;
				break;
			case 6:
				y ++;
				break;
			case 7:
				x ++;
				y ++;
				break;
		}

		if (x < 0) {
			x = width + x;
		}
		if (x >= width) {
			x -= width;
		}
		if (y < 0) {
			y = height + y;
		}
		if (y >= height) {
			y -= height;
		}

		px.x = x;
		px.y = y;
		px.r = r;
		px.g = g;
		px.b = b;


		erase = 1;
		for (i = 0; i < length - 1; i++) {
			if (px_mem[length - 1].x == px_mem[i].x && px_mem[length - 1].y == px_mem[i].y) {
				erase = 0;
			}
		}
		if (erase) {
			draw_color_pixel(
				px_mem[length - 1].x,
				px_mem[length - 1].y,
				0,
				0,
				0,
				' '
			);
		}

		for (i = 1; i < length; i++) {
			px_mem[length - i] = px_mem[length - 1 - i];
		}

		px_mem[0] = px;


		for (i = 0; i < length; i++) {
			if (px_mask[i]) {
				for (j = i; j < length; j++) {
					if (j != i && px_mem[i].x == px_mem[j].x && px_mem[i].y == px_mem[j].y) {
						px_mask[j] = 0;
					}
				}
			}
		}


		for (i = 0; i < length; i++) {
			px = px_mem[i];
			if (px_mask[i]) {
			draw_color_pixel(px.x, px.y, px.r, px.g, px.b, px_char);
			}
		}

		usleep(delta_t);
	}

	printf("\x1b[?25h"); /* make cursor visible again */

	enable_canonical_and_echo(info);
	clrscr();
	return 0;
}
