Esempio n. 1
0
void GLUtil::EnableDebugOutput(DebugOutputFrequency freq)
{
	// Initialize GL_ARB_debug_output
	if (GLEW_ARB_debug_output)
	{
		glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
		glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
		
		if (freq == DebugOutputFrequencyMedium)
		{
			glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_LOW_ARB, 0, NULL, GL_FALSE);
		}
		else if (freq == DebugOutputFrequencyLow)
		{
			glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM_ARB, 0, NULL, GL_FALSE);
			glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_LOW_ARB, 0, NULL, GL_FALSE);
		}
		
		glDebugMessageCallbackARB(&GLUtil::DebugOutput, NULL);
	}
	else
	{
		THROW_GL_EXCEPTION(GLException::CapabilityError, "GL_ARB_debug_output is not supported.");
	}
}
bool initDebugOutput()
{
	bool Validated(true);

	glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
	glDebugMessageCallbackARB(&glf::debugOutput, NULL);
	GLuint MessageId(4);
	glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE);
	glDebugMessageControlARB(GL_DEBUG_SOURCE_APPLICATION_ARB, GL_DEBUG_TYPE_OTHER_ARB, GL_DONT_CARE, 0, NULL, GL_TRUE);
	glDebugMessageControlARB(GL_DEBUG_SOURCE_APPLICATION_ARB, GL_DEBUG_TYPE_OTHER_ARB, GL_DONT_CARE, 1, &MessageId, GL_FALSE);
	std::string Message1("Message 1");
	glDebugMessageInsertARB(
		GL_DEBUG_SOURCE_APPLICATION_ARB, 
		GL_DEBUG_TYPE_OTHER_ARB, 1, 
		GL_DEBUG_SEVERITY_MEDIUM_ARB,
		GLsizei(Message1.size()), Message1.c_str());
	std::string Message2("Message 2");
	glDebugMessageInsertARB(
		GL_DEBUG_SOURCE_THIRD_PARTY_ARB, 
		GL_DEBUG_TYPE_OTHER_ARB, 2, 
		GL_DEBUG_SEVERITY_MEDIUM_ARB,
		GLsizei(Message2.size()), Message2.c_str());
	glDebugMessageInsertARB(
		GL_DEBUG_SOURCE_APPLICATION_ARB, 
		GL_DEBUG_TYPE_OTHER_ARB, 2, 
		GL_DEBUG_SEVERITY_MEDIUM_ARB,
		-1, "Message 3");
	glDebugMessageInsertARB(
		GL_DEBUG_SOURCE_APPLICATION_ARB, 
		GL_DEBUG_TYPE_OTHER_ARB, MessageId, 
		GL_DEBUG_SEVERITY_MEDIUM_ARB,
		-1, "Message 4");

	return Validated;
}
Esempio n. 3
0
bool GLUtils::EnableDebugOutput(DebugOutputFrequency freq)
{
	// Initialize GL_ARB_debug_output
	if (GLEW_ARB_debug_output)
	{
		glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
		glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);

		if (freq == DebugOutputFrequencyMedium)
		{
			glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_LOW_ARB, 0, NULL, GL_FALSE);
		}
		else if (freq == DebugOutputFrequencyLow)
		{
			glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM_ARB, 0, NULL, GL_FALSE);
			glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_LOW_ARB, 0, NULL, GL_FALSE);
		}
			
		glDebugMessageCallbackARB(&DebugOutput, NULL);
	}
	else
	{
		FW_LOG_ERROR("GL_ARB_debug_output is not supported");
		return false;
	}

	return true;
}
// enables/disables user events (app and third party)
void 
VSDebugLib::enableUserMessages(bool enabled) {

	glDebugMessageControlARB(GL_DEBUG_SOURCE_APPLICATION_ARB, GL_DONT_CARE,
						GL_DONT_CARE, 0, NULL, enabled);
	glDebugMessageControlARB(GL_DEBUG_SOURCE_THIRD_PARTY_ARB, GL_DONT_CARE,
						GL_DONT_CARE, 0, NULL, enabled);
}
Esempio n. 5
0
void initialize() {
	
	if(!isEnabled()) {
		return;
	}
	
	if(!GLEW_ARB_debug_output) {
		LogWarning << "OpenGL debug output disabled";
		return;
	}
	
	glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
	
	// GLEW versions before 1.11.0 define GLDEBUGPROCARB with a non-const user pointer
	#if defined(GLEW_VERSION_4_5)
	glDebugMessageCallbackARB(gldebug::callback, NULL);
	#else
	glDebugMessageCallbackARB((GLDEBUGPROCARB)gldebug::callback, NULL);
	#endif
	
	// Forward messages with high severity level
	glDebugMessageControlARB(GL_DONT_CARE,
	                         GL_DONT_CARE,
	                         GL_DEBUG_SEVERITY_HIGH_ARB,
	                         0,
	                         NULL,
	                         GL_TRUE);
	
	// Forward messages with medium severity level
	glDebugMessageControlARB(GL_DONT_CARE,
	                         GL_DONT_CARE,
	                         GL_DEBUG_SEVERITY_MEDIUM_ARB,
	                         0,
	                         NULL,
	                         GL_TRUE);
	
	// Forward messages from the application
	glDebugMessageControlARB(GL_DEBUG_SOURCE_APPLICATION_ARB,
	                         GL_DONT_CARE,
	                         GL_DONT_CARE,
	                         0,
	                         NULL,
	                         GL_TRUE);
	
	
	std::string strInitialized("OpenGL debug output enabled");
	glDebugMessageInsertARB(GL_DEBUG_SOURCE_APPLICATION_ARB,
	                        GL_DEBUG_TYPE_OTHER_ARB,
	                        1,
	                        GL_DEBUG_SEVERITY_LOW_ARB,
	                        GLsizei(strInitialized.size()), strInitialized.c_str());
}
// Enables/disables low severity events
void 
VSDebugLib::enableLowSeverityMessages(bool enabled) {

	glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, 
						GL_DEBUG_SEVERITY_LOW_ARB, 0, NULL, enabled);

}
Esempio n. 7
0
bool initDebugOutput()
{
	glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
	glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
	glDebugMessageCallbackARB(&glf::debugOutput, NULL);

	return true;
}
Esempio n. 8
0
void GlfwApp::onCreate() {
  windowAspect = glm::aspect(windowSize);
  windowAspectInverse = 1.0f / windowAspect;
  glfwSetWindowUserPointer(window, this);
  glfwSetKeyCallback(window, glfwKeyCallback);
  glfwSetMouseButtonCallback(window, glfwMouseButtonCallback);
  glfwMakeContextCurrent(window);
  glfwSwapInterval(1);

// Initialize the OpenGL bindings
// For some reason we have to set this experminetal flag to properly
// init GLEW if we use a core context.
  glewExperimental = GL_TRUE;
  if (0 != glewInit()) {
    FAIL("Failed to initialize GL3W");
  }
  glGetError();
#ifdef RIFT_DEBUG
  GL_CHECK_ERROR;
  glEnable (GL_DEBUG_OUTPUT_SYNCHRONOUS);
  GL_CHECK_ERROR;
  GLuint unusedIds = 0;
  if (glDebugMessageCallback) {
    glDebugMessageCallback(debugCallback, this);
    GL_CHECK_ERROR;
    glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE,
        0, &unusedIds, true);
    GL_CHECK_ERROR;

  } else if (glDebugMessageCallbackARB) {
    glDebugMessageCallbackARB(debugCallback, this);
    GL_CHECK_ERROR;
    glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE,
        0, &unusedIds, true);
    GL_CHECK_ERROR;
  }
#endif
  GL_CHECK_ERROR;
/*
  if (glNamedStringARB) {
    for (int i = 0;
        Resources::LIB_SHADERS[i] != Resource::NO_SHADER; ++i) {

      std::string shaderFile = getShaderPath(
          Resources::LIB_SHADERS[i]);
      std::string shaderSrc = Files::read(shaderFile);
      size_t lastSlash = shaderFile.rfind('/');
      std::string name = shaderFile.substr(lastSlash);
      glNamedStringARB(GL_SHADER_INCLUDE_ARB,
          name.length(), name.c_str(),
          shaderSrc.length(), shaderSrc.c_str());
      GL_CHECK_ERROR;
    }
  }
*/
  compileAllShaders(Resources::VERTEX_SHADERS, GL_VERTEX_SHADER);
  compileAllShaders(Resources::FRAGMENT_SHADERS, GL_FRAGMENT_SHADER);
}
Esempio n. 9
0
File: Debug.cpp Progetto: d-phaz/Eve
//=================================================================================================
void eve::ogl::init_debug_stream(void)
{
#if defined(GL_ARB_debug_output)
	glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
	glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE);
	glDebugMessageCallbackARB(&eve::mess::Server::ogl_debug_output, 0);
	EVE_OGL_CHECK_ERROR;
#endif
}
Esempio n. 10
0
bool initDebugOutput()
{
    bool Validated(true);

    glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
    glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
    glDebugMessageCallbackARB(&amd::debugOutput, NULL);

    return Validated;
}
Esempio n. 11
0
bool initDebugOutput()
{
#	ifdef GL_ARB_debug_output
		glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
		glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
		glDebugMessageCallbackARB(&glf::debugOutput, NULL);
#	endif

	return true;
}
Esempio n. 12
0
bool initDebugOutput()
{
    bool Validated(true);

    glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
    glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM_ARB, 0, NULL, GL_FALSE);
    glDebugMessageCallbackARB(&glf::debugOutput, NULL);

    return Validated;
}
bool initDebugOutput()
{
	bool Validated(true);

	glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
	glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
	glDebugMessageCallbackARB(&glf::debugOutput, NULL);

	glf::logImplementationDependentLimit(GL_MAX_SUBROUTINES, "GL_MAX_SUBROUTINES");

	return Validated;
}
Esempio n. 14
0
static void test_api_error(unsigned flags)
{
   GLboolean skip_setup = !!(flags & SKIP_SETUP);
   GLboolean debug_enable = !!(flags & DEBUG_ENABLE);
   GLboolean callback_enable = !!(flags & CALLBACK_ENABLE);

   if (!skip_setup) {
      printf("Testing Debug %s and Callback %s\n",
             debug_enable ? "enabled" : "disabled",
             callback_enable ? "enabled" : "disabled");

      glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB, GL_DEBUG_TYPE_ERROR_ARB,
                               GL_DEBUG_SEVERITY_HIGH_ARB, 0, NULL, debug_enable);
      glDebugMessageCallbackARB(callback_enable ? debug_callback : NULL, USER_PARAM);
   } else {
      puts("Testing defaults.");
   }

   if (!piglit_check_gl_error(GL_NO_ERROR))
      piglit_report_result(PIGLIT_FAIL);

   /* empty the log */
   while (fetch_one_log_message());

   callback_called = GL_FALSE;
   glEnable(0xFFFFFFFF); /* GL error */

   if (!piglit_check_gl_error(GL_INVALID_ENUM))
      piglit_report_result(PIGLIT_FAIL);

   if (callback_called != (callback_enable && debug_enable)) {
      puts(callback_called ? "  The callback shouldn't have been called."
                           : "  The callback should have been called.");
      piglit_report_result(PIGLIT_FAIL);
   }

   if ((skip_setup || debug_enable) && !callback_enable) {
      /* the log must contain the error */
      if (!fetch_one_log_message()) {
         puts("  The log shouldn't be empty.");
         piglit_report_result(PIGLIT_FAIL);
      }
   } else {
      /* the log must be empty */
      if (fetch_one_log_message()) {
         puts("  The log should be empty.");
         piglit_report_result(PIGLIT_FAIL);
      }
   }

   if (!piglit_check_gl_error(GL_NO_ERROR))
      piglit_report_result(PIGLIT_FAIL);
}
Esempio n. 15
0
    bool
    dumpState(std::ostream &os) {
        glretrace::Context *currentContext = glretrace::getCurrentContext();
        if (glretrace::insideGlBeginEnd ||
            !currentContext) {
            return false;
        }

        if (glretrace::supportsDebugOutput) {
            // Our state dump generates lots of errors as it often tries to get
            // state that's not supported, so silence debug messages temporarily.
            glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_FALSE);
        }

        glstate::dumpCurrentContext(os);

        if (glretrace::supportsDebugOutput) {
            glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
        }

        return true;
    }
bool initDebugOutput()
{
	glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
	glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
	glDebugMessageCallbackARB(&glf::debugOutput, NULL);

	glf::logImplementationDependentLimit(GL_MAX_COMPUTE_UNIFORM_BLOCKS, "GL_MAX_COMPUTE_UNIFORM_BLOCKS");
	glf::logImplementationDependentLimit(GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS, "GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS");
	glf::logImplementationDependentLimit(GL_MAX_COMPUTE_IMAGE_UNIFORMS, "GL_MAX_COMPUTE_IMAGE_UNIFORMS");
	glf::logImplementationDependentLimit(GL_MAX_COMPUTE_SHARED_MEMORY_SIZE, "GL_MAX_COMPUTE_SHARED_MEMORY_SIZE");
	glf::logImplementationDependentLimit(GL_MAX_COMPUTE_UNIFORM_COMPONENTS, "GL_MAX_COMPUTE_UNIFORM_COMPONENTS");
	glf::logImplementationDependentLimit(GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS, "GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS");
	glf::logImplementationDependentLimit(GL_MAX_COMPUTE_ATOMIC_COUNTERS, "GL_MAX_COMPUTE_ATOMIC_COUNTERS");
	glf::logImplementationDependentLimit(GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS, "GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS");
	glf::logImplementationDependentLimit(GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS, "GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS");
	
	glf::logImplementationDependentLimit(GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT, "GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT");

	return true;
}
Esempio n. 17
0
void OpenGLManager::Init(OpenGLManager* manager) {
	logger->info("Initialising OpenGL.");

	OpenGLManager::manager = manager;

	glfwInit();

	glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);

	window = glfwCreateWindow(screenWidth, screenHeight, "Tetris 3D", NULL,
	NULL);
	if (!window) {
		glfwTerminate();
		exit(EXIT_FAILURE);
	}
	glfwMakeContextCurrent(window);
	glfwSetErrorCallback(glfw_error_callback);
	glfwSetWindowSizeCallback(window, glfw_onResize);
	glfwMakeContextCurrent(window);
	glewInit();

	glEnable(GL_BLEND);
	glEnable(GL_DEPTH_TEST);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_CULL_FACE); // cull face
	glCullFace(GL_FRONT); // cull back face //GL_BACK
	glFrontFace(GL_CCW); // GL_CCW for counter clock-wise //GL_CW clockwise

	glDebugMessageCallbackARB(gl_debug_callback, this);
	glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);

	//Controlling the volume of debug output.
	GLuint unusedIds = 0;
	//glDebugMessageControlARB(enum source, enum type, enum severity, sizei count, const uint* ids, boolean enabled).
	glDebugMessageControlARB(GL_DONT_CARE,
	GL_DONT_CARE,
	GL_DONT_CARE, 0, &unusedIds, true);

	logger->info("Initialised OpenGL.");

}
Esempio n. 18
0
	void initGLDebug(const OpenGL::Format &fmt, GLDEBUGPROC callback, void* userparam)
	{
		assert( fmt.versionMajor >= 3 );

		if ( (fmt.versionMajor > 4) || (fmt.versionMajor == 4 && fmt.versionMinor >= 3) )
		{
			glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
			glDebugMessageCallback(callback, userparam);
			glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, true);
		}
		else if ( glewIsSupported("GL_ARB_debug_output") )
		{
			glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
			glDebugMessageCallbackARB(callback, userparam);
			glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, true);
		}
		else
		{
			// Log(LogType::Warning, LogSource::Engine, LogSeverity::Medium, "OpenGL API debug output is not supported on this system.");
		}
	}
Esempio n. 19
0
bool initDebugOutput()
{
	bool Validated(true);

	glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
	glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
	glDebugMessageCallbackARB(&glf::debugOutput, NULL);

	glf::logImplementationDependentLimit(GL_MAX_IMAGE_UNITS, "GL_MAX_IMAGE_UNITS");
	glf::logImplementationDependentLimit(GL_MAX_VERTEX_IMAGE_UNIFORMS, "GL_MAX_VERTEX_IMAGE_UNIFORMS");
	glf::logImplementationDependentLimit(GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS, "GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS");
	glf::logImplementationDependentLimit(GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS, "GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS");
	glf::logImplementationDependentLimit(GL_MAX_GEOMETRY_IMAGE_UNIFORMS, "GL_MAX_GEOMETRY_IMAGE_UNIFORMS");
	glf::logImplementationDependentLimit(GL_MAX_FRAGMENT_IMAGE_UNIFORMS, "GL_MAX_FRAGMENT_IMAGE_UNIFORMS");
	glf::logImplementationDependentLimit(GL_MAX_COMBINED_IMAGE_UNIFORMS, "GL_MAX_COMBINED_IMAGE_UNIFORMS");
	glf::logImplementationDependentLimit(GL_MAX_ARRAY_TEXTURE_LAYERS, "GL_MAX_ARRAY_TEXTURE_LAYERS");
	glf::logImplementationDependentLimit(GL_MAX_TEXTURE_IMAGE_UNITS, "GL_MAX_TEXTURE_IMAGE_UNITS");
	glf::logImplementationDependentLimit(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, "GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS");
	glf::logImplementationDependentLimit(GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS, "GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS");
	//glf::logImplementationDependentLimit(GL_MAX_TEXTURE_UNITS, "GL_MAX_TEXTURE_UNITS");

	return Validated;
}
Esempio n. 20
0
void RequreExtentions()
{
  CHECK_GL_ERRORS;

  std::cout << "GPU Vendor: " << glGetString(GL_VENDOR) << std::endl;
  std::cout << "GPU Name  : " << glGetString(GL_RENDERER) << std::endl;
  std::cout << "GL_VER    : " << glGetString(GL_VERSION) << std::endl;
  std::cout << "GLSL_VER  : " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;

  // enable debug output
  //
  glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
  glDebugMessageCallbackARB(&DebugCallback, NULL);

  glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE);
  glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR_ARB, GL_DONT_CARE, 0, NULL, GL_TRUE);
  glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE_ARB, GL_DONT_CARE, 0, NULL, GL_TRUE);
  glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB, GL_DONT_CARE, 0, NULL, GL_TRUE);
  glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY_ARB, GL_DONT_CARE, 0, NULL, GL_TRUE);
  glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB, GL_DONT_CARE, 0, NULL, GL_TRUE);
}
Esempio n. 21
0
int main(int argc, char **argv){
	/* vertices for a triangle */
	/* Why does triangle[] = { vec4_new(...) } result in a segfault when returning
	 * from _mm_load_ps?
	 */
	/* Just want a sort of 3D object, but not a closed object otherwise it's hard
	 * to tell what's going on w/ flat shading */
	vec4_t object[18];
	//+Z face
	object[0] = vec4_new(-1, -1, 1, 1);
	object[1] = vec4_new(1, -1, 1, 1);
	object[2] = vec4_new(1, 1, 1, 1);
	object[3] = vec4_new(1, 1, 1, 1);
	object[4] = vec4_new(-1, 1, 1, 1);
	object[5] = vec4_new(-1, -1, 1, 1);
	//+X face
	object[6] = vec4_new(1, -1, 1, 1);
	object[7] = vec4_new(1, -1, -1, 1);
	object[8] = vec4_new(1, 1, -1, 1);
	object[9] = vec4_new(1, 1, -1, 1);
	object[10] = vec4_new(1, 1, 1, 1);
	object[11] = vec4_new(1, -1, 1, 1);
	//-X face
	object[12] = vec4_new(-1, -1, 1, 1);
	object[13] = vec4_new(-1, -1, -1, 1);
	object[14] = vec4_new(-1, 1, -1, 1);
	object[15] = vec4_new(-1, 1, -1, 1);
	object[16] = vec4_new(-1, 1, 1, 1);
	object[17] = vec4_new(-1, -1, 1, 1);

	if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
		fprintf(stderr, "SDL Init error: %s\n", SDL_GetError());
		return 1;
	}

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
#ifdef DEBUG
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
#endif

	SDL_Window *win = SDL_CreateWindow("SSE GL Test", SDL_WINDOWPOS_CENTERED,
		SDL_WINDOWPOS_CENTERED, WIN_WIDTH, WIN_HEIGHT, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(win);

	if (check_GL_error("Opened win + context")){
		SDL_GL_DeleteContext(context);
		SDL_DestroyWindow(win);
		return 1;
	}

	glewExperimental = GL_TRUE;
	GLenum err = glewInit();
	if (err != GLEW_OK){
		fprintf(stderr, "GLEW init error %d\n", err);
		SDL_GL_DeleteContext(context);
		SDL_DestroyWindow(win);
		return 1;
	}
	check_GL_error("Post GLEW init");
#ifdef DEBUG
	glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
	glDebugMessageCallbackARB(gl_debug_callback, NULL);
	glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE,
		0, NULL, GL_TRUE);
#endif
	glClearColor(0, 0, 0, 1);
	glClearDepth(1);
	glEnable(GL_DEPTH_TEST);

	//Model's vao and vbo
	GLuint model[2];
	glGenVertexArrays(1, model);
	glBindVertexArray(model[0]);
	glGenBuffers(1, model + 1);
	glBindBuffer(GL_ARRAY_BUFFER, model[1]);
	glBufferData(GL_ARRAY_BUFFER, 4 * 6 * 3 * sizeof(GLfloat), object, GL_STATIC_DRAW);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
	if (check_GL_error("Setup buffers")){
		return 1;
	}

	GLint vshader = make_shader(vert_shader_src, GL_VERTEX_SHADER);
	GLint fshader = make_shader(frag_shader_src, GL_FRAGMENT_SHADER);
	if (vshader == -1 || fshader == -1){
		return 1;
	}
	GLint program = make_program(vshader, fshader);
	if (program == -1){
		return 1;
	}
	glDeleteShader(vshader);
	glDeleteShader(fshader);

	mat4_t model_mat = mat4_mult(mat4_rotate(45, vec4_new(1, 1, 0, 0)), mat4_scale(2, 2, 2));
	model_mat = mat4_mult(mat4_translate(vec4_new(0, 2, -5, 1)), model_mat);
	mat4_t view_mat = mat4_look_at(vec4_new(0, 0, 5, 0), vec4_new(0, 0, 0, 0), vec4_new(0, 1, 0, 0));
	mat4_t proj_mat = mat4_perspective(75, ((float)WIN_WIDTH) / WIN_HEIGHT, 1, 100);
	glUseProgram(program);
	GLuint model_unif = glGetUniformLocation(program, "model");
	GLuint view_unif = glGetUniformLocation(program, "view");
	GLuint proj_unif = glGetUniformLocation(program, "proj");
	glUniformMatrix4fv(model_unif, 1, GL_FALSE, (GLfloat*)&model_mat);
	glUniformMatrix4fv(view_unif, 1, GL_FALSE, (GLfloat*)&view_mat);
	glUniformMatrix4fv(proj_unif, 1, GL_FALSE, (GLfloat*)&proj_mat);

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glDrawArrays(GL_TRIANGLES, 0, 18);
	SDL_GL_SwapWindow(win);
	check_GL_error("Post Draw");

	SDL_Event e;
	int quit = 0;
	while (!quit){
		while (SDL_PollEvent(&e)){
			if (e.type == SDL_QUIT || e.type == SDL_KEYDOWN){
				quit = 1;
			}
		}
	}

	glDeleteProgram(program);
	glDeleteVertexArrays(1, model);
	glDeleteBuffers(1, model + 1);
	SDL_GL_DeleteContext(context);
	SDL_DestroyWindow(win);

	return 0;
}
Esempio n. 22
0
int main( int argc, char ** argv )
{
   // Размеры окна по-умолчанию
   size_t const default_width  = 800;
   size_t const default_height = 800;

   glutInit               (&argc, argv);
   glutInitWindowSize     (default_width, default_height);
   // Указание формата буфера экрана:
   // - GLUT_DOUBLE - двойная буферизация
   // - GLUT_RGB - 3-ёх компонентный цвет
   // - GLUT_DEPTH - будет использоваться буфер глубины
   glutInitDisplayMode    (GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
   // Создаем контекст версии 3.3
   glutInitContextVersion (3, 3);
   // Контекст будет поддерживать отладку и "устаревшую" функциональность, которой, например, может пользоваться библиотека AntTweakBar
   glutInitContextFlags   (GLUT_FORWARD_COMPATIBLE | GLUT_DEBUG);
   // Указание либо на core либо на compatibility профил
   glutInitContextProfile (GLUT_COMPATIBILITY_PROFILE );
   int window_handle = glutCreateWindow("OpenGL basic sample");

   // Инициализация указателей на функции OpenGL
   if (glewInit() != GLEW_OK)
   {
      cerr << "GLEW init failed" << endl;
      return 1;
   }

   // Проверка созданности контекста той версии, какой мы запрашивали
   if (!GLEW_VERSION_3_3)
   {
      cerr << "OpenGL 3.3 not supported" << endl;
      return 1;
   }

#ifdef USE_CORE_OPENGL
   glutDestroyWindow(window_handle);
   glutInitContextProfile(GLUT_CORE_PROFILE);
   window_handle = glutCreateWindow("OpenGL basic sample");
#endif

   // Трассировка ошибок по callback'у
   glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
   glDebugMessageCallbackARB(gl_debug_proc, NULL);
   // выключить все трассировки
   glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE           , GL_DONT_CARE, 0, NULL, false);
   // включить сообщения только об ошибках
   glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR_ARB, GL_DONT_CARE, 0, NULL, true );

   // подписываемся на оконные события
   glutReshapeFunc(reshape_func);
   glutDisplayFunc(display_func);
   glutIdleFunc   (idle_func   );
   glutCloseFunc  (close_func  );
   glutKeyboardFunc(keyboard_func);

   // подписываемся на события для AntTweakBar'а
   glutMouseFunc        ((GLUTmousebuttonfun)TwEventMouseButtonGLUT);
   glutMotionFunc       ((GLUTmousemotionfun)TwEventMouseMotionGLUT);
   glutPassiveMotionFunc((GLUTmousemotionfun)TwEventMouseMotionGLUT);
   glutSpecialFunc      ((GLUTspecialfun    )TwEventSpecialGLUT    );
   TwGLUTModifiersFunc  (glutGetModifiers);

   try
   {
      g_triangle.reset(new triangle_demo_t());
      // Вход в главный цикл приложения
      glutMainLoop();
   }
   catch( std::exception const & except )
   {
      std::cout << except.what() << endl;
      return 1;
   }

   return 0;
}
Esempio n. 23
0
void
initContext() {
    glretrace::Context *currentContext = glretrace::getCurrentContext();

    /* Ensure we have adequate extension support */
    assert(currentContext);
    supportsTimestamp   = currentContext->hasExtension("GL_ARB_timer_query");
    supportsElapsed     = currentContext->hasExtension("GL_EXT_timer_query") || supportsTimestamp;
    supportsOcclusion   = currentContext->hasExtension("GL_ARB_occlusion_query");
    supportsDebugOutput = currentContext->hasExtension("GL_ARB_debug_output");
    supportsARBShaderObjects = currentContext->hasExtension("GL_ARB_shader_objects");

    /* Check for timer query support */
    if (retrace::profilingGpuTimes) {
        if (!supportsTimestamp && !supportsElapsed) {
            std::cout << "Error: Cannot run profile, GL_ARB_timer_query or GL_EXT_timer_query extensions are not supported." << std::endl;
            exit(-1);
        }

        GLint bits = 0;
        glGetQueryiv(GL_TIME_ELAPSED, GL_QUERY_COUNTER_BITS, &bits);

        if (!bits) {
            std::cout << "Error: Cannot run profile, GL_QUERY_COUNTER_BITS == 0." << std::endl;
            exit(-1);
        }
    }

    /* Check for occlusion query support */
    if (retrace::profilingPixelsDrawn && !supportsOcclusion) {
        std::cout << "Error: Cannot run profile, GL_ARB_occlusion_query extension is not supported." << std::endl;
        exit(-1);
    }

    /* Setup debug message call back */
    if (retrace::debug && supportsDebugOutput) {
        glretrace::Context *currentContext = glretrace::getCurrentContext();
        glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
        glDebugMessageCallbackARB(&debugOutputCallback, currentContext);

        if (DEBUG_OUTPUT_SYNCHRONOUS) {
            glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
        }
    }

    /* Sync the gpu and cpu start times */
    if (retrace::profilingCpuTimes || retrace::profilingGpuTimes) {
        if (!retrace::profiler.hasBaseTimes()) {
            double cpuTimeScale = 1.0E9 / getTimeFrequency();
            GLint64 currentTime = getCurrentTime() * cpuTimeScale;
            retrace::profiler.setBaseCpuTime(currentTime);
            retrace::profiler.setBaseGpuTime(currentTime);
        }
    }

    if (retrace::profilingMemoryUsage) {
        GLint64 currentVsize, currentRss;
        getCurrentVsize(currentVsize);
        retrace::profiler.setBaseVsizeUsage(currentVsize);
        getCurrentRss(currentRss);
        retrace::profiler.setBaseRssUsage(currentRss);
    }
}
Esempio n. 24
0
/*///////////////////////
//  Public Functions   //
///////////////////////*/
int main(int argc, char **argv)
{
    GLFWwindow *window = NULL;

    UNUSED_ARG(argc);
    UNUSED_ARG(argv);

    // initialize GLFW, our platform abstraction library.
    glfwSetErrorCallback(glfw_error);
    if (!glfwInit())
    {
        exit(EXIT_FAILURE);
    }

    glfwWindowHint(GLFW_VISIBLE,    GL_TRUE);
    glfwWindowHint(GLFW_RESIZABLE,  GL_FALSE);
    glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#if GL_DEBUG_ENABLE
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT,  GL_TRUE);
#endif

    // create the main application window and OpenGL context.
    window = glfwCreateWindow(GW_WINDOW_WIDTH, GW_WINDOW_HEIGHT, GW_WINDOW_TITLE, NULL, NULL);
    if (window == NULL)
    {
        fprintf(stderr, "ERROR: Cannot create primary GLFW window.\n");
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    glfwMakeContextCurrent(window);

    // now that we have an OpenGL context, load extensions provided by the platform.
    // note that glewExperimental is defined by the GLEW library and is required on
    // OSX or the glGenVertexArrays() call will cause a fault.
    glewExperimental = GL_TRUE;
    if (glewInit()  != GLEW_OK)
    {
        fprintf(stderr, "ERROR: Cannot initialize GLEW for the primary context.\n");
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    // clear any OpenGL error status and configure debug output.
    glGetError();
#if GL_DEBUG_ENABLE
    if (GLEW_ARB_debug_output)
    {
        glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
        glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
        glDebugMessageCallbackARB(gl_arb_debug, NULL);
    }
#endif

    // initialize global managers:
    gDisplayManager = new DisplayManager();
    gDisplayManager->Init(window);
    gInputManager = new InputManager();
    gInputManager->Init(window);

    Player *player = new Player(0);
    player->Init(gDisplayManager);
    gEntityManager = new EntityManager();
    gEntityManager->AddEntity(player);

    // game loop setup and run:
    const double   Step = GW_SIM_TIMESTEP;
    double previousTime = glfwGetTime();
    double currentTime  = previousTime;
    double elapsedTime  = 0.0;
    double accumulator  = 0.0;
    double simTime      = 0.0;
    double t            = 0.0;
    int    width        = 0;
    int    height       = 0;

    while (!glfwWindowShouldClose(window))
    {
        // retrieve the current framebuffer size, which
        // may be different from the current window size.
        glfwGetFramebufferSize(window, &width, &height);

        // update the main game clock.
        previousTime = currentTime;
        currentTime  = glfwGetTime();
        elapsedTime  = currentTime - previousTime;
        if (elapsedTime > GW_MAX_TIMESTEP)
        {
            elapsedTime = GW_MAX_TIMESTEP;
        }
        if (elapsedTime < GW_MIN_TIMESTEP)
        {
            elapsedTime = GW_MIN_TIMESTEP;
        }
        accumulator += elapsedTime;

        // process user input at the start of the frame.
        input(currentTime, elapsedTime);

        // execute the simulation zero or more times per-frame.
        // the simulation runs at a fixed timestep.
        while (accumulator >= Step)
        {
            // @todo: swap game state buffers here.
            // pass the current game state to simulate.
            simulate(simTime, Step);
            accumulator -= Step;
            simTime += Step;
        }

        // interpolate display state.
        t = accumulator / Step;
        // state = currentState * t + previousState * (1.0 - t);
        render(currentTime, elapsedTime, t, width, height);

        // now present the current frame and process OS events.
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // teardown global managers.
    delete gEntityManager;
    delete gDisplayManager;
    delete gInputManager;

    // perform any top-level cleanup.
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Esempio n. 25
0
void VCWindow::Initalize()
{
    std::cout << "Creating a VCWindow..." << std::endl;
    
	// =====   GLFW   ======================================================
	glfwSetErrorCallback(glewErrorCallback);

	if (!glfwInit())
	{
		std::cout << "Failed to initialize GLFW." << std::endl;
		std::cin.ignore();
	}
	 
	//glfwWindowHint(GLFW_DECORATED, false);
	//glfwWindowHint(GLFW_SAMPLES, 4);
	//glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	//glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
	//glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#if DEBUG
	glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, true);
#endif

	GLFWWindowHandle = glfwCreateWindow(1280, 600, "Thilenius - A 0.0.1", NULL, NULL);
	if (!GLFWWindowHandle)
	{
		glfwTerminate();
		std::cout << "Failed to create a window." << std::endl;
		std::cin.ignore();
	}

	glfwMakeContextCurrent(GLFWWindowHandle);

	// =====   GLEW   ======================================================
	glewExperimental = true;
	GLenum glewError = glewInit();
	if( glewError != GLEW_OK )
	{
		printf( "Error initializing GLEW! %s\n", glewGetErrorString( glewError ) );
		std::cin.ignore();
	}

	// =====   Debug   ======================================================
#if DEBUG
	glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
	glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
	glDebugMessageCallbackARB(&glDebugCallback, NULL);
#endif


	GLint major, minor;
	glGetIntegerv(GL_MAJOR_VERSION, &major); 
	glGetIntegerv(GL_MINOR_VERSION, &minor);
    std::cout << "OpenGL version: " << major << "." << minor << std::endl;
    std::cout << "Hardware: " << glGetString(GL_RENDERER) << std::endl << std::endl;
    
	glfwGetWindowSize(GLFWWindowHandle, &Width, &Height);
	FullViewport = VCRectangle(0, 0, Width, Height);
	
	SetVSync(false);
	std::cout << "VCWindow Initialized." << std::endl;
    glErrorCheck();

	VCInteropWindowSetPos(200, 200);
}
Esempio n. 26
0
bool render_with_preview(Driver &driver){
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0){
		std::cerr << "SDL_Init error: " << SDL_GetError() << std::endl;
		return false;
	}

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
#ifdef DEBUG
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
#endif

	const RenderTarget &target = driver.get_scene().get_render_target();
	SDL_Window *win = SDL_CreateWindow("tray render", SDL_WINDOWPOS_CENTERED,
		SDL_WINDOWPOS_CENTERED, target.get_width(), target.get_height(),
		SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(win);

	if (ogl_LoadFunctions() == ogl_LOAD_FAILED){
		std::cerr << "ogl failed to load OpenGL functions" << std::endl;
		SDL_GL_DeleteContext(context);
		SDL_DestroyWindow(win);
		SDL_Quit();
		return false;
	}
	glClearColor(0.f, 0.f, 0.f, 1.f);
	glClearDepth(1.f);

#ifdef DEBUG
	glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
	glDebugMessageCallbackARB(util::gldebug_callback, NULL);
	glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0,
		NULL, GL_TRUE);
#endif

	GLint program = util::load_program(VERTEX_SHADER_SRC, FRAGMENT_SHADER_SRC);
	if (program == -1){
		std::cerr << "GLSL shader failed to compile, aborting\n";
		SDL_GL_DeleteContext(context);
		SDL_DestroyWindow(win);
		SDL_Quit();
		return false;
	}
	glUseProgram(program);

	GLuint color;
	glGenTextures(1, &color);
	glBindTexture(GL_TEXTURE_2D, color);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, target.get_width(), target.get_height(), 0, GL_RGB,
		GL_UNSIGNED_BYTE, NULL);
	//Disable linear filtering so the image is only as nice as the ray tracer renders it
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

	//A dummy vao, required for core profile but we don't really need it
	GLuint vao;
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	//Run the driver so it renders while we update the texture with the
	//new output from it
	std::vector<Color24> color_buf(target.get_width() * target.get_height());
	driver.render();
	//We also track if we're done so we can stop updating the textures after doing a last
	//update
	bool quit = false, render_done = false;
	while (!quit){
		SDL_Event e;
		while (SDL_PollEvent(&e)){
			if (e.type == SDL_QUIT || (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)){
				driver.cancel();
				quit = true;
			}
		}
		//Let the driver do some work
		SDL_Delay(16);
		//Update the texture with new data.
		//We could do better and only update blocks of updated pixels, but this is more
		//work than I want to put into this
		if (!render_done){
			render_done = driver.done();
			target.get_colorbuf(color_buf);
			glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, target.get_width(), target.get_height(), GL_RGB,
				GL_UNSIGNED_BYTE, color_buf.data());
		}

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
		SDL_GL_SwapWindow(win);
	}
	glDeleteProgram(program);
	glDeleteTextures(1, &color);
	glDeleteVertexArrays(1, &vao);
	SDL_GL_DeleteContext(context);
	SDL_DestroyWindow(win);
	SDL_Quit();
	//If the user aborted we may not have finished the render so report our status
	return driver.done();
}
Esempio n. 27
0
File: main.cpp Progetto: dquam/Bak3d
bool initGLBase()
{
    GLuint PixelFormat;
    
    PIXELFORMATDESCRIPTOR pfd;
    memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));

    pfd.nSize      = sizeof(PIXELFORMATDESCRIPTOR);
    pfd.nVersion   = 1;
    pfd.dwFlags    = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 32;
    pfd.cDepthBits = 24;
    pfd.cStencilBits = 8;
    
    g_hDC = GetDC( g_hWnd );
    PixelFormat = ChoosePixelFormat( g_hDC, &pfd );
    SetPixelFormat( g_hDC, PixelFormat, &pfd);
    g_hRC = wglCreateContext( g_hDC );
    wglMakeCurrent( g_hDC, g_hRC );
    // calling glewinit NOW because the inside glew, there is mistake to fix...
    // This is the joy of using Core. The query glGetString(GL_EXTENSIONS) is deprecated from the Core profile.
    // You need to use glGetStringi(GL_EXTENSIONS, <index>) instead. Sounds like a "bug" in GLEW.
    glewInit();
    //wglSwapInterval(0);
#if 1
#define GLCOMPAT
    if(!wglCreateContextAttribsARB)
        wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
    if(wglCreateContextAttribsARB)
    {
        HGLRC hRC = NULL;
        int attribList[] =
        {
            WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
            WGL_CONTEXT_MINOR_VERSION_ARB, 3,
#ifdef GLCOMPAT
            WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
#else
            WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
#endif
            WGL_CONTEXT_FLAGS_ARB,
            //WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB|
#ifndef GLCOMPAT
            //WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB| // use it if you want errors when compat options still used
#endif
#ifdef _DEBUG
            WGL_CONTEXT_DEBUG_BIT_ARB
#else
            0
#endif
            ,0, 0
        };
        if (!(hRC = wglCreateContextAttribsARB(g_hDC, 0, attribList)))
        {
            LOGE("wglCreateContextAttribsARB() failed for OpenGL context.\n");
            return false;
            //attribList[3] = 0;
            //if (!(hRC = wglCreateContextAttribsARB(g_hDC, 0, attribList)))
            //    LOGE("wglCreateContextAttribsARB() failed for OpenGL context.\n");
        }
        if (!wglMakeCurrent(g_hDC, hRC))
        { LOGE("wglMakeCurrent() failed for OpenGL context.\n"); }
        else {
            wglDeleteContext( g_hRC );
            g_hRC = hRC;
#ifdef _DEBUG
            if(!glDebugMessageCallbackARB)
            {
                glDebugMessageCallbackARB = (PFNGLDEBUGMESSAGECALLBACKARBPROC)wglGetProcAddress("glDebugMessageCallbackARB");
                glDebugMessageControlARB =  (PFNGLDEBUGMESSAGECONTROLARBPROC)wglGetProcAddress("glDebugMessageControlARB");
            }
            if(glDebugMessageCallbackARB)
            {
                glDebugMessageCallbackARB(myOpenGLCallback, NULL);
                glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_HIGH_ARB, 0, NULL, GL_TRUE);
            }
#endif
        }
    }
#endif
    glewInit();
    LOGOK("Loaded Glew\n");

    LOGOK("initialized OpenGL basis\n");
    return true;
}
bool gr_opengl_init(std::unique_ptr<os::GraphicsOperations>&& graphicsOps)
{
	if (GL_initted) {
		gr_opengl_cleanup(false);
		GL_initted = false;
	}

	mprintf(( "Initializing OpenGL graphics device at %ix%i with %i-bit color...\n",
		  gr_screen.max_w,
		  gr_screen.max_h,
		  gr_screen.bits_per_pixel ));

	graphic_operations = std::move(graphicsOps);

	if ( opengl_init_display_device() ) {
		Error(LOCATION, "Unable to initialize display device!\n"
		      "This most likely means that your graphics drivers do not support the minimum required OpenGL version which is %d.%d.\n",
			  (MIN_REQUIRED_GL_VERSION / 10),
			  (MIN_REQUIRED_GL_VERSION % 10));
	}

	// Initialize function pointers
	if (!gladLoadGLLoader(GL_context->getLoaderFunction())) {
		Error(LOCATION, "Failed to load OpenGL!");
	}

	// version check
	GL_version = (GLVersion.major * 10) + GLVersion.minor;

	if (GL_version < MIN_REQUIRED_GL_VERSION) {
		Error(LOCATION, "Current GL Version of %d.%d is less than the "
			"required version of %d.%d.\n"
			"Switch video modes or update your drivers.",
			GLVersion.major,
			GLVersion.minor,
			(MIN_REQUIRED_GL_VERSION / 10),
			(MIN_REQUIRED_GL_VERSION % 10));
	}

	GL_initted = true;

#ifndef NDEBUG
	// Set up the debug extension if present
	if (GLAD_GL_ARB_debug_output) {
		nprintf(("OpenGL Debug", "Using OpenGL debug extension\n"));
		glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
		GLuint unusedIds = 0;
		glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, &unusedIds, true);

		glDebugMessageCallbackARB(debug_callback, nullptr);

		// Now print all pending log messages
		while (hasPendingDebugMessage()) {
			printNextDebugMessage();
		}
	}
#endif


	// this MUST be done before any other gr_opengl_* or
	// opengl_* function calls!!
	opengl_setup_function_pointers();

	mprintf(( "  OpenGL Vendor    : %s\n", glGetString(GL_VENDOR) ));
	mprintf(( "  OpenGL Renderer  : %s\n", glGetString(GL_RENDERER) ));
	mprintf(( "  OpenGL Version   : %s\n", glGetString(GL_VERSION) ));
	mprintf(( "\n" ));

	if (Cmdline_fullscreen_window || Cmdline_window) {
		opengl_go_windowed();
	} else {
		opengl_go_fullscreen();
	}

	init_extensions();

	// init state system (must come AFTER light is set up)
	GL_state.init();

	GLint max_texture_units = GL_supported_texture_units;
	GLint max_texture_coords = GL_supported_texture_units;

	glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &max_texture_units);
	max_texture_coords = 1;

	// create vertex array object to make OpenGL Core happy
	glGenVertexArrays(1, &GL_vao);
	glBindVertexArray(GL_vao);

	GL_state.Texture.init(max_texture_units);
	GL_state.Array.init(max_texture_coords);
	GL_state.Constants.init();

	opengl_set_texture_target();
	GL_state.Texture.SetActiveUnit(0);
	GL_state.Texture.SetTarget(GL_TEXTURE_2D);
	GL_state.Texture.Enable();

	// ready the texture system
	opengl_tcache_init();

	opengl_tnl_init();

	// setup default shaders, and shader related items
	opengl_shader_init();

	// post processing effects, after shaders are initialized
	opengl_setup_scene_textures();
	opengl_post_process_init();

	// must be called after extensions are setup
	opengl_set_vsync( !Cmdline_no_vsync );

	gr_reset_matrices();
	gr_setup_viewport();

	glClear(GL_DEPTH_BUFFER_BIT);
	glClear(GL_STENCIL_BUFFER_BIT);

	glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);

	glDepthRange(0.0, 1.0);

	glPixelStorei(GL_PACK_ALIGNMENT, 1);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

	glFlush();

	Gr_current_red = &Gr_red;
	Gr_current_blue = &Gr_blue;
	Gr_current_green = &Gr_green;
	Gr_current_alpha = &Gr_alpha;

	gr_opengl_reset_clip();
	gr_opengl_clear();
	gr_opengl_flip();
	gr_opengl_clear();
	gr_opengl_flip();
	gr_opengl_clear();

	glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &GL_max_elements_vertices);
	glGetIntegerv(GL_MAX_ELEMENTS_INDICES, &GL_max_elements_indices);

	mprintf(( "  Max texture units: %i (%i)\n", GL_supported_texture_units, max_texture_units ));
	mprintf(( "  Max client texture states: %i (%i)\n", GL_supported_texture_units, max_texture_coords ));
	mprintf(( "  Max elements vertices: %i\n", GL_max_elements_vertices ));
	mprintf(( "  Max elements indices: %i\n", GL_max_elements_indices ));
	mprintf(( "  Max texture size: %ix%i\n", GL_max_texture_width, GL_max_texture_height ));

	mprintf(( "  Max render buffer size: %ix%i\n",
		  GL_max_renderbuffer_size,
		  GL_max_renderbuffer_size ));

	mprintf(( "  Can use compressed textures: %s\n", Use_compressed_textures ? NOX("YES") : NOX("NO") ));
	mprintf(( "  Texture compression available: %s\n", Texture_compression_available ? NOX("YES") : NOX("NO") ));
	mprintf(( "  Post-processing enabled: %s\n", (Cmdline_postprocess) ? "YES" : "NO"));
	mprintf(( "  Using %s texture filter.\n", (GL_mipmap_filter) ? NOX("trilinear") : NOX("bilinear") ));

	mprintf(( "  OpenGL Shader Version: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION) ));

	mprintf(("  Max uniform block size: %d\n", GL_state.Constants.GetMaxUniformBlockSize()));
	mprintf(("  Max uniform buffer bindings: %d\n", GL_state.Constants.GetMaxUniformBlockBindings()));
	mprintf(("  Uniform buffer byte offset alignment: %d\n", GL_state.Constants.GetUniformBufferOffsetAlignment()));

	// This stops fred crashing if no textures are set
	gr_screen.current_bitmap = -1;

	mprintf(("... OpenGL init is complete!\n"));

	if (Cmdline_ati_color_swap)
		GL_read_format = GL_RGBA;

	return true;
}
Esempio n. 29
0
void GFXGLDevice::initGLState()
{  
   // We don't currently need to sync device state with a known good place because we are
   // going to set everything in GFXGLStateBlock, but if we change our GFXGLStateBlock strategy, this may
   // need to happen.
   
   // Deal with the card profiler here when we know we have a valid context.
   mCardProfiler = new GFXGLCardProfiler();
   mCardProfiler->init(); 
   glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, (GLint*)&mMaxShaderTextures);
   // JTH: Needs removed, ffp
   //glGetIntegerv(GL_MAX_TEXTURE_UNITS, (GLint*)&mMaxFFTextures);
   glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, (GLint*)&mMaxTRColors);
   mMaxTRColors = getMin( mMaxTRColors, (U32)(GFXTextureTarget::MaxRenderSlotId-1) );
   
   glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
   
   // [JTH 5/6/2016] GLSL 1.50 is really SM 4.0
   // Setting mPixelShaderVersion to 3.0 will allow Advanced Lighting to run.   
   mPixelShaderVersion = 3.0;

	// Set capability extensions.
   mCapabilities.anisotropicFiltering = mCardProfiler->queryProfile("GL_EXT_texture_filter_anisotropic");
   mCapabilities.bufferStorage = mCardProfiler->queryProfile("GL_ARB_buffer_storage");
   mCapabilities.shaderModel5 = mCardProfiler->queryProfile("GL_ARB_gpu_shader5");
   mCapabilities.textureStorage = mCardProfiler->queryProfile("GL_ARB_texture_storage");
   mCapabilities.samplerObjects = mCardProfiler->queryProfile("GL_ARB_sampler_objects");
   mCapabilities.copyImage = mCardProfiler->queryProfile("GL_ARB_copy_image");
   mCapabilities.vertexAttributeBinding = mCardProfiler->queryProfile("GL_ARB_vertex_attrib_binding");

   String vendorStr = (const char*)glGetString( GL_VENDOR );
   if( vendorStr.find("NVIDIA", 0, String::NoCase | String::Left) != String::NPos)
      mUseGlMap = false;
   
   // Workaround for all Mac's, has a problem using glMap* with volatile buffers
#ifdef TORQUE_OS_MAC
   mUseGlMap = false;
#endif

#if TORQUE_DEBUG
   if( gglHasExtension(ARB_debug_output) )
   {
      glEnable(GL_DEBUG_OUTPUT);
      glDebugMessageCallbackARB(glDebugCallback, NULL);
      glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
      GLuint unusedIds = 0;
      glDebugMessageControlARB(GL_DONT_CARE,
            GL_DONT_CARE,
            GL_DONT_CARE,
            0,
            &unusedIds,
            GL_TRUE);
   }
   else if(gglHasExtension(AMD_debug_output))
   {
      glEnable(GL_DEBUG_OUTPUT);
      glDebugMessageCallbackAMD(glAmdDebugCallback, NULL);      
      //glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
      GLuint unusedIds = 0;
      glDebugMessageEnableAMD(GL_DONT_CARE, GL_DONT_CARE, 0,&unusedIds, GL_TRUE);
   }
#endif

   PlatformGL::setVSync(smDisableVSync ? 0 : 1);

   //install vsync callback
   Con::NotifyDelegate clbk(this, &GFXGLDevice::vsyncCallback);
   Con::addVariableNotify("$pref::Video::disableVerticalSync", clbk);

   //OpenGL 3 need a binded VAO for render
   GLuint vao;
   glGenVertexArrays(1, &vao);
   glBindVertexArray(vao);
}
Esempio n. 30
0
int main(int argc, char* argv[])
{
  vsx_argvector::get_instance()->init_from_argc_argv(argc, argv);

  if (vsx_argvector::get_instance()->has_param("help"))
  {
    glewInit();
    app_print_cli_help();
    exit(0);
  }

  // Initialise GLFW
  glfwInit();
  set_modifiers();

  int     width, height, running, frames, x, y;
  double  t, t1;
  char    titlestr[ 200 ];

  bool start_fullscreen = false;
  bool manual_resolution_set = false;
  int x_res = 1280;
  int y_res = 720;


  if (vsx_argvector::get_instance()->has_param("f"))
  {
    start_fullscreen = true;
  }

  if (vsx_argvector::get_instance()->has_param_with_value("s"))
  {
    vsx_string arg2 = vsx_argvector::get_instance()->get_param_value("s");
    vsx_avector<vsx_string> parts;
    vsx_string deli = ",";
    explode(arg2, deli, parts);
    if (parts.size() == 2)
    {
      x_res = vsx_string_helper::s2i(parts[0]);
      y_res = vsx_string_helper::s2i(parts[1]);
      manual_resolution_set = true;
    } else
    {
      deli = "x";
      explode(arg2, deli, parts);
      if ( parts.size() == 2 )
      {
        x_res = vsx_string_helper::s2i(parts[0]);
        y_res = vsx_string_helper::s2i(parts[1]);
        manual_resolution_set = true;
      }
    }
  }


  if (start_fullscreen && !manual_resolution_set)
  {
    // try to get the resolution from the desktop for fullscreen
    GLFWvidmode video_mode;
    glfwGetDesktopMode(&video_mode);
    x_res = video_mode.Height;
    y_res = video_mode.Width;
  }


  if (vsx_argvector::get_instance()->has_param("gl_debug"))
  {
    printf("enabling GL DEBUG\n");
    glfwOpenWindowHint( GLFW_OPENGL_DEBUG_CONTEXT , GL_TRUE );
  }

  // OpenGL version
  glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 2);
  glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 1);

  if( !glfwOpenWindow( x_res, y_res, 0,0,0,0,16,0, start_fullscreen?GLFW_FULLSCREEN:GLFW_WINDOW ) ) // GLFW_FULLSCREEN
  {
    printf("Error! Could not create an OpenGL context. Please check your GPU drivers...\n");
    glfwTerminate();
    return 0;
  }

  glewInit();


  if (start_fullscreen)
    glfwEnable( GLFW_MOUSE_CURSOR );

  app_load(0);

  glfwEnable(GLFW_AUTO_POLL_EVENTS);

  for (int i = 1; i < argc; i++)
  {
    vsx_string arg1 = argv[i];
    if (arg1 == "-p") {
      if (i+1 < argc)
      {
        i++;
        vsx_string arg2 = argv[i];
        vsx_avector<vsx_string> parts;
        vsx_string deli = ",";
        explode(arg2, deli, parts);
        glfwSetWindowPos( vsx_string_helper::s2i(parts[0]), vsx_string_helper::s2i(parts[1]) );
      }
    }
  }

  glfwSetKeyCallback(&key_event);
  glfwSetMouseButtonCallback(&mouse_button_event);
  glfwSetMousePosCallback(&mouse_pos_event);
  glfwSetCharCallback(&key_char_event);
  glfwSetMouseWheelCallback(&mouse_wheel);
  // set window size callback function
  glfwSetWindowSizeCallback(window_size);
  // Enable sticky keys
  glfwEnable( GLFW_STICKY_KEYS );


  // vsync handling
  bool vsync = true;
  if (vsx_argvector::get_instance()->has_param("novsync"))
  {
    vsync = false;
    glfwSwapInterval(0);
  }
  else
  {
    glfwSwapInterval(1);
  }
  // Main loop
  running = GL_TRUE;
  frames = 0;

  if (vsx_argvector::get_instance()->has_param("gl_debug"))
  {
    // enable debug callback
    if (__GLEW_ARB_debug_output)
    {
      glDebugMessageCallbackARB( myErrorCallback, NULL);
      GLuint unusedIds = 0;
      glDebugMessageControlARB(
          GL_DONT_CARE,
          GL_DONT_CARE,
          GL_DONT_CARE,
          0,
          &unusedIds,
          true
      );
    }
  }

  int display_gpu_vram_stats = 0;
  if (vsx_argvector::get_instance()->has_param("gl_vram"))
  {
    display_gpu_vram_stats = 1;
  }


  #if PLATFORM_FAMILY == PLATFORM_FAMILY_UNIX
  sprintf( titlestr, "Vovoid VSXu Artiste %s [GNU/Linux %d-bit]", vsxu_ver, PLATFORM_BITS);
  #endif
  #if PLATFORM_FAMILY == PLATFORM_FAMILY_WINDOWS
  sprintf( titlestr, "Vovoid VSXu Artiste %s [Windows %d-bit]", vsxu_ver, PLATFORM_BITS);
  #endif
  glfwSetWindowTitle( titlestr );


  vsx_timer frame_delay;
  int initial_vram_free = 0;
  while( running )
  {
    frame_delay.start();

    if (mouse_pos_type)
    {
      if (mouse_pos_type == 1) app_mouse_move(last_x,last_y);
      else app_mouse_move_passive(last_x,last_y);
      mouse_pos_type = 0;
    }


    if (__GLEW_NVX_gpu_memory_info && display_gpu_vram_stats)
    {
    //      #define GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX 0x9047
    //      #define GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX 0x9048
    //      #define GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX 0x9049
    //      #define GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX 0x904A
    //      #define GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX 0x904B

//          GLint total_memory;
//          GLint total_available;
          GLint available_memory;
//          GLint eviction_count;
//          GLint eviction_size;
//          glGetIntegerv(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &total_memory);
//          glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &total_available);
//          glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX, &eviction_count);
//          glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX, &eviction_size);

          glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &available_memory);
//          float available_memory_f = (float)available_memory;

          if (initial_vram_free == 0) initial_vram_free = available_memory >> 10;

          vsx_printf("GPU MEMORY INFO: Before frame: available vram: %d MB\n", available_memory >> 10);
          vsx_printf("GPU MEMORY INFO: Probably used vram: %d MB\n", initial_vram_free - (available_memory >> 10));

          //if (gtm)
          //((vsx_tm*)gtm)->plot( available_memory_f, "gpu memory free" );

    }


    app_pre_draw();

    // Get time and mouse position
    t = glfwGetTime();
    glfwGetMousePos( &x, &y );
    float delta = t-t1;
    t1 = t;
    if (key_pressed != -1)
    {
      //printf("%f\n", delta);
      key_time += delta;
      if (key_time > 0.3f)
      {
        key_repeat_time += delta;
        if (key_repeat_time > initial_key_delay)
        {
          key_repeat_time = 0.0f;
          if (key_character != -1)
            app_char(key_character);

          app_key_down((long)key_pressed);
          initial_key_delay *= 0.99f;
          //printf("repeating key: %d\n", key_character);
        }
      }
    }

    frames ++;

      // Get window size (may be different than the requested size)
      glfwGetWindowSize( &width, &height );
      height = height > 0 ? height : 1;

      // Set viewport
      vsx_gl_state::get_instance()->viewport_set( 0, 0, width, height );

      // Clear color buffer
        glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();	// Reset The Modelview Matrix

    app_draw(0);

    glfwSwapBuffers();

//#if (PLATFORM != PLATFORM_WINDOWS)
//    if (!vsync)
//    {
//      float dtime = frame_delay.dtime();

//      if (dtime < 1.0f/60.0f)
//      {
//        float sleeptime = (1.0f / 60.0f - dtime)*1000000.0f;
//        usleep( (useconds_t) sleeptime );
//      }
//    }
//#endif


    running = glfwGetWindowParam( GLFW_OPENED );
  }