void JForm::javaTickerChanged()
{
	qDebug() << ticker();
  if (ticker().isEmpty())
    w_ticker->hide();
  else
  {
    w_ticker->setText(ticker());
    if (w_ticker->isHidden())
	{
      w_ticker->show();
	}
  }
}
Example #2
0
  void 
  OPCollTicker::eventUpdate(const IntEvent &event, 
			    const PairEventData &) 
  {
    stream(event.getdt());
    ticker();
  }
Example #3
0
//------------------------------------------------------------------------------------------------------------------------//
STDMETHODIMP CMarketDataProvider::_OnLastQuote(struct QuoteUpdateParams* pParams, struct QuoteUpdateInfo* pResults)
{
	CTicker ticker(*pParams);
	CQuote	quote(*pResults);

	OnLastQuote(ticker, quote);
	return S_OK;
}
Example #4
0
  void
  OPVTK::initialise()
  {
    size_t vecSize = 1;
  
    for (size_t iDim(0); iDim < NDIM; ++iDim)
      {
	binWidth[iDim] *= Sim->dynamics.units().unitLength();
      
	if (binWidth[iDim] > 0.5 * Sim->primaryCellSize[iDim])
	  M_throw() << "Your bin width is too large for the " << iDim 
		    << " dimension";
      
	nBins[iDim] = static_cast<size_t>
	  (Sim->primaryCellSize[iDim] / binWidth[iDim]);
      
	//This is just to ensure the bin width fits an integer number of
	//times into the simulation
	binWidth[iDim] = Sim->primaryCellSize[iDim] / nBins[iDim];
      
	invBinWidth[iDim] = 1.0 / binWidth[iDim];
      
	vecSize *= nBins[iDim];
      }
  
    binVol = binWidth[0] * binWidth[1] * binWidth[2];
  
  
    if (CollisionStats)
      {
	collCounter.clear();
	collCounter.resize(vecSize, 0);
      }
  
    if (fields)
      {      
	mVsquared.resize(vecSize, 0.0);
	SampleCounter.resize(vecSize, 0);
	Momentum.resize(vecSize, Vector (0,0,0));
      
	std::string tmp("< ");
      
	for (size_t iDim(0); iDim < NDIM; ++iDim)
	  tmp += boost::lexical_cast<std::string>(nBins[iDim]) + " ";
      
	dout << "Number of bins " << tmp << ">" << std::endl;
      
	tmp = std::string("< ");
      
	for (size_t iDim(0); iDim < NDIM; ++iDim)
	  tmp +=boost::lexical_cast<std::string>
	    (binWidth[iDim]/Sim->dynamics.units().unitLength()) + " ";
      
	dout << "Bin width " << tmp << ">" << std::endl;  
      } 

    ticker();
  }
Example #5
0
//-----------------------------------------------------------------------------------------------------//
STDMETHODIMP CMarketDataProvider::_AcceptRisks(const ITicker& Params, IRisks& Info)
{
	CTicker	ticker(Params);
	CRisks risks(Info);

	AcceptRisks(ticker, risks);

	return S_OK;
};
void* Reap_CPU_V1(void* param)
{
	Reap_CPU_param* state = (Reap_CPU_param*)param;

	Work tempwork;
	tempwork.time = 13371337;

	uint8_t tempdata[512];
	memset(tempdata, 0, 512);

	uint8_t finalhash[32];
	uint8_t hash_results[1] = {};

	uint32_t current_server_id;

	while(!shutdown_now)
	{
		if (current_work.old)
		{
			Wait_ms(20);
			continue;
		}
		if (tempwork.time != current_work.time)
		{
			pthread_mutex_lock(&current_work_mutex);
			tempwork = current_work;
			pthread_mutex_unlock(&current_work_mutex);
			memcpy(tempdata, &tempwork.data[0], 128);
			*(uint32_t*)&tempdata[100] = state->thread_id;
			current_server_id = tempwork.server_id;
		}

		*(uint64_t*)&tempdata[76] = tempwork.ntime_at_getwork + (ticker()-tempwork.time)/1000;

		for(uint32_t h=0; h<CPU_BATCH_SIZE; ++h)
		{
			BlockHash_1_mine_V1(tempdata, finalhash, hash_results);
			if (hash_results[0])
			{
				BlockHash_1(tempdata, finalhash);
				if (finalhash[30] != 0 || finalhash[31] != 0)
					cpu_shares_hwinvalid++;
				else
					cpu_shares_hwvalid++;
				if (CPU_Hash_Below_Target(finalhash, &tempwork.target_share[0]))
					CPU_Got_share(state,tempdata,tempwork.target_share,current_server_id);
			}
			++*(uint32_t*)&tempdata[108];
		}
		state->hashes += CPU_BATCH_SIZE;
	}
	pthread_exit(NULL);
	return NULL;
}
void* Reap_CPU_XPM_hp7(void* param)
{

	Reap_CPU_param* state = (Reap_CPU_param*)param;

	Work tempwork;
	tempwork.time = 13371337;

	//uchar tempdata[80];
	//memset(tempdata, 0, 80);

	uchar finalhash[32];
	uchar temphash[32];
	uchar hash_results[1] = {};

	uint current_server_id;
	
	uint starttime = ticker();
	uint currenttime = starttime;
	
	uint foundprimes=0;

	while(!shutdown_now)
	{
		if (current_work.old)
		{
			Wait_ms(20);
			continue;
		}
		if (tempwork.time != current_work.time)
		{
			pthread_mutex_lock(&current_work_mutex);
			tempwork = current_work;
			pthread_mutex_unlock(&current_work_mutex);

			*(uint*)&tempwork.data[76] = state->thread_id<<28;
			current_server_id = tempwork.server_id;
		}

		bool result = MinePrime_hp(state,tempwork);
		if (result) 
		{
			pthread_mutex_lock(&current_work_mutex);
			current_work.old = true;
			pthread_mutex_unlock(&current_work_mutex);
		}
		++*(uint*)&tempwork.data[76];
	}
	pthread_exit(NULL);
	return NULL;
}
Example #8
0
void TestTickerObject()
{
    JuggleLib::Ticker ticker(period);
    JuggleLib::Ticker::Slot slot = std::bind(Ticked);
//    JuggleLib::Ticker::Connection callbackConnection =  ticker.AddTickResponder(slot);
    ticker.Start();
    while(!hasTicked_.load()){
        std::cout << "waiting" << std::endl;
        std::this_thread::sleep_for(std::chrono::microseconds(250));
    }
    std::cout << "stop Ticker" << std::endl;
    ticker.Stop();
 
}
Example #9
0
  void 
  OPStructureImaging::initialise()
  {
    dout << "Initialising Structure imaging with a max of " << imageCount
	 << " snapshots"<< std::endl;


    id = Sim->topology.size();
  
    for (const shared_ptr<Topology>& ptr : Sim->topology)
      if (boost::iequals(structureName, ptr->getName()))
	id = ptr->getID();
  
    if (id == Sim->topology.size())
      M_throw() << "Could not find a structure named " << structureName << " in the simulation";
  
    imagelist.clear();
    ticker();
  }
Example #10
0
  void 
  OPSCParameter::initialise() 
  {
    for (size_t iDim(0); iDim < NDIM; ++iDim)
      if (Sim->primaryCellSize[iDim] != 1.0) 
	M_throw() << "Cannot use this parameter in a non-cubic box";
  
    maxWaveNumber = lrint(std::pow(Sim->N, 1.0/3.0));

    if (boost::math::pow<3>(maxWaveNumber) != Sim->N)
      M_throw() << "Failed, N does not have an integer cube root!";

    dout << "Max wavelength is "
	 << 1.0 / (maxWaveNumber * Sim->units.unitLength()) << std::endl;

    maxWaveNumber *= 2;

    runningsum.resize(maxWaveNumber + 1, 0);

    ticker();
  }
Example #11
0
//-----------------------------------------------------------------------------------------------------//
STDMETHODIMP CMarketDataProvider::_AcceptQuote(const QuoteUpdateParams& Params, QuoteUpdateInfo& Info)
{
	HRESULT __Result = E_FAIL;
	try
	{
		CTicker	ticker(Params);
		CQuote	quote(Info);

		AcceptQuote(ticker, quote);
		
		__Result = S_OK;
	}
	catch (_com_error& err)
	{
		TRACE_COM_ERROR(err);
	}
	catch (...)
	{
		TRACE_UNKNOWN_ERROR();
	}
	return __Result;
};
Example #12
0
int main(int ac, char **av)
{
  if (ac>1 && (string)av[1]=="start")
  {
    pid_t pid = fork() ;
    if (pid<0)
    {
      fprintf(stderr, "fork() failed: %m\n") ;
      return 1 ;
    }
    if (pid>0)
    {
      fprintf(stderr, "started as pid=%d\n", pid) ;
      return 0 ;
    }
    umask(0) ;
    setsid() ; // don't check for failure
    chdir("/") ;
    freopen( "/dev/null", "r", stdin) ;
    freopen( "/dev/null", "w", stdout) ;
    freopen( "/dev/null", "w", stderr) ;
  }
  return ticker(ac,av).exec() ;
}
Example #13
0
/* Update the display. */
void osd_update_video_and_audio(struct osd_bitmap *bitmap)
{
	static const int waittable[FRAMESKIP_LEVELS][FRAMESKIP_LEVELS] =
	{
		{ 1,1,1,1,1,1,1,1,1,1,1,1 },
		{ 2,1,1,1,1,1,1,1,1,1,1,0 },
		{ 2,1,1,1,1,0,2,1,1,1,1,0 },
		{ 2,1,1,0,2,1,1,0,2,1,1,0 },
		{ 2,1,0,2,1,0,2,1,0,2,1,0 },
		{ 2,0,2,1,0,2,0,2,1,0,2,0 },
		{ 2,0,2,0,2,0,2,0,2,0,2,0 },
		{ 2,0,2,0,0,3,0,2,0,0,3,0 },
		{ 3,0,0,3,0,0,3,0,0,3,0,0 },
		{ 4,0,0,0,4,0,0,0,4,0,0,0 },
		{ 6,0,0,0,0,0,6,0,0,0,0,0 },
		{12,0,0,0,0,0,0,0,0,0,0,0 }
	};
	int i;
	static int showfps,showfpstemp;
	TICKER curr;
	static TICKER prev_measure=0,this_frame_base,prev;
	static int speed = 100;
	static int vups,vfcount;
	int have_to_clear_bitmap = 0;

	if (prev_measure==0)
	{
		/* first time through, initialize timer */
		prev_measure = ticker() - FRAMESKIP_LEVELS * TICKS_PER_SEC/video_fps;
	}

	if (frameskip_counter == 0)
		this_frame_base = prev_measure + FRAMESKIP_LEVELS * TICKS_PER_SEC/video_fps;

	/* update audio */
	msdos_update_audio();

	if (osd_skip_this_frame() == 0)
	{
		if (showfpstemp)
		{
			showfpstemp--;
			if (showfps == 0 && showfpstemp == 0)
			{
				have_to_clear_bitmap = 1;
			}
		}

		if (input_ui_pressed(IPT_UI_SHOW_FPS))
		{
			if (showfpstemp)
			{
				showfpstemp = 0;
				have_to_clear_bitmap = 1;
			}
			else
			{
				showfps ^= 1;
				if (showfps == 0)
				{
					have_to_clear_bitmap = 1;
				}
			}
		}

		/* now wait until it's time to update the screen */
		if (throttle)
		{
			profiler_mark(PROFILER_IDLE);
			if (video_sync)
			{
				static TICKER last;
				do
				{
					vsync();
					curr = ticker();
				} while (TICKS_PER_SEC / (curr - last) > video_fps * 11 /10);
				last = curr;
			}
			else
			{
				TICKER target;
				/* wait for video sync but use normal throttling */
				if (wait_vsync)
					vsync();
				curr = ticker();
				target = this_frame_base + frameskip_counter * TICKS_PER_SEC/video_fps;
				if ((curr < target) && (target-curr<TICKS_PER_SEC))
				{
					do
					{
						#ifdef WIZ
						    spend_cycles(1024); // WIZ
						#endif
						curr = ticker();
					} while ((curr < target) && (target-curr<TICKS_PER_SEC));
				}
			}
			profiler_mark(PROFILER_END);
		}
		else curr = ticker();

		if (frameskip_counter == 0)
		{
			int divdr;
			divdr = video_fps * (curr - prev_measure) / (100 * FRAMESKIP_LEVELS);
			if (divdr==0)
			    divdr=1;
			speed = (TICKS_PER_SEC + divdr/2) / divdr;
			prev_measure = curr;
		}

		prev = curr;

		vfcount += waittable[frameskip][frameskip_counter];
		if (vfcount >= video_fps)
		{
			extern int vector_updates; /* avgdvg_go_w()'s per Mame frame, should be 1 */
			vfcount = 0;
			vups = vector_updates;
			vector_updates = 0;
		}

		if (showfps || showfpstemp)
		{
			int fps;
			char buf[30];
			int divdr;
			divdr = 100 * FRAMESKIP_LEVELS;
			fps = (video_fps * (FRAMESKIP_LEVELS - frameskip) * speed + (divdr / 2)) / divdr;
			sprintf(buf,"%s%2d%4d%%%4d/%d fps",autoframeskip?"auto":"fskp",frameskip,speed,fps,(int)(video_fps+0.5));
			ui_text(bitmap,buf,Machine->uiwidth-strlen(buf)*Machine->uifontwidth,0);
			if (vector_game)
			{
				sprintf(buf," %d vector updates",vups);
				ui_text(bitmap,buf,Machine->uiwidth-strlen(buf)*Machine->uifontwidth,Machine->uifontheight);
			}
		}

		if (bitmap->depth == 8)
		{
			if (dirty_bright)
			{
				dirty_bright = 0;
				for (i = 0;i < 256;i++)
				{
					float rate = brightness * brightness_paused_adjust * pow(i / 255.0, 1 / osd_gamma_correction) / 100;
					bright_lookup[i] = 255 * rate + 0.5;
				}
			}
			if (dirtypalette)
			{
				dirtypalette = 0;
				for (i = 0;i < screen_colors;i++)
				{
					if (dirtycolor[i])
					{
						unsigned char r,g,b;
						
						dirtycolor[i] = 0;

						r = current_palette[3*i+0];
						g = current_palette[3*i+1];
						b = current_palette[3*i+2];
						if (i != Machine->uifont->colortable[1])	/* don't adjust the user interface text */
						{
							r = bright_lookup[r];
							g = bright_lookup[g];
							b = bright_lookup[b];
						}
						wiz_video_color8(i,r,g,b);
					}
				}
				wiz_video_setpalette();
			}
		}
		else
		{
			if (dirty_bright)
			{
				dirty_bright = 0;
				for (i = 0;i < 256;i++)
				{
					float rate = brightness * brightness_paused_adjust * pow(i / 255.0, 1 / osd_gamma_correction) / 100;
					bright_lookup[i] = 255 * rate + 0.5;
				}
			}
			if (dirtypalette)
			{
				if (use_dirty) init_dirty(1);	/* have to redraw the whole screen */

				dirtypalette = 0;
				for (i = 0;i < screen_colors;i++)
				{
					if (dirtycolor[i])
					{
						int r,g,b;

						dirtycolor[i] = 0;

						r = current_palette[3*i+0];
						g = current_palette[3*i+1];
						b = current_palette[3*i+2];
						if (i != Machine->uifont->colortable[1])	/* don't adjust the user interface text */
						{
							r = bright_lookup[r];
							g = bright_lookup[g];
							b = bright_lookup[b];
						}
						palette_16bit_lookup[i] = makecol(r,g,b);
					}
				}
			}
		}

		/* copy the bitmap to screen memory */
		profiler_mark(PROFILER_BLIT);
		update_screen(bitmap);
		profiler_mark(PROFILER_END);

		if (have_to_clear_bitmap)
			osd_clearbitmap(bitmap);

		if (use_dirty)
		{
			if (!vector_game)
				swap_dirty();
			init_dirty(0);
		}

		if (have_to_clear_bitmap)
			osd_clearbitmap(bitmap);

		if (throttle && autoframeskip && frameskip_counter == 0)
		{
			static int frameskipadjust;
			int adjspeed;

			/* adjust speed to video refresh rate if vsync is on */
			adjspeed = speed * video_fps / vsync_frame_rate;

			if (adjspeed >= 92)
			{
				frameskipadjust++;
				if (frameskipadjust >= 3)
				{
					frameskipadjust = 0;
					if (frameskip > 0) frameskip--;
				}
			}
			else
			{
				if (adjspeed < 80)
					frameskipadjust -= (90 - adjspeed) / 5;
				else
				{
					/* don't push frameskip too far if we are close to 100% speed */
					if (frameskip < 8)
						frameskipadjust--;
				}

				while (frameskipadjust <= -2)
				{
					frameskipadjust += 2;
#ifdef WIZ
					if (frameskip < 7) frameskip++;
#else
					if (frameskip < FRAMESKIP_LEVELS-1) frameskip++;
#endif
				}
			}
		}
	}

	/* Check for PGUP, PGDN and pan screen */
	pan_display();

	if (input_ui_pressed(IPT_UI_FRAMESKIP_INC))
	{
		if (autoframeskip)
		{
			autoframeskip = 0;
			frameskip = 0;
		}
		else
		{
			if (frameskip == FRAMESKIP_LEVELS-1)
			{
				frameskip = 0;
				autoframeskip = 1;
			}
			else
				frameskip++;
		}

		if (showfps == 0)
			showfpstemp = 2*video_fps;
	}

	if (input_ui_pressed(IPT_UI_FRAMESKIP_DEC))
	{
		if (autoframeskip)
		{
			autoframeskip = 0;
			frameskip = FRAMESKIP_LEVELS-1;
		}
		else
		{
			if (frameskip == 0)
				autoframeskip = 1;
			else
				frameskip--;
		}

		if (showfps == 0)
			showfpstemp = 2*video_fps;
	}

	if (input_ui_pressed(IPT_UI_THROTTLE))
	{
		throttle ^= 1;
	}

	frameskip_counter = (frameskip_counter + 1) % FRAMESKIP_LEVELS;
}
Example #14
0
 void 
 OPCollTicker::eventUpdate(const System&, const NEventData&, const double& dt)
 {
   stream(dt);
   ticker();
 }
Example #15
0
/* set the actual display screen but don't allocate the screen bitmap */
int osd_set_display(int width,int height,int depth,int attributes,int orientation)
{
	int     i;

	if (!gfx_height || !gfx_width)
	{
		printf("Please specify height AND width (e.g. -640x480)\n");
		return 0;
	}

	/* Mark the dirty buffers as dirty */

	if (use_dirty)
	{
		if (vector_game)
			/* vector games only use one dirty buffer */
			init_dirty (0);
		else
			init_dirty(1);
		swap_dirty();
		init_dirty(1);
	}
	if (dirtycolor)
	{
		for (i = 0;i < screen_colors;i++)
			dirtycolor[i] = 1;
		dirtypalette = 1;
	}

	/* Set video mode */
	wiz_set_video_mode(depth,gfx_width,gfx_height);

	vsync_frame_rate = video_fps;

	if (video_sync)
	{
		TICKER a,b;
		float rate;


		/* wait some time to let everything stabilize */
		for (i = 0;i < 60;i++)
		{
			vsync();
			a = ticker();
		}

		/* small delay for really really fast machines */
		for (i = 0;i < 100000;i++) ;

		vsync();
		b = ticker();

		rate = ((float)TICKS_PER_SEC)/(b-a);

		logerror("target frame rate = %ffps, video frame rate = %3.2fHz\n",video_fps,rate);

		/* don't allow more than 8% difference between target and actual frame rate */
		while (rate > video_fps * 108 / 100)
			rate /= 2;

		if (rate < video_fps * 92 / 100)
		{
			osd_close_display();
			logerror("-vsync option cannot be used with this display mode:\n"
						"video refresh frequency = %dHz, target frame rate = %ffps\n",
						(int)(TICKS_PER_SEC/(b-a)),video_fps);
			return 0;
		}

		logerror("adjusted video frame rate = %3.2fHz\n",rate);
			vsync_frame_rate = rate;

		if (Machine->sample_rate)
		{
			Machine->sample_rate = Machine->sample_rate * video_fps / rate;
			logerror("sample rate adjusted to match video freq: %d\n",Machine->sample_rate);
		}
	}

	return 1;
}
Example #16
0
int msdos_init_sound(void)
{
#ifdef USE_SEAL
	int i;

	/* Ask the user if no soundcard was chosen */
	if (soundcard == -1)
	{
		unsigned int k;

		printf("\nSelect the audio device:\n");

		for (k = 0;k < AGetAudioNumDevs();k++)
		{
			/* don't show the AWE32, it's too slow, users must choose Sound Blaster */
			if (AGetAudioDevCaps(k,&caps) == AUDIO_ERROR_NONE &&
					strcmp(caps.szProductName,"Sound Blaster AWE32"))
				printf("  %2d. %s\n",k,caps.szProductName);
		}
		printf("\n");

		if (k < 10)
		{
			i = getch();
			soundcard = i - '0';
		}
		else
			scanf("%d",&soundcard);
	}

	/* initialize SEAL audio library */
	if (soundcard == 0)     /* silence */
	{
		/* update the Machine structure to show that sound is disabled */
		Machine->sample_rate = 0;
		return 0;
	}

	/* open audio device */
	/*                              info.nDeviceId = AUDIO_DEVICE_MAPPER;*/
	info.nDeviceId = soundcard;
	/* always use 16 bit mixing if possible - better quality and same speed of 8 bit */
	info.wFormat = AUDIO_FORMAT_16BITS | AUDIO_FORMAT_MONO | AUDIO_FORMAT_RAW_SAMPLE;

	/* use stereo output if supported */
	if (usestereo)
	{
		if (Machine->drv->sound_attributes & SOUND_SUPPORTS_STEREO)
			info.wFormat = AUDIO_FORMAT_16BITS | AUDIO_FORMAT_STEREO | AUDIO_FORMAT_RAW_SAMPLE;
	}

	info.nSampleRate = Machine->sample_rate;
	if (AOpenAudio(&info) != AUDIO_ERROR_NONE)
	{
		printf("audio initialization failed\n");
		return 1;
	}

	AGetAudioDevCaps(info.nDeviceId,&caps);
	logerror("Using %s at %d-bit %s %u Hz\n",
			caps.szProductName,
			info.wFormat & AUDIO_FORMAT_16BITS ? 16 : 8,
			info.wFormat & AUDIO_FORMAT_STEREO ? "stereo" : "mono",
			info.nSampleRate);

	/* open and allocate voices, allocate waveforms */
	if (AOpenVoices(SOUND_CHANNELS) != AUDIO_ERROR_NONE)
	{
		printf("voices initialization failed\n");
		return 1;
	}

	for (i = 0; i < SOUND_CHANNELS; i++)
	{
		lpWave[i] = 0;
	}

	stream_playing = 0;
	stream_cache_data = 0;
	stream_cache_len = 0;
	stream_cache_stereo = 0;

	/* update the Machine structure to reflect the actual sample rate */
	Machine->sample_rate = info.nSampleRate;

	logerror("set sample rate: %d\n",Machine->sample_rate);
	if (sampleratedetect)
	{
		TICKER a,b;
		LONG start,end;


		if (ACreateAudioVoice(&hVoice[0]) != AUDIO_ERROR_NONE)
			return 1;

		if ((lpWave[0] = (LPAUDIOWAVE)malloc(sizeof(AUDIOWAVE))) == 0)
		{
			ADestroyAudioVoice(hVoice[0]);
			return 1;
		}

		lpWave[0]->wFormat = AUDIO_FORMAT_8BITS | AUDIO_FORMAT_MONO;
		lpWave[0]->nSampleRate = Machine->sample_rate;
		lpWave[0]->dwLength = 3*Machine->sample_rate;
		lpWave[0]->dwLoopStart = 0;
		lpWave[0]->dwLoopEnd = 3*Machine->sample_rate;
		if (ACreateAudioData(lpWave[0]) != AUDIO_ERROR_NONE)
		{
			free(lpWave[0]);
			lpWave[0] = 0;

			return 1;
		}

		memset(lpWave[0]->lpData,0,3*Machine->sample_rate);
		/* upload the data to the audio DRAM local memory */
		AWriteAudioData(lpWave[0],0,3*Machine->sample_rate);
		APrimeVoice(hVoice[0],lpWave[0]);
		ASetVoiceFrequency(hVoice[0],Machine->sample_rate);
		ASetVoiceVolume(hVoice[0],0);
		AStartVoice(hVoice[0]);

		a = ticker();
		/* wait some time to let everything stabilize */
		do
		{
			AUpdateAudioEx(Machine->sample_rate / Machine->drv->frames_per_second);
			b = ticker();
		} while (b-a < TICKS_PER_SEC/10);

		a = ticker();
		AGetVoicePosition(hVoice[0],&start);
		do
		{
			AUpdateAudioEx(Machine->sample_rate / Machine->drv->frames_per_second);
			b = ticker();
		} while (b-a < TICKS_PER_SEC);
		AGetVoicePosition(hVoice[0],&end);
		nominal_sample_rate = Machine->sample_rate;
		Machine->sample_rate = end - start;
		logerror("actual sample rate: %d\n",Machine->sample_rate);

		AStopVoice(hVoice[0]);
		ADestroyAudioData(lpWave[0]);
		free(lpWave[0]);
		lpWave[0] = 0;
		ADestroyAudioVoice(hVoice[0]);
	}
	else
		nominal_sample_rate = Machine->sample_rate;

#if 0
	{
		char *blaster_env;
		/* Get Soundblaster base address from environment variabler BLASTER   */
		/* Soundblaster OPL base port, at some compatibles this must be 0x388 */

		if(!getenv("BLASTER"))
		{
			printf("\nBLASTER variable not found, disabling fm sound!\n");
                        No_OPL = options.no_fm = 1;
		}
		else
		{
			blaster_env = getenv("BLASTER");
			BaseSb = i = 0;
			while ((blaster_env[i] & 0x5f) != 0x41) i++;        /* Look for 'A' char */
			while (blaster_env[++i] != 0x20) {
				BaseSb = (BaseSb << 4) + (blaster_env[i]-0x30);
			}
		}
	}
#endif

#endif

#ifdef USE_ALLEGRO
	reserve_voices(1,0);
	if (install_sound(DIGI_AUTODETECT,MIDI_NONE,0) != 0)
	{
		logerror("Allegro install_sound error: %s\n",allegro_error);
		return 1;
	}

	nominal_sample_rate = Machine->sample_rate;
#endif

	num_used_opl = 0;

	osd_set_mastervolume(attenuation);	/* set the startup volume */

	return 0;
}
Example #17
0
 void 
 OPCollTicker::eventUpdate(const LocalEvent &event, const NEventData&) 
 {
   stream(event.getdt());
   ticker();
 }
Example #18
0
static display_t draw()
{
#if COMPILE_ANIMATIONS
	static byte usbImagePos = FRAME_HEIGHT;
	static byte chargeImagePos = FRAME_HEIGHT;
#endif

	// Draw date
	drawDate();

	// Draw time animated
	display_t busy = ticker();

	// Draw battery icon
	drawBattery();

	byte fix = 20;

	// Draw USB icon
	image_s icon = newImage(fix, FRAME_HEIGHT - 9, usbIcon, 16, 8, WHITE, NOINVERT, 0);
	draw_bitmap_set(&icon);

#if COMPILE_ANIMATIONS
	if(animateIcon(USB_CONNECTED(), &usbImagePos))
	{
		icon.y = usbImagePos;
		draw_bitmap_s2(NULL);
		icon.x += 20;
	}
#else
	if(USB_CONNECTED())
	{
		draw_bitmap_s2(NULL);
		icon.x += 20;
	}
#endif
	
	// Draw charging icon
	icon.width = 8;
#if COMPILE_ANIMATIONS
	if(animateIcon(CHARGING(), &chargeImagePos))
	{
		icon.bitmap = chargeIcon;
		icon.y = chargeImagePos;
		draw_bitmap_s2(NULL);
		icon.x += 12;
	}	
#else
	if(CHARGING())
	{
		icon.bitmap = chargeIcon;
		draw_bitmap_s2(NULL);
		icon.x += 12;
	}
#endif

	icon.y = FRAME_HEIGHT - 8;

#if COMPILE_STOPWATCH
	// Stopwatch icon
	if(stopwatch_active())
	{
		icon.bitmap = stopwatch;
		draw_bitmap_s2(&icon);
		icon.x += 12;
	}
#endif	

	// Draw next alarm
	alarm_s nextAlarm;
	if(alarm_getNext(&nextAlarm))
	{
		time_s alarmTime;
		alarmTime.hour = nextAlarm.hour;
		alarmTime.mins = nextAlarm.min;
		alarmTime.ampm = CHAR_24;
		time_timeMode(&alarmTime, appConfig.timeMode);
		
		char buff[9];
		sprintf_P(buff, PSTR("%02hhu:%02hhu%c"), alarmTime.hour, alarmTime.mins, alarmTime.ampm);
		draw_string(buff, false, icon.x, FRAME_HEIGHT - 8);
		icon.x += (alarmTime.ampm == CHAR_24) ? 35 : 42;

		icon.bitmap = dowImg[alarm_getNextDay()];
		draw_bitmap_s2(&icon);

//		icon.x += 9;
	}

	return busy;
}
Example #19
0
int main(int argc, char** argv) {

  // initialize guacamole
  gua::init(argc, argv);

  gua::ShadingModelDatabase::load_shading_models_from("data/materials/");
  gua::MaterialDatabase::load_materials_from("data/materials/");

  // initialize Oculus SDK
  OVR::SensorFusion* oculus_sensor = init_oculus();
  if (!oculus_sensor) return 1; // no oculus sensor found

  // setup scene
  gua::SceneGraph graph("main_scenegraph");

  gua::TriMeshLoader loader;

  auto monkey_geometry(loader.create_geometry_from_file(
    "root_ape",
    geometry,
    "data/materials/Stones.gmd"
  ));

  auto root_monkey = graph.add_node("/", monkey_geometry);
  root_monkey->scale(0.5, 0.5, 0.5);

  // depth    monkey    cube          car
  // 1        14.084      56    3.619.000 Vertices  /      7 draw calls
  // 2        74.444     296   19.129.000 Vertices  /     37 draw calls
  // 3       436.604   1.736  112.189.000 Vertices  /    217 draw calls
  // 4     2.609.564  10.376              Vertices  /  1.297 draw calls
  // 5    15.647.324  62.216              Vertices  /  7.777 draw calls
  // 6    93.873.884 373.256              Vertices  / 46.657 draw calls
  setup_scene(graph, root_monkey, 4);

  auto lights = add_lights(graph, 50);

  auto pos = graph.add_node<gua::node::TransformNode>("/", "pos");
  pos->translate(0, 0, 2);
  auto nav = graph.add_node<gua::node::TransformNode>("/pos", "nav");

  auto screen = graph.add_node<gua::node::ScreenNode>("/pos/nav", "screen_l");
  screen->data.set_size(gua::math::vec2(0.08, 0.1));
  screen->translate(-0.04, 0, -0.05f);

  screen = graph.add_node<gua::node::ScreenNode>("/pos/nav", "screen_r");
  screen->data.set_size(gua::math::vec2(0.08, 0.1));
  screen->translate(0.04, 0, -0.05f);

  auto eye = graph.add_node<gua::node::TransformNode>("/pos/nav", "eye_l");
  eye->translate(-0.032, 0, 0);

  eye = graph.add_node<gua::node::TransformNode>("/pos/nav", "eye_r");
  eye->translate(0.032, 0, 0);

  unsigned width = 1280/2;
  unsigned height = 800;

  auto pipe = new gua::Pipeline();
  pipe->config.set_camera(gua::Camera("/pos/nav/eye_l", "/pos/nav/eye_r", "/pos/nav/screen_l", "/pos/nav/screen_r", "main_scenegraph"));
  pipe->config.set_left_resolution(gua::math::vec2ui(width, height));
  pipe->config.set_right_resolution(gua::math::vec2ui(width, height));
  pipe->config.set_enable_fps_display(true);
  pipe->config.set_enable_frustum_culling(true);
  pipe->config.set_enable_stereo(true);

  pipe->config.set_enable_ssao(true);
  pipe->config.set_ssao_intensity(2.f);
  pipe->config.set_enable_fxaa(true);
  pipe->config.set_enable_hdr(true);
  pipe->config.set_hdr_key(5.f);
  pipe->config.set_enable_bloom(true);
  pipe->config.set_bloom_radius(10.f);
  pipe->config.set_bloom_threshold(0.8f);
  pipe->config.set_bloom_intensity(0.8f);

#if WIN32
  auto oculus_window(new gua::OculusWindow("\\\\.\\DISPLAY1"));
#else
  auto oculus_window(new gua::OculusWindow(":0.0"));
#endif
  pipe->set_window(oculus_window);

  gua::Renderer renderer({
    pipe
  });

  gua::Timer timer;
  timer.start();

  double time(0);
  float desired_frame_time(1.0 / 60.0);
  gua::events::MainLoop loop;

  // application loop
  gua::events::Ticker ticker(loop, desired_frame_time);

  ticker.on_tick.connect([&]() {
    double frame_time(timer.get_elapsed());
    time += frame_time;
    timer.reset();

    std::function<void (std::shared_ptr<gua::node::Node>, int)> rotate;
    rotate = [&](std::shared_ptr<gua::node::Node> node, int depth) {
      node->rotate(frame_time * (1+depth) * 0.5, 1, 1, 0);
      for (auto child: node->get_children()) {
        rotate(child, ++depth);
      }
    };

    rotate(graph["/root_ape"], 1);

    for (int i = 0; i < lights.size(); ++i) {
      lights[i]->rotate(
          std::sin(time * (i * 0.1 + 0.5)) * frame_time * 2.5, 0, 1, 0);
    }

    graph["/root_ape"]->rotate(15 * frame_time, 0, 1, 0);
    //graph["/screen"]->rotate(20*frame_time, 0, 1, 0);

    nav->set_transform(get_oculus_transform(oculus_sensor));

    renderer.queue_draw({&graph});
  });

  loop.start();

  return 0;
}
Example #20
0
int main(int argc, char** argv) {
  // initialize guacamole
  gua::init(argc, argv);

  /////////////////////////////////////////////////////////////////////////////
  // create a set of materials
  /////////////////////////////////////////////////////////////////////////////

  // create simple untextured material shader
  auto pbr_keep_input_desc    = std::make_shared<gua::MaterialShaderDescription>("./data/materials/PBR_use_input_color.gmd");
  auto pbr_uniform_color_desc = std::make_shared<gua::MaterialShaderDescription>("./data/materials/PBR_uniform_color.gmd");

  //use this material for models where shading does not make sense
  auto pbr_keep_color_shader(std::make_shared<gua::MaterialShader>("PBR_pass_input_color", pbr_keep_input_desc));
  auto pbr_overwrite_color_shader(std::make_shared<gua::MaterialShader>("PBR_overwrite_input_color", pbr_uniform_color_desc));

  gua::MaterialShaderDatabase::instance()->add(pbr_keep_color_shader);
  gua::MaterialShaderDatabase::instance()->add(pbr_overwrite_color_shader);

  // create different materials for point-based input
  auto plod_glossy      = pbr_keep_color_shader->make_new_material();
  auto plod_rough       = pbr_keep_color_shader->make_new_material();
  auto plod_passthrough = pbr_keep_color_shader->make_new_material();

  // glossy has high metalness, low roughness and no emissivity (=no passthrough)
  plod_glossy->set_uniform("metalness", 1.0f);
  plod_glossy->set_uniform("roughness", 0.3f);
  plod_glossy->set_uniform("emissivity", 0.0f);

  // rough has no metalness, high roughness and no emissivity (=no passthrough)
  plod_rough->set_uniform("metalness", 0.0f);
  plod_rough->set_uniform("roughness", 0.8f);
  plod_rough->set_uniform("emissivity", 1.0f);

  // passthrough has emissivity of 1.0
  plod_passthrough->set_uniform("emissivity", 1.0f);

  auto rough_white = pbr_overwrite_color_shader->make_new_material();
  rough_white->set_uniform("color", gua::math::vec3f(1.0f, 1.0f, 1.0f));
  rough_white->set_uniform("metalness", 0.0f);
  rough_white->set_uniform("roughness", 0.8f);
  rough_white->set_uniform("emissivity", 0.0f);

  auto rough_red = pbr_overwrite_color_shader->make_new_material();
  rough_red->set_uniform("color", gua::math::vec3f(0.8f, 0.0f, 0.0f));
  rough_red->set_uniform("metalness", 0.0f);
  rough_red->set_uniform("roughness", 0.8f);
  rough_red->set_uniform("emissivity", 0.0f);


  // setup scene
  gua::SceneGraph graph("main_scenegraph");

  gua::LodLoader plodLoader;

  plodLoader.set_upload_budget_in_mb(32);
  plodLoader.set_render_budget_in_mb(2048);
  plodLoader.set_out_of_core_budget_in_mb(4096);

  auto transform = graph.add_node<gua::node::TransformNode>("/", "transform");
  auto model_xf = graph.add_node<gua::node::TransformNode>("/transform", "model_xf");

  auto setup_plod_node = [](std::shared_ptr<gua::node::PLodNode> const& node) {
    node->set_radius_scale(1.0f);
    node->set_enable_backface_culling_by_normal(false);
    node->set_draw_bounding_box(true);
  };

#if WIN32
  auto plod_pig_node = plodLoader.load_lod_pointcloud("plod_pig", "data/objects/Area_4_hunter_with_bow_knn.bvh", plod_rough, gua::LodLoader::NORMALIZE_POSITION | gua::LodLoader::NORMALIZE_SCALE | gua::LodLoader::MAKE_PICKABLE);
#else
  auto plod_pig_node = plodLoader.load_lod_pointcloud("plod_pig", "/mnt/pitoti/3d_pitoti/groundtruth_data/rocks/seradina12c/areas/objects/Area_4_hunter_with_bow_knn.bvh", plod_rough, gua::LodLoader::NORMALIZE_POSITION | gua::LodLoader::NORMALIZE_SCALE | gua::LodLoader::MAKE_PICKABLE);
#endif
  plod_pig_node->scale(5.0, 5.0, 5.0);
  plod_pig_node->rotate(269, gua::math::vec3(0.0, 0.0, 1.0));

  gua::TriMeshLoader loader;

  auto root_plod_pig_model = graph.add_node("/", plod_pig_node);

  auto nav = graph.add_node<gua::node::TransformNode>("/", "nav");
  nav->translate(0.0, 0.0, 1.0);

#if WIN32
  auto window = std::make_shared<gua::OculusWindow>(":0.0");
  gua::WindowDatabase::instance()->add("main_window", window);
  window->config.set_enable_vsync(false);
  window->config.set_fullscreen_mode(false);
  window->open();
#else
  auto window = std::make_shared<gua::OculusWindow>(":0.0");
  gua::WindowDatabase::instance()->add("main_window", window);
  window->config.set_enable_vsync(false);
  window->config.set_fullscreen_mode(true);
  window->config.set_size(window->get_window_resolution());
  window->config.set_resolution(window->get_window_resolution());
  window->open();
#endif

  //get the resolution from the oculus window
  gua::math::vec2ui res(window->get_window_resolution());

  auto resolve_pass = std::make_shared<gua::ResolvePassDescription>();
  resolve_pass->background_mode(gua::ResolvePassDescription::BackgroundMode::QUAD_TEXTURE);
  resolve_pass->tone_mapping_exposure(1.0f);

  auto neck = graph.add_node<gua::node::TransformNode>("/nav", "neck");

  auto camera = graph.add_node<gua::node::CameraNode>("/nav/neck", "cam");

  float camera_trans_y = 0.0;
  float camera_trans_z = 0.0;

  camera->translate(0.0, camera_trans_y, camera_trans_z);

  camera->config.set_resolution( res );
  camera->config.set_left_screen_path("/nav/neck/cam/left_screen");
  camera->config.set_right_screen_path("/nav/neck/cam/right_screen");
  camera->config.set_scene_graph_name("main_scenegraph");
  camera->config.set_output_window_name("main_window");
  camera->config.set_enable_stereo(true);
  camera->config.set_eye_dist(window->get_IPD());

  auto pipe = std::make_shared<gua::PipelineDescription>();

  pipe->add_pass(std::make_shared<gua::PLodPassDescription>());
  pipe->add_pass(std::make_shared<gua::LightVisibilityPassDescription>());
  pipe->add_pass(std::make_shared<gua::ResolvePassDescription>());

  camera->set_pipeline_description(pipe); 
  
 
  // retreive the complete viewing setup from the oculus window
  //**************
  auto left_screen = graph.add_node<gua::node::ScreenNode>("/nav/neck/cam", "left_screen");
  left_screen->data.set_size(window->get_left_screen_size());
  left_screen->translate(window->get_left_screen_translation());

  auto right_screen = graph.add_node<gua::node::ScreenNode>("/nav/neck/cam", "right_screen");
  right_screen->data.set_size(window->get_right_screen_size());
  right_screen->translate(window->get_right_screen_translation());

  //****************/

  gua::Renderer renderer;

  gua::Timer timer;
  timer.start();

  double time(0);
  float desired_frame_time(1.0 / 60.0);
  gua::events::MainLoop loop;

  // application loop
  gua::events::Ticker ticker(loop, desired_frame_time);

  ticker.on_tick.connect([&]() {
    double frame_time(timer.get_elapsed());
    time += frame_time;
    timer.reset();

    window->process_events();
    std::function<void (std::shared_ptr<gua::node::Node>, int)> rotate;
    rotate = [&](std::shared_ptr<gua::node::Node> node, int depth) {
      node->rotate(frame_time * (1+depth) * 0.5, 1, 1, 0);
      for (auto child: node->get_children()) {
        rotate(child, ++depth);
      }
    };

    float frame_offset = 1.0 * frame_time;

    camera->set_transform(window->get_oculus_sensor_orientation());
    //neck->set_transform(window->get_oculus_sensor_orientation());

    renderer.queue_draw({&graph});
  });

  loop.start();

  return 0;
}
Example #21
0
int main(int argc, char** argv)
{
    // initialize guacamole
    gua::init(argc, argv);

    // setup scene
    gua::SceneGraph graph("main_scenegraph");

    gua::TriMeshLoader loader;
    auto add_mesh = [&](int x, int y, int z) {
        auto t = graph.add_node<gua::node::TransformNode>("/", "mesh_" + std::to_string(x) + "_" + std::to_string(y));
        t->scale(0.5);
        t->translate((x - COUNT * 0.5 + 0.5) / 2, (y - COUNT * 0.5 + 0.5) / 2, (z - COUNT * 0.5 + 0.5) / 2);

        auto mesh(loader.create_geometry_from_file("teapot", "data/objects/teapot.obj", gua::TriMeshLoader::NORMALIZE_POSITION | gua::TriMeshLoader::NORMALIZE_SCALE));
        t->add_child(mesh);
    };

    for(int x(0); x < COUNT; ++x)
    {
        for(int y(0); y < COUNT; ++y)
        {
            for(int z(0); z < COUNT; ++z)
            {
                add_mesh(x, y, z);
            }
        }
    }

    auto resolution = gua::math::vec2ui(1920, 1080);

    auto light = graph.add_node<gua::node::LightNode>("/", "light");
    light->data.set_type(gua::node::LightNode::Type::POINT);
    light->scale(4.4f);
    light->translate(1.f, 0.f, 2.f);

    auto screen = graph.add_node<gua::node::ScreenNode>("/", "screen");
    screen->data.set_size(gua::math::vec2(0.001 * resolution.x, 0.001 * resolution.y));
    screen->translate(0, 0, 1.0);

    auto camera = graph.add_node<gua::node::CameraNode>("/screen", "cam");
    camera->translate(0, 0, 2.0);
    camera->config.set_resolution(resolution);
    camera->config.set_screen_path("/screen");
    camera->config.set_scene_graph_name("main_scenegraph");
    camera->config.set_output_window_name("main_window");
    camera->get_pipeline_description()->get_resolve_pass()->tone_mapping_exposure(0.8f);

    auto plane_transform = graph.add_node<gua::node::TransformNode>("/", "plane_transform");

    auto add_clipping_plane = [&](gua::math::vec3 const& pos, gua::math::vec4 const& rot) {
        auto clipping_plane = graph.add_node<gua::node::ClippingPlaneNode>("/plane_transform", "clipping_plane");
        clipping_plane->rotate(rot.x, rot.y, rot.z, rot.w);
        clipping_plane->translate(pos);
        auto plane(loader.create_geometry_from_file("plane", "data/objects/plane.obj", gua::TriMeshLoader::NORMALIZE_POSITION | gua::TriMeshLoader::NORMALIZE_SCALE));
        plane->rotate(-90, 1, 0, 0);
        // clipping_plane->add_child(plane);
    };

    add_clipping_plane(gua::math::vec3(0, 0, -0.5), gua::math::vec4(180, 1, 0, 0));
    add_clipping_plane(gua::math::vec3(0, 0, 0.5), gua::math::vec4(0, 0, 0, 0));
    add_clipping_plane(gua::math::vec3(0, 0.5, 0), gua::math::vec4(-90, 1, 0, 0));
    add_clipping_plane(gua::math::vec3(0, -0.5, 0), gua::math::vec4(90, 1, 0, 0));
    add_clipping_plane(gua::math::vec3(-0.5, 0, 0), gua::math::vec4(-90, 0, 1, 0));
    add_clipping_plane(gua::math::vec3(0.5, 0, 0), gua::math::vec4(90, 0, 1, 0));

    // auto clipping_plane_2 = graph.add_node<gua::node::ClippingPlaneNode>("/plane_transform", "clipping_plane_2");
    // clipping_plane_2->rotate(90, 1, 0, 0);
    // clipping_plane_2->translate(0, 0.5, 0);

    // add mouse interaction
    gua::utils::Trackball trackball(0.01, 0.002, 0.2);

    auto window = std::make_shared<gua::GlfwWindow>();
    gua::WindowDatabase::instance()->add("main_window", window);
    window->config.set_enable_vsync(true);
    window->config.set_size(resolution);
    window->config.set_resolution(resolution);

    window->on_resize.connect([&](gua::math::vec2ui const& new_size) {
        window->config.set_resolution(new_size);
        camera->config.set_resolution(new_size);
        screen->data.set_size(gua::math::vec2(0.001 * new_size.x, 0.001 * new_size.y));
    });

    window->on_move_cursor.connect([&](gua::math::vec2 const& pos) { trackball.motion(pos.x, pos.y); });
    window->on_button_press.connect(std::bind(mouse_button, std::ref(trackball), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

    window->open();

    gua::Renderer renderer;

    // application loop
    gua::events::MainLoop loop;
    gua::events::Ticker ticker(loop, 1.0 / 500.0);

    ticker.on_tick.connect([&]() {
        // apply trackball matrix to object
        gua::math::mat4 modelmatrix = scm::math::make_translation(gua::math::float_t(trackball.shiftx()), gua::math::float_t(trackball.shifty()), gua::math::float_t(trackball.distance())) *
                                      gua::math::mat4(trackball.rotation());

        plane_transform->set_transform(modelmatrix);

        window->process_events();
        if(window->should_close())
        {
            renderer.stop();
            window->close();
            loop.stop();
        }
        else
        {
            renderer.queue_draw({&graph});
        }
    });

    loop.start();

    return 0;
}
Example #22
0
Word MiniLoop(void(*start)(void),void(*stop)(void),
	Word(*ticker)(void),void(*drawer)(void))
{
	Word exit;
	Word buttons;

/* Setup (cache graphics,etc) */

	DoWipe = TRUE;
	start();			/* Prepare the background task (Load data etc.) */
	exit = 0;			/* I am running */
	gameaction = ga_nothing;	/* Game is not in progress */
	TotalGameTicks = 0;		/* No vbls processed during game */
	ElapsedTime = 0;	/* No time has elapsed yet */

	/* Init the joypad states */
	JoyPadButtons = PrevJoyPadButtons = NewJoyPadButtons = 0;

	do {		/* Run the tic immediately */
		TotalGameTicks += ElapsedTime;		/* Add to the VBL count */
		exit = ticker();			/* Process the keypad commands */

/* adaptive timing based on previous frame */

		if (DemoPlayback || DemoRecording) {
			ElapsedTime = 4;		/* Force 15 FPS */
		} else {
			ElapsedTime = (Word)LastTics;		/* Get the true time count */
			if (ElapsedTime >= 9) {		/* Too slow? */
				ElapsedTime = 8;		/* Make 7.5 fps as my mark */
			}
		}

/* Get buttons for next tic */

		PrevJoyPadButtons = JoyPadButtons;		/* Pass through the latest keypad info */

		buttons = ReadJoyButtons(0);			/* Read the controller */
		JoyPadButtons = buttons;	/* Save it */
		
		if (DemoPlayback) {					/* Playing back a demo? */
			if (buttons & (PadA|PadB|PadC|PadD) ) {		/* Abort? */
				exit = ga_exitdemo;			/* Exit the demo */
				break;
			}
			/* Get a joypad from demo data */
			JoyPadButtons = buttons = GetDemoCmd();
		}
		NewJoyPadButtons = (buttons^PrevJoyPadButtons)&buttons;	/* Get the joypad downs... */

		if (DemoRecording) {		/* Am I recording a demo? */
			DemoDataPtr[0] = LocalToNet(buttons);	/* Save the current joypad data */
			++DemoDataPtr;
		}

		/* Am I recording a demo? */
		if ((DemoRecording || DemoPlayback) && (buttons & PadStart) ) {
			exit = ga_completed;		/* End the game right now! */
		}

		if (gameaction == ga_warped) {		/* Did I end the level? */
			exit = ga_warped;	/* Exit after drawing */
			break;			/* Exit */
		}

/* sync up with the refresh */

		drawer();			/* Draw the screen */
	} while (!exit);		/* Is the loop finished? */
	stop();					/* Release resources */
	S_Clear();				/* Kill sounds */
	players.mo = 0;	/* For net consistancy checks */
	return exit;			/* Return the abort code from ticker */
}
Example #23
0
void update_screen(void)
{
	UINT8 skipped_it = skiptable[frameskip][frameskip_counter];

	if (!skipped_it)
	{
		if (option_showfps) show_fps();
		draw_volume_status(1);
		show_battery_warning();
		ui_show_popup(1);
	}
	else
	{
		draw_volume_status(0);
		ui_show_popup(0);
	}

	if (warming_up)
	{
		sceDisplayWaitVblankStart();
		last_skipcount0_time = ticker() - (int)((float)FRAMESKIP_LEVELS * PSP_TICKS_PER_FRAME);
		warming_up = 0;
	}

	if (frameskip_counter == 0)
		this_frame_base = last_skipcount0_time + (int)((float)FRAMESKIP_LEVELS * PSP_TICKS_PER_FRAME);

	frames_displayed++;
	frames_since_last_fps++;

	if (!skipped_it)
	{
		TICKER curr = ticker();
		int flip = 0;

		if (option_speedlimit)
		{
			TICKER target = this_frame_base + (int)((float)frameskip_counter * PSP_TICKS_PER_FRAME);

			if (option_vsync)
			{
				if (curr < target - 100)
				{
					video_flip_screen(1);
					flip = 1;
				}
			}

			while (curr < target)
				curr = ticker();
		}
		if (!flip) video_flip_screen(0);

		rendered_frames_since_last_fps++;

		if (frameskip_counter == 0)
		{
			float seconds_elapsed = (float)(curr - last_skipcount0_time) * (1.0 / 1000000.0);
			float frames_per_sec = (float)frames_since_last_fps / seconds_elapsed;

			game_speed_percent = (int)(100.0 * frames_per_sec / PSP_REFRESH_RATE + 0.5);
			frames_per_second = (int)((float)rendered_frames_since_last_fps / seconds_elapsed + 0.5);

			last_skipcount0_time = curr;
			frames_since_last_fps = 0;
			rendered_frames_since_last_fps = 0;

			if (option_autoframeskip)
			{
				if (option_speedlimit && frames_displayed > 2 * FRAMESKIP_LEVELS)
				{
					if (game_speed_percent >= 99)
					{
						frameskipadjust++;

						if (frameskipadjust >= 3)
						{
							frameskipadjust = 0;
							if (frameskip > 0) frameskip--;
						}
					}
					else
					{
						if (game_speed_percent < 80)
						{
							frameskipadjust -= (90 - game_speed_percent) / 5;
						}
						else if (frameskip < 8)
						{
							frameskipadjust--;
						}

						while (frameskipadjust <= -2)
						{
							frameskipadjust += 2;
							if (frameskip < FRAMESKIP_LEVELS - 1)
								frameskip++;
						}
					}
				}
			}
		}
	}

	frameskip_counter = (frameskip_counter + 1) % FRAMESKIP_LEVELS;
}
Example #24
0
void* Reap_CPU_XPM_mtrlt(void* param)
{

	Reap_CPU_param* state = (Reap_CPU_param*)param;

	Work tempwork;
	tempwork.time = 13371337;

	//uchar tempdata[80];
	//memset(tempdata, 0, 80);

	uchar finalhash[32];
	uchar temphash[32];
	uchar hash_results[1] = {};

	uint current_server_id;
	
	uint starttime = ticker();
	uint currenttime = starttime;
	
	uint foundprimes=0;

	while(!shutdown_now)
	{
		if (current_work.old)
		{
			Wait_ms(20);
			continue;
		}
		if (tempwork.time != current_work.time)
		{
			pthread_mutex_lock(&current_work_mutex);
			tempwork = current_work;
			pthread_mutex_unlock(&current_work_mutex);
			//memcpy(tempdata, &tempwork.data[0], 80);

			*(uint*)&tempwork.data[76] = state->thread_id<<28;
			current_server_id = tempwork.server_id;

		}


		uint trues=0;
		
		for(uint h=0; h<CPU_BATCH_SIZE; ++h)
		{
			bool result = MinePrime(state,tempwork);
			if (result) 
			{
				foundprimes++;
			}
			
			++*(uint*)&tempwork.data[76];
		}
		//cout << "Every " << double(CPU_BATCH_SIZE)/double(trues) << "th num is true" << endl;

		state->hashes += CPU_BATCH_SIZE;
	}
	pthread_exit(NULL);
	return NULL;
}
Example #25
0
void GameOfLife::development()
{

  wchar_t **prevLattice = lattices[latticeIndex];
  wchar_t **nextLattice = lattices[ ( latticeIndex+1 ) %2];

  /*
  std::string hello1 = "I am Samu. I am a disembodied developmental robotic agent.";
  std::string hello2 = "I am Norbi Batfai. I am an embodied human being from Earth.";
  */
  /*
  std::vector<std::string> hello =
  {
    // http://waldron.stanford.edu/~babylab/pdfs/Tardifetal2008.pdf
    "Daddy",
    "Mommy",
    "BaaBaa",
    "Bye",
    "Hi",
    "UhOh",
    "Grr",
    "Bottle",
    "YumYum",
    "Dog",
    "No",
    "WoofWoof",
    "Vroom",
    "Kitty",
    "Ball",
    "Baby",
    "Duck",
    "Cat",
    "Ouch",
    "Banana"
  };
  */
  /*
  std::vector<std::string> hello =
  {
    // Rebecca Sitton's word list of 1200 high frequency words
    // http://www.glassboroschools.us/cms/lib010/NJ01000249/Centricity/Domain/16/1200wordlisthigh%20frequency.pdf
    // http://www.schools.utah.gov/CURR/langartelem/Core/Literacy/1200Words.aspx
    "the",
    "of",
    "and",
    "a",
    "to",
    "in",
    "is",
    "you",
    "that",
    "it",
    "he",
    "for",
    "was",
    "on",
    "are",
    "as",
    "with",
    "his",
    "they",
    "at",
    "be",
    "this",
    "from",
    "I",
    "have",
    "or",
    "by",
    "one",
    "had",
    "not",
    "but",
    "what",
    "all",
    "were",
    "when",
    "we",
    "there",
    "can",
    "an",
    "your",
    "which",
    "their",
    "said",
    "if",
    "do",
    "will",
    "each",
    "about",
    "how",
    "up",
    "out",
    "them",
    "then",
    "she",
    "many",
    "some",
    "so",
    "these",
    "would",
    "other",
    "into",
    "has",
    "more",
    "her",
    "two",
    "like",
    "him",
    "see",
    "time",
    "could",
    "no",
    "make",
    "than",
    "first",
    "been",
    "its",
    "who",
    "now",
    "people",
    "my",
    "made",
    "over",
    "did",
    "down",
    "only",
    "way",
    "find",
    "use",
    "may",
    "water",
    "long",
    "little",
    "very",
    "after",
    "words",
    "called",
    "just",
    "where",
    "most",
    "know",
    "get",
    "through",
    "back",
    "much",
    "go",
    "good",
    "new",
    "write",
    "our",
    "me",
    "man",
    "too",
    "any",
    "day",
    "same",
    "right",
    "look",
    "think",
    "also",
    "around",
    "another",
    "came",
    "come",
    "work",
    "three",
    "must",
    "because",
    "does",
    "part",
    "even",
    "place",
    "well",
    "such",
    "here",
    "take",
    "why",
    "help",
    "put",
    "different",
    "away",
    "again",
    "off",
    "went",
    "old",
    "number",
    "great",
    "tell",
    "men",
    "say",
    "small",
    "every",
    "found",
    "still",
    "between",
    "mane",
    "should",
    "home",
    "big",
    "give",
    "air",
    "line",
    "set",
    "own",
    "under",
    "read",
    "last",
    "never",
    "us",
    "left",
    "end",
    "along",
    "while",
    "might",
    "next",
    "sound",
    "below",
    "saw",
    "something",
    "thought",
    "both",
    "few",
    "those",
    "always",
    "show",
    "large",
    "often",
    "together",
    "asked",
    "house",
    "don't",
    "world",
    "going",
    "want",
    "school",
    "important",
    "until",
    "form",
    "food",
    "keep",
    "children",
    "feet",
    "land",
    "side",
    "without",
    "boy",
    "once",
    "animal",
    "life",
    "enough",
    "took",
    "four",
    "head",
    "above",
    "kind",
    "began",
    "almost",
    "live",
    "page",
    "got",
    "earth",
    "need",
    "far",
    "hand",
    "high",
    "year",
    "mother",
    "light",
    "country",
    "father",
    "let",
    "night",
    "picture",
    "being",
    "study",
    "second",
    "soon",
    "story",
    "since",
    "white",
    "ever",
    "paper",
    "hard",
    "near",
    "sentence",
    "better",
    "best",
    "across",
    "during",
    "today",
    "however",
    "sure",
    "knew",
    "it's",
    "try",
    "told",
    "young",
    "sun",
    "thing",
    "whole",
    "hear",
    "example",
    "heard",
    "several",
    "change",
    "answer",
    "room",
    "sea",
    "against",
    "top",
    "turned",
    "learn",
    "point",
    "city",
    "play",
    "toward",
    "five",
    "himself",
    "usually",
    "money",
    "seen",
    "didn't",
    "car",
    "morning",
    "I'm",
    "body",
    "upon",
    "family",
    "later",
    "turn",
    "move",
    "face",
    "door",
    "cut",
    "done",
    "group",
    "true",
    "half",
    "red",
    "fish",
    "plants",
    "living",
    "black",
    "eat",
    "short",
    "United",
    "run",
    "book",
    "gave",
    "order",
    "open",
    "ground",
    "cold",
    "really",
    "table",
    "remember",
    "tree",
    "course",
    "front",
    "American",
    "space",
    "inside",
    "ago",
    "sad",
    "early",
    "I'll",
    "learned",
    "brought",
    "close",
    "nothing",
    "though",
    "idea",
    "before",
    "lived",
    "became",
    "add",
    "become",
    "grow",
    "draw",
    "yet",
    "less",
    "wind",
    "behind",
    "cannot",
    "letter",
    "among",
    "able",
    "dog",
    "shown",
    "mean",
    "English",
    "rest",
    "perhaps",
    "certain",
    "six",
    "feel",
    "fire",
    "ready",
    "green",
    "yes",
    "built",
    "special",
    "ran",
    "full",
    "town",
    "complete",
    "oh",
    "person",
    "hot",
    "anything",
    "hold",
    "state",
    "list",
    "stood",
    "hundred",
    "ten",
    "fast",
    "felt",
    "kept",
    "notice",
    "can't",
    "strong",
    "voice",
    "probably",
    "area",
    "horse",
    "matter",
    "stand",
    "box",
    "start",
    "that's",
    "class",
    "piece",
    "surface",
    "river",
    "common",
    "stop",
    "am",
    "talk",
    "whether",
    "fine",
    "round",
    "dark",
    "past",
    "ball",
    "girl",
    "road",
    "blue",
    "instead",
    "either",
    "held",
    "already",
    "warm",
    "gone",
    "finally",
    "summer",
    "understand",
    "moon",
    "animals",
    "mind",
    "outside",
    "power",
    "problem",
    "longer",
    "winter",
    "deep",
    "heavy",
    "carefully",
    "follow",
    "beautiful",
    "everyone",
    "leave",
    "everything",
    "game",
    "system",
    "bring",
    "watch",
    "shell",
    "dry",
    "within",
    "floor",
    "ice",
    "ship",
    "themselves",
    "begin",
    "fact",
    "third",
    "quite",
    "carry",
    "distance",
    "although",
    "sat",
    "possible",
    "heart",
    "real",
    "simple",
    "snow",
    "rain",
    "suddenly",
    "easy",
    "leaves",
    "lay",
    "size",
    "wild",
    "weather",
    "miss",
    "pattern",
    "sky",
    "walked",
    "main",
    "someone",
    "center",
    "field",
    "stay",
    "itself",
    "boat",
    "question",
    "wide",
    "least",
    "tiny",
    "hour",
    "happened",
    "foot",
    "care",
    "low",
    "else",
    "gold",
    "build",
    "glass",
    "rock",
    "tall",
    "alone",
    "bottom",
    "check",
    "reading",
    "fall",
    "poor",
    "map",
    "friend",
    "language",
    "job",
    "music",
    "buy",
    "window",
    "mark",
    "heat",
    "grew",
    "listen",
    "ask",
    "single",
    "clear",
    "energy",
    "week",
    "explain",
    "lost",
    "spring",
    "travel",
    "wrote",
    "farm",
    "circle",
    "whose",
    "correct",
    "bed",
    "measure",
    "straight",
    "base",
    "mountain",
    "caught",
    "hair",
    "bird",
    "wood",
    "color",
    "war",
    "fly",
    "yourself",
    "seem",
    "thus",
    "square",
    "moment",
    "teacher",
    "happy",
    "bright",
    "sent",
    "present",
    "plan",
    "rather",
    "length",
    "speed",
    "machine",
    "information",
    "except",
    "figure",
    "you're",
    "free",
    "fell",
    "suppose",
    "natural",
    "ocean",
    "government",
    "baby",
    "grass",
    "plane",
    "street",
    "couldn't",
    "reason",
    "difference",
    "maybe",
    "history",
    "mouth",
    "middle",
    "step",
    "child",
    "strange",
    "wish",
    "soil",
    "human",
    "trip",
    "woman",
    "eye",
    "milk",
    "choose",
    "north",
    "seven",
    "famous",
    "late",
    "pay",
    "sleep",
    "iron",
    "trouble",
    "store",
    "beside",
    "oil",
    "modern",
    "fun",
    "catch",
    "business",
    "reach",
    "lot",
    "won't",
    "case",
    "speak",
    "shape",
    "eight",
    "edge",
    "soft",
    "village",
    "object",
    "age",
    "minute",
    "wall",
    "meet",
    "record",
    "copy",
    "forest",
    "especially",
    "necessary",
    "he's",
    "unit",
    "flat",
    "direction",
    "south",
    "subject",
    "skin",
    "wasn't",
    "I've",
    "yellow",
    "party",
    "force",
    "test",
    "bad",
    "temperature",
    "pair",
    "ahead",
    "wrong",
    "practice",
    "sand",
    "tail",
    "wait",
    "difficult",
    "general",
    "cover",
    "material",
    "isn't",
    "thousand",
    "sign",
    "guess",
    "forward",
    "huge",
    "ride",
    "region",
    "nor",
    "period",
    "blood",
    "rich",
    "team",
    "corner",
    "cat",
    "amount",
    "garden",
    "led",
    "note",
    "various",
    "race",
    "bit",
    "result",
    "brother",
    "addition",
    "doesn't",
    "dead",
    "weight",
    "thin",
    "stone",
    "hit",
    "wife",
    "island",
    "we'll",
    "opposite",
    "born",
    "sense",
    "cattle",
    "million",
    "anyone",
    "rule",
    "science",
    "afraid",
    "women",
    "produce",
    "pull",
    "son",
    "meant",
    "broken",
    "interest",
    "chance",
    "thick",
    "sight",
    "pretty",
    "train",
    "fresh",
    "drive",
    "lead",
    "break",
    "sit",
    "bought",
    "radio",
    "method",
    "king",
    "similar",
    "return",
    "corn",
    "decide",
    "position",
    "bear",
    "hope",
    "song",
    "engine",
    "board",
    "control",
    "spread",
    "evening",
    "brown",
    "clean",
    "wouldn't",
    "section",
    "spent",
    "ring",
    "teeth",
    "quiet",
    "ancient",
    "stick",
    "afternoon",
    "silver",
    "nose",
    "century",
    "therefore",
    "level",
    "you'll",
    "death",
    "hole",
    "coast",
    "cross",
    "sharp",
    "fight",
    "capital",
    "fill",
    "deal",
    "busy",
    "beyond",
    "send",
    "love",
    "cool",
    "cause",
    "please",
    "meat",
    "lady",
    "west",
    "glad",
    "action",
    "pass",
    "type",
    "attention",
    "gas",
    "kitchen",
    "pick",
    "scale",
    "basic",
    "happen",
    "safe",
    "grown",
    "cost",
    "wear",
    "act",
    "hat",
    "arm",
    "believe",
    "major",
    "gray",
    "wonder",
    "include",
    "describe",
    "electric",
    "sold",
    "visit",
    "sheep",
    "I'd",
    "office",
    "row",
    "contain",
    "fit",
    "equal",
    "value",
    "yard",
    "beat",
    "inch",
    "sugar",
    "key",
    "product",
    "desert",
    "bank",
    "farther",
    "won",
    "total",
    "sell",
    "wire",
    "rose",
    "cotton",
    "spoke",
    "rope",
    "fear",
    "shore",
    "throughout",
    "compare",
    "movement",
    "exercise",
    "bread",
    "process",
    "nature",
    "apart",
    "path",
    "careful",
    "narrow",
    "mental",
    "nine",
    "useful",
    "public",
    "according",
    "steel",
    "salt",
    "speech",
    "forth",
    "nation",
    "knowledge",
    "appear",
    "ate",
    "dinner",
    "hurt",
    "spend",
    "experiment",
    "touch",
    "drop",
    "chair",
    "east",
    "separate",
    "truck",
    "sing",
    "column",
    "twice",
    "particular",
    "shop",
    "unless",
    "spot",
    "neither",
    "met",
    "wheel",
    "none",
    "hill",
    "television",
    "bill",
    "solve",
    "pressure",
    "report",
    "farmer",
    "count",
    "trade",
    "chief",
    "month",
    "clothes",
    "doctor",
    "indeed",
    "dance",
    "church",
    "original",
    "enjoy",
    "string",
    "sister",
    "familiar",
    "onto",
    "imagine",
    "blow",
    "quick",
    "law",
    "lie",
    "final",
    "rise",
    "loud",
    "fair",
    "herself",
    "slow",
    "noise",
    "statement",
    "hungry",
    "join",
    "tube",
    "rode",
    "empty",
    "twenty",
    "broke",
    "nice",
    "effect",
    "paid",
    "motion",
    "myself",
    "divide",
    "supply",
    "laid",
    "dear",
    "surprise",
    "gun",
    "entire",
    "fruit",
    "crowd",
    "band",
    "wet",
    "solid",
    "northern",
    "flower",
    "star",
    "feed",
    "wooden",
    "sort",
    "develop",
    "shoulder",
    "variety",
    "season",
    "share",
    "jump",
    "regular",
    "represent",
    "market",
    "we're",
    "flew",
    "finger",
    "expect",
    "army",
    "cabin",
    "camp",
    "danger",
    "purpose",
    "breakfast",
    "proper",
    "coat",
    "push",
    "express",
    "shot",
    "angry",
    "southern",
    "dress",
    "bag",
    "proud",
    "neck",
    "breath",
    "strength",
    "member",
    "twelve",
    "mine",
    "company",
    "current",
    "pound",
    "valley",
    "double",
    "till",
    "match",
    "average",
    "die",
    "liquid",
    "alive",
    "stream",
    "provide",
    "drink",
    "experience",
    "future",
    "tomorrow",
    "drove",
    "population",
    "finish",
    "station",
    "shook",
    "stage",
    "oxygen",
    "poem",
    "solution",
    "burn",
    "cent",
    "electricity",
    "everybody",
    "rate",
    "dust",
    "worth",
    "community",
    "captain",
    "bus",
    "protect",
    "cook",
    "raise",
    "further",
    "steam",
    "guide",
    "discover",
    "plain",
    "usual",
    "seat",
    "accept",
    "police",
    "consider",
    "dozen",
    "baseball",
    "rubber",
    "symbol",
    "support",
    "exactly",
    "industry",
    "they're",
    "beneath",
    "laugh",
    "groceries",
    "popular",
    "thank",
    "quarter",
    "climbed",
    "continue",
    "potatoes",
    "receive",
    "design",
    "president",
    "wchar_tge",
    "mistake",
    "hospital",
    "remain",
    "service",
    "increase",
    "students",
    "insects",
    "address",
    "sincerely",
    "dollars",
    "belong",
    "bottle",
    "flight",
    "forget",
    "bicycle",
    "secret",
    "soldier",
    "silent",
    "structure",
    "height",
    "observe",
    "indicate",
    "railroad",
    "knife",
    "married",
    "suggested",
    "entered",
    "magazine",
    "agree",
    "fifty",
    "escape",
    "threw",
    "planet",
    "dangerous",
    "event",
    "leader",
    "peace",
    "spelling",
    "chapter",
    "swimming",
    "opportunity",
    "immediately",
    "favorite",
    "settled",
    "telephone",
    "repeat",
    "prepare",
    "instance",
    "avenue",
    "newspaper",
    "actually",
    "employee",
    "review",
    "convince",
    "allowed",
    "nobody",
    "details",
    "muscles",
    "model",
    "climate",
    "coffee",
    "whenever",
    "serious",
    "angle",
    "feather",
    "determined",
    "dictionary",
    "ordinary",
    "extra",
    "rough",
    "library",
    "condition",
    "arrived",
    "located",
    "program",
    "pencil",
    "tongue",
    "title",
    "enemy",
    "garage",
    "lose",
    "vegetable",
    "parents",
    "style",
    "education",
    "required",
    "political",
    "daughter",
    "individual",
    "progress",
    "altogether",
    "activities",
    "article",
    "equipment",
    "discuss",
    "healthy",
    "perfect",
    "recognize",
    "frequently",
    "wchar_tacter",
    "personal",
    "disappear",
    "success",
    "traffic",
    "yesterday",
    "situation",
    "realize",
    "message",
    "recently",
    "account",
    "physical",
    "neighbor",
    "excited",
    "whisper",
    "available",
    "college",
    "furniture",
    "leather",
    "husband",
    "principal",
    "medicine",
    "excellent",
    "operation",
    "council",
    "author",
    "organize",
    "concern",
    "barbecue",
    "accident",
    "disease",
    "construction",
    "motor",
    "affect",
    "conversation",
    "evidence",
    "citizen",
    "environment",
    "influence",
    "cancel",
    "audience",
    "apartment",
    "worse",
    "transportation",
    "frozen",
    "waste",
    "couple",
    "function",
    "connect",
    "project",
    "pronounce",
    "offered",
    "apply",
    "improve",
    "stomach",
    "collect",
    "prevent",
    "courage",
    "occur",
    "foreign",
    "quality",
    "terrible",
    "instrument",
    "balance",
    "ability",
    "arrange",
    "rhythm",
    "avoid",
    "daily",
    "identity",
    "standard",
    "combine",
    "attached",
    "frighten",
    "social",
    "factory",
    "license",
    "recommend"

  };
  */


  //if ( age <2 )
    {
      clear_lattice ( nextLattice );

      if ( samuBrain->isLearned() )
        {
          ++age;
          xx = m_w;
        }

      int ind =  age % hello.size();
      qDebug() << m_time
      << age 
               << "   WORD:" << ind << hello[ind].c_str()
               << "Observation (MPU):" << samuBrain->get_foobar().c_str();

      ticker ( nextLattice, hello[ind] );
    }

    /*
  if ( m_time < 12000 )
    {
    ticker ( nextLattice, hello1 );
  }
  else if ( m_time < 34000 )
    {
  ticker ( nextLattice, hello2);
    }
  else
    {
      m_time = -1;
    }
  */

  /*

  if ( m_time == 1 )
    {
      //clear_lattice ( nextLattice );

      glider ( nextLattice, 2*m_w/5, 2*m_h/5 );
      glider ( nextLattice, 3*m_w/5, 3*m_h/5 );
      glider ( nextLattice, 4*m_w/5, 4*m_h/5 );
      glider ( nextLattice, 4*m_w/5, 2*m_h/5 );
      glider ( nextLattice, 2*m_w/5, 4*m_h/5 );

    }
  else if ( m_time < 5000 )
    {
      control_Conway ( prevLattice, nextLattice );
    }
  else if ( m_time < 13000 )
    {
      control_Stroop ( nextLattice );
    }
  else if ( m_time < 22000 )
    {
      control_Movie ( nextLattice );
    }
  else
    {
      m_time = -1;
    }

    */

}
Example #26
0
// FIXME: maybe mmap isn't such a good idea for giant files?
int main(int argc, char *argv[])
{
    int i, out, count;
    MPEG2Parser *mpeg2parser;


    // check for our arguments
#ifdef WRITEOUT
    if (argc < 3)
    {
        fprintf(stderr, _("Usage: %s INPUT OUTPUT\n"), argv[0]);
        exit(1);
    }
#else // WRITEOUT
    if (argc < 2)
    {
        fprintf(stderr, _("Usage: %s INPUT\n"), argv[0]);
        exit(1);
    }
#endif // WRITEOUT

    decode_init();

    mpeg2parser = new MPEG2Parser();
    if (!mpeg2parser->init(argv[1], ticker))
    {
        fprintf(stderr, "%s\n", mpeg2parser->getError());
        exit(1);
    }

    mpeg2parser->parse();

    if (mpeg2parser->getError())
        fprintf(stderr, "%s\n", mpeg2parser->getError());

#ifdef WRITEOUT
    // open our output file for writing
    if ((out = open(argv[2], O_WRONLY | O_CREAT | O_EXCL | O_LARGEFILE,
                    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0)
    {
        perror(argv[2]);
        exit(1);
    }
#endif // WRITEOUT


    List *GOPs = mpeg2parser->getGOPs();

    printf(_("GOPs: %d\n"), GOPs->getNum());

#ifdef RENDEROUT
    int GOPmax = GOPs->getNum();
    for (i = 0; i < GOPmax; i++)
    {
        Pack *packet;
        GroupOfPictures *GOP;
        Bounds *bounds;
        ElementStream *ves;
        int start, stop;
        int ves_start, ves_stop;

        uint8_t *loc;
        size_t len;

        ticker(_("Rendering GOPs"), (float) ((float) i / (float) GOPmax));

        GOP = (GroupOfPictures *) GOPs->vector(i);

        bounds = GOP->getPacketBounds();
        start = bounds->getFirst();
        stop = bounds->getMax();

        for (int j = start; j < stop; j++)
        {
            if (!(packet = (Pack *) mpeg2parser->getPackets()->vector(j)))
            {
                printf("%s", _("NULL packet?!\n"));
                exit(1);
            }

            ves_start = packet->getVideoFirst();
            ves_stop = packet->getVideoMax();

#ifdef WRITEOUT
            /* write packets to disk */
            if (loc =
                mpeg2parser->bytesAvail(packet->getStart(), packet->getLen()))
            {
                write(out, loc, packet->getLen());
            }
            else
                printf("%s", _("NULL vector area?!\n"));
#endif // WRITEOUT

            for (int k = ves_start; k < ves_stop; k++)
            {
                if (!
                    (ves =
                     (ElementStream *) mpeg2parser->getVideo()->vector(k)))
                {
                    printf("%s", _("NULL ves?!\n"));
                    exit(1);
                }
#ifdef WATCHOUT
                len = ves->getLen();
                (void *) loc = mpeg2parser->bytesAvail(ves->getStart(), len);
                if (loc && len)
                {
                    printf("%" OFF_T_FORMAT ": %ld\n", ves->getStart(), len);
                    fflush(NULL);
                    mpeg2_decode_data(&mpeg2dec, loc, loc + len);
                }
#endif // WATCHOUT
            }
        }
    }
    ticker("Rendering GOPs", 1.0);
#endif // RENDEROUT

    /*
       printf("%s",_("dumping audio ES...\n"));
       for (i=0;i<audio_list->getNum();i++)
       {
       ElementStream * audio;

       if (!(audio=(ElementStream*)audio_list->vector(i)))
       {
       Error("NULL audio vector?!");
       exit(1);
       }

       write(out,audio->getStart(),audio->getLen());
       }

       // close outfile
       close(out);

     */

    /*
       char user[512];

       printf(_("view GOPs avail: 0-%d\n"),pack_list->getNum()-1);
       printf("%s",_("Dump which GOP? "));
       fflush(NULL);
       while (fgets(user,512,stdin))
       {
       int which;
       int first, last;

       which=atoi(user);

       if (which<pack_list->getNum())
       {
       Pack * pack;
       ElementStream * video;

       if ((pack=(Pack*)pack_list->vector(which)))
       {
       first=pack->getMin();
       last=pack->getMax();

       printf(_("Showing ES %d to %d...\n"),
       first,last);
       for (i=first;i<last;i++)
       {

       if ((video=(ElementStream*)video_list->vector(i)))
       {

       mpeg2_decode_data(&mpeg2dec,
       video->getStart(),
       video->getStart()+
       video->getLen());
       }
       else
       Error("ES not found");
       }
       }
       else
       Error("Pack not found");
       }

       printf("%s",_("Dump which GOP? "));
       fflush(NULL);
       }
     */

#ifdef WRITEOUT
    close(out);
#endif

#if 0
    printf("%s", _("press enter to quit..."));
    fflush(NULL);
    char userin[128];
    fgets(userin, 128, stdin);
#endif

    // shutdown decoder
    mpeg2_close(&mpeg2dec);
    vo_close(output);

    // shutdown parser
    delete mpeg2parser;

    return 0;
}
Example #27
0
int main(int argc, char** argv) {

  //auto resolution = gua::math::vec2ui(800, 600);
  auto resolution = gua::math::vec2ui(3840, 2160);

  // initialize guacamole
  int argc_d = 0;
  char** argv_d = {};
  gua::init(argc_d, argv_d);

  // setup scene
  gua::SceneGraph graph("main_scenegraph");

  auto desc(std::make_shared<gua::MaterialShaderDescription>());
  desc->load_from_file("data/materials/SimpleMaterial.gmd");

  auto shader(std::make_shared<gua::MaterialShader>("simple_mat", desc));
  gua::MaterialShaderDatabase::instance()->add(shader);

  auto mat(shader->make_new_material());

  gua::TriMeshLoader trimeshloader;

  auto teapot_geode(
      trimeshloader.create_geometry_from_file("teapot_geode",
                                              "data/objects/teapot.obj",
                                              mat,
                                              gua::TriMeshLoader::DEFAULTS));
  auto plate_geode(
      trimeshloader.create_geometry_from_file("plate_geode",
                                              "data/objects/plate.obj",
                                              mat,
                                              gua::TriMeshLoader::DEFAULTS));

  auto head = graph.add_node<gua::node::TransformNode>("/", "head");
  head->translate(0.0, 0.0, 8.0);

  auto teapot = graph.add_node<gua::node::TransformNode>("/", "teapot");
  teapot->scale(2.0f);
  auto plate = graph.add_node<gua::node::TransformNode>("/", "plate");

  graph.add_node("/teapot", teapot_geode);
  graph.add_node("/plate", plate_geode);

  const float aspect = resolution.x * 1.0f / resolution.y;

  auto pipe = std::make_shared<gua::PipelineDescription>();

  pipe->add_pass(std::make_shared<gua::TriMeshPassDescription>());
  pipe->add_pass(std::make_shared<gua::TexturedQuadPassDescription>());
  //pipe->add_pass(std::make_shared<gua::BBoxPassDescription>());
  pipe->add_pass(std::make_shared<gua::LightVisibilityPassDescription>());
  pipe->add_pass(std::make_shared<gua::ResolvePassDescription>());
  //pipe->add_pass(std::make_shared<gua::SSAAPassDescription>());
  //pipe->add_pass(std::make_shared<gua::DebugViewPassDescription>());

  auto camera_tl =
      graph.add_node<gua::node::CameraNode>("/head", "camera_tl");
  camera_tl->config.set_output_window_name("window_tl");
  camera_tl->config.set_screen_path("/head/camera_tl/screen_tl");
  camera_tl->config.set_scene_graph_name("main_scenegraph");
  camera_tl->config.set_resolution(resolution);
  camera_tl->config.set_view_id(1);
  camera_tl->set_pipeline_description(pipe);

  auto screen_tl = graph.add_node<gua::node::ScreenNode>("/head/camera_tl", "screen_tl");
  screen_tl->data.set_size(gua::math::vec2(1.6, 0.9));
  screen_tl->translate(-0.8, 0.45, -2.5);

  auto camera_tr =
      graph.add_node<gua::node::CameraNode>("/head", "camera_tr");
  camera_tr->config.set_output_window_name("window_tr");
  camera_tr->config.set_screen_path("/head/camera_tr/screen_tr");
  camera_tr->config.set_scene_graph_name("main_scenegraph");
  camera_tr->config.set_resolution(resolution);
  camera_tr->config.set_view_id(2);
  camera_tr->set_pipeline_description(pipe);

  auto screen_tr = graph.add_node<gua::node::ScreenNode>("/head/camera_tr", "screen_tr");
  screen_tr->data.set_size(gua::math::vec2(1.6, 0.9));
  screen_tr->translate( 0.8f, 0.45, -2.5f);

  auto camera_bl =
      graph.add_node<gua::node::CameraNode>("/head", "camera_bl");
  camera_bl->config.set_output_window_name("window_bl");
  camera_bl->config.set_screen_path("/head/camera_bl/screen_bl");
  camera_bl->config.set_scene_graph_name("main_scenegraph");
  camera_bl->config.set_resolution(resolution);
  //camera_bl->config.set_view_id(2);
  camera_bl->set_pipeline_description(pipe);

  auto screen_bl = graph.add_node<gua::node::ScreenNode>("/head/camera_bl", "screen_bl");
  screen_bl->data.set_size(gua::math::vec2(1.6, 0.9));
  screen_bl->translate(-0.8, -0.45, -2.5f);

  auto camera_br =
      graph.add_node<gua::node::CameraNode>("/head", "camera_br");
  camera_br->config.set_output_window_name("window_br");
  camera_br->config.set_screen_path("/head/camera_br/screen_br");
  camera_br->config.set_scene_graph_name("main_scenegraph");
  camera_br->config.set_resolution(resolution);
  camera_br->set_pipeline_description(pipe);

  auto screen_br = graph.add_node<gua::node::ScreenNode>("/head/camera_br", "screen_br");
  screen_br->data.set_size(gua::math::vec2(1.6, 0.9));
  screen_br->translate( 0.8, -0.45, -2.5f);

  auto pointlight = graph.add_node<gua::node::LightNode>("/", "pointlight");
  pointlight->data.set_type(gua::node::LightNode::Type::POINT);
  pointlight->scale(30.0f);
  pointlight->rotate(-90, 1, 0, 0);
  pointlight->translate(1.0, 18.0, 1.0);

  pointlight->data.set_falloff(0.1f);
  pointlight->data.set_color({
    1.0f, 1.0f, 1.0f
  });
  pointlight->data.set_enable_specular_shading(true);
  pointlight->data.set_enable_diffuse_shading(true);

  auto add_window =
      [](std::string const & window_name,
         std::string const & display,
         std::shared_ptr<gua::node::CameraNode> const & cam_node) {
    auto window = std::make_shared<gua::Window>();
    window->config.set_display_name(display);
    window->join_swap_group(1);
    window->bind_swap_barrier(1);
    gua::WindowDatabase::instance()->add(window_name, window);
    set_window_default(window, cam_node->config.get_resolution());
    cam_node->config.set_output_window_name(window_name);
  };

  add_window("window_tl", ":0.0", camera_tl);

  gua::Renderer renderer;

  // application loop
  gua::events::MainLoop loop;

  gua::events::Ticker ticker(loop, 1.0 / 500.0);

  //gua::Timer frame_timer;
  //frame_timer.start();

  float time_value = 0;

  // application loop
  std::size_t cnt = 0;
  //while (true) {
    //std::this_thread::sleep_for(std::chrono::milliseconds(10));
  ticker.on_tick.connect([&]() {

    teapot_geode->rotate(0.3, 0, 1, 0);

    ++cnt;

    if (cnt == 10) {
      //add_window("window_tr", ":0.0", camera_tr);
      add_window("window_tr", ":0.1", camera_tr);
    }
    if (cnt == 20) {
      //add_window("window_bl", ":0.0", camera_bl);
      add_window("window_bl", ":0.2", camera_bl);
    }
    if (cnt == 30) {
      //add_window("window_br", ":0.0", camera_br);
      add_window("window_br", ":0.3", camera_br);
    }

    // GLFW only allows event processing from main thread
    if (gua::WindowDatabase::instance()->lookup("window_tl")) {
      gua::WindowDatabase::instance()->lookup("window_tl")->process_events();
    }

    if (gua::WindowDatabase::instance()->lookup("window_tr")) {
      gua::WindowDatabase::instance()->lookup("window_tr")->process_events();
    }

    if (gua::WindowDatabase::instance()->lookup("window_bl")) {
      gua::WindowDatabase::instance()->lookup("window_bl")->process_events();
    }

    if (gua::WindowDatabase::instance()->lookup("window_br")) {
      gua::WindowDatabase::instance()->lookup("window_br")->process_events();
    }

    plate->translate(-plate->get_bounding_box().center());
    plate->rotate(0.04f, 0, 1, 0);
    plate->translate(plate->get_bounding_box().center());

    renderer.queue_draw({
      &graph
    });
  });
  //}
  loop.start();
  renderer.stop();

  return 0;
}
Example #28
0
int main(int argc, char** argv) {
  // initialize guacamole
  gua::init(argc, argv);

  // setup scene
  gua::SceneGraph graph("main_scenegraph");

  gua::TriMeshLoader loader;

  auto teapot_mat(gua::MaterialShaderDatabase::instance()
                  ->lookup("gua_default_material")
                  ->make_new_material());

  teapot_mat->set_render_wireframe(false);
  teapot_mat->set_show_back_faces(false);

  auto transform = graph.add_node<gua::node::TransformNode>("/", "transform");
  auto teapot(loader.create_geometry_from_file(
      "teapot", "data/objects/teapot.obj",
      teapot_mat,
      gua::TriMeshLoader::NORMALIZE_POSITION |
      gua::TriMeshLoader::NORMALIZE_SCALE) );

  graph.add_node("/transform", teapot);
  teapot->set_draw_bounding_box(true);

  auto portal = graph.add_node<gua::node::TexturedQuadNode>("/", "portal");
  portal->data.set_size(gua::math::vec2(1.2f, 0.8f));
  portal->data.set_texture("portal");
  portal->translate(0.5f, 0.f, -0.2f);
  portal->rotate(-30, 0.f, 1.f, 0.f);

  auto light2 = graph.add_node<gua::node::LightNode>("/", "light2");
  light2->data.set_type(gua::node::LightNode::Type::POINT);
  light2->data.brightness = 150.0f;
  light2->scale(12.f);
  light2->translate(-3.f, 5.f, 5.f);

  auto screen = graph.add_node<gua::node::ScreenNode>("/", "screen");
  screen->data.set_size(gua::math::vec2(1.92f, 1.08f));
  screen->translate(0, 0, 1.0);

  auto portal_screen =
      graph.add_node<gua::node::ScreenNode>("/", "portal_screen");
  portal_screen->translate(0.0, 0.0, 5.0);
  portal_screen->rotate(90, 0.0, 1.0, 0.0);
  portal_screen->data.set_size(gua::math::vec2(1.2f, 0.8f));

  // add mouse interaction
  gua::utils::Trackball trackball(0.01, 0.002, 0.2);

  // setup rendering pipeline and window
  auto resolution = gua::math::vec2ui(1920, 1080);

  auto portal_camera =
      graph.add_node<gua::node::CameraNode>("/portal_screen", "portal_cam");
  portal_camera->translate(0, 0, 2.0);
  portal_camera->config.set_resolution(gua::math::vec2ui(1200, 800));
  portal_camera->config.set_screen_path("/portal_screen");
  portal_camera->config.set_scene_graph_name("main_scenegraph");
  portal_camera->config.set_output_texture_name("portal");
  portal_camera->config.set_enable_stereo(false);

  auto portal_pipe = std::make_shared<gua::PipelineDescription>();
  portal_pipe->add_pass(std::make_shared<gua::TriMeshPassDescription>());
  portal_pipe->add_pass(
      std::make_shared<gua::LightVisibilityPassDescription>());

  auto resolve_pass = std::make_shared<gua::ResolvePassDescription>();
  resolve_pass->background_mode(
      gua::ResolvePassDescription::BackgroundMode::QUAD_TEXTURE);
  resolve_pass->tone_mapping_exposure(1.0f);

  portal_pipe->add_pass(resolve_pass);
  portal_pipe->add_pass(std::make_shared<gua::DebugViewPassDescription>());

  portal_camera->set_pipeline_description(portal_pipe);

  auto camera = graph.add_node<gua::node::CameraNode>("/screen", "cam");
  camera->translate(0, 0, 2.0);
  camera->config.set_resolution(resolution);
  camera->config.set_screen_path("/screen");
  camera->config.set_scene_graph_name("main_scenegraph");
  camera->config.set_output_window_name("main_window");
  camera->config.set_enable_stereo(false);
  camera->set_pre_render_cameras({portal_camera});

  camera->get_pipeline_description()->get_resolve_pass()->tone_mapping_exposure(
    1.0f);
  camera->get_pipeline_description()->add_pass(
    std::make_shared<gua::DebugViewPassDescription>());

  auto window = std::make_shared<gua::GlfwWindow>();
  gua::WindowDatabase::instance()->add("main_window", window);

  window->config.set_enable_vsync(false);
  window->config.set_size(resolution);
  window->config.set_resolution(resolution);
  window->config.set_stereo_mode(gua::StereoMode::MONO);

  window->on_resize.connect([&](gua::math::vec2ui const& new_size) {
    window->config.set_resolution(new_size);
    camera->config.set_resolution(new_size);
    screen->data.set_size(
        gua::math::vec2(0.001 * new_size.x, 0.001 * new_size.y));
  });
  window->on_move_cursor.connect(
      [&](gua::math::vec2 const& pos) { trackball.motion(pos.x, pos.y); });
  window->on_button_press.connect(
      std::bind(mouse_button, std::ref(trackball), std::placeholders::_1,
                std::placeholders::_2, std::placeholders::_3));

  gua::Renderer renderer;

  // application loop
  gua::events::MainLoop loop;
  gua::events::Ticker ticker(loop, 1.0 / 500.0);

  ticker.on_tick.connect([&]() {

    // apply trackball matrix to object
    gua::math::mat4 modelmatrix =
        scm::math::make_translation(trackball.shiftx(), trackball.shifty(),
                                    trackball.distance()) *
        gua::math::mat4(trackball.rotation());

    transform->set_transform(modelmatrix);

    if (window->should_close()) {
      renderer.stop();
      window->close();
      loop.stop();
    } else {
      renderer.queue_draw({&graph});
    }
  });

  loop.start();

  return 0;
}
Example #29
0
int main(int argc, char** argv) {

  gua::init(argc, argv);


  //create simple untextured material shader
  auto lod_keep_input_desc = std::make_shared<gua::MaterialShaderDescription>("./data/materials/PLOD_use_input_color.gmd");
  auto lod_keep_color_shader(std::make_shared<gua::MaterialShader>("PLOD_pass_input_color", lod_keep_input_desc));
  gua::MaterialShaderDatabase::instance()->add(lod_keep_color_shader);


  //create material for pointcloud
  auto lod_rough = lod_keep_color_shader->make_new_material();
  lod_rough->set_uniform("metalness", 0.2f);
  lod_rough->set_uniform("roughness", 0.4f);
  lod_rough->set_uniform("emissivity", 0.8f);


  //configure lod backend
  gua::LodLoader lod_loader;
  lod_loader.set_out_of_core_budget_in_mb(512);
  lod_loader.set_render_budget_in_mb(512);
  lod_loader.set_upload_budget_in_mb(20);

  //load a sample pointcloud
  auto plod_node = lod_loader.load_lod_pointcloud(
    "pointcloud",
    "/opt/3d_models/lamure/plod/pig_pr.bvh",
    lod_rough,
    gua::LodLoader::NORMALIZE_POSITION | gua::LodLoader::NORMALIZE_SCALE | gua::LodLoader::MAKE_PICKABLE);

  //load a sample mesh-based lod model 
  auto mlod_node = lod_loader.load_lod_trimesh(
    //"tri_mesh", 
    "/opt/3d_models/lamure/mlod/xyzrgb_dragon_7219k.bvh", 
    //plod_rough,
    gua::LodLoader::NORMALIZE_POSITION | gua::LodLoader::NORMALIZE_SCALE/* | gua::LodLoader::MAKE_PICKABLE*/
  );

  mlod_node->set_error_threshold(0.25);

  //setup scenegraph
  gua::SceneGraph graph("main_scenegraph");
  auto scene_transform = graph.add_node<gua::node::TransformNode>("/", "transform");
  auto mlod_transform = graph.add_node<gua::node::TransformNode>("/transform", "mlod_transform");

  auto plod_transform = graph.add_node<gua::node::TransformNode>("/transform", "plod_transform");

  graph.add_node("/transform/mlod_transform", mlod_node);

  graph.add_node("/transform/plod_transform", plod_node);

  mlod_transform->translate(-0.4, 0.0, 0.0);

  plod_transform->rotate(180.0, 0.0, 1.0, 0.0);
  plod_transform->translate(0.3, 0.08, 0.0);

  //create a lightsource
  auto light_transform = graph.add_node<gua::node::TransformNode>("/transform", "light_transform");
  auto light = graph.add_node<gua::node::LightNode>("/transform/light_transform", "light");
  light->data.set_type(gua::node::LightNode::Type::POINT);
  light->data.set_enable_shadows(false);

  light->data.set_shadow_map_size(4096);
  light->data.brightness = 5.0f;
  light->translate(0.f, 0.2f, 0.f);
  light->scale(4.f);
  light->translate(0.f, 0.f, 1.f);


  auto screen = graph.add_node<gua::node::ScreenNode>("/", "screen");
  screen->data.set_size(gua::math::vec2(1.92f, 1.08f));
  screen->translate(0, 0, 1.0);

  //add mouse interaction
  scm::gl::trackball_manipulator trackball;
  trackball.transform_matrix()*scm::math::make_translation(0.01f, 0.002f, 0.2f);
  trackball.dolly(0.2f);
  float dolly_sens = 1.5f;
  gua::math::vec2 trackball_init_pos(0.f);
  gua::math::vec2 last_mouse_pos(0.f);
  int button_state = -1;

  //setup rendering pipeline and window
  auto resolution = gua::math::vec2ui(1920, 1080);

  auto camera = graph.add_node<gua::node::CameraNode>("/screen", "cam");
  camera->translate(0.0f, 0, 2.5f);
  camera->config.set_resolution(resolution);
  
  //use close near plane to allow inspection of details
  //camera->config.set_near_clip(0.01f);
  //camera->config.set_far_clip(200.0f);
  camera->config.set_screen_path("/screen");
  camera->config.set_scene_graph_name("main_scenegraph");
  camera->config.set_output_window_name("main_window");
  camera->config.set_enable_stereo(true);

  auto PLod_Pass = std::make_shared<gua::PLodPassDescription>();

  auto pipe = std::make_shared<gua::PipelineDescription>();
  pipe->add_pass(std::make_shared<gua::MLodPassDescription>());
  pipe->add_pass(PLod_Pass);
  pipe->add_pass(std::make_shared<gua::BBoxPassDescription>());
  pipe->add_pass(std::make_shared<gua::LightVisibilityPassDescription>());
  pipe->add_pass(std::make_shared<gua::ResolvePassDescription>());
  pipe->add_pass(std::make_shared<gua::DebugViewPassDescription>());
  camera->set_pipeline_description(pipe);

  pipe->get_resolve_pass()->tone_mapping_exposure(1.f);
  pipe->get_resolve_pass()->tone_mapping_method(gua::ResolvePassDescription::ToneMappingMethod::UNCHARTED);

  pipe->get_resolve_pass()->background_mode(gua::ResolvePassDescription::BackgroundMode::SKYMAP_TEXTURE);
  pipe->get_resolve_pass()->background_texture("data/textures/envlightmap.jpg");

  //init window and window behaviour
  auto window = std::make_shared<gua::GlfwWindow>();
  gua::WindowDatabase::instance()->add("main_window", window);
  window->config.set_enable_vsync(false);
  window->config.set_size(resolution);
  window->config.set_resolution(resolution);
  window->config.set_stereo_mode(gua::StereoMode::MONO);

  window->on_resize.connect([&](gua::math::vec2ui const& new_size) {
    window->config.set_resolution(new_size);
    camera->config.set_resolution(new_size);
    screen->data.set_size(gua::math::vec2(0.001 * new_size.x, 0.001 * new_size.y));
  });

  //trackball controls
  bool drag_mode = false;
  window->on_move_cursor.connect([&](gua::math::vec2 const& pos) {
    float nx = 2.f * float(pos.x - (resolution.x/2))/float(resolution.x);
    float ny = -2.f * float(resolution.y - pos.y - (resolution.y/2))/float(resolution.y);
    if (button_state != -1) {
      if (drag_mode) {
        auto ssize = screen->data.get_size();
        gua::math::vec3 trans = gua::math::vec3(ssize.x *(nx - last_mouse_pos.x), ssize.y * (ny - last_mouse_pos.y), 0.f);
        auto object_trans = scm::math::inverse(screen->get_world_transform()) * mlod_transform->get_world_transform();
        mlod_transform->set_world_transform(screen->get_world_transform() * scm::math::make_translation(trans) * object_trans);
      }
      else {
        if (button_state == 0) { // left
          trackball.rotation(trackball_init_pos.x, trackball_init_pos.y, nx, ny);
        }
        if (button_state == 1) { // right
          trackball.dolly(dolly_sens*0.5f * (ny - trackball_init_pos.y));
        }
        if (button_state == 2) { // middle
          float f = dolly_sens < 1.0f ? 0.02f : 0.3f;
          trackball.translation(f*(nx - trackball_init_pos.x), f*(ny - trackball_init_pos.y));
        }
        trackball_init_pos.x = nx;
        trackball_init_pos.y = ny;
      }
    }
    last_mouse_pos.x = nx;
    last_mouse_pos.y = ny;
  });

  window->on_button_press.connect([&](int mousebutton, int action, int mods) {
    if (action == 1) {
      drag_mode = mods == 1;
      trackball_init_pos = last_mouse_pos;
      button_state = mousebutton;
    } else
      button_state = -1;
  });


  window->on_key_press.connect(std::bind([&](gua::PipelineDescription& pipe, gua::SceneGraph& graph, int key, int scancode, int action, int mods) {
    if (action == 0) return;
    switch (std::tolower(key)) {

      case '1':
        PLod_Pass->mode(gua::PLodPassDescription::SurfelRenderMode::HQ_TWO_PASS);
        PLod_Pass->touch();
        break;
      case '2':
        PLod_Pass->mode(gua::PLodPassDescription::SurfelRenderMode::HQ_LINKED_LIST);
        PLod_Pass->touch();
        break;

      default:
        break;
    }
  },
  std::ref(*(camera->get_pipeline_description())),
  std::ref(graph),
  std::placeholders::_1,
  std::placeholders::_2,
  std::placeholders::_3,
  std::placeholders::_4));

  window->open();

  gua::Renderer renderer;

  //application loop
  gua::events::MainLoop loop;
  gua::events::Ticker ticker(loop, 1.0 / 500.0);
  ticker.on_tick.connect([&]() {
    screen->set_transform(scm::math::inverse(gua::math::mat4(trackball.transform_matrix())));

    light->rotate(0.1, 0.f, 1.f, 0.f);
    window->process_events();
    if (window->should_close()) {
      renderer.stop();
      window->close();
      loop.stop();
    }
    else {


      renderer.queue_draw({ &graph });
      std::cout << "FPS: " << window->get_rendering_fps() << "  Frametime: " << 1000.f / window->get_rendering_fps() << std::endl;
    }
  });

  loop.start();

  return 0;
}
Example #30
0
int main(int argc, char** argv)
{
    // initialize guacamole
    gua::init(argc, argv);

    // setup scene
    gua::SceneGraph graph("main_scenegraph");

    gua::math::vec4 iron(0.560, 0.570, 0.580, 1);
    gua::math::vec4 silver(0.972, 0.960, 0.915, 1);
    gua::math::vec4 aluminium(0.913, 0.921, 0.925, 1);
    gua::math::vec4 gold(1.000, 0.766, 0.336, 1);
    gua::math::vec4 copper(0.955, 0.637, 0.538, 1);
    gua::math::vec4 chromium(0.550, 0.556, 0.554, 1);
    gua::math::vec4 nickel(0.660, 0.609, 0.526, 1);
    gua::math::vec4 titanium(0.542, 0.497, 0.449, 1);
    gua::math::vec4 cobalt(0.662, 0.655, 0.634, 1);
    gua::math::vec4 platinum(0.672, 0.637, 0.585, 1);

    auto pbrMat(gua::MaterialShaderDatabase::instance()->lookup("gua_default_material")->make_new_material());
    // pbrMat.set_uniform("Color", chromium);
    // pbrMat.set_uniform("Roughness", 0.2f);
    // pbrMat.set_uniform("Metalness", 1.0f);

    std::string directory("/opt/3d_models/Cerberus_by_Andrew_Maximov/Textures/");
    pbrMat->set_uniform("ColorMap", directory + "Cerberus_A.tga");
    pbrMat->set_uniform("MetalnessMap", directory + "Cerberus_M.tga");
    pbrMat->set_uniform("RoughnessMap", directory + "Cerberus_R.tga");
    pbrMat->set_uniform("NormalMap", directory + "Cerberus_N.negated_green.tga");

    gua::TriMeshLoader loader;

    auto transform = graph.add_node<gua::node::TransformNode>("/", "transform");
    auto cerberus(loader.create_geometry_from_file(
        "cerberus", "/opt/3d_models/Cerberus_by_Andrew_Maximov/Cerberus_LP.3ds", pbrMat, gua::TriMeshLoader::NORMALIZE_POSITION | gua::TriMeshLoader::NORMALIZE_SCALE));
    graph.add_node("/transform", cerberus);
    cerberus->set_draw_bounding_box(true);
    cerberus->rotate(90, 0.f, 1.f, 0.f);
    cerberus->rotate(90, 0.f, 0.f, 1.f);

    auto pointLight = graph.add_node<gua::node::LightNode>("/", "pointLight");
    pointLight->data.set_type(gua::node::LightNode::Type::POINT);
    pointLight->data.color = gua::utils::Color3f(1.0f, 1.0f, 1.0f);
    pointLight->data.brightness = 150.0f; // lm
    pointLight->scale(9.f);
    pointLight->translate(-2.f, 3.f, 5.f);

    auto screen = graph.add_node<gua::node::ScreenNode>("/", "screen");
    screen->data.set_size(gua::math::vec2(1.92f, 1.08f));
    screen->translate(0, 0, 1.0);

    // add mouse interaction
    gua::utils::Trackball trackball(0.01, 0.002, 0.2);

    // setup rendering pipeline and window
    // auto resolution = gua::math::vec2ui(1920, 1080);
    auto resolution = gua::math::vec2ui(2560, 1440);

    std::string skymaps_dir("/opt/guacamole/resources/skymaps/");

    for(auto const& file : {std::string(directory + "Cerberus_A.tga"),
                            std::string(directory + "Cerberus_M.tga"),
                            std::string(directory + "Cerberus_R.tga"),
                            std::string(directory + "Cerberus_N.negated_green.tga"),
                            std::string(skymaps_dir + "skymap.jpg")})
    {
        gua::TextureDatabase::instance()->load(file);
    }

    auto tiledPipe(std::make_shared<gua::PipelineDescription>());
    tiledPipe->add_pass(std::make_shared<gua::TriMeshPassDescription>());
    tiledPipe->add_pass(std::make_shared<gua::LightVisibilityPassDescription>());
    tiledPipe->add_pass(std::make_shared<gua::ResolvePassDescription>());

    auto camera = graph.add_node<gua::node::CameraNode>("/screen", "cam");
    camera->translate(0, 0, 2.0);
    camera->config.set_resolution(resolution);
    camera->config.set_screen_path("/screen");
    camera->config.set_scene_graph_name("main_scenegraph");
    camera->config.set_output_window_name("main_window");
    camera->config.set_enable_stereo(false);
    camera->set_pipeline_description(tiledPipe);

    auto window = std::make_shared<gua::GlfwWindow>();
    gua::WindowDatabase::instance()->add("main_window", window);
    window->config.set_enable_vsync(false);
    window->config.set_size(resolution);
    window->config.set_resolution(resolution);
    window->config.set_stereo_mode(gua::StereoMode::MONO);
    window->on_resize.connect([&](gua::math::vec2ui const& new_size) {
        window->config.set_resolution(new_size);
        camera->config.set_resolution(new_size);
        screen->data.set_size(gua::math::vec2(0.001 * new_size.x, 0.001 * new_size.y));
    });
    window->on_move_cursor.connect([&](gua::math::vec2 const& pos) { trackball.motion(pos.x, pos.y); });
    window->on_button_press.connect(std::bind(mouse_button, std::ref(trackball), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    window->open();

    gua::Renderer renderer;

    // application loop
    gua::events::MainLoop loop;
    gua::events::Ticker ticker(loop, 1.0 / 500.0);

    size_t ctr{};
    ticker.on_tick.connect([&]() {
        // apply trackball matrix to object
        gua::math::mat4 modelmatrix = scm::math::make_translation(gua::math::float_t(trackball.shiftx()), gua::math::float_t(trackball.shifty()), gua::math::float_t(trackball.distance())) *
                                      gua::math::mat4(trackball.rotation());

        transform->set_transform(modelmatrix);

        if(ctr++ % 150 == 0)
            gua::Logger::LOG_WARNING << "Frame time: " << 1000.f / window->get_rendering_fps() << " ms, fps: " << window->get_rendering_fps() << std::endl;

        window->process_events();
        if(window->should_close())
        {
            renderer.stop();
            window->close();
            loop.stop();
        }
        else
        {
            renderer.queue_draw({&graph});
        }
    });

    loop.start();

    return 0;
}