Пример #1
0
void Globals::init ()
{	
  try
  {
	YAML::Node config(YAML::LoadFile("assets/config.yml"));
	config = config["game"];

	sf::Vector2u window_size(config["graphic"]["window"]["size"][0].as<unsigned>(),
		config["graphic"]["window"]["size"][1].as<unsigned>());

	window.reset(new sf::RenderWindow(sf::VideoMode(window_size.x, window_size.y), "Vegetable Crush Saga", sf::Style::Default & ~sf::Style::Resize));
	window->setFramerateLimit(60);

	YAML::Node paths(config["system"]["paths"]);
	loadTextures(config["graphic"]["textures"], paths["texture_pack"].as<std::string>());
	loadFonts(config["graphic"]["fonts"], paths["font_pack"].as<std::string>());

	YAML::Node items(config["gameplay"]["items"]);
	loadItems(items);
  }
  catch (YAML::ParserException e)
  {
	std::cerr << "Le fichier de config n'est pas aux normes !" << std::endl;
	std::cerr << e.what() << std::endl;
	exit(EXIT_FAILURE);
  }
}
Пример #2
0
// Initialize the 'renderer_' member. No other members have been initialized at
// this point.
bool Game::InitializeRenderer() {
#ifdef __ANDROID__
  vec2i window_size = GetWindowSize();
  if (fplbase::IsTvDevice()) {
    window_size = vec2i(kAndroidTvMaxScreenWidth, kAndroidTvMaxScreenHeight);
  }
#else
  vec2i window_size(1200, 800);
#endif  // __ANDROID__
  if (!renderer_.Initialize(window_size, GetConfig().window_title()->c_str())) {
    LogError("Renderer initialization error: %s\n",
             renderer_.last_error().c_str());
    return false;
  }

#ifdef __ANDROID__
  // Restart the app if HW scaler setting failed.
  auto retry = fplbase::LoadPreference("HWScalerRetry", 0);
  const auto kMaxRetry = 3;
  auto current_window_size = fplbase::AndroidGetScalerResolution();
  if (current_window_size.x() != window_size.x() ||
      current_window_size.y() != window_size.y()) {
    if (retry < kMaxRetry) {
      LogError("Restarting application.");
      fplbase::SavePreference("HWScalerRetry", retry + 1);
      fplbase::RelaunchApplication();
      return false;
    }
    // The HW may not support the API. Fallback to native resolution pass until
    // the API success next time.
  } else {
    // HW scaler setting was success. Clear retry counter.
    fplbase::SavePreference("HWScalerRetry", 0);
  }
#endif  // __ANDROID__

  renderer_.set_color(mathfu::kOnes4f);
  // Initialize the first frame as black.
  renderer_.ClearFrameBuffer(mathfu::kZeros4f);

#ifdef ANDROID_HMD
  vec2i size = fplbase::AndroidGetScalerResolution();
  const vec2i viewport_size =
      size.x() && size.y() ? size : renderer_.window_size();
  fplbase::InitializeUndistortFramebuffer(viewport_size.x(), viewport_size.y());
#endif  // ANDROID_HMD

#if ZOOSHI_OVERDRAW_DEBUG
  renderer_.SetBlendMode(BlendMode::kBlendModeAdd);
  renderer_.force_blend_mode() = BlendMode::kBlendModeAdd;
  renderer_.override_pixel_shader() =
      "void main() { gl_FragColor = vec4(0.2, 0.2, 0.2, 1); }";
#endif  // ZOOSHI_OVERDRAW_DEBUG

  return true;
}
void CSampleDialogScrollHelper::UpdateScrollInfo()
{
  if (0 == m_pWnd)
    return;

  CRect rect;
  GetClientRectSB(m_pWnd, rect);
  //GetClientRectSB_Ex( m_pWnd, m_display_size, rect );

  CSize window_size(rect.Width(), rect.Height());

  CSize delta_pos(0, 0);
  UpdateScrollBar(SB_HORZ, window_size.cx, m_display_size.cx, m_page_size.cx, m_scroll_pos.cx, delta_pos.cx);
  UpdateScrollBar(SB_VERT, window_size.cy, m_display_size.cy, m_page_size.cy, m_scroll_pos.cy, delta_pos.cy);
  if (delta_pos.cx != 0 || delta_pos.cy != 0)
    m_pWnd->ScrollWindow(delta_pos.cx, delta_pos.cy);
}
Пример #4
0
void PrettyImage::ShowFullsize() {
  // Work out how large to make the window, based on the size of the screen
  QRect desktop_rect(QApplication::desktop()->availableGeometry(this));
  QSize window_size(qMin(desktop_rect.width() - 20, image_.width()),
                    qMin(desktop_rect.height() - 20, image_.height()));

  // Create the window
  QScrollArea* window = new QScrollArea;
  window->setAttribute(Qt::WA_DeleteOnClose, true);
  window->setWindowTitle(tr("Clementine image viewer"));
  window->resize(window_size);

  // Create the label that displays the image
  QLabel* label = new QLabel(window);
  label->setPixmap(QPixmap::fromImage(image_));

  // Show the label in the window
  window->setWidget(label);
  window->setFrameShape(QFrame::NoFrame);
  window->show();
}
Пример #5
0
bool ghosts::render()
{
	glm::vec2 window_size(getWindowSize());
	glm::mat4 projection_matrix = glm::perspectiveFov(glm::pi<float>() * 0.25f, window_size.x, window_size.y, 0.1f, 100.0f);

	graphics::renderer::clear(window_size, glm::vec4(.95f));

	// light: direction light.xyz, intensity light.w
	//glm::vec4 light_vec(-1.f, -2.f, 0.f, 100.f);
	glm::vec4 light_vec(-1.f, -1.f, 0.f, 100.f);

	// simulate
	for (auto model : m_Models) {
		model->simulate(0.016f);
	}

	// render
	for (auto model : m_Models) {
		model->render(projection_matrix, view(), light_vec);
	}

	return true;
}
Пример #6
0
int main(int argc, char **argv)
{
    /* For select(2). */
    struct timeval tv;
    fd_set in;
    /* For parsing arguments. */
    char *cp;
    /* The key read in. */
    char c;

    struct sigaction sact;

    setlocale(LC_ALL, "");
    get_options();
    
    /* set to PCPU sorting */
    register_sort_function( -1, (cmp_t)pcpu_sort);
    
#ifdef HZ
    Hertz = HZ;
#endif

    /*
     * Parse arguments.
     */
    argv++;
    while (*argv) {
	cp = *argv++;
	while (*cp) {
	    switch (*cp) {
	      case 'd':
	        if (cp[1]) {
		    if (sscanf(++cp, "%f", &Sleeptime) != 1) {
			fprintf(stderr, PROGNAME ": Bad delay time `%s'\n", cp);
			exit(1);
		    }
		    goto breakargv;
		} else if (*argv) { /* last char in an argv, use next as arg */
		    if (sscanf(cp = *argv++, "%f", &Sleeptime) != 1) {
			fprintf(stderr, PROGNAME ": Bad delay time `%s'\n", cp);
			exit(1);
		    }
		    goto breakargv;
		} else {
		    fprintf(stderr, "-d requires an argument\n");
		    exit(1);
		}
		break;
	      case 'n':
		if (cp[1]) {
	   	    if (sscanf(++cp, "%d", &Loops) != 1) {
			fprintf(stderr, PROGNAME ": Bad value `%s'\n", cp);
			exit(1);
		    }
		    goto breakargv;
		} else if (*argv) { /* last char in an argv, use next as arg */
		    if (sscanf(cp = *argv++, "%d", &Loops) != 1) {
			fprintf(stderr, PROGNAME ": Bad value `%s'\n", cp);
			 exit(1);
	 	     }
		     goto breakargv;
		}
		break;
					
	      case 'q':
		if (!getuid())
		    /* set priority to -10 in order to stay above kswapd */
		    if (setpriority(PRIO_PROCESS, getpid(), -10)) {
			/* We check this just for paranoia.  It's not
			   fatal, and shouldn't happen. */
			perror(PROGNAME ": setpriority() failed");
		    }
		Sleeptime = 0;
		break;
	      case 'p':
		if (monpids_index >= monpids_max) {
		    fprintf(stderr, PROGNAME ": More than %u process ids specified\n",
			    monpids_max);
		    exit(1);
		}
		if (cp[1]) {
		    if (sscanf(++cp, "%d", &monpids[monpids_index]) != 1 ||
			monpids[monpids_index] < 0 || monpids[monpids_index] > 65535) {
			fprintf(stderr, PROGNAME ": Bad process id `%s'\n", cp);
			exit(1);
		    }
		} else if (*argv) { /* last char in an argv, use next as arg */
		    if (sscanf(cp = *argv++, "%d", &monpids[monpids_index]) != 1 ||
			monpids[monpids_index] < 0 || monpids[monpids_index] > 65535) {
			fprintf(stderr, PROGNAME ": Bad process id `%s'\n", cp);
			exit(1);
		    }
		} else {
		    fprintf(stderr, "-p requires an argument\n");
		    exit(1);
		}
		if (!monpids[monpids_index])
		    monpids[monpids_index] = getpid();
		/* default to no sorting when monitoring process ids */
		if (!monpids_index++) {
		    sort_type = S_NONE;
		    reset_sort_options();
		}
		cp = "_";
		break;
	      case 'b':
		Batch = 1;
	        break;
	      case 'c':
	        show_cmd = !show_cmd;
		break;
	      case 'S':
		Cumulative = 1;
		break;
	      case 'i':
		Noidle = 1;
		break;
	      case 's':
		  Secure = 1;
		  break;
	      case 'C':
		  CPU_states = 1;
		  break;
	      case '-':
		break;		/* Just ignore it */
 	      case 'v':
 	      case 'V':
 		fprintf(stdout, "top (%s)\n", procps_version);
 		exit(0);
	      case 'h':
 		fprintf(stdout, "usage: " PROGNAME " -hvbcisqS -d delay -p pid -n iterations\n");
		exit(0);
	      default:
		fprintf(stderr, PROGNAME ": Unknown argument `%c'\n", *cp);
 		fprintf(stdout, "usage: " PROGNAME " -hvbcisqS -d delay -p pid -n iterations\n");
 	        exit(1);
	    }
	    cp++;
	}
    breakargv:;
    }
    
    if (nr_cpu > 1 && CPU_states)
      header_lines++;

    setup_terminal();
    window_size(0);
    /*
     * Set up signal handlers.
     */
    sact.sa_handler = sig_end;
    sact.sa_flags = 0;
    sigemptyset(&sact.sa_mask);
    sigaction(SIGHUP, &sact, NULL);
    sigaction(SIGINT, &sact, NULL);
    sigaction(SIGQUIT, &sact, NULL);
    sact.sa_handler = sig_stop;
    sact.sa_flags = SA_RESTART;
    sigaction(SIGTSTP, &sact, NULL);
    sact.sa_handler = window_size;
    sigaction(SIGWINCH, &sact, NULL);
    sigaction(SIGCONT, &sact, NULL);

    /* loop, collecting process info and sleeping */
    while (1) {
	if (Loops > 0)
		Loops--;
	/* display the tasks */
	show_procs();
	/* sleep & wait for keyboard input */
	if (Loops == 0)
	    sig_end(0);
        if (!Batch)
        {
		tv.tv_sec = Sleeptime;
		tv.tv_usec = (Sleeptime - (int) Sleeptime) * 1000000;
		FD_ZERO(&in);
		FD_SET(0, &in);
		if (select(1, &in, 0, 0, &tv) > 0 && read(0, &c, 1) == 1)
	    		do_key(c);
        } else {
	   sleep(Sleeptime);
	}
    }
}
Пример #7
0
/*
 * Process keyboard input during the main loop
 */
void do_key(char c)
{
    int numinput, i;
    char rcfile[MAXNAMELEN];
    FILE *fp;

    /*
     * First the commands which don't require a terminal mode switch.
     */
    if (c == 'q')
	sig_end(0);
    else if (c == ' ')
        return;
    else if (c == 12) {
	clear_screen();
	return;
    } else if (c == 'I') {
	Irixmode=(Irixmode) ? 0 : 1;
	return;
    }

    /*
     * Switch the terminal to normal mode.  (Will the original
     * attributes always be normal?  Does it matter?  I suppose the
     * shell will be set up the way the user wants it.)
     */
    if (!Batch) tcsetattr(0, TCSANOW, &Savetty);

    /*
     * Handle the rest of the commands.
     */
    switch (c) {
      case '?':
      case 'h':
	PUTP(cl); PUTP(ho); putchar('\n'); PUTP(mr);
	printf("Proc-Top Revision 1.2");
	PUTP(me); putchar('\n');
	printf("Secure mode ");
	PUTP(md);
	fputs(Secure ? "on" : "off", stdout);
	PUTP(me);
	fputs("; cumulative mode ", stdout);
	PUTP(md);
	fputs(Cumulative ? "on" : "off", stdout);
	PUTP(me);
	fputs("; noidle mode ", stdout);
	PUTP(md);
	fputs(Noidle ? "on" : "off", stdout);
	PUTP(me);
	fputs("\n\n", stdout);
	printf("%s\n\nPress any key to continue", Secure ? SECURE_HELP_SCREEN : HELP_SCREEN);
	if (!Batch) tcsetattr(0, TCSANOW, &Rawtty);
	(void) getchar();
	break;
      case 'i':
	Noidle = !Noidle;
	SHOWMESSAGE(("No-idle mode %s", Noidle ? "on" : "off"));
	break;
      case 'u':
	SHOWMESSAGE(("Which User (Blank for All): "));
	strcpy(CurrUser,getstr());
	break;
      case 'k':
	if (Secure)
	    SHOWMESSAGE(("\aCan't kill in secure mode"));
	else {
	    int pid, signal;
	    PUTP(md);
	    SHOWMESSAGE(("PID to kill: "));
	    pid = getint();
	    if (pid == BAD_INPUT)
		break;
	    PUTP(top_clrtoeol);
	    SHOWMESSAGE(("Kill PID %d with signal [15]: ", pid));
	    PUTP(me);
	    signal = getsig();
	    if (signal == -1)
		signal = SIGTERM;
	    if (kill(pid, signal))
		SHOWMESSAGE(("\aKill of PID %d with %d failed: %s",
			     pid, signal, strerror(errno)));
	}
	break;
      case 'l':
	SHOWMESSAGE(("Display load average %s", !show_loadav ? "on" : "off"));
	if (show_loadav) {
	    show_loadav = 0;
	    header_lines--;
	} else {
	    show_loadav = 1;
	    header_lines++;
	}
	Numfields = make_header();
	break;
      case 'm':
	SHOWMESSAGE(("Display memory information %s", !show_memory ? "on" : "off"));
	if (show_memory) {
	    show_memory = 0;
	    header_lines -= 2;
	} else {
	    show_memory = 1;
	    header_lines += 2;
	}
	Numfields = make_header();
	break;
      case 'M':
        SHOWMESSAGE(("Sort by memory usage"));
	sort_type = S_MEM;
	reset_sort_options();
	register_sort_function(-1, (cmp_t)mem_sort);
	break;
      case 'n':
      case '#':
	printf("Processes to display (0 for unlimited): ");
	numinput = getint();
	if (numinput != BAD_INPUT) {
	    Display_procs = numinput;
	    window_size(0);
	}
	break;
      case 'r':
	if (Secure)
	    SHOWMESSAGE(("\aCan't renice in secure mode"));
	else {
	    int pid, val;

	    printf("PID to renice: ");
	    pid = getint();
	    if (pid == BAD_INPUT)
		break;
	    PUTP(tgoto(cm, 0, header_lines - 2));
	    PUTP(top_clrtoeol);
	    printf("Renice PID %d to value: ", pid);
	    val = getint();
	    if (val == BAD_INPUT)
		val = 10;
	    if (setpriority(PRIO_PROCESS, pid, val))
		SHOWMESSAGE(("\aRenice of PID %d to %d failed: %s",
			     pid, val, strerror(errno)));
	}
	break;
      case 'P':
        SHOWMESSAGE(("Sort by CPU usage"));
	sort_type = S_PCPU;
	reset_sort_options();
	register_sort_function(-1, (cmp_t)pcpu_sort);
	break;
      case 'A':
	SHOWMESSAGE(("Sort by age"));
	sort_type = S_AGE;
	reset_sort_options();
	register_sort_function(-1, (cmp_t)age_sort);
	break;
      case 'N':
	SHOWMESSAGE(("Sort numerically by pid"));
	sort_type = S_NONE;
	reset_sort_options();
	break;
    case 'c':
        show_cmd = !show_cmd;
	SHOWMESSAGE(("Show %s", show_cmd ? "command names" : "command line"));
	break;
      case 'S':
	Cumulative = !Cumulative;
	SHOWMESSAGE(("Cumulative mode %s", Cumulative ? "on" : "off"));
	if (Cumulative)
	    headers[22][1] = 'C';
	else
	    headers[22][1] = ' ';
	Numfields = make_header();
	break;
      case 's':
	if (Secure)
	    SHOWMESSAGE(("\aCan't change delay in secure mode"));
	else {
	    double tmp;
	    printf("Delay between updates: ");
	    tmp = getfloat();
	    if (!(tmp < 0))
		Sleeptime = tmp;
	}
	break;
      case 't':
	SHOWMESSAGE(("Display summary information %s", !show_stats ? "on" : "off"));
	if (show_stats) {
	    show_stats = 0;
	    header_lines -= 2;
	} else {
	    show_stats = 1;
	    header_lines += 2;
	}
	Numfields = make_header();
	break;
      case 'T':
	SHOWMESSAGE(("Sort by %stime", Cumulative ? "cumulative " : ""));
	sort_type = S_TIME;
	reset_sort_options();
	register_sort_function( -1, (cmp_t)time_sort);	
	break;
      case 'f':
      case 'F':
	change_fields();
	break;
      case 'o':
      case 'O':
	change_order();
	break;
      case 'W':
	if (getenv("HOME")) {
	    strcpy(rcfile, getenv("HOME"));
	    strcat(rcfile, "/");
	    strcat(rcfile, RCFILE);
	    fp = fopen(rcfile, "w");
	    if (fp != NULL) {
		fprintf(fp, "%s\n", Fields);
		i = (int) Sleeptime;
		if (i < 2)
		    i = 2;
		if (i > 9)
		    i = 9;
		fprintf(fp, "%d", i);
		if (Secure)
		    fprintf(fp, "%c", 's');
		if (Cumulative)
		    fprintf(fp, "%c", 'S');
		if (!show_cmd)
		    fprintf(fp, "%c", 'c');
		if (Noidle)
		    fprintf(fp, "%c", 'i');
		if (!show_memory)
		    fprintf(fp, "%c", 'm');
		if (!show_loadav)
		    fprintf(fp, "%c", 'l');
		if (!show_stats)
		    fprintf(fp, "%c", 't');
		if (!Irixmode)
		    fprintf(fp, "%c", 'I');
		fprintf(fp, "\n");
		fclose(fp);
		SHOWMESSAGE(("Wrote configuration to %s", rcfile));
	    } else {
		SHOWMESSAGE(("Couldn't open %s", rcfile));
	    }
	} else {
	    SHOWMESSAGE(("Couldn't get $HOME -- not saving"));
	}
	break;
      default:
	SHOWMESSAGE(("\aUnknown command `%c' -- hit `h' for help", c));
    }

    /*
     * Return to raw mode.
     */
    if (!Batch) tcsetattr(0, TCSANOW, &Rawtty);
    return;
}
Пример #8
0
int main(int argc, char **argv)
{

  int n,sockfd, on=1,i,j,maxfdp,optval=1;
  char recvline[LINE_MAX], in_packet[PACKET_LEN];	
  client_config_t config;
  int num_ifi = 0;
  pthread_t tid;
  thread_arg* arg;
  bool done = FALSE, is_probe = FALSE, is_error = FALSE;
  unsigned int ack_seq, seq, timestamp;
  unsigned short curr_win;

  circ_buffer_t rcv_buffer;

  ifi_t *ifi_array[IFI_MAX];

  read_client_config("client.in", &config);
  print_client_config(&config);

  num_ifi = get_ifi(ifi_array);
  print_ifi(ifi_array, num_ifi);

  srand(config.seed);
  init_circular_buffer(&rcv_buffer, config.window_size);
  
  rtt_init(&rttinfo);

  if (connection_setup(&sockfd, ifi_array, num_ifi, &rcv_buffer, &config) < 0)
    err_sys("[Error] Connection Setup Error, Terminating..\n");

  /* TODO: Recv ACK and connect to the new port */

  arg = (thread_arg*)calloc(1, sizeof(thread_arg));
  arg->rcv_buf = &rcv_buffer;
  arg->config = &config;
  arg->sockfd = sockfd;
  Pthread_create(&tid, NULL, &consumer_thread, arg);

  /* Below is the Producer Logic which reads from the socket and fills 
   * up the receive Buffer.
   */
  while (!done)
  {
    if ((n = read(sockfd, in_packet, PACKET_LEN)) < 0)
    {
      if (errno == EINTR) 
        continue;
      else
        err_sys("[Error] Unknown Read Error");
    }

    packet_info_t *pkt_info = get_packet_info(in_packet, n);

    if (!IS_DATA(pkt_info) && !(is_probe = IS_PROBE(pkt_info))
          && !(is_error = IS_ERR(pkt_info)))
    {
      free_pkt_info(pkt_info);
      continue;
    }

    if (consume_random_packet(pkt_info, config.prob_loss, TRUE))
    {
      free_pkt_info(pkt_info);
      continue;
    }

    if(IS_EOF(pkt_info) || is_error)
      done = TRUE;

    Pthread_mutex_lock(&buf_mutex);
    /* Special Handling for Probes & Errors, send an ACK, don't store in buffer */
    if(!is_probe && !is_error)
    {
      write_to_buffer(&rcv_buffer , pkt_info);
    }
    /* Save off these values as we are releasing the lock below */
    curr_win = window_size(&rcv_buffer); 
    ack_seq = NEXT_ACK(&rcv_buffer);
    seq = pkt_info->seq;
    timestamp = pkt_info->timestamp;

    Pthread_mutex_unlock(&buf_mutex);

    if(is_probe)
      printf("[Info] Persist Timer Response [Ack:%u] [Window Size:%hu]\n", ack_seq, curr_win);
    else
      printf("[Info] Received [Seq: %u] Responding with [Ack:%u] [Window Size:%hu]\n", 
          seq, ack_seq, curr_win);

    send_ack(sockfd, curr_win, seq, ack_seq, timestamp, config.prob_loss);

  }
  pthread_exit(NULL);
}
Пример #9
0
/* This routine does the first phase of the client-server Setup.
 * On successfule return, the out parameter sockfd will have the 
 * connection socket fd.
 * */
int connection_setup(int *sockfd, ifi_t *ifi_array[], int num_ifi,
    circ_buffer_t *rcv_buf, client_config_t *config)
{
  packet_t *send_pkt;
  int n, optval=1;
  char in_packet[PACKET_LEN],client_ip[IP_MAX];	
  struct sockaddr_in serv_addr, cliaddr, tempaddr;
  unsigned int ack_seq;
  unsigned short curr_win;
  bool is_error = FALSE;
  packet_info_t *rcv_pkt_info, *send_pkt_info = calloc(1, sizeof(packet_info_t));
  
  *sockfd = Socket(AF_INET, SOCK_DGRAM, 0);

  if(server_on_same_subnet(config->server_ip,ifi_array, num_ifi, client_ip))
  {	
    printf("server on same subnet, SO_DONTROUTE set\n");
    //printf("client ip set to: %s\n",client_ip);
    setsockopt(*sockfd,SOL_SOCKET, SO_DONTROUTE, &optval, sizeof(optval));
  }	
  //update  cli_ip after if it's on the same host or n/w

  bzero(&cliaddr, sizeof(cliaddr));
  cliaddr.sin_family = AF_INET;
  cliaddr.sin_port = 0;
  inet_pton(AF_INET,client_ip,&cliaddr.sin_addr);
  Bind(*sockfd, (SA*) &cliaddr, sizeof(cliaddr));

  //cli addr and port using getsockname
  int cli_port;
  char cli_ip[IP_MAX];
  socklen_t len = sizeof(tempaddr);
  bzero(&tempaddr, sizeof(tempaddr));
  getsockname(*sockfd, (SA*) &tempaddr, &len);
  Inet_ntop(AF_INET, &tempaddr.sin_addr, cli_ip, IP_MAX);
  printf("[Info]client bound to ip:%s\n",cli_ip);
  cli_port = ntohs(tempaddr.sin_port);

  //connect
  bzero(&serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_port = htons(config->server_port);
  Inet_pton(AF_INET, config->server_ip, &serv_addr.sin_addr);
  Connect(*sockfd, (SA *)&serv_addr, sizeof(serv_addr));

  assert(send_pkt_info);

  Signal(SIGALRM, sig_alarm);
  rtt_newpack(&rttinfo);          /* initialize for this packet */

  /* Prepare to send file name */
  send_pkt_info->seq = 0;
  send_pkt_info->ack = 0;
  send_pkt_info->window_size = config->window_size;
  SET_FILE_FLAG(send_pkt_info);
  send_pkt_info->data = strdup(config->file_name);
  send_pkt_info->data_len = strlen(config->file_name) + 1;

  printf("[Info] Sending file name %s to server ..\n", send_pkt_info->data);

sendagain:
  send_pkt_info->timestamp = rtt_ts(&rttinfo);
  send_pkt = build_packet(send_pkt_info);

  Write(*sockfd, (char *)send_pkt, send_pkt_info->data_len+HEADER_SIZE);

  /* set alarm for RTO seconds using setitimer */
  set_alarm(rtt_start(&rttinfo));
  if (sigsetjmp(jmpbuf, 1) != 0)
  {
    if (rtt_timeout(&rttinfo))
    {
      printf("[Error] Timed out Sending File Name, giving Up\n");
      free_pkt_info(send_pkt_info);
      free(send_pkt);
      errno = ETIMEDOUT;
      return -1;
    }
    printf("[Timeout] Retransmitting file name, next RTO:%d ms\n", rttinfo.rtt_rto);
    free(send_pkt);
    goto sendagain;
  }

  /* Now Attempt to read the Port message from the Server */
  while (1)
  {
    if ((n = read(*sockfd, in_packet, PACKET_LEN)) < 0)
    {
      if (errno == EINTR) 
        continue;
      else
        err_sys("[Error] Read Error while waiting for Port number");
    }

    rcv_pkt_info = get_packet_info(in_packet, n);

    if (consume_random_packet(rcv_pkt_info, config->prob_loss, TRUE))
    {
      free_pkt_info(rcv_pkt_info);
      continue;
    }

    if (IS_ACK(rcv_pkt_info) && (rcv_pkt_info->ack == (send_pkt_info->seq+1)))
    {
      break;
    }
    else
    {
      free_pkt_info(rcv_pkt_info);
      continue;
    }
  }

  set_alarm(0);     /* Turn off the Alarm */

  free_pkt_info(send_pkt_info);
  free(send_pkt);

  assert(rcv_pkt_info->data_len == sizeof(short));
  /* Fetch the new port from the server message */
  memcpy(&serv_addr.sin_port, rcv_pkt_info->data, sizeof(short));
  
  printf("[Info] Received new Port number %hu from Server.\n", ntohs(serv_addr.sin_port));

  /* Connect to the new port of the server child process */
  if (connect(*sockfd, (SA *)&serv_addr, sizeof(serv_addr)) < 0) {
    printf("[Error] Connect failure to server child: [%s : %hu]\n", config->server_ip, ntohs(serv_addr.sin_port));
    return -1;
  }

  printf("[Info] Connected to server's child process.\n");

  /* Advance the Circular buffer's read/write pointers to rcv_pkt_info->seq+1.
   * Basically, we are simulating the producer/consumer behavior here, in that we 
   * have written and read from the buffer.
   * Note: The server has to continue the file transfer starting from rcv_pkt_info->seq+1
   * as we will not accept anything lower than this sequence for this session
   * This is similar to the SYN+ACK in TCP
   */
  rcv_buf->next_read_seq = rcv_buf->next_contig_write_seq = rcv_pkt_info->seq+1;
  printf("rcv_buf->next_read_seq = rcv_buf->next_contig_write_seq = %u", rcv_pkt_info->seq+1);

  curr_win = window_size(rcv_buf); 
  ack_seq = NEXT_ACK(rcv_buf); 

  /* Exit if the file does not exist on the server after sending ACK.
   * In the event this ACK is lost, the server ichild timeout mechanism will kick in
   * and eventually it will timeout and give up
   */
  if(is_error = IS_ERR(rcv_pkt_info))
  {
    printf("[Info] Received Error message from server [Seq: %u] Responding with [Ack:%u] [Window Size:%hu]\n", 
        rcv_pkt_info->seq, ack_seq, curr_win);
  }
  else
  {
    printf("[Info] Received Port message [Seq: %u] Responding with [Ack:%u] [Window Size:%hu]\n", 
        rcv_pkt_info->seq, ack_seq, curr_win);
  }

  /* Simulate Loss On Tx */
  if (!consume_random_packet(rcv_pkt_info, config->prob_loss, FALSE))
  {
    send_ack(*sockfd, curr_win, rcv_pkt_info->seq, ack_seq, rcv_pkt_info->timestamp, config->prob_loss);
  }

  free_pkt_info(rcv_pkt_info);
  
  if(is_error)
  {
      printf("[Error] File %s does not exist, terminating..\n", config->file_name);
      errno = EBADF;
      return -1;
  }
  
  printf("[Info] Successful Connection Setup with [%s:%u], ready for file reception\n", 
      config->server_ip, ntohs(serv_addr.sin_port));
  return 0;

}
Пример #10
0
/* This is the Thread which will read data from the Circular buffer 
 * and print out to the Console
 */
void* consumer_thread(void *arg) 
{
  circ_buffer_t *rcv_buf;
  double mean, smoothed_mean;
  int sockfd;
  packet_info_t *pkt_info;
  double get_rand;
  bool data_present, was_buf_full, done = FALSE;
  unsigned int ack_seq;
  unsigned short new_win;
  double prob_loss;

  assert(arg);
  assert(rcv_buf = ((thread_arg *)arg)->rcv_buf);
  assert(((thread_arg *)arg)->config);
  mean = smoothed_mean = ((thread_arg *)arg)->config->mean;
  prob_loss = ((thread_arg *)arg)->config->prob_loss;
  sockfd = ((thread_arg *)arg)->sockfd;
  free(arg);

  Pthread_detach(pthread_self());

  while (!done) {
    get_rand = (double)rand()/RAND_MAX;
    smoothed_mean = -1.0 * mean * log(get_rand);

    printf("[Consumer Thread] Wake Up in %lf ms\n", smoothed_mean);
    usleep((useconds_t)(smoothed_mean * 1000));

    data_present = FALSE;
    was_buf_full = FALSE;

    Pthread_mutex_lock(&buf_mutex);
    if (IS_BUFFER_FULL(rcv_buf))
      was_buf_full = TRUE;

    while(read_from_buffer(rcv_buf, &pkt_info) >= 0)
    {
      data_present = TRUE;
      fprintf(stdout, "[Consumer thread] [seq:%u]\n%.*s\n", pkt_info->seq,
          pkt_info->data_len, pkt_info->data);

      if(IS_EOF(pkt_info))
      {
        done = TRUE;
        break;
      }
      free_pkt_info(pkt_info);
      pkt_info = NULL;
    }
   
    /* Save off these values as we are releasing the lock below */
    new_win = window_size(rcv_buf); 
    ack_seq = NEXT_ACK(rcv_buf); 

    Pthread_mutex_unlock(&buf_mutex);

    if (!data_present)
        printf("[Consumer Thread] No data this time around\n");

    if(was_buf_full)
    {
      /* Advertise New Opened Up window */
       send_ack(sockfd, new_win, 0, ack_seq, 0, prob_loss); 
    }
  }
  exit(0);
}
Пример #11
0
int main(int argc, char** argv)
{
  if (argc != 3) 
  {
    std::cout << "Usage: " << argv[0] << " FILENAME" << std::endl;
    return -1;
  }

  Uint32 flags = SDL_INIT_VIDEO | SDL_INIT_JOYSTICK;

  if (SDL_Init(flags) < 0)
  {
    std::stringstream msg;
    msg << "Couldn't initialize SDL: " << SDL_GetError();
    throw std::runtime_error(msg.str());
  }
  else
  {
    atexit(SDL_Quit);
    SDL_EnableUNICODE(1);
  }

  Size window_size(1024, 576);
  OpenGLWindow window("Image Blur", window_size, window_size);

  SDL_ShowCursor(SDL_DISABLE);

  SurfaceManager surface_manager;

  FramebufferPtr framebuffer = Framebuffer::create_hdr(window_size.width, window_size.height);

  SurfacePtr surface   = Surface::create(Pathname(argv[1], Pathname::kSysPath));
  SurfacePtr surface_2 = Surface::create(Pathname(argv[2], Pathname::kSysPath));

  float ray_length = 3.0f;
  Vector2f pos;
  Vector2f last_pos;
  int t = 0;
  std::vector<Vector2f> buffer(16);
  std::vector<Vector2f>::size_type buffer_pos = 0;
  bool quit = false;
  while(!quit)
  {
    SDL_Event event;
    last_pos = pos;
    while(SDL_PollEvent(&event))
    {
      switch(event.type)
      {
        case SDL_QUIT:
          // FIXME: This should be a bit more gentle, but will do for now
          std::cout << "Ctrl-c or Window-close pressed, game is going to quit" << std::endl;
          quit = true;
          break;

        case SDL_KEYDOWN:
          if (event.key.keysym.sym == SDLK_ESCAPE)
          {
            quit = true;
          }
          break;

        case SDL_MOUSEBUTTONDOWN:
          if (event.button.button == 1)
          {
            ray_length *= 1.0f/1.4f;
          }
          else if (event.button.button == 3)
          {
            ray_length *= 1.4f;
          }
          std::cout << ray_length << std::endl;
          break;
          
        case SDL_MOUSEMOTION:
          //std::cout << event.motion.x << ", " << event.motion.y << std::endl;
          last_pos = pos;
          pos = Vector2f(1024.0f - static_cast<float>(event.motion.x),
                         576.0f - static_cast<float>(event.motion.y));
          break;

        default:
          break;
      }
    }

    t += 30;
    //ray_length = sin(t/1000.0f);

    buffer[buffer_pos % buffer.size()] = pos;
    buffer_pos += 1;

    Display::push_framebuffer(framebuffer);

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    if (true)
    {
      if (false)
      {
        for(size_t i = 0; i < std::min(buffer_pos, buffer.size()); ++i)
        {
          size_t idx = (buffer_pos - buffer.size() + i) % buffer.size();
          pos = buffer[idx];

          float n = static_cast<float>(buffer.size());

          if (false)
          { // after image motion blur
            n = static_cast<float>(i) / ((n * n + n) / 2.0f);
          }
          else
          { // simple trail, doesn't fade out
            n = 1.0f / n;
          }

          surface->draw(SurfaceDrawingParameters()
                        .set_scale(1.0f)
                        .set_pos(pos - Vector2f(surface->get_width()/2, surface->get_height()/2))
                        .set_blend_func(GL_SRC_ALPHA, GL_ONE)
                        .set_color(Color(1.0f, 1.0f, 1.0f, n)));
        }
      }
      else
      {
        int n = 32;
        for(int i = 0; i < n; ++i)
        {
          surface->draw(SurfaceDrawingParameters()
                        .set_scale(1.0f)
                        .set_pos((static_cast<float>(i)/static_cast<float>(n-1)) * pos 
                                 + (static_cast<float>(n-i-1)/static_cast<float>(n-1)) * last_pos
                                 - Vector2f(surface->get_width()/2, surface->get_height()/2))
                        .set_blend_func(GL_SRC_ALPHA, GL_ONE)
                        .set_color(Color(1.0f, 1.0f, 1.0f, 1.0f / static_cast<float>(n))));
        }
      }
    }
    else
    {
      int n = 100;
      for(int i = 0; i < n; ++i)
      {
        float scale = 1.0f + static_cast<float>(i) / static_cast<float>(n) * ray_length;
        if (true)
          surface->draw(SurfaceDrawingParameters()
                        .set_scale(scale)
                        .set_pos(Vector2f(512, 288) - Vector2f(surface->get_width()/2 * scale, 
                                                               surface->get_height()/2 * scale)
                                 + (Vector2f(512, 288) - pos) * scale * 3.0f)
                        .set_blend_func(GL_SRC_ALPHA, GL_ONE)
                        .set_color(Color(1.0f, 1.0f, 1.0f, static_cast<float>(1)/static_cast<float>(n))));

        if (false && i == 1)
        {
          scale = 1.0f;
          //std::cout << "Black: " << pos << std::endl;
          surface_2->draw(SurfaceDrawingParameters()
                         .set_scale(scale)
                         .set_pos(Vector2f(512, 288) - Vector2f(surface_2->get_width()/2 * scale, 
                                                                surface_2->get_height()/2 * scale)
                                  + (Vector2f(512, 288) - pos) * scale * 3.0f)
                         .set_blend_func(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
                         .set_color(Color(1.0f, 1.0f, 1.0f, 1.0f)));
        }
      }
    }
    Display::pop_framebuffer();

    if (true)
    {
      glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, framebuffer->get_handle());
      glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0);

      glBlitFramebufferEXT(0, 0, framebuffer->get_width(), framebuffer->get_height(), 
                           0, 0, framebuffer->get_width(), framebuffer->get_height(),
                           GL_COLOR_BUFFER_BIT, GL_LINEAR /*NEAREST*/);

      glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0);
      glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0);
    }

    SDL_GL_SwapBuffers();
    SDL_Delay(20);
  }

  return 0;
}
Пример #12
0
/*############################ resize_window() #########################*/
signed char
resize_window(void)
{
   static int old_long_window_height = -1,
              old_short_window_height = -1;
   int        long_window_height,
              ret,
              short_window_height;
   Arg        args[2];
   Cardinal   argcount;

   if (window_size(&window_width, &window_height) == YES)
   {
#ifdef _AUTO_REPOSITION
      XWindowAttributes window_attrib;
      int               display_width,
                        display_height,
                        new_x,
                        new_y;
      Position          root_x,
                        root_y;
#endif
      static int        old_line_height = 0;

#ifdef _AUTO_REPOSITION
      /* Get new window position. */
      display_width = DisplayWidth(display, DefaultScreen(display));
      display_height = DisplayHeight(display, DefaultScreen(display));
      XGetWindowAttributes(display, XtWindow(appshell), &window_attrib);

      /* Translate coordinates relative to root window. */
      XtTranslateCoords(appshell, window_attrib.x, window_attrib.y,
                        &root_x, &root_y);

      /* Change x coordinate. */
      if ((root_x + window_width) > display_width)
      {
         new_x = display_width - window_width;

         /* Is window wider then display? */
         if (new_x < 0)
         {
            new_x = 0;
         }
      }
      else
      {
         new_x = root_x;
      }

      /* Change y coordinate. */
      if ((root_y + window_height + 23) > display_height)
      {
         new_y = display_height - window_height;

         /* Is window wider then display? */
         if (new_y < 23)
         {
            new_y = 23;
         }
      }
      else
      {
         new_y = root_y;
      }

      /* Resize window. */
      XtVaSetValues(appshell,
                    XmNminWidth, window_width,
                    XmNmaxWidth, window_width,
                    XmNminHeight, window_height + line_height + line_height + glyph_height + magic_value,
                    XmNmaxHeight, window_height + line_height + line_height + glyph_height + magic_value,
                    NULL);
      XMoveResizeWindow(display, XtWindow(appshell),
                        new_x, new_y,
                        window_width,
                        window_height + line_height + line_height + glyph_height + magic_value);
#else
      XtVaSetValues(appshell,
                    XmNminWidth, window_width,
                    XmNmaxWidth, window_width,
                    XmNminHeight, window_height + line_height + line_height + glyph_height + magic_value,
                    XmNmaxHeight, window_height + line_height + line_height + glyph_height + magic_value,
                    NULL);
      XResizeWindow(display, XtWindow(appshell), window_width,
                    window_height + line_height + line_height + glyph_height + magic_value);
#endif

      /* If the line_height changed, don't forget to change the */
      /* height of the label and button window!                 */
      argcount = 0;
      XtSetArg(args[argcount], XmNwidth, (Dimension)window_width);
      argcount++;
      long_window_height = no_of_rows * line_height;
      if (long_window_height != old_long_window_height)
      {
         XtSetArg(args[argcount], XmNheight, (Dimension)long_window_height);
         argcount++;
         old_long_window_height = long_window_height;
      }
      XtSetValues(line_window_w, args, argcount);
      argcount = 0;
      XtSetArg(args[argcount], XmNwidth, (Dimension)window_width);
      argcount++;
      short_window_height = no_of_short_rows * line_height;
      if (short_window_height != old_short_window_height)
      {
         XtSetArg(args[argcount], XmNheight, (Dimension)(short_window_height));
         argcount++;
         old_short_window_height = short_window_height;
      }
      XtSetValues(short_line_window_w, args, argcount);
      argcount = 0;
      XtSetArg(args[argcount], XmNwidth, (Dimension)window_width);
      argcount++;
      if (line_height != old_line_height)
      {
         XtSetArg(args[argcount], XmNheight, (Dimension)line_height);
         argcount++;
         old_line_height = line_height;
      }
      XtSetValues(label_window_w, args, argcount);
      XtSetValues(button_window_w, args, argcount);
      ret = YES;
   }
   else
   {
      long_window_height = no_of_rows * line_height;
      if (long_window_height != old_long_window_height)
      {
         argcount = 0;
         XtSetArg(args[argcount], XmNheight, (Dimension)long_window_height);
         argcount++;
         XtSetValues(line_window_w, args, argcount);
         XtResizeWidget(line_window_w, window_width, long_window_height, 0);
      }
      short_window_height = (no_of_short_rows * line_height) + 1;
      if (short_window_height != old_short_window_height)
      {
         argcount = 0;
         XtSetArg(args[argcount], XmNheight, (Dimension)(short_window_height));
         argcount++;
         XtSetValues(short_line_window_w, args, argcount);
         XtResizeWidget(short_line_window_w, window_width,
                        short_window_height, 0);
      }
      if ((old_long_window_height != -1) && (old_short_window_height != -1))
      {
         if (short_line_window_w->core.y != (line_window_w->core.y + long_window_height))
         {
            XtMoveWidget(short_line_window_w,
                         short_line_window_w->core.x,
                         line_window_w->core.y + long_window_height);
         }
      }
      old_long_window_height = long_window_height;
      old_short_window_height = short_window_height;
      ret = NO;
   }
   return(ret);
}
	void filter_y(int w,int h,T* src,T* dst)
	{
		if(h<window_size())
			throw std::invalid_argument("Image height has to be larger than filter window size!");
		filter_y<CH>(w,h,src,dst);
	}
	void filter_x(int w,int h,T* src,T* dst)
	{
		if(w<window_size())
			throw std::invalid_argument("Image width has to be larger than filter window size!");
		filter_x<CH>(w,h,src,dst);
	}
Пример #15
0
Файл: top.c Проект: AnthraX1/rk
int main(int argc, char **argv)
{
    /* For select(2). */
    struct timeval tv;
    fd_set in;
    /* For parsing arguments. */
    char *cp;
    /* The key read in. */
    char c;

    get_options();
    /*
     * Parse arguments.
     */
    argv++;
    while (*argv) {
	cp = *argv++;
	while (*cp) {
	    switch (*cp) {
	      case 'd':
	        if (cp[1]) {
		    if (sscanf(++cp, "%f", &Sleeptime) != 1) {
			fprintf(stderr, PROGNAME ": Bad delay time `%s'\n", cp);
			exit(1);
		    }
		    goto breakargv;
		} else if (*argv) { /* last char in an argv, use next as arg */
		    if (sscanf(cp = *argv++, "%f", &Sleeptime) != 1) {
			fprintf(stderr, PROGNAME ": Bad delay time `%s'\n", cp);
			exit(1);
		    }
		    goto breakargv;
		} else {
		    fprintf(stderr, "-d requires an argument\n");
		    exit(1);
		}
		break;
	      case 'q':
		if (!getuid())
		    /* set priority to -10 in order to stay above kswapd */
		    if (setpriority(PRIO_PROCESS, getpid(), -10)) {
			/* We check this just for paranoia.  It's not
			   fatal, and shouldn't happen. */
			perror(PROGNAME ": setpriority() failed");
		    }
		Sleeptime = 0;
		break;
	      case 'c':
	        show_cmd = !show_cmd;
		break;
	      case 'S':
		Cumulative = 1;
		break;
	      case 'i':
		Noidle = 1;
		break;
	      case 's':
		Secure = 1;
		break;
	      case '-':
		break;		/* Just ignore it */
#if defined (SHOWFLAG)
              case '/': showall++;
#endif
	      default:
		fprintf(stderr, PROGNAME ": Unknown argument `%c'\n", *cp);
		exit(1);
	    }
	    cp++;
	}
    breakargv:
    }
    
    /* set to PCPU sorting */
    register_sort_function( -1, (cmp_t)pcpu_sort);
    
    /* for correct handling of some fields, we have to do distinguish 
  * between kernel versions */
    set_linux_version();
    /* get kernel symbol table, if needed */
    if (!CL_wchan_nout) {
	if (open_psdb()) {
	    CL_wchan_nout = 1;
	} else {
	    psdbsucc = 1;
	}
    }

    setup_terminal();
    window_size();
    /*
     * calculate header size, length of cmdline field ...
     */
    Numfields = make_header();
    /*
     * Set up signal handlers.
     */
    signal(SIGHUP, (void *) (int) end);
    signal(SIGINT, (void *) (int) end);
    signal(SIGQUIT, (void *) (int) end);
    signal(SIGTSTP, (void *) (int) stop);
    signal(SIGWINCH, (void *) (int) window_size);

    /* loop, collecting process info and sleeping */
    while (1) {
	if (setjmp(redraw_jmp))
	    clear_screen();

	/* display the tasks */
	show_procs();
	/* sleep & wait for keyboard input */
	tv.tv_sec = Sleeptime;
	tv.tv_usec = (Sleeptime - (int) Sleeptime) * 1000000;
	FD_ZERO(&in);
	FD_SET(0, &in);
	if (select(16, &in, 0, 0, &tv) > 0 && read(0, &c, 1) == 1)
	    do_key(c);
    }
}

/*#######################################################################
 *#### Signal handled routines: error_end, end, stop, window_size     ###
 *#### Small utilities: make_header, getstr, getint, getfloat, getsig ###
 *#######################################################################
 */


	/*
	 *  end when exiting with an error.
	 */
void error_end(int rno)
{
    if (psdbsucc)
        close_psdb();
    ioctl(0, TCSETAF, &Savetty);
    PUTP(tgoto(cm, 0, Lines - 1));
    fputs("\r\n", stdout);
    exit(rno);
}
/*
	 * Normal end of execution.
	 */
void end(void)
{
    if (psdbsucc)
	close_psdb();
    ioctl(0, TCSETAF, &Savetty);
    PUTP(tgoto(cm, 0, Lines - 1));
    fputs("\r\n", stdout);
    exit(0);
}

/*
	 * SIGTSTP catcher.
	 */
void stop(void)
{
    /* Reset terminal. */
    if (psdbsucc)
	close_psdb();
    ioctl(0, TCSETAF, &Savetty);
    PUTP(tgoto(cm, 0, Lines - 3));
    fflush(stdout);
    raise(SIGTSTP);
    /* Later... */
    ioctl(0, TCSETAF, &Rawtty);
    signal(SIGTSTP, (void *) (int) stop);
    longjmp(redraw_jmp, 1);
}

/*
       * Reads the window size and clear the window.  This is called on setup,
       * and also catches SIGWINCHs, and adjusts Maxlines.  Basically, this is
       * the central place for window size stuff.
       */
void window_size(void)
{
    struct winsize ws;

    if (ioctl(1, TIOCGWINSZ, &ws) != -1) {
	Cols = ws.ws_col;
	Lines = ws.ws_row;
    } else {
	Cols = tgetnum("co");
	Lines = tgetnum("li");
    }
    clear_screen();
}
/*
       * this adjusts the lines needed for the header to the current value
       */
int make_header(void)
{
    int i, j;

    j = 0;
    for (i = 0; i < strlen(Fields); i++) {
	if (isupper(Fields[i])) {
	    pflags[j++] = Fields[i] - 'A';
	}
    }
    strcpy(Header, "");
    for (i = 0; i < j; i++)
	strcat(Header, headers[pflags[i]]);
    /* readjust window size ... */
    Maxcmd = Cols - strlen(Header) + 7;
    Maxlines = Display_procs ? Display_procs : Lines - header_lines;
    if (Maxlines > Lines - header_lines)
	Maxlines = Lines - header_lines;
    return (j);
}
Пример #16
0
void OculusWindow::initialize_hmd_environment()
{
    try {

        auto result = ovr_Initialize(nullptr);

        if (!OVR_SUCCESS(result)) {
            Logger::LOG_WARNING << "Failed to initialize oculus environment!" << "Errorcode:" << (int)result << std::endl;
        }

        ovrGraphicsLuid luid;
        result = ovr_Create(&hmd_session_, &luid);

        if (!OVR_SUCCESS(result)) {

            throw std::runtime_error("Unable to create HMD.");
        }

        hmd_desc_ = ovr_GetHmdDesc(hmd_session_);

        // get optimal texture size for rendering
        ovrSizei ideal_texture_size_left = ovr_GetFovTextureSize(hmd_session_, ovrEyeType(0), hmd_desc_.DefaultEyeFov[0], 1);
        ovrSizei ideal_texture_size_right = ovr_GetFovTextureSize(hmd_session_, ovrEyeType(1), hmd_desc_.DefaultEyeFov[1], 1);

        math::vec2ui window_size(ideal_texture_size_left.w + ideal_texture_size_right.w, std::max(ideal_texture_size_left.h, ideal_texture_size_right.h));

        // initialize window => resolution is independent of rendering resolution!
        config.set_size(window_size);

        config.set_left_resolution(math::vec2ui(ideal_texture_size_left.w, ideal_texture_size_left.h));
        config.set_left_position(math::vec2ui(0, 0));
        config.set_right_resolution(math::vec2ui(ideal_texture_size_right.w, ideal_texture_size_right.h));
        config.set_right_position(math::vec2ui(ideal_texture_size_left.w, 0));

        // Initialize VR structures, filling out description.
        ovrEyeRenderDesc eyeRenderDesc[2];
        ovrVector3f      hmdToEyeViewOffset[2];

        eyeRenderDesc[0] = ovr_GetRenderDesc(hmd_session_, ovrEye_Left, hmd_desc_.DefaultEyeFov[0]);
        eyeRenderDesc[1] = ovr_GetRenderDesc(hmd_session_, ovrEye_Right, hmd_desc_.DefaultEyeFov[1]);

        hmdToEyeViewOffset[0] = eyeRenderDesc[0].HmdToEyeOffset;
        hmdToEyeViewOffset[1] = eyeRenderDesc[1].HmdToEyeOffset;

        // Initialize our single full screen Fov layer.
        color_layer_.Header.Type = ovrLayerType_EyeFov;
        color_layer_.Header.Flags = 0;
        color_layer_.Fov[0] = eyeRenderDesc[0].Fov;
        color_layer_.Fov[1] = eyeRenderDesc[1].Fov;

        ovrRecti left_viewport;
        left_viewport.Size = { int(config.left_resolution().x), int(config.left_resolution().y) };
        left_viewport.Pos = { int(config.left_position().x), int(config.left_position().y) };

        ovrRecti right_viewport;
        right_viewport.Size = { int(config.right_resolution().x), int(config.right_resolution().y) };
        right_viewport.Pos = { int(config.right_position().x), int(config.right_position().y) };

        color_layer_.Viewport[0] = left_viewport;
        color_layer_.Viewport[1] = right_viewport;

    }
    catch (std::exception& e) {
        gua::Logger::LOG_WARNING << "Failed to initialize oculus rift.\n" << e.what() << std::endl;
    }
}