Beispiel #1
1
static int drm_egl_init(struct MPGLContext *ctx, int flags)
{
    struct priv *p = ctx->priv;
    p->kms = NULL;
    p->old_crtc = NULL;
    p->gbm.surface = NULL;
    p->gbm.device = NULL;
    p->active = false;
    p->waiting_for_flip = false;
    p->ev.version = DRM_EVENT_CONTEXT_VERSION;
    p->ev.page_flip_handler = page_flipped;

    p->vt_switcher_active = vt_switcher_init(&p->vt_switcher, ctx->vo->log);
    if (p->vt_switcher_active) {
        vt_switcher_acquire(&p->vt_switcher, acquire_vt, ctx);
        vt_switcher_release(&p->vt_switcher, release_vt, ctx);
    } else {
        MP_WARN(ctx->vo, "Failed to set up VT switcher. Terminal switching will be unavailable.\n");
    }

    MP_VERBOSE(ctx->vo, "Initializing KMS\n");
    p->kms = kms_create(ctx->vo->log);
    if (!p->kms) {
        MP_ERR(ctx->vo, "Failed to create KMS.\n");
        return -1;
    }

    // TODO: arguments should be configurable
    if (!kms_setup(p->kms, "/dev/dri/card0", -1, 0)) {
        MP_ERR(ctx->vo, "Failed to configure KMS.\n");
        return -1;
    }

    if (!init_gbm(ctx)) {
        MP_ERR(ctx->vo, "Failed to setup GBM.\n");
        return -1;
    }

    if (!init_egl(ctx, flags & VOFLAG_GLES)) {
        MP_ERR(ctx->vo, "Failed to setup EGL.\n");
        return -1;
    }

    if (!eglMakeCurrent(p->egl.display, p->egl.surface, p->egl.surface, p->egl.context)) {
        MP_ERR(ctx->vo, "Failed to make context current.\n");
        return -1;
    }

    const char *egl_exts = eglQueryString(p->egl.display, EGL_EXTENSIONS);
    void *(*gpa)(const GLubyte*) = (void *(*)(const GLubyte*))eglGetProcAddress;
    mpgl_load_functions(ctx->gl, gpa, egl_exts, ctx->vo->log);

    // required by gbm_surface_lock_front_buffer
    eglSwapBuffers(p->egl.display, p->egl.surface);

    MP_VERBOSE(ctx->vo, "Preparing framebuffer\n");
    p->gbm.bo = gbm_surface_lock_front_buffer(p->gbm.surface);
    if (!p->gbm.bo) {
        MP_ERR(ctx->vo, "Failed to lock GBM surface.\n");
        return -1;
    }
    update_framebuffer_from_bo(ctx, p->gbm.bo);
    if (!p->fb.id) {
        MP_ERR(ctx->vo, "Failed to create framebuffer.\n");
        return -1;
    }

    if (!crtc_setup(ctx)) {
        MP_ERR(
               ctx->vo,
               "Failed to set CRTC for connector %u: %s\n",
               p->kms->connector->connector_id,
               mp_strerror(errno));
        return -1;
    }

    return 0;
}
Beispiel #2
0
void Renderer::Init()
{
	// initialize OpenGL ES and EGL

	/*
	 * Here specify the attributes of the desired configuration.
	 * Below, we select an EGLConfig with at least 8 bits per color
	 * component compatible with on-screen windows
	 */
	const EGLint attribs[] =
	{
			EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
			EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
			EGL_BLUE_SIZE, 8,
			EGL_GREEN_SIZE, 8,
			EGL_RED_SIZE, 8,
			EGL_NONE
	};

	EGLint format;
	EGLint numConfigs;
	EGLConfig config;

	m_display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

	eglInitialize(m_display, NULL, NULL);

	/* Here, the application chooses the configuration it desires. In this
	 * sample, we have a very simplified selection process, where we pick
	 * the first EGLConfig that matches our criteria */
	eglChooseConfig(m_display, attribs, &config, 1, &numConfigs);

	/* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
	 * guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
	 * As soon as we picked a EGLConfig, we can safely reconfigure the
	 * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */
	eglGetConfigAttrib(m_display, config, EGL_NATIVE_VISUAL_ID, &format);

	ANativeWindow_setBuffersGeometry(m_pState->window, 0, 0, format);

	m_surface = eglCreateWindowSurface(m_display, config, m_pState->window, NULL);

	EGLint contextAttribs[] =
	{
			EGL_CONTEXT_CLIENT_VERSION, 2,
			EGL_NONE
	};
	m_context = eglCreateContext(m_display, config, NULL, contextAttribs);

	eglMakeCurrent(m_display, m_surface, m_surface, m_context);

	eglQuerySurface(m_display, m_surface, EGL_WIDTH, &m_width);
	eglQuerySurface(m_display, m_surface, EGL_HEIGHT, &m_height);

	for (TextureVectorIterator iter = m_textures.begin(); iter != m_textures.end(); ++iter)
	{
		Texture* pCurrent = *iter;
		pCurrent->Init();
	}

	for (ShaderVectorIterator iter = m_shaders.begin(); iter != m_shaders.end(); ++iter)
	{
		ShaderProgram* pCurrent = *iter;
		pCurrent->Link();
	}

	m_initialized = true;

	DLOG() << "initialized" << m_initialized;
}
Beispiel #3
0
bool EGLWindow::initializeGL(OSWindow *osWindow)
{
    PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(eglGetProcAddress("eglGetPlatformDisplayEXT"));
    if (!eglGetPlatformDisplayEXT)
    {
        return false;
    }

    std::vector<EGLint> displayAttributes;
    displayAttributes.push_back(EGL_PLATFORM_ANGLE_TYPE_ANGLE);
    displayAttributes.push_back(mPlatform.renderer);
    displayAttributes.push_back(EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE);
    displayAttributes.push_back(mPlatform.majorVersion);
    displayAttributes.push_back(EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE);
    displayAttributes.push_back(mPlatform.minorVersion);

    if (mPlatform.deviceType != EGL_DONT_CARE)
    {
        displayAttributes.push_back(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE);
        displayAttributes.push_back(mPlatform.deviceType);
    }
    displayAttributes.push_back(EGL_NONE);

    mDisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, osWindow->getNativeDisplay(), &displayAttributes[0]);
    if (mDisplay == EGL_NO_DISPLAY)
    {
        destroyGL();
        return false;
    }

    EGLint majorVersion, minorVersion;
    if (eglInitialize(mDisplay, &majorVersion, &minorVersion) == EGL_FALSE)
    {
        destroyGL();
        return false;
    }

    eglBindAPI(EGL_OPENGL_ES_API);
    if (eglGetError() != EGL_SUCCESS)
    {
        destroyGL();
        return false;
    }

    const EGLint configAttributes[] =
    {
        EGL_RED_SIZE,       (mRedBits >= 0)     ? mRedBits     : EGL_DONT_CARE,
        EGL_GREEN_SIZE,     (mGreenBits >= 0)   ? mGreenBits   : EGL_DONT_CARE,
        EGL_BLUE_SIZE,      (mBlueBits >= 0)    ? mBlueBits    : EGL_DONT_CARE,
        EGL_ALPHA_SIZE,     (mAlphaBits >= 0)   ? mAlphaBits   : EGL_DONT_CARE,
        EGL_DEPTH_SIZE,     (mDepthBits >= 0)   ? mDepthBits   : EGL_DONT_CARE,
        EGL_STENCIL_SIZE,   (mStencilBits >= 0) ? mStencilBits : EGL_DONT_CARE,
        EGL_SAMPLE_BUFFERS, mMultisample ? 1 : 0,
        EGL_NONE
    };

    EGLint configCount;
    if (!eglChooseConfig(mDisplay, configAttributes, &mConfig, 1, &configCount) || (configCount != 1))
    {
        destroyGL();
        return false;
    }

    eglGetConfigAttrib(mDisplay, mConfig, EGL_RED_SIZE, &mRedBits);
    eglGetConfigAttrib(mDisplay, mConfig, EGL_GREEN_SIZE, &mGreenBits);
    eglGetConfigAttrib(mDisplay, mConfig, EGL_BLUE_SIZE, &mBlueBits);
    eglGetConfigAttrib(mDisplay, mConfig, EGL_ALPHA_SIZE, &mAlphaBits);
    eglGetConfigAttrib(mDisplay, mConfig, EGL_DEPTH_SIZE, &mDepthBits);
    eglGetConfigAttrib(mDisplay, mConfig, EGL_STENCIL_SIZE, &mStencilBits);

    std::vector<EGLint> surfaceAttributes;
    if (strstr(eglQueryString(mDisplay, EGL_EXTENSIONS), "EGL_NV_post_sub_buffer") != nullptr)
    {
        surfaceAttributes.push_back(EGL_POST_SUB_BUFFER_SUPPORTED_NV);
        surfaceAttributes.push_back(EGL_TRUE);
    }

    surfaceAttributes.push_back(EGL_NONE);

    mSurface = eglCreateWindowSurface(mDisplay, mConfig, osWindow->getNativeWindow(), &surfaceAttributes[0]);
    if (eglGetError() != EGL_SUCCESS)
    {
        destroyGL();
        return false;
    }
    ASSERT(mSurface != EGL_NO_SURFACE);

    EGLint contextAttibutes[] =
    {
        EGL_CONTEXT_CLIENT_VERSION, mClientVersion,
        EGL_NONE
    };

    mContext = eglCreateContext(mDisplay, mConfig, NULL, contextAttibutes);
    if (eglGetError() != EGL_SUCCESS)
    {
        destroyGL();
        return false;
    }

    eglMakeCurrent(mDisplay, mSurface, mSurface, mContext);
    if (eglGetError() != EGL_SUCCESS)
    {
        destroyGL();
        return false;
    }

    if (mSwapInterval != -1)
    {
        eglSwapInterval(mDisplay, mSwapInterval);
    }

    return true;
}
Beispiel #4
0
void AppLocal::CreateWindowSurface()
{
	LOG( "AppLocal::CreateWindowSurface()" );

	const int displayPixelsWide = vrapi_GetSystemPropertyInt( &Java, VRAPI_SYS_PROP_DISPLAY_PIXELS_WIDE );
	const int displayPixelsHigh = vrapi_GetSystemPropertyInt( &Java, VRAPI_SYS_PROP_DISPLAY_PIXELS_HIGH );

	VrSettings.ShowLoadingIcon = true;
	VrSettings.RenderMonoMode = false;
	VrSettings.UseSrgbFramebuffer = false;
	VrSettings.UseProtectedFramebuffer = false;
	VrSettings.FramebufferPixelsWide = displayPixelsWide;
	VrSettings.FramebufferPixelsHigh = displayPixelsHigh;

	VrSettings.EyeBufferParms.resolutionWidth = vrapi_GetSystemPropertyInt( &Java, VRAPI_SYS_PROP_SUGGESTED_EYE_TEXTURE_WIDTH );
	VrSettings.EyeBufferParms.resolutionHeight = vrapi_GetSystemPropertyInt( &Java, VRAPI_SYS_PROP_SUGGESTED_EYE_TEXTURE_HEIGHT );
	VrSettings.EyeBufferParms.multisamples = vrapi_GetSystemPropertyInt( &Java, VRAPI_SYS_PROP_MAX_FULLSPEED_FRAMEBUFFER_SAMPLES );
	VrSettings.EyeBufferParms.colorFormat = COLOR_8888;
	VrSettings.EyeBufferParms.depthFormat = DEPTH_24;

	// Allow the app to override any settings.
	appInterface->Configure( VrSettings );

	// Make sure the app didn't mess up the Java pointers.
	VrSettings.ModeParms.Java = Java;

	// Update the levels.
	FrameParms.PerformanceParms.CpuLevel = VrSettings.PerformanceParms.CpuLevel;
	FrameParms.PerformanceParms.GpuLevel = VrSettings.PerformanceParms.GpuLevel;

	// Optionally force the window to a different resolution, which
	// will be automatically scaled up by the HWComposer.
	if ( VrSettings.FramebufferPixelsWide != displayPixelsWide ||
			VrSettings.FramebufferPixelsHigh != displayPixelsHigh )
	{
		ANativeWindow_setBuffersGeometry( nativeWindow,
			VrSettings.FramebufferPixelsWide,
			VrSettings.FramebufferPixelsHigh, 0 );
	}

	EGLint attribs[16];
	int numAttribs = 0;

	// Set the colorspace on the window
	if ( VrSettings.UseSrgbFramebuffer )
	{
		attribs[numAttribs++] = EGL_GL_COLORSPACE_KHR;
		attribs[numAttribs++] = EGL_GL_COLORSPACE_SRGB_KHR;
	}
	// Ask for TrustZone rendering support
	if ( VrSettings.UseProtectedFramebuffer )
	{
		attribs[numAttribs++] = EGL_PROTECTED_CONTENT_EXT;
		attribs[numAttribs++] = EGL_TRUE;
	}
	attribs[numAttribs++] = EGL_NONE;

	// Android doesn't let the non-standard extensions show up in the
	// extension string, so we need to try it blind.
	windowSurface = eglCreateWindowSurface( glSetup.display, glSetup.config, nativeWindow, attribs );

	if ( windowSurface == EGL_NO_SURFACE )
	{
		const EGLint attribs2[] =
		{
			EGL_NONE
		};
		windowSurface = eglCreateWindowSurface( glSetup.display, glSetup.config, nativeWindow, attribs2 );
		if ( windowSurface == EGL_NO_SURFACE )
		{
			FAIL( "eglCreateWindowSurface failed: %s", GL_GetErrorString() );
		}
		FramebufferIsSrgb = false;
		FramebufferIsProtected = false;
	}
	else
	{
		FramebufferIsSrgb = VrSettings.UseSrgbFramebuffer;
		FramebufferIsProtected = VrSettings.UseProtectedFramebuffer;
	}
	LOG( "nativeWindow %p gives surface %p", nativeWindow, windowSurface );
	LOG( "FramebufferIsSrgb: %s", FramebufferIsSrgb ? "true" : "false" );
	LOG( "FramebufferIsProtected: %s", FramebufferIsProtected ? "true" : "false" );

	if ( eglMakeCurrent( glSetup.display, windowSurface, windowSurface, glSetup.context ) == EGL_FALSE )
	{
		FAIL( "eglMakeCurrent failed: %s", GL_GetErrorString() );
	}

	CreatedSurface = true;
}
Beispiel #5
0
static int
pandora_init(int gles_version)
{
    int i, j;

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK) < 0) {
        return 0;
    }

    for (i = SDLK_0, j = AKEYCODE_0; i <= SDLK_9; i++, j++) {
        keymap[i] = j;
    }

    for (i = SDLK_a, j = AKEYCODE_A; i <= SDLK_z; i++, j++) {
        keymap[i] = j;
    }

    EGLint egl_config[] =
    {
        EGL_BUFFER_SIZE, 16,
        EGL_RED_SIZE, 5,
        EGL_GREEN_SIZE, 6,
        EGL_BLUE_SIZE, 5,
        EGL_ALPHA_SIZE, 0,
        EGL_DEPTH_SIZE, 24,
        EGL_STENCIL_SIZE, EGL_DONT_CARE,
        EGL_CONFIG_CAVEAT, EGL_NONE,
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
        EGL_RENDERABLE_TYPE, gles_version == 2 ? EGL_OPENGL_ES2_BIT : EGL_OPENGL_ES_BIT,
        EGL_NONE
    };


    GLES_Data* data = (GLES_Data*)malloc(sizeof(GLES_Data));
    memset(data,0,sizeof(GLES_Data));

    data->screen = SDL_SetVideoMode(0,0,0,SDL_FULLSCREEN);
    CHK_FREE_RET(data->screen==NULL,data,0);

    SDL_SysWMinfo  sysWmInfo;
    SDL_VERSION(&sysWmInfo.version);
    SDL_GetWMInfo(&sysWmInfo);

    data->eglDisplay = eglGetDisplay(0); // (EGLNativeDisplayType)sysWmInfo.info.x11.display);
    CHK_FREE_RET(data->eglDisplay==EGL_NO_DISPLAY,data,0);
    CHK_FREE_RET(GLES_TestError("eglGetDisplay"),data,0);

    EGLBoolean r = eglInitialize(data->eglDisplay,0,0);
    CHK_FREE_RET(!r,data,0);
    CHK_FREE_RET(GLES_TestError("eglInitialize"),data,0);

    int iConfigs;
    r = eglChooseConfig(data->eglDisplay, egl_config, &data->eglConfig, 1, &iConfigs);
    CHK_FREE_RET(!r||iConfigs!=1,data,0);
    CHK_FREE_RET(GLES_TestError("eglChooseConfig"),data,0);

    data->eglSurface = eglCreateWindowSurface(data->eglDisplay, data->eglConfig, NULL, NULL); //(NativeWindowType)sysWmInfo.info.x11.window, NULL);
    CHK_FREE_RET(data->eglSurface==EGL_NO_SURFACE,data,0);
    CHK_FREE_RET(GLES_TestError("eglCreateWindowSurface"),data,0);

	EGLint contextAttribs[] =
	{
        EGL_CONTEXT_CLIENT_VERSION, gles_version,
        EGL_NONE
	};

    data->eglContext = eglCreateContext(data->eglDisplay,data->eglConfig,NULL,contextAttribs);
    CHK_FREE_RET(data->eglContext==EGL_NO_CONTEXT,data,0);
    CHK_FREE_RET(GLES_TestError("eglCreateContext"),data,0);

    eglMakeCurrent(data->eglDisplay,data->eglSurface,data->eglSurface,data->eglContext);
    GLES_TestError("eglMakeCurrent");

    data->fbdev = open(FRAMEBUFFERDEVICE,O_RDONLY);

    G_Data = data;

    SDL_ShowCursor(0);

    // XXX: Does Pandora expose the accelerometer via SDL?
    apkenv_accelerometer_register(sdl_accelerometer);
    apkenv_audio_register(sdl_audio);
    apkenv_mixer_register(sdl_mixer);

    return 1;
}
int start() {
    EGLBoolean result;
    EGLConfig config;
    EGLint num_config;
    
    g->display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    assert(g->display != EGL_NO_DISPLAY);

    result = eglInitialize(g->display, NULL, NULL);
    assert(result != EGL_FALSE);

    static const EGLint config_kw[] = {
        EGL_RED_SIZE, 8,
        EGL_GREEN_SIZE, 8,
        EGL_BLUE_SIZE, 8,
        EGL_ALPHA_SIZE, 8,
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
        EGL_NONE
    };
    result = eglChooseConfig(g->display, config_kw, &config, 1, &num_config);
    assert(result != EGL_FALSE);

    g->context = eglCreateContext(g->display, config, EGL_NO_CONTEXT, NULL);
    assert(g->context != EGL_NO_CONTEXT);

    assert(get_fb_resolution(&g->width, &g->height) == 0);

    g->surface = create_fb_surface(g->display, config, g->width, g->height);
    assert(g->surface != EGL_NO_SURFACE);

    result = eglMakeCurrent(g->display, g->surface, g->surface, g->context);
    assert(result != EGL_FALSE);

    // init viewport
    float nearp = 1.0f;
    float farp = 500.0f;
    float hht;
    float hwd;
    glViewport(0, 0, g->width, g->height);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    hht = nearp * (float)tan(45.0 / 2.0 / 180.0 * M_PI);
    hwd = hht * (float)g->width / (float)g->height;
    glFrustumf(-hwd, hwd, -hht, hht, nearp, farp);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0.f, 0.f, -50.f);
   
    glEnableClientState( GL_VERTEX_ARRAY );
    glVertexPointer( 3, GL_BYTE, 0, quad );

    EGLint client[5];
    FILE* fd = fopen("global_image_handle.tmp", "r");
    fread(client, sizeof(EGLint), 5, fd);
    fclose(fd);
    
    glEnable(GL_TEXTURE_2D);

    g->clientbuf = create_texture_from_shared_pixmap(g->display, client);

    glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
}
Beispiel #7
0
void fgPlatformOpenWindow( SFG_Window* window, const char* title,
                           GLboolean positionUse, int x, int y,
                           GLboolean sizeUse, int w, int h,
                           GLboolean gameMode, GLboolean isSubWindow )
{
    /* Save the display mode if we are creating a menu window */
    if( window->IsMenu && ( ! fgStructure.MenuContext ) )
        fgState.DisplayMode = GLUT_DOUBLE | GLUT_RGB ;

    fghChooseConfig( &window->Window.pContext.egl.Config );

    if( ! window->Window.pContext.egl.Config )
    {
        /*
         * The "fghChooseConfig" returned a null meaning that the visual
         * context is not available.
         * Try a couple of variations to see if they will work.
         */
        if( fgState.DisplayMode & GLUT_MULTISAMPLE )
        {
            fgState.DisplayMode &= ~GLUT_MULTISAMPLE ;
            fghChooseConfig( &window->Window.pContext.egl.Config );
            fgState.DisplayMode |= GLUT_MULTISAMPLE;
        }
    }

    FREEGLUT_INTERNAL_ERROR_EXIT( window->Window.pContext.egl.Config != NULL,
                                  "EGL configuration with necessary capabilities "
                                  "not found", "fgOpenWindow" );

    if( ! positionUse )
        x = y = -1; /* default window position */
    if( ! sizeUse )
        w = h = 300; /* default window size */

    /*  Create the cursor  */
   window->Window.pContext.cursor = wl_cursor_theme_get_cursor(
                                      fgDisplay.pDisplay.cursor_theme,
                                      "left_ptr" ); 
   window->Window.pContext.cursor_surface = wl_compositor_create_surface(
                                              fgDisplay.pDisplay.compositor );

    /*  Create the main surface  */
    window->Window.pContext.surface = wl_compositor_create_surface(
                                        fgDisplay.pDisplay.compositor );

    /*  Create the shell surface with respects to the parent/child tree  */
    window->Window.pContext.shsurface = wl_shell_get_shell_surface(
                                          fgDisplay.pDisplay.shell,
                                           window->Window.pContext.surface );
    wl_shell_surface_add_listener( window->Window.pContext.shsurface,
                                   &fghShSurfaceListener, window );

    if( title)
      wl_shell_surface_set_title( window->Window.pContext.shsurface, title );

    if( gameMode )
    {
        window->State.IsFullscreen = GL_TRUE;
        wl_shell_surface_set_fullscreen( window->Window.pContext.shsurface,
                                         WL_SHELL_SURFACE_FULLSCREEN_METHOD_DEFAULT,
                                         0, NULL );
    }
    else if( !isSubWindow && !window->IsMenu )
    {
        wl_shell_surface_set_toplevel( window->Window.pContext.shsurface );
    }
    else
    {
        wl_shell_surface_set_transient( window->Window.pContext.shsurface,
                                        window->Parent->Window.pContext.surface,
                                        x, y, 0 );
    }

    /*  Create the Wl_EGL_Window  */
    window->Window.Context = fghCreateNewContext( window );
    window->Window.pContext.egl_window = wl_egl_window_create( 
                                           window->Window.pContext.surface,
                                           w, h);
    window->Window.pContext.egl.Surface = eglCreateWindowSurface( 
                              fgDisplay.pDisplay.egl.Display,
                              window->Window.pContext.egl.Config,
                              (EGLNativeWindowType)window->Window.pContext.egl_window,
                              NULL );
    eglMakeCurrent( fgDisplay.pDisplay.egl.Display, window->Window.pContext.egl.Surface,
                    window->Window.pContext.egl.Surface, window->Window.Context );

   window->Window.pContext.pointer_button_pressed = GL_FALSE;
}
Beispiel #8
0
static struct gears *
gears_create(struct display *display)
{
	const int width = 450, height = 500;
	struct gears *gears;
	int i;

	gears = malloc(sizeof *gears);
	memset(gears, 0, sizeof *gears);
	gears->d = display;
	gears->window = window_create(display);
	gears->widget = frame_create(gears->window, gears);
	window_set_title(gears->window, "Wayland Gears");

	gears->display = display_get_egl_display(gears->d);
	if (gears->display == NULL)
		die("failed to create egl display\n");

	eglBindAPI(EGL_OPENGL_API);

	gears->config = display_get_argb_egl_config(gears->d);

	gears->context = eglCreateContext(gears->display, gears->config,
					  EGL_NO_CONTEXT, NULL);
	if (gears->context == NULL)
		die("failed to create context\n");

	if (!eglMakeCurrent(gears->display, NULL, NULL, gears->context))
		die("failed to make context current\n");

	for (i = 0; i < 3; i++) {
		gears->gear_list[i] = glGenLists(1);
		glNewList(gears->gear_list[i], GL_COMPILE);
		make_gear(&gear_templates[i]);
		glEndList();
	}

	glEnable(GL_NORMALIZE);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glFrustum(-1.0, 1.0, -1.0, 1.0, 5.0, 200.0);
	glMatrixMode(GL_MODELVIEW);

	glLightfv(GL_LIGHT0, GL_POSITION, light_pos);
	glEnable(GL_CULL_FACE);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	glEnable(GL_DEPTH_TEST);
	glClearColor(0, 0, 0, 0.92);

	window_set_user_data(gears->window, gears);
	widget_set_resize_handler(gears->widget, resize_handler);
	widget_set_redraw_handler(gears->widget, redraw_handler);
	window_set_keyboard_focus_handler(gears->window,
					  keyboard_focus_handler);

	window_schedule_resize(gears->window, width, height);

	return gears;
}
int
main(int argc, char *argv[])
{
  const int winWidth = 800, winHeight = 600;
  Display *x_dpy;
  Window win;
  EGLSurface egl_surf;
  EGLContext egl_ctx;
  EGLDisplay egl_dpy;
  char *dpyName = NULL;
  GLboolean printInfo = GL_FALSE;
  EGLint egl_major, egl_minor;
  const char *s;


  if (!InitTest(argc, argv)) {
    return -1;
  }

  x_dpy = XOpenDisplay(dpyName);
  if (!x_dpy) {
    printf("Error: couldn't open display %s\n",
           dpyName ? dpyName : getenv("DISPLAY"));
    return -1;
  }

  egl_dpy = eglGetDisplay(x_dpy);
  if (!egl_dpy) {
    printf("Error: eglGetDisplay() failed\n");
    return -1;
  }

  if (!eglInitialize(egl_dpy, &egl_major, &egl_minor)) {
    printf("Error: eglInitialize() failed\n");
    return -1;
  }

  s = eglQueryString(egl_dpy, EGL_VERSION);
  printf("EGL_VERSION = %s\n", s);

  s = eglQueryString(egl_dpy, EGL_VENDOR);
  printf("EGL_VENDOR = %s\n", s);

  s = eglQueryString(egl_dpy, EGL_EXTENSIONS);
  printf("EGL_EXTENSIONS = %s\n", s);

  s = eglQueryString(egl_dpy, EGL_CLIENT_APIS);
  printf("EGL_CLIENT_APIS = %s\n", s);

  make_x_window(x_dpy, egl_dpy,
               "OpenGL ES 2.x tri", 0, 0, winWidth, winHeight,
               &win, &egl_ctx, &egl_surf);

  XMapWindow(x_dpy, win);
  if (!eglMakeCurrent(egl_dpy, egl_surf, egl_surf, egl_ctx)) {
    printf("Error: eglMakeCurrent() failed\n");
    return -1;
  }

  if (printInfo) {
    printf("GL_RENDERER   = %s\n", (char *) glGetString(GL_RENDERER));
    printf("GL_VERSION    = %s\n", (char *) glGetString(GL_VERSION));
    printf("GL_VENDOR     = %s\n", (char *) glGetString(GL_VENDOR));
    printf("GL_EXTENSIONS = %s\n", (char *) glGetString(GL_EXTENSIONS));
  }


  InitRendering();
  LoadDefaultData();

  // render once
  testHelper->app()->resizeView(winWidth, winHeight);
  testHelper->app()->resetView();
  testHelper->app()->render();
  eglSwapBuffers(egl_dpy, egl_surf);

  // begin the event loop if not in testing mode
  bool testPassed = true;
  if (!testHelper->isTesting()) {
    event_loop(x_dpy, win, egl_dpy, egl_surf);
  }
  else {
    testPassed = DoTesting();
  }

  FinalizeTest();

  eglDestroyContext(egl_dpy, egl_ctx);
  eglDestroySurface(egl_dpy, egl_surf);
  eglTerminate(egl_dpy);


  XDestroyWindow(x_dpy, win);
  XCloseDisplay(x_dpy);

  return testPassed ? 0 : 1;
}
Beispiel #10
0
static bool gfx_ctx_vc_image_buffer_init(void *data,
      const video_info_t *video)
{
   EGLBoolean result;
   EGLint pbufsurface_list[] =
   {
      EGL_WIDTH, g_egl_res,
      EGL_HEIGHT, g_egl_res,
      EGL_NONE
   };

   /* Don't bother, we just use VGImages for our EGLImage anyway. */
   if (g_api == GFX_CTX_OPENVG_API)
      return false;

   peglCreateImageKHR = (PFNEGLCREATEIMAGEKHRPROC)
      gfx_ctx_vc_get_proc_address("eglCreateImageKHR");
   peglDestroyImageKHR = (PFNEGLDESTROYIMAGEKHRPROC)
      gfx_ctx_vc_get_proc_address("eglDestroyImageKHR");

   if (!peglCreateImageKHR || !peglDestroyImageKHR 
         || !gfx_ctx_vc_egl_query_extension("KHR_image"))
      return false;

   g_egl_res = video->input_scale * RARCH_SCALE_BASE;

   eglBindAPI(EGL_OPENVG_API);
   g_pbuff_surf = eglCreatePbufferSurface(g_egl_dpy, g_egl_config, pbufsurface_list);
   if (g_pbuff_surf == EGL_NO_SURFACE)
   {
      RARCH_ERR("[VideoCore:EGLImage] failed to create PbufferSurface\n");
      goto fail;
   }

   g_eglimage_ctx = eglCreateContext(g_egl_dpy, g_egl_config, NULL, NULL);
   if (g_eglimage_ctx == EGL_NO_CONTEXT)
   {
      RARCH_ERR("[VideoCore:EGLImage] failed to create context\n");
      goto fail;
   }

   /* Test to make sure we can switch context. */
   result = eglMakeCurrent(g_egl_dpy, g_pbuff_surf, g_pbuff_surf, g_eglimage_ctx);
   if (result == EGL_FALSE)
   {
      RARCH_ERR("[VideoCore:EGLImage] failed to make context current\n");
      goto fail;
   }

   gfx_ctx_vc_bind_api(data, g_api, 0, 0);
   eglMakeCurrent(g_egl_dpy, g_egl_surf, g_egl_surf, g_egl_ctx);

   g_smooth = video->smooth;
   return true;

fail:
   if (g_pbuff_surf != EGL_NO_SURFACE)
   {
      eglDestroySurface(g_egl_dpy, g_pbuff_surf);
      g_pbuff_surf = EGL_NO_SURFACE;
   }

   if (g_eglimage_ctx != EGL_NO_CONTEXT)
   {
      eglDestroyContext(g_egl_dpy, g_eglimage_ctx);
      g_pbuff_surf = EGL_NO_CONTEXT;
   }

   gfx_ctx_vc_bind_api(data, g_api, 0, 0);
   eglMakeCurrent(g_egl_dpy, g_egl_surf, g_egl_surf, g_egl_ctx);

   return false;
}
Beispiel #11
0
static void gfx_ctx_vc_destroy(void *data)
{
   (void)data;
   unsigned i;

   if (g_egl_dpy)
   {
      for (i = 0; i < MAX_EGLIMAGE_TEXTURES; i++)
      {
         if (eglBuffer[i] && peglDestroyImageKHR)
         {
            eglBindAPI(EGL_OPENVG_API);
            eglMakeCurrent(g_egl_dpy,
                  g_pbuff_surf, g_pbuff_surf, g_eglimage_ctx);
            peglDestroyImageKHR(g_egl_dpy, eglBuffer[i]);
         }

         if (g_egl_vgimage[i])
         {
            eglBindAPI(EGL_OPENVG_API);
            eglMakeCurrent(g_egl_dpy,
                  g_pbuff_surf, g_pbuff_surf, g_eglimage_ctx);
            vgDestroyImage(g_egl_vgimage[i]);
         }
      }

      if (g_egl_ctx)
      {
         gfx_ctx_vc_bind_api(data, g_api, 0, 0);
         eglMakeCurrent(g_egl_dpy,
               EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
         eglDestroyContext(g_egl_dpy, g_egl_ctx);
      }

      if (g_egl_hw_ctx)
         eglDestroyContext(g_egl_dpy, g_egl_hw_ctx);

      if (g_eglimage_ctx)
      {
         eglBindAPI(EGL_OPENVG_API);
         eglMakeCurrent(g_egl_dpy,
               EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
         eglDestroyContext(g_egl_dpy, g_eglimage_ctx);
      }

      if (g_egl_surf)
      {
         gfx_ctx_vc_bind_api(data, g_api, 0, 0);
         eglDestroySurface(g_egl_dpy, g_egl_surf);
      }

      if (g_pbuff_surf)
      {
         eglBindAPI(EGL_OPENVG_API);
         eglDestroySurface(g_egl_dpy, g_pbuff_surf);
      }

      eglBindAPI(EGL_OPENVG_API);
      eglMakeCurrent(g_egl_dpy,
            EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
      gfx_ctx_vc_bind_api(data, g_api, 0, 0);
      eglMakeCurrent(g_egl_dpy,
            EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
      eglTerminate(g_egl_dpy);
   }

   g_egl_ctx      = NULL;
   g_egl_hw_ctx   = NULL;
   g_eglimage_ctx = NULL;
   g_egl_surf     = NULL;
   g_pbuff_surf   = NULL;
   g_egl_dpy      = NULL;
   g_egl_config   = 0;
   g_inited       = false;

   for (i = 0; i < MAX_EGLIMAGE_TEXTURES; i++)
   {
      eglBuffer[i]     = NULL;
      g_egl_vgimage[i] = 0;
   }
}
Beispiel #12
0
static bool gfx_ctx_vc_init(void *data)
{
   EGLint num_config;
   static EGL_DISPMANX_WINDOW_T nativewindow;

   DISPMANX_ELEMENT_HANDLE_T dispman_element;
   DISPMANX_DISPLAY_HANDLE_T dispman_display;
   DISPMANX_UPDATE_HANDLE_T dispman_update;
   DISPMANX_MODEINFO_T dispman_modeinfo;
   VC_RECT_T dst_rect;
   VC_RECT_T src_rect;

   static const EGLint attribute_list[] =
   {
      EGL_RED_SIZE, 8,
      EGL_GREEN_SIZE, 8,
      EGL_BLUE_SIZE, 8,
      EGL_ALPHA_SIZE, 8,
      EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
      EGL_NONE
   };

   static const EGLint context_attributes[] =
   {
      EGL_CONTEXT_CLIENT_VERSION, 2,
      EGL_NONE
   };
   settings_t *settings = config_get_ptr();

   RARCH_LOG("[VC/EGL]: Initializing...\n");
   if (g_inited)
   {
      RARCH_ERR("[VC/EGL]: Attempted to re-initialize driver.\n");
      return false;
   }

   bcm_host_init();

   /* Get an EGL display connection. */
   g_egl_dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
   if (!g_egl_dpy)
      goto error;

   /* Initialize the EGL display connection. */
   if (!eglInitialize(g_egl_dpy, NULL, NULL))
      goto error;

   /* Get an appropriate EGL frame buffer configuration. */
   if (!eglChooseConfig(g_egl_dpy, attribute_list, &g_egl_config, 1, &num_config))
      goto error;

   /* Create an EGL rendering context. */
   g_egl_ctx = eglCreateContext(
         g_egl_dpy, g_egl_config, EGL_NO_CONTEXT,
         (g_api == GFX_CTX_OPENGL_ES_API) ? context_attributes : NULL);
   if (!g_egl_ctx)
      goto error;

   if (g_use_hw_ctx)
   {
      g_egl_hw_ctx = eglCreateContext(g_egl_dpy, g_egl_config, g_egl_ctx,
            context_attributes);
      RARCH_LOG("[VC/EGL]: Created shared context: %p.\n", (void*)g_egl_hw_ctx);

      if (g_egl_hw_ctx == EGL_NO_CONTEXT)
         goto error;
   }

   /* Create an EGL window surface. */
   if (graphics_get_display_size(0 /* LCD */, &g_fb_width, &g_fb_height) < 0)
      goto error;

   dst_rect.x = 0;
   dst_rect.y = 0;
   dst_rect.width = g_fb_width;
   dst_rect.height = g_fb_height;

   src_rect.x = 0;
   src_rect.y = 0;

   /* Use dispmanx upscaling if fullscreen_x 
    * and fullscreen_y are set. */
   if (settings->video.fullscreen_x != 0 &&
      settings->video.fullscreen_y != 0)
   {
      /* Keep input and output aspect ratio equal.
       * There are other aspect ratio settings which can be used to stretch video output. */

      /* Calculate source and destination aspect ratios. */
      float srcAspect = (float)settings->video.fullscreen_x / (float)settings->video.fullscreen_y;
      float dstAspect = (float)g_fb_width / (float)g_fb_height;
      /* If source and destination aspect ratios are not equal correct source width. */
      if (srcAspect != dstAspect)
         src_rect.width = (unsigned)(settings->video.fullscreen_y * dstAspect) << 16;
      else
         src_rect.width = settings->video.fullscreen_x << 16;
      src_rect.height = settings->video.fullscreen_y << 16;
   }
   else
   {
      src_rect.width = g_fb_width << 16;
      src_rect.height = g_fb_height << 16;
   }

   dispman_display = vc_dispmanx_display_open(0 /* LCD */);
   vc_dispmanx_display_get_info(dispman_display, &dispman_modeinfo);
   dispman_update = vc_dispmanx_update_start(0);

   VC_DISPMANX_ALPHA_T alpha;
   alpha.flags = DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS;
   alpha.opacity = 255;
   alpha.mask = 0;

   dispman_element = vc_dispmanx_element_add(dispman_update, dispman_display,
      0 /*layer*/, &dst_rect, 0 /*src*/,
      &src_rect, DISPMANX_PROTECTION_NONE, &alpha, 0 /*clamp*/, DISPMANX_NO_ROTATE);

   nativewindow.element = dispman_element;

   /* Use dispmanx upscaling if fullscreen_x and fullscreen_y are set. */

   if (settings->video.fullscreen_x != 0 &&
      settings->video.fullscreen_y != 0)
   {
      /* Keep input and output aspect ratio equal.
       * There are other aspect ratio settings which 
       * can be used to stretch video output. */

      /* Calculate source and destination aspect ratios. */
      float srcAspect = (float)settings->video.fullscreen_x / (float)settings->video.fullscreen_y;
      float dstAspect = (float)g_fb_width / (float)g_fb_height;

      /* If source and destination aspect ratios are not equal correct source width. */
      if (srcAspect != dstAspect)
         nativewindow.width = (unsigned)(settings->video.fullscreen_y * dstAspect);
      else
         nativewindow.width = settings->video.fullscreen_x;
      nativewindow.height = settings->video.fullscreen_y;
   }
   else
   {
      nativewindow.width = g_fb_width;
      nativewindow.height = g_fb_height;
   }
   vc_dispmanx_update_submit_sync(dispman_update);

   g_egl_surf = eglCreateWindowSurface(g_egl_dpy, g_egl_config, &nativewindow, NULL);
   if (!g_egl_surf)
      goto error;

   /* Connect the context to the surface. */
   if (!eglMakeCurrent(g_egl_dpy, g_egl_surf, g_egl_surf, g_egl_ctx))
      goto error;

   return true;

error:
   gfx_ctx_vc_destroy(data);
   return false;
}
/**
 * Initialize an EGL context for the current display.
 */
static int engine_init_display(struct engine* engine,bool p_gl2) {
    // initialize OpenGL ES and EGL

    /*
     * Here specify the attributes of the desired configuration.
     * Below, we select an EGLConfig with at least 8 bits per color
     * component compatible with on-screen windows
     */
    const EGLint gl2_attribs[] = {
	  //  EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
	    EGL_BLUE_SIZE, 4,
	    EGL_GREEN_SIZE, 4,
	    EGL_RED_SIZE, 4,
	    EGL_ALPHA_SIZE, 0,
	    EGL_DEPTH_SIZE,     16,
	    EGL_STENCIL_SIZE,   EGL_DONT_CARE,
	    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
	    EGL_NONE
    };

    const EGLint gl1_attribs[] = {
	  //  EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
	    EGL_BLUE_SIZE, 4,
	    EGL_GREEN_SIZE, 4,
	    EGL_RED_SIZE, 4,
	    EGL_ALPHA_SIZE, 0,
	    EGL_DEPTH_SIZE,     16,
	    EGL_STENCIL_SIZE,   EGL_DONT_CARE,
	    EGL_NONE
    };

    const EGLint *attribs=p_gl2?gl2_attribs:gl1_attribs;


    EGLint w, h, dummy, format;
    EGLint numConfigs;
    EGLConfig config;
    EGLSurface surface;
    EGLContext context;

    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

    eglInitialize(display, 0, 0);


    /* Here, the application chooses the configuration it desires. In this
     * sample, we have a very simplified selection process, where we pick
     * the first EGLConfig that matches our criteria */

    eglChooseConfig(display, attribs, &config, 1, &numConfigs);

    LOGI("Num configs: %i\n",numConfigs);

    /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
     * guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
     * As soon as we picked a EGLConfig, we can safely reconfigure the
     * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */
    eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);

    ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format);
    //ANativeWindow_setFlags(engine->app->window, 0, 0, format|);

    surface = eglCreateWindowSurface(display, config, engine->app->window, NULL);

    const EGLint context_attribs[] = {
	    EGL_CONTEXT_CLIENT_VERSION,2,
	    EGL_NONE
    };
    context = eglCreateContext(display, config, EGL_NO_CONTEXT, p_gl2?context_attribs:NULL);

    if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
	LOGW("Unable to eglMakeCurrent");
	return -1;
    }

    eglQuerySurface(display, surface, EGL_WIDTH, &w);
    eglQuerySurface(display, surface, EGL_HEIGHT, &h);
    print_line("INIT VIDEO MODE: "+itos(w)+","+itos(h));

    //engine->os->set_egl_extensions(eglQueryString(display,EGL_EXTENSIONS));
    engine->os->init_video_mode(w,h);


    engine->display = display;
    engine->context = context;
    engine->surface = surface;
    engine->width = w;
    engine->height = h;
    engine->display_active=true;

    //engine->state.angle = 0;

    // Initialize GL state.
    //glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
    glEnable(GL_CULL_FACE);
  //  glShadeModel(GL_SMOOTH);
    glDisable(GL_DEPTH_TEST);
    LOGI("GL Version: %s - %s %s\n", glGetString(GL_VERSION),glGetString(GL_VENDOR), glGetString(GL_RENDERER));

    return 0;
}
Beispiel #14
0
// Description: Sets the display, OpenGL|ES context and screen stuff
void init_ogl(gl_t *state, void *launcher_state)
{
    bcm_host_init();

    // Initialize struct
    memset(state, 0, sizeof(gl_t));
    state->controller_1_fd = -1;
    state->controller_2_fd = -1;
    state->window_should_close = false;

    // Set a user pointer up
    state->user_pointer = launcher_state;

    int32_t success = 0;
    EGLBoolean result;
    EGLint num_config;

    static EGL_DISPMANX_WINDOW_T nativewindow;

    DISPMANX_ELEMENT_HANDLE_T dispman_element;
    DISPMANX_DISPLAY_HANDLE_T dispman_display;
    DISPMANX_UPDATE_HANDLE_T dispman_update;
    VC_RECT_T dst_rect;
    VC_RECT_T src_rect;

    static const EGLint attribute_list[] =
    {
       EGL_RED_SIZE, 8,
       EGL_GREEN_SIZE, 8,
       EGL_BLUE_SIZE, 8,
       EGL_ALPHA_SIZE, 8,
       EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
       EGL_NONE
    };
   
    static const EGLint context_attributes[] =
    {
       EGL_CONTEXT_CLIENT_VERSION, 2,
       EGL_NONE
    }; 

    EGLConfig config;

    // get an EGL display connection
    state->display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    assert(state->display!=EGL_NO_DISPLAY);
 
    // initialize the EGL display connection
    result = eglInitialize(state->display, NULL, NULL);
    assert(EGL_FALSE != result);

    // get an appropriate EGL frame buffer configuration
    result = eglChooseConfig(state->display, attribute_list, &config, 1, &num_config);
    assert(EGL_FALSE != result);

    // get an appropriate EGL frame buffer configuration
    result = eglBindAPI(EGL_OPENGL_ES_API);
    assert(EGL_FALSE != result);

    // create an EGL rendering context
    state->context = eglCreateContext(state->display, config, EGL_NO_CONTEXT, context_attributes);
    assert(state->context!=EGL_NO_CONTEXT);

    // create an EGL window surface
    success = graphics_get_display_size(0 /* LCD */, &state->screen_width, &state->screen_height);
    assert( success >= 0 );

    dst_rect.x = 0;
    dst_rect.y = 0;
    dst_rect.width = state->screen_width;
    dst_rect.height = state->screen_height;
      
    src_rect.x = 0;
    src_rect.y = 0;
    src_rect.width = state->screen_width << 16;
    src_rect.height = state->screen_height << 16;

    dispman_display = vc_dispmanx_display_open( 0 /* LCD */);
    dispman_update = vc_dispmanx_update_start( 0 );

    VC_DISPMANX_ALPHA_T alpha;
    alpha.flags = DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS;
    alpha.opacity = 255;
    alpha.mask = 0;         

    dispman_element = vc_dispmanx_element_add ( dispman_update, dispman_display,
      0/*layer*/, &dst_rect, 0/*src*/,
      &src_rect, DISPMANX_PROTECTION_NONE, &alpha, 0/*clamp*/, 0/*transform*/);
      
    nativewindow.element = dispman_element;
    nativewindow.width = state->screen_width;
    nativewindow.height = state->screen_height;
    vc_dispmanx_update_submit_sync( dispman_update );
      
    state->surface = eglCreateWindowSurface( state->display, config, &nativewindow, NULL );
    assert(state->surface != EGL_NO_SURFACE);

    // connect the context to the surface
    result = eglMakeCurrent(state->display, state->surface, state->surface, state->context);
    assert(EGL_FALSE != result);

    // Open input event
    state->controller_1_fd = open("/dev/input/event1",O_RDONLY|O_NONBLOCK);
    state->controller_2_fd = open("/dev/input/event2",O_RDONLY|O_NONBLOCK);
}
static bool setup_egl(NativeDisplayType nativeDisplay, NativeWindowType nativeWindow, EGLDisplay* peglDisplay, EGLSurface* peglSurface, EGLContext* peglContext)
{
	EGLDisplay eglDisplay = EGL_NO_DISPLAY;
	EGLSurface eglSurface = EGL_NO_SURFACE;
	EGLContext eglContext = EGL_NO_CONTEXT;
	EGLConfig  eglConfig  = 0;

	/*
	Step 1 - Get the default display.
		EGL uses the concept of a "display" which in most environments
		corresponds to a single physical screen. Since we usually want
		to draw to the main screen or only have a single screen to begin
		with, we let EGL pick the default display.
		Querying other displays is platform specific.
	*/
	eglDisplay = eglGetDisplay(nativeDisplay);

	/*
		Step 2 - Initialize EGL.
		EGL has to be initialized with the display obtained in the
		previous step. We cannot use other EGL functions except
		eglGetDisplay and eglGetError before eglInitialize has been
		called.
		If we're not interested in the EGL version number we can just
		pass NULL for the second and third parameters.
	*/
	EGLint iMajorVersion = 0,
	       iMinorVersion = 0;

	if (!eglInitialize(eglDisplay, &iMajorVersion, &iMinorVersion))
	{
		printf("Error: eglInitialize() failed.\n");
		return false;
	}

	/*
		Step 3 - Specify the required configuration attributes.
		An EGL "configuration" describes the pixel format and type of
		surfaces that can be used for drawing.
		For now we just want to use a 16 bit RGB surface that is a
		Window surface, i.e. it will be visible on screen. The list
		has to contain key/value pairs, terminated with EGL_NONE.
	 */
	EGLint configAttrs[] =
	{
		EGL_BUFFER_SIZE,       32,
	        EGL_DEPTH_SIZE,        24,
        	EGL_NONE
	};
	
	/*
		Step 4 - Find a config that matches all requirements.
		eglChooseConfig provides a list of all available configurations
		that meet or exceed the requirements given as the second
		argument. In most cases we just want the first config that meets
		all criteria, so we can limit the number of configs returned to 1.
	*/
	int iConfigs;
	if (!eglChooseConfig(eglDisplay, configAttrs, &eglConfig, 1, &iConfigs) || (iConfigs != 1))
	{
		int errcode = eglGetError();
		printf("Error: eglChooseConfig() failed. with ErrorCode : 0x%08X\n", errcode);
		eglTerminate(eglDisplay);
		return false;
	}

	/*
		Step 5 - Create a surface to draw to.
		Use the config picked in the previous step and the native window
		handle when available to create a window surface. A window surface
		is one that will be visible on screen inside the native display (or
		fullscreen if there is no windowing system).
		Pixmaps and pbuffers are surfaces which only exist in off-screen
		memory.
	*/
	eglSurface = eglCreateWindowSurface(eglDisplay, eglConfig, nativeWindow, NULL);
	if (!TestEGLError("eglCreateWindowSurface"))
	{
		eglTerminate(eglDisplay);
		return false;
	}

	/*
		Step 6 - Create a context.
		EGL has to create a context for OpenGL ES. Our OpenGL ES resources
		like textures will only be valid inside this context
		(or shared contexts)
	*/
	eglContext = eglCreateContext(eglDisplay, eglConfig, NULL, NULL);
	if (!TestEGLError("eglCreateContext"))
	{
		eglTerminate(eglDisplay);
		return false;
	}

	/*
		Step 7 - Bind the context to the current thread and use our
		window surface for drawing and reading.
		Contexts are bound to a thread. This means you don't have to
		worry about other threads and processes interfering with your
		OpenGL ES application.
		We need to specify a surface that will be the target of all
		subsequent drawing operations, and one that will be the source
		of read operations. They can be the same surface.
	*/
	eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext);
	if (!TestEGLError("eglMakeCurrent"))
	{
		eglTerminate(eglDisplay);
		return false;
	}

	(*peglDisplay) = eglDisplay;
	(*peglSurface) = eglSurface;
	(*peglContext) = eglContext;

	return true;
}
Beispiel #16
0
BOOL init( void )
{
  const SDL_VideoInfo *info = NULL;
  int depth;
  int flags;

  load_options();

  if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK ) < 0 )
  {
    fprintf( stderr, "SDL says: %s\n", SDL_GetError() );
    return FALSE;
  }

  joy = SDL_JoystickOpen( 0 );
  if( joy ) SDL_JoystickEventState( SDL_ENABLE );
  
//  printf( "%p\n", joy );

  needquit = TRUE;

  depth = 32;
  if( (info = SDL_GetVideoInfo()) )
    depth = info->vfmt->BitsPerPixel;

#ifdef __amigaos4__
  printf( "Detected MiniGL v%d.%d\n",
    MiniGLBase->lib_Version,
    MiniGLBase->lib_Revision );

  if( ( MiniGLBase->lib_Version < 2 ) ||
      ( ( MiniGLBase->lib_Version == 2 ) &&
        ( MiniGLBase->lib_Revision < 1 ) ) )
  {
    //screenbodge = TRUE;
    printf( "WARNING: The video screen won't work properly on the spaceship level\n" );
    printf( "with this version on MiniGL.\n" );
  }
#endif

#ifdef HAVE_GLES
flags = 0;
#else
flags = SDL_OPENGL;
#endif

#ifndef PANDORA
  if( fullscreen )
#endif
	flags |= SDL_FULLSCREEN;

#ifdef PANDORA
  ssrf = SDL_SetVideoMode( 800, 480, depth, flags );
#else
  ssrf = SDL_SetVideoMode( WINWIDTH, WINHEIGHT, depth, flags );
#endif
	
  if( ssrf == 0 )
  {
    fprintf( stderr, "SDL says: %s\n", SDL_GetError() );
    return FALSE;
  }

  SDL_ShowCursor( SDL_DISABLE );
#ifdef HAVE_GLES
// create EGL context
// *TODO* : real egl Checking for error
#define eglCheck()	 FALSE
	eglDisplay = eglGetDisplay((EGLNativeDisplayType) EGL_DEFAULT_DISPLAY);
	
	// Initialise EGL
	EGLint maj, min;
	if (!eglInitialize(eglDisplay, &maj, &min))
	{
		fprintf( stderr, "EGL Error: eglInitialize failed\n");
		return FALSE;
	}
	
	EGLint pi32ConfigAttribs[]  = { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT , EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, EGL_NONE };
	EGLint pi32ContextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 1 , EGL_NONE };

	int num_config;
	
	EGLConfig config;
	if (!eglChooseConfig(eglDisplay, pi32ConfigAttribs, &config, 1, &num_config) || (num_config != 1))
	{
		fprintf(stderr, "EGL Error: eglChooseConfig failed\n");
		return FALSE;
	}
	
	eglSurface = eglCreateWindowSurface(eglDisplay, config, NULL, NULL);
	
	if (eglCheck())
	return FALSE;
	
	eglBindAPI(EGL_OPENGL_ES_API);
	if (eglCheck())
	return FALSE;
	
	eglContext = eglCreateContext(eglDisplay, config, NULL, pi32ContextAttribs);
	
	if (eglCheck())
	return FALSE;

	eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext);
	
	if (eglCheck())
	return FALSE;
	
	EGLint w,h;
	eglQuerySurface(eglDisplay, eglSurface, EGL_WIDTH, &w);
	eglQuerySurface(eglDisplay, eglSurface, EGL_HEIGHT, &h);
	
	// now, setup viewport to adapt to the surface
	//*TODO* adjust if surface is smaller
	int dx = (w-WINWIDTH)/2;
	int dy = (h-WINHEIGHT)/2;
	glViewport(dx, dy, WINWIDTH, WINHEIGHT);
#endif
/*
#ifdef __amigaos4__
  if( screenbodge )
  {
    struct IntuitionBase *ibase = (struct IntuitionBase *)IntuitionBase;
    win = ibase->ActiveWindow;
    if( !win )
      screenbodge = FALSE;
  }
#endif
*/
  // initialize sdl mixer, open up the audio device
  if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 )
  {
    fprintf( stderr, "SDL_Mixer says: %s\n", Mix_GetError() );
  } else {
    audioavailable = TRUE;
  }

  loadsounds();

  if( !render_init() ) return FALSE;

  titlestate = 0;
  what_are_we_doing = WAWD_TITLES;

  return TRUE;
}
Beispiel #17
0
static void sample(TestPlatform* p, void* eglDisplay, void* nativeWinSurface, int maxFrameCount, int openglesVersion) {
    
    switch (openglesVersion) {
        case 1:
        {
            renderer.init = initRenderOpenGLES1;
            renderer.renderFrame = renderFrameOpenGLES1;
            renderer.destroy = destroyRenderOpenGLES1;
            renderer.renderableType = EGL_OPENGL_ES_BIT;
            renderer.clientVersion = 1;
            LOG(I, "Running with OpenGL ES 1.X")
            break;
        }
        case 2:
        {
            renderer.init = initRenderOpenGLES2;
            renderer.renderFrame = renderFrameOpenGLES2;
            renderer.destroy = destroyRenderOpenGLES2;
            renderer.renderableType = EGL_OPENGL_ES2_BIT;
            renderer.clientVersion = 2;
            LOG(I, "Running with OpenGL ES 2.X")
            break;
        }
        default:
            return;
            break;
    }
    
    setenv(p->ios_platform_env_key, p->ios_platform_env_value, 1);
    if ((display = eglGetDisplay(eglDisplay)) == EGL_NO_DISPLAY) {
        logEGLError( "eglGetDisplay", eglGetError());
        return;
    }
    if (!eglInitialize(display, 0, 0)) {
        logEGLError( "eglInitialize", eglGetError());
        return;
    }
    
    EGLint config_attribs[] = {
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
        EGL_BLUE_SIZE, 8,
        EGL_GREEN_SIZE, 8,
        EGL_RED_SIZE, 8,
        EGL_RENDERABLE_TYPE, renderer.renderableType,
        EGL_NONE
    };
    
    if (!eglChooseConfig(display, config_attribs, &config, 1, &numConfigs)) {
        logEGLError( "eglChooseConfig", eglGetError());
        return;
    }
    
    EGLint num_attrs = 0;
    getEGLConfigAttributeForEGLAPIVersion(1,
                                          4,
                                          NULL,
                                          &num_attrs);
    EGLint* attrs = (EGLint* ) malloc(num_attrs * sizeof(EGLint));
    getEGLConfigAttributeForEGLAPIVersion(1,
                                          4,
                                          attrs,
                                          &num_attrs);
    displayEGLConfig(display, config, attrs, num_attrs);
    
    init:
    if (!(surface = eglCreateWindowSurface(display, config, nativeWinSurface, NULL))) {
        logEGLError( "eglCreateWindowSurface", eglGetError());
        return;
    }
    
    if (!eglQuerySurface(display, surface, EGL_WIDTH, &width) ||
        !eglQuerySurface(display, surface, EGL_HEIGHT, &height)) {
        logEGLError( "eglQuerySurface", eglGetError());
        return;
    }

    EGLint context_attribs[] = {
        EGL_CONTEXT_CLIENT_VERSION, renderer.clientVersion /* 1 or 2 or 3 */,
        EGL_NONE};
    if (!(context = eglCreateContext(display, config, EGL_NO_CONTEXT, context_attribs))) {
        logEGLError( "eglCreateContext", eglGetError());
        return;
    }
    
    if (!eglMakeCurrent(display, surface, surface, context)) {
        logEGLError( "eglMakeCurrent", eglGetError());
        return;
    }
    
    if (!eglSwapInterval(display, 1)) {
        logEGLError("eglSwapInterval()", eglGetError());
        return;
    }

    EGLint error;
    if (!renderer.init()) {
        return;
    }
    
    int i = 0;
    TimeRecord_t s;
    TimeRecord_t e;
    while (i < maxFrameCount)
    {
        LOG(I, "FRAME ...")
        renderer.renderFrame();
        START_RECORD_DURATION(&s);
        if (!eglSwapBuffers(display, surface)) {
            error = eglGetError();
            logEGLError("eglSwapBuffers()", error);
            if (error != EGL_CONTEXT_LOST) {
                break;
            }
            if (!eglDestroySurface(display, surface)) {
                logEGLError( "eglDestroySurface", eglGetError());
                break;
            }
            surface = EGL_NO_SURFACE;
            
            if (!eglDestroyContext(display, context)) {
                logEGLError( "eglDestroyContext", eglGetError());
                break;
            };
            context = EGL_NO_CONTEXT;

            if (!eglMakeCurrent(display, surface, surface, context)) {
                logEGLError( "eglMakeCurrent", eglGetError());
                return;
            }
            
            goto init;
        }
        LOG(I, "FRAME DONE")
        END_RECORD_DURATION(&e);
        LOG_DURATION(&s, &e)
        i++;
    }
    
    renderer.destroy();
    
    if (!eglDestroySurface(display, surface)) {
        logEGLError( "eglDestroySurface", eglGetError());
        return;
    }
    surface = EGL_NO_SURFACE;
    
    if (!eglDestroyContext(display, context)) {
        logEGLError( "eglDestroyContext", eglGetError());
        return;
    };
    context = EGL_NO_CONTEXT;
    
    if (!eglMakeCurrent(display, surface, surface, context)) {
        logEGLError( "eglMakeCurrent", eglGetError());
        return;
    }

    if(!eglTerminate(display)) {
        logEGLError( "eglTerminate", eglGetError());
        return;
    }
    display = EGL_NO_DISPLAY;
    if(!eglReleaseThread()) {
        logEGLError( "eglReleaseThread", eglGetError());
        return;
    }
}
Beispiel #18
0
		~SwapChainGL()
		{
			eglMakeCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
			eglDestroyContext(m_display, m_context);
			eglDestroySurface(m_display, m_surface);
		}
Beispiel #19
0
static int      _egl_init       (s52engine *engine)
{
    g_print("s52egl:_egl_init(): starting ..\n");

    if ((NULL!=engine->eglDisplay) && (EGL_NO_DISPLAY!=engine->eglDisplay)) {
        g_print("_egl_init(): EGL is already up .. skipped!\n");
        return FALSE;
    }

// EGL Error code -
// #define EGL_SUCCESS             0x3000
// #define EGL_NOT_INITIALIZED     0x3001
// #define EGL_BAD_ACCESS          0x3002
// #define EGL_BAD_ALLOC           0x3003
// #define EGL_BAD_ATTRIBUTE       0x3004
// #define EGL_BAD_CONFIG          0x3005
// #define EGL_BAD_CONTEXT         0x3006
// #define EGL_BAD_CURRENT_SURFACE 0x3007
// #define EGL_BAD_DISPLAY         0x3008
// #define EGL_BAD_MATCH           0x3009
// #define EGL_BAD_NATIVE_PIXMAP   0x300A
// #define EGL_BAD_NATIVE_WINDOW   0x300B
// #define EGL_BAD_PARAMETER       0x300C
// #define EGL_BAD_SURFACE         0x300D
// #define EGL_CONTEXT_LOST        0x300E


    EGLNativeWindowType eglWindow = 0;
    EGLDisplay eglDisplay = EGL_NO_DISPLAY;
    EGLSurface eglSurface = EGL_NO_SURFACE;
    EGLContext eglContext = EGL_NO_CONTEXT;

    EGLBoolean ret = eglBindAPI(EGL_OPENGL_ES_API);
    if (EGL_TRUE != ret)
        g_print("eglBindAPI() failed. [0x%x]\n", eglGetError());

    eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    if (EGL_NO_DISPLAY == eglDisplay)
        g_print("eglGetDisplay() failed. [0x%x]\n", eglGetError());

    EGLint major = 2;
    EGLint minor = 0;
    if (EGL_FALSE == eglInitialize(eglDisplay, &major, &minor) || EGL_SUCCESS != eglGetError())
        g_print("eglInitialize() failed. [0x%x]\n", eglGetError());

    g_print("EGL Version   :%s\n", eglQueryString(eglDisplay, EGL_VERSION));
    g_print("EGL Vendor    :%s\n", eglQueryString(eglDisplay, EGL_VENDOR));
    g_print("EGL Extensions:%s\n", eglQueryString(eglDisplay, EGL_EXTENSIONS));

    // Here, the application chooses the configuration it desires. In this
    // sample, we have a very simplified selection process, where we pick
    // the first EGLConfig that matches our criteria
    EGLint     eglNumConfigs = 0;
    EGLConfig  eglConfig;
    eglGetConfigs(eglDisplay, NULL, 0, &eglNumConfigs);
    g_print("eglNumConfigs = %i\n", eglNumConfigs);

    /*
    int i = 0;
    for (i = 0; i<eglNumConfigs; ++i) {
        EGLint samples = 0;
        //if (EGL_FALSE == eglGetConfigAttrib(eglDisplay, eglConfig[i], EGL_SAMPLES, &samples))
        //    printf("eglGetConfigAttrib in loop for an EGL_SAMPLES fail at i = %i\n", i);
        if (EGL_FALSE == eglGetConfigAttrib(eglDisplay, eglConfig[i], EGL_SAMPLE_BUFFERS, &samples))
            printf("eglGetConfigAttrib in loop for an  EGL_SAMPLE_BUFFERS fail at i = %i\n", i);

        if (samples > 0)
            printf("sample found: %i\n", samples);

    }
    eglGetConfigs(eglDisplay, configs, num_config[0], num_config))
    */

    // Here specify the attributes of the desired configuration.
    // Below, we select an EGLConfig with at least 8 bits per color
    // component compatible with on-screen windows
    const EGLint eglConfigList[] = {
        EGL_SURFACE_TYPE,    EGL_WINDOW_BIT,
        EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,

        EGL_RED_SIZE,        8,
        EGL_GREEN_SIZE,      8,
        EGL_BLUE_SIZE,       8,

        EGL_NONE
    };

    if (EGL_FALSE == eglChooseConfig(eglDisplay, eglConfigList, &eglConfig, 1, &eglNumConfigs))
        g_print("eglChooseConfig() failed. [0x%x]\n", eglGetError());
    if (0 == eglNumConfigs)
        g_print("eglChooseConfig() eglNumConfigs no matching config [0x%x]\n", eglGetError());

	eglWindow = (EGLNativeWindowType) gtk_widget_get_window(engine->window);
    if (FALSE == eglWindow) {
        g_print("ERROR: EGLNativeWindowType is NULL (can't draw)\n");
        g_assert(0);
    }
    g_print("DEBUG: eglDisplay  =0X%X\n", (guint)eglDisplay);
    g_print("DEBUG: eglConfig   =0X%X\n", (guint)eglConfig);
    g_print("DEBUG: eglWindowXID=0X%X\n", (guint)GDK_WINDOW_XID(eglWindow));

    eglSurface = eglCreateWindowSurface(eglDisplay, eglConfig, GDK_WINDOW_XID(gtk_widget_get_window(engine->window)), NULL);
    if (EGL_NO_SURFACE == eglSurface || EGL_SUCCESS != eglGetError())
        g_print("eglCreateWindowSurface() failed. EGL_NO_SURFACE [0x%x]\n", eglGetError());

    // Then we can create the context and set it current:
    EGLint eglContextList[] = {
        EGL_CONTEXT_CLIENT_VERSION, 2,
        EGL_NONE
    };
    eglContext = eglCreateContext(eglDisplay, eglConfig, EGL_NO_CONTEXT, eglContextList);
    if (EGL_NO_CONTEXT == eglContext || EGL_SUCCESS != eglGetError())
        g_print("eglCreateContext() failed. [0x%x]\n", eglGetError());

    if (EGL_FALSE == eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext))
        g_print("Unable to eglMakeCurrent()\n");

    engine->eglDisplay = eglDisplay;
    engine->eglContext = eglContext;
    engine->eglSurface = eglSurface;
    engine->eglWindow  = eglWindow;

    g_print("s52egl:_egl_init(): end ..\n");

    return 1;
}
Beispiel #20
0
		void makeCurrent()
		{
			eglMakeCurrent(m_display, m_surface, m_surface, m_context);
		}
Beispiel #21
0
bool create_ANGLE(EGLNativeWindowType hWnd,
                  int msaaSampleCount,
                  EGLDisplay* eglDisplay,
                  EGLContext* eglContext,
                  EGLSurface* eglSurface,
                  EGLConfig* eglConfig) {
    static const EGLint contextAttribs[] = {
        EGL_CONTEXT_CLIENT_VERSION, 2,
        EGL_NONE, EGL_NONE
    };
    static const EGLint configAttribList[] = {
        EGL_RED_SIZE,       8,
        EGL_GREEN_SIZE,     8,
        EGL_BLUE_SIZE,      8,
        EGL_ALPHA_SIZE,     8,
        EGL_DEPTH_SIZE,     8,
        EGL_STENCIL_SIZE,   8,
        EGL_NONE
    };
    static const EGLint surfaceAttribList[] = {
        EGL_NONE, EGL_NONE
    };

    EGLDisplay display = get_angle_egl_display(GetDC(hWnd));

    if (EGL_NO_DISPLAY == display) {
        SkDebugf("Could not create ANGLE egl display!\n");
        return false;
    }

    // Initialize EGL
    EGLint majorVersion, minorVersion;
    if (!eglInitialize(display, &majorVersion, &minorVersion)) {
       return false;
    }

    EGLint numConfigs;
    if (!eglGetConfigs(display, NULL, 0, &numConfigs)) {
       return false;
    }

    // Choose config
    bool foundConfig = false;
    if (msaaSampleCount) {
        static const int kConfigAttribListCnt =
                                SK_ARRAY_COUNT(configAttribList);
        EGLint msaaConfigAttribList[kConfigAttribListCnt + 4];
        memcpy(msaaConfigAttribList,
               configAttribList,
               sizeof(configAttribList));
        SkASSERT(EGL_NONE == msaaConfigAttribList[kConfigAttribListCnt - 1]);
        msaaConfigAttribList[kConfigAttribListCnt - 1] = EGL_SAMPLE_BUFFERS;
        msaaConfigAttribList[kConfigAttribListCnt + 0] = 1;
        msaaConfigAttribList[kConfigAttribListCnt + 1] = EGL_SAMPLES;
        msaaConfigAttribList[kConfigAttribListCnt + 2] = msaaSampleCount;
        msaaConfigAttribList[kConfigAttribListCnt + 3] = EGL_NONE;
        if (eglChooseConfig(display, msaaConfigAttribList, eglConfig, 1, &numConfigs)) {
            SkASSERT(numConfigs > 0);
            foundConfig = true;
        }
    }
    if (!foundConfig) {
        if (!eglChooseConfig(display, configAttribList, eglConfig, 1, &numConfigs)) {
           return false;
        }
    }

    // Create a surface
    EGLSurface surface = eglCreateWindowSurface(display, *eglConfig,
                                                (EGLNativeWindowType)hWnd,
                                                surfaceAttribList);
    if (surface == EGL_NO_SURFACE) {
       return false;
    }

    // Create a GL context
    EGLContext context = eglCreateContext(display, *eglConfig,
                                          EGL_NO_CONTEXT,
                                          contextAttribs );
    if (context == EGL_NO_CONTEXT ) {
       return false;
    }

    // Make the context current
    if (!eglMakeCurrent(display, surface, surface, context)) {
       return false;
    }

    *eglDisplay = display;
    *eglContext = context;
    *eglSurface = surface;
    return true;
}
Beispiel #22
0
	void GlContext::create(uint32_t _width, uint32_t _height)
	{
#	if BX_PLATFORM_RPI
		bcm_host_init();
#	endif // BX_PLATFORM_RPI

		m_eglLibrary = eglOpen();

		if (NULL == g_platformData.context)
		{
			BX_UNUSED(_width, _height);
			EGLNativeDisplayType ndt = (EGLNativeDisplayType)g_platformData.ndt;
			EGLNativeWindowType  nwh = (EGLNativeWindowType )g_platformData.nwh;

#	if BX_PLATFORM_WINDOWS
			if (NULL == g_platformData.ndt)
			{
				ndt = GetDC( (HWND)g_platformData.nwh);
			}
#	endif // BX_PLATFORM_WINDOWS

			m_display = eglGetDisplay(ndt);
			BGFX_FATAL(m_display != EGL_NO_DISPLAY, Fatal::UnableToInitialize, "Failed to create display %p", m_display);

			EGLint major = 0;
			EGLint minor = 0;
			EGLBoolean success = eglInitialize(m_display, &major, &minor);
			BGFX_FATAL(success && major >= 1 && minor >= 3, Fatal::UnableToInitialize, "Failed to initialize %d.%d", major, minor);

			BX_TRACE("EGL info:");
			const char* clientApis = eglQueryString(m_display, EGL_CLIENT_APIS);
			BX_TRACE("   APIs: %s", clientApis); BX_UNUSED(clientApis);

			const char* vendor = eglQueryString(m_display, EGL_VENDOR);
			BX_TRACE(" Vendor: %s", vendor); BX_UNUSED(vendor);

			const char* version = eglQueryString(m_display, EGL_VERSION);
			BX_TRACE("Version: %s", version); BX_UNUSED(version);

			const char* extensions = eglQueryString(m_display, EGL_EXTENSIONS);
			BX_TRACE("Supported EGL extensions:");
			dumpExtensions(extensions);

			EGLint attrs[] =
			{
				EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,

#	if BX_PLATFORM_ANDROID
				EGL_DEPTH_SIZE, 16,
#	else
				EGL_DEPTH_SIZE, 24,
#	endif // BX_PLATFORM_
				EGL_STENCIL_SIZE, 8,

				EGL_NONE
			};

			EGLint numConfig = 0;
			success = eglChooseConfig(m_display, attrs, &m_config, 1, &numConfig);
			BGFX_FATAL(success, Fatal::UnableToInitialize, "eglChooseConfig");

#	if BX_PLATFORM_ANDROID

			EGLint format;
			eglGetConfigAttrib(m_display, m_config, EGL_NATIVE_VISUAL_ID, &format);
			ANativeWindow_setBuffersGeometry( (ANativeWindow*)g_platformData.nwh, _width, _height, format);

#	elif BX_PLATFORM_RPI
			DISPMANX_DISPLAY_HANDLE_T dispmanDisplay = vc_dispmanx_display_open(0);
			DISPMANX_UPDATE_HANDLE_T  dispmanUpdate  = vc_dispmanx_update_start(0);

			VC_RECT_T dstRect = { 0, 0, _width,        _height       };
			VC_RECT_T srcRect = { 0, 0, _width  << 16, _height << 16 };

			DISPMANX_ELEMENT_HANDLE_T dispmanElement = vc_dispmanx_element_add(dispmanUpdate
				, dispmanDisplay
				, 0
				, &dstRect
				, 0
				, &srcRect
				, DISPMANX_PROTECTION_NONE
				, NULL
				, NULL
				, DISPMANX_NO_ROTATE
				);

			s_dispmanWindow.element = dispmanElement;
			s_dispmanWindow.width   = _width;
			s_dispmanWindow.height  = _height;
			nwh = &s_dispmanWindow;

			vc_dispmanx_update_submit_sync(dispmanUpdate);
#	endif // BX_PLATFORM_ANDROID

			m_surface = eglCreateWindowSurface(m_display, m_config, nwh, NULL);
			BGFX_FATAL(m_surface != EGL_NO_SURFACE, Fatal::UnableToInitialize, "Failed to create surface.");

			const bool hasEglKhrCreateContext = !!bx::findIdentifierMatch(extensions, "EGL_KHR_create_context");
			const bool hasEglKhrNoError       = !!bx::findIdentifierMatch(extensions, "EGL_KHR_create_context_no_error");

			for (uint32_t ii = 0; ii < 2; ++ii)
			{
				bx::StaticMemoryBlockWriter writer(s_contextAttrs, sizeof(s_contextAttrs) );

				EGLint flags = 0;

				if (hasEglKhrCreateContext)
				{
					bx::write(&writer, EGLint(EGL_CONTEXT_MAJOR_VERSION_KHR) );
					bx::write(&writer, EGLint(BGFX_CONFIG_RENDERER_OPENGLES / 10) );

					bx::write(&writer, EGLint(EGL_CONTEXT_MINOR_VERSION_KHR) );
					bx::write(&writer, EGLint(BGFX_CONFIG_RENDERER_OPENGLES % 10) );

					flags |= BGFX_CONFIG_DEBUG && hasEglKhrNoError ? 0
						| EGL_CONTEXT_FLAG_NO_ERROR_BIT_KHR
						: 0
						;

					if (0 == ii)
					{
						flags |= BGFX_CONFIG_DEBUG ? 0
							| EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR
//							| EGL_OPENGL_ES3_BIT_KHR
							: 0
							;

						bx::write(&writer, EGLint(EGL_CONTEXT_FLAGS_KHR) );
						bx::write(&writer, flags);
					}
				}
				else
				{
					bx::write(&writer, EGLint(EGL_CONTEXT_CLIENT_VERSION) );
					bx::write(&writer, 2);
				}

				bx::write(&writer, EGLint(EGL_NONE) );

				m_context = eglCreateContext(m_display, m_config, EGL_NO_CONTEXT, s_contextAttrs);
				if (NULL != m_context)
				{
					break;
				}

				BX_TRACE("Failed to create EGL context with EGL_CONTEXT_FLAGS_KHR (%08x).", flags);
			}

			BGFX_FATAL(m_context != EGL_NO_CONTEXT, Fatal::UnableToInitialize, "Failed to create context.");

			success = eglMakeCurrent(m_display, m_surface, m_surface, m_context);
			BGFX_FATAL(success, Fatal::UnableToInitialize, "Failed to set context.");
			m_current = NULL;

			eglSwapInterval(m_display, 0);
		}

		import();
	}
Beispiel #23
0
int engine_init_display(void)
{
	EGLint attribs[]=
	{
		EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
		EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
		EGL_NATIVE_RENDERABLE, EGL_FALSE,
		EGL_BUFFER_SIZE, 32,
		EGL_DEPTH_SIZE, 24,
		EGL_SAMPLES, 1,
		EGL_NONE
	};
	EGLint contextAttribs[]=
	{
		EGL_CONTEXT_CLIENT_VERSION, 2,
		EGL_NONE
	};
	EGLint format=0, numConfig=0;
	EGLint major=0, minor=0;
	EGLConfig eglConfig;

	if((display=eglGetDisplay((EGLNativeDisplayType)EGL_DEFAULT_DISPLAY))==EGL_NO_DISPLAY)
	{
		LOGI("eglGetDisplay failed.\n");
		return 0;
	}

	if(!eglInitialize(display, &major, &minor))
	{
		LOGI("eglInitialize failed.\n");
		return 0;
	}

	if(major<1||minor<3)
	{
		LOGI("System does not support at least EGL 1.3\n");
		return 0;
	}

	if(!eglChooseConfig(display, attribs, &eglConfig, 1, &numConfig))
	{
		LOGI("eglChooseConfig failed.\n");
		return 0;
	}

	if((surface=eglCreateWindowSurface(display, eglConfig, (EGLNativeWindowType)app->window, NULL))==EGL_NO_SURFACE)
	{
		LOGI("eglCreateWindowSurface failed.\n");
		return 0;
	}

	if((context=eglCreateContext(display, eglConfig, EGL_NO_CONTEXT, contextAttribs))==EGL_NO_CONTEXT)
	{
		LOGI("eglCreateContext failed.\n");
		return 0;
	}

	if(!eglMakeCurrent(display, surface, surface, context))
	{
		LOGI("eglMakeCurrent failed.\n");
		return 0;
	}

	eglQuerySurface(display, surface, EGL_WIDTH, &width);
	eglQuerySurface(display, surface, EGL_HEIGHT, &height);

	LOGI("Width: %d Height: %d\n", width, height);

	glViewport(0, 0, width, height);

	Objects[GLSL_FONT_SHADER]=CreateProgram("2d_v.glsl", "font_f.glsl");
	glUseProgram(Objects[GLSL_FONT_SHADER]);
	Objects[GLSL_FONT_VVERT]=glGetAttribLocation(Objects[GLSL_FONT_SHADER], "vVert");
	Objects[GLSL_FONT_TEX]=glGetUniformLocation(Objects[GLSL_FONT_SHADER], "Tex");
	Objects[GLSL_FONT_WIDTH]=glGetUniformLocation(Objects[GLSL_FONT_SHADER], "right");
	Objects[GLSL_FONT_HEIGHT]=glGetUniformLocation(Objects[GLSL_FONT_SHADER], "top");

	Objects[TEXTURE_FONT]=Image_Upload("font.tga", IMAGE_BILINEAR|IMAGE_REPEAT);

	Objects[GLSL_GAUGE_SHADER]=CreateProgram("2d_v.glsl", "gauge_f.glsl");
	glUseProgram(Objects[GLSL_GAUGE_SHADER]);
	Objects[GLSL_GAUGE_VVERT]=glGetAttribLocation(Objects[GLSL_GAUGE_SHADER], "vVert");
	Objects[GLSL_GAUGE_TEX]=glGetUniformLocation(Objects[GLSL_GAUGE_SHADER], "Tex");
	Objects[GLSL_GAUGE_AMOUNT]=glGetUniformLocation(Objects[GLSL_GAUGE_SHADER], "Amount");
	Objects[GLSL_GAUGE_WIDTH]=glGetUniformLocation(Objects[GLSL_GAUGE_SHADER], "right");
	Objects[GLSL_GAUGE_HEIGHT]=glGetUniformLocation(Objects[GLSL_GAUGE_SHADER], "top");

	Objects[TEXTURE_AFR]=Image_Upload("afr.tga", IMAGE_BILINEAR|IMAGE_REPEAT);
	Objects[TEXTURE_BAT]=Image_Upload("bat.tga", IMAGE_BILINEAR|IMAGE_REPEAT);
	Objects[TEXTURE_CLT]=Image_Upload("clt.tga", IMAGE_BILINEAR|IMAGE_REPEAT);
	Objects[TEXTURE_IGN]=Image_Upload("ign.tga", IMAGE_BILINEAR|IMAGE_REPEAT);
	Objects[TEXTURE_MAP]=Image_Upload("map.tga", IMAGE_BILINEAR|IMAGE_REPEAT);
	Objects[TEXTURE_MAT]=Image_Upload("mat.tga", IMAGE_BILINEAR|IMAGE_REPEAT);
	Objects[TEXTURE_RPM]=Image_Upload("rpm.tga", IMAGE_BILINEAR|IMAGE_REPEAT);
	Objects[TEXTURE_TPS]=Image_Upload("tps.tga", IMAGE_BILINEAR|IMAGE_REPEAT);

	glEnable(GL_CULL_FACE);
	glDisable(GL_DEPTH_TEST);

	return 1;
}
Beispiel #24
0
static int engine_init_display(struct engine* engine) 
{
    // initialize OpenGL ES and EGL


    const EGLint attribs[] = 
    {
            EGL_NATIVE_VISUAL_ID, WINDOW_FORMAT_RGB_565,
            EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
    	    EGL_BLUE_SIZE, 5,
            EGL_GREEN_SIZE, 6,
            EGL_RED_SIZE, 5,
            EGL_DEPTH_SIZE,1,
            EGL_NONE
    };



    EGLint w, h, dummy, format;
    EGLint numConfigs;
    EGLConfig config;
    EGLSurface surface;
    EGLContext context;

    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);


    EGLint majorVersion;
    EGLint minorVersion;

    eglInitialize(display, &majorVersion, &minorVersion);
    //eglInitialize(display, 0, 0);
    LOGI("OpenGL %i.%i", majorVersion,minorVersion);

    //query num of configs
    int* num_conf = new int[1];
    eglGetConfigs(display, NULL, 0, num_conf);  //if configuration array is null it still returns the number of configurations
    int configurations = num_conf[0];

    LOGI("total num configs: %i", configurations);

    //just some debugging info if the need arises...
    LOGI("EGL_OPENGL_ES2_BIT id:%i", EGL_OPENGL_ES2_BIT); //print the numerical code for the ES2 bit mask, etc
    LOGI("EGL_SURFACE_TYPE::EGL_WINDOW_BIT id:%i", EGL_WINDOW_BIT);
    LOGI("WINDOW_FORMAT_RGB_565 id:%i", WINDOW_FORMAT_RGB_565);

    //now query the configs
    EGLConfig* conf = new EGLConfig[configurations];
    eglGetConfigs(display, conf, configurations, num_conf);

    int* depth = new int[1];
	int* r = new int[1];
	int* g = new int[1];
	int* b = new int[1];
	int* a = new int[1];
	int* s = new int[1];
	int* renderType = new int[1];
	int* surfaceType = new int[1];
	int* formatType = new int[1];

	EGLConfig configToUse; //this is the one true config that we will use

    for(int i = 0; i < configurations; i++)
     {
      eglGetConfigAttrib(display, conf[i], EGL_DEPTH_SIZE, depth);
      eglGetConfigAttrib(display, conf[i], EGL_RED_SIZE, r);
      eglGetConfigAttrib(display, conf[i], EGL_GREEN_SIZE, g);
      eglGetConfigAttrib(display, conf[i], EGL_BLUE_SIZE, b);
      eglGetConfigAttrib(display, conf[i], EGL_ALPHA_SIZE, a);
      eglGetConfigAttrib(display, conf[i], EGL_RENDERABLE_TYPE, renderType);
      eglGetConfigAttrib(display, conf[i], EGL_STENCIL_SIZE, s);
      eglGetConfigAttrib(display, conf[i], EGL_SURFACE_TYPE, surfaceType);
      eglGetConfigAttrib(display, conf[i], EGL_NATIVE_VISUAL_ID, formatType);

      LOGI("(R%i,G%i,B%i,A%i)depth:(%i) stencil:(%i) surfaceType:(%i) renderType:(%i) formatType:(%i)",r[0],g[0],b[0],a[0],depth[0],s[0],surfaceType[0], renderType[0],formatType[0]);


      if((renderType[0] & EGL_OPENGL_ES2_BIT) > 0 &&
    	(surfaceType[0] & EGL_WINDOW_BIT) > 0 &&
    	(formatType[0] & WINDOW_FORMAT_RGB_565) > 0 &&
    	depth[0]>0)
      {

    	  configToUse=conf[i];

    	  LOGI("Config #%i" , i );

    	  LOGI("(R%i,G%i,B%i,A%i) %idepth %istencil %isurfaceType %iNativeVisualId",r[0],g[0],b[0],a[0],depth[0],s[0],surfaceType[0],formatType[0]);
      }

     }

    //bridge the pixel format back into android
    eglGetConfigAttrib(display, configToUse, EGL_NATIVE_VISUAL_ID, &format);
    ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format);

    surface = eglCreateWindowSurface(display, configToUse, engine->app->window, NULL);

    if(surface == EGL_NO_SURFACE ) 
    {
    	LOGW("Error making surface, EGL_NO_SURFACE");
    }

    //now create the OpenGL ES2 context
    const EGLint contextAttribs[] = 
    {
    		EGL_CONTEXT_CLIENT_VERSION , 2,
    		EGL_NONE
    };

    context = eglCreateContext(display, configToUse, NULL, contextAttribs);

    if(context == EGL_NO_CONTEXT ) 
    {
    	LOGW("Error making context, EGL_NO_CONTEXT");
    }

    if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) 
    {
        LOGW("Unable to eglMakeCurrent");
        return -1;
    }

    eglQuerySurface(display, surface, EGL_WIDTH, &w);
    eglQuerySurface(display, surface, EGL_HEIGHT, &h);


    ContextWidth = w;
    ContextHeight = h;

    engine->display = display;
    engine->context = context;
    engine->surface = surface;
    engine->width = w;
    engine->height = h;
    engine->state.angle = 0;

    glEnable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);

    //GLubyte* rendererString = new GLubyte[512];
    const GLubyte* rendererString = rendererString=glGetString(GL_VERSION);
    LOGI("Renderer: %s",rendererString);


    //
	//
	// LOAD ALL RESOURCES
	//
	//

    //////////////////
    // PHONG SHADER //
    //////////////////

    if(!PhongShader.createShader((char*)"phong.vs",(char*)"phong.fs"))
    {
    	LOGE("Could not create phong program.");
    	return false;
    }

	PositionAttributes = glGetAttribLocation(PhongShader.ID, "aPosition");
	NormalAttributes =   glGetAttribLocation(PhongShader.ID, "aNormal");
	TexCoordAttributes = glGetAttribLocation(PhongShader.ID, "aTexCoords");
	MVPMatrixUniform = glGetUniformLocation( PhongShader.ID, "MVPMatrixUniform" );
	EyePosUniform = glGetUniformLocation(PhongShader.ID,"EyePosUniform");
	LightPosUniform = glGetUniformLocation(PhongShader.ID,"LightPosUniform");
	TextureSampler = glGetUniformLocation(PhongShader.ID,"sTexture");

	LOGI("===PHONG-DEBUG VALUES===");
	LOGI("PositionAttributes: %i",PositionAttributes);
	LOGI("NormalAttributes: %i",NormalAttributes);
	LOGI("TexCoordAttributes: %i",TexCoordAttributes);

	LOGI("MVPMatrixUniform: %i",MVPMatrixUniform);
	LOGI("EyePosUniform: %i",EyePosUniform);
	LOGI("LightPosUniform: %i",LightPosUniform);

	LOGI("TextureSampler: %i",TextureSampler);
	LOGI("===END===");

    //////////////////
    // DEPTH SHADER //
    //////////////////

	if(!DepthShader.createShader((char*)"depthcolor.vs",(char*)"depthcolor.fs")) 
	{
		LOGE("Could not create depth shader program.");
		return false;
	}

	DepthShaderMVPMatrixUniform = 	glGetUniformLocation(DepthShader.ID, "MVPMatrixUniform");
	DepthShaderPositionAttributes = glGetAttribLocation(DepthShader.ID, "aPosition");

	LOGI("===DEPTH-DEBUG VALUES===");
	LOGI("DepthShaderPositionAttributes: %i",DepthShaderPositionAttributes);
	LOGI("DepthShaderMVPMatrixUniform: %i",DepthShaderMVPMatrixUniform);
	LOGI("===END===");
	/////////////////////////////////
	// TEXPASSTHRU (SKYBOX) SHADER //
	/////////////////////////////////

	if(!TexPassThruShader.createShader((char*)"texpassthru.vs",(char*)"texpassthru.fs")) 
	{
		LOGE("Could not create texpassthru program.");
		return false;
	}

	TexPassThruSampler = glGetUniformLocation(TexPassThruShader.ID,"sTexture");
	TexPassThruMVPMatrixUniform = glGetUniformLocation(TexPassThruShader.ID,"MVPMatrixUniform");

	TexPassThruPositionAttributes = glGetAttribLocation(TexPassThruShader.ID, "aPosition");
	TexPassThruTexCoordAttributes = glGetAttribLocation(TexPassThruShader.ID, "aTexCoords");

	LOGI("===TEXPASSTHRU-DEBUG VALUES===");
	LOGI("TexPassThruSampler: %i",TexPassThruSampler);
	LOGI("TexPassThruMVPMatrixUniform: %i",TexPassThruMVPMatrixUniform);
	LOGI("TexPassThruPositionAttributes: %i",TexPassThruPositionAttributes);
	LOGI("TexPassThruTexCoordAttributes: %i",TexPassThruTexCoordAttributes);
	LOGI("===END===");



    ////////////////////////
    // ENVIRONMENT SHADER //
    ////////////////////////

	if (!EnvironmentMappingShader.createShader((char*)"environmentcubemap.vs",(char*)"environmentcubemap.fs")) 
	{
		LOGE("Could not create program.");
		return false;
	}

	EnvironmentMappingShaderMVPMatrixUniform=glGetUniformLocation(EnvironmentMappingShader.ID,"MVPMatrixUniform");
	EnvironmentMappingShaderPositionAttributes=glGetAttribLocation(EnvironmentMappingShader.ID, "aPosition");
	EnvironmentMappingShaderNormalAttributes=glGetAttribLocation(EnvironmentMappingShader.ID, "aNormal");
	EnvironmentMappingShaderCubeSampler=glGetUniformLocation(EnvironmentMappingShader.ID,"sCubeTexture");

	LOGI("===ENVIRONMENT-DEBUG VALUES===");
	LOGI("EnvironmentMappingShaderCubeSampler: %i",EnvironmentMappingShaderCubeSampler);
	LOGI("EnvironmentMappingShaderMVPMatrixUniform: %i",EnvironmentMappingShaderMVPMatrixUniform);
	LOGI("EnvironmentMappingShaderPositionAttributes: %i",EnvironmentMappingShaderPositionAttributes);
	LOGI("TexPassThruTeEnvironmentMappingShaderNormalAttributesxCoordAttributes: %i",EnvironmentMappingShaderNormalAttributes);
	LOGI("===END===");

	//Matrices
	esMatrixLoadIdentity(&MVPMatrix);

	//viewport
	glViewport(0, 0, w, h);
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	checkGlError("glViewport");

	//load resources internally from the APK

	StatueMesh.loadMesh((char*)"athena.obj");
	checkGlError("loadMesh");

	if(!StoneTexture.loadTexture((char*)"rockish.tga")) 
	{
		LOGE("texture loading FAILED");
	}

	CubeSkyBox.loadSkyBox();

	if(!EnvironmentCubeTexture.loadCubeTexture())
		LOGE("Could not load cube texture.");

    return 0;
}
Beispiel #25
0
GL_Window::GL_Window(int w, int h)
{
    int width = w;
    int height = h;
    XSetWindowAttributes swa;
    x_display = XOpenDisplay(NULL);
    DefaultScreen(x_display);
    root = DefaultRootWindow(x_display);
    swa.event_mask = ExposureMask | PointerMotionMask | KeyPressMask | ButtonPressMask |
                     MotionNotify | ButtonReleaseMask | StructureNotifyMask;

    win = XCreateWindow(x_display, root, 0, 0, width, height, 0,
                        CopyFromParent, InputOutput, CopyFromParent, CWEventMask, &swa);

    // handle window close correctly

    XMapWindow(x_display, win);
    Atom delmsg = XInternAtom(x_display, "WM_DELETE_WINDOW", False);
    XSetWMProtocols(x_display, win, &delmsg, 1);

    // limit resize to 16:9 ratio

    XSizeHints *hints = XAllocSizeHints();
    hints->flags |= PAspect;
    hints->min_aspect.x = 16;
    hints->min_aspect.y = 9;
    hints->max_aspect.x = 16;
    hints->max_aspect.y = 9;
    XSetWMNormalHints(x_display, win, hints);
    XFree(hints);


    // EGL stuff

    EGLint major, minor;
    EGLint numConfigs;
    EGLConfig config;
    const EGLint configAttribs[] = {
            EGL_RENDERABLE_TYPE, EGL_WINDOW_BIT,
            EGL_RED_SIZE, 8,
            EGL_GREEN_SIZE, 8,
            EGL_BLUE_SIZE, 8,
            EGL_DEPTH_SIZE, 24,
            EGL_NONE
    };
    const EGLint contextAttribs[] = {
            EGL_CONTEXT_CLIENT_VERSION, 2,
            EGL_NONE
    };
    display = eglGetDisplay((EGLNativeDisplayType)x_display);
    eglInitialize(display, &major, &minor);
    eglChooseConfig(display, configAttribs, &config, 1, &numConfigs);
    surface = eglCreateWindowSurface(display, config,
                    (EGLNativeWindowType)win, NULL);
    context = eglCreateContext(display, config,
                    EGL_NO_CONTEXT, contextAttribs);
    eglMakeCurrent(display, surface, surface, context);



}
Beispiel #26
0
int
main(int argc, char *argv[])
{
   const int winWidth = 400, winHeight = 300;
   Display *x_dpy;
   Window win;
   EGLSurface egl_surf;
   EGLContext egl_ctx;
   EGLDisplay egl_dpy;
   char *dpyName = NULL;
   EGLint egl_major, egl_minor, es_ver;
   int i;

   for (i = 1; i < argc; i++) {
      if (strcmp(argv[i], "-display") == 0) {
         dpyName = argv[i+1];
         i++;
      }
      else {
         usage();
         return -1;
      }
   }

   x_dpy = XOpenDisplay(dpyName);
   if (!x_dpy) {
      printf("Error: couldn't open display %s\n",
	     dpyName ? dpyName : getenv("DISPLAY"));
      return -1;
   }

   egl_dpy = eglGetDisplay(x_dpy);
   if (!egl_dpy) {
      printf("Error: eglGetDisplay() failed\n");
      return -1;
   }

   if (!eglInitialize(egl_dpy, &egl_major, &egl_minor)) {
      printf("Error: eglInitialize() failed\n");
      return -1;
   }

   es_ver = 1;
   /* decide the version from the executable's name */
   if (argc > 0 && argv[0] && strstr(argv[0], "es2"))
      es_ver = 2;
   make_x_window(x_dpy, egl_dpy,
                 "ES info", 0, 0, winWidth, winHeight, es_ver,
                 &win, &egl_ctx, &egl_surf);

   /*XMapWindow(x_dpy, win);*/
   if (!eglMakeCurrent(egl_dpy, egl_surf, egl_surf, egl_ctx)) {
      printf("Error: eglMakeCurrent() failed\n");
      return -1;
   }

   info(egl_dpy);

   eglDestroyContext(egl_dpy, egl_ctx);
   eglDestroySurface(egl_dpy, egl_surf);
   eglTerminate(egl_dpy);


   XDestroyWindow(x_dpy, win);
   XCloseDisplay(x_dpy);

   return 0;
}
Beispiel #27
0
void
MoonEGLContext::MakeCurrent ()
{
	g_assert (context);
	eglMakeCurrent (display, surface, surface, context);
}
Beispiel #28
0
/* Run through multiple variants to detect clear color, quad color (frag
 * shader param), and vertices
 */
void test_query(int querytype, int w, int h)
{
	static const GLfloat clear_color[] = {0.0, 0.0, 0.0, 0.0};
	static const GLfloat quad_color[]  = {1.0, 0.0, 0.0, 1.0};
	static const GLfloat quad2_color[]  = {0.0, 1.0, 0.0, 1.0};
	static const GLfloat vertices[] = {
			-0.45, -0.75, 0.0,
			 0.45, -0.75, 0.0,
			-0.45,  0.75, 0.0,
			 0.45,  0.75, 0.0,
	};
	static const GLfloat vertices2[] = {
			-0.15, -0.23, 1.0,
			 0.25, -0.33, 1.0,
			-0.35,  0.43, 1.0,
			 0.45,  0.53, 1.0,
	};
	static const char *queryname[] = {
			"none",
			"samples-passed",
			"time-elapsed",
	};

	RD_START("query", "query=%s", queryname[querytype]);
	display = get_display();

	/* get an appropriate EGL frame buffer configuration */
	ECHK(eglChooseConfig(display, config_attribute_list, &config, 1, &num_config));
	DEBUG_MSG("num_config: %d", num_config);

	/* create an EGL rendering context */
	ECHK(context = eglCreateContext(display, config, EGL_NO_CONTEXT, context_attribute_list));

	surface = make_window(display, config, w, h);

	ECHK(eglQuerySurface(display, surface, EGL_WIDTH, &width));
	ECHK(eglQuerySurface(display, surface, EGL_HEIGHT, &height));

	DEBUG_MSG("Buffer: %dx%d", width, height);

	/* connect the context to the surface */
	ECHK(eglMakeCurrent(display, surface, surface, context));

	program = get_program(vertex_shader_source, fragment_shader_source);

	GCHK(glBindAttribLocation(program, 0, "aPosition"));

	link_program(program);

	GCHK(glGenQueries(1, &query));

	GCHK(glDepthMask(GL_TRUE));
	GCHK(glEnable(GL_DEPTH_TEST));

	GCHK(glViewport(0, 0, width, height));

	if (clear_color) {
		/* clear the color buffer */
		GCHK(glClearColor(clear_color[0], clear_color[1], clear_color[2], clear_color[3]));
		GCHK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
	}

	GCHK(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vertices));
	GCHK(glEnableVertexAttribArray(0));

	/* now set up our uniform. */
	GCHK(uniform_location = glGetUniformLocation(program, "uColor"));

	GCHK(glUniform4fv(uniform_location, 1, quad_color));
	GCHK(glDrawArrays(GL_TRIANGLE_STRIP, 0, 4));

	switch (querytype) {
	case 1:
		GCHK(glBeginQuery(GL_ANY_SAMPLES_PASSED, query));
		break;
	case 2:
		GCHK(glBeginQuery(GL_TIME_ELAPSED_EXT, query));
		break;
	}

	/* Quad 2 render */
	GCHK(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vertices2));

	/* now set up our uniform. */
	GCHK(uniform_location = glGetUniformLocation(program, "uColor"));

	GCHK(glUniform4fv(uniform_location, 1, quad2_color));
	GCHK(glDrawArrays(GL_TRIANGLE_STRIP, 0, 4));

	switch (querytype) {
	case 1:
		GCHK(glEndQuery(GL_ANY_SAMPLES_PASSED));
		break;
	case 2:
		GCHK(glEndQuery(GL_TIME_ELAPSED_EXT));
		break;
	}

	if (querytype > 0) {
		GLuint result;
		do
		{
			GCHK(glGetQueryObjectuiv(query, GL_QUERY_RESULT_AVAILABLE, &result));
		} while (!result);
		GCHK(glGetQueryObjectuiv(query, GL_QUERY_RESULT, &result));

		DEBUG_MSG("Query ended with %d", result);

	}

	ECHK(eglSwapBuffers(display, surface));
	GCHK(glFlush());

	usleep(1000000);

	GCHK(glDeleteQueries(1, &query));

	eglTerminate(display);

	RD_END();
}
bool OverlayComposer::initEGL()
{

    if (mWindow == NULL)
    {
        ALOGE("NativeWindow is NULL");
        return false;
    }

    int format;
    ANativeWindow const * const window = mWindow.get();
    window->query(window, NATIVE_WINDOW_FORMAT, &format);

    EGLint w, h, dummy;
    EGLint numConfigs=0;
    EGLSurface surface;
    EGLContext context;
    EGLBoolean result;
    status_t err;

    // initialize EGL
    EGLint attribs[] = {
            EGL_SURFACE_TYPE,       EGL_WINDOW_BIT,
            EGL_NONE,               0,
            EGL_NONE
    };


    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    checkEGLErrors("eglGetDisplay");
    eglInitialize(display, NULL, NULL);
    eglGetConfigs(display, NULL, 0, &numConfigs);

    EGLConfig config = NULL;
    err = selectConfigForPixelFormat(display, attribs, format, &config);
    ALOGE_IF(err, "couldn't find an EGLConfig matching the screen format");

    EGLint r,g,b,a;
    eglGetConfigAttrib(display, config, EGL_RED_SIZE,   &r);
    eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
    eglGetConfigAttrib(display, config, EGL_BLUE_SIZE,  &b);
    eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);

    //if (window->isUpdateOnDemand()) {
    //    mFlags |= PARTIAL_UPDATES;
    //}

    //if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy) == EGL_TRUE) {
    //   if (dummy == EGL_SLOW_CONFIG)
    //       mFlags |= SLOW_CONFIG;
    //}


     /*
     * Create our main surface
     */

    surface = eglCreateWindowSurface(display, config, mWindow.get(), NULL);
    checkEGLErrors("eglCreateWindowSurface");

    //if (mFlags & PARTIAL_UPDATES) {
    //    // if we have partial updates, we definitely don't need to
    //    // preserve the backbuffer, which may be costly.
    //    eglSurfaceAttrib(display, surface,
    //            EGL_SWAP_BEHAVIOR, EGL_BUFFER_DESTROYED);
    //}

    /*
     * Create our OpenGL ES context
     */
//#define EGL_IMG_context_priority
//#define HAS_CONTEXT_PRIORITY
    EGLint contextAttributes[] = {
#ifdef EGL_IMG_context_priority
#ifdef HAS_CONTEXT_PRIORITY
#warning "using EGL_IMG_context_priority"
        EGL_CONTEXT_PRIORITY_LEVEL_IMG, EGL_CONTEXT_PRIORITY_HIGH_IMG,
#endif
#endif
        EGL_NONE, EGL_NONE
    };
    context = eglCreateContext(display, config, NULL, contextAttributes);
    checkEGLErrors("eglCreateContext");
    mDisplay = display;
    mConfig  = config;
    mSurface = surface;
    mContext = context;
    //mFormat  = ;
    //mPageFlipCount = 0;

    /*
     * Gather OpenGL ES extensions
     */

    result = eglMakeCurrent(display, surface, surface, context);
    checkEGLErrors("eglMakeCurrent");
    if (!result) {
        ALOGE("Couldn't create a working GLES context. check logs. exiting...");
        return false;
    }

    //GLExtensions& extensions(GLExtensions::getInstance());
    //extensions.initWithGLStrings(
    //        glGetString(GL_VENDOR),
    //        glGetString(GL_RENDERER),
    //        glGetString(GL_VERSION),
    //        glGetString(GL_EXTENSIONS),
    //        eglQueryString(display, EGL_VENDOR),
    //        eglQueryString(display, EGL_VERSION),
    //        eglQueryString(display, EGL_EXTENSIONS));

    //glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
    //glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims);

    //ALOGI("EGL informations:");
    //ALOGI("# of configs : %d", numConfigs);
    //ALOGI("vendor    : %s", extensions.getEglVendor());
    //ALOGI("version   : %s", extensions.getEglVersion());
    //ALOGI("extensions: %s", extensions.getEglExtension());
    //ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS)?:"Not Supported");
    //ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);

    //ALOGI("OpenGL informations:");
    //ALOGI("vendor    : %s", extensions.getVendor());
    //ALOGI("renderer  : %s", extensions.getRenderer());
    //ALOGI("version   : %s", extensions.getVersion());
    //ALOGI("extensions: %s", extensions.getExtension());
    //ALOGI("GL_MAX_TEXTURE_SIZE = %d", mMaxTextureSize);
    //ALOGI("GL_MAX_VIEWPORT_DIMS = %d x %d", mMaxViewportDims[0], mMaxViewportDims[1]);
    //ALOGI("flags = %08x", mFlags);

    // Unbind the context from this thread
    //eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);


    return true;
}
Beispiel #30
0
/**
* Initialize an EGL context for the current display.
*/
static int engine_init_display(struct engine* engine) {
	// initialize OpenGL ES and EGL

	/*
	* Here specify the attributes of the desired configuration.
	* Below, we select an EGLConfig with at least 8 bits per color
	* component compatible with on-screen windows
	*/
	const EGLint attribs[] = {
		EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
		EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
		EGL_BLUE_SIZE, 8,
		EGL_GREEN_SIZE, 8,
        EGL_RED_SIZE, 8,
        EGL_ALPHA_SIZE, 8,
        EGL_DEPTH_SIZE, 8,
        EGL_STENCIL_SIZE, 8,
        EGL_NONE
	};
	EGLint w, h, format;
	EGLint numConfigs;
	EGLConfig config;
	EGLSurface surface;
	EGLContext context;

	EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

	eglInitialize(display, 0, 0);

	/* Here, the application chooses the configuration it desires. In this
	* sample, we have a very simplified selection process, where we pick
	* the first EGLConfig that matches our criteria */
	eglChooseConfig(display, attribs, &config, 1, &numConfigs);

	/* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
	* guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
	* As soon as we picked a EGLConfig, we can safely reconfigure the
	* ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */
	eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);

	ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format);

	surface = eglCreateWindowSurface(display, config, engine->app->window, NULL);

	EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
	context = eglCreateContext(display, config, NULL, contextAttribs);

	if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
		LOGW("Unable to eglMakeCurrent");
		return -1;
	}

	eglQuerySurface(display, surface, EGL_WIDTH, &w);
	eglQuerySurface(display, surface, EGL_HEIGHT, &h);

	engine->display = display;
	engine->context = context;
	engine->surface = surface;
	engine->width = w;
	engine->height = h;
	engine->state.angle = 0;

	if (!engine->mCubeRenderer)
	{
		engine->mCubeRenderer.reset(new SimpleRenderer());
		engine->mCubeRenderer->UpdateWindowSize(w, h);
	}

	return 0;
}