【osg】【第4讲帧的学习】

【如何计算帧】

run循环中

while(!viewer->done())
{
    frame();
}

【如何计算帧数】

帧数=1/一帧的时间

float start_time=0.0;
float end_time=0.0;
while(!viewer->done())
{
    start_time = timer->tick();
    frame();
    end_time =timer->tick();
    std::cout<< 1/(tiemr->delta(start_time,end_time))<<std::endl;
}

【如何使帧数平均】

帧数=3/取三帧的时间

float start_time=0.0;
float end_time=0.0;
int count=0;
while(!viewer->done())
{
    if(count==0)
    {
        start_time = timer->tick();
    }
    count++:
    frame();
    if(count==3)
    {
        end_time =timer->tick();
        std::cout<< 3/(tiemr->delta(start_time,end_time))<<std::endl;
        count=0;
    }
}
 

【如何控制一帧0.1s】

睡眠时间=0.1-实际一帧的时间;

循环睡眠时间

float start_time=0.0;
float end_time=0.0;
float sleep_time=0.0;
int count=0;
while(!viewer->done())
{
    if(count==0)
    {
        start_time = timer->tick();
    }
    count++:
    OpenThreads::Thread::microSleep(sleep_time*1000000);
    frame();
//控制帧数10,每帧0.1
    if(count==3)
    {
        end_time =timer->tick();
        std::cout<< 3/(tiemr->delta(start_time,end_time))<<std::endl;
        count=0;
        sleep_time = 0.1-tiemr->delta(start_time,end_time);
        if(sleep_time<0)
        {
            sleep_time=0;
        }
    }
}
 

出现的问题:当实际时间比预期时间长,sleep为负值,导致没有睡眠,三帧时间短,3/很小的数,最后结果很大;

【解决不睡眠导致的帧数很大问题】

方法一:利用缓冲区

将sleep_time适当分割,此处用last_time,记录以前的睡眠时间,适当减小,设为下一帧的睡眠时间,防止睡过头。

float start_time=0.0;
float end_time=0.0;
float sleep_time=0.0;
float last_time=0.0;
int count=0;
while(!viewer->done())
{
    if(count==0)
    {
        start_time = timer->tick();
    }
    count++:
    OpenThreads::Thread::microSleep(sleep_time*1000000);
    last_time=sleep_time;
    frame();
//控制帧数10,每帧0.1
    if(count==3)
    {
        end_time =timer->tick();
        std::cout<< 3/(tiemr->delta(start_time,end_time))<<std::endl;
        count=0;
        sleep_time = 0.1-tiemr->delta(start_time,end_time);
        if(sleep_time<0)
        {
            sleep_time=last_time*0.8;
            last_time=sleep_time;
        }
    }
}
 

方法二:利用缓冲区每帧控制法

将sleep_time适当分割,此处用last_time,记录以前的睡眠时间,适当减小,设为下一帧的睡眠时间,防止睡过头,对每帧进行睡眠。

float start_time=0.0;
float end_time=0.0;
float per_str_time =0.0;
float per_end_time =0.0;
float sleep_time=0.0;
float last_time=0.0;
int count=0;
while (!viewer->done())
	{
		per_str_time = timer->tick();
		
		if (count == 0)
		{
			start_frame_time = timer->tick();
		}
		count++;
		viewer->frame();
		per_end_time = timer->tick();
		sleep_time = 0.1 - (timer->delta_s(per_str_time, per_end_time));
		if (sleep_time<0)
		{
			sleep_time = last_sleep*0.8;
		}
		last_sleep = sleep_time;
		OpenThreads::Thread::microSleep(sleep_time*1000000);
		if (count == 3)
		{
			//限制帧数为10,每帧绘制0.1s
			count = 0;
			end_frame_time = timer->tick();
			std::cout << "当前帧数" << 3 / (timer->delta_s(start_frame_time, end_frame_time)) << std::endl;
		
		}

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页