因此,我一直在使用OpenGL + GLFW开发游戏引擎。最初,我一直在使用LWJGL包装器和Java。我决定将我的代码库移植到C ++。我一直在通过lambda来使用“ glfwSetCursorPosCallback”函数,如下所示:
//Java:
glfwSetCursorPosCallback(win, (window, xpos, ypos) -> {
engine.onCursorMoved(xpos, ypos);
});
这样做使我可以将Engine类中的所有不同“事件”联系在一起,并使GLFW设置代码+原始更新循环与其余引擎代码分开。使Engine类保持整洁。
我想使用C ++做同样的事情,但是以下内容无效:
glfwSetCursorPosCallback(window, [engine](GLFWwindow* window, double x, double y) {
engine.onCursorMoved(x, y);
});
对于C ++ lambda,如果将lambda用作函数参数,则无法在“ []”块中传递任何内容。
因此,我在最初的问题上进行了更多研究,我还阅读到使用lambda时性能较差。
所以我尝试将成员函数作为参数传递:
// I changed "onCursorMoved" use the proper parameter signature
// "onCursorMoved(GLFWwindow* window, double x, double y)"
glfwSetCursorPosCallback(window, engine.onCursorMoved);
由于您无法将实例类成员函数作为参数传递给glfwSetCursorPosCallback,因此尝试此操作也失败了。
所以我问,我应该采取什么方法?是否有办法解决lambda /成员函数的局限性,或者我完全缺少的完全不同的方法?
PS-我对C ++完全不了解,所以如果答案很明显,请原谅我。
编辑:为了帮助说明/阐明我要实现的目标,这是基于我以前的Java版本的Engine.h。
class Engine {
private:
//member variables for scene graph, etc
public:
Engine();
~Engine();
public:
void onWindowResized(int width, int height);
void onCursorMoved(double x, double y);
void onUpdate(float timeStep);
void onRender();
};
基本上,以main开头的GLFW回调/循环会触发带有“ on”前缀的不同功能。这种方法是可行的,还是以某种方式在C ++中有更好的方法来实现(这种方法来自Java,而Java在对象中所有内容都在其中),这种思维方式是否对这种情况有缺陷?
使用glfwSetWindowUserPointer()
设置Engine
实例给定的窗口应该呼吁回调。
然后在(捕获以下)lambda表达式可以调用glfwGetWindowUserPointer()
与window
,施放void*
到Engine*
,并调用相应的成员函数。
例:
#include <GLFW/glfw3.h>
#include <cstdlib>
class Engine
{
public:
void onCursorPos( double x, double y )
{
mX = x;
mY = y;
}
double mX, mY;
};
int main()
{
if( !glfwInit() )
exit( EXIT_FAILURE );
glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 2 );
glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 1 );
GLFWwindow* window = glfwCreateWindow( 640, 480, "Simple example", NULL, NULL );
Engine engine;
glfwSetWindowUserPointer( window, &engine );
glfwSetCursorPosCallback( window, []( GLFWwindow* window, double x, double y )
{
Engine* engine = static_cast<Engine*>( glfwGetWindowUserPointer( window ) );
engine->onCursorPos( x, y );
} );
glfwMakeContextCurrent( window );
glfwSwapInterval( 1 );
while( !glfwWindowShouldClose( window ) )
{
glClearColor( engine.mX / 640.0, engine.mY / 480.0, 1.0, 1.0 );
glClear( GL_COLOR_BUFFER_BIT );
glfwSwapBuffers( window );
glfwPollEvents();
}
glfwDestroyWindow( window );
glfwTerminate();
exit( EXIT_SUCCESS );
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句