Ejemplo n.º 1
0
void player_colision()
{
	int i;
	int point = 0;

	for ( i = 0; i < e.count; i++ ) {
		if ( pos_test( p.p[0].x, p.p[0].y, e.p[i].x, e.p[i].y ) ) {
			p.point += e.p[i].point;
			b.point = e.p[i].point;
    		b.x = e.p[i].x;
    		b.y = e.p[i].y;
    		b.active = 1;
    		b.update = 1;
    		b.b_count = 5;
			eat_set( i, GAME_WIDTH, GAME_HEIGHT );
			player_add();
		}
	}
	for ( i = 1; i < p.count; i++ ) {
		if ( pos_test( p.p[0].x, p.p[0].y, p.p[i].x, p.p[i].y ) ) {
			point = (p.count - i) * EAT_POINT;
			printf("cannibalism: adding %d points!\n", point);
			p.c = color_set( 0.8f, 0.2f, 0.2f );
			p.point += point;
			p.count = i-1;
			b.point = point;
    		b.x = p.p[0].x;
    		b.y = p.p[0].y;
    		b.active = 1;
    		b.update = 1;
    		b.b_count = 5;
		}
	}
	for ( i = 0; i < w.count; i++ ) {
		if ( pos_test( p.p[0].x, p.p[0].y, w.p[i].x, w.p[i].y ) ) {
        	player_set( PLAYER_X, PLAYER_Y );
        	wall_set( GAME_WIDTH, GAME_HEIGHT );
        	eat_set( 0, GAME_WIDTH, GAME_HEIGHT );
			game_over = 1;
		}
	}
	if ( p.p[0].x >= (float)GAME_WIDTH ) {
		p.p[0].x = 0.0f;
	}
	if ( p.p[0].x < 0.0f ) {
		p.p[0].x = (float)GAME_WIDTH;
	}
	if ( p.p[0].y >= (float)GAME_HEIGHT ) {
		p.p[0].y = 0.0f;
	}
	if ( p.p[0].y < 0.0f ) {
		p.p[0].y = (float)GAME_HEIGHT;
	}
}
Ejemplo n.º 2
0
char escolha_inicial() {
    char c;
    int first = 1;
    do {
        move(0, 0);
        addstr("Que jogador fará o primeiro movimento (");
        if(!first)
            color_set(RED_PAIR, 0);
        addstr("M/R");
        if(!first)
            color_set(DEFAULT_PAIR, 0);
        addstr(")? ");
        refresh();
        c = getch();
        first = 0;
    } while(c != 'M' && c != 'R');
    if(c == 'M')
        return MERCENARIOS;
    return GUARDAS;
}
Ejemplo n.º 3
0
Material::Material()
{
  diffuse.reset(nullptr);
  normal.reset(nullptr);
  height.reset(nullptr);
  specular.reset(nullptr);
  cubemap.reset(nullptr);

  glm::vec3 zero(1, 0, 0);
  color_set(zero, zero, zero, 0);
}
Ejemplo n.º 4
0
void setWhite( Image *src ) {
  int i, j;
  Color White;

  color_set(&White, 1.0, 1.0, 1.0);

  for(i=0;i<src->rows;i++) {
    for(j=0;j<src->cols;j++) {
      image_setColor( src, i, j, White );
    }
  }
}
Ejemplo n.º 5
0
static int console_usecolorpair(struct NcConsole* self, int pair) {
	if(pair > MAX_PAIR) return 0;
	if (!self_hasColors(self)) return 0;
	self->lastused.fgcol = self->active.fgcol;
	self->lastused.bgcol = self->active.bgcol;

	//if (self->lastattr) wattr_off(stdscr,self->lastattr,NULL);
	self->lastattr = COLOR_PAIR(pair + MIN_PAIR);
	color_set(pair + MIN_PAIR, NULL);
	//wattr_on(stdscr, self->lastattr, NULL);
	return 1;
}
Ejemplo n.º 6
0
void wall_set(int dx, int dy)
{
	int i;

	w.count = rand()%WALL_MAX;
	w.c = color_set( 0.2f, 0.2f, 0.8f );
	w.p = weMalloc( w.count * sizeof(position) );
	for ( i = 0; i < w.count; i++ ) {
		w.p[i].x = ( rand()%( dx/(int)delta ) * (int)delta )*1.0f;
		w.p[i].y = ( rand()%( dy/(int)delta ) * (int)delta )*1.0f;
	}
}
Ejemplo n.º 7
0
void wtfprint(const char *str, int percent)
{
	int i = rand()%10;
	while(*str) {
		color_set(30+i);
		fputc(*str, stdout);
		fg_color_clr();
		if (rand()%100 <= percent)
			i = (i+1)%10;
		*str++;
	}

}
Ejemplo n.º 8
0
/**
 * @brief Set the curses drawing color
 */
static void Sv_DrawConsole_Color(int32_t color) {

	if (!has_colors()) {
		return;
	}

	color_set(color, NULL);

	if (color == 3 || color == 0) {
		attron(A_BOLD);
	} else {
		attroff(A_BOLD);
	}
}
Ejemplo n.º 9
0
static void console_restorecolors(struct NcConsole *self) {
	int i, maxc = MIN(self->maxcolors, CONSOLE_MAXSAVECOLORS);
	for (i = MIN_COLOR; i < maxc; i++) {
		init_color(i,
			console_tothousand(self->org_colors[i].r),
			console_tothousand(self->org_colors[i].g),
			console_tothousand(self->org_colors[i].b)
		);
	}
	for (i = MIN_PAIR; i < maxc+MIN_PAIR; i++) {
		init_pair(i, self->org_fgcolors[i-MIN_PAIR], self->org_bgcolors[i-MIN_PAIR]);
	}
	color_set(MIN_PAIR, NULL);
}
Ejemplo n.º 10
0
static Module * genWood(float x, float y, float z, int fill){
	// set up fields
	Module *wood, *outline, *woodpile;
	Color brown0, brown1, dkBrown0, dkBrown1, final, outlineC;
	int thickness, gen;
	// set up different brown colors for wood
	color_set(&brown0, (float)(123/255.0), (float)(63/255.0), 
		0.0);
	color_set(&brown1, (float)(112/255.0), (float)(66/255.0), 
		(float)(20/255.0));
	color_set(&dkBrown0, (float)(101/255.0), (float)(67/255.0), 
		(float)(33/255.0));
	color_set(&dkBrown1, (float)(72/255.0), (float)(60/255.0), 
		(float)(50/255.0));
	color_set(&final, 0, 0, 0);

	// randomly generate a number between 0 and 4 inclusive
	gen = (int)(rand() % 4);
	// select outline color and fill color depending on gen
	if (gen == 0){
		color_copy(&final, &brown0);
		color_copy(&outlineC, &dkBrown0);
	}
Ejemplo n.º 11
0
void desenhar_linha(char tab[9][9], unsigned int y) {
    unsigned int x;
    move(y * 2 + 2, 0);
    printw("%c ", 'A' + y);
    addwstr(L"│");
    for(x = 0; x < 9; x++) {
        switch(tab[y][x]) {
            case 'M':
                color_set(GREEN_PAIR, 0);
                break;
            case 'G':
                color_set(RED_PAIR, 0);
                break;
            case 'R':
            case 'T':
                color_set(YELLOW_PAIR, 0);
                break;
        }
        printw(" %c", tab[y][x]);
        if(tab[y][x] != ' ')
            color_set(DEFAULT_PAIR, 0);
        addwstr(L" │");
    }
}
Ejemplo n.º 12
0
void GameField::drawCurrentTetromino(Tetromino& tetromino) const{
	for(int i = 0; i < tetromino.getTetrominoPieceCount() ; ++i){
		std::pair<int, int> tetrominoPiece = tetromino.getTetrominoPiece(i);
		int x = tetromino.getX() + 2 * tetrominoPiece.first;	//TODO: CONNECT TO TETRIS.HPP FOR THE THICKNESS 
		int y = tetromino.getY() + 1 * tetrominoPiece.second;


		color_set(tetromino.getColorID(), 0);
		for(int height = 0; height < 1; ++height){
			for(int width = 0; width < 2; ++width){
				mvaddstr(y + height, x + width, " ");
			}
		}
	}
}
Ejemplo n.º 13
0
void tup_show_message(const char *s)
{
	const char *tup = " tup ";
	clear_progress();
	color_set(stdout);
	/* If we get to the end, show a green bar instead of grey. */
	if(cur_phase == 5)
		printf("[%s%s%s] ", color_final(), tup, color_end());
	else
		printf("[%s%.*s%s%.*s] ", color_reverse(), cur_phase, tup, color_end(), 5-cur_phase, tup+cur_phase);
	timespan_end(&main_ts);
	if(display_job_time)
		printf("[%.3fs] ", timespan_seconds(&main_ts));
	printf("%s", s);
}
Ejemplo n.º 14
0
void IoCurses_colorSet(IoCurses *self)
{
	if (!DATA(self)->colorOn)
	{
		start_color();
		DATA(self)->colorOn = 1;
		/*pair_content(0, &(DATA(self)->fgColor), &(DATA(self)->bgColor));*/
	}
	init_pair(0, DATA(self)->fgColor, DATA(self)->bgColor);
#if ! defined(__PDCURSES__)
	color_set(0, NULL);
#else
	attrset(COLOR_PAIR(0));
#endif
}
Ejemplo n.º 15
0
int make_square(int color,int x,int y)
{
color_set(color,0);
move(x,y);
addstr("#");
move(x+1,y);
addstr("#");
move(x+2,y);
addstr("#");
move(x+3,y);
addstr("#");

move(x,y+6);
addstr("#");
move(x+1,y+6);
addstr("#");
move(x+2,y+6);
addstr("#");
move(x+3,y+6);
addstr("#");

move(x,y+1);
addstr("#");
move(x+3,y+1);
addstr("#");
move(x,y+2);
addstr("#");
move(x+3,y+2);
addstr("#");
move(x,y+3);
addstr("#");
move(x+3,y+3);
addstr("#");
move(x,y+4);
addstr("#");
move(x+3,y+4);
addstr("#");
move(x,y+5);
addstr("#");
move(x+3,y+5);
addstr("#");



refresh();


}
Ejemplo n.º 16
0
Archivo: progress.c Proyecto: 5kg/tup
void show_result(struct tup_entry *tent, int is_error, struct timespan *ts, const char *extra_text, int always_display)
{
	FILE *f;
	float tdiff = 0.0;

	job_time += tent->mtime;

	if(ts) {
		tdiff = timespan_seconds(ts);
	}

	sum++;
	if(sum > total) {
		fprintf(stderr, "tup internal error: progress bar is sized incorrectly.\n");
	}

	if(quiet && !always_display)
		return;

	if(is_error) {
		got_error = 1;
		f = stderr;
	} else {
		f = stdout;
	}
	clear_active(f);
	color_set(f);
	if(is_error) {
		fprintf(stderr, "* %s", color_error_mode());
	} else {
		printf(" ");
	}
	/* If we aren't going to show a progress bar, then %-complete here is
	 * helpful.
	 */
	if(total && !display_progress) fprintf(f, "%3i%% ", percent_complete());
	if(display_job_numbers) fprintf(f, "%i) ", sum);
	if(display_job_time && ts) {
		fprintf(f, "[%.3fs] ", tdiff);
	}

	if(extra_text)
		fprintf(f, "%s: ", extra_text);

	print_tup_entry(f, tent);
	fprintf(f, "\n");
	color_error_mode_clear();
}
Ejemplo n.º 17
0
static void set_ansi_attribute(const int attrib)
{
  switch (attrib)
  {
    case -1:
      return;
    case 0:
      standend();
      return;
    case 1:
      attrset(A_BOLD);
      return;
  }
  if (attrib >= 30 && attrib <= 37) {
    color_set(attrib-29,NULL);
    return;
  }
}
Ejemplo n.º 18
0
void drawCrcl(WINDOW * win, int x, int y, int size, int color)
{
	/*
	 * method known as Berchiem's Circle
	 * converted to ncurses library
	 */

  int radius = size/2;
  int error = 1 - radius;
  int errorY = 1;
  int errorX = -2 * radius;
  int r = radius, i = 0;
	color_set(color, NULL);

mvwaddstr(win,y+radius, x, "*" );
mvwaddstr(win,y-radius, x, "*" );
mvwaddstr(win,y, x+radius, "*" );
mvwaddstr(win,y, x-radius, "*" );


  while(r > i)
  {
    if(error >= 0) // >= 0 produces a slimmer circle. =0 produces the circle picture at radius 11 above
    {
      r--;
      errorX += 2;
      error += errorX;
    }
    i++;
    errorY += 2;
    error += errorY;
mvwaddstr(win,y+i, (x+r), "*" );
mvwaddstr(win,y+i, (x-r), "*" );
mvwaddstr(win,y-i, (x+r), "*" );
mvwaddstr(win,y-i, (x-r), "*" );
mvwaddstr(win,y+r, (x+i), "*" );
mvwaddstr(win,y+r, (x-i), "*" );
mvwaddstr(win,y-r, (x+i), "*" );
mvwaddstr(win,y-r, (x-i), "*" );

  }
	refresh();

}
Ejemplo n.º 19
0
void game_init( float x, float y, float width, float height )
{
	int i;

	GAME_WIDTH = width;
	GAME_HEIGHT = height;
	PLAYER_X = x;
	PLAYER_Y = y;
    p.t_max = 2;
    p.p = weMalloc( p.t_max * sizeof(position) );
	player_set( PLAYER_X, PLAYER_Y );
	e.count = rand()%EAT_MAX + 10;
	e.p = weMalloc( e.count * sizeof(position) );
	e.c = color_set(0.2f, 0.8f, 0.2f);
	for ( i = 0; i < e.count; i++) {
		eat_set(i, GAME_WIDTH, GAME_HEIGHT );
	}
	wall_set( GAME_WIDTH, GAME_HEIGHT );
}
Ejemplo n.º 20
0
Archivo: config.c Proyecto: 5kg/tup
/* Notes:
 * iserr=0 means stdout, for sub-processes that succeed
 * iserr=1 means stderr, for run-scripts
 * iserr=2 means stderr, for tup errors (eg: missing deps)
 * iserr=3 means stderr, for sub-processes that fail
 */
int display_output(int fd, int iserr, const char *name, int display_name, FILE *f)
{
	if(fd != -1) {
		char buf[1024];
		int rc;
		int displayed = 0;
		FILE *out = stdout;

		if(iserr)
			out = stderr;
		if(f)
			out = f;

		while(1) {
			rc = read(fd, buf, sizeof(buf));
			if(rc < 0) {
				perror("display_output: read");
				fprintf(stderr, "tup internal error: Unable to display output from a sub-process.\n");
				return -1;
			}
			if(rc == 0)
				break;
			if(!displayed) {
				displayed = 1;
				clear_active(out);
				if(iserr == 2) {
					/* For tup errors (eg: missing deps) */
					fprintf(out, " *** tup errors ***\n");
				}
				if(iserr == 1) {
					/* This is for run-scripts */
					if(display_name) {
						color_set(stderr);
						fprintf(out, " *** tup: stderr from command '%s%s%s%s' ***\n", color_type(TUP_NODE_CMD), color_append_normal(), name, color_end());
					}
				}
			}
			fprintf(out, "%.*s", rc, buf);
		}
	}
	return 0;
}
Ejemplo n.º 21
0
WINDOW * InitDisplay(void)
{
    WINDOW * mainwin;
	int Channel;

    /*  Initialize ncurses  */

    if ( (mainwin = initscr()) == NULL ) {
	fprintf(stderr, "Error initialising ncurses.\n");
	exit(EXIT_FAILURE);
    }

    start_color();                    /*  Initialize colours  */

	init_pair(1, COLOR_WHITE, COLOR_BLUE);
	init_pair(2, COLOR_YELLOW, COLOR_BLUE);

	color_set(1, NULL);
	// bkgd(COLOR_PAIR(1));
	// attrset(COLOR_PAIR(1) | A_BOLD);

	// Title bar
    mvaddstr(0, 19, " LoRa Habitat and SSDV Gateway by daveake ");
    refresh();

	// Windows for LoRa live data
	for (Channel=0; Channel<=1; Channel++)
	{
		Config.LoRaDevices[Channel].Window = newwin(14, 38, 1, Channel ? 41 : 1);
		wbkgd(Config.LoRaDevices[Channel].Window, COLOR_PAIR(2));
		
		// wcolor_set(Config.LoRaDevices[Channel].Window, 2, NULL);
		// waddstr(Config.LoRaDevices[Channel].Window, "WINDOW");
		// mvwaddstr(Config.LoRaDevices[Channel].Window, 0, 0, "Window");
		wrefresh(Config.LoRaDevices[Channel].Window);
	}
	
	curs_set(0);
		   
	return mainwin;
}	
Ejemplo n.º 22
0
VALUE tui_init(VALUE self) {
	setlocale(LC_ALL, "");
	
	initscr();


	/*intrflush(stdscr, 0);*/
	keypad(stdscr, TRUE); /* enable keyboard mapping */
	nonl();               /* tell curses not to do NL->CR/NL on output */
	raw();                /* characters typed are immediately passed through */
	noecho();             /* don't echo input */
	meta(stdscr, 1);

	if(has_colors() == 0) {
		endwin();
		return Qfalse;
	}
	start_color();
	
		
	init_pair(1, COLOR_YELLOW, COLOR_BLUE);  /* text */
	init_pair(2, COLOR_WHITE, COLOR_BLUE);  /* keyword */
	init_pair(3, COLOR_BLACK, COLOR_CYAN);  /* selection */
	init_pair(4, COLOR_GREEN, COLOR_BLUE);  /* strings */
	init_pair(5, COLOR_YELLOW, COLOR_BLACK);  /* fold */
	init_pair(6, COLOR_BLACK, COLOR_BLUE);  /* borders */
	init_pair(7, COLOR_CYAN, COLOR_BLUE);  /* - */
	init_pair(8, COLOR_BLUE, COLOR_BLUE);  /* tabs */
	init_pair(9, COLOR_BLACK, COLOR_RED);  /* error */
	init_pair(10, COLOR_RED, COLOR_BLUE);  /* error */
	
	color_set(1, 0);
	bkgdset(1);
	
	/*clear();
	move(0, 0);
	addnstr("hi", 2);
	refresh();*/
		
	return Qtrue;
}
Ejemplo n.º 23
0
void draw_status() {
  int min_y = MAP_SIZE_Y + 1;
  color_set(WHITE, NULL);

  // clear the line (to prevent overlapping previous text)
  move(min_y, 0);
  clrtoeol();

  // what am I standing on?
  char floor_text[MAP_SIZE_X];
  char *floor_name = name_from_glyph(map[player.x_pos][player.y_pos]);
  sprintf(floor_text, "You are standing on %s.", floor_name);
  mvaddstr(min_y, 0, floor_text);
  min_y++;

  // what do I have in my possession?
  char inv_text[MAP_SIZE_X];
  int water_count = player.inventory[get_inventory_index("water")].count;
  sprintf(inv_text, "You have %d water.", water_count);
  mvaddstr(min_y, 0, inv_text);

  refresh();
}
Ejemplo n.º 24
0
int main() {
/* variables */
int maxy, maxx;
int x;
char inp;

/* init options */
srand(time(NULL));
srand48(time(NULL));
initscr();
start_color();
use_default_colors();
init_pair(1,COLOR_GREEN,-1);
init_pair(2,COLOR_WHITE,-1);
color_set(1,NULL);
noecho();
nodelay(stdscr,true);
curs_set(0);

/* declare matrix */
getmaxyx(stdscr, maxy, maxx);
unsigned int lines=(unsigned int)(drand48()*THICKNESS*(maxx*maxy)+1);
unsigned int delay=(unsigned int)((unsigned int)(MAXDELAY*(lines/(THICKNESS*(maxx*maxy))))+MINDELAY);
signed long int matrix[lines][5];

/* functions */
unsigned char randchr(){
return rand()%95+32;
}
void reinit(){
matrix[x][1] = -((unsigned long int)rand()%maxy*2);
matrix[x][2] = -((unsigned long int)rand()%maxy*2);
if(matrix[x][2]>=matrix[x][1]) matrix[x][2]-=(unsigned int)(rand()%maxy);
matrix[x][3]=(unsigned int)rand()%maxx;
matrix[x][0]=rand();
}
Ejemplo n.º 25
0
int main(int argc, char **argv)
{
	int opt, lindex = -1;
	char *outfile = NULL;
	unsigned char *intext = NULL;
	int length = 0;

	while((opt = getopt_long(argc, argv, optstring, options, &lindex)) != -1) {
		switch(opt) {
			case 'h':
				if(lindex == 0) {
					usage(1, 1);
				} else {
					usage(1, 0);
				}
				exit(EXIT_SUCCESS);
				break;
			case 'o':
				outfile = optarg;
				break;
			case 's':
				size = atoi(optarg);
				if(size <= 0) {
					fprintf(stderr, "Invalid size: %d\n", size);
					exit(EXIT_FAILURE);
				}
				break;
			case 'v':
				version = atoi(optarg);
				if(version < 0) {
					fprintf(stderr, "Invalid version: %d\n", version);
					exit(EXIT_FAILURE);
				}
				break;
			case 'l':
				switch(*optarg) {
					case 'l':
					case 'L':
						level = QR_ECLEVEL_L;
						break;
					case 'm':
					case 'M':
						level = QR_ECLEVEL_M;
						break;
					case 'q':
					case 'Q':
						level = QR_ECLEVEL_Q;
						break;
					case 'h':
					case 'H':
						level = QR_ECLEVEL_H;
						break;
					default:
						fprintf(stderr, "Invalid level: %s\n", optarg);
						exit(EXIT_FAILURE);
						break;
				}
				break;
			case 'm':
				margin = atoi(optarg);
				if(margin < 0) {
					fprintf(stderr, "Invalid margin: %d\n", margin);
					exit(EXIT_FAILURE);
				}
				break;
			case 'd':
				dpi = atoi(optarg);
				if( dpi < 0 ) {
					fprintf(stderr, "Invalid DPI: %d\n", dpi);
					exit(EXIT_FAILURE);
				}
				break;
			case 't':
				if(strcasecmp(optarg, "png") == 0) {
					image_type = PNG_TYPE;
				} else if(strcasecmp(optarg, "eps") == 0) {
					image_type = EPS_TYPE;
				} else if(strcasecmp(optarg, "svg") == 0) {
					image_type = SVG_TYPE;
				} else if(strcasecmp(optarg, "ansi") == 0) {
					image_type = ANSI_TYPE;
				} else if(strcasecmp(optarg, "ansi256") == 0) {
					image_type = ANSI256_TYPE;
				} else if(strcasecmp(optarg, "asciii") == 0) {
					image_type = ASCIIi_TYPE;
				} else if(strcasecmp(optarg, "ascii") == 0) {
					image_type = ASCII_TYPE;
				} else if(strcasecmp(optarg, "utf8") == 0) {
					image_type = UTF8_TYPE;
				} else if(strcasecmp(optarg, "ansiutf8") == 0) {
					image_type = ANSIUTF8_TYPE;
				} else {
					fprintf(stderr, "Invalid image type: %s\n", optarg);
					exit(EXIT_FAILURE);
				}
				break;
			case 'S':
				structured = 1;
				break;
			case 'k':
				hint = QR_MODE_KANJI;
				break;
			case 'c':
				casesensitive = 1;
				break;
			case 'i':
				casesensitive = 0;
				break;
			case '8':
				eightbit = 1;
				break;
			case 'M':
				micro = 1;
				break;
			case 'f':
				if(color_set(fg_color, optarg)) {
					fprintf(stderr, "Invalid foreground color value.\n");
					exit(EXIT_FAILURE);
				}
				break;
			case 'b':
				if(color_set(bg_color, optarg)) {
					fprintf(stderr, "Invalid background color value.\n");
					exit(EXIT_FAILURE);
				}
				break;
			case 'V':
				usage(0, 0);
				exit(EXIT_SUCCESS);
				break;
			case 0:
				break;
			default:
				fprintf(stderr, "Try `qrencode --help' for more information.\n");
				exit(EXIT_FAILURE);
				break;
		}
	}

	if(argc == 1) {
		usage(1, 0);
		exit(EXIT_SUCCESS);
	}

	if(outfile == NULL && image_type == PNG_TYPE) {
		fprintf(stderr, "No output filename is given.\n");
		exit(EXIT_FAILURE);
	}

	if(optind < argc) {
		intext = (unsigned char *)argv[optind];
		length = strlen((char *)intext);
	}
	if(intext == NULL) {
		intext = readStdin(&length);
	}

	if(micro && version > MQRSPEC_VERSION_MAX) {
		fprintf(stderr, "Version should be less or equal to %d.\n", MQRSPEC_VERSION_MAX);
		exit(EXIT_FAILURE);
	} else if(!micro && version > QRSPEC_VERSION_MAX) {
		fprintf(stderr, "Version should be less or equal to %d.\n", QRSPEC_VERSION_MAX);
		exit(EXIT_FAILURE);
	}

	if(margin < 0) {
		if(micro) {
			margin = 2;
		} else {
			margin = 4;
		}
	}

	if(micro) {
		if(version == 0) {
			fprintf(stderr, "Version must be specified to encode a Micro QR Code symbol.\n");
			exit(EXIT_FAILURE);
		}
		if(structured) {
			fprintf(stderr, "Micro QR Code does not support structured symbols.\n");
			exit(EXIT_FAILURE);
		}
	}

	if(structured) {
		if(version == 0) {
			fprintf(stderr, "Version must be specified to encode structured symbols.\n");
			exit(EXIT_FAILURE);
		}
		qrencodeStructured(intext, length, outfile);
	} else {
		qrencode(intext, length, outfile);
	}

	return 0;
}
Ejemplo n.º 26
0
int main(int argc, char* argv[])
{
	int is_running = 1;
	int x_terminal_size, y_terminal_size;
        int is_lurking = 0;
        int is_yelling = 0;
        int in_deepsix = 0;
        int sending_im = 0;
        int i;

	/* josh-note:
			These need to be uncommented for the client connection to work. */
/*	int client_id = init_client("Henry");                   create a client. */
/*      init_user_list(client_id);                      init the client size user list. */

	log_init();
	log_writeln(" --------------------------- ");
	log_writeln(" > Starting BlackChat");

        signal(SIGALRM, scroll_ended_handler);

        for(i = 0; i < 26; i ++) {   /* set our message to null */
                memset(yell_messages[i], '\0', MAX_MESSAGE_LENGTH * sizeof(wchar_t)); 
        }

	transcript_buffer   = (wchar_t*)malloc(sizeof(wchar_t)*transcript_buffer_size);
	f_transcript_buffer = (wchar_t*)malloc(sizeof(wchar_t)*f_transcript_buffer_size);
    memset(client_buffer, '\0', sizeof(client_buffer));
	memset(transcript_buffer, '\0', sizeof(transcript_buffer));

	get_terminal_size(&x_terminal_size, &y_terminal_size);
	log_writeln(" > ... detecting current terminal size xy:(%d,%d)", x_terminal_size, y_terminal_size);

	log_writeln(" > ... initializing ncurses screen in raw mode");
	initscr();
//	start_color();
	init_pair(0, COLOR_WHITE,   COLOR_BLACK);
	init_pair(1, COLOR_GREEN,   COLOR_BLACK);
	init_pair(2, COLOR_YELLOW,  COLOR_BLACK);
        init_pair(3, COLOR_CYAN,    COLOR_BLACK);
        init_pair(4, COLOR_MAGENTA, COLOR_BLACK);
	raw();
	keypad(stdscr, TRUE);
	noecho();

	color_set(0, NULL);
	
	log_writeln(" > ... creating transcript and client window");
	transcript_window  				= newwin(TRANSCRIPT_MAX_ROWS,TRANSCRIPT_MAX_COLUMNS,   0,0);
	fullscreen_transcript_window	= newwin(TRANSCRIPT_MAX_ROWS,TRANSCRIPT_MAX_COLUMNS*2, 0,0);
	client_chat_window 				= newwin(MAX_ROWS,MAX_COLUMNS,24,0);
        lurk_win           			= newwin(MAX_ROWS,MAX_COLUMNS,24,0);
        yell_win           			= newwin(23,40,0,0);
        deepsix_win        			= newwin(23,40,0,0);
        im_win						= newwin(TRANSCRIPT_MAX_ROWS,TRANSCRIPT_MAX_COLUMNS,   0,0);
        status_win					= newwin(3,40,21,40);
        info_win					= newwin(3,40,0,40);
   //     box(yell_win, '|', '-');

        set_yell_message(0, L"Hello World");
        set_yell_message(1, L"Yo dog!");
        set_yell_message(2, L"Hey everyone!");
        set_yell_message(3, L"Whats up?");
        set_yell_message(12,L"I agree.");

        wcolor_set(lurk_win,           4, NULL);
        wcolor_set(transcript_window,  3, NULL);
        wcolor_set(client_chat_window, 4, NULL);
        wcolor_set(yell_win,           2, NULL);
        wprintw(lurk_win, "Lurking... Use CTRL-L to unLurk or CTRL-Q to quit.");
	log_writeln(" > ... creating other 9 windows");
	init_other_windows();

	log_writeln(" > ... [beginning transcript]");
	write_to_transcript_window(L"***************************************");
	write_to_transcript_window(L"******** Wecome to BlackChat! *********");
	write_to_transcript_window(L"***************************************");
        
	set_window_user_name(0, L"chris");
	set_window_user_name(1, L"sue");
	set_window_user_name(2, L"dan");
	set_window_user_name(3, L"joe");
	append_text_to_window(0, L"Sup!");
	append_text_to_window(1, L"yo everyone, I'm in love with blackchat!");
	append_text_to_window(2, L"hey, my name is Dan!");
	append_text_to_window(3, L"Hey!?");

	can_deepsix_user(0, 0);
	set_user_status(1, 'L');
	set_user_status(2, 'L');
	
	/* Set our info window text. */
	wprintw(info_win, "       Black Chat  v1.0\n");
	wprintw(info_win, "UI: Henry Stratmann|Client: Josh Hartman\n");
	wprintw(info_win, "Server: Tyler Reid |Protocol: Tim Rhoads\n");
	

	while(is_running) {
		int ch = getch();
/*		wchar_t buf[512];          //get wchar_ts

		sprintf(buf, "key pressed: '%c'  int value: %d\n", ch, ch);
		write_to_transcript_window(buf);
  */                                      //end get wchar_t

            /* Check if were in "Lurk" mode. */
            if(is_lurking) {
                    switch(ch) {
                            case 12: /* lurk-off */
                                    is_lurking = 0;
                                    print_client_chat_buffer();
                                    break;
                            case 17: /* quit */
                                    is_running = 0;
                                    break;
                            default:
                                    wrefresh(lurk_win);
                    }
            }
            /* Check if were in IM mode. */
            else if(sending_im) {
            		/*
            		 TODO: Display list of users (like deepsix) to send IM to.
            		 	All IM's will be displayed on the main transcript with some type of "marker"
            		 	indicating that this was an IM.
            		 */
            		if(ch >= 48 && ch <= 57) {
            				/* josh-note:
            					Have josh send IM based on "ch" */
            		}
            
            
            		/* quit */
                    if(ch == 17) {
                    		is_running = 0;
                    }
                    
                    /* exit IM */
                    sending_im = 0;
                    window_page_up(transcript_window,            &transcript_current_line, TRANSCRIPT_MAX_COLUMNS,   transcript_buffer);
                    window_page_up(fullscreen_transcript_window, &transcript_current_line, TRANSCRIPT_MAX_COLUMNS*2, f_transcript_buffer);
            }
            /* Check if were in deepsix mode. */
            else if(in_deepsix) {
            		/* kick user */
            		if(ch >= 48 && ch <= 57) {
            				/* josh-note:
            					Have josh make a "kick_user(ch-48)" command. 
            					Also, have josh keep track of who user voted for and display message on transcript as to how user voted
            					and/or if they already voted for the user. */		
            		}
            
            		/* quit */
                    if(ch == 17) {
                    		is_running = 0;
                    }
                    
                    /* exit deepsix */
                    in_deepsix = 0;
                    window_page_up(transcript_window,            &transcript_current_line, TRANSCRIPT_MAX_COLUMNS,   transcript_buffer);
                    window_page_up(fullscreen_transcript_window, &transcript_current_line, TRANSCRIPT_MAX_COLUMNS*2, f_transcript_buffer);
            }
            /* Check if were yelling. */
            else if(is_yelling) {
                    // redrawwin(yell_win);
                    // wrefresh(yell_win);
                    int index = ch - 97;
        

                    /* Write our comment to our transcript window.  */
                    if(index >= 0 && index < 26) {
                            if( yell_messages[index][0] != '\0' ) {
                                    write_to_transcript_window( yell_messages[index] );
                            }
                    }
                    
                    is_yelling = 0;
                    redrawwin(client_chat_window);
                    wrefresh(client_chat_window);
                    redrawwin(transcript_window);
                    wrefresh(transcript_window);
            } else {
		/* Check what keys we pressed. */
		switch(ch) {
		        /*
			 * Check if we pressed a control key. */
			if(iscntrl(ch)) {
				case 7:  /* CTRL-G */
					gaudy_mode_on = (gaudy_mode_on == 1) ? 0 : 1;
					if(gaudy_mode_on) {
						client_buffer[ client_cursor_position++ ] = 2;
					} else {
						client_buffer[ client_cursor_position++ ] = 3;
					}

					/* Print out updates to the window. */
					print_client_chat_buffer();
					break;

				case 127:/* Backsapce Key (grok hack) */
				case 8:  /* CTRL-H */
					client_buffer[ wcslen(client_buffer)-1 ] = '\0';
					print_client_chat_buffer();
					break;
					
				case 9:  /* CTRL-I   /   TAB */
					if(!sending_im) {
						sending_im = 1;
						draw_im_window();
					}
					break;
					
				case 10: /* CTRL-J and CTRL-M */
		/* UNCOMMENT ME FOR USE WITH SERVER */
					{
						wchar_t *buf = NULL;


						/* If we had gaudy mode on, we need to disable it. */
						if(gaudy_mode_on) {
							client_buffer[ client_cursor_position++ ] = 3;
                                                	client_buffer[ client_cursor_position++ ] = ' ';
							gaudy_mode_on = 0;
						}


						/* Get our buffer togther to write to the transcript window. */
						buf = (wchar_t*)malloc( (wcslen(L"[Client Says]: ")+wcslen(client_buffer)+1) * sizeof(wchar_t) );
						write_to_transcript_window(L"[Client Says]: ");
						write_to_transcript_window(client_buffer);
						
					//	sprintf(buf, "[Client Says]: %ls", client_buffer);
					//	write_to_transcript_window(buf);
					}
					clear_text_from_client_typing_window();
				/*	write_out(client_id);                    enter key is pressed so send a message to the server. */
						    break;

				case 11: /* CTRL-K */
					{
						int i;
						for(i = client_cursor_position+1; i < wcslen(client_buffer); i ++) {
							client_buffer[i] = '\0';
						}
					}
					break;

					    case 12: /* CTRL-L */
							if(!is_lurking) {
							    redrawwin(lurk_win);
							    wrefresh(lurk_win);
							    is_lurking = 1;
							}
						    break;

				case 14: /* CTRL-N */
                                        alarm(5);
					user_is_scrolling = 1;
					transcript_current_line ++;

					window_page_down( transcript_window,
							  &transcript_current_line,
							  TRANSCRIPT_MAX_COLUMNS,
							  transcript_buffer );
							  
					window_page_down( fullscreen_transcript_window,
							  &transcript_current_line,
							  TRANSCRIPT_MAX_COLUMNS*2,
							  f_transcript_buffer );
					break;
				case 16: /* CTRL-P */
                                        alarm(5);
					user_is_scrolling = 1;
					transcript_current_line --;

					window_page_up( transcript_window,
						    	&transcript_current_line,
							TRANSCRIPT_MAX_COLUMNS,
							transcript_buffer );
							
					window_page_up( fullscreen_transcript_window,
							  &transcript_current_line,
							  TRANSCRIPT_MAX_COLUMNS*2,
							  f_transcript_buffer );
					break;
		
				case 17: /* CTRL-Q */ 
					log_writeln(" > ... recived quit signal from client");
					is_running = 0;
					break;
		
				case 20: /* CTRL-T */
					if(transcript_maxed) {
						transcript_maxed = 0;
						window_page_up(transcript_window, &transcript_current_line, TRANSCRIPT_MAX_COLUMNS, transcript_buffer);
						wclear(fullscreen_transcript_window);
						wrefresh(fullscreen_transcript_window);
					} else {
						transcript_maxed = 1;
						window_page_up(fullscreen_transcript_window, &transcript_current_line, TRANSCRIPT_MAX_COLUMNS*2, f_transcript_buffer);
						wclear(transcript_window);
						wrefresh(transcript_window);
					}
					break;
		
				case 21: /* CTRL-U */
					client_current_line = 0;
					client_cursor_position = 0;
					memset(client_buffer, '\0', wcslen(client_buffer)+1);	
					print_client_chat_buffer();
					break;

				case 23: /* CTRL-W */
					delete_last_word_in_buffer(client_buffer);
					print_client_chat_buffer();
					break;
                                case 25: /* CTRL-Y */
                                        {
                                            if(!is_yelling)
                                            {
                                                redrawwin(yell_win);
                                                wrefresh(yell_win);
                                                is_yelling = 1;
                                            }
                                        }
                                        break; 
				case 29: /* CTRL-] */
                                        alarm(0);
					user_is_scrolling = 0;
					print_transcript_chat_buffer();
					break;
                                case 30: /* CTRL-6 */
                                        if(!in_deepsix)
                                        {
                                            draw_deepsix_window();
                                            in_deepsix = 1;
                                        }
                                        break;

                                /*
                                 * If we encountered an unkown escape wchar_tcter, break out of here so we don't
                                 * print it. */
                                break;              /* TODO: Fix me! */
			}
#if 0
			/* Scroll the clients typing window down. */
			case KEY_DOWN:
				client_current_line ++;
				if(client_current_line*MAX_COLUMNS > wcslen(client_buffer)) client_current_line --;

					    wclear(client_chat_window);
					    wprintw(client_chat_window, &client_buffer[client_current_line*MAX_COLUMNS]);
					    break;
			/* Scroll the clients typing window up. */
			case KEY_UP:
				client_current_line --;
				if(client_current_line < 0) client_current_line = 0;

					    wclear(client_chat_window);
					    wprintw(client_chat_window, &client_buffer[client_current_line*MAX_COLUMNS]);
					    break;
#endif
			/* Delete the previous chracter. */
			case KEY_BACKSPACE:
				/* Check if were deleting the last wchar_tacter. */
				if( client_cursor_position == wcslen(client_buffer) ) {
					client_buffer[ client_cursor_position-1 ] = '\0';
					client_cursor_position --;
					print_client_chat_buffer();
				} else {
					/* If were here, that means were NOT deleting the last wchar_tacter. */
					int i;
					for(i = client_cursor_position-1; i < wcslen(client_buffer); i ++) {
						client_buffer[i] = client_buffer[i+1];
					}
					client_cursor_position --;
					print_client_chat_buffer();
				}
				break;

			/* If were here, that means we didn't press any "special" keys so that means were
			 * trying to write some generic wchar_tacters to our chat window. */
			default:
				/* Make sure we don't print a control wchar_tacter. */
				if(!iscntrl(ch)) {
					/* Check if were inserting a wchar_tacter before the end of our client
					 * typing buffer. */
					if( client_cursor_position != wcslen(client_buffer) ) {
	
						/* Move all wchar_tacters in front of the cursor up one. */
						int i;
						for(i = wcslen(client_buffer)+1; i > client_cursor_position; i --) {
							client_buffer[i] = client_buffer[i-1];
						}
					}

					/* Add the wchar_tacter to our buffer. */
					client_buffer[ client_cursor_position++ ] = ch;

					/* Print our new/updated buffer. */
					print_client_chat_buffer();
					break;
				}
			}
		}

        	/* Read from the server. */
        	/* josh-note
        			Uncomment this! */
/*      	read_from_server(client_id); */

        	refresh_all_windows(is_lurking);
	}

	log_writeln(" > ... [ending transcript]");
	log_writeln(" > ... freeing resources");
	free_other_windows();
	free(transcript_buffer);

	delwin(transcript_window);
	delwin(fullscreen_transcript_window);
	delwin(client_chat_window);
	delwin(status_win);
	delwin(info_win);
	delwin(im_win);
	delwin(deepsix_win);
	delwin(yell_win);
	endwin();
        
    /* josh-note
    		This should be uncommented to close down the client socket. */
/*  close_client(client_id); */

	log_writeln(" > ... closing client log");
	log_writeln(" > ... bye bye for now!");
	log_close();
	return 0;
}
Ejemplo n.º 27
0
Archivo: color.c Proyecto: dkastner/sc
void
initcolor(int colornum)
{
    if (!colornum) {
	int i;

	for (i = 0; i < 8; i++)	cpairs[i] =
	    (struct colorpair *)scxmalloc((unsigned)sizeof(struct colorpair));
    }

/* default colors */
    if (!colornum || colornum == 1) {
	cpairs[0]->fg = COLOR_WHITE;
	cpairs[0]->bg = COLOR_BLUE;
	cpairs[0]->expr = NULL;
	init_pair(1, cpairs[0]->fg, cpairs[0]->bg);
    }

/* default for negative numbers */
    if (!colornum || colornum == 2) {
	cpairs[1]->fg = COLOR_RED;
	cpairs[1]->bg = COLOR_WHITE;
	cpairs[1]->expr = NULL;
	init_pair(2, cpairs[1]->fg, cpairs[1]->bg);
    }

/* default for cells with errors */
    if (!colornum || colornum == 3) {
	cpairs[2]->fg = COLOR_WHITE;
	cpairs[2]->bg = COLOR_RED;
	cpairs[2]->expr = NULL;
	init_pair(3, cpairs[2]->fg, cpairs[2]->bg);
    }

/* default for '*' marking cells with attached notes */
    if (!colornum || colornum == 4) {
	cpairs[3]->fg = COLOR_BLACK;
	cpairs[3]->bg = COLOR_YELLOW;
	cpairs[3]->expr = NULL;
	init_pair(4, cpairs[3]->fg, cpairs[3]->bg);
    }

    if (!colornum || colornum == 5) {
	cpairs[4]->fg = COLOR_BLACK;
	cpairs[4]->bg = COLOR_CYAN;
	cpairs[4]->expr = NULL;
	init_pair(5, cpairs[4]->fg, cpairs[4]->bg);
    }

    if (!colornum || colornum == 6) {
	cpairs[5]->fg = COLOR_RED;
	cpairs[5]->bg = COLOR_CYAN;
	cpairs[5]->expr = NULL;
	init_pair(6, cpairs[5]->fg, cpairs[5]->bg);
    }

    if (!colornum || colornum == 7) {
	cpairs[6]->fg = COLOR_WHITE;
	cpairs[6]->bg = COLOR_BLACK;
	cpairs[6]->expr = NULL;
	init_pair(7, cpairs[6]->fg, cpairs[6]->bg);
    }

    if (!colornum || colornum == 8) {
	cpairs[7]->fg = COLOR_RED;
	cpairs[7]->bg = COLOR_BLACK;
	cpairs[7]->expr = NULL;
	init_pair(8, cpairs[7]->fg, cpairs[7]->bg);
    }

    if (color && has_colors())
	color_set(1, NULL);
}
Ejemplo n.º 28
0
void show_progress(int active, enum TUP_NODE_TYPE type)
{
	int console_width = tup_option_get_int("display.width");
	if(total && display_progress && console_width >= 10) {
		/* -3 for the [] and leading space, and -6 for the " 100% " at
		 * the end.
		 */
		int max = console_width - 9;
		int fill;
		char buf[console_width + color_len + 1];
		int num_infos = 0;
		int i = 0;
		int x;
		int tmpmax;
		int offset;

		if(max > total)
			max = total;
		if(got_error)
			type = TUP_NODE_ROOT;

		clear_active(stdout);

		fill = max * sum / total;

		if(color_len) {
			memset(buf, ' ', sizeof(buf));
		} else {
			memset(buf, '.', fill);
			memset(buf+fill, ' ', sizeof(buf) - fill);
		}

		for(x=0; x<ARRAY_SIZE(infos); x++) {
			infos[x].len = 0;
		}

		if(total_time != -1) {
			infos[i].len = get_time_remaining(infos[i].text, sizeof(infos[i].text), job_time, total_time, 0);
		} else {
			infos[i].len = get_time_remaining(infos[i].text, sizeof(infos[i].text), sum, total, 1);
		}
		i++;

		infos[i].len = snprintf(infos[i].text, sizeof(infos[i].text), "Remaining=%i", total-sum);
		i++;

		if(active != -1) {
			infos[i].len = snprintf(infos[i].text, sizeof(infos[i].text), "Active=%i", active);
		} else {
			/* Override maxlen to disable "Active..." */
			infos[i].maxlen = 0;
		}
		i++;

		tmpmax = max;
		for(x=0; x<ARRAY_SIZE(infos); x++) {
			int spacing = 0;
			if(x)
				spacing = 1;
			if(tmpmax >= infos[x].maxlen + spacing) {
				tmpmax -= infos[x].maxlen + spacing;
				num_infos++;
			} else {
				break;
			}
		}
		offset = tmpmax / 2;
		for(x=0; x<num_infos; x++) {
			if(x)
				offset++;
			memcpy(buf + offset, infos[x].text, infos[x].len);
			offset += infos[x].maxlen;
		}

		color_set(stdout);
		printf(" [%s%s%.*s%s%.*s] %3i%%", color_type(type), color_append_reverse(), fill, buf, color_end(), max-fill, buf+fill, percent_complete());
		is_active = 1;
		fflush(stdout);
	}
}
Ejemplo n.º 29
0
void start(std::string filename, bool saveprog, bool savestats,bool usetree)
{
	if(!progrunning)
		return;

	clear();

	Textstream ts;
	ts.open_file(filename);
	if(saveprog)
		ts.loadposition();

	Wordtree errortree;
	std::string treefilename="wordstat.stat";
	
	if(usetree)
		errortree.restorefromFile(treefilename);

	//Variables
	bool timerunning = false;

	int keystrokes = 0;
	int wrongstrokes = 0;
	std::chrono::high_resolution_clock::time_point starttime;
	std::chrono::high_resolution_clock::time_point curtime;
	int elapsedseconds = 0;
	float keysperminute = 0.0;
	float errorpercent = 0.0;

	Intstring line;
	int clength = 0;
	int tprog = 0;
	bool * correctness = new bool;
	bool lastwordwrong = false;
	std::string typedword;

	int yval = 0;

	std::mutex printingmutex;

	//Lambdas
	auto add_widech = [&](int c){
		char bytes[5];
		for(unsigned char a = 0; a < 5 ; ++a)
			bytes[a] = 0;

		felocale::to_utf8(c,bytes);
		printw(bytes);
	};

	auto updatestates = [&](){
		if(timerunning)
		{
			curtime = std::chrono::high_resolution_clock::now();
			elapsedseconds = std::chrono::duration_cast <std::chrono::seconds> (curtime - starttime) .count();
		}
		if(elapsedseconds > 0)
			keysperminute = (((double)keystrokes) * 60 / ((double)elapsedseconds));
		errorpercent = (float)(wrongstrokes * 100) / (float)keystrokes;
	};

	auto printstatus = [&](){
		printingmutex.lock();
		if(timerunning)
		{
			updatestates();
			move(0,0);
			clrtoeol();
			std::string s = "Seconds elapsed: "+std::to_string(elapsedseconds)+" Error Ratio:"+std::to_string(errorpercent)+'%'
			+" Keystrokes per Minutes:"+std::to_string(keysperminute);
			mvprintw(0,0,s.c_str());
		}
		else
		{
			mvprintw(0,0,"Begin Typing to start the time measurement....");
		}
		refresh();
		printingmutex.unlock();
	};

	auto nextline = [&](){
		clear();
		std::string tstring = ts.nextline();
		line = tstring;
		if(line.empty()){
			clear();
			mvprintw(1,0,"You reached The End of the line...");
			printstatus();
			timerunning = false;
			progrunning = false;
		}
		else
		{
			if(clength < line.length())
			{
				delete[] correctness;
				correctness = new bool [line.length()];
				clength = line.length();
			}
			tprog = 0;
			yval = 2;
		}
	};

	auto printline = [&](){
		if( !progrunning )
			return;
		
		printingmutex.lock();
		move(yval,0);
		int x;
		for(x = 0; x < tprog; ++x)
		{
			color_set(1,0);
			if(!correctness[x])
				color_set(3,0);
			add_widech(line.at(x));
		}
		if(x < line.length())
		{
			color_set(2,0);
			add_widech(line.at(x));
			++x;
		}
		color_set(1,0);
		for(; x < line.length();++x)
			add_widech(line.at(x));

		//Add a pilcrow at the end
		if(tprog == line.length())
			color_set(2,0);

		add_widech(0xb6);

		color_set(1,0);
		printingmutex.unlock();
	};

	auto doscreen = [&](){
		printstatus();
		printline();
		refresh();
	};

	auto feedtree = [&](int c){
		//Do the wordtree magic
		if(usetree)
		{
			if(line.at(tprog) == ' ' || tprog == line.length())
			{
				Intstring* word = line.getWordBefore(tprog);
				std::string uword = felocale::convertstring(*word);
				if(lastwordwrong)
					errortree.insertError(uword,typedword);
				else
					errortree.insert(uword);
				typedword.clear();
				lastwordwrong=false;
				delete word;
			}
			else if(c != 0){
				char bytes[5];
				for(unsigned char d = 0; d < 5; ++d)
					bytes[d] = 0;
				char count = felocale::to_utf8(c,bytes);
				for(unsigned char a = 0; a < count; ++a)
					typedword.append(bytes);
			}
		}
	};

	auto comparechar = [&](int c){
		feedtree(c);
		++keystrokes;
		if(tprog == line.length())
			return;

		if(c == line.at(tprog))
			correctness[tprog] = true;
		else{
			lastwordwrong = true;
			correctness[tprog] = false;
			++wrongstrokes;
		}

		++tprog;
	};

	auto get_widech = [&]() {

		int a = getch();

		//UNICODE char!
		if( (a & 0x80) == 0x80)
		{
			int c = 0;

			char bytecount = 0;
			char marker = 0x40;
			while ((a & marker) == marker)
			{
				marker >>= 1;
				++bytecount;
			}

			//move the bits from the first byte over
			char cm = 1;
			char mask = 0;
			while(cm != marker)
			{
				mask |= cm;
				cm <<= 1; 
			}
			c |= (a & mask);

			//move the remaining bytes in.
			//the length is cut appropiately
			for(int a = 0; a<bytecount; ++a)
			{
				c <<= 6;
				c |= (getch() & 0x3f);
			}
			a = c;
		}
		return a;
	};
Ejemplo n.º 30
0
int main(int argc, char *argv[]) {
  Image *src;
  const int rows = 600;
  const int cols = 800;
  const int Resolution = 50;
	Color white;
  Color Grey;
  Color dkGrey;
  Color Red;
  Color Blue;
  Point unitCircle[Resolution];
  Point unitSquare[4];
  Point pt[Resolution];
  Point ptt[Resolution];
  int i, j, index = 0;
  Matrix VTM, GTM, LTM;
  Polygon *ship[50];
  Color shipColor[50];
  double theta = 0.0;
  double phaserAngle = 0.0;
  int firePhase = 0;

  color_set(&Grey, 180/255.0, 180/255.0, 183/255.0);
  color_set(&dkGrey, 140/255.0, 140/255.0, 143/255.0);
  color_set(&Red, 250/255.0, 40/255.0, 40/255.0);
  color_set(&Blue, 30/255.0, 20/255.0, 250/255.0);

  if(argc > 1) {
    theta = atoi(argv[1]);
  }
  printf("Drawing ship with orientation %.2f degrees\n", theta);

  if(argc > 2) {
    phaserAngle = atoi(argv[2]);
    firePhase = 1;

    printf("Drawing phaser with angle %.2f degrees\n", phaserAngle);
  }

  srand(42);

  src = image_create(rows, cols);
	color_set(&white, 1.0, 1.0, 1.0);
	for(i=0; i<rows; i++){
		for(j=0; j<cols; j++){
			if((rand()%50) == 13){
				image_setColor(src, i, j, white);
			}
		}
	}

  // initialize the three matrices
  matrix_identity(&VTM);
  matrix_identity(&GTM);
  matrix_identity(&LTM);

  // Fix world coordinates as normal (x, y) 

  // give the view window an origin at -180m, -150m
  // size is a 4x3 ratio
  // VTM = T(0, rows-1)S(cols/vx, rows/vy)T(180, 150)
  matrix_translate2D(&VTM, 120, 100);
  matrix_scale2D(&VTM, cols/(4*60), -rows/(3*60));
  matrix_translate2D(&VTM, 0, rows-1);
  printf("VTM\n");
  matrix_print(&VTM, stdout);

  // make a space ship oriented along the positive X axis
  // use the LTM to move simple primitives into place
  // use the GTM to rotate the ship
  // use the VTM to change the view

  // make a list of points that form the unit circle
  for(i=0;i<Resolution;i++) {
    point_set2D(&(unitCircle[i]), 
    cos( i * 2.0 * M_PI / (float)Resolution), 
    sin( i * 2.0 * M_PI / (float)Resolution));
  }
  // set up the unit square
  point_set2D(&(unitSquare[0]), 0, 0);
  point_set2D(&(unitSquare[1]), 1, 0);
  point_set2D(&(unitSquare[2]), 1, 1);
  point_set2D(&(unitSquare[3]), 0, 1);

  // build a set of polygons that form the ship in model space
  // put the origin of the model between the engines

  // outline for the main disk
  matrix_identity(&LTM);
  matrix_scale2D(&LTM, 31, 31);
  // move it 20m along the X-axis
  matrix_translate2D(&LTM, 60, 0);
  // transform the circle points using LTM
  for(i=0;i<Resolution;i++) {
    matrix_xformPoint(&LTM, &(unitCircle[i]), &(pt[i]));
  }

  // add the polygon
  matrix_print(&LTM, stdout);
  ship[index] = polygon_createp(Resolution, pt);
  shipColor[index++] = Red;

  printf("Post-LTM\n");
  polygon_print(ship[0], stdout);

  // main disk
  matrix_identity(&LTM);
  matrix_scale2D(&LTM, 30, 30);
  // move it 20m along the X-axis
  matrix_translate2D(&LTM, 60, 0);
  // transform the circle points using LTM
  for(i=0;i<Resolution;i++) {
    matrix_xformPoint(&LTM, &(unitCircle[i]), &(pt[i]));
  }

  // add the polygon
  matrix_print(&LTM, stdout);
  ship[index] = polygon_createp(Resolution, pt);
  shipColor[index++] = Grey;

  // central bridge disk
  matrix_identity(&LTM);
  matrix_scale2D(&LTM, 10, 10);
  // move it 20m along the X-axis
  matrix_translate2D(&LTM, 60, 0);
  // transform the circle points using LTM
  for(i=0;i<Resolution;i++) {
    matrix_xformPoint(&LTM, &(unitCircle[i]), &(pt[i]));
  }

  // add the polygon
  matrix_print(&LTM, stdout);
  ship[index] = polygon_createp(Resolution, pt);
  shipColor[index++] = dkGrey;

  // make the body disk elongated along the X axis
  matrix_identity(&LTM);
  matrix_scale2D(&LTM, 30, 12);
  matrix_translate2D(&LTM, 2.5, 0);

  // transform the circle points using LTM
  for(i=0;i<Resolution;i++) {
    matrix_xformPoint(&LTM, &(unitCircle[i]), &(pt[i]));
  }

  // add the polygon
  matrix_print(&LTM, stdout);
  ship[index] = polygon_createp(Resolution, pt);
  shipColor[index++] = Grey;
  
  // make a trapezoidal strut out of the unit square
  matrix_identity(&LTM);
  matrix_translate2D(&LTM, -0.5, 0.0);
  matrix_scale2D(&LTM, 10, 10);
  matrix_shear2D(&LTM, .2, 0.0);

  for(i=0;i<4;i++) {
    matrix_xformPoint(&LTM, &(unitSquare[i]), &(pt[i]));
  }

  // move the strut out from the origin along the Y axis
  matrix_identity(&LTM);
  matrix_translate2D(&LTM, 0, 12);

  for(i=0;i<4;i++) {
    matrix_xformPoint(&LTM, &(pt[i]), &(ptt[i]));
  }

  // add the polygon
  matrix_print(&LTM, stdout);
  ship[index] = polygon_createp(4, ptt);
  shipColor[index++] = Grey;

  // place the second strut
  matrix_identity(&LTM);
  matrix_scale2D(&LTM, 1, -1);
  matrix_translate2D(&LTM, 0, -12);

  for(i=0;i<4;i++) {
    matrix_xformPoint(&LTM, &(pt[i]), &(ptt[i]));
  }

  // add the polygon
  ship[index] = polygon_createp(4, ptt);
  shipColor[index++] = Grey;

  // create an engine outline from the unit circle
  matrix_identity(&LTM);
  matrix_scale2D(&LTM, 31, 6);

  // make the engine
  for(i=0;i<Resolution;i++) {
    matrix_xformPoint(&LTM, &(unitCircle[i]), &(pt[i]));
  }

  // send one engine to the right location
  matrix_identity(&LTM);
  matrix_translate2D(&LTM, -5, 27);

  // move the engine
  for(i=0;i<Resolution;i++) {
    matrix_xformPoint(&LTM, &(pt[i]), &(ptt[i]));
  }

  // add the polygon
  ship[index] = polygon_createp(Resolution, ptt);
  shipColor[index++] = Blue;

  // send the other engine to the right location
  matrix_identity(&LTM);
  matrix_translate2D(&LTM, -5, -27);

  // move the engine
  for(i=0;i<Resolution;i++) {
    matrix_xformPoint(&LTM, &(pt[i]), &(ptt[i]));
  }

  // add the polygon
  ship[index] = polygon_createp(Resolution, ptt);
  shipColor[index++] = Blue;

  // create an engine
  matrix_identity(&LTM);
  matrix_scale2D(&LTM, 30, 5);

  // make the engine
  for(i=0;i<Resolution;i++) {
    matrix_xformPoint(&LTM, &(unitCircle[i]), &(pt[i]));
  }

  // send one engine to the right location
  matrix_identity(&LTM);
  matrix_translate2D(&LTM, -5, 27);

  // move the engine
  for(i=0;i<Resolution;i++) {
    matrix_xformPoint(&LTM, &(pt[i]), &(ptt[i]));
  }

  // add the polygon
  ship[index] = polygon_createp(Resolution, ptt);
  shipColor[index++] = Grey;

  // send the other engine to the right location
  matrix_identity(&LTM);
  matrix_translate2D(&LTM, -5, -27);

  // move the engine
  for(i=0;i<Resolution;i++) {
    matrix_xformPoint(&LTM, &(pt[i]), &(ptt[i]));
  }

  // add the polygon
  ship[index] = polygon_createp(Resolution, ptt);
  shipColor[index++] = Grey;

  // set up the phaser
  if(firePhase) {
    matrix_identity(&LTM);

    matrix_scale2D(&LTM, 100, 2);

    // orient the phaser
    matrix_rotateZ(&LTM, cos(phaserAngle*M_PI/180.0), sin(phaserAngle*M_PI/180.0));
    
    // translate it to the center of the disk and out
    matrix_translate2D(&LTM, 
           60 + 30 * cos(phaserAngle*M_PI/180.0), 
           30 * sin(phaserAngle*M_PI/180.0) );

    // use the unit square
    for(i=0;i<4;i++) {
      matrix_xformPoint(&LTM, &(unitSquare[i]), &(pt[i]));
    }
    
    // add the polygon
    ship[index] = polygon_createp(4, pt);
    shipColor[index++] = Red;
  }

  matrix_rotateZ(&GTM, cos(theta*M_PI/180.0), sin(theta*M_PI/180.0));

  printf("GTM:\n");
  matrix_print(&GTM, stdout);

  printf("Pre-GTM/VTM\n");
  polygon_print(ship[0], stdout);

  for(i=0;i<index;i++) {

    // multiply the polygon by the global transform matrix
    matrix_xformPolygon(&GTM, ship[i]);
    if(i==0) {
      printf("Pre-VTM\n");
      polygon_print(ship[i], stdout);
    }

    // multiply the polygon by the view transformation matrix
    matrix_xformPolygon(&VTM, ship[i]);

    if(i==0) {
      printf("Pre-draw\n");
      polygon_print(ship[i], stdout);
    }

    // draw the polygon
    polygon_drawFill(ship[i], src, shipColor[i]);
  }

  image_write(src, "space.ppm");


  image_free(src);

  return(0);
}