The JLWJGL 3 Getting Started demo runs very smoothly but I noticed the main loop relies on vsync. In LWJGL 3, is there any equivalent of Display.sync(60)? I think it's unlikely but possible that the graphics card doesn't support vsync. If that's the case or if vsync is disabled, then the main loop will be an infinite busy loop and burn through CPU and power. I've tested this with glfwSwapInterval(0) just to be sure, and I found that it is indeed a busy loop.
I modified the demo and added a very cheap sync, and it protects the CPU when I set glfwSwapInterval(0). I remember Display.sync(fps) being more elaborate (with a running average). Can I get your opinion on the way I'm capping it below? It tests correctly for me and I'm able to turn the framerate up and down, but I'm curious to know if my reasoning is correct or if I'm missing anything.
private void loop() {
// This line is critical for LWJGL's interoperation with GLFW's
// OpenGL context, or any context that is managed externally.
// LWJGL detects the context that is current in the current thread,
// creates the ContextCapabilities instance and makes the OpenGL
// bindings available for use.
GLContext.createFromCurrent();
// Set the clear color
glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
// Run the rendering loop until the user has attempted to close
// the window or has pressed the ESCAPE key.
long lastNanos = System.nanoTime();
while ( glfwWindowShouldClose(window) == GL_FALSE ) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer
syncFrameRate(60, lastNanos);
lastNanos = System.nanoTime();
glfwSwapBuffers(window); // swap the color buffers
// Poll for window events. The key callback above will only be
// invoked during this call.
glfwPollEvents();
}
}
private void syncFrameRate(float fps, long lastNanos) {
long targetNanos = lastNanos + (long) (1_000_000_000.0f / fps) - 1_000_000L; // subtract 1 ms to skip the last sleep call
try {
while (System.nanoTime() < targetNanos) {
Thread.sleep(1);
}
}
catch (InterruptedException ignore) {}
}
Thanks!