Exemple #1
0
/* Make sure the peeking works fine on normal read. */
static int eq_wait_read_peek(void)
{
	int testret;
	int ret;

	testret = FAIL;

	ret = create_eq(32, FI_WRITE, FI_WAIT_NONE);
	if (ret) {
		sprintf(err_buf, "fi_eq_open ret=%d, %s", ret,
				fi_strerror(-ret));
		goto fail;
	}

	ret = insert_events(5);
	if (ret)
		goto fail;

	ret = read_events(5, FI_PEEK);
	if (ret)
		goto fail;

	ret = read_events(5, 0);
	if (ret)
		goto fail;

	testret = PASS;
fail:
	FT_CLOSE_FID(eq);
	return TEST_RET_VAL(ret, testret);
}
Exemple #2
0
static int check_events(void)
{
	struct input_event *iev;
	int ret = 0;
	int rep_config_done = 0;
	int rep_keys_done = 0;

	read_events();

	while (have_events()) {
		iev = next_event();
		switch (iev->type) {
		case EV_REP:
			ret = parse_autorepeat_config(iev);
			rep_config_done = 1;
			break;
		case EV_KEY:
			ret = parse_key(iev);
			rep_keys_done = 1;
			break;
		default:
			tst_resm(TFAIL,
				 "Unexpected event type '0x%04x' received",
				iev->type);
			ret = 0;
			break;
		}

		if (!ret || (rep_config_done && rep_keys_done))
			break;
	}

	return ret;
}
Exemple #3
0
static	void
NeWS_send(const char *cp, size_t len)
{
    struct sigaction orig;

    if (PostScript == (PSFILE *) NULL || (globals.ev.flags & NeWS_ev_mask))
	return;

    (void) sigaction(SIGPIPE, &psio_sigpipe_handler_struct, &orig);
    sigpipe_error = False;

    NeWS_send_byte = cp;
    NeWS_send_end = cp + len;
    NeWS_xout.xio_events |= XIO_OUT;
#if HAVE_POLL
    if (NeWS_xout.pfd != NULL)
	NeWS_xout.pfd->events |= POLLOUT;
#endif

    write_to_NeWS();
    (void) read_events(NeWS_ev_mask | EV_ACK);

    if (!(globals.ev.flags & EV_ACK)) {	/* if interrupted */
	/* ||| Do somthing more severe here */
    }

    globals.ev.flags &= ~EV_ACK;

    /* put back generic handler for SIGPIPE */
    (void) sigaction(SIGPIPE, &orig, (struct sigaction *) NULL);

    if (!NeWS_in_header)
	post_send();
}
Exemple #4
0
static struct input_event *next_event(void)
{
	if (!have_events())
		read_events();

	return &events[ev_iter++];
}
Exemple #5
0
static int prepare_read_events(int daemonize)
{
	int fd;
	struct sockaddr_nl sa;
	struct sigaction act;

	fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_UEVENT);
	if (fd < 0) {
		logger(-1, errno, "Error in socket()");
		return 1;
	}

	memset(&sa, 0, sizeof(sa));
	sa.nl_family = AF_NETLINK;
	sa.nl_groups = 1;
	if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
		if (errno == ENOENT)
			logger(-1, 0, "Looks like vzevent kernel module "
					"is not loaded; exiting.");
		else
			logger(-1, errno, "Error in bind()");
		close(fd);
		return 1;
	}

	sigemptyset(&act.sa_mask);
	act.sa_handler = child_handler;
	act.sa_flags = SA_NOCLDSTOP;
	sigaction(SIGCHLD, &act, NULL);

	if (daemonize != 0)
		return daemon_read_events(fd, &sa);
	else
		return read_events(fd, &sa);
}
Exemple #6
0
static void *
watch(void *arg)
{
	int fd, err;
	queue_t q;
	struct inotify_event *event;

	fd = ((struct watch_data_t *)arg)->fd;
	q = ((struct watch_data_t *)arg)->q;
	free(arg);

	while (1) {
		while (!queue_empty(q)) {
			event = queue_front(q);
			queue_dequeue(q);
			err = create_ihandler_thread(event);
			if (err < 0)
				err_msg("warning[watch]: Unable to spawn inotify event handler for event->wd #%d\n", event->wd);
		}

		if (event_check(fd) > 0) {
			int r;
			r = read_events(q, fd);
			if (r < 0)  /* read(2) in read_events() returned an error. */
				break;
		}
	}

	return NULL;
}
Exemple #7
0
// -----------------------------------------------------------
// town data
// -----------------------------------------------------------
bool t_abstract_town::read( std::streambuf&					 stream, 
							t_qualified_adv_object_type const& type,
							int								 version )
{
	t_owned_adv_object::read( stream, type, version );
	m_buildings = get_bitset<k_town_building_count>( stream );
	m_enabled_buildings = get_bitset<k_town_building_count>( stream );
	if (version < 14)
		t_creature_array::read_version( stream, 0 );
	else if (version < 19)
		t_creature_array::read_version( stream, 1 );
	else
		t_creature_array::read( stream ); // 19 and later allow creature array it's own version
	read_string16( stream, m_name );

	get_towndwelling_count();	// trigger assert if too many

	if (version < 10)
		m_named_by_map = !m_name.empty();
	else
		m_named_by_map = get< bool >( stream );

	m_type = get<t_town_type>( stream );
	read_events( stream, version );

	if ( version < 16 )
		m_ai_importance = k_ai_importance_normal;
	else
		m_ai_importance = t_ai_importance( get< t_uint8 >( stream ) );

	return true;
}
Exemple #8
0
CAMLprim value stub_fsevents_read_events(value env)
{
  CAMLparam1(env);
  CAMLlocal3(event_list, event, cons);
  struct event *to_free;
  struct event *events = read_events((struct env*)env);
  event_list = Val_emptylist;
  while (events != NULL) {
    // A tuple to store the filed
    event = caml_alloc(2, 0);
    Store_field(event, 0, caml_copy_string(events->path));
    Store_field(event, 1, caml_copy_string(events->wpath));
    to_free = events;
    events = events->next;

    // This is how you do event::event_list in c
    cons = caml_alloc(2, 0);
    Store_field(cons, 0, event);
    Store_field(cons, 1, event_list);
    event_list = cons;

    // Free the processed event
    free(to_free->path);
    free(to_free->wpath);
    free(to_free);
  }

  CAMLreturn(event_list);
}
Exemple #9
0
/** Dispatch events in an event queue
 *
 * \param display The display context object
 * \param queue The event queue to dispatch
 * \return The number of dispatched events on success or -1 on failure
 *
 * Dispatch all incoming events for objects assigned to the given
 * event queue. On failure -1 is returned and errno set appropriately.
 *
 * This function blocks if there are no events to dispatch. If calling from
 * the main thread, it will block reading data from the display fd. For other
 * threads this will block until the main thread queues events on the queue
 * passed as argument.
 *
 * \memberof wl_display
 */
WL_EXPORT int
wl_display_dispatch_queue(struct wl_display *display,
			  struct wl_event_queue *queue)
{
	struct pollfd pfd[2];
	int ret;

	pthread_mutex_lock(&display->mutex);

	ret = dispatch_queue(display, queue);
	if (ret == -1)
		goto err_unlock;
	if (ret > 0) {
		pthread_mutex_unlock(&display->mutex);
		return ret;
	}

	/* We ignore EPIPE here, so that we try to read events before
	 * returning an error.  When the compositor sends an error it
	 * will close the socket, and if we bail out here we don't get
	 * a chance to process the error. */
	ret = wl_connection_flush(display->connection);
	if (ret < 0 && errno != EAGAIN && errno != EPIPE) {
		display_fatal_error(display, errno);
		goto err_unlock;
	}

	display->reader_count++;

	pthread_mutex_unlock(&display->mutex);

	pfd[0].fd = display->fd;
	pfd[0].events = POLLIN;
	do {
		ret = poll(pfd, 1, -1);
	} while (ret == -1 && errno == EINTR);

	if (ret == -1) {
		wl_display_cancel_read(display);
		return -1;
	}

	pthread_mutex_lock(&display->mutex);

	if (read_events(display) == -1)
		goto err_unlock;

	ret = dispatch_queue(display, queue);
	if (ret == -1)
		goto err_unlock;

	pthread_mutex_unlock(&display->mutex);

	return ret;

 err_unlock:
	pthread_mutex_unlock(&display->mutex);
	return -1;
}
Exemple #10
0
static int daemon_read_events(int fd, struct sockaddr_nl *sa)
{
	if (daemon(0, 0) < 0) {
		logger(-1, errno, "Error in daemon()");
		return 1;
	}
	/* Now make logger stop printing to stdout/stderr */
	set_log_quiet(1);
	return read_events(fd, sa);
}
int main(void)
{
   int nout, nin;
   
   mcfioC_Init();
   nout = write_events();
   nin = read_events();
   printf(" %d events written and %d events read back\n",nout,nin);
   return 0;
}
Exemple #12
0
/** Dispatch events in an event queue
 *
 * \param display The display context object
 * \param queue The event queue to dispatch
 * \return The number of dispatched events on success or -1 on failure
 *
 * Dispatch all incoming events for objects assigned to the given
 * event queue. On failure -1 is returned and errno set appropriately.
 *
 * This function blocks if there are no events to dispatch. If calling from
 * the main thread, it will block reading data from the display fd. For other
 * threads this will block until the main thread queues events on the queue
 * passed as argument.
 *
 * \memberof wl_display
 */
WL_EXPORT int
wl_display_dispatch_queue(struct wl_display *display,
			  struct wl_event_queue *queue)
{
	struct pollfd pfd[2];
	int ret;

	pthread_mutex_lock(&display->mutex);

	ret = dispatch_queue(display, queue);
	if (ret == -1)
		goto err_unlock;
	if (ret > 0) {
		pthread_mutex_unlock(&display->mutex);
		return ret;
	}

	ret = wl_connection_flush(display->connection);
	if (ret < 0 && errno != EAGAIN) {
		display_fatal_error(display, errno);
		goto err_unlock;
	}

	display->reader_count++;

	pthread_mutex_unlock(&display->mutex);

	pfd[0].fd = display->fd;
	pfd[0].events = POLLIN;
	do {
		ret = poll(pfd, 1, -1);
	} while (ret == -1 && errno == EINTR);

	if (ret == -1) {
		wl_display_cancel_read(display);
		return -1;
	}

	pthread_mutex_lock(&display->mutex);

	if (read_events(display) == -1)
		goto err_unlock;

	ret = dispatch_queue(display, queue);
	if (ret == -1)
		goto err_unlock;

	pthread_mutex_unlock(&display->mutex);

	return ret;

 err_unlock:
	pthread_mutex_unlock(&display->mutex);
	return -1;
}
Exemple #13
0
int resolve_event(char *name, struct perf_event_attr *attr)
{
	struct event *e;
	if (!eventlist)
		read_events(NULL);
	for (e = eventlist; e; e = e->next) {
		if (!strcasecmp(e->name, name)) {
			return jevent_name_to_attr(e->event, attr);
		}
	}
	return -1;
}
Exemple #14
0
static gboolean next_local(XEvent *event_return)
{
	g_return_val_if_fail(q != NULL, FALSE);
	g_return_val_if_fail(event_return != NULL, FALSE);
	if(!qnum)
		read_events(FALSE);
	if(qnum) {
		*event_return = q[qstart];
		pop(qstart);
		return TRUE;
	}
	return FALSE;
}
Exemple #15
0
/** Read events from display file descriptor
 *
 * \param display The display context object
 * \return 0 on success or -1 on error.  In case of error errno will
 * be set accordingly
 *
 * This will read events from the file descriptor for the display.
 * This function does not dispatch events, it only reads and queues
 * events into their corresponding event queues.  If no data is
 * avilable on the file descriptor, wl_display_read_events() returns
 * immediately.  To dispatch events that may have been queued, call
 * wl_display_dispatch_pending() or
 * wl_display_dispatch_queue_pending().
 *
 * Before calling this function, wl_display_prepare_read() must be
 * called first.
 *
 * \memberof wl_display
 */
WL_EXPORT int
wl_display_read_events(struct wl_display *display)
{
	int ret;

	pthread_mutex_lock(&display->mutex);

	ret = read_events(display);

	pthread_mutex_unlock(&display->mutex);

	return ret;
}
int CInotify::process_events()
{
	if(waitnotify())
	{
		int ret = read_events();			
		if(ret == -1)
		{
			return -1;
		}
	}

	return 0;
}
Exemple #17
0
int walk_events(int (*func)(void *data, char *name, char *event, char *desc),
		void *data)
{
	struct event *e;
	if (!eventlist)
		read_events(NULL);
	for (e = eventlist; e; e = e->next) {
		int ret = func(data, e->name, e->event, e->desc);
		if (ret)
			return ret;
	}
	return 0;
}
Exemple #18
0
int process_inotify_events (queue_t q, int fd) {
  while (keep_running && (watched_items > 0)) {
    if (event_check (fd) > 0) {
      int r;
      r = read_events (q, fd);
      if (r < 0) {
        break;
      } else {
        handle_events (q);
      }
    }
  }
  return 0;
}
Exemple #19
0
static void
waitack(void)
{
    if (PostScript == (PSFILE *) NULL)
	return;

    if (NeWS_pending > 0)
	(void) read_events(EV_GE_ACK);

    if (globals.ev.flags & EV_ACK) {
	globals.ev.flags &= ~EV_ACK;
	return;
    }

    /* ||| Do something more serious here */
}
Exemple #20
0
gboolean xqueue_exists_local(xqueue_match_func match, gpointer data)
{
	gulong i, checked;
	g_return_val_if_fail(q != NULL, FALSE);
	g_return_val_if_fail(match != NULL, FALSE);
	checked = 0;
	while(TRUE) {
		for(i = checked; i < qnum; ++i, ++checked) {
			const gulong p = (qstart + i) % qsz;
			if(match(&q[p], data))
				return TRUE;
		}
		if(!read_events(FALSE))
			break;
	}
	return FALSE;
}
/***********************************************************************//**
 * @brief Read LAT events from FITS file.
 *
 * @param[in] file FITS file.
 *
 * This method read the LAT event list from a FITS file.
 *
 * The method clears the object before loading, thus any events residing in
 * the object before loading will be lost.
 ***************************************************************************/
void GLATEventList::read(const GFits& file)
{
    // Clear object
    clear();

    // Get HDU (pointer is always valid)
    const GFitsTable& hdu = *file.table("EVENTS");

    // Read event data
    read_events(hdu);

    // Read data selection keywords
    read_ds_keys(hdu);

    // If we have a GTI extension, then read Good Time Intervals from that
    // extension
    if (file.contains("GTI")) {
        const GFitsTable& gti = *file.table("GTI");
        m_gti.read(gti);
    }

    // ... otherwise build GTI from TSTART and TSTOP
    else {

        // Read start and stop time
        double tstart = hdu.real("TSTART");
        double tstop  = hdu.real("TSTOP");

        // Create time reference from header information
        GTimeReference timeref(hdu);
        
        // Set start and stop time
        GTime start(tstart);
        GTime stop(tstop);

        // Append start and stop time as single time interval to GTI
        m_gti.append(start, stop);

        // Set GTI time reference
        m_gti.reference(timeref);

    } // endelse: GTI built from TSTART and TSTOP

    // Return
    return;
}
Exemple #22
0
gboolean xqueue_remove_local(XEvent *event_return, xqueue_match_func match, gpointer data)
{
	gulong i, checked;
	g_return_val_if_fail(q != NULL, FALSE);
	g_return_val_if_fail(event_return != NULL, FALSE);
	g_return_val_if_fail(match != NULL, FALSE);
	checked = 0;
	while(TRUE) {
		for(i = checked; i < qnum; ++i, ++checked) {
			const gulong p = (qstart + i) % qsz;
			if(match(&q[p], data)) {
				*event_return = q[p];
				pop(p);
				return TRUE;
			}
		}
		if(!read_events(FALSE))
			break;
	}
	return FALSE;
}
Exemple #23
0
void
ecore_main_loop_begin(void)
{
   void (*_ecore_main_loop_begin)(void) =
      dlsym(RTLD_NEXT, "ecore_main_loop_begin");


   if (!_hook_setting->recording && _hook_setting->file_name)
     {
        ts.td = calloc(1, sizeof(Timer_Data));
#ifdef DEBUG_TSUITE
        printf("<%s> rec file is <%s>\n", __func__, _hook_setting->file_name);
#endif
        vr_list = read_events(_hook_setting->file_name, ts.td);
        if (ts.td->current_event)
          {  /* Got first event in list, run test */
             tsuite_feed_event(ts.td);
          }
     }

   return _ecore_main_loop_begin();
}
Exemple #24
0
int main(int argc,char *argv[])
{
   General general;
   Stopping sto;
   Concentration conc;
   Event *event;
   Measurement meas;
   int i;
   event=(Event *) malloc(MAXEVENTS*sizeof(Event));
   read_command_line(argc,argv,&general);
   read_setup(&general,&meas,&conc);
   allocate_general_sto_conc(&general, &meas, &sto, &conc);
   switch(general.cs) {
        default:
        case CS_RUTHERFORD:
            fprintf(stderr, "erd_depth is using Rutherford cross sections\n");
            break;
        case CS_LECUYER:
            fprintf(stderr, "erd_depth is using L'Ecuyer corrected Rutherford cross sections\n");
            break;
        case CS_ANDERSEN:
            fprintf(stderr, "erd_depth is using Andersen corrected Rutherford cross sections\n");
            break;
   }
   clear_conc(&general, &conc);
   read_events(&general,&meas,event,&conc);
   calculate_stoppings(&general, &meas, &sto);
   create_conc_profile(&general,&meas,&sto,&conc);
   for(i=0;i<general.niter;i++){
      calculate_primary_energy(&general,&meas,&sto,&conc);
      clear_conc(&general, &conc);
      calculate_recoil_depths(&general,&meas,event,&sto,&conc);
      create_conc_profile(&general,&meas,&sto,&conc);
   }

   output(&general,&conc,event);

   exit(0);
}
Exemple #25
0
int main(int argc, char *argv[])
{
  int s;
  int numsentences;
  FILE *words;
  char grammar[1000];
  char buffer[1000];
  float temp;
  int npflag;

  time_t g_time;
  time_t s_time;

  if(argc!=8) 
    {
      fprintf(stderr,"ERROR in command line, usage:\n cat countsfile | parser.out sentences-file grammarfile beamsize punctuation-flag distaflag distvflag npflag\n");
      return 0;
    }

  sscanf(argv[1],"%s",buffer);
  words=fopen(buffer,"r");
  assert(words!=NULL);

  sscanf(argv[2],"%s",grammar);

  sscanf(argv[3],"%f",&temp);
  BEAMPROB = log(temp);

  sscanf(argv[4],"%d",&PUNC_FLAG);

  sscanf(argv[5],"%d",&DISTAFLAG);
  sscanf(argv[6],"%d",&DISTVFLAG);
  sscanf(argv[7],"%d",&npflag);
  assert(npflag==0 || npflag==1);
  set_treebankoutputflag(npflag);

  mymalloc_init();
  mymalloc_char_init();

  hash_make_table(8000007,&new_hash);
  effhash_make_table(1000003,&eff_hash);

  read_grammar(grammar);

  numsentences=read_sentences(words,sentences,2500);

  fprintf(stderr,"NUMSENTENCES %d\n",numsentences);

  read_events(stdin,&new_hash,-1);

  for(s=0;s<numsentences;s++)
   {
     time(&g_time);

     pthresh = -5000000;

     parse_sentence(&sentences[s]);
     
/*     print_chart();*/
     time(&s_time);
     printf("TIME %d\n",(int) (s_time-g_time));
   }
  return 1;
}
Exemple #26
0
int 
glite_wll_perftest_init(const char *host,
			const char *user,
			const char *testname,
			const char *filename, 
			int n)
{
	edg_wll_Context ctx;

	if (edg_wll_InitContext(&ctx) != 0) {
		fprintf(stderr, "edg_wll_InitContext() failed\n");
		return(-1);
	}

	if(trio_asprintf(&termination_string, EDG_WLL_FORMAT_USERTAG,
		    PERFTEST_END_TAG_NAME, PERFTEST_END_TAG_VALUE) < 0)
		return(-1);

	/* set parameters */
	if(user) 
		test_user = strdup(user);
	else {
		test_user = getenv("PERFTEST_USER");
		if(test_user == NULL) 
			test_user = "******";
	}
	if(testname)
		test_name = strdup(testname);
	else {
		test_name = getenv("PERFTEST_NAME");
		if(test_name == NULL)
			test_name = "unspecified";
	}
	if(host == NULL) {
		host = getenv("PERFTEST_HOST");
		if(host == NULL)
			host = "localhost";
	}
	{
		char *p;

		p = strrchr(host, ':');
  		if(p) 
			*p = 0;
		dest_host = strdup(host);
		if(p) {
			*p++ = ':';
			dest_port = atoi(p);
		} else 
			dest_port = GLITE_JOBID_DEFAULT_PORT;
	}

	/* reset event source */
	cur_event = cur_job = 0;
	njobs = n;

	/* if we are asked to read events in, read them */
	if(filename) {
		int fd;
		
		if((fd=open(filename, O_RDONLY)) < 0) {
			fprintf(stderr, "glite_wll_perftest_init: Could not open event file %s: %s",
				filename, strerror(errno));
			return(-1);
		}
		
		if((nevents=read_events(fd)) < 0)
			return(-1);

		close(fd);

		fprintf(stderr, "PERFTEST_JOB_SIZE=%d\n", nevents);
		fprintf(stderr, "PERFTEST_NUM_JOBS=%d\n", njobs);
		fprintf(stderr, "PERFTEST_NUM_SUBJOBS=%d\n", nsubjobs);
	}

	/* we suppose nsubjobs was filled in by read_events() */


	/* generate final_jobid */
	do {
		glite_jobid_t jobid;

		if(glite_wll_perftest_createJobId(dest_host,
						  dest_port,
						  test_user,
						  test_name,
						  n,
						  &jobid) != 0) {
			fprintf(stderr, "produceJobId: error creating jobid\n");
			return(-1);
		}
		if((final_jobid=edg_wlc_JobIdUnparse(jobid)) == NULL) {
			fprintf(stderr, "produceJobId: error unparsing jobid\n");
			return(-1);
		}
		glite_jobid_free(jobid);
	} while(0);

	/* generate jobids[0..njobs-1, 0..nsubjobs] */
	jobids = calloc(njobs*(nsubjobs + 1), sizeof(char*));
	if(jobids == NULL) {
		fprintf(stderr, "glite_wll_perftest_init: not enough memory for job id's\n");
		return(-1);
	}
        while (--n >= 0) {
		glite_jobid_t jobid;
		glite_jobid_t *subjobid;
		int i;

		if(glite_wll_perftest_createJobId(dest_host,
						  dest_port,
						  test_user,
						  test_name,
						  n,
						  &jobid) != 0) {
			fprintf(stderr, "produceJobId: error creating jobid\n");
			return(-1);
		}
		if((jobids[n*(nsubjobs+1)]=edg_wlc_JobIdUnparse(jobid)) == NULL) {
			fprintf(stderr, "produceJobId: error unparsing jobid\n");
			return(-1);
		}

		/* generate subjob ids */
		if(nsubjobs > 0) {
			if(edg_wll_GenerateSubjobIds(ctx, jobid, nsubjobs, test_name,
						     &subjobid) < 0) {
				fprintf(stderr, "produceJobId: error generating subjob ids\n");
				return -1;
			}
		}
		for(i = 1; i <= nsubjobs; i++) {
			if((jobids[n*(nsubjobs+1) + i] = edg_wlc_JobIdUnparse(subjobid[i-1])) == NULL) {
				fprintf(stderr, "produceJobId: error unparsing jobid\n");
				return(-1);
			}
			glite_jobid_free(subjobid[i-1]);
		}
		glite_jobid_free(jobid);
	}

			
	return(0);
}
Exemple #27
0
void
ScreenManager::display()
{
  show_software_cursor(globals::software_cursor);
  
  Uint32 last_ticks = SDL_GetTicks();
  float previous_frame_time;
  std::vector<Input::Event> events;

  while (!screens.empty())
  {
    events.clear();
    Uint32 dt;
      
    // Get time and update Input::Events
    if (playback_input)
    {
      // Get Time
      read(std::cin, previous_frame_time);

      // Update InputManager so that SDL_QUIT and stuff can be
      // handled, even if the basic events are taken from record
      input_manager.update(previous_frame_time);
      input_controller->clear_events();
      read_events(std::cin, events);

      //Ceu SDL_DT
      dt = previous_frame_time*1000;
      int dt_us = 1000*dt;
      ceu_sys_go(&CEUapp, CEU_IN__WCLOCK, &dt_us);
      ceu_sys_go(&CEUapp, CEU_IN_SDL_DT, &dt);
    }
    else
    {
      // Get Time
      Uint32 ticks = SDL_GetTicks();
      previous_frame_time  = float(ticks - last_ticks)/1000.0f;
      dt = ticks - last_ticks;
      last_ticks = ticks;

      // Update InputManager and get Events
      input_manager.update(previous_frame_time);
      input_controller->poll_events(events);

      //Ceu SDL_DT
      int dt_us = 1000*dt;
      ceu_sys_go(&CEUapp, CEU_IN__WCLOCK, &dt_us);
      ceu_sys_go(&CEUapp, CEU_IN_SDL_DT, &dt);
    }
      
    if (record_input)
    {
      write(std::cerr, previous_frame_time);
      write_events(std::cerr, events);
    }

    if (globals::software_cursor)
      cursor.update(previous_frame_time);

    // previous frame took more than one second
    if (previous_frame_time > 1.0)
    {
      ///if (globals::developer_mode)
        log_warn("ScreenManager: previous frame took longer than 1 second (%1% sec.), ignoring and doing frameskip", previous_frame_time);
    }
    else
    {  
      update(previous_frame_time, events);
      
      // cap the framerate at the desired value
      // figure out how long this frame took
      float current_frame_time = float(SDL_GetTicks() - last_ticks) / 1000.0f;
      // idly delay if this frame didn't last long enough to
      // achieve <desired_fps> frames per second
      if (current_frame_time < 1.0f / globals::desired_fps) {
        Uint32 sleep_time = static_cast<Uint32>(1000 *((1.0f / globals::desired_fps) - current_frame_time));
        SDL_Delay(sleep_time);
      }
    }
  }
}
Exemple #28
0
/**
 * Each substructure in the M2 has a variable size except the header.
 * Memory for each substructure must therefore be allocated at reading depending on header values.
 * @param lk_m2_file The file to read data.
 * @param ptr Pointer to a M2/WotLK structure.
 */
int read_model(FILE *lk_m2_file, LKM2 *ptr) {
	//Header
	fseek(lk_m2_file, 0, SEEK_SET);
	fread(&ptr->header, sizeof(LKModelHeader), 1, lk_m2_file);
	char real_id[5];
	real_id[0] = ptr->header.id[0];
	real_id[1] = ptr->header.id[1];
	real_id[2] = ptr->header.id[2];
	real_id[3] = ptr->header.id[3];
	real_id[4] = '\0';
	if (strcmp("MD20", real_id)) {
		fprintf(stderr, "This is not an M2 file.\n");
		exit(EXIT_FAILURE);
	}
	if (ptr->header.version != 264) {
		fprintf(stderr, "Incorrect model version (%d).\n", ptr->header.version);
		fprintf(stderr, "A WotLK model (264) is expected.\n");
		exit(EXIT_FAILURE);
	}

	//Name
	ptr->filename = malloc(ptr->header.nameLength);
	fseek(lk_m2_file, ptr->header.nameOfs, SEEK_SET);
	fread(ptr->filename, sizeof(char), ptr->header.nameLength, lk_m2_file);

	//Global Sequences
	ptr->globalsequences = malloc(
			ptr->header.nGlobalSequences * sizeof(unsigned int));
	if (ptr->header.nGlobalSequences > 0) {
		fseek(lk_m2_file, ptr->header.ofsGlobalSequences, SEEK_SET);
		fread(ptr->globalsequences, sizeof(unsigned int),
				ptr->header.nGlobalSequences, lk_m2_file);
	}

	//Animations
	ptr->animations = malloc(
			ptr->header.nAnimations * sizeof(LKModelAnimation));
	fseek(lk_m2_file, ptr->header.ofsAnimations, SEEK_SET);
	fread(ptr->animations, sizeof(LKModelAnimation), ptr->header.nAnimations,
			lk_m2_file);

	//Animation Files
	FILE **anim_files;
	anim_files = malloc(ptr->header.nAnimations * sizeof(FILE *));
	int i;
	for (i = 0; i < ptr->header.nAnimations; i++) {
		if (((ptr->animations[i].flags & 0x40) == 0)
				&& ((ptr->animations[i].flags & 0x130) == 0)) { //If anim[i] is not an alias and is not stored in the model
			printf("\t%s\n",
					animfile_name(model_name, ptr->animations[i].animID,
							ptr->animations[i].subAnimID));
			anim_files[i] = (FILE *) fcaseopen(
					animfile_name(model_name, ptr->animations[i].animID,
							ptr->animations[i].subAnimID), "r+b");
			if (anim_files[i] == NULL) {
				fprintf(stderr, KRED "[Error] " RESET
				"[Anim #%d, ID%d, Flags %d] %s file not found.\n", i,
						ptr->animations[i].animID, ptr->animations[i].flags,
						animfile_name(model_name, ptr->animations[i].animID,
								ptr->animations[i].subAnimID));
				fprintf(stderr, "[aliasNext %d]\n", ptr->animations[i].Index);
				exit(EXIT_FAILURE);
			}
		}
	}

	//Animations Lookup Table
	ptr->AnimLookup = malloc(ptr->header.nAnimationLookup * sizeof(short));
	fseek(lk_m2_file, ptr->header.ofsAnimationLookup, SEEK_SET);
	fread(ptr->AnimLookup, sizeof(short), ptr->header.nAnimationLookup,
			lk_m2_file);

	//Bones
	read_bones(lk_m2_file, ptr, anim_files);

	//Skeleton Bone Lookup
	ptr->keybonelookup = malloc(ptr->header.nKeyBoneLookup * sizeof(short));
	fseek(lk_m2_file, ptr->header.ofsKeyBoneLookup, SEEK_SET);
	fread(ptr->keybonelookup, sizeof(short), ptr->header.nKeyBoneLookup,
			lk_m2_file);

	//Vertices
	ptr->vertices = malloc(ptr->header.nVertices * sizeof(ModelVertex));
	fseek(lk_m2_file, ptr->header.ofsVertices, SEEK_SET);
	fread(ptr->vertices, sizeof(ModelVertex), ptr->header.nVertices,
			lk_m2_file);

	//Colors
	read_colors(lk_m2_file, ptr, anim_files);

	//Textures Definition
	if (ptr->header.nTextures > 0) {
		ptr->textures_def = malloc(
				ptr->header.nTextures * sizeof(ModelTextureDef));
		fseek(lk_m2_file, ptr->header.ofsTextures, SEEK_SET);
		fread(ptr->textures_def, sizeof(ModelTextureDef), ptr->header.nTextures,
				lk_m2_file);
		//textures names
		ptr->texture_names = malloc(ptr->header.nTextures * sizeof(char *));
		int i;
		for (i = 0; i < ptr->header.nTextures; i++) {
			if (ptr->textures_def[i].type == 0) { //Filename is referenced in the m2 only when the type is 0
				if (ptr->textures_def[i].nameLen >= 256) {
					fprintf(stderr,
							"nameLen too large : %d\nPlease report this issue.",
							ptr->textures_def[i].nameLen);
					return -1;
				}
				ptr->texture_names[i] = malloc(ptr->textures_def[i].nameLen);
				fseek(lk_m2_file, ptr->textures_def[i].nameOfs,
				SEEK_SET);
				fread(ptr->texture_names[i], sizeof(char),
						ptr->textures_def[i].nameLen, lk_m2_file);
			}
		}
	}

	//Transparency
	read_transparency(lk_m2_file, ptr, anim_files);

	//TexReplace
	ptr->TexReplace = malloc(ptr->header.nTexReplace * sizeof(short));
	fseek(lk_m2_file, ptr->header.ofsTexReplace, SEEK_SET);
	fread(ptr->TexReplace, sizeof(short), ptr->header.nTexReplace, lk_m2_file);

	//Render Flags
	ptr->renderflags = malloc(ptr->header.nRenderFlags * sizeof(int));
	fseek(lk_m2_file, ptr->header.ofsRenderFlags, SEEK_SET);
	fread(ptr->renderflags, sizeof(int), ptr->header.nRenderFlags, lk_m2_file);

	//Bone Lookup Table
	ptr->BoneLookupTable = malloc(ptr->header.nBoneLookupTable * sizeof(int16));
	fseek(lk_m2_file, ptr->header.ofsBoneLookupTable, SEEK_SET);
	fread(ptr->BoneLookupTable, sizeof(int16), ptr->header.nBoneLookupTable,
			lk_m2_file);

	//Texture Lookup Table
	ptr->TexLookupTable = malloc(ptr->header.nTexLookup * sizeof(short));
	fseek(lk_m2_file, ptr->header.ofsTexLookup, SEEK_SET);
	fread(ptr->TexLookupTable, sizeof(short), ptr->header.nTexLookup,
			lk_m2_file);

	//TexUnit
	ptr->TexUnit = malloc(ptr->header.nTexUnitLookup * sizeof(short));
	fseek(lk_m2_file, ptr->header.ofsTexUnitLookup, SEEK_SET);
	fread(ptr->TexUnit, sizeof(short), ptr->header.nTexUnitLookup, lk_m2_file);

	//TransLookup
	ptr->TransparencyLookup = malloc(
			ptr->header.nTransparencyLookup * sizeof(short));
	fseek(lk_m2_file, ptr->header.ofsTransparencyLookup, SEEK_SET);
	fread(ptr->TransparencyLookup, sizeof(short),
			ptr->header.nTransparencyLookup, lk_m2_file);

	//TexAnimLookup
	ptr->TexAnimLookup = malloc(ptr->header.nTexAnimLookup * sizeof(short));
	fseek(lk_m2_file, ptr->header.ofsTexAnimLookup, SEEK_SET);
	fread(ptr->TexAnimLookup, sizeof(short), ptr->header.nTexAnimLookup,
			lk_m2_file);

	//BoundingTriangles
	ptr->BoundingTriangles = malloc(
			ptr->header.nBoundingTriangles / 3 * sizeof(Triangle));
	fseek(lk_m2_file, ptr->header.ofsBoundingTriangles, SEEK_SET);
	fread(ptr->BoundingTriangles, sizeof(Triangle),
			ptr->header.nBoundingTriangles / 3, lk_m2_file);

	//BoundingVertices
	ptr->BoundingVertices = malloc(
			ptr->header.nBoundingVertices * sizeof(Vec3D));
	fseek(lk_m2_file, ptr->header.ofsBoundingVertices, SEEK_SET);
	fread(ptr->BoundingVertices, sizeof(Vec3D), ptr->header.nBoundingVertices,
			lk_m2_file);

	//BoundingNormals
	ptr->BoundingNormals = malloc(ptr->header.nBoundingNormals * sizeof(Vec3D));
	fseek(lk_m2_file, ptr->header.ofsBoundingNormals, SEEK_SET);
	fread(ptr->BoundingNormals, sizeof(Vec3D), ptr->header.nBoundingNormals,
			lk_m2_file);

	//Attachments
	read_attachments(lk_m2_file, ptr, anim_files);

	//Attachment Lookup Table
	ptr->AttachLookup = malloc(ptr->header.nAttachLookup * sizeof(short));
	fseek(lk_m2_file, ptr->header.ofsAttachLookup, SEEK_SET);
	fread(ptr->AttachLookup, sizeof(short), ptr->header.nAttachLookup,
			lk_m2_file);

	//Events
	read_events(lk_m2_file, ptr);

	//Lights
	read_lights(lk_m2_file, ptr, anim_files);

	//Cameras
	read_cameras(lk_m2_file, ptr, anim_files);

	//Cameras Lookup
	ptr->CameraLookup = malloc(ptr->header.nCameraLookup * sizeof(short));
	fseek(lk_m2_file, ptr->header.ofsCameraLookup, SEEK_SET);
	fread(ptr->CameraLookup, sizeof(short), ptr->header.nCameraLookup,
			lk_m2_file);

	//TexAnims
	read_texanims(lk_m2_file, ptr, anim_files);
	/*TODO
	 Ribbons;
	 Particles
	 */
	return 0;
}