Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

timer和频率的实现 #1

Open
livexia opened this issue Sep 30, 2021 · 2 comments
Open

timer和频率的实现 #1

livexia opened this issue Sep 30, 2021 · 2 comments
Assignees

Comments

@livexia
Copy link
Owner

livexia commented Sep 30, 2021

目前代码中实现timer和频率限制是通过线性计算时间实现的,而我对现有的实现却不能有一个很直观的了解,因为除了一个timer之外,还需要存在对指令执行频率的控制,假如按照当前的逻辑很可能使得代码更加的没法阅读,于是希望利用thread实现相同的功能。这个issue仅仅做一个代码留存,也用作后续thread效果的记录。

当前实现简单说明:在执行前记录时间,执行后再次记录时间,计算时间差,累计时间差直到时间差达到60Hz,这个时候执行计时器减一,或者对蜂鸣器的操作。
不足:当前实现仅仅实现了两个timer需要以60Hz的频率减一,而未能实现chip8大致是以一种500Hz的频率执行指令,我认为是可以实现的,实际上是相同的逻辑,需要增加额外的变量,额外的循环。鉴于自己的懒惰于是没有实现。

代码片段:

    pub fn run(&mut self) -> Result<()> {
        let mut last_time = Utc::now();
        let mut accumulator = 0.0;
        let timer_freq = 1000.0 / 60.0;
        let mut running = true;
        while running && (self.pc as usize) < MEMORY_SIZE - 1 {    
            let cur_time = Utc::now();
            let mut delta = (cur_time - last_time).num_milliseconds() as f64;
            if delta > 100.0 {
                delta = 100.0;
            }
            last_time = cur_time;
            accumulator += delta;
            while accumulator >= timer_freq {
                self.delay_timer = self.delay_timer.saturating_sub(1);
                if self.sound_timer > 0 {
                    self.audio.resume();
                    self.sound_timer -= 1;
                } else {
                    self.audio.pause();
                }
                accumulator -= timer_freq;
            }

            self.run_cycle(&mut running)?;
            self.video.draw()?;

            std::thread::sleep(Duration::from_micros(5000));
        };        

        Ok(())
    }
@livexia
Copy link
Owner Author

livexia commented Oct 2, 2021

目前利用多线程的实现基本符合描述,但是存在几个改进点

  1. 动画更加顺滑,当前存在闪屏的现象
  2. 频率最好能够通过参数控制

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant