From 25a5f1dd83a6fe914feffb372a8fd278df7441ef Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Sun, 30 Sep 2018 14:43:53 +0900 Subject: [PATCH] ui: Sleep when vsync doesn't work (#692) --- internal/ui/ui_glfw.go | 21 +++++++++++++++++++++ run.go | 3 +++ 2 files changed, 24 insertions(+) diff --git a/internal/ui/ui_glfw.go b/internal/ui/ui_glfw.go index be0331dec..47dd87e2d 100644 --- a/internal/ui/ui_glfw.go +++ b/internal/ui/ui_glfw.go @@ -625,11 +625,32 @@ func (u *userInterface) loop(g GraphicsContext) error { if err := u.update(g); err != nil { return err } + + u.m.Lock() + vsync := u.vsync + u.m.Unlock() + // The bound framebuffer must be the original screen framebuffer // before swapping buffers. opengl.GetContext().BindScreenFramebuffer() + _ = u.runOnMainThread(func() error { + if !vsync { + u.swapBuffers() + return nil + } + + n1 := time.Now().UnixNano() u.swapBuffers() + n2 := time.Now().UnixNano() + d := time.Duration(n2 - n1) + + // On macOS Mojave, vsync might not work (#692). + // As a tempoarry fix, just wait for a millisecond not to consume CPU too much. + const threshold = 4 * time.Millisecond // 250 [Hz] + if d < threshold { + time.Sleep(threshold - d) + } return nil }) } diff --git a/run.go b/run.go index 7dfaed164..bc7be7c3c 100644 --- a/run.go +++ b/run.go @@ -38,6 +38,9 @@ const FPS = DefaultTPS // CurrentFPS returns the current number of FPS (frames per second), that represents // how many swapping buffer happens per second. // +// On some environments, CurrentFPS doesn't return a reliable value since vsync doesn't work well there. +// If you want to measure the application's speed, Use CurrentTPS. +// // CurrentFPS is concurrent-safe. func CurrentFPS() float64 { return clock.CurrentFPS()