Esempio n. 1
0
	void DispatcherPrivate::run_steps()
	{
		int now = _wall.read_us();
		TRACE(("run_steps(): starting, now=%i.\r\n", now));

		clear_signals();
		clear_normal_step();
		run_tasks(StateCommited);
#ifdef DISPATCH_DEBUG
		int tick_before = get_tick();
#endif

		// no commited nodes left, see if we have enough time for a normal loop
		for(;;)
		{
			int tdiff = wall_diff(now);
			if(tdiff >= _clock_multiplier)
				break;

			run_tasks(StateNormal | StateUrgent);
	
			DelayedThread::signal_wait(SIGNAL_CHANGED, (_clock_multiplier - tdiff) / 1000);
		}

		run_tasks(StateUrgent);

		TRACE(("Dispatcher wait end (diff=%i, tdiff=%i).\r\n", wall_diff(now), get_tick() - tick_before));
	}
Esempio n. 2
0
void seqplay::clear(double i_timeLimit)
{
	tick_t t1 = get_tick();
	while (!isEmpty()){
		if (i_timeLimit > 0 
			&& tick2sec(get_tick()-t1)>=i_timeLimit) break;
		pop_back();
	}
}
Esempio n. 3
0
unsigned t_delay_tick(unsigned count)
{
    unsigned base=get_tick(0);
    if(readl(P_AO_RTI_PWR_CNTL_REG0)&(1<<8)){
        while(get_tick(base)<count);
    }else{
        while(get_tick(base)<count*100);
    }
    return 0;
}
Esempio n. 4
0
void bti_test(node *a, size_t n)
    {
    int i;
    int r;
    long t1, t2;
    t1 = get_tick();
    r = random(30000);
    for (i = 0; i < LOOP; i++)
        bti_search(r, a, &n);
    t2 = get_tick();
    printf("\n lv_search %d loops ellapse %ld ticks.", LOOP, diff_tick(t1,t2));
    }
Esempio n. 5
0
void li_test(int a[], int n)
    {
    int i;
    long t1, t2;
    t1 = get_tick();
    for (i = 0; i < LOOP; i++) bi_search(random(30000), a, n);
    t2 = get_tick();
    printf("\n li_search %d loops ellapse %ld ticks.", LOOP, diff_tick(t1,t2));
    t1 = get_tick();
    for (i = 0; i < LOOP; i++) bii_search(random(30000), a, n);
    t2 = get_tick();
    printf("\n lfi_search %d loops ellapse %ld ticks.", LOOP, diff_tick(t1,t2));
    }
Esempio n. 6
0
long sort_testnm(int n, int m, void (*sort_func)(int*, int))
    {
    long t1, t2, t;
    int *a;
    a = set_array(a, n, m);
    t1 = get_tick();
    sort_func(a, n);
    t2 = get_tick();
    t = diff_tick(t1, t2);
    if (!is_sorted(a, n))
	t = -1;
    free(a);
    return t;
    }
Esempio n. 7
0
static void gear_up(void) {
	printf("SHIFT UP\n");
	IGNITION_CUT();
	gear(UP);

	uint32_t timer = get_tick() + 500;

	while(1) {
		if (get_tick() > timer) {
			gear(STOP);
			IGNITION_UNCUT();
			gear(DOWN);
			_delay_ms(100);
			gear(STOP);
			printf("DIDN'T REACH END\n");
			return;
		}

		if (can_has_data()) {
			struct can_message message;
			read_message(&message);
			if ((message.id == GEAR_STOP_BUTTON) && (message.data[0] == 2)) {
				gear(STOP);
				IGNITION_UNCUT();
				_delay_ms(50);
				gear(DOWN);

				uint32_t timer2 = get_tick() + 200;
				while(1) {
					if (get_tick() > timer2) {
						gear(STOP);
						printf("FAILED TO RELEASE AFTER SHIFT\n");
						return;
					}

					if (can_has_data()) {
						struct can_message message;
						read_message(&message);
						if ((message.id == GEAR_STOP_BUTTON) && (message.data[0] == 0)) {
							_delay_ms(100);
							gear(STOP);
							printf("PERFECT GEARSHIFT\n");
							return;
						}
					}
				}
			}
		}
	}
}
Esempio n. 8
0
void lv_test(int a[], int n)
    {
    int i;
    int r;
    long t1, t2;
    t1 = get_tick();
    r = random(30000);
    for (i = 0; i < LOOP; i++) lv_search(&r, a, &n, sizeof(int), intcmp);
    t2 = get_tick();
    printf("\n lv_search %d loops ellapse %ld ticks.", LOOP, diff_tick(t1,t2));
    t1 = get_tick();
    r = random(30000);
    for (i = 0; i < LOOP; i++) lfv_search(&r, a, &n, sizeof(int), intcmp);
    t2 = get_tick();
    printf("\n lfv_search %d loops ellapse %ld ticks.", LOOP, diff_tick(t1,t2));
    }
CORBA::Boolean OpenHRP_PathPlannerSVC_impl::calcPath()
{
    std::cout << "OpenHRP_PathPlannerSVC_impl::calcPath()" << std::endl;
    tick_t t1 = get_tick(); 
    bool status = path_->calcPath();
    std::cout << "OpenHRP_PathPlannerSVC_impl::fin." << std::endl;
    std::cout << "total computation time = " << tick2sec(get_tick()-t1) << "[s]" 
              << std::endl;
    std::cout << "computation time for collision check = " 
              << path_->timeCollisionCheck() << "[s]" << std::endl;
    std::cout << "computation time for forward kinematics = " 
              << path_->timeForwardKinematics() << "[s]" << std::endl;
    std::cout << "collision check function was called " 
              << path_->countCollisionCheck() << " times" << std::endl;
    return status;
}
Esempio n. 10
0
void IOLoop::loop() {
    for(;;) {
        m_activeEventList.clear();
        int ret = m_poller->processEvent(&m_activeEventList);
        //LOG_STDOUT("Loop: Start run EventHandler");
        for(auto it = m_activeEventList.begin(); it != m_activeEventList.end(); it++) {
            IOEvent* ev = *it;
            ev->handleEvent((void*)&ret);
        }
        TimeEventList_t timeObj;
        timeObj.swap(m_timeEventList);
        uint64_t now = get_tick();
        for (TimeItem_t* it : timeObj) {
            if (now >= it->next_tick) {
                it->callback((void*)&now);
                delete it;
            }
            else {
                m_timeEventList.push_back(it);
            }
        }
        PostEventList_t postFunList;
        postFunList.swap(m_postEventList);
        //LOG_STDOUT("Loop: Start run FuncHandler");
        for (Function_t& it : postFunList){
            it(NULL);
        }
    }
}
Esempio n. 11
0
 dword tick_diff(Tick pre_tick)
 {
     Tick tick_now = get_tick();
     
     dword ms = (dword)((tick_now - pre_tick) * 1000 / GetTickFrequency());
     return ms;
 }
Esempio n. 12
0
TimeItem_t* IOLoop::add_timer(uint64_t timeout, const Function_t& callback) {
    TimeItem_t* pTime = new TimeItem_t;
    pTime->callback = callback;
    pTime->timeout = timeout;
    pTime->next_tick = get_tick() + timeout;
    m_timeEventList.push_back(pTime);
    return pTime;
}
Esempio n. 13
0
static void * threadProc(void * parm)
{
    struct timeval tv;
    int sleepAmount = 1000000 / THREAD_QUEUE_INTERVAL;
    unsigned int sequenceTime;

    // prime the pump
    threadTimer = get_tick();
    threadQueueTimer = threadTimer + threadQueueTicks;
    while (threadTimer < threadQueueTimer) {
        if (threadService) {
            threadService();
        }
        threadTimer++;
    }
    
    while (!threadQuit) {
        tv.tv_sec = 0;
        tv.tv_usec = sleepAmount;

        select(0, NULL, NULL, NULL, &tv);

        sequenceTime = get_tick();

        sleepAmount = 1000000 / THREAD_QUEUE_INTERVAL;
        if ((int)(threadTimer - sequenceTime) > threadQueueTicks) {
            // we're running ahead, so sleep for half the usual
            // amount and try again
            sleepAmount /= 2;
            continue;
        }

        threadQueueTimer = sequenceTime + threadQueueTicks;
        while (threadTimer < threadQueueTimer) {
            if (threadService) {
                threadService();
            }
            threadTimer++;
        }
    }

    return NULL;
}
Esempio n. 14
0
    uint32 tick_diff(Tick old_tick)
    {
        Tick tick_now = get_tick();

#ifdef WIN32
        uint32 ms = (uint32)((tick_now - old_tick) * 1000 / GetTickFrequency());
#else
        uint32 ms = (tick_now - old_tick) / 1000000;
#endif

        return ms;
    }
Esempio n. 15
0
int main(int argc, char *argv[])
{
#ifdef CONFIG_TIMER_SUPPORT
	volatile __u32 count;

#if 1
	for (count = 0; count < 10000; count++)
		printf("%s(): %d\n", __func__, get_tick());
#else
	volatile __u32 m = get_tick() + 10;

	do {
		count = get_tick();
		if (count & 1)
			printf("%d, %d\n", count, m);
	} while (count < m);
#endif
#else
	printf("Timer not support on this platform!\n");
#endif

	return 0;
}
Esempio n. 16
0
int main(void) {
	init();

	while (1) {
		static uint32_t timers[1] = {0};
		uint32_t tick = get_tick();

		if (tick > timers[0]) {
			uint8_t node_id = 2;
			can_broadcast(HEARTBEAT, &node_id);
			timers[0] += 30;
		}
	}

	return 0;
}
Esempio n. 17
0
void	write_incantation(t_zappy *s, t_clientIA *client)
{
  char		*str;

  if (FD_ISSET(client->socket, &(s->writesd)))
    {
      while ((str = try_get_cmd(client->buff_write)))
	{
	  send_buffer(client, str);
	  free(str);
	}
    }
  if (((client->lastAction < get_tick(0.0f))))
    {
      are_requirements_met(s, client, false);
      client->call_incantation = false;
    }
}
Esempio n. 18
0
void HttpServer::onRead(const StreamPtr_t& stream, Buffer* buf) {
    HttpParserObj* obj = HttpParserObj::GetInstance();
    obj->parseBuffer(buf->buffer(), buf->offset());
    m_read_time = get_tick();
//    LOG_STDOUT("OnRequest: %s", buf);
    
    if (obj->ready()) {
        LOG_STDOUT("Url: %s", obj->url().c_str());
        buf->read(NULL, obj->length());
        
//        HttpResponse res;
//        res.setHttp404Status();
//        HttpServer::addResponseList(stream->fd(), res);

        HttpTask* tsk = new HttpTask(stream->fd(),obj->method(), obj->url());
        tsk->setHttpCallback(m_httpCallback);
//      线程池中会delete
        g_httpThreadPool.addTask(tsk);
    }
}
Esempio n. 19
0
int main ( int argc, char *argv[])
{
   float sigma, rcut, dt, eqtemp, dens, boxlx, boxly, boxlz, sfx, sfy, sfz, sr6, vrcut, dvrcut, dvrc12, freex; 
   int nstep, nequil, iscale, nc, mx, my, mz, iprint;
   float *rx, *ry, *rz, *vx, *vy, *vz, *fx, *fy, *fz, *potentialPointer, *virialPointer, *virialArray, *potentialArray, *virialArrayTemp, *potentialArrayTemp;
   float ace, acv, ack, acp, acesq, acvsq, acksq, acpsq, vg, kg, wg;
   int   *head, *list;
   int   natoms=0;
   int ierror;
   int jstart, step, itemp;
   float potential, virial, kinetic;
   float tmpx;
   int i, icell;
   cl_int err;

   cl_device_id device;
   cl_context context;
   cl_command_queue queue;
   cl_program program;
   cl_kernel force_kernel;
   cl_kernel add_kernel;

   cl_mem d_rx, d_ry, d_rz, d_fx, d_fy, d_fz, d_head, d_list, d_potential, d_virial, d_virialArray, d_potentialArray;

   ierror = input_parameters (&sigma, &rcut, &dt, &eqtemp, &dens, &boxlx, &boxly, &boxlz, &sfx, &sfy, &sfz, &sr6, &vrcut, &dvrcut, &dvrc12, &freex, &nstep, &nequil, &iscale, &nc, &natoms, &mx, &my, &mz, &iprint);
   //printf ("\nReturned from input_parameters, natoms = %d\n", natoms);
   device = create_device();
   context = clCreateContext(NULL, 1, &device, NULL, NULL, &err);
   if(err < 0) {
     perror("Couldn't create a context");
     exit(1);   
   }
   /* Build the program */
   program = build_program(context, device, PROGRAM_FILE);
   force_kernel = clCreateKernel(program, FORCE_KERNEL, &err);
   if(err < 0) {
     perror("Couldn't create a kernel");
     exit(1);
   }
   //printf("\nmx = %d, my = %d, mz = %d\n",mx,my,mz);
   rx = (float *)malloc(2*natoms*sizeof(float));
   ry = (float *)malloc(2*natoms*sizeof(float));
   rz = (float *)malloc(2*natoms*sizeof(float));
   vx = (float *)malloc(natoms*sizeof(float));
   vy = (float *)malloc(natoms*sizeof(float));
   vz = (float *)malloc(natoms*sizeof(float));
   fx = (float *)malloc(natoms*sizeof(float));
   fy = (float *)malloc(natoms*sizeof(float));
   fz = (float *)malloc(natoms*sizeof(float));
   list = (int *)malloc(2*natoms*sizeof(int));
   head= (int *)malloc((mx+2)*(my+2)*(mz+2)*sizeof(int));
   virialPointer = (float *)malloc(sizeof(float));
   potentialPointer = (float *)malloc(sizeof(float));
   int index = 0;

   int numBlocks = ceil(natoms/(float)BLOCK_WIDTH);
   virialArray = (float *)malloc( (numBlocks)* sizeof(float));
   potentialArray = (float *)malloc((numBlocks) * sizeof(float));
   virialArrayTemp = (float *)malloc(numBlocks * sizeof(float));
   potentialArrayTemp = (float *)malloc(numBlocks * sizeof(float));
   for (index = 0; index < numBlocks; index++)
   {
      virialArray[index] = (float)0;
      potentialArray[index] = (float)0;
   }
  // printf ("\nFinished allocating memory\n");

   initialise_particles (rx, ry, rz, vx, vy, vz, nc);
 //  printf ("\nReturned from initialise_particles\n");

   loop_initialise(&ace, &acv, &ack, &acp, &acesq, &acvsq, &acksq, &acpsq, sigma, rcut, dt);
//   printf ("\nReturned from loop_initialise\n");

//   output_particles(rx,ry,rz,vx,vy,vz,fx,fy,fz,0);
      movout (rx, ry, rz, vx, vy, vz, sfx, sfy, sfz, head, list, mx, my, mz, natoms);
 //  printf ("\nReturned from movout\n");
   //   check_cells(rx, ry, rz, head, list, mx, my, mz, natoms,0,0);
   *potentialPointer = (float)0;
   *virialPointer = (float)0;
   d_rx = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float) * natoms * 2, rx, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_ry = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float) * natoms * 2, ry, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_rz = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float) * natoms * 2, rz, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_fx = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float) * natoms, fx, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_fy = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float) * natoms, fy, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_fz = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float) * natoms, fz, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_head = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, (mx+2)*(my+2)*(mz+2)*sizeof(int), head, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_list = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, 2*natoms*sizeof(int), list, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_virialArray = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,  sizeof(float) * (numBlocks), virialArray, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_potentialArray = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,  sizeof(float) * (numBlocks), potentialArray, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }

    
   err = clSetKernelArg(force_kernel, 0, sizeof(cl_mem), &d_virialArray);
   err |= clSetKernelArg(force_kernel, 1, sizeof(cl_mem), &d_potentialArray);
   err |= clSetKernelArg(force_kernel, 2, sizeof(cl_mem), &d_rx);
   err |= clSetKernelArg(force_kernel, 3, sizeof(cl_mem), &d_ry);
   err |= clSetKernelArg(force_kernel, 4, sizeof(cl_mem), &d_rz);
   err |= clSetKernelArg(force_kernel, 5, sizeof(cl_mem), &d_fx);
   err |= clSetKernelArg(force_kernel, 6, sizeof(cl_mem), &d_fy);
   err |= clSetKernelArg(force_kernel, 7, sizeof(cl_mem), &d_fz);
   err |= clSetKernelArg(force_kernel, 8, sizeof(sigma), &sigma);
   err |= clSetKernelArg(force_kernel, 9, sizeof(rcut), &rcut);
   err |= clSetKernelArg(force_kernel, 10, sizeof(vrcut), &vrcut);
   err |= clSetKernelArg(force_kernel, 11, sizeof(dvrc12), &dvrc12);
   err |= clSetKernelArg(force_kernel, 12, sizeof(dvrcut), &dvrcut);
   err |= clSetKernelArg(force_kernel, 13, sizeof(cl_mem), &d_head);
   err |= clSetKernelArg(force_kernel, 14, sizeof(cl_mem), &d_list);
   err |= clSetKernelArg(force_kernel, 15, sizeof(mx), &mx);
   err |= clSetKernelArg(force_kernel, 16, sizeof(my), &my);
   err |= clSetKernelArg(force_kernel, 17, sizeof(mz), &mz);
   err |= clSetKernelArg(force_kernel, 18, sizeof(natoms), &natoms);
   err |= clSetKernelArg(force_kernel, 19, sizeof(sfx), &sfx);
   err |= clSetKernelArg(force_kernel, 20, sizeof(sfy), &sfy);
   err |= clSetKernelArg(force_kernel, 21, sizeof(sfz), &sfz);
   if(err < 0) {
     printf("Couldn't set an argument for the transpose kernel");
     exit(1);   
   }
   //size_t max_size;
   //clGetKernelWorkGroupInfo(add_kernel, device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_size), &max_size, NULL);
   //printf("\nMAX SIZE: %d\n", max_size);
   
   queue = clCreateCommandQueue(context, device, 0, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }
   size_t global_size[1];
   size_t local_size[1];
   global_size[0] = BLOCK_WIDTH * ceil(natoms / (float) BLOCK_WIDTH);
   local_size[0] = BLOCK_WIDTH;
   long double elapsedTime = (float)0.0;
   long unsigned int startTime;
   long unsigned int endTime;
   

   startTime = get_tick();
   err = clEnqueueNDRangeKernel(queue, force_kernel, 1, NULL, global_size, local_size, 0, NULL, NULL);
   clFinish(queue);
   endTime = get_tick();
   if(err < 0) {
     printf("Couldn't enqueue force kernel\n");
     printf("%d\n", err);
     printf("CL_INVALID_PROGRAM_EXECUTABLE: %d\n", CL_INVALID_PROGRAM_EXECUTABLE);
     printf("CL_INVALID_COMMAND_QUEUE: %d\n",CL_INVALID_COMMAND_QUEUE );
     printf("CL_INVALID_KERNEL: %d\n", CL_INVALID_KERNEL);
     printf("CL_INVALID_CONTEXT: %d\n", CL_INVALID_CONTEXT);
     printf("CL_INVALID_KERNEL_ARGS: %d\n", CL_INVALID_KERNEL_ARGS);
     printf("CL_INVALID_WORK_DIMENSION: %d\n", CL_INVALID_WORK_DIMENSION);
     printf("CL_INVALID_GLOBAL_WORK_SIZE: %d\n", CL_INVALID_GLOBAL_WORK_SIZE);
     printf("CL_INVALID_GLOBAL_OFFSET: %d\n", CL_INVALID_GLOBAL_OFFSET);
     printf("CL_INVALID_WORK_GROUP_SIZE: %d\n", CL_INVALID_WORK_GROUP_SIZE);
     exit(1);   
   }
   elapsedTime += endTime - startTime;
   err = clEnqueueReadBuffer(queue, d_fx, CL_TRUE, 0, sizeof(float) * natoms, fx, 0, NULL, NULL);
   err |= clEnqueueReadBuffer(queue, d_fy, CL_TRUE, 0, sizeof(float) * natoms, fy, 0, NULL, NULL);
   err |= clEnqueueReadBuffer(queue, d_fz, CL_TRUE, 0, sizeof(float) * natoms, fz, 0, NULL, NULL);
   err |= clEnqueueReadBuffer(queue, d_virialArray, CL_TRUE, 0, sizeof(float) * numBlocks, virialArrayTemp, 0, NULL, NULL);
   err |= clEnqueueReadBuffer(queue, d_potentialArray, CL_TRUE, 0, sizeof(float) * numBlocks, potentialArrayTemp, 0, NULL, NULL);
   if(err < 0) {
     printf("Couldn't read fx buffer\n");
     printf("%d\n",err );
     printf("CL_INVALID_COMMAND_QUEUE: %d\n",CL_INVALID_COMMAND_QUEUE);
     printf("CL_INVALID_CONTEXT: %d\n", CL_INVALID_CONTEXT);
     printf("CL_INVALID_MEM_OBJECT: %d\n", CL_INVALID_MEM_OBJECT);
     printf("CL_INVALID_VALUE: %d\n",CL_INVALID_VALUE);
     printf("CL_INVALID_EVENT_WAIT_LIST: %d\n", CL_INVALID_EVENT_WAIT_LIST);
     printf("CL_MEM_OBJECT_ALLOCATION_FAILURE: %d\n",CL_MEM_OBJECT_ALLOCATION_FAILURE);
     printf("CL_OUT_OF_HOST_MEMORY: %d\n", CL_OUT_OF_HOST_MEMORY);
     exit(1);   
   }
   clFinish(queue);
   virial = 0.0;
   potential = 0.0;
   int tempInd = 0;
   for (tempInd =0; tempInd < numBlocks; tempInd++)
   {
      potential += potentialArrayTemp[tempInd];
      virial += virialArrayTemp[tempInd];
   }
   virial *= 48.0/3.0;
   potential *= 4.0;

  // printf ("\nReturned from force: potential = %f, virial = %f, kinetic = %f\n",potential, virial, kinetic);
//   output_particles(rx,ry,rz,vx,vy,vz,fx,fy,fz,0);


   for(step=1;step<=nstep;step++){
     // if(step>=85)printf ("\nStarted step %d\n",step);
      movea (rx, ry, rz, vx, vy, vz, fx, fy, fz, dt, natoms);
//      check_cells(rx, ry, rz, head, list, mx, my, mz, natoms,step,step);
    //  if(step>85)printf ("\nReturned from movea\n");
      movout (rx, ry, rz, vx, vy, vz, sfx, sfy, sfz, head, list, mx, my, mz, natoms);
   //  if(step>85) printf ("\nReturned from movout\n");
  //    check_cells(rx, ry, rz, head, list, mx, my, mz, natoms,step,step);
      clReleaseMemObject(d_rx);
      clReleaseMemObject(d_ry);
      clReleaseMemObject(d_rz);
      clReleaseMemObject(d_fx);
      clReleaseMemObject(d_fy);
      clReleaseMemObject(d_fz);
      clReleaseMemObject(d_head);
      clReleaseMemObject(d_list);
      clReleaseMemObject(d_virialArray);
      clReleaseMemObject(d_potentialArray);
   d_rx = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float) * natoms * 2, rx, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_ry = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float) * natoms * 2, ry, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_rz = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float) * natoms * 2, rz, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_fx = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float) * natoms, fx, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_fy = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float) * natoms, fy, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_fz = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float) * natoms, fz, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_head = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, (mx+2)*(my+2)*(mz+2)*sizeof(int), head, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_list = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, 2*natoms*sizeof(int), list, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }    
   d_virialArray = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,  sizeof(float) * (numBlocks), virialArray, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }   
   d_potentialArray = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,  sizeof(float) * (numBlocks), potentialArray, &err);
   if(err < 0) {
     perror("Couldn't create a command queue");
     exit(1);   
   }    
    
   err = clSetKernelArg(force_kernel, 0, sizeof(cl_mem), &d_virialArray);
   err |= clSetKernelArg(force_kernel, 1, sizeof(cl_mem), &d_potentialArray);
   err |= clSetKernelArg(force_kernel, 2, sizeof(cl_mem), &d_rx);
   err |= clSetKernelArg(force_kernel, 3, sizeof(cl_mem), &d_ry);
   err |= clSetKernelArg(force_kernel, 4, sizeof(cl_mem), &d_rz);
   err |= clSetKernelArg(force_kernel, 5, sizeof(cl_mem), &d_fx);
   err |= clSetKernelArg(force_kernel, 6, sizeof(cl_mem), &d_fy);
   err |= clSetKernelArg(force_kernel, 7, sizeof(cl_mem), &d_fz);
   err |= clSetKernelArg(force_kernel, 8, sizeof(sigma), &sigma);
   err |= clSetKernelArg(force_kernel, 9, sizeof(rcut), &rcut);
   err |= clSetKernelArg(force_kernel, 10, sizeof(vrcut), &vrcut);
   err |= clSetKernelArg(force_kernel, 11, sizeof(dvrc12), &dvrc12);
   err |= clSetKernelArg(force_kernel, 12, sizeof(dvrcut), &dvrcut);
   err |= clSetKernelArg(force_kernel, 13, sizeof(cl_mem), &d_head);
   err |= clSetKernelArg(force_kernel, 14, sizeof(cl_mem), &d_list);
   err |= clSetKernelArg(force_kernel, 15, sizeof(mx), &mx);
   err |= clSetKernelArg(force_kernel, 16, sizeof(my), &my);
   err |= clSetKernelArg(force_kernel, 17, sizeof(mz), &mz);
   err |= clSetKernelArg(force_kernel, 18, sizeof(natoms), &natoms);
   err |= clSetKernelArg(force_kernel, 19, sizeof(sfx), &sfx);
   err |= clSetKernelArg(force_kernel, 20, sizeof(sfy), &sfy);
   err |= clSetKernelArg(force_kernel, 21, sizeof(sfz), &sfz);

   if(err < 0) {
     printf("Couldn't set an argument for the transpose kernel");
     exit(1);   
   }


      global_size[0] = BLOCK_WIDTH * ceil(natoms / (float) BLOCK_WIDTH);
      local_size[0] = BLOCK_WIDTH;
      //printf("Global Size: %d\n", global_size[0]);
      //printf("Local Size: %d\n", local_size[0]);
      clFinish(queue);
      startTime = get_tick();
      err = clEnqueueNDRangeKernel(queue, force_kernel, 1, NULL, global_size, local_size, 0, NULL, NULL);
      clFinish(queue);
      endTime = get_tick();
      elapsedTime += endTime - startTime;
      if(err < 0) {
        printf("Couldn't enqueue force kernel\n");
        exit(1);   
      }
      //float fxTest[natoms];
      //size_t sizy = sizeof(float) * (natoms);
      err = clEnqueueReadBuffer(queue, d_fx, CL_TRUE, 0, sizeof(float) * natoms, fx, 0, NULL, NULL);
      err |= clEnqueueReadBuffer(queue, d_fy, CL_TRUE, 0, sizeof(float) * natoms, fy, 0, NULL, NULL);
      err |= clEnqueueReadBuffer(queue, d_fz, CL_TRUE, 0, sizeof(float) * natoms, fz, 0, NULL, NULL);
      err |= clEnqueueReadBuffer(queue, d_virialArray, CL_TRUE, 0, sizeof(float) * numBlocks, virialArrayTemp, 0, NULL, NULL);
      err |= clEnqueueReadBuffer(queue, d_potentialArray, CL_TRUE, 0, sizeof(float) * numBlocks, potentialArrayTemp, 0, NULL, NULL);
      if(err < 0) {
        printf("Couldn't read buffer\n");
        printf("%d\n",err );
        printf("CL_INVALID_COMMAND_QUEUE: %d\n",CL_INVALID_COMMAND_QUEUE);
        printf("CL_INVALID_CONTEXT: %d\n", CL_INVALID_CONTEXT);
        printf("CL_INVALID_MEM_OBJECT: %d\n", CL_INVALID_MEM_OBJECT);
        printf("CL_INVALID_VALUE: %d\n",CL_INVALID_VALUE);
        printf("CL_INVALID_EVENT_WAIT_LIST: %d\n", CL_INVALID_EVENT_WAIT_LIST);
        printf("CL_MEM_OBJECT_ALLOCATION_FAILURE: %d\n",CL_MEM_OBJECT_ALLOCATION_FAILURE);
        printf("CL_OUT_OF_HOST_MEMORY: %d\n", CL_OUT_OF_HOST_MEMORY);
        exit(1);   
      }
      clFinish(queue);
      //numInc = 0;
      //globalThreads = ceil(numBlocks / (float)BLOCK_WIDTH);
     // startTime = get_tick();
      virial = 0.0;
      potential = 0.0;
      int tempInd = 0;
      for (tempInd =0; tempInd < numBlocks; tempInd++)
      {
        potential += potentialArrayTemp[tempInd];
        virial += virialArrayTemp[tempInd];
      }
      virial *= 48.0/3.0;
      potential *= 4.0;

//      if(step>85)printf ("\nReturned from force: potential = %f, virial = %f, kinetic = %f\n",potential, virial, kinetic);
 //     fflush(stdout);
      moveb (&kinetic, vx, vy, vz, fx, fy, fz, dt, natoms);
 //     check_cells(rx, ry, rz, head, list, mx, my, mz, natoms,step,step);
  // if(step>85)   printf ("\nReturned from moveb: potential = %f, virial = %f, kinetic = %f\n",potential, virial, kinetic);
      sum_energies (potential, kinetic, virial, &vg, &wg, &kg);
      hloop (kinetic, step, vg, wg, kg, freex, dens, sigma, eqtemp, &tmpx, &ace, &acv, &ack, &acp, &acesq, &acvsq, &acksq, &acpsq, vx, vy, vz, iscale, iprint, nequil, natoms);

   }

   tidyup (ace, ack, acv, acp, acesq, acksq, acvsq, acpsq, nstep, nequil);
   elapsedTime = elapsedTime / (float) 1000;
   printf("\n%Lf seconds have elapsed\n", elapsedTime);
   
   return 0;
}
Esempio n. 20
0
void shell(char *str) {
	if (!strcmp(str, "exit")) {
			panic("Exit.", __LINE__, __FILE__);
	} else if (!strcmp(str, "test")) {
		testing_shell(str);
		
	} else if (!strcmp(str, "time")) {
		print_time();
		printk("\n");
		
	} else if (!strcmp(str, "tick")) {
		printk("Tick: %d\n", get_tick());
	
	} else if (!strcmp(str, "clock")) {
		printk("WARN: no clock yet");
	} else if (!strcmp(str, "clear")) {
		tty_clear();
		
	} else if (!strcmp(str, "reset-clock")) {
		hours = 0;
		minutes = 0;
		seconds = 0;
		
	} else if (!strcmp(str, "write")) {
		char *to_write = (char*) kmalloc(sizeof(char) * 30);
		size_t len = strlen("\nLet's write this...\n");
		
		memcpy(to_write, "Let's write this...\n\0", len + 1);
		call(1, (uint32_t) to_write, (uint32_t) len, 0, 0, 0);
		
	} else if (!strcmp(str, "tty")) {
		++tty_index;
		if (tty_index == 3) {
			tty_index = 0;
		}
		current_tty = ttys[tty_index];
		printk("\n[SYS] Switched to tty %d.\n", tty_index);

	} else if (!strcmp(str, "reboot")) {
		printk("System will reboot...");
		reboot();
		
	} else if (!strcmp(str, "sys-info")) {
		printk("%s %s (%s) by %s.\nCopyright C 2015 %s.\nAll rights reserved.\n", OS_Name, Version, Relase_Date, Author, Author);
		
	} else if (!strcmp(str, "help")) {
		printk("After kernel boots up, user must enter user name and machine name. Now, a shell has started. Here user can use some commands:\n");
		printk("	-> help -> display this page\n");
		printk("	-> time -> display current time\n");
		printk("	-> tick -> display current tick\n");
		printk("	-> clock -> start a clock that can be stoped when ESC is pressed\n");
		printk("	-> clear -> clear the screen\n");
		printk("	-> reset->clock -> set clock to 0\n");
		printk("	-> sys->info -> prints info about system\n");
		printk("	-> test -> enter into testing shell that allows testing kernel functions\n");
		printk("	-> exit -> close shell\n\n");
	
		printk("Testing shell:\n");
		printk("	Tests avabile in testing shell:\n");
		printk("		-> exit -> close testing shell\n");
		printk("		-> print-stdin -> print all data from standard input\n");
		printk("		-> size -> print sizes of types, of kernel and RAM\n");
		printk("		-> page-fault -> generate page fault\n");
		printk("		-> address -> print addresses of all kernel variables and of some temporary\n");
		printk("		-> alloc -> test kmalloc and kfree\n");
		
	} else {
		printk("Command not found!\n");
	}
}
Esempio n. 21
0
static void acpi_processor_idle(void)
{
    struct acpi_processor_power *power = processor_powers[smp_processor_id()];
    struct acpi_processor_cx *cx = NULL;
    int next_state;
    uint64_t t1, t2 = 0;
    u32 exp = 0, pred = 0;
    u32 irq_traced[4] = { 0 };

    if ( max_cstate > 0 && power && !sched_has_urgent_vcpu() &&
         (next_state = cpuidle_current_governor->select(power)) > 0 )
    {
        cx = &power->states[next_state];
        if ( power->flags.bm_check && acpi_idle_bm_check()
             && cx->type == ACPI_STATE_C3 )
            cx = power->safe_state;
        if ( cx->idx > max_cstate )
            cx = &power->states[max_cstate];
        menu_get_trace_data(&exp, &pred);
    }
    if ( !cx )
    {
        if ( pm_idle_save )
            pm_idle_save();
        else
            safe_halt();
        return;
    }

    cpufreq_dbs_timer_suspend();

    sched_tick_suspend();
    /* sched_tick_suspend() can raise TIMER_SOFTIRQ. Process it now. */
    process_pending_softirqs();

    /*
     * Interrupts must be disabled during bus mastering calculations and
     * for C2/C3 transitions.
     */
    local_irq_disable();

    if ( !cpu_is_haltable(smp_processor_id()) )
    {
        local_irq_enable();
        sched_tick_resume();
        cpufreq_dbs_timer_resume();
        return;
    }

    if ( (cx->type == ACPI_STATE_C3) && errata_c6_eoi_workaround() )
        cx = power->safe_state;

    power->last_state = cx;

    /*
     * Sleep:
     * ------
     * Invoke the current Cx state to put the processor to sleep.
     */
    switch ( cx->type )
    {
    case ACPI_STATE_C1:
    case ACPI_STATE_C2:
        if ( cx->type == ACPI_STATE_C1 || local_apic_timer_c2_ok )
        {
            /* Get start time (ticks) */
            t1 = get_tick();
            /* Trace cpu idle entry */
            TRACE_4D(TRC_PM_IDLE_ENTRY, cx->idx, t1, exp, pred);
            /* Invoke C2 */
            acpi_idle_do_entry(cx);
            /* Get end time (ticks) */
            t2 = get_tick();
            trace_exit_reason(irq_traced);
            /* Trace cpu idle exit */
            TRACE_6D(TRC_PM_IDLE_EXIT, cx->idx, t2,
                     irq_traced[0], irq_traced[1], irq_traced[2], irq_traced[3]);
            /* Update statistics */
            acpi_update_idle_stats(power, cx, ticks_elapsed(t1, t2));
            /* Re-enable interrupts */
            local_irq_enable();
            break;
        }

    case ACPI_STATE_C3:
        /*
         * Before invoking C3, be aware that TSC/APIC timer may be 
         * stopped by H/W. Without carefully handling of TSC/APIC stop issues,
         * deep C state can't work correctly.
         */
        /* preparing APIC stop */
        lapic_timer_off();

        /* Get start time (ticks) */
        t1 = get_tick();
        /* Trace cpu idle entry */
        TRACE_4D(TRC_PM_IDLE_ENTRY, cx->idx, t1, exp, pred);

        /*
         * disable bus master
         * bm_check implies we need ARB_DIS
         * !bm_check implies we need cache flush
         * bm_control implies whether we can do ARB_DIS
         *
         * That leaves a case where bm_check is set and bm_control is
         * not set. In that case we cannot do much, we enter C3
         * without doing anything.
         */
        if ( cx->type != ACPI_STATE_C3 )
            /* nothing to be done here */;
        else if ( power->flags.bm_check && power->flags.bm_control )
        {
            spin_lock(&c3_cpu_status.lock);
            if ( ++c3_cpu_status.count == num_online_cpus() )
            {
                /*
                 * All CPUs are trying to go to C3
                 * Disable bus master arbitration
                 */
                acpi_set_register(ACPI_BITREG_ARB_DISABLE, 1);
            }
            spin_unlock(&c3_cpu_status.lock);
        }
        else if ( !power->flags.bm_check )
        {
            /* SMP with no shared cache... Invalidate cache  */
            ACPI_FLUSH_CPU_CACHE();
        }

        /* Invoke C3 */
        acpi_idle_do_entry(cx);

        if ( (cx->type == ACPI_STATE_C3) &&
             power->flags.bm_check && power->flags.bm_control )
        {
            /* Enable bus master arbitration */
            spin_lock(&c3_cpu_status.lock);
            acpi_set_register(ACPI_BITREG_ARB_DISABLE, 0);
            c3_cpu_status.count--;
            spin_unlock(&c3_cpu_status.lock);
        }

        /* Get end time (ticks) */
        t2 = get_tick();

        /* recovering TSC */
        cstate_restore_tsc();
        trace_exit_reason(irq_traced);
        /* Trace cpu idle exit */
        TRACE_6D(TRC_PM_IDLE_EXIT, cx->idx, t2,
                 irq_traced[0], irq_traced[1], irq_traced[2], irq_traced[3]);

        /* Update statistics */
        acpi_update_idle_stats(power, cx, ticks_elapsed(t1, t2));
        /* Re-enable interrupts */
        local_irq_enable();
        /* recovering APIC */
        lapic_timer_on();

        break;

    default:
        /* Now in C0 */
        power->last_state = &power->states[0];
        local_irq_enable();
        sched_tick_resume();
        cpufreq_dbs_timer_resume();
        return;
    }

    /* Now in C0 */
    power->last_state = &power->states[0];

    sched_tick_resume();
    cpufreq_dbs_timer_resume();

    if ( cpuidle_current_governor->reflect )
        cpuidle_current_governor->reflect(power);
}
int main(int argc, char **argv)
{
	int i;
	char *connect_client = NULL;
	int connect_port = -1;

	for (i = 1; i < argc; i++)
	{
		if (strcmp(argv[i], "--prefix") == 0)
		{
			if (++i == argc) usage(argv[0]);
			prefix = argv[i];
		}
		else if (strcmp(argv[i], "--timeout") == 0)
		{
			if (++i == argc) usage(argv[0]);
			timeout = atoi(argv[i]);
		}
		else if (strcmp(argv[i], "--confirmation") == 0)
		{
			if (++i == argc) usage(argv[0]);
			confirmation_command_pattern = argv[i];
		}
		else if (strcmp(argv[i], "--connect") == 0)
		{
			if (++i == argc) usage(argv[0]);
			connect_client = argv[i];
			if (++i == argc) usage(argv[0]);
			connect_port = atoi(argv[i]);
		}
		else
		{
			usage(argv[0]);
		}
	}

	{
		snd_seq_t *seq;
		int port;

		if (snd_seq_open(&seq, "default", SND_SEQ_OPEN_INPUT, 0) < 0)
		{
			fprintf(stderr, "Cannot open the ALSA sequencer.\n");
			exit(1);
		}

		snd_seq_set_client_name(seq, "Brainstorm");
		port = snd_seq_create_simple_port(seq, "Brainstorm recording port", SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE, SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION);

		if ((connect_client != NULL) && (connect_port >= 0))
		{
			int connect_client_id = -1;

			{
				snd_seq_client_info_t *client_info;
				snd_seq_client_info_malloc(&client_info);

				while (snd_seq_query_next_client(seq, client_info) == 0)
				{
					if (strcmp(snd_seq_client_info_get_name(client_info), connect_client) == 0)
					{
						connect_client_id = snd_seq_client_info_get_client(client_info);
						break;
					}
				}

				snd_seq_client_info_free(client_info);
			}

			if (connect_client_id < 0) connect_client_id = atoi(connect_client);
			snd_seq_connect_from(seq, port, connect_client_id, connect_port);
		}

		signal(SIGALRM, alarm_handler);

		{
			snd_seq_event_t *event;

			while (snd_seq_event_input(seq, &event) >= 0)
			{
				switch (event->type)
				{
					case SND_SEQ_EVENT_NOTEOFF:
					{
						alarm(timeout);
						create_midi_file_for_first_event();
						MidiFileTrack_createNoteOffEvent(track, get_tick(), event->data.note.channel, event->data.note.note, event->data.note.velocity);
						break;
					}
					case SND_SEQ_EVENT_NOTEON:
					{
						alarm(timeout);
						create_midi_file_for_first_event();
						MidiFileTrack_createNoteOnEvent(track, get_tick(), event->data.note.channel, event->data.note.note, event->data.note.velocity);
						break;
					}
					case SND_SEQ_EVENT_KEYPRESS:
					{
						alarm(timeout);
						create_midi_file_for_first_event();
						MidiFileTrack_createKeyPressureEvent(track, get_tick(), event->data.note.channel, event->data.note.note, event->data.note.velocity);
						break;
					}
					case SND_SEQ_EVENT_CONTROLLER:
					{
						alarm(timeout);
						create_midi_file_for_first_event();
						MidiFileTrack_createControlChangeEvent(track, get_tick(), event->data.control.channel, event->data.control.param, event->data.control.value);
						break;
					}
					case SND_SEQ_EVENT_PGMCHANGE:
					{
						alarm(timeout);
						create_midi_file_for_first_event();
						MidiFileTrack_createProgramChangeEvent(track, get_tick(), event->data.control.channel, event->data.control.value);
						break;
					}
					case SND_SEQ_EVENT_CHANPRESS:
					{
						alarm(timeout);
						create_midi_file_for_first_event();
						MidiFileTrack_createChannelPressureEvent(track, get_tick(), event->data.control.channel, event->data.control.value);
						break;
					}
					case SND_SEQ_EVENT_PITCHBEND:
					{
						alarm(timeout);
						create_midi_file_for_first_event();
						MidiFileTrack_createPitchWheelEvent(track, get_tick(), event->data.control.channel, event->data.control.value);
						break;
					}
					default:
					{
						/* I'm ignoring the pseudoevents which ALSA provides as convenience features (SND_SEQ_EVENT_NOTE, SND_SEQ_EVENT_CONTROL14, SND_SEQ_EVENT_NONREGPARAM, and SND_SEQ_EVENT_REGPARAM).  Hopefully I can find some way to convince ALSA to normalize them into true MIDI events. */
						break;
					}
				}
			}
		}
	}

	return 0;
}
Esempio n. 23
0
void game_one_game() {
    should_end_game = 0;
    game_time       = 0;
    
    // Zeitinfo an Client
    game_send_info(SEND_BROADCAST);

    // Regeln laden
    lua_pushliteral(L, "rules_init");
    lua_rawget(L, LUA_GLOBALSINDEX);
    if (lua_pcall(L, 0, 0, 0) != 0) {
        fprintf(stderr, "error calling rules_init: %s\n", lua_tostring(L, -1));
        lua_pop(L, 1);
    }

    // Karte laden
    world_init();

    // Alle Viecher tot. vm_id = 0
    creature_init();

    // Initialer Worldtick. ruft level_init und ersten level_tick auf.
    world_tick();

    // Beginn der Zeitrechnung...
    int lasttick = 0;
    gettimeofday(&game_start, NULL);

    // onPlayerCreated Event an Rules, PLAYER_CREATED an VM
    player_game_start();

    // Spiel gestartet
    lua_pushliteral(L, "on_game_started");
    lua_rawget(L, LUA_GLOBALSINDEX);
    if (lua_pcall(L, 0, 0, 0) != 0) {
        fprintf(stderr, "error calling on_game_started: %s\n", lua_tostring(L, -1));
        lua_pop(L, 1);
    } 

    // Rule Handler
    game_call_rule_handler("onNewGame", 0);

    while (!game_exit && !should_end_game) {
        int tick = get_tick(&game_start);
        int delta;
        if (realtime) {
            delta = tick - lasttick;
            if (delta < 0 || delta > 200) {
                // Timewarp?
                lasttick = tick;
                continue;
            } else if (delta < 100) {
#ifdef WIN32
                Sleep(max(95 - delta, 10));
#else
                usleep(max(95000 - delta * 1000, 1000));
#endif
                continue;
            }
        } else {
            delta = 100;
        }
        lasttick = tick;

        // Realtime update
        real_time = time(NULL) - server_start; 
        
        // GC
        lua_gc(L, LUA_GCSTEP, 1);

        if (!game_paused) {
            // Runde starten
            game_send_round_info(SEND_BROADCAST, delta);

            // Rule Handler
            game_call_rule_handler("onRound", 0);

            // World Zeugs
            world_tick();
        }

        player_round();

        if (!game_paused) {
            // Spielerprogramme ausfuehren
            player_think();
        }

        player_sync();

        if (!game_paused) {
            // Viecher bewegen
            creature_moveall(delta);

            // Zeit weiterlaufen lassen
            game_time += delta;
        }
        
        // IO Lesen/Schreiben
        server_tick();
    }

    // Spiel beendet
    lua_pushliteral(L, "on_game_ended");
    lua_rawget(L, LUA_GLOBALSINDEX);
    if (lua_pcall(L, 0, 0, 0) != 0) {
        fprintf(stderr, "error calling on_game_ended: %s\n", lua_tostring(L, -1));
        lua_pop(L, 1);
    } 

    server_game_end();
    
    creature_shutdown();
    world_shutdown();
}
Esempio n. 24
0
r32 time_since(u64 then)
{
    u64 now = get_tick();
    return get_elapsed_time(then, now);
}
Esempio n. 25
0
void __udelay(int n)
{	
	unsigned base= get_tick(0);
	while(get_tick(base) < n);
}
Esempio n. 26
0
void gui_tick(VideoMode mode, r32 gui_time, r32 gui_dt)
{
    persist bool flag_DrawDroneGoto     = true;
    persist bool flag_DrawDrone         = true;
    persist bool flag_DrawVisibleRegion = true;
    persist bool flag_DrawTargets       = true;
    persist bool flag_DrawObstacles     = true;
    persist bool flag_Paused            = false;
    persist bool flag_Recording         = false;
    persist bool flag_SetupRecord       = false;

    persist int record_from = 0;
    persist int record_to = 0;
    persist int record_frame_skip = 1;
    persist int record_width = 0;
    persist int record_height = 0;
    persist float record_region_x = -1.0f;
    persist float record_region_y = -1.0f;
    persist float record_region_scale = 2.0f;
    persist jo_gif_t record_gif;

    persist int seek_cursor = 0;
    persist int selected_target = -1;

    persist Color color_Clear          = { 0.00f, 0.00f, 0.00f, 1.00f };
    persist Color color_Tiles          = { 0.20f, 0.35f, 0.46f, 0.66f };
    persist Color color_Grid           = { 0.00f, 0.00f, 0.00f, 1.00f };
    persist Color color_VisibleRegion  = { 0.87f, 0.93f, 0.84f, 0.50f };
    persist Color color_GreenLine      = { 0.10f, 1.00f, 0.20f, 1.00f };
    persist Color color_SelectedTarget = { 0.85f, 0.34f, 0.32f, 1.00f };
    persist Color color_Targets        = { 0.85f, 0.83f, 0.37f, 1.00f };
    persist Color color_Obstacles      = { 0.43f, 0.76f, 0.79f, 1.00f };
    persist Color color_Drone          = { 0.87f, 0.93f, 0.84f, 0.50f };
    persist Color color_DroneGoto      = { 0.87f, 0.93f, 0.84f, 0.50f };
    #define RGBA(C) C.r, C.g, C.b, C.a

    persist float send_timer = 0.0f;
    persist float send_interval = 1.0f; // In simulation time units

    NDC_SCALE_X = (mode.height / (r32)mode.width) / 12.0f;
    NDC_SCALE_Y = 1.0f / 12.0f;

    if (flag_Recording || flag_SetupRecord)
    {
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        float Ax = 2.0f / record_region_scale;
        float Bx = -1.0f - Ax*record_region_x;
        float Ay = 2.0f / record_region_scale;
        float By = -1.0f - Ay*record_region_y;
        float modelview[] = {
            Ax,   0.0f, 0.0f, 0.0f,
            0.0f, Ay,   0.0f, 0.0f,
            0.0f, 0.0f, 1.0f, 0.0f,
            Bx,   By,   0.0f, 1.0f
        };
        glLoadMatrixf(modelview);
    }
    else
    {
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
    }

    if (!flag_Paused)
    {
        if (flag_Recording)
        {
            if (seek_cursor >= record_to)
            {
                flag_Paused = true;
                flag_Recording = false;
                seek_cursor = record_from;
                jo_gif_end(&record_gif);
            }
            else if (seek_cursor + record_frame_skip >= record_to)
            {
                // clamp to end
                seek_cursor = record_to;
            }
            else
            {
                seek_cursor += record_frame_skip;
            }
        }
        else if (seek_cursor < HISTORY_LENGTH-1)
        {
            seek_cursor++;
        }
        else
        {
            sim_Command cmd;

            if (!sim_recv_cmd(&cmd))
            {
                cmd.type = sim_CommandType_NoCommand;
                cmd.x = 0.0f;
                cmd.y = 0.0f;
                cmd.i = 0;
            }

            STATE = sim_tick(STATE, cmd);
            add_history(cmd, STATE);
            seek_cursor = HISTORY_LENGTH-1;

            send_timer -= Sim_Timestep;
            if (send_timer <= 0.0f)
            {
                sim_send_state(&STATE);
                send_timer += send_interval;
            }
        }
    }

    sim_State draw_state = HISTORY_STATE[seek_cursor];
    sim_Drone drone = draw_state.drone;
    sim_Robot *robots = draw_state.robots;
    sim_Robot *targets = draw_state.robots;
    sim_Robot *obstacles = draw_state.robots + Num_Targets;

    if (flag_Recording || flag_SetupRecord)
    {
        glViewport(0, 0, record_width, record_height);
    }
    else
    {
        glViewport(0, 0, mode.width, mode.height);
    }

    glClearColor(RGBA(color_Clear));
    glClear(GL_COLOR_BUFFER_BIT);
    glLineWidth(2.0f);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // draw grid tiles
    glBegin(GL_TRIANGLES);
    {
        color4f(color_Tiles);
        for (int yi = 0; yi < 20; yi++)
        for (int xi = 0; xi < 20; xi++)
        {
            r32 x = xi*1.0f;
            r32 y = yi*1.0f;
            fill_square(x, y, x+1.0f, y+1.0f);
        }
    }
    glEnd();

    glBegin(GL_LINES);
    {
        // draw grid lines
        color4f(color_Grid);
        for (int i = 0; i <= 20; i++)
        {
            r32 x = (r32)i;
            draw_line(x, 0.0f, x, 20.0f);
            draw_line(0.0f, x, 20.0f, x);
        }

        // draw visible region
        if (flag_DrawVisibleRegion)
        {
            color4f(color_VisibleRegion);
            draw_circle(drone.x, drone.y, 2.5f);
        }

        // draw green line
        color4f(color_GreenLine);
        draw_line(0.0f, 20.0f, 20.0f, 20.0f);

        // draw targets
        if (flag_DrawTargets)
        {
            color4f(color_Targets);
            for (int i = 0; i < Num_Targets; i++)
                draw_robot(targets[i]);
            if (selected_target >= 0)
            {
                color4f(color_SelectedTarget);
                draw_robot(targets[selected_target]);
            }
        }

        // draw obstacles
        if (flag_DrawObstacles)
        {
            color4f(color_Obstacles);
            for (int i = 0; i < Num_Obstacles; i++)
                draw_robot(obstacles[i]);
        }

        // draw drone
        if (flag_DrawDrone)
        {
            color4f(color_Drone);
            draw_line(drone.x - 0.5f, drone.y,
                      drone.x + 0.5f, drone.y);
            draw_line(drone.x, drone.y - 0.5f,
                      drone.x, drone.y + 0.5f);
        }

        // draw drone goto
        if (flag_DrawDroneGoto)
        {
            color4f(color_DroneGoto);
            draw_circle(drone.xr, drone.yr, 0.45f);
        }

        // draw indicators of magnet or bumper activations
        for (int i = 0; i < Num_Targets; i++)
        {
            r32 x = targets[i].x;
            r32 y = targets[i].y;
            if (targets[i].action.was_bumped)
            {
                glColor4f(1.0f, 0.3f, 0.1f, 1.0f);
                draw_circle(x, y, 0.5f);
            }
            else if (targets[i].action.was_top_touched)
            {
                glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
                draw_circle(x, y, 0.5f);
            }
        }
    }
    glEnd();

    // TODO: Change capture res?
    if (flag_Recording)
    {
        static unsigned char capture_data[1024*1024*4];
        Assert(sizeof(capture_data) >=
               record_width*record_height*4);
        glReadPixels(0, 0,
                     record_width,
                     record_height,
                     GL_RGBA,
                     GL_UNSIGNED_BYTE,
                     capture_data);

        jo_gif_frame(&record_gif, capture_data,
                     2, false);
    }

    ImGui_ImplSdl_NewFrame(mode.window);

    // DRAW FLAGS
    if (ImGui::CollapsingHeader("Rendering"))
    {
        ImGui::Checkbox("Drone goto", &flag_DrawDroneGoto);
        ImGui::Checkbox("Drone", &flag_DrawDrone);
        ImGui::Checkbox("Visible region", &flag_DrawVisibleRegion);
        ImGui::Checkbox("Targets", &flag_DrawTargets);
        ImGui::Checkbox("Obstacles", &flag_DrawObstacles);
    } // END DRAW FLAGS

    // COLORS
    if (ImGui::CollapsingHeader("Colors"))
    {
        ImGui::ColorEdit4("Clear", &color_Clear.r);
        ImGui::ColorEdit4("Grid", &color_Grid.r);
        ImGui::ColorEdit4("VisibleRegion", &color_VisibleRegion.r);
        ImGui::ColorEdit4("GreenLine", &color_GreenLine.r);
        ImGui::ColorEdit4("Targets", &color_Targets.r);
        ImGui::ColorEdit4("Obstacles", &color_Obstacles.r);
        ImGui::ColorEdit4("Drone", &color_Drone.r);
        ImGui::ColorEdit4("DroneGoto", &color_DroneGoto.r);
    } // END COLORS

    // REWIND HISTORY
    if (ImGui::CollapsingHeader("Seek##header"))
    {
        ImGui::Checkbox("Paused", &flag_Paused);
        ImGui::SliderInt("Seek##bar", &seek_cursor, 0, HISTORY_LENGTH-1);
        ImGui::InputInt("Seek frame", &seek_cursor);
        if (seek_cursor < 0) seek_cursor = 0;
        if (seek_cursor > HISTORY_LENGTH-1) seek_cursor = HISTORY_LENGTH-1;
        ImGui::Text("Time: %.2f seconds", (seek_cursor+1) * Sim_Timestep);
    } // END REWIND HISTORY

    // ROBOTS
    if (ImGui::CollapsingHeader("Robots"))
    {
        ImGui::Columns(4, "RobotsColumns");
        ImGui::Separator();
        ImGui::Text("ID"); ImGui::NextColumn();
        ImGui::Text("X"); ImGui::NextColumn();
        ImGui::Text("Y"); ImGui::NextColumn();
        ImGui::Text("Angle"); ImGui::NextColumn();
        ImGui::Separator();
        for (int i = 0; i < Num_Targets; i++)
        {
            char label[32];
            sprintf(label, "%02d", i);
            if (ImGui::Selectable(label, selected_target == i, ImGuiSelectableFlags_SpanAllColumns))
                selected_target = i;
            ImGui::NextColumn();
            ImGui::Text("%.2f", robots[i].x); ImGui::NextColumn();
            ImGui::Text("%.2f", robots[i].y); ImGui::NextColumn();
            ImGui::Text("%.2f", robots[i].q); ImGui::NextColumn();
        }
        ImGui::Columns(1);
        ImGui::Separator();
    }
    else
    {
        selected_target = -1;
    } // END ROBOTS

    // COMMUNICATION
    if (ImGui::CollapsingHeader("Communication"))
    {
        ImGui::TextWrapped("The rate at which the state is "
                           "sent can be changed using this slider. "
                           "The slider value represents the time "
                           "interval (in simulation time) "
                           "between each send.");
        ImGui::SliderFloat("Send interval", &send_interval,
                           Sim_Timestep, 1.0f);
        ImGui::Separator();

        ImGui::Text("Last 10 non-trivial commands received:");
        ImGui::Columns(5, "CommunicationColumns");
        ImGui::Separator();
        ImGui::Text("Time"); ImGui::NextColumn();
        ImGui::Text("type"); ImGui::NextColumn();
        ImGui::Text("x"); ImGui::NextColumn();
        ImGui::Text("y"); ImGui::NextColumn();
        ImGui::Text("i"); ImGui::NextColumn();
        ImGui::Separator();
        int count = 0;
        for (int i = 0; count < 10 && i <= seek_cursor; i++)
        {
            sim_State state_i = HISTORY_STATE[seek_cursor-i];
            sim_Command cmd_i = HISTORY_CMD[seek_cursor-i];
            if (cmd_i.type == sim_CommandType_NoCommand)
                continue;
            char label[32];
            sprintf(label, "%.2f", state_i.elapsed_time);
            ImGui::Selectable(label, false,
                              ImGuiSelectableFlags_SpanAllColumns);
            ImGui::NextColumn();
            switch (cmd_i.type)
            {
                case sim_CommandType_NoCommand:
                {
                    ImGui::Text("Nothing"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                } break;
                case sim_CommandType_LandInFrontOf:
                {
                    ImGui::Text("Land 180"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                    ImGui::Text("%d", cmd_i.i); ImGui::NextColumn();
                } break;
                case sim_CommandType_LandOnTopOf:
                {
                    ImGui::Text("Land 45"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                    ImGui::Text("%d", cmd_i.i); ImGui::NextColumn();
                } break;
                case sim_CommandType_Track:
                {
                    ImGui::Text("Track"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                    ImGui::Text("%d", cmd_i.i); ImGui::NextColumn();
                } break;
                case sim_CommandType_Search:
                {
                    ImGui::Text("Search"); ImGui::NextColumn();
                    ImGui::Text("%.2f", cmd_i.x); ImGui::NextColumn();
                    ImGui::Text("%.2f", cmd_i.y); ImGui::NextColumn();
                    ImGui::Text("-"); ImGui::NextColumn();
                } break;
            }
            count++;
        }
        ImGui::Columns(1);
        ImGui::Separator();
    } // END COMMUNICATION

    // RECORDING GIFS
    if (ImGui::CollapsingHeader("Recording"))
    {
        flag_SetupRecord = true;
        if (ImGui::Button("Mark frame as begin"))
        {
            record_from = seek_cursor;
        }
        ImGui::SameLine();
        ImGui::Text("Record from: %d", record_from);
        if (ImGui::Button("Mark frame as end"))
        {
            record_to = seek_cursor;
        }
        ImGui::SameLine();
        ImGui::Text("Record to: %d", record_to);
        ImGui::InputInt("Frame skip", &record_frame_skip);

        ImGui::InputInt("Record width", &record_width);
        ImGui::InputInt("Record height", &record_height);
        if (record_width <= 0) record_width = mode.width;
        if (record_height <= 0) record_height = mode.height;

        ImGui::SliderFloat("Record x", &record_region_x, -1.0f, 1.0f);
        ImGui::SliderFloat("Record y", &record_region_y, -1.0f, 1.0f);
        ImGui::SliderFloat("Record scale", &record_region_scale, 0.0f, 2.0f);

        if (ImGui::Button("Start recording") && !flag_Recording)
            ImGui::OpenPopup("Save recording as?");
        if (ImGui::BeginPopupModal("Save recording as?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
        {
            persist char filename[1024];
            persist bool init_filename = true;
            if (init_filename)
            {
                sprintf(filename, "recording%u.gif", STATE.seed);
                init_filename = false;
            }
            ImGui::InputText("Filename", filename, sizeof(filename));
            ImGui::Separator();

            if (ImGui::Button("OK", ImVec2(120,0)))
            {
                flag_Recording = true;
                flag_Paused = false;
                seek_cursor = record_from-1;
                record_gif = jo_gif_start(filename, (short)record_width, (short)record_height, 0, 32);
                ImGui::CloseCurrentPopup();
            }
            ImGui::SameLine();
            if (ImGui::Button("Cancel", ImVec2(120,0)))
            {
                ImGui::CloseCurrentPopup();
            }
            ImGui::EndPopup();
        }

        if (ImGui::Button("Stop recording") && flag_Recording)
        {
            flag_Recording = false;
            flag_Paused = true;
            jo_gif_end(&record_gif);
        }

        if (record_from < 0) record_from = 0;
        if (record_from > HISTORY_LENGTH-1) record_from = HISTORY_LENGTH-1;
        if (record_to < record_from) record_to = record_from;
        if (record_to > HISTORY_LENGTH-1) record_to = HISTORY_LENGTH-1;
        if (record_frame_skip < 1) record_frame_skip = 1;
        ImGui::Separator();
    }
    else
    {
        flag_SetupRecord = false;
    } // END RECORDING GIFS

    // RESET AND SET SEED
    persist int custom_seed = 0;
    if (ImGui::Button("Reset"))
    {
        if (custom_seed > 0)
            STATE = sim_init((u32)custom_seed);
        else
            STATE = sim_init((u32)get_tick());
        HISTORY_LENGTH = 0;
        sim_Command cmd;
        cmd.type = sim_CommandType_NoCommand;
        add_history(cmd, STATE);
    }
    ImGui::SameLine();
    ImGui::InputInt("Seed", &custom_seed);
    // END RESET AND SET SEED

    // SAVE SIMULATION
    if (ImGui::Button("Save.."))
        ImGui::OpenPopup("Save as?");
    if (ImGui::BeginPopupModal("Save as?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
    {
        persist char filename[1024];
        persist bool init_filename = true;
        if (init_filename)
        {
            sprintf(filename, "simulation%u", STATE.seed);
            init_filename = false;
        }
        ImGui::InputText("Filename", filename, sizeof(filename));
        ImGui::Separator();

        if (ImGui::Button("OK", ImVec2(120,0)))
        {
            write_history(filename);
            ImGui::CloseCurrentPopup();
        }
        ImGui::SameLine();
        if (ImGui::Button("Cancel", ImVec2(120,0)))
        {
            ImGui::CloseCurrentPopup();
        }
        ImGui::EndPopup();
    } // END SAVE SIMULATION

    ImGui::SameLine();

    // SAVE SINGLE SNAPSHOT
    persist bool init_snapshot_filename = true;
    if (ImGui::Button("Save snapshot.."))
        ImGui::OpenPopup("Save snapshot as?");
    if (ImGui::BeginPopupModal("Save snapshot as?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
    {
        persist char filename[1024];
        ImGui::TextWrapped("The filename is relative to the executable,"
                           "unless you write an absolute path.");
        if (init_snapshot_filename)
        {
            sprintf(filename, "snapshot%u-%u", STATE.seed, seek_cursor);
            init_snapshot_filename = false;
        }
        ImGui::InputText("Filename", filename, sizeof(filename));
        ImGui::Separator();

        if (ImGui::Button("OK", ImVec2(120,0)))
        {
            sim_Observed_State snapshot =
                sim_observe_state(HISTORY_STATE[seek_cursor]);
            printf("%.2f\n", snapshot.obstacle_q[0]);
            sim_write_snapshot(filename, snapshot);
            ImGui::CloseCurrentPopup();
        }
        ImGui::SameLine();
        if (ImGui::Button("Cancel", ImVec2(120,0)))
        {
            ImGui::CloseCurrentPopup();
        }
        ImGui::EndPopup();
    }
    else
    {
        init_snapshot_filename = true;
    } // END SAVE SIMULATION

    ImGui::SameLine();

    // LOAD SIMULATION
    if (ImGui::Button("Load.."))
        ImGui::OpenPopup("Load file?");
    if (ImGui::BeginPopupModal("Load file?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
    {
        persist char filename[1024];
        persist bool init_filename = true;
        if (init_filename)
        {
            sprintf(filename, "simulation%u", STATE.seed);
            init_filename = false;
        }
        ImGui::InputText("Filename", filename, sizeof(filename));
        ImGui::Separator();

        if (ImGui::Button("OK", ImVec2(120,0)))
        {
            read_history(filename);
            seek_cursor = 0;
            flag_Paused = true;
            ImGui::CloseCurrentPopup();
        }
        ImGui::SameLine();
        if (ImGui::Button("Cancel", ImVec2(120,0)))
        {
            ImGui::CloseCurrentPopup();
        }
        ImGui::EndPopup();
    } // END LOAD SIMULATION

    ImGui::Render();
} // END gui_tick
Esempio n. 27
0
int main(int argc, char *argv[])
{
    if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
    {
        Printf("Failed to initialize SDL: %s\n", SDL_GetError());
        return -1;
    }

    VideoMode mode = {};
    mode.width = 800;
    mode.height = 600;
    mode.gl_major = 1;
    mode.gl_minor = 5;
    mode.double_buffer = 1;
    mode.depth_bits = 24;
    mode.stencil_bits = 8;
    mode.multisamples = 4;
    mode.swap_interval = 1;

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, mode.gl_major);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, mode.gl_minor);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,          mode.double_buffer);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,            mode.depth_bits);
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE,          mode.stencil_bits);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,    mode.multisamples>0?1:0);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,    mode.multisamples);

    mode.window = SDL_CreateWindow(
        "World Simulator",
        SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED,
        mode.width, mode.height,
        SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);

    if (!mode.window)
    {
        Printf("Failed to create a window: %s\n", SDL_GetError());
        return -1;
    }

    SDL_GLContext context = SDL_GL_CreateContext(mode.window);

    // Note: This must be set on a valid context
    SDL_GL_SetSwapInterval(mode.swap_interval);

    SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &mode.gl_major);
    SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &mode.gl_minor);
    SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER,          &mode.double_buffer);
    SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE,            &mode.depth_bits);
    SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE,          &mode.stencil_bits);
    SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES,    &mode.multisamples);
    mode.swap_interval = SDL_GL_GetSwapInterval();

    sim_init_msgs(false);

    ImGui_ImplSdl_Init(mode.window);

    STATE = sim_init((u32)get_tick());
    HISTORY_LENGTH = 0;

    bool running = true;
    u64 initial_tick = get_tick();
    u64 last_frame_t = initial_tick;
    r32 elapsed_time = 0.0f;
    r32 delta_time = 1.0f / 60.0f;
    while (running)
    {
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            ImGui_ImplSdl_ProcessEvent(&event);
            switch (event.type)
            {
                case SDL_WINDOWEVENT:
                {
                    switch (event.window.event)
                    {
                        case SDL_WINDOWEVENT_SIZE_CHANGED:
                        {
                            Printf("Window %d size changed to %dx%d\n",
                                    event.window.windowID,
                                    event.window.data1,
                                    event.window.data2);
                            mode.width = event.window.data1;
                            mode.height = event.window.data2;
                        } break;
                    }
                } break;

                case SDL_QUIT:
                {
                    running = false;
                } break;
            }
        }
        gui_tick(mode, elapsed_time, delta_time);
        SDL_GL_SwapWindow(mode.window);

        delta_time = time_since(last_frame_t);
        if (mode.fps_lock > 0)
        {
            r32 target_time = 1.0f / (r32)mode.fps_lock;
            r32 sleep_time = target_time - delta_time;
            if (sleep_time >= 0.01f)
                SDL_Delay((u32)(sleep_time * 1000.0f));
            delta_time = time_since(last_frame_t);
        }
        last_frame_t = get_tick();
        elapsed_time = time_since(initial_tick);

        GLenum error = glGetError();
        if (error != GL_NO_ERROR)
        {
            Printf("An error occurred: %s\n", gl_error_message(error));
            running = false;
        }
    }

    ImGui_ImplSdl_Shutdown();
    SDL_GL_DeleteContext(context);
    SDL_DestroyWindow(mode.window);
    SDL_Quit();

    return 0;
}
Esempio n. 28
0
 void SongTime::set_beat(Beat b) throw() {
   m_data = (static_cast<int64_t>(b) * (1 << 24)) | get_tick();
 }
Esempio n. 29
0
int main(int argc, char *argv[]) {
    char *host       = NULL;
    char *renderer   = NULL;
    int   width      = 800;
    int   height     = 600;
    int   fullscreen = 0;

#ifdef EVENT_HOST
    host = EVENT_HOST;
#endif

#ifdef DEFAULT_RENDERER
    renderer = TOSTRING(DEFAULT_RENDERER);
#endif

    // GUI Environment setzt default Renderer um.
    if (getenv("GUI"))
        renderer = getenv("GUI");

#ifdef WIN32
    char *sep = strrchr(argv[0], '\\');
    if (sep) { *sep = '\0'; chdir(argv[0]); }

    // Spezialfaelle fuer Windows Screensaver Aufrufe
    if (argc == 2 && stricmp(argv[1], "/s") == 0) {
        host  = "infon.dividuum.de";
        width = 1024, height = 768, fullscreen = 1;
        goto screen_saver_start;
    } else if (argc == 3 && stricmp(argv[1], "/p") == 0) {
        exit(EXIT_SUCCESS);
    } else if (argc == 2 && strstr(argv[1], "/c:") == argv[1]) {
        die("There are no settings");
    }
#endif

    // Keine Fehler auf stderr
    opterr = 0;

    int opt; 
    while ((opt = getopt(argc, argv, ":fvx:y:r:h")) != -1) {
        switch (opt) {
            case '?': die("you specified an unknown option -%c.", optopt);
            case ':': die("missing argument to option -%c.", optopt);
            case 'r': renderer   = optarg;          break;
            case 'f': fullscreen = 1;               break;
            case 'x': width      = atoi(optarg);    break;
            case 'y': height     = atoi(optarg);    break;
            case 'h': die("usage: %s [-r <renderer>] [-f] [-x <width>] [-y <height>] [-v] [-h] <server[:port]>\n"
                          "\n"
                          " -r <renderer>    - renderer to use (sdl_gui, gl_gui, ...)\n"
                          " -x <width>       - initial screen width.\n"
                          " -y <height>      - initial screen height.\n"
                          " -f               - start in fullscreen mode.\n"
                          " -v               - display version information.\n"
                          " -h               - this help.\n"
                          "\n"
                          "<server[:port]>   - ip/hostname of an infon game server.\n"
                          "                    if no port is given, 1234 is used.\n", argv[0]);
            case 'v': info(); exit(EXIT_SUCCESS);
        }
    }

    switch (argc - optind) {
        case 0:  break;
        case 1:  host = argv[optind]; break;
        default: die("you specified more than one game server hostname");
    }

    if (!renderer)
        die("no renderer specified. use the '-r <renderer>' option");

#ifdef WIN32
    if (!host) {
        if (yesno("You did not specify a game server.\nConnect to 'infon.dividuum.de:1234'?"))
            host = "infon.dividuum.de";
        else
            die("You must supply the game servers hostname\n"
                "as a command line parameter.\n\n"
                "Example: 'infon.exe infon.dividuum.de'\n\n"
                "Visit http://infon.dividuum.de/ for help.");
    } 
#else
    if (!host)
        die("usage: %s [options] <server[:port]>\n"
            "see %s -h for a full list of options", argv[0], argv[0]);
#endif


#ifndef WIN32
    signal(SIGTERM, sighandler);
    signal(SIGINT,  sighandler);
    signal(SIGPIPE, SIG_IGN);
#else
screen_saver_start:
#endif

    srand(time(NULL));
    gettimeofday(&start, NULL);

    if (!renderer_init(renderer)) 
        die("cannot initialize the renderer '%s'", renderer);

    if (!renderer_open(width, height, fullscreen))
        die("cannot start the renderer '%s'. sorry", renderer);

    client_init(host);
    client_game_init();

    int lastticks = get_tick();
    while (!signal_received && !renderer_wants_shutdown() && client_is_connected()) {
        int nowticks = get_tick();
        int delta = nowticks - lastticks;

        if (nowticks < lastticks || nowticks > lastticks + 1000) {
            // Timewarp?
            lastticks = nowticks;
            continue;
        }
        lastticks = nowticks;

        // IO Lesen/Schreiben
        client_tick(delta);
        client_creature_move(delta);
        renderer_tick(game_time, delta);

        game_time += delta;
    }

    client_game_shutdown();
    client_shutdown();

    renderer_close();
    renderer_shutdown();
    return EXIT_SUCCESS; 
}