Exemplo n.º 1
0
int
main(int argc, char *argv[])
{
   glfwInit();

   glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
   glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
   glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
   glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);

   window = glfwCreateWindow(300, 300, argv[0], NULL, NULL);
   if (!window) {
       return EXIT_SKIP;
   }

   glfwMakeContextCurrent(window);

   if (!gladLoadGLES2Loader((GLADloadproc) glfwGetProcAddress)) {
       return EXIT_FAILURE;
   }

   assert(GLAD_GL_ES_VERSION_2_0);
   assert(GLAD_GL_EXT_debug_marker == glfwExtensionSupported("GL_EXT_debug_marker"));

   init();
   reshape();
   draw();

   glfwDestroyWindow(window);
   glfwTerminate();

   return 0;
}
Exemplo n.º 2
0
/** makes sure that we can use all the extensions we need for this app */
bool checkExtensions()
{
    /**
        the extesnsions that are going to be need are for bindless vbo's which are:
    */
    std::vector<std::string> extensions {
        // Allows the use of the gpu to have direct accesss to client memory
        //  bypass gpu memory managent, 
        //  have persistent mappings to buffer objects
        "GL_ARB_buffer_storage"                 // https://www.opengl.org/registry/specs/ARB/buffer_storage.txt
        ,"GL_ARB_map_buffer_range"              // https://www.opengl.org/registry/specs/ARB/map_buffer_range.txt
        ,"GL_ARB_sync"                          // https://www.opengl.org/registry/specs/ARB/sync.txt

        // queries the gpu for time stamps
        ,"GL_ARB_timer_query"                   // http://www.opengl.org/registry/specs/ARB/timer_query.txt

        // debug printing support
        ,"GL_ARB_debug_output"                  // http://www.opengl.org/registry/specs/ARB/debug_output.txt
    };

    bool found_lacking = false;
    for (auto extension : extensions) {
        if (glfwExtensionSupported(extension.c_str()) == GL_FALSE){
            std::cerr << extension << " - is required and not supported on this machine." << std::endl;
            found_lacking = true;
        }
    }

    return !found_lacking;
}
Exemplo n.º 3
0
static inline jboolean wrapped_Java_com_badlogic_jglfw_Glfw_glfwExtensionSupported
(JNIEnv* env, jclass clazz, jstring obj_extension, char* extension) {

//@line:922

		return glfwExtensionSupported(extension) == GL_TRUE;
	
}
Exemplo n.º 4
0
bool initExtensions() {
#define LOAD_EXTENSION_FUNCTION(TYPE, FN)  FN = (TYPE)glfwGetProcAddress(#FN);
	bool bRet = false;
	do {

//		char* p = (char*) glGetString(GL_EXTENSIONS);
//		printf(p);

		/* Supports frame buffer? */
		if (glfwExtensionSupported("GL_EXT_framebuffer_object") != GL_FALSE)
		{

			/* Loads frame buffer extension functions */
			LOAD_EXTENSION_FUNCTION(PFNGLGENERATEMIPMAPEXTPROC,
					glGenerateMipmapEXT);
			LOAD_EXTENSION_FUNCTION(PFNGLGENFRAMEBUFFERSEXTPROC,
					glGenFramebuffersEXT);
			LOAD_EXTENSION_FUNCTION(PFNGLDELETEFRAMEBUFFERSEXTPROC,
					glDeleteFramebuffersEXT);
			LOAD_EXTENSION_FUNCTION(PFNGLBINDFRAMEBUFFEREXTPROC,
					glBindFramebufferEXT);
			LOAD_EXTENSION_FUNCTION(PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC,
					glCheckFramebufferStatusEXT);
			LOAD_EXTENSION_FUNCTION(PFNGLFRAMEBUFFERTEXTURE2DEXTPROC,
					glFramebufferTexture2DEXT);

		} else {
			break;
		}

		if (glfwExtensionSupported("GL_ARB_vertex_buffer_object") != GL_FALSE) {
			LOAD_EXTENSION_FUNCTION(PFNGLGENBUFFERSARBPROC, glGenBuffersARB);
			LOAD_EXTENSION_FUNCTION(PFNGLBINDBUFFERARBPROC, glBindBufferARB);
			LOAD_EXTENSION_FUNCTION(PFNGLBUFFERDATAARBPROC, glBufferDataARB);
			LOAD_EXTENSION_FUNCTION(PFNGLBUFFERSUBDATAARBPROC,
					glBufferSubDataARB);
			LOAD_EXTENSION_FUNCTION(PFNGLDELETEBUFFERSARBPROC,
					glDeleteBuffersARB);
		} else {
			break;
		}
		bRet = true;
	} while (0);
	return bRet;
}
Exemplo n.º 5
0
/*
 * loadExtensions() - Load OpenGL extensions for anything above OpenGL
 * version 1.1. (This is a requirement only on Windows, so on other
 * platforms, this function just checks for the required extensions.)
 */
void loadExtensions() {
    //These extension strings indicate that the OpenGL Shading Language
    // and GLSL shader objects are supported.
    if(!glfwExtensionSupported("GL_ARB_shading_language_100"))
    {
        printError("GL init error", "GL_ARB_shading_language_100 extension was not found");
        return;
    }
    if(!glfwExtensionSupported("GL_ARB_shader_objects"))
    {
        printError("GL init error", "GL_ARB_shader_objects extension was not found");
        return;
    }
    else
    {
#ifdef __WIN32__
        glCreateProgram           = (PFNGLCREATEPROGRAMPROC)glfwGetProcAddress("glCreateProgram");
        glDeleteProgram           = (PFNGLDELETEPROGRAMPROC)glfwGetProcAddress("glDeleteProgram");
        glUseProgram              = (PFNGLUSEPROGRAMPROC)glfwGetProcAddress("glUseProgram");
        glCreateShader            = (PFNGLCREATESHADERPROC)glfwGetProcAddress("glCreateShader");
        glDeleteShader            = (PFNGLDELETESHADERPROC)glfwGetProcAddress("glDeleteShader");
        glShaderSource            = (PFNGLSHADERSOURCEPROC)glfwGetProcAddress("glShaderSource");
        glCompileShader           = (PFNGLCOMPILESHADERPROC)glfwGetProcAddress("glCompileShader");
        glGetShaderiv             = (PFNGLGETSHADERIVPROC)glfwGetProcAddress("glGetShaderiv");
        glGetShaderInfoLog        = (PFNGLGETSHADERINFOLOGPROC)glfwGetProcAddress("glGetShaderInfoLog");
        glAttachShader            = (PFNGLATTACHSHADERPROC)glfwGetProcAddress("glAttachShader");
        glLinkProgram             = (PFNGLLINKPROGRAMPROC)glfwGetProcAddress("glLinkProgram");
        glGetProgramiv            = (PFNGLGETPROGRAMIVPROC)glfwGetProcAddress("glGetProgramiv");
        glGetProgramInfoLog       = (PFNGLGETPROGRAMINFOLOGPROC)glfwGetProcAddress("glGetProgramInfoLog");
        glGetUniformLocation      = (PFNGLGETUNIFORMLOCATIONPROC)glfwGetProcAddress("glGetUniformLocation");
        glUniform1fv              = (PFNGLUNIFORM1FVPROC)glfwGetProcAddress("glUniform1fv");

        if( !glCreateProgram || !glDeleteProgram || !glUseProgram ||
            !glCreateShader || !glDeleteShader || !glShaderSource || !glCompileShader || 
            !glGetShaderiv || !glGetShaderInfoLog || !glAttachShader || !glLinkProgram ||
            !glGetProgramiv || !glGetProgramInfoLog || !glGetUniformLocation ||
            !glUniform1fv )
        {
            printError("GL init error", "One or more required OpenGL functions were not found");
            return;
        }
#endif
    }
}
Exemplo n.º 6
0
/*
 * loadExtensions - Load the required OpenGL extensions.
 */
void loadExtensions() {
  // These extension strings indicate that the OpenGL Shading Language,
  // GLSL shader objects and floating-point textures are supported.
  if(!glfwExtensionSupported("GL_ARB_shading_language_100"))
    {
      printError("GL init error", "GL_ARB_shading_language_100 extension was not found");
      return;
    }
  if(!glfwExtensionSupported("GL_ARB_shader_objects"))
    {
      printError("GL init error", "GL_ARB_shader_objects extension was not found");
      return;
    }
  // else
#ifdef __WIN32__
  glActiveTextureARB        = (PFNGLACTIVETEXTUREARBPROC)glfwGetProcAddress("glActiveTextureARB");
  glCreateProgramObjectARB  = (PFNGLCREATEPROGRAMOBJECTARBPROC)glfwGetProcAddress("glCreateProgramObjectARB");
  glDeleteObjectARB         = (PFNGLDELETEOBJECTARBPROC)glfwGetProcAddress("glDeleteObjectARB");
  glUseProgramObjectARB     = (PFNGLUSEPROGRAMOBJECTARBPROC)glfwGetProcAddress("glUseProgramObjectARB");
  glCreateShaderObjectARB   = (PFNGLCREATESHADEROBJECTARBPROC)glfwGetProcAddress("glCreateShaderObjectARB");
  glShaderSourceARB         = (PFNGLSHADERSOURCEARBPROC)glfwGetProcAddress("glShaderSourceARB");
  glCompileShaderARB        = (PFNGLCOMPILESHADERARBPROC)glfwGetProcAddress("glCompileShaderARB");
  glGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC)glfwGetProcAddress("glGetObjectParameterivARB");
  glAttachObjectARB         = (PFNGLATTACHOBJECTARBPROC)glfwGetProcAddress("glAttachObjectARB");
  glGetInfoLogARB           = (PFNGLGETINFOLOGARBPROC)glfwGetProcAddress("glGetInfoLogARB");
  glLinkProgramARB          = (PFNGLLINKPROGRAMARBPROC)glfwGetProcAddress("glLinkProgramARB");
  glGetUniformLocationARB   = (PFNGLGETUNIFORMLOCATIONARBPROC)glfwGetProcAddress("glGetUniformLocationARB");
  glUniform4fARB            = (PFNGLUNIFORM4FARBPROC)glfwGetProcAddress("glUniform4fARB");
  glUniform1fARB            = (PFNGLUNIFORM1FARBPROC)glfwGetProcAddress("glUniform1fARB");
  glUniform1iARB            = (PFNGLUNIFORM1IARBPROC)glfwGetProcAddress("glUniform1iARB");
  
  if( !glActiveTextureARB ||
    !glCreateProgramObjectARB || !glDeleteObjectARB || !glUseProgramObjectARB ||
    !glCreateShaderObjectARB || !glCreateShaderObjectARB || !glCompileShaderARB || 
    !glGetObjectParameterivARB || !glAttachObjectARB || !glGetInfoLogARB || 
    !glLinkProgramARB || !glGetUniformLocationARB || !glUniform4fARB ||
    !glUniform1fARB || !glUniform1iARB )
    {
      printError("GL init error", "One or more GL_ARB_shader_objects functions were not found");
      return;
    }
#endif
}
Exemplo n.º 7
0
void		init_msaa()
{
	if (!glfwExtensionSupported("GL_ARB_multisample"))
	{
		printf("GL_ARB_multisample extension not supported\n");

		glfwTerminate();
		exit(EXIT_FAILURE);
	}
}
Exemplo n.º 8
0
int flextInit(void)
{
  
    int major = glfwGetWindowParam(GLFW_OPENGL_VERSION_MAJOR);
    int minor = glfwGetWindowParam(GLFW_OPENGL_VERSION_MINOR);

    flextLoadOpenGLFunctions();
    
    /* --- Check for minimal version and profile --- */

    if (major * 10 + minor < 20) {
	fprintf(stderr, "Error: OpenGL version 2.0 not supported.\n");
        fprintf(stderr, "       Your version is %d.%d.\n", major, minor);
        fprintf(stderr, "       Try updating your graphics driver.\n");
        return GL_FALSE;
    }


    /* --- Check for extensions --- */

    if (!glfwExtensionSupported("GL_EXT_framebuffer_object")) {
        fprintf(stderr, "Error: OpenGL extension EXT_framebuffer_object not supported.\n");
        fprintf(stderr, "       Try updating your graphics driver.\n");
        return GL_FALSE;
    }

    if (glfwExtensionSupported("GL_ARB_geometry_shader4")) {
        FLEXT_ARB_geometry_shader4 = GL_TRUE;
    }

    if (glfwExtensionSupported("GL_EXT_transform_feedback")) {
        FLEXT_EXT_transform_feedback = GL_TRUE;
    }

    if (glfwExtensionSupported("GL_EXT_texture_filter_anisotropic")) {
        FLEXT_EXT_texture_filter_anisotropic = GL_TRUE;
    }


    return GL_TRUE;
}
Exemplo n.º 9
0
int main(void)
{
    int i, width, height;
    GLFWwindow* window;

    glfwSetErrorCallback(error_callback);

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

    glfwWindowHint(GLFW_VISIBLE, GL_FALSE);

    window = glfwCreateWindow(640, 480, "Defaults", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    glfwGetFramebufferSize(window, &width, &height);

    printf("framebuffer size: %ix%i\n", width, height);

    for (i = 0;  glfw_attribs[i].name;   i++)
    {
        printf("%s: %i\n",
               glfw_attribs[i].name,
               glfwGetWindowAttrib(window, glfw_attribs[i].attrib));
    }

    for (i = 0;  gl_attribs[i].name;   i++)
    {
        GLint value = 0;

        if (gl_attribs[i].ext)
        {
            if (!glfwExtensionSupported(gl_attribs[i].ext))
                continue;
        }

        glGetIntegerv(gl_attribs[i].attrib, &value);

        printf("%s: %i\n", gl_attribs[i].name, value);
    }

    glfwDestroyWindow(window);
    window = NULL;

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Exemplo n.º 10
0
Arquivo: perf.c Projeto: imclab/nanovg
void initGPUTimer(struct GPUtimer* timer)
{
	memset(timer, 0, sizeof(*timer));

	timer->supported = glfwExtensionSupported("GL_ARB_timer_query");
	if (timer->supported) {
#ifndef GL_ARB_timer_query
		glGetQueryObjectui64v = (pfnGLGETQUERYOBJECTUI64V)glfwGetProcAddress("glGetQueryObjectui64v");
		if (!glGetQueryObjectui64v) {
			timer->supported = GL_FALSE;
			return;
		}
#endif
		glGenQueries(GPU_QUERY_COUNT, timer->queries);
	}
}
Exemplo n.º 11
0
	void Window::makeContextCurrent() {
		glfwMakeContextCurrent(m_handle);
		WindowData *wd = getWindowData(m_handle);
		// init glaer
		if (!wd->init_done) {
			gecom::log("Window") << "GLAER initializing...";
			//GLenum t_err = glGetError();
			//gecom::log("Window") << "GLEW t_err: " << t_err;
			if (!glaerInitCurrentContext()) {
				gecom::log("Window").error() << "GLAER initialization failed:";
				glfwTerminate();
				std::abort();
			}
			// clear any GL errors from init
			GLenum gl_err = glGetError();
			while (gl_err) {
				gecom::log("Window") << "GLAER initialization left GL error " << gl_err;
				gl_err = glGetError();
			}
			//gecom::log("Window") << "GL Error: " << gluErrorString(gl_err);
			gecom::log("Window") << "GL version string: " << glGetString(GL_VERSION);
			gecom::log("Window").information(0) << "GLAER initialized";
			wd->init_done = true;
			// enable GL_ARB_debug_output if available
			if (glfwExtensionSupported("GL_ARB_debug_output")) {
				// this allows the error location to be determined from a stacktrace
				glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
				// set the callback
				glDebugMessageCallback(callbackDebugGL, this);
				glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, true);
				log("Window") << "GL debug callback installed";
			} else {
				log("Window") << "GL_ARB_debug_output not available";
			}
		}
	}
Exemplo n.º 12
0
int main(int argc, char** argv)
{
    int ch, client, context, major, minor, revision, profile;
    GLint redbits, greenbits, bluebits, alphabits, depthbits, stencilbits;
    int list_extensions = GLFW_FALSE, list_layers = GLFW_FALSE;
    GLenum error;
    GLFWwindow* window;

    enum { CLIENT, CONTEXT, BEHAVIOR, DEBUG, FORWARD, HELP, EXTENSIONS, LAYERS,
           MAJOR, MINOR, PROFILE, ROBUSTNESS, VERSION,
           REDBITS, GREENBITS, BLUEBITS, ALPHABITS, DEPTHBITS, STENCILBITS,
           ACCUMREDBITS, ACCUMGREENBITS, ACCUMBLUEBITS, ACCUMALPHABITS,
           AUXBUFFERS, SAMPLES, STEREO, SRGB, SINGLEBUFFER, NOERROR_SRSLY };
    const struct option options[] =
    {
        { "behavior",         1, NULL, BEHAVIOR },
        { "client-api",       1, NULL, CLIENT },
        { "context-api",      1, NULL, CONTEXT },
        { "debug",            0, NULL, DEBUG },
        { "forward",          0, NULL, FORWARD },
        { "help",             0, NULL, HELP },
        { "list-extensions",  0, NULL, EXTENSIONS },
        { "list-layers",      0, NULL, LAYERS },
        { "major",            1, NULL, MAJOR },
        { "minor",            1, NULL, MINOR },
        { "profile",          1, NULL, PROFILE },
        { "robustness",       1, NULL, ROBUSTNESS },
        { "version",          0, NULL, VERSION },
        { "red-bits",         1, NULL, REDBITS },
        { "green-bits",       1, NULL, GREENBITS },
        { "blue-bits",        1, NULL, BLUEBITS },
        { "alpha-bits",       1, NULL, ALPHABITS },
        { "depth-bits",       1, NULL, DEPTHBITS },
        { "stencil-bits",     1, NULL, STENCILBITS },
        { "accum-red-bits",   1, NULL, ACCUMREDBITS },
        { "accum-green-bits", 1, NULL, ACCUMGREENBITS },
        { "accum-blue-bits",  1, NULL, ACCUMBLUEBITS },
        { "accum-alpha-bits", 1, NULL, ACCUMALPHABITS },
        { "aux-buffers",      1, NULL, AUXBUFFERS },
        { "samples",          1, NULL, SAMPLES },
        { "stereo",           0, NULL, STEREO },
        { "srgb",             0, NULL, SRGB },
        { "singlebuffer",     0, NULL, SINGLEBUFFER },
        { "no-error",         0, NULL, NOERROR_SRSLY },
        { NULL, 0, NULL, 0 }
    };

    // Initialize GLFW and create window

    if (!valid_version())
        exit(EXIT_FAILURE);

    glfwSetErrorCallback(error_callback);

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

    while ((ch = getopt_long(argc, argv, "a:b:dfhlm:n:p:s:v", options, NULL)) != -1)
    {
        switch (ch)
        {
            case 'a':
            case CLIENT:
                if (strcasecmp(optarg, API_NAME_OPENGL) == 0)
                    glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
                else if (strcasecmp(optarg, API_NAME_OPENGL_ES) == 0)
                    glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
                else
                {
                    usage();
                    exit(EXIT_FAILURE);
                }
                break;
            case 'b':
            case BEHAVIOR:
                if (strcasecmp(optarg, BEHAVIOR_NAME_NONE) == 0)
                {
                    glfwWindowHint(GLFW_CONTEXT_RELEASE_BEHAVIOR,
                                   GLFW_RELEASE_BEHAVIOR_NONE);
                }
                else if (strcasecmp(optarg, BEHAVIOR_NAME_FLUSH) == 0)
                {
                    glfwWindowHint(GLFW_CONTEXT_RELEASE_BEHAVIOR,
                                   GLFW_RELEASE_BEHAVIOR_FLUSH);
                }
                else
                {
                    usage();
                    exit(EXIT_FAILURE);
                }
                break;
            case 'c':
            case CONTEXT:
                if (strcasecmp(optarg, API_NAME_NATIVE) == 0)
                    glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_NATIVE_CONTEXT_API);
                else if (strcasecmp(optarg, API_NAME_EGL) == 0)
                    glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API);
                else
                {
                    usage();
                    exit(EXIT_FAILURE);
                }
                break;
            case 'd':
            case DEBUG:
                glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
                break;
            case 'f':
            case FORWARD:
                glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
                break;
            case 'h':
            case HELP:
                usage();
                exit(EXIT_SUCCESS);
            case 'l':
            case EXTENSIONS:
                list_extensions = GLFW_TRUE;
                break;
            case LAYERS:
                list_layers = GLFW_TRUE;
                break;
            case 'm':
            case MAJOR:
                glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, atoi(optarg));
                break;
            case 'n':
            case MINOR:
                glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, atoi(optarg));
                break;
            case 'p':
            case PROFILE:
                if (strcasecmp(optarg, PROFILE_NAME_CORE) == 0)
                {
                    glfwWindowHint(GLFW_OPENGL_PROFILE,
                                   GLFW_OPENGL_CORE_PROFILE);
                }
                else if (strcasecmp(optarg, PROFILE_NAME_COMPAT) == 0)
                {
                    glfwWindowHint(GLFW_OPENGL_PROFILE,
                                   GLFW_OPENGL_COMPAT_PROFILE);
                }
                else
                {
                    usage();
                    exit(EXIT_FAILURE);
                }
                break;
            case 's':
            case ROBUSTNESS:
                if (strcasecmp(optarg, STRATEGY_NAME_NONE) == 0)
                {
                    glfwWindowHint(GLFW_CONTEXT_ROBUSTNESS,
                                   GLFW_NO_RESET_NOTIFICATION);
                }
                else if (strcasecmp(optarg, STRATEGY_NAME_LOSE) == 0)
                {
                    glfwWindowHint(GLFW_CONTEXT_ROBUSTNESS,
                                   GLFW_LOSE_CONTEXT_ON_RESET);
                }
                else
                {
                    usage();
                    exit(EXIT_FAILURE);
                }
                break;
            case 'v':
            case VERSION:
                print_version();
                exit(EXIT_SUCCESS);
            case REDBITS:
                if (strcmp(optarg, "-") == 0)
                    glfwWindowHint(GLFW_RED_BITS, GLFW_DONT_CARE);
                else
                    glfwWindowHint(GLFW_RED_BITS, atoi(optarg));
                break;
            case GREENBITS:
                if (strcmp(optarg, "-") == 0)
                    glfwWindowHint(GLFW_GREEN_BITS, GLFW_DONT_CARE);
                else
                    glfwWindowHint(GLFW_GREEN_BITS, atoi(optarg));
                break;
            case BLUEBITS:
                if (strcmp(optarg, "-") == 0)
                    glfwWindowHint(GLFW_BLUE_BITS, GLFW_DONT_CARE);
                else
                    glfwWindowHint(GLFW_BLUE_BITS, atoi(optarg));
                break;
            case ALPHABITS:
                if (strcmp(optarg, "-") == 0)
                    glfwWindowHint(GLFW_ALPHA_BITS, GLFW_DONT_CARE);
                else
                    glfwWindowHint(GLFW_ALPHA_BITS, atoi(optarg));
                break;
            case DEPTHBITS:
                if (strcmp(optarg, "-") == 0)
                    glfwWindowHint(GLFW_DEPTH_BITS, GLFW_DONT_CARE);
                else
                    glfwWindowHint(GLFW_DEPTH_BITS, atoi(optarg));
                break;
            case STENCILBITS:
                if (strcmp(optarg, "-") == 0)
                    glfwWindowHint(GLFW_STENCIL_BITS, GLFW_DONT_CARE);
                else
                    glfwWindowHint(GLFW_STENCIL_BITS, atoi(optarg));
                break;
            case ACCUMREDBITS:
                if (strcmp(optarg, "-") == 0)
                    glfwWindowHint(GLFW_ACCUM_RED_BITS, GLFW_DONT_CARE);
                else
                    glfwWindowHint(GLFW_ACCUM_RED_BITS, atoi(optarg));
                break;
            case ACCUMGREENBITS:
                if (strcmp(optarg, "-") == 0)
                    glfwWindowHint(GLFW_ACCUM_GREEN_BITS, GLFW_DONT_CARE);
                else
                    glfwWindowHint(GLFW_ACCUM_GREEN_BITS, atoi(optarg));
                break;
            case ACCUMBLUEBITS:
                if (strcmp(optarg, "-") == 0)
                    glfwWindowHint(GLFW_ACCUM_BLUE_BITS, GLFW_DONT_CARE);
                else
                    glfwWindowHint(GLFW_ACCUM_BLUE_BITS, atoi(optarg));
                break;
            case ACCUMALPHABITS:
                if (strcmp(optarg, "-") == 0)
                    glfwWindowHint(GLFW_ACCUM_ALPHA_BITS, GLFW_DONT_CARE);
                else
                    glfwWindowHint(GLFW_ACCUM_ALPHA_BITS, atoi(optarg));
                break;
            case AUXBUFFERS:
                if (strcmp(optarg, "-") == 0)
                    glfwWindowHint(GLFW_AUX_BUFFERS, GLFW_DONT_CARE);
                else
                    glfwWindowHint(GLFW_AUX_BUFFERS, atoi(optarg));
                break;
            case SAMPLES:
                if (strcmp(optarg, "-") == 0)
                    glfwWindowHint(GLFW_SAMPLES, GLFW_DONT_CARE);
                else
                    glfwWindowHint(GLFW_SAMPLES, atoi(optarg));
                break;
            case STEREO:
                glfwWindowHint(GLFW_STEREO, GLFW_TRUE);
                break;
            case SRGB:
                glfwWindowHint(GLFW_SRGB_CAPABLE, GLFW_TRUE);
                break;
            case SINGLEBUFFER:
                glfwWindowHint(GLFW_DOUBLEBUFFER, GLFW_FALSE);
                break;
            case NOERROR_SRSLY:
                glfwWindowHint(GLFW_CONTEXT_NO_ERROR, GLFW_TRUE);
                break;
            default:
                usage();
                exit(EXIT_FAILURE);
        }
    }

    print_version();

    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);

    window = glfwCreateWindow(200, 200, "Version", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);

    error = glGetError();
    if (error != GL_NO_ERROR)
        printf("*** OpenGL error after make current: 0x%08x ***\n", error);

    // Report client API version

    client = glfwGetWindowAttrib(window, GLFW_CLIENT_API);
    context = glfwGetWindowAttrib(window, GLFW_CONTEXT_CREATION_API);
    major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
    minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
    revision = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
    profile = glfwGetWindowAttrib(window, GLFW_OPENGL_PROFILE);

    printf("%s context version string: \"%s\"\n",
           get_api_name(client),
           glGetString(GL_VERSION));

    printf("%s context version parsed by GLFW: %u.%u.%u\n",
           get_api_name(client),
           major, minor, revision);

    // Report client API context properties

    if (client == GLFW_OPENGL_API)
    {
        if (major >= 3)
        {
            GLint flags;

            glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
            printf("%s context flags (0x%08x):", get_api_name(client), flags);

            if (flags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT)
                printf(" forward-compatible");
            if (flags & 2/*GL_CONTEXT_FLAG_DEBUG_BIT*/)
                printf(" debug");
            if (flags & GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB)
                printf(" robustness");
            if (flags & 8/*GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR*/)
                printf(" no-error");
            putchar('\n');

            printf("%s context flags parsed by GLFW:", get_api_name(client));

            if (glfwGetWindowAttrib(window, GLFW_OPENGL_FORWARD_COMPAT))
                printf(" forward-compatible");
            if (glfwGetWindowAttrib(window, GLFW_OPENGL_DEBUG_CONTEXT))
                printf(" debug");
            if (glfwGetWindowAttrib(window, GLFW_CONTEXT_ROBUSTNESS) == GLFW_LOSE_CONTEXT_ON_RESET)
                printf(" robustness");
            if (glfwGetWindowAttrib(window, GLFW_CONTEXT_NO_ERROR))
                printf(" no-error");
            putchar('\n');
        }

        if (major >= 4 || (major == 3 && minor >= 2))
        {
            GLint mask;
            glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &mask);

            printf("%s profile mask (0x%08x): %s\n",
                   get_api_name(client),
                   mask,
                   get_profile_name_gl(mask));

            printf("%s profile mask parsed by GLFW: %s\n",
                   get_api_name(client),
                   get_profile_name_glfw(profile));
        }

        if (glfwExtensionSupported("GL_ARB_robustness"))
        {
            const int robustness = glfwGetWindowAttrib(window, GLFW_CONTEXT_ROBUSTNESS);
            GLint strategy;
            glGetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_ARB, &strategy);

            printf("%s robustness strategy (0x%08x): %s\n",
                   get_api_name(client),
                   strategy,
                   get_strategy_name_gl(strategy));

            printf("%s robustness strategy parsed by GLFW: %s\n",
                   get_api_name(client),
                   get_strategy_name_glfw(robustness));
        }
    }

    printf("%s context renderer string: \"%s\"\n",
           get_api_name(client),
           glGetString(GL_RENDERER));
    printf("%s context vendor string: \"%s\"\n",
           get_api_name(client),
           glGetString(GL_VENDOR));

    if (major >= 2)
    {
        printf("%s context shading language version: \"%s\"\n",
               get_api_name(client),
               glGetString(GL_SHADING_LANGUAGE_VERSION));
    }

    printf("%s framebuffer:\n", get_api_name(client));

    if (client == GLFW_OPENGL_API && profile == GLFW_OPENGL_CORE_PROFILE)
    {
        glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,
                                              GL_BACK_LEFT,
                                              GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE,
                                              &redbits);
        glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,
                                              GL_BACK_LEFT,
                                              GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE,
                                              &greenbits);
        glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,
                                              GL_BACK_LEFT,
                                              GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE,
                                              &bluebits);
        glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,
                                              GL_BACK_LEFT,
                                              GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE,
                                              &alphabits);
        glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,
                                              GL_DEPTH,
                                              GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE,
                                              &depthbits);
        glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,
                                              GL_STENCIL,
                                              GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE,
                                              &stencilbits);
    }
    else
    {
        glGetIntegerv(GL_RED_BITS, &redbits);
        glGetIntegerv(GL_GREEN_BITS, &greenbits);
        glGetIntegerv(GL_BLUE_BITS, &bluebits);
        glGetIntegerv(GL_ALPHA_BITS, &alphabits);
        glGetIntegerv(GL_DEPTH_BITS, &depthbits);
        glGetIntegerv(GL_STENCIL_BITS, &stencilbits);
    }

    printf(" red: %u green: %u blue: %u alpha: %u depth: %u stencil: %u\n",
           redbits, greenbits, bluebits, alphabits, depthbits, stencilbits);

    if (client == GLFW_OPENGL_ES_API ||
        glfwExtensionSupported("GL_ARB_multisample") ||
        major > 1 || minor >= 3)
    {
        GLint samples, samplebuffers;
        glGetIntegerv(GL_SAMPLES, &samples);
        glGetIntegerv(GL_SAMPLE_BUFFERS, &samplebuffers);

        printf(" samples: %u sample buffers: %u\n", samples, samplebuffers);
    }

    if (client == GLFW_OPENGL_API && profile != GLFW_OPENGL_CORE_PROFILE)
    {
        GLint accumredbits, accumgreenbits, accumbluebits, accumalphabits;
        GLint auxbuffers;

        glGetIntegerv(GL_ACCUM_RED_BITS, &accumredbits);
        glGetIntegerv(GL_ACCUM_GREEN_BITS, &accumgreenbits);
        glGetIntegerv(GL_ACCUM_BLUE_BITS, &accumbluebits);
        glGetIntegerv(GL_ACCUM_ALPHA_BITS, &accumalphabits);
        glGetIntegerv(GL_AUX_BUFFERS, &auxbuffers);

        printf(" accum red: %u accum green: %u accum blue: %u accum alpha: %u aux buffers: %u\n",
               accumredbits, accumgreenbits, accumbluebits, accumalphabits, auxbuffers);
    }

    if (list_extensions)
        list_context_extensions(client, major, minor);

    printf("Vulkan loader: %s\n",
           glfwVulkanSupported() ? "available" : "missing");

    if (glfwVulkanSupported())
    {
        uint32_t i, re_count, pd_count;
        const char** re;
        VkApplicationInfo ai = {VK_STRUCTURE_TYPE_APPLICATION_INFO};
        VkInstanceCreateInfo ici = {VK_STRUCTURE_TYPE_APPLICATION_INFO};
        VkInstance instance;
        VkPhysicalDevice* pd;
        PFN_vkCreateInstance vkCreateInstance = (PFN_vkCreateInstance)
            glfwGetInstanceProcAddress(NULL, "vkCreateInstance");
        PFN_vkDestroyInstance vkDestroyInstance;
        PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices;
        PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties;

        re = glfwGetRequiredInstanceExtensions(&re_count);

        printf("Vulkan required instance extensions:");
        for (i = 0;  i < re_count;  i++)
            printf(" %s", re[i]);
        putchar('\n');

        if (list_extensions)
            list_vulkan_instance_extensions();

        if (list_layers)
            list_vulkan_instance_layers();

        ai.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
        ai.pApplicationName = "glfwinfo";
        ai.applicationVersion = GLFW_VERSION_MAJOR;
        ai.pEngineName = "GLFW";
        ai.engineVersion = GLFW_VERSION_MAJOR;
        ai.apiVersion = VK_API_VERSION_1_0;

        ici.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
        ici.pApplicationInfo = &ai;
        ici.enabledExtensionCount = re_count;
        ici.ppEnabledExtensionNames = re;

        if (vkCreateInstance(&ici, NULL, &instance) != VK_SUCCESS)
        {
            glfwTerminate();
            exit(EXIT_FAILURE);
        }

        vkDestroyInstance = (PFN_vkDestroyInstance)
            glfwGetInstanceProcAddress(instance, "vkDestroyInstance");
        vkEnumeratePhysicalDevices = (PFN_vkEnumeratePhysicalDevices)
            glfwGetInstanceProcAddress(instance, "vkEnumeratePhysicalDevices");
        vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)
            glfwGetInstanceProcAddress(instance, "vkGetPhysicalDeviceProperties");

        if (vkEnumeratePhysicalDevices(instance, &pd_count, NULL) != VK_SUCCESS)
        {
            vkDestroyInstance(instance, NULL);
            glfwTerminate();
            exit(EXIT_FAILURE);
        }

        pd = (VkPhysicalDevice*) calloc(pd_count, sizeof(VkPhysicalDevice));

        if (vkEnumeratePhysicalDevices(instance, &pd_count, pd) != VK_SUCCESS)
        {
            free(pd);
            vkDestroyInstance(instance, NULL);
            glfwTerminate();
            exit(EXIT_FAILURE);
        }

        for (i = 0;  i < pd_count;  i++)
        {
            VkPhysicalDeviceProperties pdp;

            vkGetPhysicalDeviceProperties(pd[i], &pdp);

            printf("Vulkan %s device: \"%s\"\n",
                   get_device_type_name(pdp.deviceType),
                   pdp.deviceName);

            if (list_extensions)
                list_vulkan_device_extensions(instance, pd[i]);

            if (list_layers)
                list_vulkan_device_layers(instance, pd[i]);
        }

        free(pd);
        vkDestroyInstance(instance, NULL);
    }

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Exemplo n.º 13
0
Arquivo: fsaa.c Projeto: eledot/Plum
int main(int argc, char** argv)
{
    int ch, samples = 4;
    GLFWwindow window;

    while ((ch = getopt(argc, argv, "hs:")) != -1)
    {
        switch (ch)
        {
            case 'h':
                usage();
                exit(EXIT_SUCCESS);
            case 's':
                samples = atoi(optarg);
                break;
            default:
                usage();
                exit(EXIT_FAILURE);
        }
    }

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

    if (samples)
        printf("Requesting FSAA with %i samples\n", samples);
    else
        printf("Requesting that FSAA not be available\n");

    glfwWindowHint(GLFW_FSAA_SAMPLES, samples);

    window = glfwCreateWindow(800, 400, GLFW_WINDOWED, "Aliasing Detector", NULL);
    if (!window)
    {
        glfwTerminate();

        fprintf(stderr, "Failed to open GLFW window: %s\n", glfwErrorString(glfwGetError()));
        exit(EXIT_FAILURE);
    }

    glfwSetKeyCallback(window, key_callback);
    glfwSetWindowSizeCallback(window, window_size_callback);

    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);

    if (!glfwExtensionSupported("GL_ARB_multisample"))
    {
        glfwTerminate();

        fprintf(stderr, "Context reports GL_ARB_multisample is not supported\n");
        exit(EXIT_FAILURE);
    }

    glGetIntegerv(GL_SAMPLES_ARB, &samples);
    if (samples)
        printf("Context reports FSAA is available with %i samples\n", samples);
    else
        printf("Context reports FSAA is unavailable\n");

    glMatrixMode(GL_PROJECTION);
    gluOrtho2D(0.f, 1.f, 0.f, 0.5f);
    glMatrixMode(GL_MODELVIEW);

    while (!glfwGetWindowParam(window, GLFW_CLOSE_REQUESTED))
    {
        GLfloat time = (GLfloat) glfwGetTime();

        glClear(GL_COLOR_BUFFER_BIT);

        glLoadIdentity();
        glTranslatef(0.25f, 0.25f, 0.f);
        glRotatef(time, 0.f, 0.f, 1.f);

        glDisable(GL_MULTISAMPLE_ARB);
        glRectf(-0.15f, -0.15f, 0.15f, 0.15f);

        glLoadIdentity();
        glTranslatef(0.75f, 0.25f, 0.f);
        glRotatef(time, 0.f, 0.f, 1.f);

        glEnable(GL_MULTISAMPLE_ARB);
        glRectf(-0.15f, -0.15f, 0.15f, 0.15f);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Exemplo n.º 14
0
GLFWAPI int GLFWAPIENTRY glfwOpenWindow( int width, int height,
    int redbits, int greenbits, int bluebits, int alphabits,
    int depthbits, int stencilbits, int mode )
{
    int AccumRedBits, AccumGreenBits, AccumBlueBits, AccumAlphaBits;
    int AuxBuffers, Stereo, RefreshRate, x, Samples;

    // Is GLFW initialized?
    if( !_glfwInitialized || _glfwWin.Opened )
    {
        return GL_FALSE;
    }

    // Check input arguments
    if( mode != GLFW_WINDOW && mode != GLFW_FULLSCREEN )
    {
        return GL_FALSE;
    }

    // Clear GLFW window state
    _glfwWin.Active            = GL_TRUE;
    _glfwWin.Iconified         = GL_FALSE;
    _glfwWin.MouseLock         = GL_FALSE;
    _glfwWin.AutoPollEvents    = GL_TRUE;
    _glfwClearInput();

    // Unregister all callback functions
    _glfwWin.WindowSizeCallback    = NULL;
    _glfwWin.WindowCloseCallback   = NULL;
    _glfwWin.WindowRefreshCallback = NULL;
    _glfwWin.KeyCallback           = NULL;
    _glfwWin.CharCallback          = NULL;
    _glfwWin.MousePosCallback      = NULL;
    _glfwWin.MouseButtonCallback   = NULL;
    _glfwWin.MouseWheelCallback    = NULL;

    // Get window hints
    AccumRedBits   = _glfwWinHints.AccumRedBits;
    AccumGreenBits = _glfwWinHints.AccumGreenBits;
    AccumBlueBits  = _glfwWinHints.AccumBlueBits;
    AccumAlphaBits = _glfwWinHints.AccumAlphaBits;
    AuxBuffers     = _glfwWinHints.AuxBuffers;
    Stereo         = _glfwWinHints.Stereo;
    RefreshRate    = _glfwWinHints.RefreshRate;
    Samples        = _glfwWinHints.Samples;

    // Check width & height
    if( width > 0 && height <= 0 )
    {
        // Set the window aspect ratio to 4:3
        height = (width * 3) / 4;
    }
    else if( width <= 0 && height > 0 )
    {
        // Set the window aspect ratio to 4:3
        width = (height * 4) / 3;
    }
    else if( width <= 0 && height <= 0 )
    {
        // Default window size
        width  = 640;
        height = 480;
    }

    // Remember window settings
    _glfwWin.Width          = width;
    _glfwWin.Height         = height;
    _glfwWin.Fullscreen     = (mode == GLFW_FULLSCREEN ? 1 : 0);
    _glfwWin.WindowNoResize = _glfwWinHints.WindowNoResize;

    // Platform specific window opening routine
    if( !_glfwPlatformOpenWindow( width, height, redbits, greenbits,
            bluebits, alphabits, depthbits, stencilbits, mode,
            AccumRedBits, AccumGreenBits, AccumBlueBits, AccumAlphaBits,
            AuxBuffers, Stereo, RefreshRate, Samples ) )
    {
        return GL_FALSE;
    }

    // Flag that window is now opened
    _glfwWin.Opened = GL_TRUE;

    // Clear window hints
    _glfwWinHints.RefreshRate    = 0;
    _glfwWinHints.AccumRedBits   = 0;
    _glfwWinHints.AccumGreenBits = 0;
    _glfwWinHints.AccumBlueBits  = 0;
    _glfwWinHints.AccumAlphaBits = 0;
    _glfwWinHints.AuxBuffers     = 0;
    _glfwWinHints.Stereo         = 0;
    _glfwWinHints.WindowNoResize = 0;
    _glfwWinHints.Samples        = 0;

    // Get window parameters (such as color buffer bits etc)
    _glfwPlatformRefreshWindowParams();

    // Get OpenGL version
    glfwGetGLVersion( &_glfwWin.GLVerMajor, &_glfwWin.GLVerMinor, &x );

    // Do we have non-power-of-two textures?
    _glfwWin.Has_GL_ARB_texture_non_power_of_two =
        glfwExtensionSupported( "GL_ARB_texture_non_power_of_two" );

    // Do we have automatic mipmap generation?
    _glfwWin.Has_GL_SGIS_generate_mipmap =
        (_glfwWin.GLVerMajor >= 2) || (_glfwWin.GLVerMinor >= 4) ||
        glfwExtensionSupported( "GL_SGIS_generate_mipmap" );

    // If full-screen mode was requested, disable mouse cursor
    if( mode == GLFW_FULLSCREEN )
    {
        glfwDisable( GLFW_MOUSE_CURSOR );
    }

    return GL_TRUE;
}
Exemplo n.º 15
0
int main(int argc, char** argv)
{
    int ch, api = 0, profile = 0, strategy = 0, major = 1, minor = 0, revision;
    GLboolean debug = GL_FALSE, forward = GL_FALSE, list = GL_FALSE;
    GLint flags, mask;
    GLFWwindow* window;

    if (!valid_version())
        exit(EXIT_FAILURE);

    while ((ch = getopt(argc, argv, "a:dfhlm:n:p:r:")) != -1)
    {
        switch (ch)
        {
            case 'a':
                if (strcasecmp(optarg, API_OPENGL) == 0)
                    api = GLFW_OPENGL_API;
                else if (strcasecmp(optarg, API_OPENGL_ES) == 0)
                    api = GLFW_OPENGL_ES_API;
                else
                {
                    usage();
                    exit(EXIT_FAILURE);
                }
            case 'd':
                debug = GL_TRUE;
                break;
            case 'f':
                forward = GL_TRUE;
                break;
            case 'h':
                usage();
                exit(EXIT_SUCCESS);
            case 'l':
                list = GL_TRUE;
                break;
            case 'm':
                major = atoi(optarg);
                break;
            case 'n':
                minor = atoi(optarg);
                break;
            case 'p':
                if (strcasecmp(optarg, PROFILE_NAME_CORE) == 0)
                    profile = GLFW_OPENGL_CORE_PROFILE;
                else if (strcasecmp(optarg, PROFILE_NAME_COMPAT) == 0)
                    profile = GLFW_OPENGL_COMPAT_PROFILE;
                else
                {
                    usage();
                    exit(EXIT_FAILURE);
                }
                break;
            case 'r':
                if (strcasecmp(optarg, STRATEGY_NAME_NONE) == 0)
                    strategy = GLFW_NO_RESET_NOTIFICATION;
                else if (strcasecmp(optarg, STRATEGY_NAME_LOSE) == 0)
                    strategy = GLFW_LOSE_CONTEXT_ON_RESET;
                else
                {
                    usage();
                    exit(EXIT_FAILURE);
                }
                break;
            default:
                usage();
                exit(EXIT_FAILURE);
        }
    }

    argc -= optind;
    argv += optind;

    // Initialize GLFW and create window

    glfwSetErrorCallback(error_callback, NULL);

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

    if (major != 1 || minor != 0)
    {
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
    }

    if (api != 0)
        glfwWindowHint(GLFW_CLIENT_API, api);

    if (debug)
        glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);

    if (forward)
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

    if (profile != 0)
        glfwWindowHint(GLFW_OPENGL_PROFILE, profile);

    if (strategy)
        glfwWindowHint(GLFW_CONTEXT_ROBUSTNESS, strategy);

    glfwWindowHint(GLFW_VISIBLE, GL_FALSE);

    window = glfwCreateWindow(200, 200, "Version", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);

    // Report client API version

    api = glfwGetWindowAttrib(window, GLFW_CLIENT_API);
    major = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
    minor = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
    revision = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);

    printf("%s context version string: \"%s\"\n",
           get_client_api_name(api),
           glGetString(GL_VERSION));

    printf("%s context version parsed by GLFW: %u.%u.%u\n",
           get_client_api_name(api),
           major, minor, revision);

    // Report client API context properties

    if (api == GLFW_OPENGL_API)
    {
        if (major >= 3)
        {
            glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
            printf("%s context flags (0x%08x):", get_client_api_name(api), flags);

            if (flags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT)
                printf(" forward-compatible");
            if (flags & GL_CONTEXT_FLAG_DEBUG_BIT)
                printf(" debug");
            if (flags & GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB)
                printf(" robustness");
            putchar('\n');

            printf("%s context flags parsed by GLFW:", get_client_api_name(api));

            if (glfwGetWindowAttrib(window, GLFW_OPENGL_FORWARD_COMPAT))
                printf(" forward-compatible");
            if (glfwGetWindowAttrib(window, GLFW_OPENGL_DEBUG_CONTEXT))
                printf(" debug");
            if (glfwGetWindowAttrib(window, GLFW_CONTEXT_ROBUSTNESS) != GLFW_NO_ROBUSTNESS)
                printf(" robustness");
            putchar('\n');
        }

        if (major > 3 || (major == 3 && minor >= 2))
        {
            int profile = glfwGetWindowAttrib(window, GLFW_OPENGL_PROFILE);

            glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &mask);
            printf("%s profile mask (0x%08x): %s\n",
                   get_client_api_name(api),
                   mask,
                   get_profile_name_gl(mask));

            printf("%s profile mask parsed by GLFW: %s\n",
                   get_client_api_name(api),
                   get_profile_name_glfw(profile));
        }

        if (glfwExtensionSupported("GL_ARB_robustness"))
        {
            int robustness;
            GLint strategy;
            glGetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_ARB, &strategy);

            printf("%s robustness strategy (0x%08x): %s\n",
                   get_client_api_name(api),
                   strategy,
                   get_strategy_name_gl(strategy));

            robustness = glfwGetWindowAttrib(window, GLFW_CONTEXT_ROBUSTNESS);

            printf("%s robustness strategy parsed by GLFW: %s\n",
                   get_client_api_name(api),
                   get_strategy_name_glfw(robustness));
        }
    }

    printf("%s context renderer string: \"%s\"\n",
           get_client_api_name(api),
           glGetString(GL_RENDERER));
    printf("%s context vendor string: \"%s\"\n",
           get_client_api_name(api),
           glGetString(GL_VENDOR));

    if (major > 1)
    {
        printf("%s context shading language version: \"%s\"\n",
               get_client_api_name(api),
               glGetString(GL_SHADING_LANGUAGE_VERSION));
    }

    // Report client API extensions
    if (list)
        list_extensions(api, major, minor);

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Exemplo n.º 16
0
GLboolean _glfwRefreshContextAttribs(const _GLFWctxconfig* ctxconfig)
{
    _GLFWwindow* window = _glfwPlatformGetCurrentContext();

    window->GetIntegerv = (PFNGLGETINTEGERVPROC) glfwGetProcAddress("glGetIntegerv");
    window->GetString = (PFNGLGETSTRINGPROC) glfwGetProcAddress("glGetString");
    window->Clear = (PFNGLCLEARPROC) glfwGetProcAddress("glClear");

    if (!parseVersionString(&window->context.api,
                            &window->context.major,
                            &window->context.minor,
                            &window->context.revision))
    {
        return GL_FALSE;
    }

#if defined(_GLFW_USE_OPENGL)
    if (window->context.major > 2)
    {
        // OpenGL 3.0+ uses a different function for extension string retrieval
        // We cache it here instead of in glfwExtensionSupported mostly to alert
        // users as early as possible that their build may be broken

        window->GetStringi = (PFNGLGETSTRINGIPROC) glfwGetProcAddress("glGetStringi");
        if (!window->GetStringi)
        {
            _glfwInputError(GLFW_PLATFORM_ERROR,
                            "Entry point retrieval is broken");
            return GL_FALSE;
        }
    }

    if (window->context.api == GLFW_OPENGL_API)
    {
        // Read back context flags (OpenGL 3.0 and above)
        if (window->context.major >= 3)
        {
            GLint flags;
            window->GetIntegerv(GL_CONTEXT_FLAGS, &flags);

            if (flags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT)
                window->context.forward = GL_TRUE;

            if (flags & GL_CONTEXT_FLAG_DEBUG_BIT)
                window->context.debug = GL_TRUE;
            else if (glfwExtensionSupported("GL_ARB_debug_output") &&
                     ctxconfig->debug)
            {
                // HACK: This is a workaround for older drivers (pre KHR_debug)
                //       not setting the debug bit in the context flags for
                //       debug contexts
                window->context.debug = GL_TRUE;
            }
        }

        // Read back OpenGL context profile (OpenGL 3.2 and above)
        if (window->context.major > 3 ||
            (window->context.major == 3 && window->context.minor >= 2))
        {
            GLint mask;
            window->GetIntegerv(GL_CONTEXT_PROFILE_MASK, &mask);

            if (mask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT)
                window->context.profile = GLFW_OPENGL_COMPAT_PROFILE;
            else if (mask & GL_CONTEXT_CORE_PROFILE_BIT)
                window->context.profile = GLFW_OPENGL_CORE_PROFILE;
            else if (glfwExtensionSupported("GL_ARB_compatibility"))
            {
                // HACK: This is a workaround for the compatibility profile bit
                //       not being set in the context flags if an OpenGL 3.2+
                //       context was created without having requested a specific
                //       version
                window->context.profile = GLFW_OPENGL_COMPAT_PROFILE;
            }
        }

        // Read back robustness strategy
        if (glfwExtensionSupported("GL_ARB_robustness"))
        {
            // NOTE: We avoid using the context flags for detection, as they are
            //       only present from 3.0 while the extension applies from 1.1

            GLint strategy;
            window->GetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_ARB, &strategy);

            if (strategy == GL_LOSE_CONTEXT_ON_RESET_ARB)
                window->context.robustness = GLFW_LOSE_CONTEXT_ON_RESET;
            else if (strategy == GL_NO_RESET_NOTIFICATION_ARB)
                window->context.robustness = GLFW_NO_RESET_NOTIFICATION;
        }
    }
    else
    {
        // Read back robustness strategy
        if (glfwExtensionSupported("GL_EXT_robustness"))
        {
            // NOTE: The values of these constants match those of the OpenGL ARB
            //       one, so we can reuse them here

            GLint strategy;
            window->GetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_ARB, &strategy);

            if (strategy == GL_LOSE_CONTEXT_ON_RESET_ARB)
                window->context.robustness = GLFW_LOSE_CONTEXT_ON_RESET;
            else if (strategy == GL_NO_RESET_NOTIFICATION_ARB)
                window->context.robustness = GLFW_NO_RESET_NOTIFICATION;
        }
    }

    if (glfwExtensionSupported("GL_KHR_context_flush_control"))
    {
        GLint behavior;
        window->GetIntegerv(GL_CONTEXT_RELEASE_BEHAVIOR, &behavior);

        if (behavior == GL_NONE)
            window->context.release = GLFW_RELEASE_BEHAVIOR_NONE;
        else if (behavior == GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH)
            window->context.release = GLFW_RELEASE_BEHAVIOR_FLUSH;
    }
#endif // _GLFW_USE_OPENGL

    return GL_TRUE;
}
Exemplo n.º 17
0
int main(int argc, char** argv)
{
    int ch, width, height;
    thrd_t physics_thread = 0;
    GLFWwindow* window;
    GLFWmonitor* monitor = NULL;

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

    while ((ch = getopt(argc, argv, "fh")) != -1)
    {
        switch (ch)
        {
            case 'f':
                monitor = glfwGetPrimaryMonitor();
                break;
            case 'h':
                usage();
                exit(EXIT_SUCCESS);
        }
    }

    if (monitor)
    {
        const GLFWvidmode* mode = glfwGetVideoMode(monitor);

        glfwWindowHint(GLFW_RED_BITS, mode->redBits);
        glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
        glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
        glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);

        width  = mode->width;
        height = mode->height;
    }
    else
    {
        width  = 640;
        height = 480;
    }

    window = glfwCreateWindow(width, height, "Particle Engine", monitor, NULL);
    if (!window)
    {
        fprintf(stderr, "Failed to create GLFW window\n");
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    if (monitor)
        glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);

    glfwSetWindowSizeCallback(window, resize_callback);
    glfwSetKeyCallback(window, key_callback);

    // Set initial aspect ratio
    glfwGetWindowSize(window, &width, &height);
    resize_callback(window, width, height);

    // Upload particle texture
    glGenTextures(1, &particle_tex_id);
    glBindTexture(GL_TEXTURE_2D, particle_tex_id);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, P_TEX_WIDTH, P_TEX_HEIGHT,
                 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, particle_texture);

    // Upload floor texture
    glGenTextures(1, &floor_tex_id);
    glBindTexture(GL_TEXTURE_2D, floor_tex_id);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    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_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, F_TEX_WIDTH, F_TEX_HEIGHT,
                 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, floor_texture);

    if (glfwExtensionSupported("GL_EXT_separate_specular_color"))
    {
        glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT,
                      GL_SEPARATE_SPECULAR_COLOR_EXT);
    }

    // Set filled polygon mode as default (not wireframe)
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    wireframe = 0;

    // Set initial times
    thread_sync.t  = 0.0;
    thread_sync.dt = 0.001f;
    thread_sync.p_frame = 0;
    thread_sync.d_frame = 0;

    mtx_init(&thread_sync.particles_lock, mtx_timed);
    cnd_init(&thread_sync.p_done);
    cnd_init(&thread_sync.d_done);

    if (thrd_create(&physics_thread, physics_thread_main, window) != thrd_success)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwSetTime(0.0);

    while (!glfwWindowShouldClose(window))
    {
        draw_scene(window, glfwGetTime());

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    thrd_join(physics_thread, NULL);

    glfwDestroyWindow(window);
    glfwTerminate();

    exit(EXIT_SUCCESS);
}
Exemplo n.º 18
0
int main(int argc, char** argv)
{
    int ch, width, height;
    float position;
    unsigned long frame_count = 0;
    double last_time, current_time;
    GLboolean fullscreen = GL_FALSE;
    GLFWmonitor* monitor = NULL;
    GLFWwindow* window;

    while ((ch = getopt(argc, argv, "fh")) != -1)
    {
        switch (ch)
        {
            case 'h':
                usage();
                exit(EXIT_SUCCESS);

            case 'f':
                fullscreen = GL_TRUE;
                break;
        }
    }

    glfwSetErrorCallback(error_callback);

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

    if (fullscreen)
    {
        const GLFWvidmode* mode;

        monitor = glfwGetPrimaryMonitor();
        mode = glfwGetVideoMode(monitor);

        glfwWindowHint(GLFW_RED_BITS, mode->redBits);
        glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
        glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
        glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);

        width = mode->width;
        height = mode->height;
    }
    else
    {
        width = 640;
        height = 480;
    }

    window = glfwCreateWindow(width, height, "", monitor, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    set_swap_interval(window, 0);

    last_time = glfwGetTime();
    frame_rate = 0.0;
    swap_tear = (glfwExtensionSupported("WGL_EXT_swap_control_tear") ||
                 glfwExtensionSupported("GLX_EXT_swap_control_tear"));

    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    glfwSetKeyCallback(window, key_callback);

    glMatrixMode(GL_PROJECTION);
    glOrtho(-1.f, 1.f, -1.f, 1.f, 1.f, -1.f);
    glMatrixMode(GL_MODELVIEW);

    while (!glfwWindowShouldClose(window))
    {
        glClear(GL_COLOR_BUFFER_BIT);

        position = cosf((float) glfwGetTime() * 4.f) * 0.75f;
        glRectf(position - 0.25f, -1.f, position + 0.25f, 1.f);

        glfwSwapBuffers(window);
        glfwPollEvents();

        frame_count++;

        current_time = glfwGetTime();
        if (current_time - last_time > 1.0)
        {
            frame_rate = frame_count / (current_time - last_time);
            frame_count = 0;
            last_time = current_time;
            update_window_title(window);
        }
    }

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Exemplo n.º 19
0
GLboolean _glfwRefreshContextAttribs(void)
{
    _GLFWwindow* window = _glfwPlatformGetCurrentContext();

    if (!parseGLVersion(&window->clientAPI,
                        &window->glMajor,
                        &window->glMinor,
                        &window->glRevision))
    {
        return GL_FALSE;
    }

#if defined(_GLFW_USE_OPENGL)
    if (window->glMajor > 2)
    {
        // OpenGL 3.0+ uses a different function for extension string retrieval
        // We cache it here instead of in glfwExtensionSupported mostly to alert
        // users as early as possible that their build may be broken

        window->GetStringi = (PFNGLGETSTRINGIPROC) glfwGetProcAddress("glGetStringi");
        if (!window->GetStringi)
        {
            _glfwInputError(GLFW_PLATFORM_ERROR,
                            "Entry point retrieval is broken");
            return GL_FALSE;
        }
    }

    if (window->clientAPI == GLFW_OPENGL_API)
    {
        // Read back context flags (OpenGL 3.0 and above)
        if (window->glMajor >= 3)
        {
            GLint flags;
            glGetIntegerv(GL_CONTEXT_FLAGS, &flags);

            if (flags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT)
                window->glForward = GL_TRUE;

            if (flags & GL_CONTEXT_FLAG_DEBUG_BIT)
                window->glDebug = GL_TRUE;
            else if (glfwExtensionSupported("GL_ARB_debug_output"))
            {
                // HACK: This is a workaround for older drivers (pre KHR_debug)
                // not setting the debug bit in the context flags for debug
                // contexts
                window->glDebug = GL_TRUE;
            }
        }

        // Read back OpenGL context profile (OpenGL 3.2 and above)
        if (window->glMajor > 3 ||
            (window->glMajor == 3 && window->glMinor >= 2))
        {
            GLint mask;
            glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &mask);

            if (mask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT)
                window->glProfile = GLFW_OPENGL_COMPAT_PROFILE;
            else if (mask & GL_CONTEXT_CORE_PROFILE_BIT)
                window->glProfile = GLFW_OPENGL_CORE_PROFILE;
        }

        // Read back robustness strategy
        if (glfwExtensionSupported("GL_ARB_robustness"))
        {
            // NOTE: We avoid using the context flags for detection, as they are
            // only present from 3.0 while the extension applies from 1.1

            GLint strategy;
            glGetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_ARB, &strategy);

            if (strategy == GL_LOSE_CONTEXT_ON_RESET_ARB)
                window->glRobustness = GLFW_LOSE_CONTEXT_ON_RESET;
            else if (strategy == GL_NO_RESET_NOTIFICATION_ARB)
                window->glRobustness = GLFW_NO_RESET_NOTIFICATION;
        }
    }
    else
    {
        // Read back robustness strategy
        if (glfwExtensionSupported("GL_EXT_robustness"))
        {
            // NOTE: The values of these constants match those of the OpenGL ARB
            // one, so we can reuse them here

            GLint strategy;
            glGetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_ARB, &strategy);

            if (strategy == GL_LOSE_CONTEXT_ON_RESET_ARB)
                window->glRobustness = GLFW_LOSE_CONTEXT_ON_RESET;
            else if (strategy == GL_NO_RESET_NOTIFICATION_ARB)
                window->glRobustness = GLFW_NO_RESET_NOTIFICATION;
        }
    }
#endif // _GLFW_USE_OPENGL

    return GL_TRUE;
}
Exemplo n.º 20
0
Arquivo: tearing.c Projeto: glfw/glfw
int main(int argc, char** argv)
{
    unsigned long frame_count = 0;
    double last_time, current_time;
    GLFWwindow* window;
    GLuint vertex_buffer, vertex_shader, fragment_shader, program;
    GLint mvp_location, vpos_location;

    glfwSetErrorCallback(error_callback);

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

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);

    window = glfwCreateWindow(640, 480, "Tearing detector", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    gladLoadGL(glfwGetProcAddress);
    set_swap_interval(window, 0);

    last_time = glfwGetTime();
    frame_rate = 0.0;
    swap_tear = (glfwExtensionSupported("WGL_EXT_swap_control_tear") ||
                 glfwExtensionSupported("GLX_EXT_swap_control_tear"));

    glfwSetKeyCallback(window, key_callback);

    glGenBuffers(1, &vertex_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL);
    glCompileShader(vertex_shader);

    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL);
    glCompileShader(fragment_shader);

    program = glCreateProgram();
    glAttachShader(program, vertex_shader);
    glAttachShader(program, fragment_shader);
    glLinkProgram(program);

    mvp_location = glGetUniformLocation(program, "MVP");
    vpos_location = glGetAttribLocation(program, "vPos");

    glEnableVertexAttribArray(vpos_location);
    glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE,
                          sizeof(vertices[0]), (void*) 0);

    while (!glfwWindowShouldClose(window))
    {
        int width, height;
        mat4x4 m, p, mvp;
        float position = cosf((float) glfwGetTime() * 4.f) * 0.75f;

        glfwGetFramebufferSize(window, &width, &height);

        glViewport(0, 0, width, height);
        glClear(GL_COLOR_BUFFER_BIT);

        mat4x4_ortho(p, -1.f, 1.f, -1.f, 1.f, 0.f, 1.f);
        mat4x4_translate(m, position, 0.f, 0.f);
        mat4x4_mul(mvp, p, m);

        glUseProgram(program);
        glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp);
        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

        glfwSwapBuffers(window);
        glfwPollEvents();

        frame_count++;

        current_time = glfwGetTime();
        if (current_time - last_time > 1.0)
        {
            frame_rate = frame_count / (current_time - last_time);
            frame_count = 0;
            last_time = current_time;
            update_window_title(window);
        }
    }

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Exemplo n.º 21
0
 bool isExtensionSupported(const char* ext) {
     return glfwExtensionSupported(ext) ? true : false;
 }
Exemplo n.º 22
0
GLFWAPI int GLFWAPIENTRY glfwOpenWindow( int width, int height,
    int redbits, int greenbits, int bluebits, int alphabits,
    int depthbits, int stencilbits, int mode )
{
    _GLFWfbconfig fbconfig;
    _GLFWwndconfig wndconfig;

    if( !_glfwInitialized || _glfwWin.opened )
    {
        return GL_FALSE;
    }

    // Set up desired framebuffer config
    fbconfig.redBits        = Max( redbits, 0 );
    fbconfig.greenBits      = Max( greenbits, 0 );
    fbconfig.blueBits       = Max( bluebits, 0 );
    fbconfig.alphaBits      = Max( alphabits, 0 );
    fbconfig.depthBits      = Max( depthbits, 0 );
    fbconfig.stencilBits    = Max( stencilbits, 0 );
    fbconfig.accumRedBits   = Max( _glfwLibrary.hints.accumRedBits, 0 );
    fbconfig.accumGreenBits = Max( _glfwLibrary.hints.accumGreenBits, 0 );
    fbconfig.accumBlueBits  = Max( _glfwLibrary.hints.accumBlueBits, 0 );
    fbconfig.accumAlphaBits = Max( _glfwLibrary.hints.accumAlphaBits, 0 );
    fbconfig.auxBuffers     = Max( _glfwLibrary.hints.auxBuffers, 0 );
    fbconfig.stereo         = _glfwLibrary.hints.stereo ? GL_TRUE : GL_FALSE;
    fbconfig.samples        = Max( _glfwLibrary.hints.samples, 0 );

    // Set up desired window config
    wndconfig.mode           = mode;
    wndconfig.refreshRate    = Max( _glfwLibrary.hints.refreshRate, 0 );
    wndconfig.windowNoResize = _glfwLibrary.hints.windowNoResize ? GL_TRUE : GL_FALSE;
    wndconfig.glMajor        = Max( _glfwLibrary.hints.glMajor, 1 );
    wndconfig.glMinor        = Max( _glfwLibrary.hints.glMinor, 0 );
    wndconfig.glForward      = _glfwLibrary.hints.glForward ? GL_TRUE : GL_FALSE;
    wndconfig.glDebug        = _glfwLibrary.hints.glDebug ? GL_TRUE : GL_FALSE;
    wndconfig.glProfile      = _glfwLibrary.hints.glProfile;

    if( wndconfig.glMajor == 1 && wndconfig.glMinor > 5 )
    {
        // OpenGL 1.x series ended with version 1.5
        return GL_FALSE;
    }
    else if( wndconfig.glMajor == 2 && wndconfig.glMinor > 1 )
    {
        // OpenGL 2.x series ended with version 2.1
        return GL_FALSE;
    }
    else if( wndconfig.glMajor == 3 && wndconfig.glMinor > 3 )
    {
        // OpenGL 3.x series ended with version 3.3
        return GL_FALSE;
    }
    else
    {
        // For now, let everything else through
    }

    if( wndconfig.glProfile &&
        ( wndconfig.glMajor < 3 || ( wndconfig.glMajor == 3 && wndconfig.glMinor < 2 ) ) )
    {
        // Context profiles are only defined for OpenGL version 3.2 and above
        return GL_FALSE;
    }

    if( wndconfig.glForward && wndconfig.glMajor < 3 )
    {
        // Forward-compatible contexts are only defined for OpenGL version 3.0 and above
        return GL_FALSE;
    }

    // Clear for next open call
    _glfwClearWindowHints();

    // Check input arguments
    if( mode != GLFW_WINDOW && mode != GLFW_FULLSCREEN )
    {
        return GL_FALSE;
    }

    // Clear GLFW window state
    _glfwWin.active         = GL_TRUE;
    _glfwWin.iconified      = GL_FALSE;
    _glfwWin.mouseLock      = GL_FALSE;
    _glfwWin.autoPollEvents = GL_TRUE;
    _glfwClearInput();

    // Unregister all callback functions
    _glfwWin.windowSizeCallback    = NULL;
    _glfwWin.windowCloseCallback   = NULL;
    _glfwWin.windowRefreshCallback = NULL;
    _glfwWin.keyCallback           = NULL;
    _glfwWin.charCallback          = NULL;
    _glfwWin.mousePosCallback      = NULL;
    _glfwWin.mouseButtonCallback   = NULL;
    _glfwWin.mouseWheelCallback    = NULL;

    // Check width & height
    if( width > 0 && height <= 0 )
    {
        // Set the window aspect ratio to 4:3
        height = (width * 3) / 4;
    }
    else if( width <= 0 && height > 0 )
    {
        // Set the window aspect ratio to 4:3
        width = (height * 4) / 3;
    }
    else if( width <= 0 && height <= 0 )
    {
        // Default window size
        width  = 640;
        height = 480;
    }

    // Remember window settings
    _glfwWin.width      = width;
    _glfwWin.height     = height;
    _glfwWin.fullscreen = (mode == GLFW_FULLSCREEN ? GL_TRUE : GL_FALSE);

    // Platform specific window opening routine
    if( !_glfwPlatformOpenWindow( width, height, &wndconfig, &fbconfig ) )
    {
        glfwCloseWindow();
        return GL_FALSE;
    }

    // Flag that window is now opened
    _glfwWin.opened = GL_TRUE;

    // Read back window and context parameters
    _glfwPlatformRefreshWindowParams();
    _glfwRefreshContextParams();

    if( _glfwWin.glMajor < wndconfig.glMajor ||
        ( _glfwWin.glMajor == wndconfig.glMajor &&
          _glfwWin.glMinor < wndconfig.glMinor ) )
    {
        glfwCloseWindow();
        return GL_FALSE;
    }

    // Do we have non-power-of-two textures (added to core in version 2.0)?
    _glfwWin.has_GL_ARB_texture_non_power_of_two =
        ( _glfwWin.glMajor >= 2 ) ||
        glfwExtensionSupported( "GL_ARB_texture_non_power_of_two" );

    // Do we have automatic mipmap generation (added to core in version 1.4)?
    _glfwWin.has_GL_SGIS_generate_mipmap =
        ( _glfwWin.glMajor >= 2 ) || ( _glfwWin.glMinor >= 4 ) ||
        glfwExtensionSupported( "GL_SGIS_generate_mipmap" );

    if( _glfwWin.glMajor > 2 )
    {
        _glfwWin.GetStringi = (PFNGLGETSTRINGIPROC) glfwGetProcAddress( "glGetStringi" );
        if( !_glfwWin.GetStringi )
        {
            // This is a very common problem among people who compile GLFW
            // on X11/GLX using custom build systems, as the glfwGetProcAddress
            // code path selection needs explicit configuration
            //
            // See readme.html section 2.2 for details

            glfwCloseWindow();
            return GL_FALSE;
        }
    }

    // If full-screen mode was requested, disable mouse cursor
    if( mode == GLFW_FULLSCREEN )
    {
        glfwDisable( GLFW_MOUSE_CURSOR );
    }

    // Start by clearing the front buffer to black (avoid ugly desktop
    // remains in our OpenGL window)
    glClear( GL_COLOR_BUFFER_BIT );
    _glfwPlatformSwapBuffers();

    return GL_TRUE;
}
Exemplo n.º 23
0
static void
Init(void)
{
    const GLubyte *extensions;
    GLboolean hasDebugExtension;
       
    extensions = glGetString(GL_EXTENSIONS);
    checkGlError("glGetString(GL_EXTENSIONS)");
    hasDebugExtension = checkExtension(debugExtensionString, extensions);

    if (GLAD_GL_VERSION_3_0) {
       GLboolean hasDebugExtension3 = GL_FALSE;
       GLint i;

       GLint num_extensions = 0;
       glGetIntegerv(GL_NUM_EXTENSIONS, &num_extensions);
       checkGlError("glGetIntegerv(GL_NUM_EXTENSIONS)");

       for (i = 0; i < num_extensions; ++i) {
          const char *extension;

          extension = (const char *)glGetStringi(GL_EXTENSIONS, i);
          checkGlError("glGetStringi(GL_EXTENSIONS, i)");

          if (strlen(extension) == 0) {
             fprintf(stderr, "error: glGetStringi returned empty string\n");
             exit(1);
          }

          if (strcmp(extension, debugExtensionString) == 0) {
             hasDebugExtension3 = GL_TRUE;
          }
       }

       if (hasDebugExtension != hasDebugExtension3) {
          fprintf(stderr, "error: %s not consistently supported by GL3\n", debugExtensionString);
          exit(1);
       }
    }

    if (hasDebugExtension != glfwExtensionSupported(debugExtensionString)) {
       fprintf(stderr, "error: %s not consistently supported by GLFW\n", debugExtensionString);
       exit(1);
    }

    if (hasDebugExtension) {
       switch (debugExtension) {
       case KHR_DEBUG:
           debugMessageInsert = khrDebugMessageInsert;
           pushDebugGroup = khrPushDebugGroup;
           popDebugGroup = khrPopDebugGroup;
           objectLabel = glObjectLabel;
           getObjectLabel = glGetObjectLabel;
           break;
       case ARB_DEBUG_OUTPUT:
           debugMessageInsert = arbDebugMessageInsert;
           break;
       case AMD_DEBUG_OUTPUT:
           debugMessageInsert = amdDebugMessageInsert;
           break;
       case EXT_DEBUG_MARKER:
           debugMessageInsert = extDebugMessageInsert;
           pushDebugGroup = extPushDebugGroup;
           popDebugGroup = extPopDebugGroup;
           break;
       }
    } else {
       fprintf(stderr, "warning: %s not supported\n", debugExtensionString);
#ifdef __APPLE__
       if (debugExtension == KHR_DEBUG && glfwExtensionSupported("GL_EXT_debug_label")) {
           // glretrace will fallback to EXT_debug_label internally
           require = GL_FALSE;
       }
#endif
       if (require) {
           exit(EXIT_SKIP);
       }
    }

    debugMessageInsert(-1, __FUNCTION__);
    pushDebugGroup(-1, __FUNCTION__);

    glClearColor(0.3, 0.1, 0.3, 1.0);
    
    popDebugGroup();

    
    // texture label
    GLuint texture = 0;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    objectLabel(GL_TEXTURE, texture, -1, "texture");
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);

    // framebuffer color attachment label
    GLuint framebuffer = 0;
    glGenFramebuffers(1, &framebuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
Exemplo n.º 24
0
int main()
{
    GLFWwindow *window;
    char *userptr = "userptr";

    glfwSetErrorCallback(errorcb);
    assert(glfwInit() == GL_TRUE);
    assert(!strcmp(glfwGetVersionString(), "3.2.1 JS WebGL Emscripten"));
    assert(glfwGetCurrentContext() == NULL);

    {
        int major, minor, rev;
        glfwGetVersion(&major, &minor, &rev);
        assert(major == 3);
        assert(minor == 2);
        assert(rev == 1);
    }

    {
        int count, x, y, w, h;
        GLFWmonitor **monitors = glfwGetMonitors(&count);
        assert(count == 1);
        for (int i = 0; i < count; ++i) {
            assert(monitors[i] != NULL);
        }

        assert(glfwGetPrimaryMonitor() != NULL);
        glfwGetMonitorPos(monitors[0], &x, &y);
        glfwGetMonitorPhysicalSize(monitors[0], &w, &h);
        assert(glfwGetMonitorName(monitors[0]) != NULL);
        glfwSetMonitorCallback(monitcb);

        // XXX: not implemented
        // assert(glfwGetVideoModes(monitors[0], &count) != NULL);
        // assert(glfwGetVideoMode(monitors[0]) != NULL);
        // glfwSetGamma(monitors[0], 1.0f);
        // assert(glfwGetGammaRamp(monitors[0]) != NULL);
        // glfwSetGammaRamp(monitors[0], ramp);
    }

    {
        int x, y, w, h;
        glfwDefaultWindowHints();
        glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);

        window = glfwCreateWindow(640, 480, "glfw3.c", NULL, NULL);
        assert(window != NULL);

        glfwSetWindowPosCallback(window, wposicb);
        glfwSetWindowSizeCallback(window, wsizecb);
        glfwSetWindowCloseCallback(window, wcloscb);
        glfwSetWindowRefreshCallback(window, wrfrscb);
        glfwSetWindowFocusCallback(window, wfocucb);
        glfwSetWindowIconifyCallback(window, wiconcb);
        glfwSetFramebufferSizeCallback(window, wfsizcb);

        assert(glfwWindowShouldClose(window) == 0);
        glfwSetWindowShouldClose(window, 1);
        assert(glfwWindowShouldClose(window) == 1);

        glfwSetWindowTitle(window, "test");
        glfwSetWindowTitle(window, "glfw3.c");

        // XXX: not implemented
        // glfwSetWindowPos(window, 1, 1);

        glfwGetWindowPos(window, &x, &y); // stub
        glfwGetWindowSize(window, &w, &h);
        assert(w == 640 && h == 480);

        glfwSetWindowSize(window, 1, 1);
        glfwGetWindowSize(window, &w, &h);
        assert(w == 1 && h == 1);

        glfwSetWindowSize(window, 640, 480);
        glfwGetFramebufferSize(window, &w, &h);

        // XXX: not implemented
        // glfwIconifyWindow(window);
        // glfwRestoreWindow(window);
        // glfwShowWindow(window);
        // glfwHideWindow(window);

        assert(glfwGetWindowMonitor(window) == NULL);
        glfwDestroyWindow(window);

        window = glfwCreateWindow(640, 480, "glfw3.c", glfwGetPrimaryMonitor(), NULL);
        assert(window != NULL);
        assert(glfwGetWindowMonitor(window) == glfwGetPrimaryMonitor());
        glfwDestroyWindow(window);

        window = glfwCreateWindow(640, 480, "glfw3.c", NULL, NULL);
        assert(window != NULL);

        assert(glfwGetWindowAttrib(window, GLFW_CLIENT_API) == GLFW_OPENGL_ES_API);

        assert(glfwGetWindowUserPointer(window) == NULL);
        glfwSetWindowUserPointer(window, userptr);
        assert(glfwGetWindowUserPointer(window) == userptr);
    }

    {
        double x, y;

        glfwSetKeyCallback(window, wkeypcb);
        glfwSetCharCallback(window, wcharcb);
        glfwSetMouseButtonCallback(window, wmbutcb);
        glfwSetCursorPosCallback(window, wcurpcb);
        glfwSetCursorEnterCallback(window, wcurecb);
        glfwSetScrollCallback(window, wscrocb);

        // XXX: stub, events come immediatly
        // glfwPollEvents();
        // glfwWaitEvents();

        assert(glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_NORMAL);

        // XXX: not implemented
        // glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);

        glfwGetKey(window, GLFW_KEY_A);
        glfwGetMouseButton(window, 0);
        glfwGetCursorPos(window, &x, &y);

        // XXX: not implemented
        // glfwSetCursorPos(window, 0, 0);
    }

    {
        // XXX: not implemented
        // glfwJoystickPresent(joy);
        // glfwGetJoystickAxes(joy, &count);
        // glfwGetJoystickButtons(joy, &count);
        // glfwGetJoystickName(joy);
    }

    {
        // XXX: not implemented
        // glfwSetClipboardString(window, "string");
        // glfwGetClipboardString(window);
    }

    {
        glfwGetTime();
        glfwSetTime(0);
    }

    {
        glfwMakeContextCurrent(window); // stub
        assert(glfwGetCurrentContext() == window);
        glfwSwapBuffers(window); // stub
        glfwSwapInterval(0); // stub
    }

    {
        assert(glfwExtensionSupported("nonexistant") == 0);
        assert(glfwGetProcAddress("nonexistant") == NULL);
    }

    glfwTerminate();

#ifdef REPORT_RESULT
    REPORT_RESULT(1);
#endif
    return 0;
}
Exemplo n.º 25
0
void PullInfo(){
  printf("================================================================================\n");
  
  int major, minor, rev;
  glfwGetVersion(&major, &minor, &rev);
  printf("GLFW version is %i.%i.%i\n", major, minor, rev);
  
  int width, height;
  glfwGetWindowSize(&width, &height);
  printf("Window size is %i %i\n", width, height);
  
  int status = glfwGetKey(GLFW_KEY_LCTRL);
  if(status == GLFW_PRESS)
    printf("Left control is pressed\n");
  else
    printf("Left control is released\n");
    
  status = glfwGetMouseButton(GLFW_MOUSE_BUTTON_1);
  if(status == GLFW_PRESS)
    printf("Mouse button 1 is pressed\n");
  else
    printf("Mouse button 1 is released\n");
    
  int x, y;
  glfwGetMousePos(&x, &y);
  printf("Mouse position is %i %i\n", x, y);
  
  int wheel = glfwGetMouseWheel();
  printf("Mouse wheel pos is %i\n", wheel);
  
  double time = glfwGetTime();
  printf("Time is %f\n", time);
  
  glfwGetGLVersion(&major, &minor, &rev);
  printf("GL version is %i.%i.%i\n", major, minor, rev);
  
  int proc = glfwGetNumberOfProcessors();
  printf("%i processors are available\n", proc);
  
  unsigned int i;
  for(i = 0; i<nb_params; i++)
    printf(" - %-27s : %i\n", GetParamName(params[i]), glfwGetWindowParam(params[i]));
  
  const char* extension = "MOZ_WEBGL_compressed_texture_s3tc";
  printf("'%s' extension is %s.\n", extension, glfwExtensionSupported(extension) ? "supported" : "not supported");  
  
  extension = "GL_EXT_framebuffer_object";
  printf("'%s' extension is %s.\n", extension, glfwExtensionSupported(extension) ? "supported" : "not supported");
  
  extension = "glBindBuffer";
  void* proc_addr = glfwGetProcAddress(extension);
  printf("'%s' extension proc address is %p.\n", extension, proc_addr);
  
  printf("Sleeping 1 sec...\n");
  glfwSleep(1);
  printf("...Done.\n");
  
  printf("================================================================================\n");
  
#ifdef REPORT_RESULT  
  int result = 1;
  REPORT_RESULT();
#endif
}
Exemplo n.º 26
0
int main(int argc, char **argv)
#endif
{
    const GLFWvidmode *video_mode;
    int c;

    while ((c = fz_getopt(argc, argv, "p:r:W:H:S:U:X")) != -1)
    {
        switch (c)
        {
        default:
            usage(argv[0]);
            break;
        case 'p':
            password = fz_optarg;
            break;
        case 'r':
            currentzoom = fz_atof(fz_optarg);
            break;
        case 'W':
            layout_w = fz_atof(fz_optarg);
            break;
        case 'H':
            layout_h = fz_atof(fz_optarg);
            break;
        case 'S':
            layout_em = fz_atof(fz_optarg);
            break;
        case 'U':
            layout_css = fz_optarg;
            break;
        case 'X':
            layout_use_doc_css = 0;
            break;
        }
    }

    if (fz_optind < argc)
    {
        fz_strlcpy(filename, argv[fz_optind], sizeof filename);
    }
    else
    {
#ifdef _WIN32
        win_install();
        if (!win_open_file(filename, sizeof filename))
            exit(0);
#else
        usage(argv[0]);
#endif
    }

    title = strrchr(filename, '/');
    if (!title)
        title = strrchr(filename, '\\');
    if (title)
        ++title;
    else
        title = filename;

    memset(&ui, 0, sizeof ui);

    search_input.p = search_input.text;
    search_input.q = search_input.p;
    search_input.end = search_input.p;

    glfwSetErrorCallback(on_error);

    if (!glfwInit()) {
        fprintf(stderr, "cannot initialize glfw\n");
        exit(1);
    }

    video_mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
    screen_w = video_mode->width;
    screen_h = video_mode->height;

    window = glfwCreateWindow(DEFAULT_WINDOW_W, DEFAULT_WINDOW_H, filename, NULL, NULL);
    if (!window) {
        fprintf(stderr, "cannot create glfw window\n");
        exit(1);
    }

    glfwMakeContextCurrent(window);

    ctx = fz_new_context(NULL, NULL, 0);
    fz_register_document_handlers(ctx);

    if (layout_css)
    {
        fz_buffer *buf = fz_read_file(ctx, layout_css);
        fz_set_user_css(ctx, fz_string_from_buffer(ctx, buf));
        fz_drop_buffer(ctx, buf);
    }

    fz_set_use_document_css(ctx, layout_use_doc_css);

    has_ARB_texture_non_power_of_two = glfwExtensionSupported("GL_ARB_texture_non_power_of_two");
    if (!has_ARB_texture_non_power_of_two)
        fz_warn(ctx, "OpenGL implementation does not support non-power of two texture sizes");

    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size);

    ui.fontsize = DEFAULT_UI_FONTSIZE;
    ui.baseline = DEFAULT_UI_BASELINE;
    ui.lineheight = DEFAULT_UI_LINEHEIGHT;

    ui_init_fonts(ctx, ui.fontsize);

    reload();

    shrinkwrap();

    glfwSetFramebufferSizeCallback(window, on_reshape);
    glfwSetCursorPosCallback(window, on_mouse_motion);
    glfwSetMouseButtonCallback(window, on_mouse_button);
    glfwSetScrollCallback(window, on_scroll);
    glfwSetCharModsCallback(window, on_char);
    glfwSetKeyCallback(window, on_key);
    glfwSetWindowRefreshCallback(window, on_display);

    glfwGetFramebufferSize(window, &window_w, &window_h);

    ui_needs_update = 1;

    while (!glfwWindowShouldClose(window))
    {
        glfwWaitEvents();
        if (ui_needs_update)
            run_main_loop();
    }

    ui_finish_fonts(ctx);

    fz_drop_link(ctx, links);
    fz_drop_page(ctx, page);
    fz_drop_outline(ctx, outline);
    fz_drop_document(ctx, doc);
    fz_drop_context(ctx);

    glfwTerminate();

    return 0;
}
Exemplo n.º 27
0
static void
testBufferStorage(void)
{

    if (!GLAD_GL_VERSION_4_4 &&
        !glfwExtensionSupported("GL_ARB_buffer_storage")) {
        fprintf(stderr, "error: GL_ARB_buffer_storage not supported\n");
        glfwTerminate();
        exit(EXIT_SKIP);
    }

    GLbitfield map_trace_explicit_bit = 0;
    if (glfwExtensionSupported("GL_VMWX_map_buffer_debug")) {
        glNotifyMappedBufferRangeVMWX = (PFNGLNOTIFYMAPPEDBUFFERRANGEVMWXPROC)glfwGetProcAddress("glNotifyMappedBufferRangeVMWX");
        assert(glNotifyMappedBufferRangeVMWX);
        map_trace_explicit_bit = GL_MAP_NOTIFY_EXPLICIT_BIT_VMWX;
    }

    GLuint buffer = 0;
    glGenBuffers(1, &buffer);

    glBindBuffer(target, buffer);

    GLsizeiptr size = 1000;

    void *data = malloc(size);
    memset(data, 0, size);

    while ((glGetError() != GL_NO_ERROR))
        ;
    
    glBufferStorage(target, size, data,
                    GL_MAP_WRITE_BIT |
                    GL_MAP_PERSISTENT_BIT |
                    GL_MAP_COHERENT_BIT |
                    map_trace_explicit_bit);

    free(data);

    GLenum error = glGetError();
    switch (error) {
    case GL_NO_ERROR:
        break;
    case GL_OUT_OF_MEMORY:
        exit(EXIT_SKIP);
    default:
        exit(EXIT_FAILURE);
    }

    GLubyte *map;

    // straightforward mapping
    map = (GLubyte *)glMapBufferRange(target, 100, 100, GL_MAP_WRITE_BIT);
    memset(map, 1, 100);
    glUnmapBuffer(target);

    // persistent mapping w/ explicit flush
    map = (GLubyte *)glMapBufferRange(target, 200, 300, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_FLUSH_EXPLICIT_BIT);
    memset(map + 20, 2, 30);
    glFlushMappedBufferRange(target, 20, 30);
    memset(map + 50, 3, 50);
    glFlushMappedBufferRange(target, 50, 50);
    glUnmapBuffer(target);

    // persistent & coherent mapping
    map = (GLubyte *)glMapBufferRange(target, 500, 100, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT | map_trace_explicit_bit);
    memset(map + 20, 4, 30);
    glNotifyMappedBufferRangeVMWX(map + 20, 30);
    memset(map + 50, 5, 50);
    glNotifyMappedBufferRangeVMWX(map + 50, 50);
    glUnmapBuffer(target);

    glBindBuffer(target, 0);

    glDeleteBuffers(1, &buffer);
}
Exemplo n.º 28
0
void InitWindow()
{
    const int width  = GetConfigInt("window.width",  640);
    const int height = GetConfigInt("window.height", 480);
    const char* title = GetConfigString("window.title", "Konstrukt");

    const bool debug = GetConfigBool("opengl.debug", false);
    const bool vsync = GetConfigBool("opengl.vsync", true);

    LogInfo("Compiled with GLFW %d.%d.%d",
             GLFW_VERSION_MAJOR,
             GLFW_VERSION_MINOR,
             GLFW_VERSION_REVISION);
    LogInfo("Using GLFW %s", glfwGetVersionString());

    assert(g_Window == NULL);
    glfwSetErrorCallback(OnGLFWError);
    if(!glfwInit())
        FatalError("GLFW init failed.");

    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_DEPTH_BITS, GetConfigInt("opengl.depth-bits", 24));
    glfwWindowHint(GLFW_STENCIL_BITS, 0);
    glfwWindowHint(GLFW_SAMPLES, GetConfigInt("opengl.samples", 0));
    glfwWindowHint(GLFW_SRGB_CAPABLE, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, debug ? GL_TRUE : GL_FALSE);

    g_Window = glfwCreateWindow(width, height, title, NULL, NULL);
    if(!g_Window)
        FatalError("Window creation failed.");

    glfwGetWindowSize(g_Window, &g_WindowWidth, &g_WindowHeight);
    glfwGetFramebufferSize(g_Window, &g_FramebufferWidth, &g_FramebufferHeight);

    glfwMakeContextCurrent(g_Window);

    if(!flextInit(g_Window))
        FatalError("Failed to load OpenGL extensions.");

    LogInfo("Using OpenGL %s\n"
            "Vendor: %s\n"
            "Renderer: %s\n"
            "GLSL: %s",
            glGetString(GL_VERSION),
            glGetString(GL_VENDOR),
            glGetString(GL_RENDERER),
            glGetString(GL_SHADING_LANGUAGE_VERSION));

    if(vsync)
    {
        if(glfwExtensionSupported("GLX_EXT_swap_control_tear") ||
           glfwExtensionSupported("WGL_EXT_swap_control_tear"))
            glfwSwapInterval(-1); // enable vsync (allow the driver to swap even if a frame arrives a little bit late)
        else
            glfwSwapInterval(1); // enable vsync
    }
    else
    {
        glfwSwapInterval(0); // disable vsync
    }

    glfwSetInputMode(g_Window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
    glfwSetInputMode(g_Window, GLFW_STICKY_KEYS, GL_FALSE);
    glfwSetInputMode(g_Window, GLFW_STICKY_MOUSE_BUTTONS, GL_FALSE);

    if(debug)
    {
        if(!FLEXT_ARB_debug_output)
            FatalError("Debug output requested, but it's not supported!");

        glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
        glDebugMessageCallbackARB(OnDebugEvent, NULL);
        LogInfo("Debug output supported! You may receive debug messages from your OpenGL driver.");
    }

    glfwSetWindowSizeCallback(g_Window, OnWindowResize);
    glfwSetFramebufferSizeCallback(g_Window, OnFramebufferResize);
    glfwSetMouseButtonCallback(g_Window, OnMouseButtonAction);
    glfwSetScrollCallback(g_Window, OnMouseScroll);
    glfwSetCursorPosCallback(g_Window, OnCursorMove);
    glfwSetKeyCallback(g_Window, OnKeyAction);
}
Exemplo n.º 29
0
int main(int argc, char** argv)
{
    int ch, samples = 4;
    GLFWwindow* window;

    while ((ch = getopt(argc, argv, "hs:")) != -1)
    {
        switch (ch)
        {
            case 'h':
                usage();
                exit(EXIT_SUCCESS);
            case 's':
                samples = atoi(optarg);
                break;
            default:
                usage();
                exit(EXIT_FAILURE);
        }
    }

    glfwSetErrorCallback(error_callback);

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

    if (samples)
        printf("Requesting MSAA with %i samples\n", samples);
    else
        printf("Requesting that MSAA not be available\n");

    glfwWindowHint(GLFW_SAMPLES, samples);
    glfwWindowHint(GLFW_VISIBLE, GL_FALSE);

    window = glfwCreateWindow(800, 400, "Aliasing Detector", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwSetKeyCallback(window, key_callback);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);

    if (!glfwExtensionSupported("GL_ARB_multisample"))
    {
        printf("GL_ARB_multisample extension not supported\n");

        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwShowWindow(window);

    glGetIntegerv(GL_SAMPLES_ARB, &samples);
    if (samples)
        printf("Context reports MSAA is available with %i samples\n", samples);
    else
        printf("Context reports MSAA is unavailable\n");

    glMatrixMode(GL_PROJECTION);
    glOrtho(0.f, 1.f, 0.f, 0.5f, 0.f, 1.f);
    glMatrixMode(GL_MODELVIEW);

    while (!glfwWindowShouldClose(window))
    {
        GLfloat time = (GLfloat) glfwGetTime();

        glClear(GL_COLOR_BUFFER_BIT);

        glLoadIdentity();
        glTranslatef(0.25f, 0.25f, 0.f);
        glRotatef(time, 0.f, 0.f, 1.f);

        glDisable(GL_MULTISAMPLE_ARB);
        glRectf(-0.15f, -0.15f, 0.15f, 0.15f);

        glLoadIdentity();
        glTranslatef(0.75f, 0.25f, 0.f);
        glRotatef(time, 0.f, 0.f, 1.f);

        glEnable(GL_MULTISAMPLE_ARB);
        glRectf(-0.15f, -0.15f, 0.15f, 0.15f);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Exemplo n.º 30
0
int main( int argc, char **argv )
{
    int        i, frames, benchmark;
    double     t0, t;
    GLFWthread physics_thread = 0;

    // Use multithreading by default, but don't benchmark
    multithreading = 1;
    benchmark = 0;

    // Check command line arguments
    for( i = 1; i < argc; i ++ )
    {
        // Use benchmarking?
        if( strcmp( argv[i], "-b" ) == 0 )
        {
            benchmark = 1;
        }

        // Force multithreading off?
        else if( strcmp( argv[i], "-s" ) == 0 )
        {
            multithreading = 0;
        }

        // With a Finder launch on Mac OS X we get a bogus -psn_0_46268417
        // kind of argument (actual numbers vary). Ignore it.
        else if( strncmp( argv[i], "-psn_", 5) == 0 );

        // Usage
        else
        {
            if( strcmp( argv[i], "-?" ) != 0 )
            {
                printf( "Unknonwn option %s\n\n", argv[ i ] );
            }
            printf( "Usage: %s [options]\n", argv[ 0 ] );
            printf( "\n");
            printf( "Options:\n" );
            printf( " -b   Benchmark (run program for 60 s)\n" );
            printf( " -s   Run program as single thread (default is to use two threads)\n" );
            printf( " -?   Display this text\n" );
            printf( "\n");
            printf( "Program runtime controls:\n" );
            printf( " w    Toggle wireframe mode\n" );
            printf( " ESC  Exit program\n" );
            exit( 0 );
        }
    }

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

    // Open OpenGL fullscreen window
    if( !glfwOpenWindow( WIDTH, HEIGHT, 5,6,5,0, 16,0, GLFW_FULLSCREEN ) )
    {
        fprintf( stderr, "Failed to open GLFW window\n" );
        glfwTerminate();
        exit( EXIT_FAILURE );
    }

    // Set window title
    glfwSetWindowTitle( "Particle engine" );

    // Disable VSync (we want to get as high FPS as possible!)
    glfwSwapInterval( 0 );

    // Window resize callback function
    glfwSetWindowSizeCallback( Resize );

    // Set keyboard input callback function
    glfwSetKeyCallback( KeyFun );

    // Upload particle texture
    glGenTextures( 1, &particle_tex_id );
    glBindTexture( GL_TEXTURE_2D, particle_tex_id );
    glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexImage2D( GL_TEXTURE_2D, 0, GL_LUMINANCE, P_TEX_WIDTH, P_TEX_HEIGHT,
                  0, GL_LUMINANCE, GL_UNSIGNED_BYTE, particle_texture );

    // Upload floor texture
    glGenTextures( 1, &floor_tex_id );
    glBindTexture( GL_TEXTURE_2D, floor_tex_id );
    glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
    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_MAG_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexImage2D( GL_TEXTURE_2D, 0, GL_LUMINANCE, F_TEX_WIDTH, F_TEX_HEIGHT,
                  0, GL_LUMINANCE, GL_UNSIGNED_BYTE, floor_texture );

    // Check if we have GL_EXT_separate_specular_color, and if so use it
    if( glfwExtensionSupported( "GL_EXT_separate_specular_color" ) )
    {
        glLightModeli( GL_LIGHT_MODEL_COLOR_CONTROL_EXT,
                       GL_SEPARATE_SPECULAR_COLOR_EXT );
    }

    // Set filled polygon mode as default (not wireframe)
    glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
    wireframe = 0;

    // Clear particle system
    for( i = 0; i < MAX_PARTICLES; i ++ )
    {
        particles[ i ].active = 0;
    }
    min_age = 0.0f;

    // Set "running" flag
    running = 1;

    // Set initial times
    thread_sync.t  = 0.0;
    thread_sync.dt = 0.001f;

    // Init threading
    if( multithreading )
    {
        thread_sync.p_frame = 0;
        thread_sync.d_frame = 0;
        thread_sync.particles_lock = glfwCreateMutex();
        thread_sync.p_done = glfwCreateCond();
        thread_sync.d_done = glfwCreateCond();
        physics_thread = glfwCreateThread( PhysicsThreadFun, NULL );
    }

    // Main loop
    t0 = glfwGetTime();
    frames = 0;
    while( running )
    {
        // Get frame time
        t = glfwGetTime() - t0;

        // Draw...
        Draw( t );

        // Swap buffers
        glfwSwapBuffers();

        // Check if window was closed
        running = running && glfwGetWindowParam( GLFW_OPENED );

        // Increase frame count
        frames ++;

        // End of benchmark?
        if( benchmark && t >= 60.0 )
        {
            running = 0;
        }
    }
    t = glfwGetTime() - t0;

    // Wait for particle physics thread to die
    if( multithreading )
    {
        glfwWaitThread( physics_thread, GLFW_WAIT );
    }

    // Display profiling information
    printf( "%d frames in %.2f seconds = %.1f FPS", frames, t,
            (double)frames / t );
    printf( " (multithreading %s)\n", multithreading ? "on" : "off" );

    // Terminate OpenGL
    glfwTerminate();

    exit( EXIT_SUCCESS );
}