cimgui-go icon indicating copy to clipboard operation
cimgui-go copied to clipboard

GLFW Backend only updates on events

Open ptxmac opened this issue 2 years ago • 8 comments

The provided GLFW backend only updates when an event happens. This means adding something like a clock will only update if the mouse moves or a key is pressed

ptxmac avatar May 09 '23 16:05 ptxmac

@ptxmac maybe try imgui.Refresh

gucio321 avatar May 09 '23 17:05 gucio321

Hmm, that could work, but I would have to add a separate go routine to post "refresh" events periodically. To me, that seems a bit of a strange design

ptxmac avatar May 09 '23 17:05 ptxmac

This works:

	go func() {
		ticker := time.NewTicker(16 * time.Millisecond)
		for {
			select {
			case <-ticker.C:
				backend.Refresh()
			}
		}
	}()

	backend.Run(loop)

But I still think it's a strange design - especially since the backend also has a SetTargetFPS which only keeps that target IF there are continuous events being processed

ptxmac avatar May 09 '23 17:05 ptxmac

I think its a design of GLFW and imgui rather than our.

gucio321 avatar May 09 '23 17:05 gucio321

I think its a design of GLFW and imgui rather than our.

Not directly, the waiting for events is specific to cimgui-go's backend: https://github.com/AllenDang/cimgui-go/blob/main/glfw_backend.cpp#L227

      glfwWaitEvents();

Another oddity is a busy wait to hit the target fps:

    while (glfwGetTime() < lasttime + 1.0 / glfw_target_fps) {
      // do nothing here
    }

Basically, if the backend get more events than the target fps, then it burns CPU cycles trying to get down to the target framerate...

The "correct" solution to both problems would be to enable v-sync instead, and call glfwSwapBuffers. That would make the backend call loop with a predictable frequency and there's no busy logic that will take over the CPU in case there's a crazy stream of events.

Downside is that the FPS is now controlled by the display, so you get 60 or 120 (or what-ever your monitor is configured to)

ptxmac avatar May 09 '23 17:05 ptxmac

I just noticed that glfwSwapBuffers is being called in a different part of the rendering loop, so the loop is already capped at the display refresh rate, which makes the wait events even more confusing 😄

ptxmac avatar May 09 '23 17:05 ptxmac

oh, its so strange :smile:. Could you please create a PR to fix the backend? I'd be so greatful since I'm not familiar with glfw at all.

gucio321 avatar May 09 '23 18:05 gucio321

Yeah, I'll have a look at it if I have the time, but I also might be missing something. It looks like @AllenDang wrote it - don't know if they had something special in mind

ptxmac avatar May 09 '23 18:05 ptxmac