From da97657afb00c57e279c453843785e3acb8f3d90 Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Tue, 3 Jan 2023 02:05:40 +0900 Subject: [PATCH] Revert "internal/ui: refactoring: remove unnecessary hack for unfocusing" This reverts commit 3f753b7086d235cf733b6a393011d5a0e26447cb. Reason: this was actually necessary. Updates #982 Updates #987 Closes #2521 --- internal/ui/ui_glfw.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/internal/ui/ui_glfw.go b/internal/ui/ui_glfw.go index fd7ac8233..2b53e6be3 100644 --- a/internal/ui/ui_glfw.go +++ b/internal/ui/ui_glfw.go @@ -1015,6 +1015,21 @@ func (u *userInterfaceImpl) loopGame() error { } func (u *userInterfaceImpl) updateGame() error { + var unfocused bool + + // On Windows, the focusing state might be always false (#987). + // On Windows, even if a window is in another workspace, vsync seems to work. + // Then let's assume the window is always 'focused' as a workaround. + if runtime.GOOS != "windows" { + unfocused = u.window.GetAttrib(glfw.Focused) == glfw.False + } + + var t1, t2 time.Time + + if unfocused { + t1 = time.Now() + } + var outsideWidth, outsideHeight float64 var deviceScaleFactor float64 var err error @@ -1046,6 +1061,20 @@ func (u *userInterfaceImpl) updateGame() error { u.swapBuffersOnRenderThread() }) + if unfocused { + t2 = time.Now() + } + + // When a window is not focused, SwapBuffers might return immediately and CPU might be busy. + // Mitigate this by sleeping (#982). + if unfocused { + d := t2.Sub(t1) + const wait = time.Second / 60 + if d < wait { + time.Sleep(wait - d) + } + } + return nil }