Skip to content

Instantly share code, notes, and snippets.

@idimiter
Last active May 8, 2017 16:57
Show Gist options
  • Save idimiter/dc5db630e894c858b537e6b46977e577 to your computer and use it in GitHub Desktop.
Save idimiter/dc5db630e894c858b537e6b46977e577 to your computer and use it in GitHub Desktop.
basic 3D object draw in terminal
// Dimitar T. Dimitrov 2017
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
const int width = 64;
const int height = 64;
char screen[width * height];
float o[8][3] = {
{ 1, -1, -1},
{ 1, -1, 1},
{-1, -1, 1},
{-1, -1, -1},
{ 1, 1, -1},
{ 1, 1, 1},
{-1, 1, 1},
{-1, 1, -1}};
int camx = 30;
int camy = 40;
int camz = 3;
void set(int x, int y, char c) {
int i = y * width + x;
if ((i > (width * height)) || i < 0)
return;
screen[i] = c;
}
void rotate(float *x, float *y, float angle) {
float cs = cos(angle);
float sn = sin(angle);
float tmp = cs * (*x) - sn * (*y);
*y = sn * (*x) + cs * (*y);
*x = tmp;
}
int main() {
while(42) {
memset(screen, ' ', width * height);
for (int i = 0; i < width * height; i += width)
screen[i] = 0x0a;
screen[width * height - 1] = 0;
for (int i = 0; i < 8; i++) {
int x = (int) (o[i][0] * 10 / (o[i][2] + camz) + camx);
int y = (int) (o[i][1] * 10 / (o[i][2] + camz) + camy);
rotate(&o[i][0], &o[i][1], 0.2f);
rotate(&o[i][2], &o[i][0], 0.1f);
set(x, y, 46);
}
printf("\x1b[2J%s\n", screen);
usleep(100000);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment