Exemplo n.º 1
0
Window::Window()
{
    window = SDL_CreateWindow("game1 test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                              800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);

    SDL_Surface *icon = SDL_LoadBMP("data/imgs/icon.bmp");
    icon->format->Amask = 0xFF000000;
    SDL_SetWindowIcon(window, icon);

    SDL_GetWindowSize(window, &_width, &_height);

    zoom = 3;

    _gl = SDL_GL_CreateContext(window);

    GLuint GLEWerr = glewInit();
    if(GLEWerr != GLEW_OK)
        printf("GLEW: %s\n", glewGetErrorString(GLEWerr));

    if( !GLEW_VERSION_3_2 )
        printf( "OpenGL 3.2 not supported!\n" );

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);

    glEnable(GL_TEXTURE_2D);

    glEnable(GL_BLEND);
    glDisable(GL_DEPTH_TEST);
    glDisable( GL_LIGHTING );
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    GLenum err = glGetError();
    if(err != GL_NO_ERROR)
    {
        printf("Error: %s\n", gluErrorString(err));
    }


    printf( "VENDOR = %s\n", glGetString( GL_VENDOR ) ) ;
    printf( "RENDERER = %s\n", glGetString( GL_RENDERER ) ) ;
    printf( "VERSION = %s\n", glGetString( GL_VERSION ) ) ;
    /*
    vShadObj = glCreateShader(GL_VERTEX_SHADER);
    fShadObj = glCreateShader(GL_FRAGMENT_SHADER);

    std::fstream vShadFile("default.glvs", std::ios::in);
    std::string vShadStr;
    if(vShadFile.is_open())
    {
    	std::stringstream buffer;
    	buffer << vShadFile.rdbuf();
    	vShadStr = buffer.str();
    }
    std::fstream fShadFile("default.glfs", std::ios::in);
    std::string fShadStr;
    if(fShadFile.is_open())
    {
    	std::stringstream buffer;
    	buffer << fShadFile.rdbuf();
    	fShadStr = buffer.str();
    }

    const char* vc_str = vShadStr.c_str();
    glShaderSource(vShadObj, 1, &vc_str, NULL);
    const char* fc_str = fShadStr.c_str();
    glShaderSource(fShadObj, 1, &fc_str, NULL);

    glCompileShader(vShadObj);
    glCompileShader(fShadObj);

    shadProg = glCreateProgram();

    glAttachShader(shadProg, vShadObj);
    glAttachShader(shadProg, fShadObj);

    glLinkProgram(shadProg);

    GLint programSuccess = GL_TRUE;
    glGetProgramiv( shadProg, GL_LINK_STATUS, &programSuccess );
    if( programSuccess != GL_TRUE )
    	printf( "Error linking program %d!\n", shadProg );

    glUseProgram(shadProg);

    _projPointer = glGetUniformLocation(shadProg, "LProjectionMatrix");
    _modViewPointer = glGetUniformLocation(shadProg, "LModelViewMatrix");
    */

    glEnable(GL_MULTISAMPLE);

    int samples = 2;
    /*
    glGenTextures(1, &fbTex);
    glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, fbTex);
    glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, samples, GL_RGBA8, _width, _height, false);

    glGenFramebuffers(1, &fbObj);
    glBindFramebuffer(GL_FRAMEBUFFER, fbObj);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, fbTex, 0);

    err = glCheckFramebufferStatus(GL_FRAMEBUFFER_EXT);
    if(err != GL_FRAMEBUFFER_COMPLETE_EXT)
    {
    	printf("Error: %s\n", gluErrorString(err));
    }
    err = glGetError();
    if(err != GL_NO_ERROR)
    	printf("Window: FrameBuffer: %s\n", gluErrorString(err));
    */
    glHint(GL_NICEST, GL_FRAGMENT_SHADER_DERIVATIVE_HINT);
    glHint(GL_NICEST, GL_LINE_SMOOTH_HINT);
    glHint(GL_NICEST, GL_POLYGON_SMOOTH_HINT);
    glHint(GL_NICEST, GL_TEXTURE_COMPRESSION_HINT);

    resize();

    err = glGetError();
    if(err != GL_NO_ERROR)
        printf("Window: Shader: %s\n", gluErrorString(err));

    /*ilInit();
    ilClearColour(255, 255, 255, 000);

    ILenum ilError = ilGetError();
    if(ilError != IL_NO_ERROR)
    {
    	printf("error loading DevIL: %s\n", iluErrorString(ilError));
    }*/

}
Exemplo n.º 2
0
/* inicjuje 
 * -oswietlenie
 * -cieniowanie
 * -biblioteke glut
 * -wspolprace z systemem okienkowym
 */
void init()
{   
   GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		std::cout << "GLEW initialisation error: " << glewGetErrorString(err) << std::endl;
		exit(-1);
	}
	std::cout << "GLEW intialised successfully. Using GLEW version: " << glewGetString(GLEW_VERSION) << std::endl;
 


    GLfloat mat_ambient[]    = { 1.0, 1.0,  1.0, 1.0 };
	GLfloat mat_diffuse[]    = { 0.5, 0.5,  0.5, 1.0 };
    GLfloat mat_specular[]   = { 1.0, 1.0,  1.0, 1.0 };
    GLfloat light1_position[] = { 10.0,		5.0,	10.0,	1.0 };
	GLfloat light2_position[] = { -10.0,	10.0,	-10.0,	1.0 };
	GLfloat light3_position[] = { 10.0,		10.0,	-10.0,	1.0 };
	GLfloat light4_position[] = { -10.0,	10.0,	10.0,	1.0 };
    GLfloat lm_ambient[]     = { 0.2, 0.2,  0.2, 1.0 };

    glMaterialfv( GL_FRONT, GL_AMBIENT, mat_ambient );
    glMaterialfv( GL_FRONT, GL_SPECULAR, mat_specular );
    glMaterialf( GL_FRONT, GL_SHININESS, 50.0 );
    glLightfv( GL_LIGHT0, GL_POSITION, light1_position );
		glLightfv( GL_LIGHT1, GL_POSITION, light2_position );
		glLightfv(GL_LIGHT1, GL_DIFFUSE, mat_diffuse);
		glLightfv( GL_LIGHT2, GL_POSITION, light3_position );
		glLightfv(GL_LIGHT2, GL_DIFFUSE, mat_diffuse);
		glLightfv( GL_LIGHT3, GL_POSITION, light4_position );
		glLightfv(GL_LIGHT3, GL_DIFFUSE, mat_diffuse);
    glLightModelfv( GL_LIGHT_MODEL_AMBIENT, lm_ambient );
    
	glEnable(GL_NORMALIZE);

    glShadeModel( GL_SMOOTH );													// obliczanie swiatla 
	
    glEnable( GL_LIGHTING );
    glEnable( GL_LIGHT0 );
	glEnable( GL_LIGHT1 );
	glEnable( GL_LIGHT2 );
	glEnable( GL_LIGHT3 );

    glDepthFunc( GL_LESS );
    glEnable( GL_DEPTH_TEST );
	//glBlendFunc (GL_SRC_ALPHA, GL_ONE);


	// DevIL sanity check
	if ( (iluGetInteger(IL_VERSION_NUM) < IL_VERSION) || (iluGetInteger(ILU_VERSION_NUM) < ILU_VERSION) || (ilutGetInteger(ILUT_VERSION_NUM) < ILUT_VERSION) )
	{
		std::cout << "DevIL versions are different... Exiting." << std::endl;
		exit(-1);
	}
	

	// Initialise all DevIL functionality
	ilInit();
	iluInit();
	ilutInit();
	ilutRenderer(ILUT_OPENGL);	// Tell DevIL that we're using OpenGL for our rendering

}
Exemplo n.º 3
0
int main(int argc, char** argv)
{
	
	if (!glfwInit())	// 初始化glfw库
	{
		std::cout << "Error::GLFW could not initialize GLFW!" << std::endl;
		return -1;
	}

	// 开启OpenGL 3.3 core profile
	std::cout << "Start OpenGL core profile version 3.3" << std::endl;
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

	// 创建窗口
	GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT,
		"Demo of Skybox", NULL, NULL);
	if (!window)
	{
		std::cout << "Error::GLFW could not create winddow!" << std::endl;
		glfwTerminate();
		std::system("pause");
		return -1;
	}
	// 创建的窗口的context指定为当前context
	glfwMakeContextCurrent(window);

	// 注册窗口键盘事件回调函数
	glfwSetKeyCallback(window, key_callback);
	// 注册鼠标事件回调函数
	glfwSetCursorPosCallback(window, mouse_move_callback);
	// 注册鼠标滚轮事件回调函数
	glfwSetScrollCallback(window, mouse_scroll_callback);
	// 鼠标捕获 停留在程序内
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

	// 初始化GLEW 获取OpenGL函数
	glewExperimental = GL_TRUE; // 让glew获取所有拓展函数
	GLenum status = glewInit();
	if (status != GLEW_OK)
	{
		std::cout << "Error::GLEW glew version:" << glewGetString(GLEW_VERSION) 
			<< " error string:" << glewGetErrorString(status) << std::endl;
		glfwTerminate();
		std::system("pause");
		return -1;
	}

	// 设置视口参数
	glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
	
	//Section1 顶点属性数据
	// 指定立方体顶点属性数据 顶点位置 纹理
	GLfloat cubeVertices[] = {
		-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,	// A
		0.5f, -0.5f, 0.5f, 1.0f, 0.0f,	// B
		0.5f, 0.5f, 0.5f,1.0f, 1.0f,	// C
		0.5f, 0.5f, 0.5f,1.0f, 1.0f,	// C
		-0.5f, 0.5f, 0.5f,0.0f, 1.0f,	// D
		-0.5f, -0.5f, 0.5f,0.0f, 0.0f,	// A


		-0.5f, -0.5f, -0.5f,0.0f, 0.0f,	// E
		-0.5f, 0.5f, -0.5f,0.0, 1.0f,   // H
		0.5f, 0.5f, -0.5f,1.0f, 1.0f,	// G
		0.5f, 0.5f, -0.5f,1.0f, 1.0f,	// G
		0.5f, -0.5f, -0.5f,1.0f, 0.0f,	// F
		-0.5f, -0.5f, -0.5f,0.0f, 0.0f,	// E

		-0.5f, 0.5f, 0.5f,0.0f, 1.0f,	// D
		-0.5f, 0.5f, -0.5f,1.0, 1.0f,   // H
		-0.5f, -0.5f, -0.5f,1.0f, 0.0f,	// E
		-0.5f, -0.5f, -0.5f,1.0f, 0.0f,	// E
		-0.5f, -0.5f, 0.5f,0.0f, 0.0f,	// A
		-0.5f, 0.5f, 0.5f,0.0f, 1.0f,	// D

		0.5f, -0.5f, -0.5f,1.0f, 0.0f,	// F
		0.5f, 0.5f, -0.5f,1.0f, 1.0f,	// G
		0.5f, 0.5f, 0.5f,0.0f, 1.0f,	// C
		0.5f, 0.5f, 0.5f,0.0f, 1.0f,	// C
		0.5f, -0.5f, 0.5f, 0.0f, 0.0f,	// B
		0.5f, -0.5f, -0.5f,1.0f, 0.0f,	// F

		0.5f, 0.5f, -0.5f,1.0f, 1.0f,	// G
		-0.5f, 0.5f, -0.5f,0.0, 1.0f,   // H
		-0.5f, 0.5f, 0.5f,0.0f, 0.0f,	// D
		-0.5f, 0.5f, 0.5f,0.0f, 0.0f,	// D
		0.5f, 0.5f, 0.5f,1.0f, 0.0f,	// C
		0.5f, 0.5f, -0.5f,1.0f, 1.0f,	// G

		-0.5f, -0.5f, 0.5f,0.0f, 0.0f,	// A
		-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,// E
		0.5f, -0.5f, -0.5f,1.0f, 1.0f,	// F
		0.5f, -0.5f, -0.5f,1.0f, 1.0f,	// F
		0.5f, -0.5f, 0.5f,1.0f, 0.0f,	// B
		-0.5f, -0.5f, 0.5f,0.0f, 0.0f,	// A
	};
	// 指定包围盒的顶点属性 位置
	GLfloat skyboxVertices[] = {
		// 背面
		-1.0f, 1.0f, -1.0f,		// A
		-1.0f, -1.0f, -1.0f,	// B
		1.0f, -1.0f, -1.0f,		// C
		1.0f, -1.0f, -1.0f,		// C
		1.0f, 1.0f, -1.0f,		// D
		-1.0f, 1.0f, -1.0f,		// A

		// 左侧面
		-1.0f, -1.0f, 1.0f,		// E
		-1.0f, -1.0f, -1.0f,	// B
		-1.0f, 1.0f, -1.0f,		// A
		-1.0f, 1.0f, -1.0f,		// A
		-1.0f, 1.0f, 1.0f,		// F
		-1.0f, -1.0f, 1.0f,		// E

		// 右侧面
		1.0f, -1.0f, -1.0f,		// C
		1.0f, -1.0f, 1.0f,		// G
		1.0f, 1.0f, 1.0f,		// H
		1.0f, 1.0f, 1.0f,		// H
		1.0f, 1.0f, -1.0f,		// D
		1.0f, -1.0f, -1.0f,		// C

		// 正面
		-1.0f, -1.0f, 1.0f,  // E
		-1.0f, 1.0f, 1.0f,  // F
		1.0f, 1.0f, 1.0f,  // H
		1.0f, 1.0f, 1.0f,  // H
		1.0f, -1.0f, 1.0f,  // G
		-1.0f, -1.0f, 1.0f,  // E

		// 顶面
		-1.0f, 1.0f, -1.0f,  // A
		1.0f, 1.0f, -1.0f,  // D
		1.0f, 1.0f, 1.0f,  // H
		1.0f, 1.0f, 1.0f,  // H
		-1.0f, 1.0f, 1.0f,  // F
		-1.0f, 1.0f, -1.0f,  // A

		// 底面
		-1.0f, -1.0f, -1.0f,  // B
		-1.0f, -1.0f, 1.0f,   // E
		1.0f, -1.0f, 1.0f,    // G
		1.0f, -1.0f, 1.0f,    // G
		1.0f, -1.0f, -1.0f,   // C
		-1.0f, -1.0f, -1.0f,  // B
	};


	// Section2 准备缓存对象
	GLuint cubeVAOId, cubeVBOId;
	glGenVertexArrays(1, &cubeVAOId);
	glGenBuffers(1, &cubeVBOId);
	glBindVertexArray(cubeVAOId);
	glBindBuffer(GL_ARRAY_BUFFER, cubeVBOId);
	glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), cubeVertices, GL_STATIC_DRAW);
	// 顶点位置数据
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 
		5 * sizeof(GL_FLOAT), (GLvoid*)0);
	glEnableVertexAttribArray(0);
	// 顶点纹理数据
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 
		5 * sizeof(GL_FLOAT), (GLvoid*)(3 * sizeof(GL_FLOAT)));
	glEnableVertexAttribArray(1);
	glBindVertexArray(0);

	GLuint skyBoxVAOId, skyBoxVBOId;
	glGenVertexArrays(1, &skyBoxVAOId);
	glGenBuffers(1, &skyBoxVBOId);
	glBindVertexArray(skyBoxVAOId);
	glBindBuffer(GL_ARRAY_BUFFER, skyBoxVBOId);
	glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), skyboxVertices, GL_STATIC_DRAW);
	// 顶点位置数据
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
		3 * sizeof(GL_FLOAT), (GLvoid*)0);
	glEnableVertexAttribArray(0);
	glBindVertexArray(0);

	// Section3 加载纹理
	GLuint cubeTextId = TextureHelper::load2DTexture("../../resources/textures/container.jpg");
	std::vector<const char*> faces;
// 	faces.push_back("../../resources/skyboxes/sky/sky_rt.jpg");
// 	faces.push_back("../../resources/skyboxes/sky/sky_lf.jpg");
// 	faces.push_back("../../resources/skyboxes/sky/sky_up.jpg");
// 	faces.push_back("../../resources/skyboxes/sky/sky_dn.jpg");
// 	faces.push_back("../../resources/skyboxes/sky/sky_bk.jpg");
// 	faces.push_back("../../resources/skyboxes/sky/sky_ft.jpg");
// 
	faces.push_back("../../resources/skyboxes/urbansp/urbansp_rt.tga");
	faces.push_back("../../resources/skyboxes/urbansp/urbansp_lf.tga");
	faces.push_back("../../resources/skyboxes/urbansp/urbansp_up.tga");
	faces.push_back("../../resources/skyboxes/urbansp/urbansp_dn.tga");
	faces.push_back("../../resources/skyboxes/urbansp/urbansp_bk.tga");
	faces.push_back("../../resources/skyboxes/urbansp/urbansp_ft.tga");
	GLuint skyBoxTextId = TextureHelper::loadCubeMapTexture(faces);
	// Section4 准备着色器程序
	Shader shader("scene.vertex", "scene.frag");
	Shader skyBoxShader("skybox.vertex", "skybox.frag");

	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);
	glDepthFunc(GL_LESS);
	// 开始游戏主循环
	while (!glfwWindowShouldClose(window))
	{
		GLfloat currentFrame = (GLfloat)glfwGetTime();
		deltaTime = currentFrame - lastFrame;
		lastFrame = currentFrame;
		glfwPollEvents(); // 处理例如鼠标 键盘等事件
		do_movement(); // 根据用户操作情况 更新相机属性

		// 设置colorBuffer颜色
		glClearColor(0.18f, 0.04f, 0.14f, 1.0f);
		// 清除colorBuffer
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// 先绘制场景
		shader.use();
		glm::mat4 projection = glm::perspective(camera.mouse_zoom,
			(GLfloat)(WINDOW_WIDTH) / WINDOW_HEIGHT, 0.1f, 100.0f); // 投影矩阵
		glUniformMatrix4fv(glGetUniformLocation(shader.programId, "projection"),
			1, GL_FALSE, glm::value_ptr(projection));
		glm::mat4 view = camera.getViewMatrix(); // 视变换矩阵
		glUniformMatrix4fv(glGetUniformLocation(shader.programId, "view"),
			1, GL_FALSE, glm::value_ptr(view));
		glm::mat4 model;
		glUniformMatrix4fv(glGetUniformLocation(shader.programId, "model"),
			1, GL_FALSE, glm::value_ptr(model));

		glBindVertexArray(cubeVAOId);
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, cubeTextId);
		glUniform1i(glGetUniformLocation(skyBoxShader.programId, "text"), 0);
		glDrawArrays(GL_TRIANGLES, 0, 36);

		// 然后绘制包围盒
		glDepthFunc(GL_LEQUAL); // 深度测试条件 小于等于
		skyBoxShader.use();
		view = glm::mat4(glm::mat3(camera.getViewMatrix())); // 视变换矩阵 移除translate部分
		glUniformMatrix4fv(glGetUniformLocation(skyBoxShader.programId, "projection"),
			1, GL_FALSE, glm::value_ptr(projection));
		glUniformMatrix4fv(glGetUniformLocation(skyBoxShader.programId, "view"),
			1, GL_FALSE, glm::value_ptr(view));
		
		glBindVertexArray(skyBoxVAOId);
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_CUBE_MAP, skyBoxTextId); // 注意绑定到CUBE_MAP
		glUniform1i(glGetUniformLocation(skyBoxShader.programId, "skybox"), 0);
		glDrawArrays(GL_TRIANGLES, 0, 36);

		glBindVertexArray(0);
		glUseProgram(0);
		glDepthFunc(GL_LESS);
		glfwSwapBuffers(window); // 交换缓存
	}
	// 释放资源
	glDeleteVertexArrays(1, &cubeVAOId);
	glDeleteVertexArrays(1, &skyBoxVAOId);
	glDeleteBuffers(1, &cubeVBOId);
	glDeleteBuffers(1, &skyBoxVBOId);
	glfwTerminate();
	return 0;
}
bool initGL()
{
    //Initialize GLEW
    GLenum glewError = glewInit();
    if( glewError != GLEW_OK )
    {
        printf( "Error initializing GLEW! %s\n", glewGetErrorString( glewError ) );
        return false;
    }

    //Make sure OpenGL 2.1 is supported
    if( !GLEW_VERSION_2_1 )
    {
        printf( "OpenGL 2.1 not supported!\n" );
        return false;
    }

    //Set the viewport
    glViewport( 0.f, 0.f, SCREEN_WIDTH, SCREEN_HEIGHT );

    //Initialize Projection Matrix
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    glOrtho( 0.0, SCREEN_WIDTH, SCREEN_HEIGHT, 0.0, 1.0, -1.0 );

    //Initialize Modelview Matrix
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    //Initialize clear color
    glClearColor( 0.f, 0.f, 0.f, 1.f );

    //Enable texturing
    glEnable( GL_TEXTURE_2D );

    //Set blending
    glEnable( GL_BLEND );
    glDisable( GL_DEPTH_TEST );
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

    //Initialize stencil clear value
    glClearStencil( 0 );

    //Check for error
    GLenum error = glGetError();
    if( error != GL_NO_ERROR )
    {
        printf( "Error initializing OpenGL! %s\n", gluErrorString( error ) );
        return false;
    }

    //Initialize DevIL and DevILU
    ilInit();
    iluInit();
    ilClearColour( 255, 255, 255, 000 );

    //Check for error
    ILenum ilError = ilGetError();
    if( ilError != IL_NO_ERROR )
    {
        printf( "Error initializing DevIL! %s\n", iluErrorString( ilError ) );
        return false;
    }

    return true;
}
Exemplo n.º 5
0
int main( int argc, char **argv )
{
    int width = 1024, height=768;
    float widthf = (float) width, heightf = (float) height;
    double t;
    float fps = 0.f;

    // Initialise GLFW
    if( !glfwInit() )
    {
        fprintf( stderr, "Failed to initialize GLFW\n" );
        exit( EXIT_FAILURE );
    }

    // Force core profile on Mac OSX
#ifdef __APPLE__
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
    glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif
    // Open a window and create its OpenGL context
    if( !glfwOpenWindow( width, height, 0,0,0,0, 24, 0, GLFW_WINDOW ) )
    {
        fprintf( stderr, "Failed to open GLFW window\n" );

        glfwTerminate();
        exit( EXIT_FAILURE );
    }

    glfwSetWindowTitle( "002_forward_a" );


    // Core profile is flagged as experimental in glew
#ifdef __APPLE__
    glewExperimental = GL_TRUE;
#endif
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
          /* Problem: glewInit failed, something is seriously wrong. */
          fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
          exit( EXIT_FAILURE );
    }

    // Ensure we can capture the escape key being pressed below
    glfwEnable( GLFW_STICKY_KEYS );

    // Enable vertical sync (on cards that support it)
    glfwSwapInterval( 1 );
    GLenum glerr = GL_NO_ERROR;
    glerr = glGetError();

    if (!imguiRenderGLInit(DroidSans_ttf, DroidSans_ttf_len))
    {
        fprintf(stderr, "Could not init GUI renderer.\n");
        exit(EXIT_FAILURE);
    }

    // Init viewer structures
    Camera camera;
    camera_defaults(camera);
    GUIStates guiStates;
    init_gui_states(guiStates);

    // GUI
    float numLights = 10.f;

    // Load images and upload textures
    GLuint textures[3];
    glGenTextures(3, textures);
    int x;
    int y;
    int comp; 
    unsigned char * diffuse = stbi_load("textures/spnza_bricks_a_diff.tga", &x, &y, &comp, 3);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, textures[0]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, x, y, 0, GL_RGB, GL_UNSIGNED_BYTE, diffuse);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    fprintf(stderr, "Diffuse %dx%d:%d\n", x, y, comp);
    unsigned char * spec = stbi_load("textures/spnza_bricks_a_spec.tga", &x, &y, &comp, 1);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, textures[1]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, x, y, 0, GL_RED, GL_UNSIGNED_BYTE, spec);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    fprintf(stderr, "Spec %dx%d:%d\n", x, y, comp);

    // Try to load and compile shader
    int status;
    ShaderGLSL gbuffer_shader;
    const char * shaderFileGBuffer = "002/2_gbuffera.glsl";
    //int status = load_shader_from_file(gbuffer_shader, shaderFileGBuffer, ShaderGLSL::VERTEX_SHADER | ShaderGLSL::FRAGMENT_SHADER | ShaderGLSL::GEOMETRY_SHADER);
    status = load_shader_from_file(gbuffer_shader, shaderFileGBuffer, ShaderGLSL::VERTEX_SHADER | ShaderGLSL::FRAGMENT_SHADER);
    if ( status == -1 )
    {
        fprintf(stderr, "Error on loading  %s\n", shaderFileGBuffer);
        exit( EXIT_FAILURE );
    }    

    // Compute locations for gbuffer_shader
    GLuint gbuffer_projectionLocation = glGetUniformLocation(gbuffer_shader.program, "Projection");
    GLuint gbuffer_viewLocation = glGetUniformLocation(gbuffer_shader.program, "View");
    GLuint gbuffer_objectLocation = glGetUniformLocation(gbuffer_shader.program, "Object");
    GLuint gbuffer_timeLocation = glGetUniformLocation(gbuffer_shader.program, "Time");
    GLuint gbuffer_diffuseLocation = glGetUniformLocation(gbuffer_shader.program, "Diffuse");
    GLuint gbuffer_specLocation = glGetUniformLocation(gbuffer_shader.program, "Spec");

    // Load Blit shader
    ShaderGLSL blit_shader;
    const char * shaderFileBlit = "002/2_blita.glsl";
    //int status = load_shader_from_file(blit_shader, shaderFileBlit, ShaderGLSL::VERTEX_SHADER | ShaderGLSL::FRAGMENT_SHADER | ShaderGLSL::GEOMETRY_SHADER);
    status = load_shader_from_file(blit_shader, shaderFileBlit, ShaderGLSL::VERTEX_SHADER | ShaderGLSL::FRAGMENT_SHADER);
    if ( status == -1 )
    {
        fprintf(stderr, "Error on loading  %s\n", shaderFileBlit);
        exit( EXIT_FAILURE );
    }    

    // Compute locations for blit_shader
    GLuint blit_tex1Location = glGetUniformLocation(blit_shader.program, "Texture1");

    // Load light accumulation shader
    ShaderGLSL lighting_shader;
    const char * shaderFileLighting = "002/2_lighta.glsl";
    //int status = load_shader_from_file(lighting_shader, shaderFileLighting, ShaderGLSL::VERTEX_SHADER | ShaderGLSL::FRAGMENT_SHADER | ShaderGLSL::GEOMETRY_SHADER);
    status = load_shader_from_file(lighting_shader, shaderFileLighting, ShaderGLSL::VERTEX_SHADER | ShaderGLSL::FRAGMENT_SHADER);
    if ( status == -1 )
    {
        fprintf(stderr, "Error on loading  %s\n", shaderFileLighting);
        exit( EXIT_FAILURE );
    }    
    // Compute locations for lighting_shader
    GLuint lighting_materialLocation = glGetUniformLocation(lighting_shader.program, "Material");
    GLuint lighting_normalLocation = glGetUniformLocation(lighting_shader.program, "Normal");
    GLuint lighting_depthLocation = glGetUniformLocation(lighting_shader.program, "Depth");
    GLuint lighting_inverseViewProjectionLocation = glGetUniformLocation(lighting_shader.program, "InverseViewProjection");
    GLuint lighting_cameraPositionLocation = glGetUniformLocation(lighting_shader.program, "CameraPosition");
    GLuint lighting_lightPositionLocation = glGetUniformLocation(lighting_shader.program, "LightPosition");
    GLuint lighting_lightColorLocation = glGetUniformLocation(lighting_shader.program, "LightColor");
    GLuint lighting_lightIntensityLocation = glGetUniformLocation(lighting_shader.program, "LightIntensity");

    // Load geometry
    int   cube_triangleCount = 12;
    int   cube_triangleList[] = {0, 1, 2, 2, 1, 3, 4, 5, 6, 6, 5, 7, 8, 9, 10, 10, 9, 11, 12, 13, 14, 14, 13, 15, 16, 17, 18, 19, 17, 20, 21, 22, 23, 24, 25, 26, };
    float cube_uvs[] = {0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f,  1.f, 0.f,  1.f, 1.f,  0.f, 1.f,  1.f, 1.f,  0.f, 0.f, 0.f, 0.f, 1.f, 1.f,  1.f, 0.f,  };
    float cube_vertices[] = {-0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5 };
    float cube_normals[] = {0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, };
    int   plane_triangleCount = 2;
    int   plane_triangleList[] = {0, 1, 2, 2, 1, 3}; 
    float plane_uvs[] = {0.f, 0.f, 0.f, 10.f, 10.f, 0.f, 10.f, 10.f};
    float plane_vertices[] = {-50.0, -1.0, 50.0, 50.0, -1.0, 50.0, -50.0, -1.0, -50.0, 50.0, -1.0, -50.0};
    float plane_normals[] = {0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0};
    int   quad_triangleCount = 2;
    int   quad_triangleList[] = {0, 1, 2, 2, 1, 3}; 
    float quad_vertices[] =  {-1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0};

    // Vertex Array Object
    GLuint vao[3];
    glGenVertexArrays(3, vao);

    // Vertex Buffer Objects
    GLuint vbo[12];
    glGenBuffers(12, vbo);

    // Cube
    glBindVertexArray(vao[0]);
    // Bind indices and upload data
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[0]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cube_triangleList), cube_triangleList, GL_STATIC_DRAW);
    // Bind vertices and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cube_vertices), cube_vertices, GL_STATIC_DRAW);
    // Bind normals and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cube_normals), cube_normals, GL_STATIC_DRAW);
    // Bind uv coords and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[3]);
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*2, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cube_uvs), cube_uvs, GL_STATIC_DRAW);

    // Plane
    glBindVertexArray(vao[1]);
    // Bind indices and upload data
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[4]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(plane_triangleList), plane_triangleList, GL_STATIC_DRAW);
    // Bind vertices and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[5]);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(plane_vertices), plane_vertices, GL_STATIC_DRAW);
    // Bind normals and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[6]);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(plane_normals), plane_normals, GL_STATIC_DRAW);
    // Bind uv coords and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[7]);
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*2, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(plane_uvs), plane_uvs, GL_STATIC_DRAW);

    // Quad
    glBindVertexArray(vao[2]);
    // Bind indices and upload data
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[8]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quad_triangleList), quad_triangleList, GL_STATIC_DRAW);
    // Bind vertices and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[9]);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*2, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(quad_vertices), quad_vertices, GL_STATIC_DRAW);

    // Unbind everything. Potentially illegal on some implementations
    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    // Init frame buffers
    GLuint gbufferFbo;
    GLuint gbufferTextures[3];
    GLuint gbufferDrawBuffers[2];
    glGenTextures(3, gbufferTextures);

    // Create color texture
    glBindTexture(GL_TEXTURE_2D, gbufferTextures[0]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_FLOAT, 0);
    //glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    // Create normal texture
    glBindTexture(GL_TEXTURE_2D, gbufferTextures[1]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_FLOAT, 0);
    //glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    // Create depth texture
    glBindTexture(GL_TEXTURE_2D, gbufferTextures[2]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    // Create Framebuffer Object
    glGenFramebuffers(1, &gbufferFbo);
    glBindFramebuffer(GL_FRAMEBUFFER, gbufferFbo);

    // Attach textures to framebuffer
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 , GL_TEXTURE_2D, gbufferTextures[0], 0);
    gbufferDrawBuffers[0] = GL_COLOR_ATTACHMENT0;
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1 , GL_TEXTURE_2D, gbufferTextures[1], 0);
    gbufferDrawBuffers[1] = GL_COLOR_ATTACHMENT1;
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, gbufferTextures[2], 0);

    if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
    {
        fprintf(stderr, "Error on building framebuffer\n");
        exit( EXIT_FAILURE );
    }
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    do
    {
        t = glfwGetTime();

        // Mouse states
        int leftButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_LEFT );
        int rightButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_RIGHT );
        int middleButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_MIDDLE );

        if( leftButton == GLFW_PRESS )
            guiStates.turnLock = true;
        else
            guiStates.turnLock = false;

        if( rightButton == GLFW_PRESS )
            guiStates.zoomLock = true;
        else
            guiStates.zoomLock = false;

        if( middleButton == GLFW_PRESS )
            guiStates.panLock = true;
        else
            guiStates.panLock = false;

        // Camera movements
        int altPressed = glfwGetKey(GLFW_KEY_LSHIFT);
        if (!altPressed && (leftButton == GLFW_PRESS || rightButton == GLFW_PRESS || middleButton == GLFW_PRESS))
        {
            int x; int y;
            glfwGetMousePos(&x, &y);
            guiStates.lockPositionX = x;
            guiStates.lockPositionY = y;
        }
        if (altPressed == GLFW_PRESS)
        {
            int mousex; int mousey;
            glfwGetMousePos(&mousex, &mousey);
            int diffLockPositionX = mousex - guiStates.lockPositionX;
            int diffLockPositionY = mousey - guiStates.lockPositionY;
            if (guiStates.zoomLock)
            {
                float zoomDir = 0.0;
                if (diffLockPositionX > 0)
                    zoomDir = -1.f;
                else if (diffLockPositionX < 0 )
                    zoomDir = 1.f;
                camera_zoom(camera, zoomDir * GUIStates::MOUSE_ZOOM_SPEED);
            }
            else if (guiStates.turnLock)
            {
                camera_turn(camera, diffLockPositionY * GUIStates::MOUSE_TURN_SPEED,
                            diffLockPositionX * GUIStates::MOUSE_TURN_SPEED);

            }
            else if (guiStates.panLock)
            {
                camera_pan(camera, diffLockPositionX * GUIStates::MOUSE_PAN_SPEED,
                            diffLockPositionY * GUIStates::MOUSE_PAN_SPEED);
            }
            guiStates.lockPositionX = mousex;
            guiStates.lockPositionY = mousey;
        }
  
        // Get camera matrices
        glm::mat4 projection = glm::perspective(45.0f, widthf / heightf, 0.1f, 100.f); 
        glm::mat4 worldToView = glm::lookAt(camera.eye, camera.o, camera.up);
        glm::mat4 objectToWorld;
        glm::mat4 worldToScreen = projection * worldToView;
        glm::mat4 screenToWorld = glm::transpose(glm::inverse(worldToScreen));

        glBindFramebuffer(GL_FRAMEBUFFER, gbufferFbo);
        glDrawBuffers(2, gbufferDrawBuffers);

        // Viewport 
        glViewport( 0, 0, width, height  );

        // Default states
        glEnable(GL_DEPTH_TEST);

        // Clear the front buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Bind gbuffer shader
        glUseProgram(gbuffer_shader.program);
        // Upload uniforms
        glUniformMatrix4fv(gbuffer_projectionLocation, 1, 0, glm::value_ptr(projection));
        glUniformMatrix4fv(gbuffer_viewLocation, 1, 0, glm::value_ptr(worldToView));
        glUniformMatrix4fv(gbuffer_objectLocation, 1, 0, glm::value_ptr(objectToWorld));
        glUniform1f(gbuffer_timeLocation, t);
        glUniform1i(gbuffer_diffuseLocation, 0);
        glUniform1i(gbuffer_specLocation, 1);

        // Bind textures
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, textures[0]);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, textures[1]);

        // Render vaos
        glBindVertexArray(vao[0]);
        glDrawElementsInstanced(GL_TRIANGLES, cube_triangleCount * 3, GL_UNSIGNED_INT, (void*)0, 4);
        glBindVertexArray(vao[1]);
        glDrawElements(GL_TRIANGLES, plane_triangleCount * 3, GL_UNSIGNED_INT, (void*)0);

        // Unbind framebuffer
        glBindFramebuffer(GL_FRAMEBUFFER, 0);

        // Viewport 
        glViewport( 0, 0, width, height );

        // Clear the front buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Bind lighting shader
        glUseProgram(lighting_shader.program);
        // Upload uniforms
        glUniform1i(lighting_materialLocation, 0);
        glUniform1i(lighting_normalLocation, 1);
        glUniform1i(lighting_depthLocation, 2);
        glUniform3fv(lighting_cameraPositionLocation, 1, glm::value_ptr(camera.eye));
        glUniformMatrix4fv(lighting_inverseViewProjectionLocation, 1, 0, glm::value_ptr(screenToWorld));

        // Bind color to unit 0
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, gbufferTextures[0]);        
        // Bind normal to unit 1
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, gbufferTextures[1]);    
        // Bind depth to unit 2
        glActiveTexture(GL_TEXTURE2);
        glBindTexture(GL_TEXTURE_2D, gbufferTextures[2]);        

        // Blit above the rest
        glDisable(GL_DEPTH_TEST);

        glEnable(GL_BLEND);
        glBlendFunc(GL_ONE, GL_ONE);

        for (int i = 0; i < (int) numLights; ++i)
        {
            float tl = t * i;

            //Update light uniforms
            float lightPosition[3] = { sinf(tl) * 10.f, -0.5f, cosf(tl) * 10.f};
            float lightColor[3] = {sinf(tl) *  1.f, 1.f - cosf(tl), -sinf(tl)};
            float lightIntensity = 10.0;

            glUniform3fv(lighting_lightPositionLocation, 1, lightPosition);
            glUniform3fv(lighting_lightColorLocation, 1, lightColor);
            glUniform1f(lighting_lightIntensityLocation, lightIntensity);

            // Draw quad
            glBindVertexArray(vao[2]);
            glDrawElements(GL_TRIANGLES, quad_triangleCount * 3, GL_UNSIGNED_INT, (void*)0);
        }

        glDisable(GL_BLEND);

        // Bind blit shader
        glUseProgram(blit_shader.program);
        // Upload uniforms
        glUniform1i(blit_tex1Location, 0);
        // use only unit 0
        glActiveTexture(GL_TEXTURE0);

        // Viewport 
        glViewport( 0, 0, width/3, height/4  );
        // Bind texture
        glBindTexture(GL_TEXTURE_2D, gbufferTextures[0]);        
        // Draw quad
        glBindVertexArray(vao[2]);
        glDrawElements(GL_TRIANGLES, quad_triangleCount * 3, GL_UNSIGNED_INT, (void*)0);
        // Viewport 
        glViewport( width/3, 0, width/3, height/4  );
        // Bind texture
        glBindTexture(GL_TEXTURE_2D, gbufferTextures[1]);        
        // Draw quad
        glBindVertexArray(vao[2]);
        glDrawElements(GL_TRIANGLES, quad_triangleCount * 3, GL_UNSIGNED_INT, (void*)0);
        // Viewport 
        glViewport( width/3 * 2, 0, width/3, height/4  );
        // Bind texture
        glBindTexture(GL_TEXTURE_2D, gbufferTextures[2]);        
        // Draw quad
        glBindVertexArray(vao[2]);
        glDrawElements(GL_TRIANGLES, quad_triangleCount * 3, GL_UNSIGNED_INT, (void*)0);
        
#if 1
        // Draw UI
        glDisable(GL_DEPTH_TEST);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glViewport(0, 0, width, height);

        unsigned char mbut = 0;
        int mscroll = 0;
        int mousex; int mousey;
        glfwGetMousePos(&mousex, &mousey);
        mousey = height - mousey;

        if( leftButton == GLFW_PRESS )
            mbut |= IMGUI_MBUT_LEFT;

        imguiBeginFrame(mousex, mousey, mbut, mscroll);
        int logScroll = 0;
        char lineBuffer[512];
        imguiBeginScrollArea("001", width - 210, height - 310, 200, 300, &logScroll);
        sprintf(lineBuffer, "FPS %f", fps);
        imguiLabel(lineBuffer);
        imguiSlider("Lights", &numLights, 0.0, 100.0, 1.0);
        imguiEndScrollArea();
        imguiEndFrame();
        imguiRenderGLDraw(width, height); 

        glDisable(GL_BLEND);
#endif
        
        // Check for errors
        GLenum err = glGetError();
        if(err != GL_NO_ERROR)
        {
            fprintf(stderr, "OpenGL Error : %s\n", gluErrorString(err));
            
        }

        // Swap buffers
        glfwSwapBuffers();

    } // Check if the ESC key was pressed or the window was closed
    while( glfwGetKey( GLFW_KEY_ESC ) != GLFW_PRESS &&
           glfwGetWindowParam( GLFW_OPENED ) );

    // Clean UI
    imguiRenderGLDestroy();

    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    exit( EXIT_SUCCESS );
}
Exemplo n.º 6
0
int main()
{
	GLFWwindow* window = nullptr;

	glfwSetErrorCallback(error_callback);

	// Inititiating GLFW library
	if (!glfwInit()) 
		exit(EXIT_FAILURE);

	// Sets hints for the next call to glfwCreateWindow - Keep these for future debugging
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
	glfwWindowHint(GLFW_REFRESH_RATE, GLFW_DONT_CARE);// This hint is ignored for windowed mode windows.

	// Creating window
	window = glfwCreateWindow(640, 480, "Title", NULL, NULL);

	// Failure check - Creating window
	if (!window)
	{
		glfwTerminate();
		exit(EXIT_FAILURE);
	}
	else
	{
		fprintf(stderr, "GLFW Window initialized\n");
	}

	// Bind key-inputs
	glfwSetKeyCallback(window, key_callback);

	// Fetch OpenGL version - Makes sure correct version is loaded from GLEW
	glfwMakeContextCurrent(window);
	// Inititiating GLEW library
	glewExperimental = true;
	GLenum err = glewInit();

	// Failure check - Inititiating GLEW
	if (GLEW_OK != err)
	{
		fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
	}
	else
	{
		fprintf(stderr, "GLEW initialized\n");
	}

#ifdef _DEBUG
	if (glDebugMessageCallback){
		std::cout << "Register OpenGL debug callback " << std::endl;
		glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
		glDebugMessageCallback((GLDEBUGPROC)openglCallbackFunction, nullptr);
		GLuint unusedIds = 0;
		glDebugMessageControl(GL_DONT_CARE,
			GL_DONT_CARE,
			GL_DONT_CARE,
			0,
			&unusedIds,
			true);
	}
	else
	{
		std::cout << "glDebugMessageCallback not available" << std::endl;
	}
#endif

	// VSync
	glfwSwapInterval(1);

	////////////////////////////////////////////////////////////

	// Engine classes
	Graphics ge = Graphics();
	Physics ph = Physics();

	InitMeshes(&ge);

	InitCameras();
	ge.SetCamera(&cameras[cameraIndex]);
	
	fpsCounter fpsC;
	int tickCounter = 400;
	////////////////////////////////////////////////////////////
	while (!glfwWindowShouldClose(window))
	{
		std::stringstream ss;
		ss << fpsC.get();

		glfwSetWindowTitle(window, ss.str().c_str());

		KeyEvents(window, &ge, &ph);

		UpdateProjections(window);
		RotateCamera(&cameras[cameraIndex], window);
		MoveCamera(&cameras[cameraIndex], window);

		if (fpsC.deltaTime() > 0 && tickCounter < 1)
		{
			//ph.move(&mustangHigh, &fpsC);
			ph.move(&EndOfLine, &fpsC);
		}
		else
		{
			tickCounter--;
		}

		Collision(&EndOfLine, &target);
		Collision(&EndOfLine, &target2);

		ge.PrepareRender();
		ge.Render(&mustang);
		ge.Render(&mustang2);
		ge.Render(&mustang3);
		ge.Render(&mustang4);
		ge.Render(&mustangHigh);

		ge.Render(&ground);
		ge.Render(&target);
		ge.Render(&target2);

		ge.Render(&EndOfLine);

		fpsC.tick();
		Sleep(1000 / 120);

		glfwSwapBuffers(window);
		glfwPollEvents();// Processes all pending events
	}
	////////////////////////////////////////////////////////////
	
	glfwDestroyWindow(window);
	glfwTerminate();
	return 0;
}
Exemplo n.º 7
0
int main(int argc, char **argv)
{	
  // Notre fenêtre
	
  SDL_Window* fenetre(0);
  SDL_GLContext contexteOpenGL(0);
	
  SDL_Event event;
  bool done(false);
	
	
  // Initialisation de la SDL
	
  if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_HAPTIC) < 0)
  {
    std::cout << "Erreur lors de l'initialisation de la SDL : " << SDL_GetError() << std::endl;
    SDL_Quit();
		
    return -1;
  }

  IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG);
	
	
  // Version d'OpenGL
	
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
	
	
  // Double Buffer
	
  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
	
  // Création de la fenêtre

  fenetre = SDL_CreateWindow(
    "NGEngine - 01Basic", 
    SDL_WINDOWPOS_CENTERED, 
    SDL_WINDOWPOS_CENTERED, 
    800, 600, 
    SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL
  );

  if(fenetre == 0) {
    std::cout << "Erreur lors de la creation de la fenetre : " << SDL_GetError() << std::endl;
    SDL_Quit();

    return -1;
  }


  // Création du contexte OpenGL

  contexteOpenGL = SDL_GL_CreateContext(fenetre);

  if(contexteOpenGL == 0)
  {
    std::cout << SDL_GetError() << std::endl;
    SDL_DestroyWindow(fenetre);
    SDL_Quit();
    return -1;
  }

  // On initialise GLEW
  GLenum initialisationGLEW( glewInit() );

  // Si l'initialisation a échouée :
  if(initialisationGLEW != GLEW_OK)
  {
    // On affiche l'erreur grâce à la fonction : glewGetErrorString(GLenum code)

    std::cout << "Erreur d'initialisation de GLEW : " << glewGetErrorString(initialisationGLEW) << std::endl;


    // On quitte la SDL

    SDL_GL_DeleteContext(contexteOpenGL);
    SDL_DestroyWindow(fenetre);
    SDL_Quit();

    return -1;
  }

  glClearColor(0.3, 0.3, 0.5, 1.);

  // Vertices et coordonnées

//  float vertices[] = {-0.5, -0.5,   0.0, 0.5,   0.5, -0.5};

  // Création de la subscene

  nge::scene::Scene scene;
  nge::scene::SubScene *subscene = new nge::scene::SubScene(600, 800, 600, 0, 0);

  scene.add(subscene);

  Sint32 vertices[] = {
    0, 0,
    160, 0,
    0, 160,
    160, 160,
  };

  Uint8 colors[] = {
    255, 0, 0, 255, 
    0, 255, 255, 255,
    0, 255, 0, 255,
    0, 0, 255, 255
  };

  double texcoords[] {
    0., 0.,
    1., 0.,
    0., 1.,
    1., 1.
  };

  nge::texture::Texture *tex = NGE_SDL_Texture_Load("nge.png");
  nge::video::D2::entity::Basic 
    e1(4, 1, GL_TRIANGLE_STRIP), 
    e2(4, 1, GL_TRIANGLE_STRIP), 
    e3(4, 1, GL_TRIANGLE_STRIP), 
    e4(4, 1, GL_TRIANGLE_STRIP);

  nge::video::shader::Shader *shaders[3];

  shaders[0] = new nge::video::shader::Shader();
  if(!shaders[0]->load_files("Shaders/vertex2.vert", "Shaders/vertex2.frag"))
    printf("fichiers des shaders non trouvés.\n");

  shaders[1] = new nge::video::shader::Shader();
  if(!shaders[1]->load_files("Shaders/vertex2color4.vert", "Shaders/vertex2color4.frag"))
    printf("fichiers des shaders non trouvés.\n");

  shaders[2] = new nge::video::shader::Shader();
  if(!shaders[2]->load_files("Shaders/vertex2color4tex2.vert", "Shaders/vertex2color4tex2.frag"))
    printf("fichiers des shaders non trouvés.\n");

  if(!shaders[0]->compile())
    printf("shaders not compiled\n");
  else 
    printf("shaders compiled\n");

  if(!shaders[1]->compile())
    printf("shaders not compiled\n");
  else 
    printf("shaders compiled\n");

  if(!shaders[2]->compile())
    printf("shaders not compiled\n");
  else 
    printf("shaders compiled\n");

  shaders[0]->set_matrix(&subscene->_projection, &subscene->_modelview);
  shaders[1]->set_matrix(&subscene->_projection, &subscene->_modelview);
  shaders[2]->set_matrix(&subscene->_projection, &subscene->_modelview);

  e1.setVertexBuf(vertices, false);  // (x, y) couples
  e1._shader = shaders[0];

  e2.setVertexBuf(vertices, false);  // (x, y) couples
  e2.setColorBuf(colors, false);
  e2._shader = shaders[1];
  *(e2.getPosition()) = glm::vec2(165, 0);

  e3.setVertexBuf(vertices, false);  // (x, y) couples
  e3.setColorBuf(colors, false);
  e3.setTexCoords(texcoords, false);
  e3.setTexture(tex, true); // free the texture
  e3._shader = shaders[2];
  *(e3.getPosition()) = glm::vec2(330, 0);

  e4.setVertexBuf(vertices, false);  // (x, y) couples
  e4.setColorBuf(colors, false);
  e4.setTexCoords(texcoords, false);
  e4.setTexture(tex, false); // don't free the texture
  e4._shader = shaders[2];
  *(e4.getPosition()) = glm::vec2(0, 170);

  subscene->add(&e1);
  subscene->add(&e2);
  subscene->add(&e3);
  subscene->add(&e4);

  char down;
  
  nge::video::D2::Camera *cam;
  cam = subscene->getCamera2D();

  bool t[6] = {0};

  // Boucle principale
  while(!done)
  {
    while(SDL_PollEvent(&event)) {

      switch(event.type) {
        
        case SDL_QUIT:
          done = 1;
          break;

        case SDL_KEYDOWN:
          switch (event.key.keysym.sym) {
            case SDLK_ESCAPE:
              done = 1;
              break;
            case SDLK_LEFT:
              t[0] = 1;
              break;
            case SDLK_RIGHT:
              t[1] = 1;
              break;
            case SDLK_UP:
              t[2] = 1;
              break;
            case SDLK_DOWN:
              t[3] = 1;
              break;
            case SDLK_z:
              t[4] = 1;
              break;
            case SDLK_s:
              t[5] = 1;
              break;
            default:
              break;
          }
          break;
        case SDL_KEYUP:
          switch (event.key.keysym.sym) {
            case SDLK_LEFT:
              t[0] = 0;
              break;
            case SDLK_RIGHT:
              t[1] = 0;
              break;
            case SDLK_UP:
              t[2] = 0;
              break;
            case SDLK_DOWN:
              t[3] = 0;
              break;
            case SDLK_z:
              t[4] = 0;
              break;
            case SDLK_s:
              t[5] = 0;
              break;
            default:
              break;
          }
          break;
        default:
          break;
      }
    }

#define NB 5

    if(t[0])
      cam->moveX(-NB);
    else;

    if(t[1])
      cam->moveX(NB);
    else;

    if(t[2])
      cam->moveY(-NB);
    else;

    if(t[3])
      cam->moveY(NB);
    else;

#undef NB

    if(t[4]) {
      cam->increaseWidth(- cam->getZoomXSpeed() * 2);
      cam->increaseHeight(- cam->getZoomYSpeed() * 2);
    }
    else;

    if(t[5]) {
      cam->increaseWidth(cam->getZoomXSpeed() * 2);
      cam->increaseHeight(cam->getZoomYSpeed() * 2);
    }
    else;

    // on met à jour
    if(e4._alpha == 255)
      down = -5;
    else if(e4._alpha == 0)
      down = 5;
    
    e4._alpha += down;
    // Nettoyage de l'écran

    glClear(GL_COLOR_BUFFER_BIT);
    subscene->draw();

    // Actualisation de la fenêtre

    SDL_GL_SwapWindow(fenetre);

    SDL_Delay(10);
  }


  // On quitte la SDL

  delete shaders[0];
  delete shaders[1];
  delete shaders[2];

  SDL_GL_DeleteContext(contexteOpenGL);
  SDL_DestroyWindow(fenetre);
  SDL_Quit();

  return 0;
}
// ------------------------------------------------------------------- main ---
int main( int argc, char **argv )
{
    GLFWwindow* window;

    glfwSetErrorCallback( error_callback );

    if (!glfwInit( ))
    {
        exit( EXIT_FAILURE );
    }

    glfwWindowHint( GLFW_VISIBLE, GL_TRUE );
    glfwWindowHint( GLFW_RESIZABLE, GL_FALSE );

    window = glfwCreateWindow( 1, 1, "Distance fields demo", NULL, NULL );

    if (!window)
    {
        glfwTerminate( );
        exit( EXIT_FAILURE );
    }

    glfwMakeContextCurrent( window );
    glfwSwapInterval( 1 );

    glfwSetFramebufferSizeCallback( window, reshape );
    glfwSetWindowRefreshCallback( window, display );
    glfwSetKeyCallback( window, keyboard );

#ifndef __APPLE__
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf( stderr, "Error: %s\n", glewGetErrorString(err) );
        exit( EXIT_FAILURE );
    }
    fprintf( stderr, "Using GLEW %s\n", glewGetString(GLEW_VERSION) );
#endif

    init();

    glfwSetWindowSize( window, 512, 512 );
    glfwShowWindow( window );

    glfwSetTime(0.0);

    while(!glfwWindowShouldClose( window ))
    {
        display( window );

        angle += 30 * glfwGetTime();
        glfwSetTime(0.0);

        glfwPollEvents( );
    }

    glfwDestroyWindow( window );
    glfwTerminate( );

    return EXIT_SUCCESS;
}
Exemplo n.º 9
0
// --------------------------------------------------------------------------------------------------------------------
bool GfxApiOpenGLBase::Init(const std::string& _title, int _x, int _y, int _width, int _height)
{
#if defined(_DEBUG)
    //glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, 1);
#endif

    mWnd = CreateGLWindow(_title.c_str(), _x, _y, _width, _height);
    if (!mWnd) {
        console::warn("Unable to create SDL Window, which is required for GL.");
        return false;
    }

    if (!GfxBaseApi::Init(_title, _x, _y, _width, _height)) {
        return false;
    }

    glfwMakeContextCurrent(mWnd);

    if (g_bInitOpenGL)
    {
        g_bInitOpenGL = false;
        GLenum err = glewInit();
        if (GLEW_OK != err)
        {
            console::error("Unable to initialize GLEW; err: %s -- required -- so exiting.", glewGetErrorString(err));
            return false;
        }
    }

    console::log("GL created successfully! Info follows.");
    console::log("Vendor: %s", glGetString(GL_VENDOR));
    console::log("Renderer: %s", glGetString(GL_RENDERER));
    console::log("Version: %s", glGetString(GL_VERSION));
    console::log("Shading Language Version: %s", glGetString(GL_SHADING_LANGUAGE_VERSION));

    glfwSwapInterval(0);

    // Default GL State
    glCullFace(GL_FRONT);
    glEnable(GL_CULL_FACE);
    glDisable(GL_SCISSOR_TEST);
    glEnable(GL_DEPTH_TEST);
    glDepthMask(1);
    glDepthFunc(GL_LESS);
    glDisable(GL_BLEND);
    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);

#if defined(_DEBUG)
    if (glDebugMessageControl != NULL && glDebugMessageCallback != NULL) {
        glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
        // glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_OTHER, GL_DEBUG_SEVERITY_LOW, 0, nullptr, GL_FALSE);
        glDebugMessageCallback(ErrorCallback, nullptr);
        glEnable(GL_DEBUG_OUTPUT);
    }
#endif

    return true;
}
Exemplo n.º 10
0
int main(int /* argc */, char ** /* argv */) 
{
    // 
    // Setup GLFW, glew and some initial GL state
    //
    static const char windowTitle[] = "CPU Subdivision Example";

    if (not glfwInit()) {
        printf("Failed to initialize GLFW\n");
        return 1;
    }
    
#define CORE_PROFILE
#ifdef CORE_PROFILE
    setGLCoreProfile();
#endif

    #if GLFW_VERSION_MAJOR>=3
        if (not (g_window=glfwCreateWindow(g_width, g_height, windowTitle, NULL, NULL))) {
            printf("Failed to open window.\n");
            glfwTerminate();
            return 1;
        }
        glfwMakeContextCurrent(g_window);

        // accommodate high DPI displays (e.g. mac retina displays)
        glfwGetFramebufferSize(g_window, &g_width, &g_height);
        glfwSetFramebufferSizeCallback(g_window, reshape);

        glfwSetWindowCloseCallback(g_window, windowClose);
    #else
        if (glfwOpenWindow(g_width, g_height, 8, 8, 8, 8, 24, 8, GLFW_WINDOW) == GL_FALSE) {
            printf("Failed to open window.\n");
            glfwTerminate();
            return 1;
        }
        glfwSetWindowTitle(windowTitle);
        glfwSetWindowSizeCallback(reshape);
        glfwSetWindowCloseCallback(windowClose);
    #endif

    

#if defined(OSD_USES_GLEW)
#ifdef CORE_PROFILE
    // this is the only way to initialize glew correctly under core profile context.
    glewExperimental = true;
#endif
    if (GLenum r = glewInit() != GLEW_OK) {
        printf("Failed to initialize glew. Error = %s\n", glewGetErrorString(r));
        exit(1);
    }
#ifdef CORE_PROFILE
    // clear GL errors which was generated during glewInit()
    glGetError();
#endif
#endif

    initOsd();
    
    //
    // Start the main drawing loop
    //
    while (g_running) {
        idle();
        display();
        
#if GLFW_VERSION_MAJOR>=3
        glfwPollEvents();
        glfwSwapBuffers(g_window);
#else
        glfwSwapBuffers();
#endif
        
        glFinish();
    }
}
Exemplo n.º 11
0
int main(void)
{
    // Create window and load extensions
    glfwSetErrorCallback(errorCallback);
    if (!glfwInit()) {
        std::exit(EXIT_FAILURE);
    }

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* window = glfwCreateWindow(globals.width, globals.height,
        "Toon shading", NULL, NULL);
    if (!window) {
        glfwTerminate();
        std::exit(EXIT_FAILURE);
    }
    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);

    glewExperimental = GL_TRUE;
    GLenum status = glewInit();
    if (status != GLEW_OK) {
        std::cerr << "Error: " << glewGetErrorString(status) << std::endl;
        std::exit(EXIT_FAILURE);
    }
    std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;

    glfwSetKeyCallback(window, keyCallback);
    glfwSetMouseButtonCallback(window, mouseButtonCallback);
    glfwSetCursorPosCallback(window, cursorPosCallback);
    glfwSetFramebufferSizeCallback(window, framebufferSizeCallback);
    glfwSetScrollCallback(window, scrollCallback);

    TwInit(TW_OPENGL_CORE, NULL);
    TwWindowSize(globals.width, globals.height);

    TwBar *myBar;
    myBar = TwNewBar("Toon config");

    TwAddVarCB(myBar, "X pos", TW_TYPE_FLOAT, setLightXpos, getLightXpos , &globals.lightdir_x, " step=0.5 group=Light label='x-pos' ");
    TwAddVarCB(myBar, "Y pos", TW_TYPE_FLOAT, setLightYpos, getLightYpos , &globals.lightdir_y, " step=0.5 group=Light label='y-pos' ");
    TwAddVarCB(myBar, "Z pos", TW_TYPE_FLOAT, setLightZpos, getLightZpos , &globals.lightdir_z, " step=0.01 group=Light label='z-pos' ");

    TwAddVarRW(myBar, "Ambient color", TW_TYPE_COLOR3F, &globals.ambientColor, "group=Material colormode=hls");

    TwAddVarRW(myBar, "Diffuse color", TW_TYPE_COLOR3F, &globals.diffuseColor, "group=Material colormode=hls");
    TwAddVarCB(myBar, "Diffuse intensity", TW_TYPE_FLOAT,setDifflvl, getDifflvl, &globals.material_kd, "group=Material step=0.01");

    TwAddVarRW(myBar, "Outline color", TW_TYPE_COLOR3F, &globals.outlineColor, "group=Material colormode=hls");
    TwAddVarCB(myBar, "Outline intensity", TW_TYPE_FLOAT, setOutlinelvl, getOutlinelvl , &globals.outline_intensity, " step=0.01 min=0.0 max=1.0 group=Material");

    TwAddVarCB(myBar, "Background color", TW_TYPE_COLOR3F, setBgcolorCallBack, getBgcolorCallBack, &globals.bg_color[0], "group=Misc colormode=hls");

    TwAddVarCB(myBar, "Color levels", TW_TYPE_INT8, setColorlvl, getColorlvl , &globals.colorlvl, " step=1 min=2 max=6 group=Material");


    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);
    // Initialize rendering
    init();

    // Start rendering loop
    while (!glfwWindowShouldClose(window)) {
        display();
        TwDraw();
        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    glfwDestroyWindow(window);
    glfwTerminate();

    exit(EXIT_SUCCESS);
}
Exemplo n.º 12
0
bool CGameEngineGL::BInitializeGraphics()
{
	int windowX = SDL_WINDOWPOS_CENTERED;
	int windowY = SDL_WINDOWPOS_CENTERED;
	int nWindowWidth, nWindowHeight;
	if( !m_pHmd )
	{
		nWindowWidth = m_nWindowWidth = 1024;
		nWindowHeight = m_nWindowHeight = 768;
	}
	else
	{
		uint32_t unWidth, unHeight;
		m_pHmd->GetWindowBounds( &windowX, &windowY, &unWidth, &unHeight );
		nWindowWidth = unWidth;
		nWindowHeight = unHeight;
		m_nWindowWidth = 640;
		m_nWindowHeight = 480;
	}

	SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
	SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );

	m_window = SDL_CreateWindow( "SteamworksExample",
					windowX,
					windowY,
					nWindowWidth,
					nWindowHeight,
					SDL_WINDOW_OPENGL );
	if ( !m_window ) {
		OutputDebugString( "Couldn't create SDL window: " );
		OutputDebugString( SDL_GetError() );
		OutputDebugString( "\n" );
		return false;
	}

	m_context = SDL_GL_CreateContext( m_window );
	if ( !m_context ) {
		OutputDebugString( "Couldn't create OpenGL context: " );
		OutputDebugString( SDL_GetError() );
		OutputDebugString( "\n" );
		return false;
	}
	
	GLenum err = glewInit();
	if( err != GLEW_OK )
	{
		fprintf(stderr, "glewInit failed with %s\n", glewGetErrorString( err ) );
		return false;
	}

	SDL_GL_SetSwapInterval( 1 );

	// Clear any errors
	glGetError();

	glClearDepth( 1.0f );
	glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );

	glEnable( GL_BLEND );
	glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

	glDisable( GL_CULL_FACE );
	glDisable( GL_ALPHA_TEST );
	glDisable( GL_STENCIL_TEST );
	glDisable( GL_SCISSOR_TEST );
	glDisable( GL_LIGHTING );
	glDisable( GL_DEPTH_TEST );
	glDisable( GL_FOG );

	glDepthMask( GL_FALSE );

	// We always need these two
	glEnableClientState( GL_COLOR_ARRAY );
	glEnableClientState( GL_VERTEX_ARRAY );

	// This we'll enable as needed
	glDisableClientState( GL_TEXTURE_COORD_ARRAY );

	glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glTranslatef( 0, 0, 0 );
	
	glMatrixMode( GL_TEXTURE );
	glLoadIdentity();
	glTranslatef( 0, 0, 0 );

	glDepthRange( 0.0f, 1.0f );
	
	// create some other VR-related resources
	if( m_pHmd )
	{
		if( !m_pVRGLHelper->BInit( m_pHmd ) )
		{
			OutputDebugString( "Unable to init VRGLHelper\n" );
			return false;
		}
		m_pVRGLHelper->InitUIRenderTarget( m_nWindowWidth, m_nWindowHeight );
		m_pVRGLHelper->BInitPredistortRenderTarget();
	}

	AdjustViewport();

	return true;
}
Exemplo n.º 13
0
// ------------------------------------------------------------------- main ---
int main( int argc, char **argv )
{
    GLFWwindow* window;

    glfwSetErrorCallback( error_callback );

    if (!glfwInit( ))
    {
        exit( EXIT_FAILURE );
    }

    glfwWindowHint( GLFW_VISIBLE, GL_TRUE );
    glfwWindowHint( GLFW_RESIZABLE, GL_FALSE );

    window = glfwCreateWindow( 1, 1, "Freetype OpenGL / LCD filtering", NULL, NULL );

    if (!window)
    {
        glfwTerminate( );
        exit( EXIT_FAILURE );
    }

    glfwMakeContextCurrent( window );
    glfwSwapInterval( 1 );

    glfwSetFramebufferSizeCallback( window, reshape );
    glfwSetWindowRefreshCallback( window, display );
    glfwSetKeyCallback( window, keyboard );

#ifndef __APPLE__
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf( stderr, "Error: %s\n", glewGetErrorString(err) );
        exit( EXIT_FAILURE );
    }
    fprintf( stderr, "Using GLEW %s\n", glewGetString(GLEW_VERSION) );
#endif
    size_t i;
    texture_font_t *font = 0;
    atlas = texture_atlas_new( 512, 512, 3 );
    const char * filename = "fonts/Vera.ttf";
    wchar_t *text = L"A Quick Brown Fox Jumps Over The Lazy Dog 0123456789";
    buffer = vertex_buffer_new( "vertex:3f,tex_coord:2f,color:4f,ashift:1f,agamma:1f" );
    vec2 pen = {{0,0}};
    vec4 color = {{0,0,0,1}};

    for( i=7; i < 27; ++i)
    {
        font = texture_font_new_from_file( atlas, i, filename );
        pen.x = 0;
        pen.y -= font->height;
        texture_font_load_glyphs( font, text );
        add_text( buffer, font, text, &color, &pen );
        texture_font_delete( font );
    }
    glBindTexture( GL_TEXTURE_2D, atlas->id );

    shader = shader_load( "shaders/text.vert",
                          "shaders/text.frag" );
    mat4_set_identity( &projection );
    mat4_set_identity( &model );
    mat4_set_identity( &view );

    glfwSetWindowSize( window, 800, 500 );
    glfwShowWindow( window );

    while(!glfwWindowShouldClose( window ))
    {
        display( window );
        glfwPollEvents( );
    }

    glfwDestroyWindow( window );
    glfwTerminate( );

    return 0;
}
Exemplo n.º 14
0
bool VideoSettings::Init()
{
	int glewErr = glewInit();
    if (glewErr != GLEW_OK) {
        // problem: glewInit failed, something is seriously wrong
		wxLogMessage(wxT("Error: GLEW failed to initialise.\n\tGLEW Error: %s\n"), glewGetErrorString(glewErr));
		return false;
	}  else {
		wxLogMessage(wxT("Info: GLEW successfully initiated.\n"));
	}

	// Now get some specifics on the card
	// First up, the details
	if(glewIsSupported("GL_EXT_texture_filter_anisotropic"))
		glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, (GLint*)&AnisofilterLevel);
	else
		AnisofilterLevel = 0;

	glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, (GLint*)&numTextureUnits);
	vendor = ((char *)glGetString(GL_VENDOR));
	version = ((char *)glGetString(GL_VERSION));
	renderer = ((char *)glGetString(GL_RENDERER));

	//char *extens = (char *)glGetString(GL_EXTENSIONS);
	//wxLogMessage(extens);

	double num = atof((char *)glGetString(GL_VERSION));
	supportOGL20 = (num >= 2.0);
	if (supportOGL20)
		supportNPOT = true;
	else
		supportNPOT = glewIsSupported("GL_ARB_texture_non_power_of_two") == GL_TRUE ? true : false;

	supportFragProg = glewIsSupported("GL_ARB_fragment_program") == GL_TRUE ? true : false;
	supportVertexProg = glewIsSupported("GL_ARB_vertex_program") == GL_TRUE ? true : false;
	supportGLSL = glewIsSupported("GL_ARB_shading_language_100") == GL_TRUE ? true : false;
	supportShaders = (supportFragProg && supportVertexProg);

	supportDrawRangeElements = glewIsSupported("GL_EXT_draw_range_elements") == GL_TRUE ? true : false;
	supportMultiTex = glewIsSupported("GL_ARB_multitexture") == GL_TRUE ? true : false;
	supportVBO = glewIsSupported("GL_ARB_vertex_buffer_object") == GL_TRUE ? true : false;
	supportCompression = glewIsSupported("GL_ARB_texture_compression GL_ARB_texture_cube_map GL_EXT_texture_compression_s3tc") == GL_TRUE ? true : false;
	supportPointSprites = glewIsSupported("GL_ARB_point_sprite GL_ARB_point_parameters") == GL_TRUE ? true : false;
#ifdef _WINDOWS
	supportPBO = wglewIsSupported("WGL_ARB_pbuffer WGL_ARB_render_texture") == GL_TRUE ? true : false;
	supportAntiAlias = wglewIsSupported("WGL_ARB_multisample") == GL_TRUE ? true : false;
	supportWGLPixelFormat = wglewIsSupported("WGL_ARB_pixel_format") == GL_TRUE ? true : false;
#endif
	supportFBO = glewIsSupported("GL_EXT_framebuffer_object") == GL_TRUE ? true : false;
	supportTexRects = glewIsSupported("GL_ARB_texture_rectangle") == GL_TRUE ? true : false;

	// Now output and log the info
	wxLogMessage(wxT("Video Renderer: %s"), renderer);
	wxLogMessage(wxT("Video Vendor: %s"), vendor);
	wxLogMessage(wxT("Driver Version: %s"), version);

	
	if (wxString(renderer, wxConvUTF8).IsSameAs(wxT("GDI Generic"), false)) {
		wxLogMessage(wxT("\tWarning: Running in software mode, this is not enough. Please try updating your video drivers."));
		// bloody oath - wtb a graphics card
		hasHardware = false;
	} else {
		hasHardware = true;
	}
	
	/*
	// Display Device info
	wxLogMessage(wxT("Display Device Count: %i"), wxDisplay::GetCount());
	for (size_t i=0; i<wxDisplay::GetCount(); i++) {
		wxDisplay disp(i);
		wxRect bounds = disp.GetGeometry();
		wxString name = disp.GetName();
		wxLogMessage(wxT("Device Name: %s\n Primary Device: %i\n Bit-Depth: %ibits\n Window Bounds: %i,%i,%i,%i\n"), name.c_str(), disp.IsPrimary(), disp.GetCurrentMode().GetDepth(), bounds.x, bounds.y, bounds.width, bounds.height);
	}

	if (wxDisplay::GetCount() > 1) {
		// TODO: If they have more than one device we should ask which they want to use.
		
	}
	*/

	wxLogMessage(wxT("Support wglPixelFormat: %s"), supportWGLPixelFormat ? wxT("true") : wxT("false"));
	wxLogMessage(wxT("Support Texture Compression: %s"), supportCompression ? wxT("true") : wxT("false"));
	wxLogMessage(wxT("Support Multi-Textures: %s"), supportMultiTex ? wxT("true") : wxT("false"));
	wxLogMessage(wxT("Support Draw Range Elements: %s"), supportDrawRangeElements ? wxT("true") : wxT("false"));
	wxLogMessage(wxT("Support Vertex Buffer Objects: %s"), supportVBO ? wxT("true") : wxT("false"));
	wxLogMessage(wxT("Support Point Sprites: %s"), supportPointSprites ? wxT("true") : wxT("false"));
	wxLogMessage(wxT("Support Pixel Shaders: %s"), supportFragProg ? wxT("true") : wxT("false"));
	wxLogMessage(wxT("Support Vertex Shaders: %s"), supportVertexProg ? wxT("true") : wxT("false"));
	wxLogMessage(wxT("Support GLSL: %s"), supportGLSL ? wxT("true") : wxT("false"));
	wxLogMessage(wxT("Support Anti-Aliasing: %s"), supportAntiAlias ? wxT("true") : wxT("false"));
	wxLogMessage(wxT("Support Pixel Buffer Objects: %s"), supportPBO ? wxT("true") : wxT("false"));
	wxLogMessage(wxT("Support Frame Buffer Objects: %s"), supportFBO ? wxT("true") : wxT("false"));
	wxLogMessage(wxT("Support Non-Power-of-Two: %s"), supportNPOT ? wxT("true") : wxT("false"));
	wxLogMessage(wxT("Support Rectangle Textures: %s"), supportTexRects ? wxT("true") : wxT("false"));
	wxLogMessage(wxT("Support OpenGL 2.0: %s"), supportOGL20 ? wxT("true") : wxT("false"));

	// Max texture sizes
	GLint texSize; 
	// Rectangle
	if (glewIsSupported("GL_ARB_texture_rectangle")) {
		glGetIntegerv(GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB, &texSize); 
		wxLogMessage(wxT("Max Rectangle Texture Size Supported: %i"), texSize);
	}
	// Square
	glGetIntegerv(GL_MAX_TEXTURE_SIZE, &texSize); 
	wxLogMessage(wxT("Max Texture Size Supported: %i\n"), texSize);
	

	
	// Debug:
	//supportPointSprites = false; // Always set to false,  for now.
	//supportVBO = false;
	//supportFBO = false;
	//supportNPOT = false;
	//supportPBO = false;
	//supportCompression = false;
	//supportTexRects = false;

	init = true;

	return true;
}
Exemplo n.º 15
0
Moose::Window::CScreen::CScreen()
{
  
  const SDL_VideoInfo *sdlVideoInfo = 0;
  if ( SDL_Init( SDL_INIT_VIDEO ) < 0 )
  {
    g_Error << "Couldn't initialize screen (SDL_Init())!\n";
  }
  else
  {

    sdlVideoInfo = SDL_GetVideoInfo();

    if ( !sdlVideoInfo )
    {
      g_Error << "Couldn't initialize screen "
              << "( SDL_GetVideoInfo())!\n";

    }
    else
    {
      // Define which screen depth should be used, currently allowed are
      // 32, 24 and 16. Any other ScreenDepth will revert to desktop depth.
      switch ( m_iScreenDepth ) {

      case 32:
      case 24:
      case 16:
        break;

      default:
        m_iScreenDepth = sdlVideoInfo->vfmt->BitsPerPixel;
        break;
      }




      SDL_GL_SetAttribute(SDL_GL_RED_SIZE,   m_iRedSize);
      SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, m_iGreenSize);
      SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,  m_iBlueSize);
      SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, m_iDepthBufferSize);
      SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, m_iMultiSampleBuffers );
      SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, m_iMultiSampleSamples );
      SDL_GL_SetAttribute (SDL_GL_DOUBLEBUFFER, m_bDoubleBuffer);
#ifdef MOOSE_USE_OPENGL3
      SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, m_iGLMajorVersion);
      SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, m_iGLMinorVersion);

      m_pMainWindow = SDL_CreateWindow( m_ScreenName.c_str(),
                                        SDL_WINDOWPOS_CENTERED, 
                                        SDL_WINDOWPOS_CENTERED, 
                                        m_iWidth,
                                        m_iHeight,
                                        SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
      if ( m_pMainWindow == NULL)
      {
        g_Error << "Couldn't initialize screen "
                << "( SDL_CreateWindow: "
                << SDL_GetError() << ")!\n";
      }

      m_pGLContext = SDL_GL_CreateContext(m_pMainWindow);
      g_Log << "Ladies and gents, we have OpenGL 3.2!\n";
#else
      if ( SDL_SetVideoMode( m_iWidth,
                             m_iHeight,
                             m_iScreenDepth,
                             m_iVideoModeFlags) == NULL )
      {
        
        g_Error << "Couldn't initialize screen "
                << "( SDL_SetVideoMode: "
                << SDL_GetError() << ")!\n";
      }
      g_Log << "Ladies and gents, we have OpenGL 2.x\n";
#endif
      
    } // ..!sdlVideoInfo
  } // ..SDL_Init
  GLenum status = glewInit();
  if ( status != GLEW_OK  )
  {
    g_Error << "Error initializing GLEW: " << glewGetErrorString(status)<< "\n";
  }
#ifdef MOOSE_USE_OPENGL3

  SDL_GL_SetSwapInterval(m_bVerticalSync);
  // check actual state
  switch(SDL_GL_GetSwapInterval())
  {
  case 1:
    m_bVerticalSync = 1;
  default:
    m_bVerticalSync = 0;
  }
#endif
  // When images are loaded as textures they are flipped and mirrored over Y-axis.
  // By manipulating the texture matrix accordingly we can get rid of the annoyance.
  //
  // Unfortunately, this bugger messes up the GL_TEXTURE_RECTANGLE_ARB extension.
  // (It took Couple of hours of debugging until the culprit was ACCIDENTALY found)
  // So, a better ( only ) solution is to flip image directly using SDL_Surface.
  //
  //glMatrixMode(GL_TEXTURE);
  //glRotatef(180.0f,0.0f,0.0f,1.0f);
  //glScalef(-1.0f,1.0f,1.0f);
  //glMatrixMode(GL_MODELVIEW);

  // Register ffmpeg-provided codecs for video textures
  //av_register_all();
}
Exemplo n.º 16
0
/*
    PsychOSOpenOnscreenWindow()
    
    Creates the pixel format and the context objects and then instantiates the context onto the screen.
    
    -The pixel format and the context are stored in the target specific field of the window recored.  Close
    should clean up by destroying both the pixel format and the context.
    
    -We mantain the context because it must be be made the current context by drawing functions to draw into 
    the specified window.
    
    -We maintain the pixel format object because there seems to be now way to retrieve that from the context.
    
    -To tell the caller to clean up PsychOSOpenOnscreenWindow returns FALSE if we fail to open the window. It 
    would be better to just issue an PsychErrorExit() and have that clean up everything allocated outside of
    PsychOpenOnscreenWindow().
*/
boolean PsychOSOpenOnscreenWindow(PsychScreenSettingsType *screenSettings, PsychWindowRecordType *windowRecord, int numBuffers, int stereomode, int conserveVRAM)
{
  RECT winRec;
  PsychRectType             screenrect;
  CGDirectDisplayID         cgDisplayID;
  int         pf;
  unsigned int nNumFormats;
  HDC         hDC;
  HWND        hWnd;
  WNDCLASS    wc;
  PIXELFORMATDESCRIPTOR pfd;
  int         attribs[48];
  int         attribcount;
  float       fattribs[2]={0,0};
  int x, y, width, height, i, bpc;
  GLenum      glerr;
  DWORD flags;
  boolean fullscreen = FALSE;
  DWORD windowStyle = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  // The WS_EX_NOACTIVATE flag prevents the window from grabbing keyboard focus. That way,
  // the new Java-GetChar can do its job.
  DWORD windowExtendedStyle = WS_EX_APPWINDOW | 0x08000000; // const int WS_EX_NOACTIVATE = 0x08000000;

	 // Init to safe default:
    windowRecord->targetSpecific.glusercontextObject = NULL;
    
    // Map the logical screen number to a device handle for the corresponding
    // physical display device: CGDirectDisplayID is currently typedef'd to a
    // HDC windows hardware device context handle.
    PsychGetCGDisplayIDFromScreenNumber(&cgDisplayID, screenSettings->screenNumber);

    // Check if this should be a fullscreen window:
    PsychGetScreenRect(screenSettings->screenNumber, screenrect);
    if (PsychMatchRect(screenrect, windowRecord->rect)) {
      // This is supposed to be a fullscreen window with the dimensions of
      // the current display/desktop:
      // Switch system to fullscreen-mode without changing any settings:
      fullscreen = ChangeScreenResolution(screenSettings->screenNumber, 0, 0, 0, 0);
    }
    else {
      // Window size different from current screen size:
      // A regular desktop window with borders and control icons is requested, e.g., for debugging:
      fullscreen = FALSE;
    }

	 // Special case for explicit multi-display setup under Windows when opening a window on
	 // screen zero. We enforce the fullscreen - flag, aka a borderless top level window. This way,
    // if anything of our automatic full-desktop window emulation code goes wrong on exotic setups,
    // the user can still enforce a suitably positioned and sized borderless toplevel window.
    if (PsychGetNumDisplays()>2 && screenSettings->screenNumber == 0) fullscreen = TRUE;

    if (fullscreen) {
      windowStyle = WS_POPUP;		      // Set The WindowStyle To WS_POPUP (Popup Window without borders)
      windowExtendedStyle |= WS_EX_TOPMOST;   // Set The Extended Window Style To WS_EX_TOPMOST
    }
    else {
      windowStyle |= WS_OVERLAPPEDWINDOW;
      windowExtendedStyle |= WS_EX_TOPMOST;   // Set The Extended Window Style To WS_EX_TOPMOST
    }

    // Define final position and size of window:
    x=windowRecord->rect[kPsychLeft];
    y=windowRecord->rect[kPsychTop];
    width=PsychGetWidthFromRect(windowRecord->rect);
    height=PsychGetHeightFromRect(windowRecord->rect);

    // Register our own window class for Psychtoolbox onscreen windows:
    // Only register the window class once - use hInstance as a flag.
    if (!hInstance) {
      hInstance = GetModuleHandle(NULL);
      wc.style         = CS_OWNDC;
      wc.lpfnWndProc   = WndProc;
      wc.cbClsExtra    = 0;
      wc.cbWndExtra    = 0;
      wc.hInstance     = hInstance;
      wc.hIcon         = LoadIcon(hInstance, IDI_WINLOGO);
      wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
      wc.hbrBackground = NULL;
      wc.lpszMenuName  = NULL;
      wc.lpszClassName = "PTB-OpenGL";

      if (!RegisterClass(&wc)) {
		  hInstance = 0;
        printf("\nPTB-ERROR[Register Windowclass failed]: Unknown error, Win32 specific.\n\n");
        return(FALSE);
      }
    }

    //if (PSYCH_DEBUG == PSYCH_ON) printf("Creating Window...\n");

    // Adjust window bounds to account for the window borders if we are in non-fullscreen mode:
    if (!fullscreen) {
      winRec.left=x; winRec.top=y; winRec.right=x+width; winRec.bottom=y+height;
      AdjustWindowRectEx(&winRec, windowStyle, 0, windowExtendedStyle);
      x=winRec.left; y=winRec.top; width=winRec.right - winRec.left; height=winRec.bottom - winRec.top;
    }

    // Window class registered: Create a window of this class with some specific properties:
    hWnd = CreateWindowEx(windowExtendedStyle,
			  "PTB-OpenGL",
			  "PTB Onscreen window",
			  windowStyle,
			  x, y, width, height, NULL, NULL, hInstance, NULL);

    if (hWnd == NULL) {
        printf("\nPTB-ERROR[CreateWindow() failed]: Unknown error, Win32 specific.\n\n");
        return(FALSE);
    }

    // Retrieve device context for the window:
    hDC = GetDC(hWnd);

    // Setup optional flags for pixelformat:
    flags = 0;
    // Init pfd to zero:
    memset(&pfd, 0, sizeof(pfd));
    attribcount = 0;

    attribs[attribcount++]=0x2001; // WGL_DRAW_TO_WINDOW_ARB
    attribs[attribcount++]=GL_TRUE;
    attribs[attribcount++]=0x2010; // WGL_SUPPORT_OPENGL_ARB
    attribs[attribcount++]=GL_TRUE;
    attribs[attribcount++]=0x2007; // WGL_SWAP_METHOD_ARB
    attribs[attribcount++]=0x2028; // WGL_SWAP_EXCHANGE_ARB
    attribs[attribcount++]=0x2013; // WGL_PIXEL_TYPE_ARB
    
    // Select either floating point or fixed point framebuffer:
    if (windowRecord->depth == 64 || windowRecord->depth == 128) {
      // Request a floating point drawable instead of a fixed-point one:
      attribs[attribcount++]=WGL_TYPE_RGBA_FLOAT_ARB;
    }
    else {
      // Request standard fixed point drawable:
      attribs[attribcount++]=0x202B; // WGL_TYPE_RGBA_ARB
    }
    
    // Select requested depth per color component 'bpc' for each channel:
    bpc = 8; // We default to 8 bpc == RGBA8
    if (windowRecord->depth == 30)  { bpc = 10; printf("PTB-INFO: Trying to enable at least 10 bpc fixed point framebuffer.\n"); }
    if (windowRecord->depth == 64)  { bpc = 16; printf("PTB-INFO: Trying to enable 16 bpc floating point framebuffer.\n"); }
    if (windowRecord->depth == 128) { bpc = 32; printf("PTB-INFO: Trying to enable 32 bpc floating point framebuffer.\n"); }
    
    // Set up color depth for each channel:
    attribs[attribcount++]=WGL_RED_BITS_ARB;
    attribs[attribcount++]=bpc;
    attribs[attribcount++]=WGL_GREEN_BITS_ARB;
    attribs[attribcount++]=bpc;
    attribs[attribcount++]=WGL_BLUE_BITS_ARB;
    attribs[attribcount++]=bpc;
    attribs[attribcount++]=WGL_ALPHA_BITS_ARB;
    // Alpha channel has only 2 bpc in the fixed point bpc=10 case, i.e. RGBA=8882.
    attribs[attribcount++]=(bpc == 10) ? 2 : bpc;
    
    
    // Stereo display support: If stereo display output is requested with OpenGL native stereo,
    // we request a stereo-enabled rendering context.
    if(stereomode==kPsychOpenGLStereo) {
      flags = flags | PFD_STEREO;
      attribs[attribcount++]=0x2012; // WGL_STEREO_ARB
      attribs[attribcount++]=GL_TRUE;
    }
    
    // Double buffering requested?
    if(numBuffers>=2) {
      // Enable double-buffering:
      flags = flags | PFD_DOUBLEBUFFER;
      attribs[attribcount++]=0x2011; // WGL_DOUBLE_BUFFER_ARB
      attribs[attribcount++]=GL_TRUE;
      
      // AUX buffers for Flip-Operations needed?
      if ((conserveVRAM & kPsychDisableAUXBuffers) == 0) {
	// Allocate one or two (mono vs. stereo) AUX buffers for new "don't clear" mode of Screen('Flip'):
	// Not clearing the framebuffer after "Flip" is implemented by storing a backup-copy of
	// the backbuffer to AUXs before flip and restoring the content from AUXs after flip.
	pfd.cAuxBuffers=(stereomode==kPsychOpenGLStereo || stereomode==kPsychCompressedTLBRStereo || stereomode==kPsychCompressedTRBLStereo) ? 2 : 1;
	attribs[attribcount++]=0x2024; // WGL_AUX_BUFFERS_ARB
	attribs[attribcount++]=pfd.cAuxBuffers;
      }
    }
    
    //if (PSYCH_DEBUG == PSYCH_ON) printf("Device context is %p\n", hDC);
    
    // Build pixelformat descriptor:
    pfd.nSize        = sizeof(pfd);
    pfd.nVersion     = 1;
    pfd.dwFlags      = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_SWAP_EXCHANGE |flags;  // Want OpenGL capable window with bufferswap via page-flipping...
    pfd.iPixelType   = PFD_TYPE_RGBA; // Want a RGBA pixel format.
    pfd.cColorBits   = 32;            // 32 bpp at least...
    pfd.cAlphaBits   = 8;             // Want a 8 bit alpha-buffer.
    
    // Support for OpenGL 3D rendering requested?
    if (PsychPrefStateGet_3DGfx()) {
      // Yes. Allocate and attach a 24bit depth buffer and 8 bit stencil buffer:
      pfd.cDepthBits = 24;
      pfd.cStencilBits = 8;
      attribs[attribcount++]=0x2022; // WGL_DEPTH_BITS_ARB
      attribs[attribcount++]=24;
      attribs[attribcount++]=0x2023; // WGL_STENCIL_BITS_ARB
      attribs[attribcount++]=8;
    }
    
    // Multisampled Anti-Aliasing requested?
    if (windowRecord->multiSample > 0) {
      // Request a multisample buffer:
      attribs[attribcount++]= 0x2041; // WGL_SAMPLE_BUFFERS_ARB
      attribs[attribcount++]= 1;
      // Request at least multiSample samples per pixel:
      attribs[attribcount++]= 0x2042; // WGL_SAMPLES_ARB
      attribs[attribcount++]= windowRecord->multiSample;
    }
    
    // Finalize attribs-array:
    attribs[attribcount++]= 0;
    
    //if (PSYCH_DEBUG == PSYCH_ON) printf("Choosing pixelformat\n");
    
    // Create pixelformat:
    // This is typical Microsoft brain-damage: We first need to create a window the
    // conventional old way just to be able to get a handle to the new wglChoosePixelFormat
    // method, which will us - after destroying and recreating the new window - allow to
    // select the pixelformat we actually want!
    
    // Step 1: Choose pixelformat old-style:
    pf = ChoosePixelFormat(hDC, &pfd);
    
    // Do we have a valid pixelformat?
    if (pf == 0) {
      // Nope. We give up!
      ReleaseDC(hDC, hWnd);
      DestroyWindow(hWnd);      
      printf("\nPTB-ERROR[ChoosePixelFormat() failed]: Unknown error, Win32 specific.\n\n");
      return(FALSE);
    }
    
    // Yes. Set it:
    if (SetPixelFormat(hDC, pf, &pfd) == FALSE) {
      ReleaseDC(hDC, hWnd);
      DestroyWindow(hWnd);      
      
      printf("\nPTB-ERROR[SetPixelFormat() failed]: Unknown error, Win32 specific.\n\n");
      return(FALSE);
    }
    
    // Ok, create and attach the rendering context.
    windowRecord->targetSpecific.contextObject = wglCreateContext(hDC);
    if (windowRecord->targetSpecific.contextObject == NULL) {
      ReleaseDC(hDC, hWnd);
      DestroyWindow(hWnd);
      
      printf("\nPTB-ERROR:[Context creation failed] Unknown, Win32 specific.\n\n");
      return(FALSE);
    }
    
    // Store the handles...
    windowRecord->targetSpecific.windowHandle = hWnd;
    windowRecord->targetSpecific.deviceContext = hDC;
    
    // Activate the rendering context:
    PsychOSSetGLContext(windowRecord);
    
    // Ok, the OpenGL rendering context is up and running. Auto-detect and bind all
    // available OpenGL extensions via GLEW:
    glerr = glewInit();
    if (GLEW_OK != glerr)
      {
	/* Problem: glewInit failed, something is seriously wrong. */
	printf("\nPTB-ERROR[GLEW init failed: %s]: Please report this to the forum. Will try to continue, but may crash soon!\n\n", glewGetErrorString(glerr));
	fflush(NULL);
      }
    else {
      if (PsychPrefStateGet_Verbosity()>4) printf("PTB-INFO: Using GLEW version %s for automatic detection of OpenGL extensions...\n", glewGetString(GLEW_VERSION));
    }
    
    DescribePixelFormat(hDC, pf, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
    
    if ((stereomode==kPsychOpenGLStereo) && ((pfd.dwFlags & PFD_STEREO)==0)) {
      // Ooops. Couldn't get the requested stereo-context from hardware :(
      ReleaseDC(hDC, hWnd);
      DestroyWindow(hWnd);
      
      printf("PTB-ERROR: OpenGL native stereo mode unavailable. Your hardware may not support it,\n"
	     "PTB-ERROR: or at least not on a flat-panel? Expect abortion of your script soon...");
      
      return(FALSE);
    }
    
	// Special debug override for faulty drivers with non-working extension:
	if (conserveVRAM & kPsychOverrideWglChoosePixelformat) wglChoosePixelFormatARB = NULL;

	// Step 2: Ok, we have an OpenGL rendering context with all known extensions bound:
	// Do we have (or want) support for wglChoosePixelFormatARB?
   // We skip use of it if we can do without it, i.e., when we don't need unusual framebuffer
   // configs (like non 8bpc fixed) and we don't need multisampling. This is a work-around
   // for hardware that has trouble (=driver bugs) with wglChoosePixelformat() in some modes, e.g., the NVidia
	// Quadro gfx card, which fails to enable quad-buffered stereo when using wglChoosePixelformat(),
	// but does so perfectly well when using the old-style ChoosePixelFormat(). 
	if ((wglChoosePixelFormatARB == NULL) || ((bpc==8) && (windowRecord->multiSample <= 0))) {
	  // Failed (==NULL) or disabled via override.
	  if ((wglChoosePixelFormatARB == NULL) && (PsychPrefStateGet_Verbosity() > 1)) printf("PTB-WARNING: Could not bind wglChoosePixelFormat - Extension. Some features will be unavailable, e.g., Anti-Aliasing and high precision framebuffers.\n");
	}
	else {
	  // Supported. We destroy the rendering context and window, then recreate it with
	  // the wglChoosePixelFormat - method...
	  wglMakeCurrent(NULL, NULL);

	  // Delete rendering context:
	  wglDeleteContext(windowRecord->targetSpecific.contextObject);
	  windowRecord->targetSpecific.contextObject=NULL;

      // Release device context:
      ReleaseDC(windowRecord->targetSpecific.deviceContext, windowRecord->targetSpecific.windowHandle);
      windowRecord->targetSpecific.deviceContext=NULL;

   	// Close & Destroy the window:
      DestroyWindow(windowRecord->targetSpecific.windowHandle);
      windowRecord->targetSpecific.windowHandle=NULL;

		// Ok, old window and stuff is dead. Create new window:
    	hWnd = CreateWindowEx(windowExtendedStyle, "PTB-OpenGL", "PTB Onscreen window", windowStyle,
			  						 x, y, width, height, NULL, NULL, hInstance, NULL);
    	if (hWnd == NULL) {
        printf("\nPTB-ERROR[CreateWindow() - II failed]: Unknown error, Win32 specific.\n\n");
        return(FALSE);
    	}

	   // Retrieve device context for the window:
    	hDC = GetDC(hWnd);

		pf = 0;
		nNumFormats=0;
		wglChoosePixelFormatARB(hDC, &attribs[0], NULL, 1, &pf, &nNumFormats);
      if (nNumFormats==0 && windowRecord->multiSample > 0) {
		 	// Failed. Probably due to too demanding multisample requirements: Lets lower them...
			for (i=0; i<attribcount && attribs[i]!=0x2042; i++);
			// Reduce requested number of samples/pixel and retry until we get one:
			while (nNumFormats==0 && windowRecord->multiSample > 0) {
				// printf("Failed for multisampling level %i nNum=%i\n", windowRecord->multiSample, nNumFormats);
				attribs[i+1]--;
	  			windowRecord->multiSample--;
				wglChoosePixelFormatARB(hDC, &attribs[0], NULL, 1, &pf, &nNumFormats);
			}
			// If we still do not get one with 0 samples per pixel, we can try to disable
			// multisampling completely:
			if (windowRecord->multiSample == 0 && nNumFormats==0) {
				// printf("Failed for multisampling level %i nNum=%i --> Disabling multisampling...\n", windowRecord->multiSample, nNumFormats);
				// We 0-Out all entries related to multi-sampling, including the
				// GL_SAMPLES_ARB and GL_SAMPLE_BUFFERS_ARB enums themselves:
				for (i=0; i<attribcount && attribs[i]!=0x2042; i++);
	  			attribs[i]=0;
	  			for (i=0; i<attribcount && attribs[i]!=0x2041; i++);
	  			attribs[i]=0;
	  			attribs[i+1]=0;
				wglChoosePixelFormatARB(hDC, &attribs[0], NULL, 1, &pf, &nNumFormats);
			}
      }

		if (nNumFormats==0 && numBuffers>=2) {
			// We still don't have a valid pixelformat, but double-buffering is enabled.
			// Let's try if we get one if we do not request any AUX-Buffers:
			for (i=0; i<attribcount && attribs[i]!=0x2024; i++);
			attribs[i+1] = 0; // Zero AUX-Buffers requested.
			wglChoosePixelFormatARB(hDC, &attribs[0], NULL, 1, &pf, &nNumFormats);
		}

		if (nNumFormats==0 && numBuffers>=2) {
			// We still don't have a valid pixelformat, but double-buffering is enabled.
			// Let's try if we get one if we do not request SWAP_EXCHANGED double buffering anymore:
			for (i=0; i<attribcount && attribs[i]!=0x2028; i++);
			attribs[i] = 0x202A; // WGL_SWAP_UNDEFINED_ARB
			wglChoosePixelFormatARB(hDC, &attribs[0], NULL, 1, &pf, &nNumFormats);
		}

		// Either we have a multisampled or non-multisampled format, or none. If we failed,
		// then we can not do anything anymore about it.

	   // Do we have a valid pixelformat?
      if (nNumFormats == 0) {
		   // Nope. We give up!
         ReleaseDC(hDC, hWnd);
         DestroyWindow(hWnd);      
         printf("\nPTB-ERROR[wglChoosePixelFormat() failed]: Unknown error, Win32 specific. Code: %i.\n\n", GetLastError());
         return(FALSE);
      }

      // Yes. Set it:
      if (SetPixelFormat(hDC, pf, &pfd) == FALSE) {
         ReleaseDC(hDC, hWnd);
         DestroyWindow(hWnd);      

         printf("\nPTB-ERROR[SetPixelFormat() - II failed]: Unknown error, Win32 specific.\n\n");
         return(FALSE);
      }

      // Ok, create and attach the rendering context.
      windowRecord->targetSpecific.contextObject = wglCreateContext(hDC);
      if (windowRecord->targetSpecific.contextObject == NULL) {
         ReleaseDC(hDC, hWnd);
         DestroyWindow(hWnd);

         printf("\nPTB-ERROR:[Context creation II failed] Unknown, Win32 specific.\n\n");
         return(FALSE);
      }
    
      // Store the handles...
      windowRecord->targetSpecific.windowHandle = hWnd;
      windowRecord->targetSpecific.deviceContext = hDC;

      // Activate the rendering context:
      PsychOSSetGLContext(windowRecord);

      DescribePixelFormat(hDC, pf, sizeof(PIXELFORMATDESCRIPTOR), &pfd);

      if ((stereomode==kPsychOpenGLStereo) && ((pfd.dwFlags & PFD_STEREO)==0)) {
         // Ooops. Couldn't get the requested stereo-context from hardware :(
         ReleaseDC(hDC, hWnd);
         DestroyWindow(hWnd);

         printf("PTB-ERROR: OpenGL native stereo mode unavailable. Your hardware may not support it,\n"
	             "PTB-ERROR: or at least not on a flat-panel? Expect abortion of your script soon...");

         return(FALSE);
      }		
		// Done with final window and OpenGL context setup. We've got our final context enabled.
	 }

	 // Enable multisampling if this was requested:
    if (windowRecord->multiSample > 0) glEnable(0x809D); // 0x809D == GL_MULTISAMPLE_ARB
	 // Throw away any error-state this could have created on old hardware...
	 glGetError();

    // External 3D graphics support enabled? Or OpenGL quad-buffered stereo enabled?
	 // For the former, we need this code for OpenGL state isolation. For the latter we
    // need this code as workaround for Windows brain-damage. For some reason it helps
    // to properly shutdown stereo contexts on Windows...
	 if (PsychPrefStateGet_3DGfx() || stereomode == kPsychOpenGLStereo) {
		// Yes. We need to create an extra OpenGL rendering context for the external
		// OpenGL code to provide optimal state-isolation. The context shares all
		// heavyweight ressources likes textures, FBOs, VBOs, PBOs, display lists and
		// starts off as an identical copy of PTB's context as of here.
      windowRecord->targetSpecific.glusercontextObject = wglCreateContext(hDC);
		if (windowRecord->targetSpecific.glusercontextObject == NULL) {
         ReleaseDC(hDC, hWnd);
         DestroyWindow(hWnd);
			printf("\nPTB-ERROR[UserContextCreation failed]: Creating a private OpenGL context for Matlab OpenGL failed for unknown reasons.\n\n");
			return(FALSE);
		}

		wglMakeCurrent(windowRecord->targetSpecific.deviceContext, windowRecord->targetSpecific.glusercontextObject);
		wglMakeCurrent(windowRecord->targetSpecific.deviceContext, windowRecord->targetSpecific.contextObject);

		// Copy full state from our main context:
		if(!wglCopyContext(windowRecord->targetSpecific.contextObject, windowRecord->targetSpecific.glusercontextObject, GL_ALL_ATTRIB_BITS)) {
			// This is ugly, but not fatal...
			if (PsychPrefStateGet_Verbosity()>1) {
				printf("\nPTB-WARNING[wglCopyContext for user context failed]: Copying state to private OpenGL context for Matlab OpenGL failed for unknown reasons.\n\n");
			}
		}

	   // Enable ressource sharing with master context for this window:
		if (!wglShareLists(windowRecord->targetSpecific.contextObject, windowRecord->targetSpecific.glusercontextObject)) {
			// This is ugly, but not fatal...
			if (PsychPrefStateGet_Verbosity()>1) {
				printf("\nPTB-WARNING[wglShareLists for user context failed]: Ressource sharing with private OpenGL context for Matlab OpenGL failed for unknown reasons.\n\n");
			}		
		}

	 }

    // Finally, show our new window:
    ShowWindow(hWnd, SW_SHOW);

    // Give it higher priority than other applications windows:
    // Disabled: Interferes with JAVA-GetChar: SetForegroundWindow(hWnd);

    // Set the focus on it:
    // Disabled: Interferes with JAVA-GetChar: SetFocus(hWnd);

    // Capture the window if it is a fullscreen one: This window will receive all
    // mouse move and mouse button press events. Important for GetMouse() to work
    // properly...
    if (fullscreen) SetCapture(hWnd);

    // Increase our own open window counter:
    win32_windowcount++;

    // Some info for the user regarding non-fullscreen and ATI hw:
    if (!fullscreen && (strstr(glGetString(GL_VENDOR), "ATI"))) {
      printf("PTB-INFO: Some ATI graphics cards may not support proper syncing to vertical retrace when\n");
      printf("PTB-INFO: running in windowed mode (non-fullscreen). If PTB aborts with 'Synchronization failure'\n");
      printf("PTB-INFO: you can disable the sync test via call to Screen('Preference', 'SkipSyncTests', 1); .\n");
      printf("PTB-INFO: You won't get proper stimulus onset timestamps though, so windowed mode may be of limited use.\n");
    }

    // Dynamically bind the VSYNC extension:
    //if (strstr(glGetString(GL_EXTENSIONS), "WGL_EXT_swap_control")) {
      // Bind it:
      // wglSwapIntervalEXT=(PFNWGLEXTSWAPCONTROLPROC) wglGetProcAddress("wglSwapIntervalEXT");
    //}
    //else {
	 if (wglSwapIntervalEXT == NULL) {
      wglSwapIntervalEXT = NULL;
      printf("PTB-WARNING: Your graphics driver doesn't allow me to control syncing wrt. vertical retrace!\n");
      printf("PTB-WARNING: Please update your display graphics driver as soon as possible to fix this.\n");
      printf("PTB-WARNING: Until then, you can manually enable syncing to VBL somewhere in the display settings\n");
      printf("PTB-WARNING: tab of your machine.\n");
    }

    // Ok, we should be ready for OS independent setup...

    //printf("\nPTB-INFO: Low-level (Windoze) setup of onscreen window finished!\n");
    //fflush(NULL);

    // Well Done!
    return(TRUE);
}
Exemplo n.º 17
0
// ------------------------------------------------------------------- main ---
int main( int argc, char **argv )
{
    GLFWwindow* window;
    char* screenshot_path = NULL;

    if (argc > 1)
    {
        if (argc == 3 && 0 == strcmp( "--screenshot", argv[1] ))
            screenshot_path = argv[2];
        else
        {
            fprintf( stderr, "Unknown or incomplete parameters given\n" );
            exit( EXIT_FAILURE );
        }
    }

    glfwSetErrorCallback( error_callback );

    if (!glfwInit( ))
    {
        exit( EXIT_FAILURE );
    }

    glfwWindowHint( GLFW_VISIBLE, GL_FALSE );
    glfwWindowHint( GLFW_RESIZABLE, GL_FALSE );

    window = glfwCreateWindow( 400, 400, argv[0], NULL, NULL );

    if (!window)
    {
        glfwTerminate( );
        exit( EXIT_FAILURE );
    }

    glfwMakeContextCurrent( window );
    glfwSwapInterval( 1 );

    glfwSetFramebufferSizeCallback( window, reshape );
    glfwSetWindowRefreshCallback( window, display );
    glfwSetKeyCallback( window, keyboard );

#ifndef __APPLE__
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf( stderr, "Error: %s\n", glewGetErrorString(err) );
        exit( EXIT_FAILURE );
    }
    fprintf( stderr, "Using GLEW %s\n", glewGetString(GLEW_VERSION) );
#endif

    init();

    glfwShowWindow( window );
    reshape( window, 400, 400 );

    glfwSetTime(1.0);

    while (!glfwWindowShouldClose( window ))
    {
        display( window );
        glfwPollEvents( );

        if (screenshot_path)
        {
            screenshot( window, screenshot_path );
            glfwSetWindowShouldClose( window, 1 );
        }
    }

    glfwDestroyWindow( window );
    glfwTerminate( );

    return EXIT_SUCCESS;
}
Exemplo n.º 18
0
int main(int argc, char** argv)
{

	if (!glfwInit())	// 初始化glfw库
	{
		std::cout << "Error::GLFW could not initialize GLFW!" << std::endl;
		return -1;
	}

	// 开启OpenGL 3.3 core profile
	std::cout << "Start OpenGL core profile version 3.3" << std::endl;
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

	// 创建窗口
	GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT,
		"Demo of PBO(unpack stream texture)", NULL, NULL);
	if (!window)
	{
		std::cout << "Error::GLFW could not create winddow!" << std::endl;
		glfwTerminate();
		return -1;
	}
	glfwSetWindowPos(window, 300, 100);
	// 创建的窗口的context指定为当前context
	glfwMakeContextCurrent(window);

	// 注册窗口键盘事件回调函数
	glfwSetKeyCallback(window, key_callback);
	// 注册鼠标事件回调函数
	glfwSetCursorPosCallback(window, mouse_move_callback);
	// 注册鼠标滚轮事件回调函数
	glfwSetScrollCallback(window, mouse_scroll_callback);
	// 鼠标捕获 停留在程序内
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

	// 初始化GLEW 获取OpenGL函数
	glewExperimental = GL_TRUE; // 让glew获取所有拓展函数
	GLenum status = glewInit();
	if (status != GLEW_OK)
	{
		std::cout << "Error::GLEW glew version:" << glewGetString(GLEW_VERSION)
			<< " error string:" << glewGetErrorString(status) << std::endl;
		glfwTerminate();
		return -1;
	}

	// 设置视口参数
	glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

	// Section1 准备顶点数据
	setupQuadVAO();
	preparePBO();
	initImageData();
	initTexture();

	// Section2 加载字体
	FontResourceManager::getInstance().loadFont("arial", "../../resources/fonts/arial.ttf");
	FontResourceManager::getInstance().loadASCIIChar("arial", 38, unicodeCharacters);
	// Section3 准备着色器程序
	Shader shader("scene.vertex", "scene.frag");
	Shader textShader("text.vertex", "text.frag");

	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	// 开始游戏主循环
	while (!glfwWindowShouldClose(window))
	{
		GLfloat currentFrame = (GLfloat)glfwGetTime();
		deltaTime = currentFrame - lastFrame;
		lastFrame = currentFrame;
		glfwPollEvents(); // 处理例如鼠标 键盘等事件
		do_movement(); // 根据用户操作情况 更新相机属性

		// 清除颜色缓冲区 重置为指定颜色
		glClearColor(0.18f, 0.04f, 0.14f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glm::mat4 projection;
		glm::mat4 view;
		glm::mat4 model;
		// 这里填写场景绘制代码
		// 先绘制纹理图片
		shader.use();
		glUniformMatrix4fv(glGetUniformLocation(shader.programId, "projection"),
			1, GL_FALSE, glm::value_ptr(projection));
		glUniformMatrix4fv(glGetUniformLocation(shader.programId, "view"),
			1, GL_FALSE, glm::value_ptr(view));
		model = glm::mat4();
		glUniformMatrix4fv(glGetUniformLocation(shader.programId, "model"),
			1, GL_FALSE, glm::value_ptr(model));
		renderScene(shader);
		// 在绘制信息文字
		
		textShader.use();
		projection = glm::ortho(0.0f, (GLfloat)(WINDOW_WIDTH),
		0.0f, (GLfloat)WINDOW_HEIGHT);
		view = glm::mat4();
		glUniformMatrix4fv(glGetUniformLocation(textShader.programId, "projection"),
			1, GL_FALSE, glm::value_ptr(projection));
		glUniformMatrix4fv(glGetUniformLocation(textShader.programId, "view"),
			1, GL_FALSE, glm::value_ptr(view));
		model = glm::mat4();
		glUniformMatrix4fv(glGetUniformLocation(textShader.programId, "model"),
			1, GL_FALSE, glm::value_ptr(model));
		renderInfo(textShader);

		printTransferRate();

		glBindVertexArray(0);
		glUseProgram(0);
		glfwSwapBuffers(window); // 交换缓存
	}
	// 释放资源
	glDeleteVertexArrays(1, &quadVAOId);
	glDeleteBuffers(1, &quadVBOId);
	glDeleteVertexArrays(1, &textVAOId);
	glDeleteBuffers(1, &textVBOId);
	glDeleteBuffers(2, PBOIds);  // 注意释放PBO
	releaseImageData();

	glfwTerminate();
	return 0;
}
Exemplo n.º 19
0
/*!
The C main procedure running the GLFW GUI application.
*/
int main(int argc, char *argv[])
{  
	// set command line arguments
	vector<string> cmdLineArgs;
	for(int i = 1; i < argc; i++)
		cmdLineArgs.push_back(argv[i]);

   if (!glfwInit())
   {  fprintf(stderr, "Failed to initialize GLFW\n");
      exit(EXIT_FAILURE);
   }

   glfwSetErrorCallback(onGLFWError);
   
   // Enable fullscreen anti aliasing with 4 samples
   glfwWindowHint(GLFW_SAMPLES, 4);
   //glfwWindowHint(GLFW_DECORATED, false); // start without any window frame

   scrWidth = 600;
   scrHeight = 480;

   window = glfwCreateWindow(scrWidth, scrHeight, "My Title", NULL, NULL);
   if (!window)
   {  glfwTerminate();
      exit(EXIT_FAILURE);
   }
   
   // Get the currenct GL context. After this you can call GL   
   glfwMakeContextCurrent(window);

   // On some systems screen & framebuffer size are different
   // All commands in GLFW are in screen coords but rendering in GL is
   // in framebuffer coords
   SLint fbWidth, fbHeight;
   glfwGetFramebufferSize(window, &fbWidth, &fbHeight);
   scr2fbX = (float)fbWidth / (float)scrWidth;
   scr2fbY = (float)fbHeight / (float)scrHeight;

   /* Include OpenGL via GLEW
   The goal of the OpenGL Extension Wrangler Library (GLEW) is to assist C/C++ 
   OpenGL developers with two tedious tasks: initializing and using extensions 
   and writing portable applications. GLEW provides an efficient run-time 
   mechanism to determine whether a certain extension is supported by the 
   driver or not. OpenGL core and extension functionality is exposed via a 
   single header file. Download GLEW at: http://glew.sourceforge.net/
   */
   GLenum err = glewInit();
   if (GLEW_OK != err)
   {  fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
      exit(EXIT_FAILURE);
   }

   glfwSetWindowTitle(window, "SLProject Test Application");
   glfwSetWindowPos(window, 10, 30);

   
   // Set number of monitor refreshes between 2 buffer swaps
   glfwSwapInterval(1);

   // Set your own physical screen dpi
   int dpi = (int)(142 * scr2fbX);
   cout << "GUI     : GLFW" << endl;
   cout << "DPI     : " << dpi << endl;
   
    slCreateScene("../_globals/oglsl/",
                  "../_data/models/",
                  "../_data/images/textures/");

    svIndex = slCreateSceneView((int)(scrWidth  * scr2fbX),
                                (int)(scrHeight * scr2fbY),
                                dpi, 
                                (SLCmd)SL_STARTSCENE,
                                cmdLineArgs,
                                (void*)&onPaint,
                                0,
                                createTestSceneView);
    // Set GLFW callback functions
    glfwSetKeyCallback(window, onKeyAction);
    glfwSetWindowSizeCallback(window, onResize);
    glfwSetMouseButtonCallback(window, onMouseButton);
    glfwSetCursorPosCallback(window, onMouseMove);
    glfwSetScrollCallback(window, onMouseWheel);
    glfwSetWindowCloseCallback(window, onClose);

    // Event loop
    // set max fps
    float fps = 60.0f;
    double deltaTime = 1.0f/fps;
    double time = glfwGetTime();
    while (!glfwWindowShouldClose(window))
    {
        if(time+deltaTime > glfwGetTime())
        {
            Sleep((time+deltaTime-glfwGetTime())*1000);
        }

        time = glfwGetTime();

        // if no updated occured wait for the next event (power saving)
        if (!onPaint()) 
            glfwWaitEvents();
        else glfwPollEvents();
    }
   
   glfwDestroyWindow(window);
   glfwTerminate();
   exit(0);
}
Exemplo n.º 20
0
void load() {
  GLenum err = glewInit();
  if (GLEW_OK != err) {
    /* Problem: glewInit failed, something is seriously wrong. */
    fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
  }
  fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));

  if (!use_framebuffer_object()) {
    error("Framebuffer objects are required but not supported by OpenGL implementation.\n");
    exit(1);
  }

  if (!use_shader_programs()) {
    error("Shader programs are required but not supported by OpenGL implementation.");
    exit(1);
  }

  if (!use_vertex_buffer_object()) {
    error("Vertex buffer objects are required but not supported by OpenGL implementation");
    exit(1);
  }
  /*
  SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
  SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  */
  scene = new Scene();

  texture = new GLuint[texture_count];
  glGenTextures(texture_count, texture);
  logGL();
  for (int i = 0 ; i < texture_count ; ++i) {
    glBindTexture(GL_TEXTURE_2D, texture[i]);
    glTexParameterf(GL_TEXTURE_2D,
		    GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D,
		    GL_TEXTURE_MIN_FILTER, GL_LINEAR/*_MIPMAP_LINEAR*/);
    glTexParameterf(GL_TEXTURE_2D,
		    GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameterf(GL_TEXTURE_2D,
		    GL_TEXTURE_WRAP_T, GL_CLAMP);
    //glTexParameteri(GL_TEXTURE_2D,
    //		    GL_GENERATE_MIPMAP, GL_TRUE); // automatic mipmap
    //glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, 512, 512, 0,
    //		 GL_RGBA, GL_UNSIGNED_BYTE, 0);
    //logGL();
    glTexImage2D(GL_TEXTURE_2D, 0, texture_format[i], 1280, 720, 0,
		 texture_format[i], GL_UNSIGNED_BYTE, 0);
    //logGL();
  }
  glBindTexture(GL_TEXTURE_2D, 0);

  glGenFramebuffers(1, &fbo);
  glBindFramebuffer(GL_FRAMEBUFFER, fbo);

  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
			 GL_TEXTURE_2D, texture[0], 0);
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
  			 GL_TEXTURE_2D, texture[1], 0);
  //logGL();

  GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  if(status != GL_FRAMEBUFFER_COMPLETE) {
    if (status == GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT)
      error("FRAMEBUFFER_INCOMPLETE_ATTACHMENT");
    else if (status == GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT)
      error("FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT");
    else if (status == GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER)
      error("FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER");
    else if (status == GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER)
      error("FRAMEBUFFER_INCOMPLETE_READ_BUFFER");
    else if (status == GL_FRAMEBUFFER_UNSUPPORTED)
      error("FRAMEBUFFER_UNSUPPORTED");
    else if (status == GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE)
      error("FRAMEBUFFER_INCOMPLETE_MULTISAMPLE");
    else if (status == GL_FRAMEBUFFER_UNDEFINED)
      error("FRAMEBUFFER_UNDEFINED");
    else
      error("Failed to initialize FBO for unknown reasons.");
  }

  glBindFramebuffer(GL_FRAMEBUFFER_EXT, 0);
  logGL();
}
Exemplo n.º 21
0
// Create window
// 
// Much of the Creation code was taken from the openGL wiki at:
// 
// http://www.opengl.org/wiki/Tutorial:_OpenGL_3.0_Context_Creation_(GLX) on 2/1/13
// 
//-----------------------------------------------------------------------------
CPUTResult CPUTWindowX::Create(CPUT* cput, const std::string WindowTitle, CPUTWindowCreationParams windowParams)
{
    CPUTResult result = CPUT_ERROR;
    
    pDisplay = XOpenDisplay(NULL);
    if (!pDisplay) {
        return result;
    }

    int glx_major, glx_minor;

    // FBConfigs were added in GLX version 1.3.
    if (!glXQueryVersion(pDisplay, &glx_major, &glx_minor)) {
        printf( "glXQueryVersion failed" );
        exit(1);
    }
    
    if (((glx_major == 1) && (glx_minor < 3)) || (glx_major < 1)) {
        printf( "Invalid GLX version" );
        exit(1);
    }
    printf( "GLX version: %d.%d\n", glx_major, glx_minor );

    // Get a matching FB config
    int visual_attribs[] =
    {
        GLX_X_RENDERABLE    , True,
        GLX_DRAWABLE_TYPE   , GLX_WINDOW_BIT,
        GLX_RENDER_TYPE     , GLX_RGBA_BIT,
        GLX_X_VISUAL_TYPE   , GLX_TRUE_COLOR,
        GLX_RED_SIZE        , 8,
        GLX_GREEN_SIZE      , 8,
        GLX_BLUE_SIZE       , 8,
        GLX_ALPHA_SIZE      , 8,
        GLX_DEPTH_SIZE      , 24,
        GLX_STENCIL_SIZE    , 8,
        GLX_DOUBLEBUFFER    , True,
        //GLX_SAMPLE_BUFFERS  , 1,
        //GLX_SAMPLES         , 4,
        None
    };
    int fbcount;
    GLXFBConfig *fbc = glXChooseFBConfig(pDisplay, DefaultScreen( pDisplay ), visual_attribs, &fbcount );
    if ( !fbc )
    {
        printf( "Failed to retrieve a framebuffer config\n" );
        exit(1);
    }

    // Pick the FB config/visual with the most samples per pixel
    printf( "Getting XVisualInfos\n" );
    int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999;
    
    for ( int i = 0; i < fbcount; i++ )
    {
        XVisualInfo *vi = glXGetVisualFromFBConfig( pDisplay, fbc[i] );
        if (vi)
        {
            int samp_buf, samples;
            glXGetFBConfigAttrib( pDisplay, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf );
            glXGetFBConfigAttrib( pDisplay, fbc[i], GLX_SAMPLES       , &samples  );
 
            printf( "  Matching fbconfig %d, visual ID 0lx%2lx: SAMPLE_BUFFERS = %d,"
                    " SAMPLES = %d\n", 
                    i, vi -> visualid, samp_buf, samples );
 
            if ( best_fbc < 0 || samp_buf && samples > best_num_samp ) {
                best_fbc = i, best_num_samp = samples;
            }
            if ( worst_fbc < 0 || !samp_buf || samples < worst_num_samp ) {
                worst_fbc = i, worst_num_samp = samples;
            }
        }
        XFree( vi );
    }
    
    GLXFBConfig bestFbc = fbc[ best_fbc ];

    // Be sure to free the FBConfig list allocated by glXChooseFBConfig()
    XFree( fbc );
    
    // Get a visual
    XVisualInfo *vi = glXGetVisualFromFBConfig( pDisplay, bestFbc );
    printf( "Chosen visual ID = 0x%lx\n", vi->visualid );
 
    printf( "Creating colormap\n" );
    XSetWindowAttributes swa;
    swa.colormap = XCreateColormap(pDisplay,
                                          RootWindow(pDisplay, vi->screen), 
                                          vi->visual, AllocNone );
    swa.background_pixmap = None ;
    swa.border_pixel      = 0;
    swa.event_mask        = ExposureMask | Button1MotionMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask | StructureNotifyMask;
    
    printf( "Creating window\n" );
    win = XCreateWindow( pDisplay, RootWindow(pDisplay, vi->screen ), 
                        0, 0, windowParams.windowWidth, windowParams.windowHeight, 0, vi->depth, InputOutput, 
                        vi->visual, 
                        CWBorderPixel | CWColormap | CWEventMask, &swa );
    if ( !win )
    {
        printf( "Failed to create window.\n" );
        exit(1);
    }

    // Done with the visual info data
    XFree( vi );
 
    // register interest in the delete window message
    wmDeleteMessage = XInternAtom(pDisplay, "WM_DELETE_WINDOW", False);
    XSetWMProtocols(pDisplay, win, &wmDeleteMessage, 1);
   
    XStoreName( pDisplay, win, WindowTitle.c_str() );
    
    printf( "Mapping window\n" );
    XMapWindow( pDisplay, win );
 
    // Get the default screen's GLX extension list
    const char *glxExts = glXQueryExtensionsString(pDisplay,
                                                   DefaultScreen( pDisplay ) );

    // NOTE: It is not necessary to create or make current to a context before
    // calling glXGetProcAddressARB
    glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;
    glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)
                                  glXGetProcAddressARB( (const GLubyte *) "glXCreateContextAttribsARB" );
 
    ctx = 0;
    
    // Install an X error handler so the application won't exit if GL 3.0
    // context allocation fails.
    //
    // Note this error handler is global.  All display connections in all threads
    // of a process use the same error handler, so be sure to guard against other
    // threads issuing X commands while this code is running.
    ctxErrorOccurred = false;
    int (*oldHandler)(Display*, XErrorEvent*) =
         XSetErrorHandler(&ctxErrorHandler);
 
    // Check for the GLX_ARB_create_context extension string and the function.
    // If either is not present, use GLX 1.3 context creation method.
    if (!isExtensionSupported( glxExts, "GLX_ARB_create_context" ) ||
        !glXCreateContextAttribsARB )
    {
        printf("glXCreateContextAttribsARB() not found"
               " ... using old-style GLX context\n" );
        ctx = glXCreateNewContext( pDisplay, bestFbc, GLX_RGBA_TYPE, 0, True );
    }
    else
    {
        int contextMajor = 3;
        int contextMinor = 3;
        printf( "Creating context %d.%d\n",  contextMajor, contextMinor);
        int context_attribs[] =
        {
            GLX_CONTEXT_MAJOR_VERSION_ARB, contextMajor,
            GLX_CONTEXT_MINOR_VERSION_ARB, contextMinor,
            GLX_CONTEXT_FLAGS_ARB        , GLX_CONTEXT_DEBUG_BIT_ARB,
            None
        };

        ctx = glXCreateContextAttribsARB(pDisplay, bestFbc, 0,
                                         True, context_attribs );

        // Sync to ensure any errors generated are processed.
        XSync( pDisplay, False );
        if ( !ctxErrorOccurred && ctx ) {
            printf( "Created GL 3.2 context\n" );
        } else {
            printf( "Failed to create requested context" );
        }
    }

    // Sync to ensure any errors generated are processed.
    XSync( pDisplay, False );
 
    // Restore the original error handler
    XSetErrorHandler( oldHandler );
    
    if ( ctxErrorOccurred || !ctx )
    {
        printf( "Failed to create an OpenGL context\n" );
        exit(1);
    }
 
    // Verifying that context is a direct context
    if ( ! glXIsDirect ( pDisplay, ctx ) )
    {
        printf( "Indirect GLX rendering context obtained\n" );
    }
    else
    {
        printf( "Direct GLX rendering context obtained\n" );
    }

    if (glXMakeCurrent( pDisplay, win, ctx ) == False) {
        printf( "glXMakeCurrent failed.");
    }

    glewExperimental=true;
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    }
    
    // glewInit can generate an error which is apparently innocuous. Clear it out here.
    // http://www.opengl.org/wiki/OpenGL_Loading_Library on 2/20/13
    glGetError();
    
    printf("Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
    printf("GL Version: %s\n", glGetString(GL_VERSION));


    return CPUT_SUCCESS;
}
Exemplo n.º 22
0
int GameEngineMain(int argc, _TCHAR* argv[])
// int _main (int argc, const char * const* argv)
#endif
{
	bool bStdModuleExist = EngineStdReference();
	klb_assert(bStdModuleExist, "The links of a system are insufficient.");

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH);
	glutCreateWindow("GLEW Test");

	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
	  /* Problem: glewInit failed, something is seriously wrong. */
	  fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
	}
	fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));

#define HEIGHT	(768)
#define WIDTH	(1024)
#define POS_X	(10)
#define POS_Y	(10)
//#define HEIGHT	(800)
//#define WIDTH	(400)
	int scrW	= WIDTH;
	int scrH	= HEIGHT;
	
	int fixedDelta = 0;

	*g_basePath = 0;
	*g_fileName = 0;
	g_pathExtern	= PATH_EXTERN;
	g_pathInstall	= PATH_INSTALL;

	g_fileName[0] = 0;

	bool hasDefaultFont = true;
	bool hasDefaultDB   = false;

	if (argc > 1) {
		int parse	= 1;
		int max		= argc;
		while (parse < max) {
			if(*argv[parse] == '-') {
				if (strcmp("-w",argv[parse]) == 0) {
					sscanf_s(argv[parse+1],"%i",&scrW);
				}

				if (strcmp("-h",argv[parse]) == 0) {
					sscanf_s(argv[parse+1],"%i",&scrH);
				}

				if (strcmp("-i",argv[parse]) == 0) {
					g_pathInstall = convertPath(argv[parse+1]);
				}

				if (strcmp("-e",argv[parse]) == 0) {
					g_pathExtern = convertPath(argv[parse+1]);
				}

				if (strcmp("-t",argv[parse]) == 0) {
					fixedDelta = atoi(argv[parse+1]);
				}

				if (strcmp("-enc", argv[parse]) == 0) {
					bool encrypt = false;
					if (stricmp(argv[parse+1],"true") == 0) {
						encrypt = true;
					}

					if (stricmp(argv[parse+1],"1") == 0) {
						encrypt = true;
					}

					CWin32Platform::setEncrypt(encrypt);
				}

				if (strcmp("-no", argv[parse]) == 0) {
					if (strcmp("defaultfont", argv[parse+1]) == 0) {
						hasDefaultFont = false;
					}
				}

				parse += 2;
			} else {
				// Specify the boot file
				const char* file = argv[parse];
				int lenf = strlen(file);
				
				memcpy(g_fileName, file, lenf);
				g_fileName[lenf] = 0;

				// ファイル名そのものは start.lua に相当する起動ファイルとする。
                // File name of the file used as a start.lua
				parse++;
			}
		}
	}

	CWin32PathConv& pathconv = CWin32PathConv::getInstance();
	pathconv.setPath(g_pathInstall, g_pathExtern);

	WNDCLASS wc;
	HWND hwnd;
	HDC hDC;
	HGLRC hRC;
	HINSTANCE hInstance = GetModuleHandle(NULL);

	// register window class
	wc.style = CS_OWNDC;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = hInstance;
	wc.hIcon = LoadIcon( NULL, IDI_APPLICATION );
	wc.hCursor = LoadCursor( NULL, IDC_ARROW );
	wc.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH );
	wc.lpszMenuName = NULL;
	wc.lpszClassName = "GameEngineGL";
	RegisterClass( &wc );
	
	// create main window
	hwnd = CreateWindow(
		"GameEngineGL", "Playground", 
		WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE,
		0, 0, 256, 256,
		NULL, NULL, hInstance, NULL );

/*		"EngineGL", NULL,
		WS_THICKFRAME|WS_DISABLED,
		CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
		NULL, NULL, 
		hInstance, 
		NULL
	);*/
	
	if (!hwnd)
		return -1;

	// enable OpenGL for the window
	EnableOpenGL( hwnd, &hDC, &hRC );

	// COM Initialization
	CoInitialize(NULL);

	EnableWindow(hwnd, TRUE);

	DragAcceptFiles(hwnd, true);

	RECT area;
	area.left = 0;
	area.top = 0;
#ifdef _WIN32_WCE
	area.right = GetSystemMetrics(SM_CXSCREEN);
	area.bottom = GetSystemMetrics(SM_CYSCREEN);

	SetWindowLong(hwnd, GWL_STYLE, WS_POPUP);

	SetWindowPos(hwnd, HWND_TOPMOST,
					area.left, area.top,
					area.right, area.bottom,
					SWP_FRAMECHANGED);
#else
	// Window border hard coded
	//area.right = scrW + 8;
	//area.bottom = scrH + 27;
	////area.right = GetSystemMetrics(SM_CXSCREEN);
	////area.bottom = GetSystemMetrics(SM_CYSCREEN);
	int addW = GetSystemMetrics(SM_CXSIZEFRAME) * 2;
	int addH = GetSystemMetrics(SM_CYSIZEFRAME) * 2 + GetSystemMetrics(SM_CYCAPTION);
	area.right = scrW + addW;
	area.bottom = scrH + addH;
	

	/*
	AdjustWindowRect(
		&area,
		WS_SYSMENU|WS_THICKFRAME|WS_DISABLED,
		false
	);*/

	SetWindowPos(hwnd, HWND_TOP,
					area.left, area.top,
					area.right, area.bottom,
					SWP_NOMOVE);
#endif

	/* set as foreground window to give this app focus in case it doesn't have it */
	SetForegroundWindow(hwnd);
	ShowWindow(hwnd, SW_SHOWNORMAL);

	glClearColor(1.0f, 0.7f, 0.2039f, 0.0f);
	glDisable( GL_CULL_FACE );

	//

	// testCodeInit();

	CPFInterface& pfif = CPFInterface::getInstance();
	CWin32Platform * pPlatform = new CWin32Platform(hwnd);

	if (!hasDefaultFont) {
		pPlatform->setNoDefaultFont();
	}

	pfif.setPlatformRequest(pPlatform);
	GameSetup();	// client side setup

	// Can only access client AFTER GameSetup.
	pfif.client().setInitParam((hasDefaultDB   ? IClientRequest::ENGINE_USE_DEFAULTDB   : 0)
							|  (hasDefaultFont ? IClientRequest::ENGINE_USE_DEFAULTFONT : 0), NULL); 

	// sound initialize
	SoundSystemInitFor_Win32();
	CWin32AudioMgr::getInstance().init(hwnd);

	// set screen size
	pfif.client().setScreenInfo(false, scrW, scrH);
	// boot path
	if (strlen(g_fileName)) {
		pfif.client().setFilePath(g_fileName);
	} else {
		pfif.client().setFilePath(NULL);
	}
	if (!pfif.client().initGame()) {
		klb_assertAlways("Could not initialize game, most likely memory error");
	} else {
		static DWORD lastTime = GetTickCount();

		// Main message loop:
		bool quit = false;
		s32 frameTime = pfif.client().getFrameTime();
		IClientRequest& pClient = pfif.client();

		while (!quit)
		{
			/* relay message queue messages to windowproc's */
			MSG msg;
			while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
			{
				TranslateMessage(&msg);

				if (msg.message == WM_QUIT)
				{
					quit = true;
					break;
				}

				DispatchMessage(&msg);
			}

			if (!quit) {
				// This is not the safest or best way to handle timing, but this code
				// is only added to make the triangle rotate at a basically constant
				// rate, independent of the target (Win32) platform
				DWORD newTime   = GetTickCount();
				DWORD delta     = newTime - lastTime;

				// Handle rollover
				if (newTime < lastTime) {
					delta = 0;
				} else {
					if (delta > (DWORD)frameTime) {
						sendEvents();

						lastTime = newTime;
						//dglClear(GL_COLOR_BUFFER_BIT);
	
						//
						// Rendering complete.
						//		
						//testCodeLoop(delta);
						pClient.frameFlip(fixedDelta ? fixedDelta : delta);

						// pfIF.platform().flipFrame();
						SwapBuffers( hDC );
					}
                    // コントロール(ex. TextBox)が作られている場合、その再描画を行う
					// If a Control (ex TextBox) is done, redraw them.
					CWin32Widget::ReDrawControls();
				}
			}
			Sleep(1);
		}
	}

	pfif.client().finishGame();

	SoundSystemExitFor_Win32();

	delete pPlatform;

	// shutdown OpenGL
	DisableOpenGL( hwnd, hDC, hRC );

	CWin32AudioMgr::getInstance().release();

	// End of COM
	CoUninitialize();

	if(DestroyWindow (hwnd)) {
		printf("DestroyWindow SUCCESS\n");
    }
	return 0;
}
Exemplo n.º 23
0
Arquivo: window.c Projeto: vrld/G4L
int l_window_new(lua_State* L)
{
	const char* name = luaL_checkstring(L, 1);
	int w = luaL_checkinteger(L, 2);
	int h = luaL_checkinteger(L, 3);

	int x = luaL_optinteger(L, 4, -1);
	int y = luaL_optinteger(L, 5, -1);

	Window* win = (Window*)lua_newuserdata(L, sizeof(Window));
	if (NULL == win)
		return luaL_error(L, "Cannot create window: Out of memory.");

	glutInitWindowSize(w,h);
	glutInitWindowPosition(x,y);
	win->id = glutCreateWindow(name);
	LUA = L;
	glutSetWindow(win->id);

	glutDisplayFunc(_draw);
	glutReshapeFunc(_reshape);
	glutIdleFunc(_update);
	glutVisibilityFunc(_visibility);
	glutKeyboardFunc(_keyboard);
	glutSpecialFunc(_special);
	glutMouseFunc(_mouse);
	glutMotionFunc(_motion);
	glutPassiveMotionFunc(_passiveMotion);
	glutEntryFunc(_entry);

	if (!context_available())
	{
		GLenum glew_status = glewInit();
		if (GLEW_OK != glew_status)
			return luaL_error(L, "Error initializing GLEW: %s",
			                  glewGetErrorString(glew_status));

		// check for opengl 3.3
		if (!GLEW_VERSION_3_3)
			return luaL_error(L, "OpenGL version too old");

		context_set_available();
	}

	if (luaL_newmetatable(L, INTERNAL_NAME))
	{
		lua_pushcfunction(L, l_window___index);
		lua_setfield(L, -2, "__index");

		lua_pushcfunction(L, l_window___newindex);
		lua_setfield(L, -2, "__newindex");

		luaL_Reg reg[] =
		{
			{"__gc",       l_window___gc},
			{"destroy",    l_window_destroy},
			{"redraw",     l_window_redraw},
			{"swap",       l_window_swap},
			{"position",   l_window_position},
			{"resize",     l_window_resize},
			{"fullscreen", l_window_fullscreen},
			{"show",       l_window_show},
			{"hide",       l_window_hide},
			{"iconify",    l_window_iconify},
			{"title",      l_window_title},
			{"cursor",     l_window_cursor},
			{NULL, NULL}
		};
		l_registerFunctions(L, -1, reg);
	}
	lua_setmetatable(L, -2);

	// create callback table
	luaL_newmetatable(L, CALLBACKS_NAME);
	lua_newtable(L);
	lua_rawseti(L, -2, win->id);
	lua_pop(L, 1);

	return 1;
}
Exemplo n.º 24
0
	//Initializes OpenGL functions, window size and calls openGL standard initialize functions and creates the main window
	OpenGL::OpenGL(int windowWidth,int windowHeight, int redbits, int greenbits, int bluebits, int alphabits, int depthbits, int stencilbits, bool windowresize, bool fullscreen)
	{
		this->currentViewportHeight = windowHeight;
		this->currentViewportWidth = windowWidth;
		this->width = windowWidth;
		this->height = windowHeight;
		if(glfwInit() != 1)
		{
			cgl::Error("Could not initialize GLFWINIT()");
		}
		if(windowresize == true)
		{
			glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, 1);
		}
		else
		{
			//Call GLFW callback function of resizing, built in function.
		}
		if(this->height == 0 && this->width == 0)
		{
			this->height = 600;
			this->width = 800;
			if(glfwOpenWindow(this->width, this->height, redbits, greenbits, bluebits, alphabits, depthbits, stencilbits, GLFW_FULLSCREEN) != 1)
			{
				cgl::Error("Could not open GLFW Window");
			}
		}
		else
		{
			if(fullscreen == true)
			{
				if(glfwOpenWindow(this->width, this->height, redbits, greenbits, bluebits, alphabits, depthbits, stencilbits, GLFW_FULLSCREEN) != 1)
				{
					cgl::Error("Could not open window");
				}
			}
			else
			{
				if(this->width < 1)
				{
					this->width = 800;
				}
				if(this->height < 1)
				{
					this->height = 600;
				}
				if(glfwOpenWindow(this->width, this->height, redbits, greenbits, bluebits, alphabits, depthbits, stencilbits, GLFW_WINDOW) != 1)
				{
					cgl::Error("Could not open GLFW Window");
				}
			}
		}
		//glfwEnable(GLFW_AUTO_POLL_EVENTS);
		GLenum initReturn;
		if((initReturn = glewInit()) != GLEW_OK)
		{
			std::cout << glewGetErrorString(initReturn);
			cgl::Error("Could not initialize glew");
		}
		glfwSetWindowPos(0,0);
		glfwSetWindowTitle("Custom Game Library");
		//Additional Init Settings
		//glViewport(0,0, this->width, this->height);
	}
Exemplo n.º 25
0
Graphics::PixelBuffer SurfaceSdlGraphicsManager::setupScreen(uint screenW, uint screenH, bool fullscreen, bool accel3d) {
	uint32 sdlflags;
	int bpp;

	closeOverlay();

#ifdef USE_OPENGL
	_opengl = accel3d;
	_antialiasing = 0;
#endif
	_fullscreen = fullscreen;

	ConfMan.registerDefault("fullscreen_res", "desktop");
	const Common::String &fsres = ConfMan.get("fullscreen_res");
	if (fsres != "desktop") {
		uint newW, newH;
		int converted = sscanf(fsres.c_str(), "%ux%u", &newW, &newH);
		if (converted == 2) {
			_desktopW = newW;
			_desktopH = newH;
		} else {
			warning("Could not parse 'fullscreen_res' option: expected WWWxHHH, got %s", fsres.c_str());
		}
	}

	ConfMan.registerDefault("aspect_ratio", true);
	_lockAspectRatio = ConfMan.getBool("aspect_ratio");
	uint fbW = screenW;
	uint fbH = screenH;
	_gameRect = Math::Rect2d(Math::Vector2d(0, 0), Math::Vector2d(1, 1));

#ifdef USE_OPENGL
	bool framebufferSupported = false;

	// Use the desktop resolution for fullscreen when possible
	if (_fullscreen) {
		if (g_engine->hasFeature(Engine::kSupportsArbitraryResolutions)) {
			// If the game supports arbitrary resolutions, use the desktop mode as the game mode
			screenW = _desktopW;
			screenH = _desktopH;
		} else if (_opengl) {
			// If available, draw to a framebuffer and scale it to the desktop resolution
#ifndef AMIGAOS
			// Spawn a 32x32 window off-screen
			SDL_putenv(const_cast<char *>("SDL_VIDEO_WINDOW_POS=9000,9000"));
			SDL_SetVideoMode(32, 32, 0, SDL_OPENGL);
			SDL_putenv(const_cast<char *>("SDL_VIDEO_WINDOW_POS=centered"));
			Graphics::initExtensions();
			framebufferSupported = Graphics::isExtensionSupported("GL_EXT_framebuffer_object");
			if (_fullscreen && framebufferSupported) {
				screenW = _desktopW;
				screenH = _desktopH;

				if (_lockAspectRatio) {
					float scale = MIN(_desktopH / float(fbH), _desktopW / float(fbW));
					float scaledW = scale * (fbW / float(_desktopW));
					float scaledH = scale * (fbH / float(_desktopH));
					_gameRect = Math::Rect2d(
						Math::Vector2d(0.5 - (0.5 * scaledW), 0.5 - (0.5 * scaledH)),
						Math::Vector2d(0.5 + (0.5 * scaledW), 0.5 + (0.5 * scaledH))
					);
				}
			}
#endif
		}
	}

	if (_opengl) {
		if (ConfMan.hasKey("antialiasing"))
			_antialiasing = ConfMan.getInt("antialiasing");

		SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
		SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
		SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
		SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
		SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
		SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
		SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
		setAntialiasing(true);

		sdlflags = SDL_OPENGL;
		bpp = 24;
	} else
#endif
	{
		bpp = 16;
		sdlflags = SDL_SWSURFACE;
	}

	if (_fullscreen && !accel3d && _lockAspectRatio) {
		screenW = _desktopW;
		screenH = _desktopH;
		_gameRect = Math::Rect2d(
			Math::Vector2d((_desktopW - fbW) / 2, (_desktopH - fbH) / 2),
			Math::Vector2d((_desktopW + fbW) / 2, (_desktopH + fbH) / 2)
		);
	}

	if (_fullscreen)
		sdlflags |= SDL_FULLSCREEN;

	_screen = SDL_SetVideoMode(screenW, screenH, bpp, sdlflags);
#ifdef USE_OPENGL
	// If 32-bit with antialiasing failed, try 32-bit without antialiasing
	if (!_screen && _opengl && _antialiasing) {
		warning("Couldn't create 32-bit visual with AA, trying 32-bit without AA");
		setAntialiasing(false);
		_screen = SDL_SetVideoMode(screenW, screenH, bpp, sdlflags);
	}

	// If 32-bit failed, try 16-bit
	if (!_screen && _opengl) {
		warning("Couldn't create 32-bit visual, trying 16-bit");
		SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
		SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
		SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
		SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 1);
		setAntialiasing(true);
		_screen = SDL_SetVideoMode(screenW, screenH, 0, sdlflags);
	}

	// If 16-bit with antialiasing failed, try 16-bit without antialiasing
	if (!_screen && _opengl && _antialiasing) {
		warning("Couldn't create 16-bit visual with AA, trying 16-bit without AA");
		setAntialiasing(false);
		_screen = SDL_SetVideoMode(screenW, screenH, 0, sdlflags);
	}

	// If 16-bit with alpha failed, try 16-bit without alpha
	if (!_screen && _opengl) {
		warning("Couldn't create 16-bit visual with alpha, trying without alpha");
		SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
		SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
		SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
		SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0);
		setAntialiasing(true);
		_screen = SDL_SetVideoMode(screenW, screenH, 0, sdlflags);
	}

	// If 16-bit without alpha and with antialiasing didn't work, try without antialiasing
	if (!_screen && _opengl && _antialiasing) {
		warning("Couldn't create 16-bit visual with AA, trying 16-bit without AA");
		setAntialiasing(false);
		_screen = SDL_SetVideoMode(screenW, screenH, 0, sdlflags);
	}
#endif

	if (!_screen) {
		warning("Error: %s", SDL_GetError());
		g_system->quit();
	}

#ifdef USE_OPENGL
	if (_opengl) {
		int glflag;
		const GLubyte *str;

		// apply atribute again for sure based on SDL docs
		SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);

		str = glGetString(GL_VENDOR);
		debug("INFO: OpenGL Vendor: %s", str);
		str = glGetString(GL_RENDERER);
		debug("INFO: OpenGL Renderer: %s", str);
		str = glGetString(GL_VERSION);
		debug("INFO: OpenGL Version: %s", str);
		SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &glflag);
		debug("INFO: OpenGL Red bits: %d", glflag);
		SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &glflag);
		debug("INFO: OpenGL Green bits: %d", glflag);
		SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &glflag);
		debug("INFO: OpenGL Blue bits: %d", glflag);
		SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &glflag);
		debug("INFO: OpenGL Alpha bits: %d", glflag);
		SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &glflag);
		debug("INFO: OpenGL Z buffer depth bits: %d", glflag);
		SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &glflag);
		debug("INFO: OpenGL Double Buffer: %d", glflag);
		SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &glflag);
		debug("INFO: OpenGL Stencil buffer bits: %d", glflag);

#ifdef USE_GLEW
		debug("INFO: GLEW Version: %s", glewGetString(GLEW_VERSION));
		GLenum err = glewInit();
		if (err != GLEW_OK) {
			warning("Error: %s", glewGetErrorString(err));
			g_system->quit();
		}
#endif

#ifdef USE_OPENGL_SHADERS
		debug("INFO: GLSL version: %s", glGetString(GL_SHADING_LANGUAGE_VERSION));

		const GLfloat vertices[] = {
			0.0, 0.0,
			1.0, 0.0,
			0.0, 1.0,
			1.0, 1.0,
		};

		// Setup the box shader used to render the overlay
		const char* attributes[] = { "position", "texcoord", NULL };
		_boxShader = Graphics::Shader::fromStrings("box", Graphics::BuiltinShaders::boxVertex, Graphics::BuiltinShaders::boxFragment, attributes);
		_boxVerticesVBO = Graphics::Shader::createBuffer(GL_ARRAY_BUFFER, sizeof(vertices), vertices);
		_boxShader->enableVertexAttribute("position", _boxVerticesVBO, 2, GL_FLOAT, GL_TRUE, 2 * sizeof(float), 0);
		_boxShader->enableVertexAttribute("texcoord", _boxVerticesVBO, 2, GL_FLOAT, GL_TRUE, 2 * sizeof(float), 0);
#endif

		Graphics::initExtensions();

	}
#endif

	_overlayWidth = screenW;
	_overlayHeight = screenH;

#ifdef USE_OPENGL
	if (_opengl) {
		uint32 rmask, gmask, bmask, amask;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
		rmask = 0x00001f00;
		gmask = 0x000007e0;
		bmask = 0x000000f8;
		amask = 0x00000000;
#else
		rmask = 0x0000f800;
		gmask = 0x000007e0;
		bmask = 0x0000001f;
		amask = 0x00000000;
#endif
		_overlayscreen = SDL_CreateRGBSurface(SDL_SWSURFACE, _overlayWidth, _overlayHeight, 16,
						rmask, gmask, bmask, amask);
		_overlayScreenGLFormat = GL_UNSIGNED_SHORT_5_6_5;
	} else
#endif
	{
		_overlayscreen = SDL_CreateRGBSurface(SDL_SWSURFACE, _overlayWidth, _overlayHeight, 16,
					_screen->format->Rmask, _screen->format->Gmask, _screen->format->Bmask, _screen->format->Amask);
	}

	if (!_overlayscreen) {
		warning("Error: %s", SDL_GetError());
		g_system->quit();
	}

	/*_overlayFormat.bytesPerPixel = _overlayscreen->format->BytesPerPixel;

// 	For some reason the values below aren't right, at least on my system
	_overlayFormat.rLoss = _overlayscreen->format->Rloss;
	_overlayFormat.gLoss = _overlayscreen->format->Gloss;
	_overlayFormat.bLoss = _overlayscreen->format->Bloss;
	_overlayFormat.aLoss = _overlayscreen->format->Aloss;

	_overlayFormat.rShift = _overlayscreen->format->Rshift;
	_overlayFormat.gShift = _overlayscreen->format->Gshift;
	_overlayFormat.bShift = _overlayscreen->format->Bshift;
	_overlayFormat.aShift = _overlayscreen->format->Ashift;*/

	_overlayFormat = Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0);

	_screenChangeCount++;

	SDL_PixelFormat *f = _screen->format;
	_screenFormat = Graphics::PixelFormat(f->BytesPerPixel, 8 - f->Rloss, 8 - f->Gloss, 8 - f->Bloss, 0,
										f->Rshift, f->Gshift, f->Bshift, f->Ashift);

#if defined(USE_OPENGL) && !defined(AMIGAOS)
	if (_opengl && _fullscreen
			&& !g_engine->hasFeature(Engine::kSupportsArbitraryResolutions)
			&& framebufferSupported) {
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
		_frameBuffer = new Graphics::FrameBuffer(fbW, fbH);
		_frameBuffer->attach();
	}
#endif
	if (_fullscreen && !accel3d) {
		_subScreen = SDL_CreateRGBSurface(SDL_SWSURFACE, fbW, fbH, bpp, _screen->format->Rmask, _screen->format->Gmask, _screen->format->Bmask, _screen->format->Amask);
		return Graphics::PixelBuffer(_screenFormat, (byte *)_subScreen->pixels);
	}
	return Graphics::PixelBuffer(_screenFormat, (byte *)_screen->pixels);
}
Exemplo n.º 26
0
	//************FUNCTIONS************
	//Initializes a few settings like title, lighting, etc... all in one line
	void OpenGL::Initialize(std::string windowTitle, bool enableLighting, bool enableCullFace, bool enableDepthTest, bool enable2D, bool enableLineSmoothing)
	{
		glfwSetWindowTitle(windowTitle.c_str());
		GLenum initReturn;
		if((initReturn = glewInit()) != GLEW_OK)
		{
			std::cout << glewGetErrorString(initReturn) <<  std::endl << "Could not initialize glew" << std::endl;
			exit(1);
		}
	/*	glMatrixMode(GL_PROJECTION);
		glLoadIdentity();

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();*/

		if(enableDepthTest == true)
		{
			glEnable(GL_DEPTH_TEST);	// Gives depth testing
		}
		if(enableCullFace == true)
		{
			glEnable(GL_CULL_FACE);		// Don't draw the backside
		}
		if(enableLighting == true)
		{
			glEnable(GL_LIGHTING);		// Enables fixed pipeline lighting
		}
		glEnable(GL_LIGHT0);			// Enables light0
		if(enable2D == true)
		{
			glEnable(GL_TEXTURE_2D);	// Enables use of 2D textures
		}
		glEnable(GL_NORMALIZE);			// Normals automaticially normalized
		if(enableLineSmoothing == true)
		{
			glEnable(GL_LINE_SMOOTH);
		}

	/*	GLfloat mat_specular[] = { .5, 0.5, 0.5, 1.0 };
		GLfloat mat_shininess[] = { 25.0 };
		glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
		glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
		glColorMaterial ( GL_FRONT_AND_BACK, GL_EMISSION ) ;
		glEnable ( GL_COLOR_MATERIAL ) ;
		glFrontFace(GL_CW);				// Winding of elements*/

		/*GLenum initReturn;
		if((initReturn = glewInit()) != GLEW_OK)
		{
			std::cout << glewGetErrorString(initReturn)<< std::endl;
			exit(1);
		}*/
		//glfwSetWindowTitle(windowTitle.c_str());

		//glEnable(GL_TEXTURE_2D);									// Enable Texture Mapping ( NEW )
		//glShadeModel(GL_SMOOTH);									// Enable Smooth Shading
		glClearColor(1.0f, 1.0f, 1.0f, 0.5f);						// White Background
		glClearDepth(1.0f);											// Depth Buffer Setup
		glEnable(GL_DEPTH_TEST);									// Enables Depth Testing
		glDepthFunc(GL_LEQUAL);										// The Type Of Depth Testing To Do
		glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);			// Really Nice Perspective Calculations
	}
Exemplo n.º 27
0
// -----------------------------------------------------------------------------
WindowGLFW::WindowGLFW(int width, int height, bool invisible)
    : WindowBase(width, height)
{
    if (glfwInit() == 0) {
        std::cout << "WindowGLFW: Failed initialize GLFW " << std::endl;
        throw std::exception();
    }

    // Create a windowed mode window and its OpenGL context
    glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
    glfwWindowHint(GLFW_SAMPLES, 0);     // Disable MSAA
    glfwWindowHint(GLFW_DEPTH_BITS, 24); // Enable

    if (invisible) {
         glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
    }

#ifdef _GLESMODE
    glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
#else
    glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
#endif

    m_hWindow = glfwCreateWindow(width, height, "GLFW", NULL, NULL);

    if (!m_hWindow) {
        glfwTerminate();
        std::cout << "WindowGLFW: Failed create window" << std::endl;
        throw std::exception();
    }

    glfwMakeContextCurrent(m_hWindow);

#ifdef USE_GLEW
    // dwRenderer requires glewExperimental
    // because it calls glGenVertexArrays()
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    if (err != GLEW_OK) {
        glfwDestroyWindow(m_hWindow);
        glfwTerminate();
        std::cout << "WindowGLFW: Failed to init GLEW: " << glewGetErrorString(err) << std::endl;
        throw std::exception();
    }
    glGetError(); // clears error on init
#endif

    // No vsync
    glfwSwapInterval(0);

    glfwSetInputMode(m_hWindow, GLFW_STICKY_KEYS, GL_FALSE);

    //Callbacks
    glfwSetWindowUserPointer(m_hWindow, this);
    glfwSetKeyCallback(m_hWindow, [](GLFWwindow *win, int key, int scancode, int action, int mods) {
        WindowGLFW *window = reinterpret_cast<WindowGLFW *>(glfwGetWindowUserPointer(win));
        window->onKeyCallback(key, scancode, action, mods);
    });
    glfwSetMouseButtonCallback(m_hWindow, [](GLFWwindow *win, int button, int action, int mods) {
        WindowGLFW *window = reinterpret_cast<WindowGLFW *>(glfwGetWindowUserPointer(win));
        window->onMouseButtonCallback(button, action, mods);
    });
    glfwSetCursorPosCallback(m_hWindow, [](GLFWwindow *win, double x, double y) {
        WindowGLFW *window = reinterpret_cast<WindowGLFW *>(glfwGetWindowUserPointer(win));
        window->onMouseMoveCallback(x, y);
    });
    glfwSetScrollCallback(m_hWindow, [](GLFWwindow *win, double dx, double dy) {
        WindowGLFW *window = reinterpret_cast<WindowGLFW *>(glfwGetWindowUserPointer(win));
        window->onMouseWheelCallback(dx, dy);
    });
    glfwSetFramebufferSizeCallback(m_hWindow, [](GLFWwindow *win, int width, int height) {
        WindowGLFW *window = reinterpret_cast<WindowGLFW *>(glfwGetWindowUserPointer(win));
        window->onResizeWindowCallback(width, height);
    });
}
Exemplo n.º 28
0
void Rekd2D::Core::Game::Run(char* title, unsigned int width, unsigned int height, unsigned int windowWidth, unsigned int windowHeight)
{
	SDL_Init(SDL_INIT_EVERYTHING);
	InitGL(2, 1);
	m_Window = new Window(title, width, height, windowWidth, windowHeight);
	int err = glewInit();
	if (err != 0) std::cout << "GLEW ERROR " << err << ": " << glewGetErrorString(err) << std::endl;
	Init();
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	err = SDLNet_Init();
	if (err != 0) std::cout << "SDLNet ERROR " << err << ": " << SDLNet_GetError() << std::endl;
	err = IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF);
	if (!err) std::cout << "IMG ERROR " << err << ": " << IMG_GetError() << std::endl;
	m_Renderer = new Renderer(m_Window);
	m_Window->GenerateFramebuffer();
	m_PostProcess = new PredefinedShader(
		"void main() { gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; gl_TexCoord[0] = gl_MultiTexCoord0; }",
		"uniform sampler2D sampler; void main() { gl_FragColor = texture2D(sampler, gl_TexCoord[0].st); }"
		);
	SDL_StartTextInput();
	Load();
	Event e;
	m_Window->Show();
	unsigned int last = 0, delta = 0;
	unsigned int now;
	MouseState s;
	KeyboardState ks;
	while (m_Window->Update())
	{
		m_Window->BindFramebuffer();
		now = SDL_GetTicks();
		if (now > last)
		{
			delta = now - last;
			last = now;
		}
		while (m_Window->PollEvent(&e))
		{
			s = Mouse::GetState();
			ks = Keyboard::GetState();
			if (e.Type == Enum::EventType::MouseMove)
			{
				s.X = (int)((e.MouseMove.DestinationX + e.MouseMove.RelativeX) / (float)m_Window->GetWidth() * width);
				s.Y = (int)((e.MouseMove.DestinationY + e.MouseMove.RelativeY) / (float)m_Window->GetHeight() * height);
				s.RelX = e.MouseMove.RelativeX;
				s.RelY = e.MouseMove.RelativeY;

				Mouse::SetState(s);
			}
			else if (e.Type == Enum::EventType::MouseClick)
			{
				s.X = (int)(e.MouseButton.X / (float)m_Window->GetWidth() * width);
				s.Y = (int)(e.MouseButton.Y / (float)m_Window->GetHeight() * height);
				if (e.MouseButton.Button < 4)
					s.MouseButtons[e.MouseButton.Button] = true;
				Mouse::SetState(s);
			}
			else if (e.Type == Enum::EventType::MouseRelease)
			{
				s.X = (int)(e.MouseButton.X / (float)m_Window->GetWidth() * width);
				s.Y = (int)(e.MouseButton.Y / (float)m_Window->GetHeight() * height);
				if (e.MouseButton.Button < 4)
					s.MouseButtons[e.MouseButton.Button] = false;
				Mouse::SetState(s);
			}
			else if (e.Type == Enum::EventType::KeyDown)
			{
				ks.Keys[e.Keyboard.KeyCode] = true;
				ks.Mods[e.Keyboard.KeyCode] = e.Keyboard.Modifiers;
				Keyboard::SetState(ks);
			}
			else if (e.Type == Enum::EventType::KeyUp)
			{
				ks.Keys[e.Keyboard.KeyCode] = false;
				ks.Mods[e.Keyboard.KeyCode] = 0;
				Keyboard::SetState(ks);
			}
			else if (e.Type == Enum::EventType::Text)
			{
				KeyDown(e.Text.Append, e.Text.Text, e.Text.Cursor, e.Text.SelectionLength);
			}
		}
		m_Renderer->Clear(Color(43, 78, 124));
		Update(delta);
		Render(delta);

		m_Window->UnbindFramebuffer();
		m_Renderer->Clear(Color(43, 78, 124));
		glLoadIdentity();
		m_PostProcess->Bind();
		m_Window->BindScreentex();
		glBegin(GL_QUADS);
		glTexCoord2f(0, 1);
		glVertex2f(0, 0);
		glTexCoord2f(1, 1);
		glVertex2f(width, 0);
		glTexCoord2f(1, 0);
		glVertex2f(width, height);
		glTexCoord2f(0, 0);
		glVertex2f(0, height);
		glEnd();
	}
	Unload();
	IMG_Quit();
	SDLNet_Quit();
	m_Renderer->Dispose();
	m_Window->Dispose();
	delete m_Window;
	delete m_Renderer;
	SDL_Quit();
}
Exemplo n.º 29
0
void MainApp::initializeGL()
{
    // initialize glew
    GLenum err = glewInit();
    if ( err != GLEW_OK )
        return reportError(QString::fromUtf8(reinterpret_cast<const char*>(glewGetErrorString(err))));
 
    // set some basic opengl flags
    glEnable(GL_DEPTH_TEST);  // Enables Depth Testing
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDepthFunc(GL_LESS);     // The Type Of Depth Test To Do
    glShadeModel(GL_SMOOTH);  // Enables Smooth Color Shading
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

    // load shader programs
    if ( !m_glProgramMaterial.loadAndLink("shaders/vshader.glsl", "shaders/fshader.glsl") )
        return reportError(QString::fromUtf8(m_glProgramMaterial.getLastError().c_str()));
    if ( !m_glProgramTexD.loadAndLink("shaders/vshaderTexD.glsl", "shaders/fshaderTexD.glsl") )
        return reportError(QString::fromUtf8(m_glProgramTexD.getLastError().c_str()));

    // set texture to sample from GL_TEXTURE0
    GLUniform::setUniform(m_glProgramTexD, "u_diffuseMap", INT, 0);

    // get the uniform locations TODO make this in a class
    GLuint uMatrices = glGetUniformBlockIndex(m_glProgramMaterial.getProgramIdx(), "Matrices");
    if ( uMatrices == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Matrices" << std::endl;

    GLuint uLights = glGetUniformBlockIndex(m_glProgramMaterial.getProgramIdx(), "Lights");
    if ( uLights == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Lights" << std::endl;

    GLuint uMaterial = glGetUniformBlockIndex(m_glProgramMaterial.getProgramIdx(), "Material");
    if ( uMaterial == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Material" << std::endl;

    // bind uniform blocks to indices TODO make this in a class
    glUniformBlockBinding(m_glProgramMaterial.getProgramIdx(), uMatrices, UB_MATRICES);
    glUniformBlockBinding(m_glProgramMaterial.getProgramIdx(), uLights, UB_LIGHT);
    glUniformBlockBinding(m_glProgramMaterial.getProgramIdx(), uMaterial, UB_MATERIAL);
    
    // same for other program
    uMatrices = glGetUniformBlockIndex(m_glProgramTexD.getProgramIdx(), "Matrices");
    if ( uMatrices == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Matrices" << std::endl;
    uLights = glGetUniformBlockIndex(m_glProgramTexD.getProgramIdx(), "Lights");
    if ( uLights == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Lights" << std::endl;
    uMaterial = glGetUniformBlockIndex(m_glProgramTexD.getProgramIdx(), "Material");
    if ( uMaterial == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Material" << std::endl;
 
    glUniformBlockBinding(m_glProgramTexD.getProgramIdx(), uMatrices, UB_MATRICES);
    glUniformBlockBinding(m_glProgramTexD.getProgramIdx(), uLights, UB_LIGHT);
    glUniformBlockBinding(m_glProgramTexD.getProgramIdx(), uMaterial, UB_MATERIAL);

    m_glUniformMatrixBuffer.generate(1);
    m_glUniformLightsBuffer.generate(1);
    m_glUniformMaterialBuffer.generate(1);

    m_glUniformMatrixBuffer.bind(GL_UNIFORM_BUFFER);
    m_glUniformMatrixBuffer.setEmpty(MAT_BUFFER_SIZE, GL_DYNAMIC_DRAW);
    m_glUniformLightsBuffer.bind(GL_UNIFORM_BUFFER);
    m_glUniformLightsBuffer.setEmpty(LIGHT_BUFFER_SIZE, GL_DYNAMIC_DRAW);
    m_glUniformMaterialBuffer.bind(GL_UNIFORM_BUFFER);
    m_glUniformMaterialBuffer.setEmpty(MATERIAL_BUFFER_SIZE, GL_DYNAMIC_DRAW);

    m_glUniformMatrixBuffer.bindBase(UB_MATRICES);
    m_glUniformLightsBuffer.bindBase(UB_LIGHT);
    m_glUniformMaterialBuffer.bindBase(UB_MATERIAL);
   
    GLBuffer::unbindBuffers(GL_UNIFORM_BUFFER);

    // initialize physics
    m_physics.init();

    // initialize table
    std::shared_ptr<Table> table = std::shared_ptr<Table>(new Table);
    if ( !table->init(m_physics, glm::vec3(0.0f, 0.0f, 0.0f)) )
        return reportError("Unable to load table");
    table->setUniforms(m_glUniformMaterialBuffer, MATERIALS);
    m_renderTargets.push_back(std::shared_ptr<iGLRenderable>(table));
    m_physicsTargets.push_back(std::shared_ptr<iPhysicsObject>(table));

    // initialize puck
    std::shared_ptr<Puck> puck = std::shared_ptr<Puck>(new Puck);
    if ( !puck->init(m_physics, glm::vec3(0.0f, 0.0f, 0.0f), 0.1f) )
        return reportError("Unable to load puck");
    puck->setUniforms(m_glUniformMaterialBuffer, MATERIALS);
    m_renderTargets.push_back(std::shared_ptr<iGLRenderable>(puck));
    m_physicsTargets.push_back(std::shared_ptr<iPhysicsObject>(puck));

    // TODO temporary just to show physics works
    //puck->setVelocity(glm::vec3(1.2f,0.0f,2.0f));

    // move the camera back and up
    m_camera[0].moveStraight(-3.0f);
    m_camera[0].moveHoriz(5.0f);
    m_camera[0].moveVert(2.0f);
    m_camera[0].rotateVert(-25.0f);
    m_camera[0].rotateHoriz(57.0f);
   
    m_camera[1].rotateHoriz(180.0);
    m_camera[1].moveStraight(-3.0f);
    m_camera[1].moveHoriz(5.0f);
    m_camera[1].moveVert(2.0f);
    m_camera[1].rotateVert(-25.0f);
    m_camera[1].rotateHoriz(57.0f);

    for ( int i = 0; i < LIGHT_ARRAY_SIZE; ++i )
        m_lights.addLight(LIGHT_DARK);
   
    // turn light #0 on player 1s position
    const glm::vec3 position0 = m_camera[0].getTranslation()[3].xyz();
    const LightInfo lightInfo0({
        position0 * -1.0f,
        glm::vec3(1.0f,1.0f,1.0f),
        glm::vec3(0.4f, 0.4f, 0.4f),
        glm::vec3(0.0f, 0.0f, 0.0f)});
    m_lights.setLightInfo(lightInfo0, 0);
    
    // turn light #1 on player 1s position
    const glm::vec3 position1 = m_camera[1].getTranslation()[3].xyz();
    const LightInfo lightInfo1({
        position1 * -1.0f,
        glm::vec3(1.0f,1.0f,1.0f),
        glm::vec3(0.4f, 0.4f, 0.4f),
        glm::vec3(0.0f, 0.0f, 0.0f)});
    m_lights.setLightInfo(lightInfo1, 1);

#ifdef GRAPHICS_DEBUG
    std::cout << "Loading Wireframe Debug Program" << std::endl;

    // load programs
    if ( !m_glProgramWireframe.loadAndLink("./shaders/debug/vshaderWireframe.glsl", "./shaders/debug/fshaderWireframe.glsl", "./shaders/debug/gshaderWireframe.glsl") )
        return reportError(QString::fromUtf8(m_glProgramWireframe.getLastError().c_str()));
    if ( !m_glProgramTexDWireframe.loadAndLink("./shaders/debug/vshaderTexDWireframe.glsl", "./shaders/debug/fshaderTexDWireframe.glsl", "./shaders/debug/gshaderTexDWireframe.glsl") )
        return reportError(QString::fromUtf8(m_glProgramTexDWireframe.getLastError().c_str()));

    // get and bind uniform block locations
    uMatrices = glGetUniformBlockIndex(m_glProgramWireframe.getProgramIdx(), "Matrices");
    if ( uMatrices == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Matrices" << std::endl;
    uLights = glGetUniformBlockIndex(m_glProgramWireframe.getProgramIdx(), "Lights");
    if ( uLights == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Lights" << std::endl;
    uMaterial = glGetUniformBlockIndex(m_glProgramWireframe.getProgramIdx(), "Material");
    if ( uMaterial == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Material" << std::endl;
    
    glUniformBlockBinding(m_glProgramWireframe.getProgramIdx(), uMatrices, UB_MATRICES);
    glUniformBlockBinding(m_glProgramWireframe.getProgramIdx(), uLights, UB_LIGHT);
    glUniformBlockBinding(m_glProgramWireframe.getProgramIdx(), uMaterial, UB_MATERIAL);

    uMatrices = glGetUniformBlockIndex(m_glProgramTexDWireframe.getProgramIdx(), "Matrices");
    if ( uMatrices == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Matrices" << std::endl;
    uLights = glGetUniformBlockIndex(m_glProgramTexDWireframe.getProgramIdx(), "Lights");
    if ( uLights == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Lights" << std::endl;
    uMaterial = glGetUniformBlockIndex(m_glProgramTexDWireframe.getProgramIdx(), "Material");
    if ( uMaterial == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Material" << std::endl;
    
    glUniformBlockBinding(m_glProgramTexDWireframe.getProgramIdx(), uMatrices, UB_MATRICES);
    glUniformBlockBinding(m_glProgramTexDWireframe.getProgramIdx(), uLights, UB_LIGHT);
    glUniformBlockBinding(m_glProgramTexDWireframe.getProgramIdx(), uMaterial, UB_MATERIAL);

    // find window size uniform for the wireframe 
    m_winSizeWireframe.init(m_glProgramWireframe, "u_windowSize", VEC2F);
    m_winSizeWireframe.loadData(glm::vec2(this->width()/4.0f, this->height()/2.0f));
    m_winSizeWireframe.set();
    m_winSizeTexDWireframe.init(m_glProgramTexDWireframe, "u_windowSize", VEC2F);
    m_winSizeTexDWireframe.loadData(glm::vec2(this->width()/4.0f, this->height()/2.0f));
    m_winSizeTexDWireframe.set();

    // set texture to sample from GL_TEXTURE0
    GLUniform diffuseMapWireframe;
    diffuseMapWireframe.init(m_glProgramTexDWireframe, "u_diffuseMap", INT);
    diffuseMapWireframe.loadData(0);
    diffuseMapWireframe.set();
#endif

#ifdef NORMALS_DEBUG
    std::cout << "Loading Normals Debug OpenGL Program" << std::endl;

    if ( !m_glProgramNormals.loadAndLink("./shaders/debug/vshaderNormals.glsl", "./shaders/debug/fshaderNormals.glsl", "./shaders/debug/gshaderNormals.glsl") )
        return reportError(QString::fromUtf8(m_glProgramNormals.getLastError().c_str()));

    // get and bind uniform block locations
    uMatrices = glGetUniformBlockIndex(m_glProgramNormals.getProgramIdx(), "Matrices");
    if ( uMatrices == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Matrices" << std::endl;
    glUniformBlockBinding(m_glProgramNormals.getProgramIdx(), uMatrices, UB_MATRICES);

    // get the location projection matrix uniform
    m_uniformProjection.init(m_glProgramNormals, "u_projectionMatrix", MAT4F);
#endif
    
#ifdef PHYSICS_DEBUG
    std::cout << "Loading Physics Debug OpenGL Program" << std::endl;

    if ( !m_glProgramDebug.loadAndLink("./shaders/debug/vshaderPassthrough.glsl", "./shaders/debug/fshaderPassthrough.glsl") )
        return reportError(QString::fromUtf8(m_glProgramDebug.getLastError().c_str()));

    // get and bind uniform block locations
    uMatrices = glGetUniformBlockIndex(m_glProgramDebug.getProgramIdx(), "Matrices");
    if ( uMatrices == GL_INVALID_INDEX )
        std::cout << "Warning: Unable to find uniform block Matrices" << std::endl;
    glUniformBlockBinding(m_glProgramDebug.getProgramIdx(), uMatrices, UB_MATRICES);
  
    // tell physics world to use debug drawer
    m_physicsDebug = std::shared_ptr<PhysicsDebug>(new PhysicsDebug);
    m_physics.get()->setDebugDrawer(m_physicsDebug.get());
#endif
}
Exemplo n.º 30
0
int main( int argc, char* argv[] )
{
       
    
    //get_settings read_settings; //create a settings reading object.    
    int screenDataW = 1920; //put screen data into a temp var
    int screenDataH = 1080;
    

    
    if (SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
    {
        std::cout << "SDL init error: " << SDL_GetError();
     return 0;
    } //start SDL

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); //set GL version of the window
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);    
    SDL_Window* window = SDL_CreateWindow( "RainbowRPG - SDL2.0 - OpenGL2.1", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screenDataW, screenDataH, SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_OPENGL); //create OpenGL window

    SDL_GLContext glcontext = SDL_GL_CreateContext(window); //set context as OpenGL
        initGL(screenDataW, screenDataH); //init GL.
    
    GLenum err = glewInit();

    if (GLEW_OK != err)
    {
         std::cout << "initialiseing GLEW failed." << glewGetErrorString(err);
         return 0 ;
    }

    std::cout << "Using GLEW - " << glewGetString(GLEW_VERSION) << "\n";

//     glMatrixMode (GL_MODELVIEW);
//   glLoadIdentity();     
//        glScalef(scale, scale, scale);
//      glBegin(GL_QUADS); //draw quad.
//            glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
//            //glColor3f(SQUARE::colour4f[0],SQUARE::colour4f[1],SQUARE::colour4f[2]);
//            //glColor4f(SQUARE::colour4f[0],SQUARE::colour4f[1],SQUARE::colour4f[2],SQUARE::colour4f[3]);
//            glVertex2f(-1.0f,1.0f);
//            glVertex2f(1.0f,1.0f);
//            glVertex2f(1.0f,-1.0f);
//            glVertex2f(-1.0f,-1.0f);
//            glEnd();
//           
//            GLenum error = glGetError();
//            if( error != GL_NO_ERROR )
//            {
//            std::cout << "Error drawing! 177 " << gluErrorString( error ) << "\n";
//            return false;
//            }
//            SDL_GL_SwapWindow(window); //show content.
//            SDL_Delay(1000);
//     return 0;

    //command_thread.detach();
//    SDL_Delay(1000);
    std::string mapFile ("a.map");
    std::cout << "Initialising map!\n\n";
    
    map* ptrmap; //create a pointer of type map.
    map currentMap (screenDataW, screenDataH, mapFile);
    ptrmap = &currentMap; //make pointer point to instance of map.
    std::cout << "checking for inputted commands....";
    

    command* ptrCommand; //create a pointer of type command.
    command commandline; //create command line object.
    std::cout << "creating command line thread...\n";
    boost::thread command_thread ( boost::bind (&command::start_command, &commandline) ); //create a thread of the command line.
    std::cout << "Command thread started\n\n";
    ptrCommand = & commandline; //make pointer point to command object.
    
    int entities = ptrmap -> return_number_of_entities();
    
    boost::thread logic_loop (boost::bind(&entity_logic_loop, entities, ptrmap)); //create logic loop thread.
    
    std::cout << "Running game loop func\n\n";
    game_loop(ptrCommand, ptrmap, window);
    //game_loop( ptrmap, window);

    currentMap.destroy_map(); //destroy the map!
    SDL_GL_DeleteContext(glcontext); //clean up
    SDL_Quit(); //quit SDL   
    logic_loop.join(); //join logic thread.
    std::cout << "\nQuited nicely, press any letter/number key then tap return to terminate \n(This is a problem with using threads and std::cin together, must find a better way of doing this safely\n\n"; // - Remember killing the thread causes recursive terminate >.<.)\n\n";
    command_thread.join(); //detach both out threads.
    


    return 0;
    
    }