- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
什么是使用 C++ 在 OpenGL 窗口中每秒同步帧数的有效且准确的方法。我试过将 Sleep(17);
放在我的主游戏循环中,这将它降低到每秒 59 帧,但它并不准确和高效。这是我的主循环中没有 Sleep(17);
的 OpenGL 窗口代码:
#include <windows.h>
#include <gl\gl.h>
HDC hDC = NULL;
HGLRC hRC = NULL;
HWND hWnd = NULL;
HINSTANCE hInstance;
bool keys[256];
bool active = true;
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
GLvoid ReSizeGLScene(GLsizei width, GLsizei height)
{
if (height == 0)
{
height = 1;
}
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 800, 0, 600, 1, -1);
glMatrixMode(GL_MODELVIEW);
}
int InitGL(GLvoid)
{
glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
return 1;
}
int DrawGLScene(GLvoid)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
return 1;
}
GLvoid KillGLWindow(GLvoid)
{
if (hRC)
{
if (!wglMakeCurrent(NULL,NULL))
{
MessageBox(NULL, "Release Of DC And RC Failed." ,"SHUTDOWN ERROR" ,MB_OK | MB_ICONINFORMATION);
}
if (!wglDeleteContext(hRC))
{
MessageBox(NULL, "Release Rendering Context Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
}
hRC = NULL;
}
if (hDC && !ReleaseDC(hWnd, hDC))
{
MessageBox(NULL, "Release Device Context Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hDC = NULL;
}
if (hWnd && !DestroyWindow(hWnd))
{
MessageBox(NULL, "Could Not Release hWnd.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hWnd = NULL;
}
if (!UnregisterClass("Project2DClass",hInstance))
{
MessageBox(NULL, "Could Not Unregister Class.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hInstance = NULL;
}
}
BOOL CreateGLWindow(char* title, int width, int height, int bits)
{
GLuint PixelFormat;
WNDCLASS wc;
DWORD dwExStyle;
DWORD dwStyle;
RECT WindowRect;
WindowRect.left = (long)0;
WindowRect.right = (long)width;
WindowRect.top = (long)0;
WindowRect.bottom = (long)height;
hInstance = GetModuleHandle(NULL);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = (WNDPROC) WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = "Project2DClass";
if (!RegisterClass(&wc))
{
MessageBox(NULL, "Failed To Register The Window Class.", "ERROR", MB_OK|MB_ICONEXCLAMATION);
return 0;
}
dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
dwStyle = WS_OVERLAPPEDWINDOW;
AdjustWindowRectEx(&WindowRect, dwStyle, false, dwExStyle);
if (!(hWnd = CreateWindowEx(
dwExStyle,
"Project2DClass",
title,
dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
0,
0,
WindowRect.right-WindowRect.left,
WindowRect.bottom-WindowRect.top,
NULL,
NULL,
hInstance,
NULL))
)
{
KillGLWindow();
MessageBox(NULL, "Window Creation Error.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
return 0;
}
static PIXELFORMATDESCRIPTOR pfd =
{
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
bits,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
32,
0,
0,
PFD_MAIN_PLANE,
0,
0,
0,
0
};
if (!(hDC = GetDC(hWnd)))
{
KillGLWindow();
MessageBox(NULL, "Can't Create A GL Device Context.", "ERROR", MB_OK|MB_ICONEXCLAMATION);
return 0;
}
if (!(PixelFormat=ChoosePixelFormat(hDC, &pfd)))
{
KillGLWindow();
MessageBox(NULL, "Can't Find A Suitable PixelFormat.", "ERROR", MB_OK|MB_ICONEXCLAMATION);
return 0;
}
if(!SetPixelFormat(hDC, PixelFormat, &pfd))
{
KillGLWindow();
MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return 0;
}
if (!(hRC = wglCreateContext(hDC)))
{
KillGLWindow();
MessageBox(NULL, "Can't Create A GL Rendering Context.", "ERROR", MB_OK|MB_ICONEXCLAMATION);
return 0;
}
if(!wglMakeCurrent(hDC, hRC))
{
KillGLWindow();
MessageBox(NULL,"Can't Activate The GL Rendering Context.", "ERROR", MB_OK|MB_ICONEXCLAMATION);
return 0;
}
ShowWindow(hWnd, SW_SHOW);
SetForegroundWindow(hWnd);
SetFocus(hWnd);
ReSizeGLScene(width, height);
if (!InitGL())
{
KillGLWindow();
MessageBox(NULL, "Initialization Failed.", "ERROR", MB_OK|MB_ICONEXCLAMATION);
return 0;
}
return 1;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_ACTIVATE:
{
if (!HIWORD(wParam))
{
active = true;
}
else
{
active = false;
}
return 0;
}
case WM_SYSCOMMAND:
{
switch (wParam)
{
case SC_SCREENSAVE:
case SC_MONITORPOWER:
return 0;
}
break;
}
case WM_CLOSE:
{
PostQuitMessage(0);
return 0;
}
case WM_KEYDOWN:
{
keys[wParam] = true;
return 0;
}
case WM_KEYUP:
{
keys[wParam] = false;
return 0;
}
case WM_SIZE:
{
ReSizeGLScene(LOWORD(lParam), HIWORD(lParam));
return 0;
}
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
MSG msg;
BOOL running = true;
if (!CreateGLWindow("Project 2D", 800, 600, 32))
{
return 0;
}
while(running)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
{
running = false;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
if (active)
{
if (keys[VK_ESCAPE])
{
running = false;
}
else
{
DrawGLScene();
SwapBuffers(hDC);
}
}
}
}
KillGLWindow();
return (msg.wParam);
}
另外,我怎样才能让我的窗口在屏幕中间启动。
编辑:
这是 LWJGL 框架的 java 等价物:
/*
* Copyright (c) 2002-2012 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opengl;
import org.lwjgl.Sys;
/**
* A highly accurate sync method that continually adapts to the system
* it runs on to provide reliable results.
*
* @author Riven
* @author kappaOne
*/
class Sync {
/** number of nano seconds in a second */
private static final long NANOS_IN_SECOND = 1000L * 1000L * 1000L;
/** The time to sleep/yield until the next frame */
private static long nextFrame = 0;
/** whether the initialisation code has run */
private static boolean initialised = false;
/** for calculating the averages the previous sleep/yield times are stored */
private static RunningAvg sleepDurations = new RunningAvg(10);
private static RunningAvg yieldDurations = new RunningAvg(10);
/**
* An accurate sync method that will attempt to run at a constant frame rate.
* It should be called once every frame.
*
* @param fps - the desired frame rate, in frames per second
*/
public static void sync(int fps) {
if (fps <= 0) return;
if (!initialised) initialise();
try {
// sleep until the average sleep time is greater than the time remaining till nextFrame
for (long t0 = getTime(), t1; (nextFrame - t0) > sleepDurations.avg(); t0 = t1) {
Thread.sleep(1);
sleepDurations.add((t1 = getTime()) - t0); // update average sleep time
}
// slowly dampen sleep average if too high to avoid yielding too much
sleepDurations.dampenForLowResTicker();
// yield until the average yield time is greater than the time remaining till nextFrame
for (long t0 = getTime(), t1; (nextFrame - t0) > yieldDurations.avg(); t0 = t1) {
Thread.yield();
yieldDurations.add((t1 = getTime()) - t0); // update average yield time
}
} catch (InterruptedException e) {
}
// schedule next frame, drop frame(s) if already too late for next frame
nextFrame = Math.max(nextFrame + NANOS_IN_SECOND / fps, getTime());
}
/**
* This method will initialise the sync method by setting initial
* values for sleepDurations/yieldDurations and nextFrame.
*
* If running on windows it will start the sleep timer fix.
*/
private static void initialise() {
initialised = true;
sleepDurations.init(1000 * 1000);
yieldDurations.init((int) (-(getTime() - getTime()) * 1.333));
nextFrame = getTime();
String osName = System.getProperty("os.name");
if (osName.startsWith("Win")) {
// On windows the sleep functions can be highly inaccurate by
// over 10ms making in unusable. However it can be forced to
// be a bit more accurate by running a separate sleeping daemon
// thread.
Thread timerAccuracyThread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (Exception e) {}
}
});
timerAccuracyThread.setName("LWJGL Timer");
timerAccuracyThread.setDaemon(true);
timerAccuracyThread.start();
}
}
/**
* Get the system time in nano seconds
*
* @return will return the current time in nano's
*/
private static long getTime() {
return (Sys.getTime() * NANOS_IN_SECOND) / Sys.getTimerResolution();
}
private static class RunningAvg {
private final long[] slots;
private int offset;
private static final long DAMPEN_THRESHOLD = 10 * 1000L * 1000L; // 10ms
private static final float DAMPEN_FACTOR = 0.9f; // don't change: 0.9f is exactly right!
public RunningAvg(int slotCount) {
this.slots = new long[slotCount];
this.offset = 0;
}
public void init(long value) {
while (this.offset < this.slots.length) {
this.slots[this.offset++] = value;
}
}
public void add(long value) {
this.slots[this.offset++ % this.slots.length] = value;
this.offset %= this.slots.length;
}
public long avg() {
long sum = 0;
for (int i = 0; i < this.slots.length; i++) {
sum += this.slots[i];
}
return sum / this.slots.length;
}
public void dampenForLowResTicker() {
if (this.avg() > DAMPEN_THRESHOLD) {
for (int i = 0; i < this.slots.length; i++) {
this.slots[i] *= DAMPEN_FACTOR;
}
}
}
}
}
最佳答案
SwapBuffers
启用了垂直回扫同步 (V-Sync)。除非你在图形驱动程序中禁用它,否则它应该默认启用。您还可以使用 Swap Interval 扩展来微调 SwapBuffers
计时和显示垂直回扫之间的比率。
此外,由于 Windows 错误地计算了 CPU 时间消耗,因此在 SwapBuffers
之后添加一个 Sleep(0)
,这解决了指示 CPU 负载过高的问题。
关于c++ - OpenGL 窗口的高效同步功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19222194/
我正在构建一个 RCP 应用程序,其中每个季度都会更新功能/插件。因此,如果用户选择自动更新功能/插件,则会下载更新插件的新 jar,但旧插件仍在使用我不再使用的磁盘空间。 我厌倦了删除包含旧 jar
我如何从外部 Controller 功能中调用 Controller 内部的功能,例如电话间隙回调功能 这是 Controller 外部定义的功能 function onDeviceReady()
如果某个功能(例如 MediaSource)可用,我如何使用 Google Dart 检查。 new MediaSource() 抛出一个错误。如何以编程方式检查此类或功能是否存在?有任何想法吗?是否
我正在尝试运行 Azure Orchestrations,突然我开始从 statusQueryGetUri 收到错误: 协调器函数“UploadDocumentOrchestrator”失败:函数“U
我见过 iPhone 上的应用程序,如果在 3.0 上运行,将使用 3.0 功能/API,例如应用内电子邮件编辑器,如果在 2.x 上运行,则不使用这些功能,并退出应用程序以启动邮件相反。 这是怎么做
这是 DB 规范化理论中的一个概念: Third normal form is violated when a non-key field is a fact about another non-ke
如果我定义 #if SOMETHING #endif 而且我还没有在任何地方定义 SOMETHING。 #if 中的代码会编译吗? 最佳答案 当#if的参数表达式中使用的名称未定义为宏时(在所有其他宏
我刚刚澄清了 A* 路径查找应该如何在两条路径具有相等值的 [情况] 下运行,无论是在计算期间还是在结束时,如果有两条相等的短路径。 例如,我在我的起始节点,我可以扩展到两个可能的节点,但它们都具有相
Java有没有类似下面的东西 宏 一种遍历所有私有(private)字段的方法 类似于 smalltalk symbols 的东西——即用于快速比较静态字符串的东西? 请注意,我正在尝试为 black
这个程序应该将华氏度转换为摄氏度: #include int main() { float fahrenheit, celsius; int max, min, step;
当打开PC缓存功能后, 软件将采用先进先出的原则排队对示波器采集的每一帧数据, 进行帧缓存。 当发现屏幕中有感兴趣的波形掠过时, 鼠标点击软件的(暂停)按钮, 可以选择回看某一帧的波形
我有一个特殊的(虚拟)函数,我想在沙盒环境中使用它: disable.system.call eval(parse(text = 'model.frame("1 ~ 1")'), envir = e
使用新的 Service 实现,我是否必须为我的所有服务提供一个 Options 方法? 使用我的所有服务当前使用的旧 ServiceBase 方法,OPTIONS 返回 OK,但没有 Access-
我正在阅读 Fogus 的关于 Clojure 的喜悦的书,在并行编程章节中,我看到了一个函数定义,它肯定想说明一些重要的事情,但我不知道是什么。此外,我看不到这个函数有什么用 - 当我执行时,它什么
我有大量的 C 代码,大部分代码被注释掉和/或 #if 0。当我使用 % 键匹配 if-else 的左括号和右括号时,它也匹配注释掉的代码。 有没有办法或vim插件在匹配括号时不考虑注释掉或#if 0
我有这个功能: map(map(fn x =>[x])) [[],[1],[2,3,4]]; 产生: val it = [[],[[1]],[[2],[3],[4]]] 我不明白这个功能是如何工作的。
我使用 Visual Studio 代码创建了一个函数应用程序,然后发布了它。功能应用程序运行良好。我现在在功能门户中使用代码部署功能(KUDU)并跳过构建。下面是日志 9:55:46 AM
我有一个数据框df: userID Score Task_Alpha Task_Beta Task_Charlie Task_Delta 3108 -8.00 Easy Easy
我真的无法解决这个问题: 我有一个返回数据框的函数。但是,数据框仅打印在我的控制台中,尽管我希望将其存储在工作空间中。我怎样才能做到这一点? 样本数据: n <- 32640 t <- seq(3*p
有没有办法找出所有可能的激活器命令行选项? activator -help仅提供最低限度的可用选项/功能列表,但所有好的东西都隐藏起来,即使在 typesafe 网站在线文档中也不可用。 到目前为止,
我是一名优秀的程序员,十分优秀!