src/video/SDL_egl.c
author Sam Lantinga <slouken@libsdl.org>
Wed, 03 Jan 2018 10:03:25 -0800
changeset 11811 5d94cb6b24d3
parent 11723 bc7ca7cfa6ca
child 11829 fcbafc9e443c
permissions -rw-r--r--
Updated copyright for 2018
     1 /*
     2  *  Simple DirectMedia Layer
     3  *  Copyright (C) 1997-2018 Sam Lantinga <slouken@libsdl.org>
     4  * 
     5  *  This software is provided 'as-is', without any express or implied
     6  *  warranty.  In no event will the authors be held liable for any damages
     7  *  arising from the use of this software.
     8  * 
     9  *  Permission is granted to anyone to use this software for any purpose,
    10  *  including commercial applications, and to alter it and redistribute it
    11  *  freely, subject to the following restrictions:
    12  * 
    13  *  1. The origin of this software must not be misrepresented; you must not
    14  *     claim that you wrote the original software. If you use this software
    15  *     in a product, an acknowledgment in the product documentation would be
    16  *     appreciated but is not required.
    17  *  2. Altered source versions must be plainly marked as such, and must not be
    18  *     misrepresented as being the original software.
    19  *  3. This notice may not be removed or altered from any source distribution.
    20  */
    21 #include "../SDL_internal.h"
    22 
    23 #if SDL_VIDEO_OPENGL_EGL
    24 
    25 #if SDL_VIDEO_DRIVER_WINDOWS || SDL_VIDEO_DRIVER_WINRT
    26 #include "../core/windows/SDL_windows.h"
    27 #endif
    28 #if SDL_VIDEO_DRIVER_ANDROID
    29 #include <android/native_window.h>
    30 #endif
    31 
    32 #include "SDL_sysvideo.h"
    33 #include "SDL_log.h"
    34 #include "SDL_egl_c.h"
    35 #include "SDL_loadso.h"
    36 #include "SDL_hints.h"
    37 
    38 #ifdef EGL_KHR_create_context
    39 /* EGL_OPENGL_ES3_BIT_KHR was added in version 13 of the extension. */
    40 #ifndef EGL_OPENGL_ES3_BIT_KHR
    41 #define EGL_OPENGL_ES3_BIT_KHR 0x00000040
    42 #endif
    43 #endif /* EGL_KHR_create_context */
    44 
    45 #if SDL_VIDEO_DRIVER_RPI
    46 /* Raspbian places the OpenGL ES/EGL binaries in a non standard path */
    47 #define DEFAULT_EGL ( vc4 ? "libEGL.so.1" : "/opt/vc/lib/libbrcmEGL.so" )
    48 #define DEFAULT_OGL_ES2 ( vc4 ? "libGLESv2.so.2" : "/opt/vc/lib/libbrcmGLESv2.so" )
    49 #define ALT_EGL "/opt/vc/lib/libEGL.so"
    50 #define ALT_OGL_ES2 "/opt/vc/lib/libGLESv2.so"
    51 #define DEFAULT_OGL_ES_PVR ( vc4 ? "libGLES_CM.so.1" : "/opt/vc/lib/libbrcmGLESv2.so" )
    52 #define DEFAULT_OGL_ES ( vc4 ? "libGLESv1_CM.so.1" : "/opt/vc/lib/libbrcmGLESv2.so" )
    53 
    54 #elif SDL_VIDEO_DRIVER_ANDROID || SDL_VIDEO_DRIVER_VIVANTE
    55 /* Android */
    56 #define DEFAULT_EGL "libEGL.so"
    57 #define DEFAULT_OGL_ES2 "libGLESv2.so"
    58 #define DEFAULT_OGL_ES_PVR "libGLES_CM.so"
    59 #define DEFAULT_OGL_ES "libGLESv1_CM.so"
    60 
    61 #elif SDL_VIDEO_DRIVER_WINDOWS || SDL_VIDEO_DRIVER_WINRT
    62 /* EGL AND OpenGL ES support via ANGLE */
    63 #define DEFAULT_EGL "libEGL.dll"
    64 #define DEFAULT_OGL_ES2 "libGLESv2.dll"
    65 #define DEFAULT_OGL_ES_PVR "libGLES_CM.dll"
    66 #define DEFAULT_OGL_ES "libGLESv1_CM.dll"
    67 
    68 #elif SDL_VIDEO_DRIVER_COCOA
    69 /* EGL AND OpenGL ES support via ANGLE */
    70 #define DEFAULT_EGL "libEGL.dylib"
    71 #define DEFAULT_OGL_ES2 "libGLESv2.dylib"
    72 #define DEFAULT_OGL_ES_PVR "libGLES_CM.dylib"   //???
    73 #define DEFAULT_OGL_ES "libGLESv1_CM.dylib"     //???
    74 
    75 #else
    76 /* Desktop Linux */
    77 #define DEFAULT_OGL "libGL.so.1"
    78 #define DEFAULT_EGL "libEGL.so.1"
    79 #define DEFAULT_OGL_ES2 "libGLESv2.so.2"
    80 #define DEFAULT_OGL_ES_PVR "libGLES_CM.so.1"
    81 #define DEFAULT_OGL_ES "libGLESv1_CM.so.1"
    82 #endif /* SDL_VIDEO_DRIVER_RPI */
    83 
    84 #ifdef SDL_VIDEO_STATIC_ANGLE
    85 #define LOAD_FUNC(NAME) \
    86 _this->egl_data->NAME = (void *)NAME;
    87 #else
    88 #define LOAD_FUNC(NAME) \
    89 _this->egl_data->NAME = SDL_LoadFunction(_this->egl_data->dll_handle, #NAME); \
    90 if (!_this->egl_data->NAME) \
    91 { \
    92     return SDL_SetError("Could not retrieve EGL function " #NAME); \
    93 }
    94 #endif
    95 
    96 static const char * SDL_EGL_GetErrorName(EGLint eglErrorCode)
    97 {
    98 #define SDL_EGL_ERROR_TRANSLATE(e) case e: return #e;
    99     switch (eglErrorCode) {
   100         SDL_EGL_ERROR_TRANSLATE(EGL_SUCCESS);
   101         SDL_EGL_ERROR_TRANSLATE(EGL_NOT_INITIALIZED);
   102         SDL_EGL_ERROR_TRANSLATE(EGL_BAD_ACCESS);
   103         SDL_EGL_ERROR_TRANSLATE(EGL_BAD_ALLOC);
   104         SDL_EGL_ERROR_TRANSLATE(EGL_BAD_ATTRIBUTE);
   105         SDL_EGL_ERROR_TRANSLATE(EGL_BAD_CONTEXT);
   106         SDL_EGL_ERROR_TRANSLATE(EGL_BAD_CONFIG);
   107         SDL_EGL_ERROR_TRANSLATE(EGL_BAD_CURRENT_SURFACE);
   108         SDL_EGL_ERROR_TRANSLATE(EGL_BAD_DISPLAY);
   109         SDL_EGL_ERROR_TRANSLATE(EGL_BAD_SURFACE);
   110         SDL_EGL_ERROR_TRANSLATE(EGL_BAD_MATCH);
   111         SDL_EGL_ERROR_TRANSLATE(EGL_BAD_PARAMETER);
   112         SDL_EGL_ERROR_TRANSLATE(EGL_BAD_NATIVE_PIXMAP);
   113         SDL_EGL_ERROR_TRANSLATE(EGL_BAD_NATIVE_WINDOW);
   114         SDL_EGL_ERROR_TRANSLATE(EGL_CONTEXT_LOST);
   115     }
   116     return "";
   117 }
   118 
   119 int SDL_EGL_SetErrorEx(const char * message, const char * eglFunctionName, EGLint eglErrorCode)
   120 {
   121     const char * errorText = SDL_EGL_GetErrorName(eglErrorCode);
   122     char altErrorText[32];
   123     if (errorText[0] == '\0') {
   124         /* An unknown-to-SDL error code was reported.  Report its hexadecimal value, instead of its name. */
   125         SDL_snprintf(altErrorText, SDL_arraysize(altErrorText), "0x%x", (unsigned int)eglErrorCode);
   126         errorText = altErrorText;
   127     }
   128     return SDL_SetError("%s (call to %s failed, reporting an error of %s)", message, eglFunctionName, errorText);
   129 }
   130 
   131 /* EGL implementation of SDL OpenGL ES support */
   132 typedef enum {
   133     SDL_EGL_DISPLAY_EXTENSION,
   134     SDL_EGL_CLIENT_EXTENSION
   135 } SDL_EGL_ExtensionType;
   136 
   137 static SDL_bool SDL_EGL_HasExtension(_THIS, SDL_EGL_ExtensionType type, const char *ext)
   138 {
   139     size_t ext_len;
   140     const char *ext_override;
   141     const char *egl_extstr;
   142     const char *ext_start;
   143 
   144     /* Invalid extensions can be rejected early */
   145     if (ext == NULL || *ext == 0 || SDL_strchr(ext, ' ') != NULL) {
   146         /* SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "SDL_EGL_HasExtension: Invalid EGL extension"); */
   147         return SDL_FALSE;
   148     }
   149 
   150     /* Extensions can be masked with an environment variable.
   151      * Unlike the OpenGL override, this will use the set bits of an integer
   152      * to disable the extension.
   153      *  Bit   Action
   154      *  0     If set, the display extension is masked and not present to SDL.
   155      *  1     If set, the client extension is masked and not present to SDL.
   156      */
   157     ext_override = SDL_getenv(ext);
   158     if (ext_override != NULL) {
   159         int disable_ext = SDL_atoi(ext_override);
   160         if (disable_ext & 0x01 && type == SDL_EGL_DISPLAY_EXTENSION) {
   161             return SDL_FALSE;
   162         } else if (disable_ext & 0x02 && type == SDL_EGL_CLIENT_EXTENSION) {
   163             return SDL_FALSE;
   164         }
   165     }
   166 
   167     ext_len = SDL_strlen(ext);
   168     switch (type) {
   169     case SDL_EGL_DISPLAY_EXTENSION:
   170         egl_extstr = _this->egl_data->eglQueryString(_this->egl_data->egl_display, EGL_EXTENSIONS);
   171         break;
   172     case SDL_EGL_CLIENT_EXTENSION:
   173         /* EGL_EXT_client_extensions modifies eglQueryString to return client extensions
   174          * if EGL_NO_DISPLAY is passed. Implementations without it are required to return NULL.
   175          * This behavior is included in EGL 1.5.
   176          */
   177         egl_extstr = _this->egl_data->eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
   178         break;
   179     default:
   180         /* SDL_LogDebug(SDL_LOG_CATEGORY_VIDEO, "SDL_EGL_HasExtension: Invalid extension type"); */
   181         return SDL_FALSE;
   182     }
   183 
   184     if (egl_extstr != NULL) {
   185         ext_start = egl_extstr;
   186 
   187         while (*ext_start) {
   188             ext_start = SDL_strstr(ext_start, ext);
   189             if (ext_start == NULL) {
   190                 return SDL_FALSE;
   191             }
   192             /* Check if the match is not just a substring of one of the extensions */
   193             if (ext_start == egl_extstr || *(ext_start - 1) == ' ') {
   194                 if (ext_start[ext_len] == ' ' || ext_start[ext_len] == 0) {
   195                     return SDL_TRUE;
   196                 }
   197             }
   198             /* If the search stopped in the middle of an extension, skip to the end of it */
   199             ext_start += ext_len;
   200             while (*ext_start != ' ' && *ext_start != 0) {
   201                 ext_start++;
   202             }
   203         }
   204     }
   205 
   206     return SDL_FALSE;
   207 }
   208 
   209 void *
   210 SDL_EGL_GetProcAddress(_THIS, const char *proc)
   211 {
   212     static char procname[1024];
   213     void *retval;
   214     
   215     /* eglGetProcAddress is busted on Android http://code.google.com/p/android/issues/detail?id=7681 */
   216 #if !defined(SDL_VIDEO_DRIVER_ANDROID)
   217     if (_this->egl_data->eglGetProcAddress) {
   218         retval = _this->egl_data->eglGetProcAddress(proc);
   219         if (retval) {
   220             return retval;
   221         }
   222     }
   223 #endif
   224     
   225     retval = SDL_LoadFunction(_this->egl_data->egl_dll_handle, proc);
   226     if (!retval && SDL_strlen(proc) <= 1022) {
   227         procname[0] = '_';
   228         SDL_strlcpy(procname + 1, proc, 1022);
   229         retval = SDL_LoadFunction(_this->egl_data->egl_dll_handle, procname);
   230     }
   231     return retval;
   232 }
   233 
   234 void
   235 SDL_EGL_UnloadLibrary(_THIS)
   236 {
   237     if (_this->egl_data) {
   238         if (_this->egl_data->egl_display) {
   239             _this->egl_data->eglTerminate(_this->egl_data->egl_display);
   240             _this->egl_data->egl_display = NULL;
   241         }
   242 
   243         if (_this->egl_data->dll_handle) {
   244             SDL_UnloadObject(_this->egl_data->dll_handle);
   245             _this->egl_data->dll_handle = NULL;
   246         }
   247         if (_this->egl_data->egl_dll_handle) {
   248             SDL_UnloadObject(_this->egl_data->egl_dll_handle);
   249             _this->egl_data->egl_dll_handle = NULL;
   250         }
   251         
   252         SDL_free(_this->egl_data);
   253         _this->egl_data = NULL;
   254     }
   255 }
   256 
   257 int
   258 SDL_EGL_LoadLibrary(_THIS, const char *egl_path, NativeDisplayType native_display, EGLenum platform)
   259 {
   260     void *dll_handle = NULL, *egl_dll_handle = NULL; /* The naming is counter intuitive, but hey, I just work here -- Gabriel */
   261     const char *path = NULL;
   262     int egl_version_major = 0, egl_version_minor = 0;
   263 #if SDL_VIDEO_DRIVER_WINDOWS || SDL_VIDEO_DRIVER_WINRT
   264     const char *d3dcompiler;
   265 #endif
   266 #if SDL_VIDEO_DRIVER_RPI
   267     SDL_bool vc4 = (0 == access("/sys/module/vc4/", F_OK));
   268 #endif
   269 
   270     if (_this->egl_data) {
   271         return SDL_SetError("EGL context already created");
   272     }
   273 
   274     _this->egl_data = (struct SDL_EGL_VideoData *) SDL_calloc(1, sizeof(SDL_EGL_VideoData));
   275     if (!_this->egl_data) {
   276         return SDL_OutOfMemory();
   277     }
   278 
   279 #if SDL_VIDEO_DRIVER_WINDOWS || SDL_VIDEO_DRIVER_WINRT
   280     d3dcompiler = SDL_GetHint(SDL_HINT_VIDEO_WIN_D3DCOMPILER);
   281     if (!d3dcompiler) {
   282         if (WIN_IsWindowsVistaOrGreater()) {
   283             d3dcompiler = "d3dcompiler_46.dll";
   284         } else {
   285             d3dcompiler = "d3dcompiler_43.dll";
   286         }
   287     }
   288     if (SDL_strcasecmp(d3dcompiler, "none") != 0) {
   289         if (SDL_LoadObject(d3dcompiler) == NULL) {
   290             SDL_ClearError();
   291         }
   292     }
   293 #endif
   294 
   295 #ifndef SDL_VIDEO_STATIC_ANGLE
   296     /* A funny thing, loading EGL.so first does not work on the Raspberry, so we load libGL* first */
   297     path = SDL_getenv("SDL_VIDEO_GL_DRIVER");
   298     if (path != NULL) {
   299         egl_dll_handle = SDL_LoadObject(path);
   300     }
   301 
   302     if (egl_dll_handle == NULL) {
   303         if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) {
   304             if (_this->gl_config.major_version > 1) {
   305                 path = DEFAULT_OGL_ES2;
   306                 egl_dll_handle = SDL_LoadObject(path);
   307 #ifdef ALT_OGL_ES2
   308                 if (egl_dll_handle == NULL && !vc4) {
   309                     path = ALT_OGL_ES2;
   310                     egl_dll_handle = SDL_LoadObject(path);
   311                 }
   312 #endif
   313 
   314             } else {
   315                 path = DEFAULT_OGL_ES;
   316                 egl_dll_handle = SDL_LoadObject(path);
   317                 if (egl_dll_handle == NULL) {
   318                     path = DEFAULT_OGL_ES_PVR;
   319                     egl_dll_handle = SDL_LoadObject(path);
   320                 }
   321 #ifdef ALT_OGL_ES2
   322                 if (egl_dll_handle == NULL && !vc4) {
   323                     path = ALT_OGL_ES2;
   324                     egl_dll_handle = SDL_LoadObject(path);
   325                 }
   326 #endif
   327             }
   328         }
   329 #ifdef DEFAULT_OGL         
   330         else {
   331             path = DEFAULT_OGL;
   332             egl_dll_handle = SDL_LoadObject(path);
   333         }
   334 #endif        
   335     }
   336     _this->egl_data->egl_dll_handle = egl_dll_handle;
   337 
   338     if (egl_dll_handle == NULL) {
   339         return SDL_SetError("Could not initialize OpenGL / GLES library");
   340     }
   341 
   342     /* Loading libGL* in the previous step took care of loading libEGL.so, but we future proof by double checking */
   343     if (egl_path != NULL) {
   344         dll_handle = SDL_LoadObject(egl_path);
   345     }   
   346     /* Try loading a EGL symbol, if it does not work try the default library paths */
   347     if (dll_handle == NULL || SDL_LoadFunction(dll_handle, "eglChooseConfig") == NULL) {
   348         if (dll_handle != NULL) {
   349             SDL_UnloadObject(dll_handle);
   350         }
   351         path = SDL_getenv("SDL_VIDEO_EGL_DRIVER");
   352         if (path == NULL) {
   353             path = DEFAULT_EGL;
   354         }
   355         dll_handle = SDL_LoadObject(path);
   356 
   357 #ifdef ALT_EGL
   358         if (dll_handle == NULL && !vc4) {
   359             path = ALT_EGL;
   360             dll_handle = SDL_LoadObject(path);
   361         }
   362 #endif
   363 
   364         if (dll_handle == NULL || SDL_LoadFunction(dll_handle, "eglChooseConfig") == NULL) {
   365             if (dll_handle != NULL) {
   366                 SDL_UnloadObject(dll_handle);
   367             }
   368             return SDL_SetError("Could not load EGL library");
   369         }
   370         SDL_ClearError();
   371     }
   372 #endif
   373 
   374     _this->egl_data->dll_handle = dll_handle;
   375 
   376     /* Load new function pointers */
   377     LOAD_FUNC(eglGetDisplay);
   378     LOAD_FUNC(eglInitialize);
   379     LOAD_FUNC(eglTerminate);
   380     LOAD_FUNC(eglGetProcAddress);
   381     LOAD_FUNC(eglChooseConfig);
   382     LOAD_FUNC(eglGetConfigAttrib);
   383     LOAD_FUNC(eglCreateContext);
   384     LOAD_FUNC(eglDestroyContext);
   385     LOAD_FUNC(eglCreatePbufferSurface);
   386     LOAD_FUNC(eglCreateWindowSurface);
   387     LOAD_FUNC(eglDestroySurface);
   388     LOAD_FUNC(eglMakeCurrent);
   389     LOAD_FUNC(eglSwapBuffers);
   390     LOAD_FUNC(eglSwapInterval);
   391     LOAD_FUNC(eglWaitNative);
   392     LOAD_FUNC(eglWaitGL);
   393     LOAD_FUNC(eglBindAPI);
   394     LOAD_FUNC(eglQueryString);
   395     LOAD_FUNC(eglGetError);
   396 
   397     if (_this->egl_data->eglQueryString) {
   398         /* EGL 1.5 allows querying for client version */
   399         const char *egl_version = _this->egl_data->eglQueryString(EGL_NO_DISPLAY, EGL_VERSION);
   400         if (egl_version != NULL) {
   401             if (SDL_sscanf(egl_version, "%d.%d", &egl_version_major, &egl_version_minor) != 2) {
   402                 egl_version_major = 0;
   403                 egl_version_minor = 0;
   404                 SDL_LogWarn(SDL_LOG_CATEGORY_VIDEO, "Could not parse EGL version string: %s", egl_version);
   405             }
   406         }
   407     }
   408 
   409     if (egl_version_major == 1 && egl_version_minor == 5) {
   410         LOAD_FUNC(eglGetPlatformDisplay);
   411     }
   412 
   413     _this->egl_data->egl_display = EGL_NO_DISPLAY;
   414 #if !defined(__WINRT__)
   415     if (platform) {
   416         if (egl_version_major == 1 && egl_version_minor == 5) {
   417             _this->egl_data->egl_display = _this->egl_data->eglGetPlatformDisplay(platform, (void *)(size_t)native_display, NULL);
   418         } else {
   419             if (SDL_EGL_HasExtension(_this, SDL_EGL_CLIENT_EXTENSION, "EGL_EXT_platform_base")) {
   420                 _this->egl_data->eglGetPlatformDisplayEXT = SDL_EGL_GetProcAddress(_this, "eglGetPlatformDisplayEXT");
   421                 if (_this->egl_data->eglGetPlatformDisplayEXT) {
   422                     _this->egl_data->egl_display = _this->egl_data->eglGetPlatformDisplayEXT(platform, (void *)(size_t)native_display, NULL);
   423                 }
   424             }
   425         }
   426     }
   427     /* Try the implementation-specific eglGetDisplay even if eglGetPlatformDisplay fails */
   428     if (_this->egl_data->egl_display == EGL_NO_DISPLAY) {
   429         _this->egl_data->egl_display = _this->egl_data->eglGetDisplay(native_display);
   430     }
   431     if (_this->egl_data->egl_display == EGL_NO_DISPLAY) {
   432         return SDL_SetError("Could not get EGL display");
   433     }
   434     
   435     if (_this->egl_data->eglInitialize(_this->egl_data->egl_display, NULL, NULL) != EGL_TRUE) {
   436         return SDL_SetError("Could not initialize EGL");
   437     }
   438 #endif
   439 
   440     if (path) {
   441         SDL_strlcpy(_this->gl_config.driver_path, path, sizeof(_this->gl_config.driver_path) - 1);
   442     } else {
   443         *_this->gl_config.driver_path = '\0';
   444     }
   445     
   446     return 0;
   447 }
   448 
   449 int
   450 SDL_EGL_ChooseConfig(_THIS) 
   451 {
   452 /* 64 seems nice. */
   453     EGLint attribs[64];
   454     EGLint found_configs = 0, value;
   455 #ifdef SDL_VIDEO_DRIVER_KMSDRM
   456     /* Intel EGL on KMS/DRM (al least) returns invalid configs that confuse the bitdiff search used */
   457     /* later in this function, so we simply use the first one when using the KMSDRM driver for now. */
   458     EGLConfig configs[1];
   459 #else
   460     /* 128 seems even nicer here */
   461     EGLConfig configs[128];
   462 #endif
   463     int i, j, best_bitdiff = -1, bitdiff;
   464    
   465     if (!_this->egl_data) {
   466         /* The EGL library wasn't loaded, SDL_GetError() should have info */
   467         return -1;
   468     }
   469   
   470     /* Get a valid EGL configuration */
   471     i = 0;
   472     attribs[i++] = EGL_RED_SIZE;
   473     attribs[i++] = _this->gl_config.red_size;
   474     attribs[i++] = EGL_GREEN_SIZE;
   475     attribs[i++] = _this->gl_config.green_size;
   476     attribs[i++] = EGL_BLUE_SIZE;
   477     attribs[i++] = _this->gl_config.blue_size;
   478     
   479     if (_this->gl_config.alpha_size) {
   480         attribs[i++] = EGL_ALPHA_SIZE;
   481         attribs[i++] = _this->gl_config.alpha_size;
   482     }
   483     
   484     if (_this->gl_config.buffer_size) {
   485         attribs[i++] = EGL_BUFFER_SIZE;
   486         attribs[i++] = _this->gl_config.buffer_size;
   487     }
   488     
   489     attribs[i++] = EGL_DEPTH_SIZE;
   490     attribs[i++] = _this->gl_config.depth_size;
   491     
   492     if (_this->gl_config.stencil_size) {
   493         attribs[i++] = EGL_STENCIL_SIZE;
   494         attribs[i++] = _this->gl_config.stencil_size;
   495     }
   496     
   497     if (_this->gl_config.multisamplebuffers) {
   498         attribs[i++] = EGL_SAMPLE_BUFFERS;
   499         attribs[i++] = _this->gl_config.multisamplebuffers;
   500     }
   501     
   502     if (_this->gl_config.multisamplesamples) {
   503         attribs[i++] = EGL_SAMPLES;
   504         attribs[i++] = _this->gl_config.multisamplesamples;
   505     }
   506 
   507     if (_this->gl_config.framebuffer_srgb_capable) {
   508 #ifdef EGL_KHR_gl_colorspace
   509         if (SDL_EGL_HasExtension(_this, SDL_EGL_DISPLAY_EXTENSION, "EGL_KHR_gl_colorspace")) {
   510             attribs[i++] = EGL_GL_COLORSPACE_KHR;
   511             attribs[i++] = EGL_GL_COLORSPACE_SRGB_KHR;
   512         } else
   513 #endif
   514         {
   515             return SDL_SetError("EGL implementation does not support sRGB system framebuffers");
   516         }
   517     }
   518 
   519     attribs[i++] = EGL_RENDERABLE_TYPE;
   520     if (_this->gl_config.profile_mask == SDL_GL_CONTEXT_PROFILE_ES) {
   521 #ifdef EGL_KHR_create_context
   522         if (_this->gl_config.major_version >= 3 &&
   523             SDL_EGL_HasExtension(_this, SDL_EGL_DISPLAY_EXTENSION, "EGL_KHR_create_context")) {
   524             attribs[i++] = EGL_OPENGL_ES3_BIT_KHR;
   525         } else
   526 #endif
   527         if (_this->gl_config.major_version >= 2) {
   528             attribs[i++] = EGL_OPENGL_ES2_BIT;
   529         } else {
   530             attribs[i++] = EGL_OPENGL_ES_BIT;
   531         }
   532         _this->egl_data->eglBindAPI(EGL_OPENGL_ES_API);
   533     } else {
   534         attribs[i++] = EGL_OPENGL_BIT;
   535         _this->egl_data->eglBindAPI(EGL_OPENGL_API);
   536     }
   537 
   538     if (_this->egl_data->egl_surfacetype) {
   539         attribs[i++] = EGL_SURFACE_TYPE;
   540         attribs[i++] = _this->egl_data->egl_surfacetype;
   541     }
   542 
   543     attribs[i++] = EGL_NONE;
   544 
   545     if (_this->egl_data->eglChooseConfig(_this->egl_data->egl_display,
   546         attribs,
   547         configs, SDL_arraysize(configs),
   548         &found_configs) == EGL_FALSE ||
   549         found_configs == 0) {
   550         return SDL_EGL_SetError("Couldn't find matching EGL config", "eglChooseConfig");
   551     }
   552 
   553     /* eglChooseConfig returns a number of configurations that match or exceed the requested attribs. */
   554     /* From those, we select the one that matches our requirements more closely via a makeshift algorithm */
   555 
   556     for (i = 0; i < found_configs; i++ ) {
   557         bitdiff = 0;
   558         for (j = 0; j < SDL_arraysize(attribs) - 1; j += 2) {
   559             if (attribs[j] == EGL_NONE) {
   560                break;
   561             }
   562             
   563             if ( attribs[j+1] != EGL_DONT_CARE && (
   564                 attribs[j] == EGL_RED_SIZE ||
   565                 attribs[j] == EGL_GREEN_SIZE ||
   566                 attribs[j] == EGL_BLUE_SIZE ||
   567                 attribs[j] == EGL_ALPHA_SIZE ||
   568                 attribs[j] == EGL_DEPTH_SIZE ||
   569                 attribs[j] == EGL_STENCIL_SIZE)) {
   570                 _this->egl_data->eglGetConfigAttrib(_this->egl_data->egl_display, configs[i], attribs[j], &value);
   571                 bitdiff += value - attribs[j + 1]; /* value is always >= attrib */
   572             }
   573         }
   574 
   575         if (bitdiff < best_bitdiff || best_bitdiff == -1) {
   576             _this->egl_data->egl_config = configs[i];
   577             
   578             best_bitdiff = bitdiff;
   579         }
   580 
   581         if (bitdiff == 0) {
   582             break; /* we found an exact match! */
   583         }
   584     }
   585     
   586     return 0;
   587 }
   588 
   589 SDL_GLContext
   590 SDL_EGL_CreateContext(_THIS, EGLSurface egl_surface)
   591 {
   592     /* max 14 values plus terminator. */
   593     EGLint attribs[15];
   594     int attr = 0;
   595 
   596     EGLContext egl_context, share_context = EGL_NO_CONTEXT;
   597     EGLint profile_mask = _this->gl_config.profile_mask;
   598     EGLint major_version = _this->gl_config.major_version;
   599     EGLint minor_version = _this->gl_config.minor_version;
   600     SDL_bool profile_es = (profile_mask == SDL_GL_CONTEXT_PROFILE_ES);
   601 
   602     if (!_this->egl_data) {
   603         /* The EGL library wasn't loaded, SDL_GetError() should have info */
   604         return NULL;
   605     }
   606 
   607     if (_this->gl_config.share_with_current_context) {
   608         share_context = (EGLContext)SDL_GL_GetCurrentContext();
   609     }
   610 
   611     /* Set the context version and other attributes. */
   612     if ((major_version < 3 || (minor_version == 0 && profile_es)) &&
   613         _this->gl_config.flags == 0 &&
   614         (profile_mask == 0 || profile_es)) {
   615         /* Create a context without using EGL_KHR_create_context attribs.
   616          * When creating a GLES context without EGL_KHR_create_context we can
   617          * only specify the major version. When creating a desktop GL context
   618          * we can't specify any version, so we only try in that case when the
   619          * version is less than 3.0 (matches SDL's GLX/WGL behavior.)
   620          */
   621         if (profile_es) {
   622             attribs[attr++] = EGL_CONTEXT_CLIENT_VERSION;
   623             attribs[attr++] = SDL_max(major_version, 1);
   624         }
   625     } else {
   626 #ifdef EGL_KHR_create_context
   627         /* The Major/minor version, context profiles, and context flags can
   628          * only be specified when this extension is available.
   629          */
   630         if (SDL_EGL_HasExtension(_this, SDL_EGL_DISPLAY_EXTENSION, "EGL_KHR_create_context")) {
   631             attribs[attr++] = EGL_CONTEXT_MAJOR_VERSION_KHR;
   632             attribs[attr++] = major_version;
   633             attribs[attr++] = EGL_CONTEXT_MINOR_VERSION_KHR;
   634             attribs[attr++] = minor_version;
   635 
   636             /* SDL profile bits match EGL profile bits. */
   637             if (profile_mask != 0 && profile_mask != SDL_GL_CONTEXT_PROFILE_ES) {
   638                 attribs[attr++] = EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR;
   639                 attribs[attr++] = profile_mask;
   640             }
   641 
   642             /* SDL flags match EGL flags. */
   643             if (_this->gl_config.flags != 0) {
   644                 attribs[attr++] = EGL_CONTEXT_FLAGS_KHR;
   645                 attribs[attr++] = _this->gl_config.flags;
   646             }
   647         } else
   648 #endif /* EGL_KHR_create_context */
   649         {
   650             SDL_SetError("Could not create EGL context (context attributes are not supported)");
   651             return NULL;
   652         }
   653     }
   654 
   655     if (_this->gl_config.no_error) {
   656 #ifdef EGL_KHR_create_context_no_error
   657         if (SDL_EGL_HasExtension(_this, SDL_EGL_DISPLAY_EXTENSION, "EGL_KHR_create_context_no_error")) {
   658             attribs[attr++] = EGL_CONTEXT_OPENGL_NO_ERROR_KHR;
   659             attribs[attr++] = _this->gl_config.no_error;
   660         } else
   661 #endif
   662         {
   663             SDL_SetError("EGL implementation does not support no_error contexts");
   664             return NULL;
   665         }
   666     }
   667 
   668     attribs[attr++] = EGL_NONE;
   669 
   670     /* Bind the API */
   671     if (profile_es) {
   672         _this->egl_data->eglBindAPI(EGL_OPENGL_ES_API);
   673     } else {
   674         _this->egl_data->eglBindAPI(EGL_OPENGL_API);
   675     }
   676 
   677     egl_context = _this->egl_data->eglCreateContext(_this->egl_data->egl_display,
   678                                       _this->egl_data->egl_config,
   679                                       share_context, attribs);
   680 
   681     if (egl_context == EGL_NO_CONTEXT) {
   682         SDL_EGL_SetError("Could not create EGL context", "eglCreateContext");
   683         return NULL;
   684     }
   685 
   686     _this->egl_data->egl_swapinterval = 0;
   687 
   688     if (SDL_EGL_MakeCurrent(_this, egl_surface, egl_context) < 0) {
   689         /* Save the SDL error set by SDL_EGL_MakeCurrent */
   690         char errorText[1024];
   691         SDL_strlcpy(errorText, SDL_GetError(), SDL_arraysize(errorText));
   692 
   693         /* Delete the context, which may alter the value returned by SDL_GetError() */
   694         SDL_EGL_DeleteContext(_this, egl_context);
   695 
   696         /* Restore the SDL error */
   697         SDL_SetError("%s", errorText);
   698 
   699         return NULL;
   700     }
   701 
   702     return (SDL_GLContext) egl_context;
   703 }
   704 
   705 int
   706 SDL_EGL_MakeCurrent(_THIS, EGLSurface egl_surface, SDL_GLContext context)
   707 {
   708     EGLContext egl_context = (EGLContext) context;
   709 
   710     if (!_this->egl_data) {
   711         return SDL_SetError("OpenGL not initialized");
   712     }
   713     
   714     /* The android emulator crashes badly if you try to eglMakeCurrent 
   715      * with a valid context and invalid surface, so we have to check for both here.
   716      */
   717     if (!egl_context || !egl_surface) {
   718          _this->egl_data->eglMakeCurrent(_this->egl_data->egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
   719     } else {
   720         if (!_this->egl_data->eglMakeCurrent(_this->egl_data->egl_display,
   721             egl_surface, egl_surface, egl_context)) {
   722             return SDL_EGL_SetError("Unable to make EGL context current", "eglMakeCurrent");
   723         }
   724     }
   725       
   726     return 0;
   727 }
   728 
   729 int
   730 SDL_EGL_SetSwapInterval(_THIS, int interval)
   731 {
   732     EGLBoolean status;
   733     
   734     if (!_this->egl_data) {
   735         return SDL_SetError("EGL not initialized");
   736     }
   737     
   738     status = _this->egl_data->eglSwapInterval(_this->egl_data->egl_display, interval);
   739     if (status == EGL_TRUE) {
   740         _this->egl_data->egl_swapinterval = interval;
   741         return 0;
   742     }
   743     
   744     return SDL_EGL_SetError("Unable to set the EGL swap interval", "eglSwapInterval");
   745 }
   746 
   747 int
   748 SDL_EGL_GetSwapInterval(_THIS)
   749 {
   750     if (!_this->egl_data) {
   751         SDL_SetError("EGL not initialized");
   752         return 0;
   753     }
   754     
   755     return _this->egl_data->egl_swapinterval;
   756 }
   757 
   758 int
   759 SDL_EGL_SwapBuffers(_THIS, EGLSurface egl_surface)
   760 {
   761     if (!_this->egl_data->eglSwapBuffers(_this->egl_data->egl_display, egl_surface)) {
   762         return SDL_EGL_SetError("unable to show color buffer in an OS-native window", "eglSwapBuffers");
   763     }
   764     return 0;
   765 }
   766 
   767 void
   768 SDL_EGL_DeleteContext(_THIS, SDL_GLContext context)
   769 {
   770     EGLContext egl_context = (EGLContext) context;
   771 
   772     /* Clean up GLES and EGL */
   773     if (!_this->egl_data) {
   774         return;
   775     }
   776     
   777     if (egl_context != NULL && egl_context != EGL_NO_CONTEXT) {
   778         SDL_EGL_MakeCurrent(_this, NULL, NULL);
   779         _this->egl_data->eglDestroyContext(_this->egl_data->egl_display, egl_context);
   780     }
   781         
   782 }
   783 
   784 EGLSurface *
   785 SDL_EGL_CreateSurface(_THIS, NativeWindowType nw) 
   786 {
   787     EGLSurface * surface;
   788 
   789     if (SDL_EGL_ChooseConfig(_this) != 0) {
   790         return EGL_NO_SURFACE;
   791     }
   792     
   793 #if SDL_VIDEO_DRIVER_ANDROID
   794     {
   795         /* Android docs recommend doing this!
   796          * Ref: http://developer.android.com/reference/android/app/NativeActivity.html 
   797          */
   798         EGLint format;
   799         _this->egl_data->eglGetConfigAttrib(_this->egl_data->egl_display,
   800                                             _this->egl_data->egl_config, 
   801                                             EGL_NATIVE_VISUAL_ID, &format);
   802 
   803         ANativeWindow_setBuffersGeometry(nw, 0, 0, format);
   804     }
   805 #endif    
   806     
   807     surface = _this->egl_data->eglCreateWindowSurface(
   808             _this->egl_data->egl_display,
   809             _this->egl_data->egl_config,
   810             nw, NULL);
   811     if (surface == EGL_NO_SURFACE) {
   812         SDL_EGL_SetError("unable to create an EGL window surface", "eglCreateWindowSurface");
   813     }
   814     return surface;
   815 }
   816 
   817 void
   818 SDL_EGL_DestroySurface(_THIS, EGLSurface egl_surface) 
   819 {
   820     if (!_this->egl_data) {
   821         return;
   822     }
   823     
   824     if (egl_surface != EGL_NO_SURFACE) {
   825         _this->egl_data->eglDestroySurface(_this->egl_data->egl_display, egl_surface);
   826     }
   827 }
   828 
   829 #endif /* SDL_VIDEO_OPENGL_EGL */
   830 
   831 /* vi: set ts=4 sw=4 expandtab: */
   832