egl.cpp revision 56fa27572a2bbdd84a4762968327dba670fedae0
1/*
2**
3** Copyright 2007 The Android Open Source Project
4**
5** Licensed under the Apache License Version 2.0(the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing software
12** distributed under the License is distributed on an "AS IS" BASIS
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18#include <assert.h>
19#include <errno.h>
20#include <stdlib.h>
21#include <stdio.h>
22#include <string.h>
23#include <unistd.h>
24#include <fcntl.h>
25#include <sys/ioctl.h>
26#include <sys/types.h>
27#include <sys/mman.h>
28
29#include <cutils/log.h>
30#include <cutils/atomic.h>
31
32#include <utils/threads.h>
33
34#include <EGL/egl.h>
35#include <EGL/eglext.h>
36#include <GLES/gl.h>
37#include <GLES/glext.h>
38
39#include <pixelflinger/format.h>
40#include <pixelflinger/pixelflinger.h>
41
42#include <private/ui/android_natives_priv.h>
43
44#include <hardware/copybit.h>
45
46#include "context.h"
47#include "state.h"
48#include "texture.h"
49#include "matrix.h"
50
51#undef NELEM
52#define NELEM(x) (sizeof(x)/sizeof(*(x)))
53
54// ----------------------------------------------------------------------------
55namespace android {
56// ----------------------------------------------------------------------------
57
58const unsigned int NUM_DISPLAYS = 1;
59
60static pthread_mutex_t gInitMutex = PTHREAD_MUTEX_INITIALIZER;
61static pthread_mutex_t gErrorKeyMutex = PTHREAD_MUTEX_INITIALIZER;
62static pthread_key_t gEGLErrorKey = -1;
63#ifndef HAVE_ANDROID_OS
64namespace gl {
65pthread_key_t gGLKey = -1;
66}; // namespace gl
67#endif
68
69template<typename T>
70static T setError(GLint error, T returnValue) {
71    if (ggl_unlikely(gEGLErrorKey == -1)) {
72        pthread_mutex_lock(&gErrorKeyMutex);
73        if (gEGLErrorKey == -1)
74            pthread_key_create(&gEGLErrorKey, NULL);
75        pthread_mutex_unlock(&gErrorKeyMutex);
76    }
77    pthread_setspecific(gEGLErrorKey, (void*)error);
78    return returnValue;
79}
80
81static GLint getError() {
82    if (ggl_unlikely(gEGLErrorKey == -1))
83        return EGL_SUCCESS;
84    GLint error = (GLint)pthread_getspecific(gEGLErrorKey);
85    pthread_setspecific(gEGLErrorKey, (void*)EGL_SUCCESS);
86    return error;
87}
88
89// ----------------------------------------------------------------------------
90
91struct egl_display_t
92{
93    egl_display_t() : type(0), initialized(0) { }
94
95    static egl_display_t& get_display(EGLDisplay dpy);
96
97    static EGLBoolean is_valid(EGLDisplay dpy) {
98        return ((uintptr_t(dpy)-1U) >= NUM_DISPLAYS) ? EGL_FALSE : EGL_TRUE;
99    }
100
101    NativeDisplayType   type;
102    volatile int32_t    initialized;
103};
104
105static egl_display_t gDisplays[NUM_DISPLAYS];
106
107egl_display_t& egl_display_t::get_display(EGLDisplay dpy) {
108    return gDisplays[uintptr_t(dpy)-1U];
109}
110
111struct egl_context_t {
112    enum {
113        IS_CURRENT      =   0x00010000,
114        NEVER_CURRENT   =   0x00020000
115    };
116    uint32_t            flags;
117    EGLDisplay          dpy;
118    EGLConfig           config;
119    EGLSurface          read;
120    EGLSurface          draw;
121
122    static inline egl_context_t* context(EGLContext ctx) {
123        ogles_context_t* const gl = static_cast<ogles_context_t*>(ctx);
124        return static_cast<egl_context_t*>(gl->rasterizer.base);
125    }
126};
127
128// ----------------------------------------------------------------------------
129
130struct egl_surface_t
131{
132    enum {
133        PAGE_FLIP = 0x00000001,
134        MAGIC     = 0x31415265
135    };
136
137    uint32_t            magic;
138    EGLDisplay          dpy;
139    EGLConfig           config;
140    EGLContext          ctx;
141
142                egl_surface_t(EGLDisplay dpy, EGLConfig config, int32_t depthFormat);
143    virtual     ~egl_surface_t();
144                bool    isValid() const;
145    virtual     bool    initCheck() const = 0;
146
147    virtual     EGLBoolean  bindDrawSurface(ogles_context_t* gl) = 0;
148    virtual     EGLBoolean  bindReadSurface(ogles_context_t* gl) = 0;
149    virtual     EGLBoolean  connect() { return EGL_TRUE; }
150    virtual     void        disconnect() {}
151    virtual     EGLint      getWidth() const = 0;
152    virtual     EGLint      getHeight() const = 0;
153
154    virtual     EGLint      getHorizontalResolution() const;
155    virtual     EGLint      getVerticalResolution() const;
156    virtual     EGLint      getRefreshRate() const;
157    virtual     EGLint      getSwapBehavior() const;
158    virtual     EGLBoolean  swapBuffers();
159    virtual     EGLBoolean  setSwapRectangle(EGLint l, EGLint t, EGLint w, EGLint h);
160    virtual     EGLClientBuffer getRenderBuffer() const;
161protected:
162    GGLSurface              depth;
163};
164
165egl_surface_t::egl_surface_t(EGLDisplay dpy,
166        EGLConfig config,
167        int32_t depthFormat)
168    : magic(MAGIC), dpy(dpy), config(config), ctx(0)
169{
170    depth.version = sizeof(GGLSurface);
171    depth.data = 0;
172    depth.format = depthFormat;
173}
174egl_surface_t::~egl_surface_t()
175{
176    magic = 0;
177    free(depth.data);
178}
179bool egl_surface_t::isValid() const {
180    LOGE_IF(magic != MAGIC, "invalid EGLSurface (%p)", this);
181    return magic == MAGIC;
182}
183
184EGLBoolean egl_surface_t::swapBuffers() {
185    return EGL_FALSE;
186}
187EGLint egl_surface_t::getHorizontalResolution() const {
188    return (0 * EGL_DISPLAY_SCALING) * (1.0f / 25.4f);
189}
190EGLint egl_surface_t::getVerticalResolution() const {
191    return (0 * EGL_DISPLAY_SCALING) * (1.0f / 25.4f);
192}
193EGLint egl_surface_t::getRefreshRate() const {
194    return (60 * EGL_DISPLAY_SCALING);
195}
196EGLint egl_surface_t::getSwapBehavior() const {
197    return EGL_BUFFER_PRESERVED;
198}
199EGLBoolean egl_surface_t::setSwapRectangle(
200        EGLint l, EGLint t, EGLint w, EGLint h)
201{
202    return EGL_FALSE;
203}
204EGLClientBuffer egl_surface_t::getRenderBuffer() const {
205    return 0;
206}
207
208// ----------------------------------------------------------------------------
209
210struct egl_window_surface_v2_t : public egl_surface_t
211{
212    egl_window_surface_v2_t(
213            EGLDisplay dpy, EGLConfig config,
214            int32_t depthFormat,
215            android_native_window_t* window);
216
217    ~egl_window_surface_v2_t();
218
219    virtual     bool        initCheck() const { return true; } // TODO: report failure if ctor fails
220    virtual     EGLBoolean  swapBuffers();
221    virtual     EGLBoolean  bindDrawSurface(ogles_context_t* gl);
222    virtual     EGLBoolean  bindReadSurface(ogles_context_t* gl);
223    virtual     EGLBoolean  connect();
224    virtual     void        disconnect();
225    virtual     EGLint      getWidth() const    { return width;  }
226    virtual     EGLint      getHeight() const   { return height; }
227    virtual     EGLint      getHorizontalResolution() const;
228    virtual     EGLint      getVerticalResolution() const;
229    virtual     EGLint      getRefreshRate() const;
230    virtual     EGLint      getSwapBehavior() const;
231    virtual     EGLBoolean  setSwapRectangle(EGLint l, EGLint t, EGLint w, EGLint h);
232    virtual     EGLClientBuffer  getRenderBuffer() const;
233
234private:
235    status_t lock(android_native_buffer_t* buf, int usage, void** vaddr);
236    status_t unlock(android_native_buffer_t* buf);
237    android_native_window_t*   nativeWindow;
238    android_native_buffer_t*   buffer;
239    android_native_buffer_t*   previousBuffer;
240    gralloc_module_t const*    module;
241    copybit_device_t*          blitengine;
242    int width;
243    int height;
244    void* bits;
245    GGLFormat const* pixelFormatTable;
246
247    struct Rect {
248        inline Rect() { };
249        inline Rect(int32_t w, int32_t h)
250            : left(0), top(0), right(w), bottom(h) { }
251        inline Rect(int32_t l, int32_t t, int32_t r, int32_t b)
252            : left(l), top(t), right(r), bottom(b) { }
253        Rect& andSelf(const Rect& r) {
254            left   = max(left, r.left);
255            top    = max(top, r.top);
256            right  = min(right, r.right);
257            bottom = min(bottom, r.bottom);
258            return *this;
259        }
260        bool isEmpty() const {
261            return (left>=right || top>=bottom);
262        }
263        void dump(char const* what) {
264            LOGD("%s { %5d, %5d, w=%5d, h=%5d }",
265                    what, left, top, right-left, bottom-top);
266        }
267
268        int32_t left;
269        int32_t top;
270        int32_t right;
271        int32_t bottom;
272    };
273
274    struct Region {
275        inline Region() : count(0) { }
276        typedef Rect const* const_iterator;
277        const_iterator begin() const { return storage; }
278        const_iterator end() const { return storage+count; }
279        static Region subtract(const Rect& lhs, const Rect& rhs) {
280            Region reg;
281            Rect* storage = reg.storage;
282            if (!lhs.isEmpty()) {
283                if (lhs.top < rhs.top) { // top rect
284                    storage->left   = lhs.left;
285                    storage->top    = lhs.top;
286                    storage->right  = lhs.right;
287                    storage->bottom = rhs.top;
288                    storage++;
289                }
290                const int32_t top = max(lhs.top, rhs.top);
291                const int32_t bot = min(lhs.bottom, rhs.bottom);
292                if (top < bot) {
293                    if (lhs.left < rhs.left) { // left-side rect
294                        storage->left   = lhs.left;
295                        storage->top    = top;
296                        storage->right  = rhs.left;
297                        storage->bottom = bot;
298                        storage++;
299                    }
300                    if (lhs.right > rhs.right) { // right-side rect
301                        storage->left   = rhs.right;
302                        storage->top    = top;
303                        storage->right  = lhs.right;
304                        storage->bottom = bot;
305                        storage++;
306                    }
307                }
308                if (lhs.bottom > rhs.bottom) { // bottom rect
309                    storage->left   = lhs.left;
310                    storage->top    = rhs.bottom;
311                    storage->right  = lhs.right;
312                    storage->bottom = lhs.bottom;
313                    storage++;
314                }
315                reg.count = storage - reg.storage;
316            }
317            return reg;
318        }
319        bool isEmpty() const {
320            return count<=0;
321        }
322    private:
323        Rect storage[4];
324        ssize_t count;
325    };
326
327    struct region_iterator : public copybit_region_t {
328        region_iterator(const Region& region)
329            : b(region.begin()), e(region.end()) {
330            this->next = iterate;
331        }
332    private:
333        static int iterate(copybit_region_t const * self, copybit_rect_t* rect) {
334            region_iterator const* me = static_cast<region_iterator const*>(self);
335            if (me->b != me->e) {
336                *reinterpret_cast<Rect*>(rect) = *me->b++;
337                return 1;
338            }
339            return 0;
340        }
341        mutable Region::const_iterator b;
342        Region::const_iterator const e;
343    };
344
345    void copyBlt(
346            android_native_buffer_t* dst, void* dst_vaddr,
347            android_native_buffer_t* src, void const* src_vaddr,
348            const Region& clip);
349
350    Rect dirtyRegion;
351    Rect oldDirtyRegion;
352};
353
354egl_window_surface_v2_t::egl_window_surface_v2_t(EGLDisplay dpy,
355        EGLConfig config,
356        int32_t depthFormat,
357        android_native_window_t* window)
358    : egl_surface_t(dpy, config, depthFormat),
359    nativeWindow(window), buffer(0), previousBuffer(0), module(0),
360    blitengine(0), bits(NULL)
361{
362    hw_module_t const* pModule;
363    hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &pModule);
364    module = reinterpret_cast<gralloc_module_t const*>(pModule);
365
366    if (hw_get_module(COPYBIT_HARDWARE_MODULE_ID, &pModule) == 0) {
367        copybit_open(pModule, &blitengine);
368    }
369
370    pixelFormatTable = gglGetPixelFormatTable();
371
372    // keep a reference on the window
373    nativeWindow->common.incRef(&nativeWindow->common);
374    nativeWindow->query(nativeWindow, NATIVE_WINDOW_WIDTH, &width);
375    nativeWindow->query(nativeWindow, NATIVE_WINDOW_HEIGHT, &height);
376}
377
378egl_window_surface_v2_t::~egl_window_surface_v2_t() {
379    if (buffer) {
380        buffer->common.decRef(&buffer->common);
381    }
382    if (previousBuffer) {
383        previousBuffer->common.decRef(&previousBuffer->common);
384    }
385    nativeWindow->common.decRef(&nativeWindow->common);
386    if (blitengine) {
387        copybit_close(blitengine);
388    }
389}
390
391EGLBoolean egl_window_surface_v2_t::connect()
392{
393    // we're intending to do software rendering
394    native_window_set_usage(nativeWindow,
395            GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
396
397    // dequeue a buffer
398    if (nativeWindow->dequeueBuffer(nativeWindow, &buffer) != NO_ERROR) {
399        return setError(EGL_BAD_ALLOC, EGL_FALSE);
400    }
401
402    // allocate a corresponding depth-buffer
403    width = buffer->width;
404    height = buffer->height;
405    if (depth.format) {
406        depth.width   = width;
407        depth.height  = height;
408        depth.stride  = depth.width; // use the width here
409        depth.data    = (GGLubyte*)malloc(depth.stride*depth.height*2);
410        if (depth.data == 0) {
411            return setError(EGL_BAD_ALLOC, EGL_FALSE);
412        }
413    }
414
415    // keep a reference on the buffer
416    buffer->common.incRef(&buffer->common);
417
418    // Lock the buffer
419    nativeWindow->lockBuffer(nativeWindow, buffer);
420    // pin the buffer down
421    if (lock(buffer, GRALLOC_USAGE_SW_READ_OFTEN |
422            GRALLOC_USAGE_SW_WRITE_OFTEN, &bits) != NO_ERROR) {
423        LOGE("connect() failed to lock buffer %p (%ux%u)",
424                buffer, buffer->width, buffer->height);
425        return setError(EGL_BAD_ACCESS, EGL_FALSE);
426        // FIXME: we should make sure we're not accessing the buffer anymore
427    }
428    return EGL_TRUE;
429}
430
431void egl_window_surface_v2_t::disconnect()
432{
433    if (buffer && bits) {
434        bits = NULL;
435        unlock(buffer);
436    }
437    // enqueue the last frame
438    nativeWindow->queueBuffer(nativeWindow, buffer);
439    if (buffer) {
440        buffer->common.decRef(&buffer->common);
441        buffer = 0;
442    }
443    if (previousBuffer) {
444        previousBuffer->common.decRef(&previousBuffer->common);
445        previousBuffer = 0;
446    }
447}
448
449status_t egl_window_surface_v2_t::lock(
450        android_native_buffer_t* buf, int usage, void** vaddr)
451{
452    int err = module->lock(module, buf->handle,
453            usage, 0, 0, buf->width, buf->height, vaddr);
454    return err;
455}
456
457status_t egl_window_surface_v2_t::unlock(android_native_buffer_t* buf)
458{
459    if (!buf) return BAD_VALUE;
460    int err = module->unlock(module, buf->handle);
461    return err;
462}
463
464void egl_window_surface_v2_t::copyBlt(
465        android_native_buffer_t* dst, void* dst_vaddr,
466        android_native_buffer_t* src, void const* src_vaddr,
467        const Region& clip)
468{
469    // FIXME: use copybit if possible
470    // NOTE: dst and src must be the same format
471
472    status_t err = NO_ERROR;
473    copybit_device_t* const copybit = blitengine;
474    if (copybit)  {
475        copybit_image_t simg;
476        simg.w = src->width;
477        simg.h = src->height;
478        simg.format = src->format;
479        simg.handle = const_cast<native_handle_t*>(src->handle);
480
481        copybit_image_t dimg;
482        dimg.w = dst->width;
483        dimg.h = dst->height;
484        dimg.format = dst->format;
485        dimg.handle = const_cast<native_handle_t*>(dst->handle);
486
487        copybit->set_parameter(copybit, COPYBIT_TRANSFORM, 0);
488        copybit->set_parameter(copybit, COPYBIT_PLANE_ALPHA, 255);
489        copybit->set_parameter(copybit, COPYBIT_DITHER, COPYBIT_DISABLE);
490        region_iterator it(clip);
491        err = copybit->blit(copybit, &dimg, &simg, &it);
492        if (err != NO_ERROR) {
493            LOGE("copybit failed (%s)", strerror(err));
494        }
495    }
496
497    if (!copybit || err) {
498        Region::const_iterator cur = clip.begin();
499        Region::const_iterator end = clip.end();
500
501        const size_t bpp = pixelFormatTable[src->format].size;
502        const size_t dbpr = dst->stride * bpp;
503        const size_t sbpr = src->stride * bpp;
504
505        uint8_t const * const src_bits = (uint8_t const *)src_vaddr;
506        uint8_t       * const dst_bits = (uint8_t       *)dst_vaddr;
507
508        while (cur != end) {
509            const Rect& r(*cur++);
510            ssize_t w = r.right - r.left;
511            ssize_t h = r.bottom - r.top;
512            if (w <= 0 || h<=0) continue;
513            size_t size = w * bpp;
514            uint8_t const * s = src_bits + (r.left + src->stride * r.top) * bpp;
515            uint8_t       * d = dst_bits + (r.left + dst->stride * r.top) * bpp;
516            if (dbpr==sbpr && size==sbpr) {
517                size *= h;
518                h = 1;
519            }
520            do {
521                memcpy(d, s, size);
522                d += dbpr;
523                s += sbpr;
524            } while (--h > 0);
525        }
526    }
527}
528
529EGLBoolean egl_window_surface_v2_t::swapBuffers()
530{
531    if (!buffer) {
532        return setError(EGL_BAD_ACCESS, EGL_FALSE);
533    }
534
535    /*
536     * Handle eglSetSwapRectangleANDROID()
537     * We copyback from the front buffer
538     */
539    if (!dirtyRegion.isEmpty()) {
540        dirtyRegion.andSelf(Rect(buffer->width, buffer->height));
541        if (previousBuffer) {
542            const Region copyBack(Region::subtract(oldDirtyRegion, dirtyRegion));
543            if (!copyBack.isEmpty()) {
544                void* prevBits;
545                if (lock(previousBuffer,
546                        GRALLOC_USAGE_SW_READ_OFTEN, &prevBits) == NO_ERROR) {
547                    // copy from previousBuffer to buffer
548                    copyBlt(buffer, bits, previousBuffer, prevBits, copyBack);
549                    unlock(previousBuffer);
550                }
551            }
552        }
553        oldDirtyRegion = dirtyRegion;
554    }
555
556    if (previousBuffer) {
557        previousBuffer->common.decRef(&previousBuffer->common);
558        previousBuffer = 0;
559    }
560
561    unlock(buffer);
562    previousBuffer = buffer;
563    nativeWindow->queueBuffer(nativeWindow, buffer);
564    buffer = 0;
565
566    // dequeue a new buffer
567    nativeWindow->dequeueBuffer(nativeWindow, &buffer);
568
569    // TODO: lockBuffer should rather be executed when the very first
570    // direct rendering occurs.
571    nativeWindow->lockBuffer(nativeWindow, buffer);
572
573    // reallocate the depth-buffer if needed
574    if ((width != buffer->width) || (height != buffer->height)) {
575        // TODO: we probably should reset the swap rect here
576        // if the window size has changed
577        width = buffer->width;
578        height = buffer->height;
579        if (depth.data) {
580            free(depth.data);
581            depth.width   = width;
582            depth.height  = height;
583            depth.stride  = buffer->stride;
584            depth.data    = (GGLubyte*)malloc(depth.stride*depth.height*2);
585            if (depth.data == 0) {
586                setError(EGL_BAD_ALLOC, EGL_FALSE);
587                return EGL_FALSE;
588            }
589        }
590    }
591
592    // keep a reference on the buffer
593    buffer->common.incRef(&buffer->common);
594
595    // finally pin the buffer down
596    if (lock(buffer, GRALLOC_USAGE_SW_READ_OFTEN |
597            GRALLOC_USAGE_SW_WRITE_OFTEN, &bits) != NO_ERROR) {
598        LOGE("eglSwapBuffers() failed to lock buffer %p (%ux%u)",
599                buffer, buffer->width, buffer->height);
600        return setError(EGL_BAD_ACCESS, EGL_FALSE);
601        // FIXME: we should make sure we're not accessing the buffer anymore
602    }
603
604    return EGL_TRUE;
605}
606
607EGLBoolean egl_window_surface_v2_t::setSwapRectangle(
608        EGLint l, EGLint t, EGLint w, EGLint h)
609{
610    dirtyRegion = Rect(l, t, l+w, t+h);
611    return EGL_TRUE;
612}
613
614EGLClientBuffer egl_window_surface_v2_t::getRenderBuffer() const
615{
616    return buffer;
617}
618
619#ifdef LIBAGL_USE_GRALLOC_COPYBITS
620
621static bool supportedCopybitsDestinationFormat(int format) {
622    // Hardware supported
623    switch (format) {
624    case HAL_PIXEL_FORMAT_RGB_565:
625    case HAL_PIXEL_FORMAT_RGBA_8888:
626    case HAL_PIXEL_FORMAT_RGBA_4444:
627    case HAL_PIXEL_FORMAT_RGBA_5551:
628    case HAL_PIXEL_FORMAT_BGRA_8888:
629        return true;
630    }
631    return false;
632}
633#endif
634
635EGLBoolean egl_window_surface_v2_t::bindDrawSurface(ogles_context_t* gl)
636{
637    GGLSurface buffer;
638    buffer.version = sizeof(GGLSurface);
639    buffer.width   = this->buffer->width;
640    buffer.height  = this->buffer->height;
641    buffer.stride  = this->buffer->stride;
642    buffer.data    = (GGLubyte*)bits;
643    buffer.format  = this->buffer->format;
644    gl->rasterizer.procs.colorBuffer(gl, &buffer);
645    if (depth.data != gl->rasterizer.state.buffers.depth.data)
646        gl->rasterizer.procs.depthBuffer(gl, &depth);
647
648#ifdef LIBAGL_USE_GRALLOC_COPYBITS
649    gl->copybits.drawSurfaceBuffer = 0;
650    if (gl->copybits.blitEngine != NULL) {
651        if (supportedCopybitsDestinationFormat(buffer.format)) {
652            buffer_handle_t handle = this->buffer->handle;
653            if (handle != NULL) {
654                gl->copybits.drawSurfaceBuffer = handle;
655            }
656        }
657    }
658#endif // LIBAGL_USE_GRALLOC_COPYBITS
659
660    return EGL_TRUE;
661}
662EGLBoolean egl_window_surface_v2_t::bindReadSurface(ogles_context_t* gl)
663{
664    GGLSurface buffer;
665    buffer.version = sizeof(GGLSurface);
666    buffer.width   = this->buffer->width;
667    buffer.height  = this->buffer->height;
668    buffer.stride  = this->buffer->stride;
669    buffer.data    = (GGLubyte*)bits; // FIXME: hopefully is is LOCKED!!!
670    buffer.format  = this->buffer->format;
671    gl->rasterizer.procs.readBuffer(gl, &buffer);
672    return EGL_TRUE;
673}
674EGLint egl_window_surface_v2_t::getHorizontalResolution() const {
675    return (nativeWindow->xdpi * EGL_DISPLAY_SCALING) * (1.0f / 25.4f);
676}
677EGLint egl_window_surface_v2_t::getVerticalResolution() const {
678    return (nativeWindow->ydpi * EGL_DISPLAY_SCALING) * (1.0f / 25.4f);
679}
680EGLint egl_window_surface_v2_t::getRefreshRate() const {
681    return (60 * EGL_DISPLAY_SCALING); // FIXME
682}
683EGLint egl_window_surface_v2_t::getSwapBehavior() const
684{
685    /*
686     * EGL_BUFFER_PRESERVED means that eglSwapBuffers() completely preserves
687     * the content of the swapped buffer.
688     *
689     * EGL_BUFFER_DESTROYED means that the content of the buffer is lost.
690     *
691     * However when ANDROID_swap_retcangle is supported, EGL_BUFFER_DESTROYED
692     * only applies to the area specified by eglSetSwapRectangleANDROID(), that
693     * is, everything outside of this area is preserved.
694     *
695     * This implementation of EGL assumes the later case.
696     *
697     */
698
699    return EGL_BUFFER_DESTROYED;
700}
701
702// ----------------------------------------------------------------------------
703
704struct egl_pixmap_surface_t : public egl_surface_t
705{
706    egl_pixmap_surface_t(
707            EGLDisplay dpy, EGLConfig config,
708            int32_t depthFormat,
709            egl_native_pixmap_t const * pixmap);
710
711    virtual ~egl_pixmap_surface_t() { }
712
713    virtual     bool        initCheck() const { return !depth.format || depth.data!=0; }
714    virtual     EGLBoolean  bindDrawSurface(ogles_context_t* gl);
715    virtual     EGLBoolean  bindReadSurface(ogles_context_t* gl);
716    virtual     EGLint      getWidth() const    { return nativePixmap.width;  }
717    virtual     EGLint      getHeight() const   { return nativePixmap.height; }
718private:
719    egl_native_pixmap_t     nativePixmap;
720};
721
722egl_pixmap_surface_t::egl_pixmap_surface_t(EGLDisplay dpy,
723        EGLConfig config,
724        int32_t depthFormat,
725        egl_native_pixmap_t const * pixmap)
726    : egl_surface_t(dpy, config, depthFormat), nativePixmap(*pixmap)
727{
728    if (depthFormat) {
729        depth.width   = pixmap->width;
730        depth.height  = pixmap->height;
731        depth.stride  = depth.width; // use the width here
732        depth.data    = (GGLubyte*)malloc(depth.stride*depth.height*2);
733        if (depth.data == 0) {
734            setError(EGL_BAD_ALLOC, EGL_NO_SURFACE);
735        }
736    }
737}
738EGLBoolean egl_pixmap_surface_t::bindDrawSurface(ogles_context_t* gl)
739{
740    GGLSurface buffer;
741    buffer.version = sizeof(GGLSurface);
742    buffer.width   = nativePixmap.width;
743    buffer.height  = nativePixmap.height;
744    buffer.stride  = nativePixmap.stride;
745    buffer.data    = nativePixmap.data;
746    buffer.format  = nativePixmap.format;
747
748    gl->rasterizer.procs.colorBuffer(gl, &buffer);
749    if (depth.data != gl->rasterizer.state.buffers.depth.data)
750        gl->rasterizer.procs.depthBuffer(gl, &depth);
751    return EGL_TRUE;
752}
753EGLBoolean egl_pixmap_surface_t::bindReadSurface(ogles_context_t* gl)
754{
755    GGLSurface buffer;
756    buffer.version = sizeof(GGLSurface);
757    buffer.width   = nativePixmap.width;
758    buffer.height  = nativePixmap.height;
759    buffer.stride  = nativePixmap.stride;
760    buffer.data    = nativePixmap.data;
761    buffer.format  = nativePixmap.format;
762    gl->rasterizer.procs.readBuffer(gl, &buffer);
763    return EGL_TRUE;
764}
765
766// ----------------------------------------------------------------------------
767
768struct egl_pbuffer_surface_t : public egl_surface_t
769{
770    egl_pbuffer_surface_t(
771            EGLDisplay dpy, EGLConfig config, int32_t depthFormat,
772            int32_t w, int32_t h, int32_t f);
773
774    virtual ~egl_pbuffer_surface_t();
775
776    virtual     bool        initCheck() const   { return pbuffer.data != 0; }
777    virtual     EGLBoolean  bindDrawSurface(ogles_context_t* gl);
778    virtual     EGLBoolean  bindReadSurface(ogles_context_t* gl);
779    virtual     EGLint      getWidth() const    { return pbuffer.width;  }
780    virtual     EGLint      getHeight() const   { return pbuffer.height; }
781private:
782    GGLSurface  pbuffer;
783};
784
785egl_pbuffer_surface_t::egl_pbuffer_surface_t(EGLDisplay dpy,
786        EGLConfig config, int32_t depthFormat,
787        int32_t w, int32_t h, int32_t f)
788    : egl_surface_t(dpy, config, depthFormat)
789{
790    size_t size = w*h;
791    switch (f) {
792        case GGL_PIXEL_FORMAT_A_8:          size *= 1; break;
793        case GGL_PIXEL_FORMAT_RGB_565:      size *= 2; break;
794        case GGL_PIXEL_FORMAT_RGBA_8888:    size *= 4; break;
795        default:
796            LOGE("incompatible pixel format for pbuffer (format=%d)", f);
797            pbuffer.data = 0;
798            break;
799    }
800    pbuffer.version = sizeof(GGLSurface);
801    pbuffer.width   = w;
802    pbuffer.height  = h;
803    pbuffer.stride  = w;
804    pbuffer.data    = (GGLubyte*)malloc(size);
805    pbuffer.format  = f;
806
807    if (depthFormat) {
808        depth.width   = pbuffer.width;
809        depth.height  = pbuffer.height;
810        depth.stride  = depth.width; // use the width here
811        depth.data    = (GGLubyte*)malloc(depth.stride*depth.height*2);
812        if (depth.data == 0) {
813            setError(EGL_BAD_ALLOC, EGL_NO_SURFACE);
814            return;
815        }
816    }
817}
818egl_pbuffer_surface_t::~egl_pbuffer_surface_t() {
819    free(pbuffer.data);
820}
821EGLBoolean egl_pbuffer_surface_t::bindDrawSurface(ogles_context_t* gl)
822{
823    gl->rasterizer.procs.colorBuffer(gl, &pbuffer);
824    if (depth.data != gl->rasterizer.state.buffers.depth.data)
825        gl->rasterizer.procs.depthBuffer(gl, &depth);
826    return EGL_TRUE;
827}
828EGLBoolean egl_pbuffer_surface_t::bindReadSurface(ogles_context_t* gl)
829{
830    gl->rasterizer.procs.readBuffer(gl, &pbuffer);
831    return EGL_TRUE;
832}
833
834// ----------------------------------------------------------------------------
835
836struct config_pair_t {
837    GLint key;
838    GLint value;
839};
840
841struct configs_t {
842    const config_pair_t* array;
843    int                  size;
844};
845
846struct config_management_t {
847    GLint key;
848    bool (*match)(GLint reqValue, GLint confValue);
849    static bool atLeast(GLint reqValue, GLint confValue) {
850        return (reqValue == EGL_DONT_CARE) || (confValue >= reqValue);
851    }
852    static bool exact(GLint reqValue, GLint confValue) {
853        return (reqValue == EGL_DONT_CARE) || (confValue == reqValue);
854    }
855    static bool mask(GLint reqValue, GLint confValue) {
856        return (confValue & reqValue) == reqValue;
857    }
858};
859
860// ----------------------------------------------------------------------------
861
862#define VERSION_MAJOR 1
863#define VERSION_MINOR 2
864static char const * const gVendorString     = "Google Inc.";
865static char const * const gVersionString    = "1.2 Android Driver";
866static char const * const gClientApiString  = "OpenGL ES";
867static char const * const gExtensionsString =
868        "EGL_KHR_image_base "
869        // "KHR_image_pixmap "
870        "EGL_ANDROID_image_native_buffer "
871        "EGL_ANDROID_swap_rectangle "
872        "EGL_ANDROID_get_render_buffer "
873        ;
874
875// ----------------------------------------------------------------------------
876
877struct extention_map_t {
878    const char * const name;
879    __eglMustCastToProperFunctionPointerType address;
880};
881
882static const extention_map_t gExtentionMap[] = {
883    { "glDrawTexsOES",
884            (__eglMustCastToProperFunctionPointerType)&glDrawTexsOES },
885    { "glDrawTexiOES",
886            (__eglMustCastToProperFunctionPointerType)&glDrawTexiOES },
887    { "glDrawTexfOES",
888            (__eglMustCastToProperFunctionPointerType)&glDrawTexfOES },
889    { "glDrawTexxOES",
890            (__eglMustCastToProperFunctionPointerType)&glDrawTexxOES },
891    { "glDrawTexsvOES",
892            (__eglMustCastToProperFunctionPointerType)&glDrawTexsvOES },
893    { "glDrawTexivOES",
894            (__eglMustCastToProperFunctionPointerType)&glDrawTexivOES },
895    { "glDrawTexfvOES",
896            (__eglMustCastToProperFunctionPointerType)&glDrawTexfvOES },
897    { "glDrawTexxvOES",
898            (__eglMustCastToProperFunctionPointerType)&glDrawTexxvOES },
899    { "glQueryMatrixxOES",
900            (__eglMustCastToProperFunctionPointerType)&glQueryMatrixxOES },
901    { "glEGLImageTargetTexture2DOES",
902            (__eglMustCastToProperFunctionPointerType)&glEGLImageTargetTexture2DOES },
903    { "glEGLImageTargetRenderbufferStorageOES",
904            (__eglMustCastToProperFunctionPointerType)&glEGLImageTargetRenderbufferStorageOES },
905    { "glClipPlanef",
906            (__eglMustCastToProperFunctionPointerType)&glClipPlanef },
907    { "glClipPlanex",
908            (__eglMustCastToProperFunctionPointerType)&glClipPlanex },
909    { "glBindBuffer",
910            (__eglMustCastToProperFunctionPointerType)&glBindBuffer },
911    { "glBufferData",
912            (__eglMustCastToProperFunctionPointerType)&glBufferData },
913    { "glBufferSubData",
914            (__eglMustCastToProperFunctionPointerType)&glBufferSubData },
915    { "glDeleteBuffers",
916            (__eglMustCastToProperFunctionPointerType)&glDeleteBuffers },
917    { "glGenBuffers",
918            (__eglMustCastToProperFunctionPointerType)&glGenBuffers },
919    { "eglCreateImageKHR",
920            (__eglMustCastToProperFunctionPointerType)&eglCreateImageKHR },
921    { "eglDestroyImageKHR",
922            (__eglMustCastToProperFunctionPointerType)&eglDestroyImageKHR },
923    { "eglSetSwapRectangleANDROID",
924            (__eglMustCastToProperFunctionPointerType)&eglSetSwapRectangleANDROID },
925    { "eglGetRenderBufferANDROID",
926            (__eglMustCastToProperFunctionPointerType)&eglGetRenderBufferANDROID },
927};
928
929/*
930 * In the lists below, attributes names MUST be sorted.
931 * Additionally, all configs must be sorted according to
932 * the EGL specification.
933 */
934
935static config_pair_t const config_base_attribute_list[] = {
936        { EGL_STENCIL_SIZE,               0                                 },
937        { EGL_CONFIG_CAVEAT,              EGL_SLOW_CONFIG                   },
938        { EGL_LEVEL,                      0                                 },
939        { EGL_MAX_PBUFFER_HEIGHT,         GGL_MAX_VIEWPORT_DIMS             },
940        { EGL_MAX_PBUFFER_PIXELS,
941                GGL_MAX_VIEWPORT_DIMS*GGL_MAX_VIEWPORT_DIMS                 },
942        { EGL_MAX_PBUFFER_WIDTH,          GGL_MAX_VIEWPORT_DIMS             },
943        { EGL_NATIVE_RENDERABLE,          EGL_TRUE                          },
944        { EGL_NATIVE_VISUAL_ID,           0                                 },
945        { EGL_NATIVE_VISUAL_TYPE,         GGL_PIXEL_FORMAT_RGB_565          },
946        { EGL_SAMPLES,                    0                                 },
947        { EGL_SAMPLE_BUFFERS,             0                                 },
948        { EGL_TRANSPARENT_TYPE,           EGL_NONE                          },
949        { EGL_TRANSPARENT_BLUE_VALUE,     0                                 },
950        { EGL_TRANSPARENT_GREEN_VALUE,    0                                 },
951        { EGL_TRANSPARENT_RED_VALUE,      0                                 },
952        { EGL_BIND_TO_TEXTURE_RGBA,       EGL_FALSE                         },
953        { EGL_BIND_TO_TEXTURE_RGB,        EGL_FALSE                         },
954        { EGL_MIN_SWAP_INTERVAL,          1                                 },
955        { EGL_MAX_SWAP_INTERVAL,          1                                 },
956        { EGL_RENDERABLE_TYPE,            EGL_OPENGL_ES_BIT                 },
957};
958
959// These configs can override the base attribute list
960// NOTE: when adding a config here, don't forget to update eglCreate*Surface()
961
962static config_pair_t const config_0_attribute_list[] = {
963        { EGL_BUFFER_SIZE,     16 },
964        { EGL_ALPHA_SIZE,       0 },
965        { EGL_BLUE_SIZE,        5 },
966        { EGL_GREEN_SIZE,       6 },
967        { EGL_RED_SIZE,         5 },
968        { EGL_DEPTH_SIZE,       0 },
969        { EGL_CONFIG_ID,        0 },
970        { EGL_SURFACE_TYPE,     EGL_WINDOW_BIT|EGL_PBUFFER_BIT|EGL_PIXMAP_BIT },
971};
972
973static config_pair_t const config_1_attribute_list[] = {
974        { EGL_BUFFER_SIZE,     16 },
975        { EGL_ALPHA_SIZE,       0 },
976        { EGL_BLUE_SIZE,        5 },
977        { EGL_GREEN_SIZE,       6 },
978        { EGL_RED_SIZE,         5 },
979        { EGL_DEPTH_SIZE,      16 },
980        { EGL_CONFIG_ID,        1 },
981        { EGL_SURFACE_TYPE,     EGL_WINDOW_BIT|EGL_PBUFFER_BIT|EGL_PIXMAP_BIT },
982};
983
984static config_pair_t const config_2_attribute_list[] = {
985        { EGL_BUFFER_SIZE,     32 },
986        { EGL_ALPHA_SIZE,       8 },
987        { EGL_BLUE_SIZE,        8 },
988        { EGL_GREEN_SIZE,       8 },
989        { EGL_RED_SIZE,         8 },
990        { EGL_DEPTH_SIZE,       0 },
991        { EGL_CONFIG_ID,        2 },
992        { EGL_SURFACE_TYPE,     EGL_WINDOW_BIT|EGL_PBUFFER_BIT|EGL_PIXMAP_BIT },
993};
994
995static config_pair_t const config_3_attribute_list[] = {
996        { EGL_BUFFER_SIZE,     32 },
997        { EGL_ALPHA_SIZE,       8 },
998        { EGL_BLUE_SIZE,        8 },
999        { EGL_GREEN_SIZE,       8 },
1000        { EGL_RED_SIZE,         8 },
1001        { EGL_DEPTH_SIZE,      16 },
1002        { EGL_CONFIG_ID,        3 },
1003        { EGL_SURFACE_TYPE,     EGL_WINDOW_BIT|EGL_PBUFFER_BIT|EGL_PIXMAP_BIT },
1004};
1005
1006static config_pair_t const config_4_attribute_list[] = {
1007        { EGL_BUFFER_SIZE,      8 },
1008        { EGL_ALPHA_SIZE,       8 },
1009        { EGL_BLUE_SIZE,        0 },
1010        { EGL_GREEN_SIZE,       0 },
1011        { EGL_RED_SIZE,         0 },
1012        { EGL_DEPTH_SIZE,       0 },
1013        { EGL_CONFIG_ID,        4 },
1014        { EGL_SURFACE_TYPE,     EGL_WINDOW_BIT|EGL_PBUFFER_BIT|EGL_PIXMAP_BIT },
1015};
1016
1017static config_pair_t const config_5_attribute_list[] = {
1018        { EGL_BUFFER_SIZE,      8 },
1019        { EGL_ALPHA_SIZE,       8 },
1020        { EGL_BLUE_SIZE,        0 },
1021        { EGL_GREEN_SIZE,       0 },
1022        { EGL_RED_SIZE,         0 },
1023        { EGL_DEPTH_SIZE,      16 },
1024        { EGL_CONFIG_ID,        5 },
1025        { EGL_SURFACE_TYPE,     EGL_WINDOW_BIT|EGL_PBUFFER_BIT|EGL_PIXMAP_BIT },
1026};
1027
1028static configs_t const gConfigs[] = {
1029        { config_0_attribute_list, NELEM(config_0_attribute_list) },
1030        { config_1_attribute_list, NELEM(config_1_attribute_list) },
1031        { config_2_attribute_list, NELEM(config_2_attribute_list) },
1032        { config_3_attribute_list, NELEM(config_3_attribute_list) },
1033        { config_4_attribute_list, NELEM(config_4_attribute_list) },
1034        { config_5_attribute_list, NELEM(config_5_attribute_list) },
1035};
1036
1037static config_management_t const gConfigManagement[] = {
1038        { EGL_BUFFER_SIZE,                config_management_t::atLeast },
1039        { EGL_ALPHA_SIZE,                 config_management_t::atLeast },
1040        { EGL_BLUE_SIZE,                  config_management_t::atLeast },
1041        { EGL_GREEN_SIZE,                 config_management_t::atLeast },
1042        { EGL_RED_SIZE,                   config_management_t::atLeast },
1043        { EGL_DEPTH_SIZE,                 config_management_t::atLeast },
1044        { EGL_STENCIL_SIZE,               config_management_t::atLeast },
1045        { EGL_CONFIG_CAVEAT,              config_management_t::exact   },
1046        { EGL_CONFIG_ID,                  config_management_t::exact   },
1047        { EGL_LEVEL,                      config_management_t::exact   },
1048        { EGL_MAX_PBUFFER_HEIGHT,         config_management_t::exact   },
1049        { EGL_MAX_PBUFFER_PIXELS,         config_management_t::exact   },
1050        { EGL_MAX_PBUFFER_WIDTH,          config_management_t::exact   },
1051        { EGL_NATIVE_RENDERABLE,          config_management_t::exact   },
1052        { EGL_NATIVE_VISUAL_ID,           config_management_t::exact   },
1053        { EGL_NATIVE_VISUAL_TYPE,         config_management_t::exact   },
1054        { EGL_SAMPLES,                    config_management_t::exact   },
1055        { EGL_SAMPLE_BUFFERS,             config_management_t::exact   },
1056        { EGL_SURFACE_TYPE,               config_management_t::mask    },
1057        { EGL_TRANSPARENT_TYPE,           config_management_t::exact   },
1058        { EGL_TRANSPARENT_BLUE_VALUE,     config_management_t::exact   },
1059        { EGL_TRANSPARENT_GREEN_VALUE,    config_management_t::exact   },
1060        { EGL_TRANSPARENT_RED_VALUE,      config_management_t::exact   },
1061        { EGL_BIND_TO_TEXTURE_RGBA,       config_management_t::exact   },
1062        { EGL_BIND_TO_TEXTURE_RGB,        config_management_t::exact   },
1063        { EGL_MIN_SWAP_INTERVAL,          config_management_t::exact   },
1064        { EGL_MAX_SWAP_INTERVAL,          config_management_t::exact   },
1065};
1066
1067static config_pair_t const config_defaults[] = {
1068        { EGL_SURFACE_TYPE,        EGL_WINDOW_BIT },
1069};
1070
1071// ----------------------------------------------------------------------------
1072
1073template<typename T>
1074static int binarySearch(T const sortedArray[], int first, int last, EGLint key)
1075{
1076   while (first <= last) {
1077       int mid = (first + last) / 2;
1078       if (key > sortedArray[mid].key) {
1079           first = mid + 1;
1080       } else if (key < sortedArray[mid].key) {
1081           last = mid - 1;
1082       } else {
1083           return mid;
1084       }
1085   }
1086   return -1;
1087}
1088
1089static int isAttributeMatching(int i, EGLint attr, EGLint val)
1090{
1091    // look for the attribute in all of our configs
1092    config_pair_t const* configFound = gConfigs[i].array;
1093    int index = binarySearch<config_pair_t>(
1094            gConfigs[i].array,
1095            0, gConfigs[i].size-1,
1096            attr);
1097    if (index < 0) {
1098        configFound = config_base_attribute_list;
1099        index = binarySearch<config_pair_t>(
1100                config_base_attribute_list,
1101                0, NELEM(config_base_attribute_list)-1,
1102                attr);
1103    }
1104    if (index >= 0) {
1105        // attribute found, check if this config could match
1106        int cfgMgtIndex = binarySearch<config_management_t>(
1107                gConfigManagement,
1108                0, NELEM(gConfigManagement)-1,
1109                attr);
1110        if (index >= 0) {
1111            bool match = gConfigManagement[cfgMgtIndex].match(
1112                    val, configFound[index].value);
1113            if (match) {
1114                // this config matches
1115                return 1;
1116            }
1117        } else {
1118            // attribute not found. this should NEVER happen.
1119        }
1120    } else {
1121        // error, this attribute doesn't exist
1122    }
1123    return 0;
1124}
1125
1126static int makeCurrent(ogles_context_t* gl)
1127{
1128    ogles_context_t* current = (ogles_context_t*)getGlThreadSpecific();
1129    if (gl) {
1130        egl_context_t* c = egl_context_t::context(gl);
1131        if (c->flags & egl_context_t::IS_CURRENT) {
1132            if (current != gl) {
1133                // it is an error to set a context current, if it's already
1134                // current to another thread
1135                return -1;
1136            }
1137        } else {
1138            if (current) {
1139                // mark the current context as not current, and flush
1140                glFlush();
1141                egl_context_t::context(current)->flags &= ~egl_context_t::IS_CURRENT;
1142            }
1143        }
1144        if (!(c->flags & egl_context_t::IS_CURRENT)) {
1145            // The context is not current, make it current!
1146            setGlThreadSpecific(gl);
1147            c->flags |= egl_context_t::IS_CURRENT;
1148        }
1149    } else {
1150        if (current) {
1151            // mark the current context as not current, and flush
1152            glFlush();
1153            egl_context_t::context(current)->flags &= ~egl_context_t::IS_CURRENT;
1154        }
1155        // this thread has no context attached to it
1156        setGlThreadSpecific(0);
1157    }
1158    return 0;
1159}
1160
1161static EGLBoolean getConfigAttrib(EGLDisplay dpy, EGLConfig config,
1162        EGLint attribute, EGLint *value)
1163{
1164    size_t numConfigs =  NELEM(gConfigs);
1165    int index = (int)config;
1166    if (uint32_t(index) >= numConfigs)
1167        return setError(EGL_BAD_CONFIG, EGL_FALSE);
1168
1169    int attrIndex;
1170    attrIndex = binarySearch<config_pair_t>(
1171            gConfigs[index].array,
1172            0, gConfigs[index].size-1,
1173            attribute);
1174    if (attrIndex>=0) {
1175        *value = gConfigs[index].array[attrIndex].value;
1176        return EGL_TRUE;
1177    }
1178
1179    attrIndex = binarySearch<config_pair_t>(
1180            config_base_attribute_list,
1181            0, NELEM(config_base_attribute_list)-1,
1182            attribute);
1183    if (attrIndex>=0) {
1184        *value = config_base_attribute_list[attrIndex].value;
1185        return EGL_TRUE;
1186    }
1187    return setError(EGL_BAD_ATTRIBUTE, EGL_FALSE);
1188}
1189
1190static EGLSurface createWindowSurface(EGLDisplay dpy, EGLConfig config,
1191        NativeWindowType window, const EGLint *attrib_list)
1192{
1193    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1194        return setError(EGL_BAD_DISPLAY, EGL_NO_SURFACE);
1195    if (window == 0)
1196        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1197
1198    EGLint surfaceType;
1199    if (getConfigAttrib(dpy, config, EGL_SURFACE_TYPE, &surfaceType) == EGL_FALSE)
1200        return EGL_FALSE;
1201
1202    if (!(surfaceType & EGL_WINDOW_BIT))
1203        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1204
1205    if (static_cast<android_native_window_t*>(window)->common.magic !=
1206            ANDROID_NATIVE_WINDOW_MAGIC) {
1207        return setError(EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE);
1208    }
1209
1210    EGLint configID;
1211    if (getConfigAttrib(dpy, config, EGL_CONFIG_ID, &configID) == EGL_FALSE)
1212        return EGL_FALSE;
1213
1214    int32_t depthFormat;
1215    int32_t pixelFormat;
1216    switch(configID) {
1217    case 0:
1218        pixelFormat = GGL_PIXEL_FORMAT_RGB_565;
1219        depthFormat = 0;
1220        break;
1221    case 1:
1222        pixelFormat = GGL_PIXEL_FORMAT_RGB_565;
1223        depthFormat = GGL_PIXEL_FORMAT_Z_16;
1224        break;
1225    case 2:
1226        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888;
1227        depthFormat = 0;
1228        break;
1229    case 3:
1230        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888;
1231        depthFormat = GGL_PIXEL_FORMAT_Z_16;
1232        break;
1233    case 4:
1234        pixelFormat = GGL_PIXEL_FORMAT_A_8;
1235        depthFormat = 0;
1236        break;
1237    case 5:
1238        pixelFormat = GGL_PIXEL_FORMAT_A_8;
1239        depthFormat = GGL_PIXEL_FORMAT_Z_16;
1240        break;
1241    default:
1242        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1243    }
1244
1245    // FIXME: we don't have access to the pixelFormat here just yet.
1246    // (it's possible that the surface is not fully initialized)
1247    // maybe this should be done after the page-flip
1248    //if (EGLint(info.format) != pixelFormat)
1249    //    return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1250
1251    egl_surface_t* surface;
1252    surface = new egl_window_surface_v2_t(dpy, config, depthFormat,
1253            static_cast<android_native_window_t*>(window));
1254
1255    if (!surface->initCheck()) {
1256        // there was a problem in the ctor, the error
1257        // flag has been set.
1258        delete surface;
1259        surface = 0;
1260    }
1261    return surface;
1262}
1263
1264static EGLSurface createPixmapSurface(EGLDisplay dpy, EGLConfig config,
1265        NativePixmapType pixmap, const EGLint *attrib_list)
1266{
1267    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1268        return setError(EGL_BAD_DISPLAY, EGL_NO_SURFACE);
1269    if (pixmap == 0)
1270        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1271
1272    EGLint surfaceType;
1273    if (getConfigAttrib(dpy, config, EGL_SURFACE_TYPE, &surfaceType) == EGL_FALSE)
1274        return EGL_FALSE;
1275
1276    if (!(surfaceType & EGL_PIXMAP_BIT))
1277        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1278
1279    if (static_cast<egl_native_pixmap_t*>(pixmap)->version !=
1280            sizeof(egl_native_pixmap_t)) {
1281        return setError(EGL_BAD_NATIVE_PIXMAP, EGL_NO_SURFACE);
1282    }
1283
1284    EGLint configID;
1285    if (getConfigAttrib(dpy, config, EGL_CONFIG_ID, &configID) == EGL_FALSE)
1286        return EGL_FALSE;
1287
1288    int32_t depthFormat;
1289    int32_t pixelFormat;
1290    switch(configID) {
1291    case 0:
1292        pixelFormat = GGL_PIXEL_FORMAT_RGB_565;
1293        depthFormat = 0;
1294        break;
1295    case 1:
1296        pixelFormat = GGL_PIXEL_FORMAT_RGB_565;
1297        depthFormat = GGL_PIXEL_FORMAT_Z_16;
1298        break;
1299    case 2:
1300        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888;
1301        depthFormat = 0;
1302        break;
1303    case 3:
1304        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888;
1305        depthFormat = GGL_PIXEL_FORMAT_Z_16;
1306        break;
1307    case 4:
1308        pixelFormat = GGL_PIXEL_FORMAT_A_8;
1309        depthFormat = 0;
1310        break;
1311    case 5:
1312        pixelFormat = GGL_PIXEL_FORMAT_A_8;
1313        depthFormat = GGL_PIXEL_FORMAT_Z_16;
1314        break;
1315    default:
1316        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1317    }
1318
1319    if (pixmap->format != pixelFormat)
1320        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1321
1322    egl_surface_t* surface =
1323        new egl_pixmap_surface_t(dpy, config, depthFormat,
1324                static_cast<egl_native_pixmap_t*>(pixmap));
1325
1326    if (!surface->initCheck()) {
1327        // there was a problem in the ctor, the error
1328        // flag has been set.
1329        delete surface;
1330        surface = 0;
1331    }
1332    return surface;
1333}
1334
1335static EGLSurface createPbufferSurface(EGLDisplay dpy, EGLConfig config,
1336        const EGLint *attrib_list)
1337{
1338    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1339        return setError(EGL_BAD_DISPLAY, EGL_NO_SURFACE);
1340
1341    EGLint surfaceType;
1342    if (getConfigAttrib(dpy, config, EGL_SURFACE_TYPE, &surfaceType) == EGL_FALSE)
1343        return EGL_FALSE;
1344
1345    if (!(surfaceType & EGL_PBUFFER_BIT))
1346        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1347
1348    EGLint configID;
1349    if (getConfigAttrib(dpy, config, EGL_CONFIG_ID, &configID) == EGL_FALSE)
1350        return EGL_FALSE;
1351
1352    int32_t depthFormat;
1353    int32_t pixelFormat;
1354    switch(configID) {
1355    case 0:
1356        pixelFormat = GGL_PIXEL_FORMAT_RGB_565;
1357        depthFormat = 0;
1358        break;
1359    case 1:
1360        pixelFormat = GGL_PIXEL_FORMAT_RGB_565;
1361        depthFormat = GGL_PIXEL_FORMAT_Z_16;
1362        break;
1363    case 2:
1364        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888;
1365        depthFormat = 0;
1366        break;
1367    case 3:
1368        pixelFormat = GGL_PIXEL_FORMAT_RGBA_8888;
1369        depthFormat = GGL_PIXEL_FORMAT_Z_16;
1370        break;
1371    case 4:
1372        pixelFormat = GGL_PIXEL_FORMAT_A_8;
1373        depthFormat = 0;
1374        break;
1375    case 5:
1376        pixelFormat = GGL_PIXEL_FORMAT_A_8;
1377        depthFormat = GGL_PIXEL_FORMAT_Z_16;
1378        break;
1379    default:
1380        return setError(EGL_BAD_MATCH, EGL_NO_SURFACE);
1381    }
1382
1383    int32_t w = 0;
1384    int32_t h = 0;
1385    while (attrib_list[0]) {
1386        if (attrib_list[0] == EGL_WIDTH)  w = attrib_list[1];
1387        if (attrib_list[0] == EGL_HEIGHT) h = attrib_list[1];
1388        attrib_list+=2;
1389    }
1390
1391    egl_surface_t* surface =
1392        new egl_pbuffer_surface_t(dpy, config, depthFormat, w, h, pixelFormat);
1393
1394    if (!surface->initCheck()) {
1395        // there was a problem in the ctor, the error
1396        // flag has been set.
1397        delete surface;
1398        surface = 0;
1399    }
1400    return surface;
1401}
1402
1403// ----------------------------------------------------------------------------
1404}; // namespace android
1405// ----------------------------------------------------------------------------
1406
1407using namespace android;
1408
1409// ----------------------------------------------------------------------------
1410// Initialization
1411// ----------------------------------------------------------------------------
1412
1413EGLDisplay eglGetDisplay(NativeDisplayType display)
1414{
1415#ifndef HAVE_ANDROID_OS
1416    // this just needs to be done once
1417    if (gGLKey == -1) {
1418        pthread_mutex_lock(&gInitMutex);
1419        if (gGLKey == -1)
1420            pthread_key_create(&gGLKey, NULL);
1421        pthread_mutex_unlock(&gInitMutex);
1422    }
1423#endif
1424    if (display == EGL_DEFAULT_DISPLAY) {
1425        EGLDisplay dpy = (EGLDisplay)1;
1426        egl_display_t& d = egl_display_t::get_display(dpy);
1427        d.type = display;
1428        return dpy;
1429    }
1430    return EGL_NO_DISPLAY;
1431}
1432
1433EGLBoolean eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor)
1434{
1435    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1436        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1437
1438    EGLBoolean res = EGL_TRUE;
1439    egl_display_t& d = egl_display_t::get_display(dpy);
1440
1441    if (android_atomic_inc(&d.initialized) == 0) {
1442        // initialize stuff here if needed
1443        //pthread_mutex_lock(&gInitMutex);
1444        //pthread_mutex_unlock(&gInitMutex);
1445    }
1446
1447    if (res == EGL_TRUE) {
1448        if (major != NULL) *major = VERSION_MAJOR;
1449        if (minor != NULL) *minor = VERSION_MINOR;
1450    }
1451    return res;
1452}
1453
1454EGLBoolean eglTerminate(EGLDisplay dpy)
1455{
1456    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1457        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1458
1459    EGLBoolean res = EGL_TRUE;
1460    egl_display_t& d = egl_display_t::get_display(dpy);
1461    if (android_atomic_dec(&d.initialized) == 1) {
1462        // TODO: destroy all resources (surfaces, contexts, etc...)
1463        //pthread_mutex_lock(&gInitMutex);
1464        //pthread_mutex_unlock(&gInitMutex);
1465    }
1466    return res;
1467}
1468
1469// ----------------------------------------------------------------------------
1470// configuration
1471// ----------------------------------------------------------------------------
1472
1473EGLBoolean eglGetConfigs(   EGLDisplay dpy,
1474                            EGLConfig *configs,
1475                            EGLint config_size, EGLint *num_config)
1476{
1477    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1478        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1479
1480    GLint numConfigs = NELEM(gConfigs);
1481    if (!configs) {
1482        *num_config = numConfigs;
1483        return EGL_TRUE;
1484    }
1485    GLint i;
1486    for (i=0 ; i<numConfigs && i<config_size ; i++) {
1487        *configs++ = (EGLConfig)i;
1488    }
1489    *num_config = i;
1490    return EGL_TRUE;
1491}
1492
1493EGLBoolean eglChooseConfig( EGLDisplay dpy, const EGLint *attrib_list,
1494                            EGLConfig *configs, EGLint config_size,
1495                            EGLint *num_config)
1496{
1497    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1498        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1499
1500    if (ggl_unlikely(num_config==0)) {
1501        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1502    }
1503
1504    if (ggl_unlikely(attrib_list==0)) {
1505        *num_config = 0;
1506        return EGL_TRUE;
1507    }
1508
1509    int numAttributes = 0;
1510    int numConfigs =  NELEM(gConfigs);
1511    uint32_t possibleMatch = (1<<numConfigs)-1;
1512    while(possibleMatch && *attrib_list != EGL_NONE) {
1513        numAttributes++;
1514        EGLint attr = *attrib_list++;
1515        EGLint val  = *attrib_list++;
1516        for (int i=0 ; i<numConfigs ; i++) {
1517            if (!(possibleMatch & (1<<i)))
1518                continue;
1519            if (isAttributeMatching(i, attr, val) == 0) {
1520                possibleMatch &= ~(1<<i);
1521            }
1522        }
1523    }
1524
1525    // now, handle the attributes which have a useful default value
1526    for (size_t j=0 ; j<NELEM(config_defaults) ; j++) {
1527        // see if this attribute was specified, if not apply its
1528        // default value
1529        if (binarySearch<config_pair_t>(
1530                (config_pair_t const*)attrib_list,
1531                0, numAttributes-1,
1532                config_defaults[j].key) < 0)
1533        {
1534            for (int i=0 ; i<numConfigs ; i++) {
1535                if (!(possibleMatch & (1<<i)))
1536                    continue;
1537                if (isAttributeMatching(i,
1538                        config_defaults[j].key,
1539                        config_defaults[j].value) == 0)
1540                {
1541                    possibleMatch &= ~(1<<i);
1542                }
1543            }
1544        }
1545    }
1546
1547    // return the configurations found
1548    int n=0;
1549    if (possibleMatch) {
1550        if (configs) {
1551            for (int i=0 ; config_size && i<numConfigs ; i++) {
1552                if (possibleMatch & (1<<i)) {
1553                    *configs++ = (EGLConfig)i;
1554                    config_size--;
1555                    n++;
1556                }
1557            }
1558        } else {
1559            for (int i=0 ; i<numConfigs ; i++) {
1560                if (possibleMatch & (1<<i)) {
1561                    n++;
1562                }
1563            }
1564        }
1565    }
1566    *num_config = n;
1567     return EGL_TRUE;
1568}
1569
1570EGLBoolean eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config,
1571        EGLint attribute, EGLint *value)
1572{
1573    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1574        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1575
1576    return getConfigAttrib(dpy, config, attribute, value);
1577}
1578
1579// ----------------------------------------------------------------------------
1580// surfaces
1581// ----------------------------------------------------------------------------
1582
1583EGLSurface eglCreateWindowSurface(  EGLDisplay dpy, EGLConfig config,
1584                                    NativeWindowType window,
1585                                    const EGLint *attrib_list)
1586{
1587    return createWindowSurface(dpy, config, window, attrib_list);
1588}
1589
1590EGLSurface eglCreatePixmapSurface(  EGLDisplay dpy, EGLConfig config,
1591                                    NativePixmapType pixmap,
1592                                    const EGLint *attrib_list)
1593{
1594    return createPixmapSurface(dpy, config, pixmap, attrib_list);
1595}
1596
1597EGLSurface eglCreatePbufferSurface( EGLDisplay dpy, EGLConfig config,
1598                                    const EGLint *attrib_list)
1599{
1600    return createPbufferSurface(dpy, config, attrib_list);
1601}
1602
1603EGLBoolean eglDestroySurface(EGLDisplay dpy, EGLSurface eglSurface)
1604{
1605    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1606        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1607    if (eglSurface != EGL_NO_SURFACE) {
1608        egl_surface_t* surface( static_cast<egl_surface_t*>(eglSurface) );
1609        if (!surface->isValid())
1610            return setError(EGL_BAD_SURFACE, EGL_FALSE);
1611        if (surface->dpy != dpy)
1612            return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1613        if (surface->ctx) {
1614            // FIXME: this surface is current check what the spec says
1615            surface->disconnect();
1616            surface->ctx = 0;
1617        }
1618        delete surface;
1619    }
1620    return EGL_TRUE;
1621}
1622
1623EGLBoolean eglQuerySurface( EGLDisplay dpy, EGLSurface eglSurface,
1624                            EGLint attribute, EGLint *value)
1625{
1626    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1627        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1628    egl_surface_t* surface = static_cast<egl_surface_t*>(eglSurface);
1629    if (!surface->isValid())
1630        return setError(EGL_BAD_SURFACE, EGL_FALSE);
1631    if (surface->dpy != dpy)
1632        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1633
1634    EGLBoolean ret = EGL_TRUE;
1635    switch (attribute) {
1636        case EGL_CONFIG_ID:
1637            ret = getConfigAttrib(dpy, surface->config, EGL_CONFIG_ID, value);
1638            break;
1639        case EGL_WIDTH:
1640            *value = surface->getWidth();
1641            break;
1642        case EGL_HEIGHT:
1643            *value = surface->getHeight();
1644            break;
1645        case EGL_LARGEST_PBUFFER:
1646            // not modified for a window or pixmap surface
1647            break;
1648        case EGL_TEXTURE_FORMAT:
1649            *value = EGL_NO_TEXTURE;
1650            break;
1651        case EGL_TEXTURE_TARGET:
1652            *value = EGL_NO_TEXTURE;
1653            break;
1654        case EGL_MIPMAP_TEXTURE:
1655            *value = EGL_FALSE;
1656            break;
1657        case EGL_MIPMAP_LEVEL:
1658            *value = 0;
1659            break;
1660        case EGL_RENDER_BUFFER:
1661            // TODO: return the real RENDER_BUFFER here
1662            *value = EGL_BACK_BUFFER;
1663            break;
1664        case EGL_HORIZONTAL_RESOLUTION:
1665            // pixel/mm * EGL_DISPLAY_SCALING
1666            *value = surface->getHorizontalResolution();
1667            break;
1668        case EGL_VERTICAL_RESOLUTION:
1669            // pixel/mm * EGL_DISPLAY_SCALING
1670            *value = surface->getVerticalResolution();
1671            break;
1672        case EGL_PIXEL_ASPECT_RATIO: {
1673            // w/h * EGL_DISPLAY_SCALING
1674            int wr = surface->getHorizontalResolution();
1675            int hr = surface->getVerticalResolution();
1676            *value = (wr * EGL_DISPLAY_SCALING) / hr;
1677        } break;
1678        case EGL_SWAP_BEHAVIOR:
1679            *value = surface->getSwapBehavior();
1680            break;
1681        default:
1682            ret = setError(EGL_BAD_ATTRIBUTE, EGL_FALSE);
1683    }
1684    return ret;
1685}
1686
1687EGLContext eglCreateContext(EGLDisplay dpy, EGLConfig config,
1688                            EGLContext share_list, const EGLint *attrib_list)
1689{
1690    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1691        return setError(EGL_BAD_DISPLAY, EGL_NO_SURFACE);
1692
1693    ogles_context_t* gl = ogles_init(sizeof(egl_context_t));
1694    if (!gl) return setError(EGL_BAD_ALLOC, EGL_NO_CONTEXT);
1695
1696    egl_context_t* c = static_cast<egl_context_t*>(gl->rasterizer.base);
1697    c->flags = egl_context_t::NEVER_CURRENT;
1698    c->dpy = dpy;
1699    c->config = config;
1700    c->read = 0;
1701    c->draw = 0;
1702    return (EGLContext)gl;
1703}
1704
1705EGLBoolean eglDestroyContext(EGLDisplay dpy, EGLContext ctx)
1706{
1707    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1708        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1709    egl_context_t* c = egl_context_t::context(ctx);
1710    if (c->flags & egl_context_t::IS_CURRENT)
1711        setGlThreadSpecific(0);
1712    ogles_uninit((ogles_context_t*)ctx);
1713    return EGL_TRUE;
1714}
1715
1716EGLBoolean eglMakeCurrent(  EGLDisplay dpy, EGLSurface draw,
1717                            EGLSurface read, EGLContext ctx)
1718{
1719    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1720        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1721    if (draw) {
1722        egl_surface_t* s = (egl_surface_t*)draw;
1723        if (!s->isValid())
1724            return setError(EGL_BAD_SURFACE, EGL_FALSE);
1725        if (s->dpy != dpy)
1726            return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1727        // TODO: check that draw is compatible with the context
1728    }
1729    if (read && read!=draw) {
1730        egl_surface_t* s = (egl_surface_t*)read;
1731        if (!s->isValid())
1732            return setError(EGL_BAD_SURFACE, EGL_FALSE);
1733        if (s->dpy != dpy)
1734            return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1735        // TODO: check that read is compatible with the context
1736    }
1737
1738    EGLContext current_ctx = EGL_NO_CONTEXT;
1739
1740    if ((read == EGL_NO_SURFACE && draw == EGL_NO_SURFACE) && (ctx != EGL_NO_CONTEXT))
1741        return setError(EGL_BAD_MATCH, EGL_FALSE);
1742
1743    if ((read != EGL_NO_SURFACE || draw != EGL_NO_SURFACE) && (ctx == EGL_NO_CONTEXT))
1744        return setError(EGL_BAD_MATCH, EGL_FALSE);
1745
1746    if (ctx == EGL_NO_CONTEXT) {
1747        // if we're detaching, we need the current context
1748        current_ctx = (EGLContext)getGlThreadSpecific();
1749    } else {
1750        egl_context_t* c = egl_context_t::context(ctx);
1751        egl_surface_t* d = (egl_surface_t*)draw;
1752        egl_surface_t* r = (egl_surface_t*)read;
1753        if ((d && d->ctx && d->ctx != ctx) ||
1754            (r && r->ctx && r->ctx != ctx)) {
1755            // one of the surface is bound to a context in another thread
1756            return setError(EGL_BAD_ACCESS, EGL_FALSE);
1757        }
1758    }
1759
1760    ogles_context_t* gl = (ogles_context_t*)ctx;
1761    if (makeCurrent(gl) == 0) {
1762        if (ctx) {
1763            egl_context_t* c = egl_context_t::context(ctx);
1764            egl_surface_t* d = (egl_surface_t*)draw;
1765            egl_surface_t* r = (egl_surface_t*)read;
1766
1767            if (c->draw) {
1768                egl_surface_t* s = reinterpret_cast<egl_surface_t*>(c->draw);
1769                s->disconnect();
1770            }
1771            if (c->read) {
1772                // FIXME: unlock/disconnect the read surface too
1773            }
1774
1775            c->draw = draw;
1776            c->read = read;
1777
1778            if (c->flags & egl_context_t::NEVER_CURRENT) {
1779                c->flags &= ~egl_context_t::NEVER_CURRENT;
1780                GLint w = 0;
1781                GLint h = 0;
1782                if (draw) {
1783                    w = d->getWidth();
1784                    h = d->getHeight();
1785                }
1786                ogles_surfaceport(gl, 0, 0);
1787                ogles_viewport(gl, 0, 0, w, h);
1788                ogles_scissor(gl, 0, 0, w, h);
1789            }
1790            if (d) {
1791                if (d->connect() == EGL_FALSE) {
1792                    return EGL_FALSE;
1793                }
1794                d->ctx = ctx;
1795                d->bindDrawSurface(gl);
1796            }
1797            if (r) {
1798                // FIXME: lock/connect the read surface too
1799                r->ctx = ctx;
1800                r->bindReadSurface(gl);
1801            }
1802        } else {
1803            // if surfaces were bound to the context bound to this thread
1804            // mark then as unbound.
1805            if (current_ctx) {
1806                egl_context_t* c = egl_context_t::context(current_ctx);
1807                egl_surface_t* d = (egl_surface_t*)c->draw;
1808                egl_surface_t* r = (egl_surface_t*)c->read;
1809                if (d) {
1810                    c->draw = 0;
1811                    d->ctx = EGL_NO_CONTEXT;
1812                    d->disconnect();
1813                }
1814                if (r) {
1815                    c->read = 0;
1816                    r->ctx = EGL_NO_CONTEXT;
1817                    // FIXME: unlock/disconnect the read surface too
1818                }
1819            }
1820        }
1821        return EGL_TRUE;
1822    }
1823    return setError(EGL_BAD_ACCESS, EGL_FALSE);
1824}
1825
1826EGLContext eglGetCurrentContext(void)
1827{
1828    // eglGetCurrentContext returns the current EGL rendering context,
1829    // as specified by eglMakeCurrent. If no context is current,
1830    // EGL_NO_CONTEXT is returned.
1831    return (EGLContext)getGlThreadSpecific();
1832}
1833
1834EGLSurface eglGetCurrentSurface(EGLint readdraw)
1835{
1836    // eglGetCurrentSurface returns the read or draw surface attached
1837    // to the current EGL rendering context, as specified by eglMakeCurrent.
1838    // If no context is current, EGL_NO_SURFACE is returned.
1839    EGLContext ctx = (EGLContext)getGlThreadSpecific();
1840    if (ctx == EGL_NO_CONTEXT) return EGL_NO_SURFACE;
1841    egl_context_t* c = egl_context_t::context(ctx);
1842    if (readdraw == EGL_READ) {
1843        return c->read;
1844    } else if (readdraw == EGL_DRAW) {
1845        return c->draw;
1846    }
1847    return setError(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
1848}
1849
1850EGLDisplay eglGetCurrentDisplay(void)
1851{
1852    // eglGetCurrentDisplay returns the current EGL display connection
1853    // for the current EGL rendering context, as specified by eglMakeCurrent.
1854    // If no context is current, EGL_NO_DISPLAY is returned.
1855    EGLContext ctx = (EGLContext)getGlThreadSpecific();
1856    if (ctx == EGL_NO_CONTEXT) return EGL_NO_DISPLAY;
1857    egl_context_t* c = egl_context_t::context(ctx);
1858    return c->dpy;
1859}
1860
1861EGLBoolean eglQueryContext( EGLDisplay dpy, EGLContext ctx,
1862                            EGLint attribute, EGLint *value)
1863{
1864    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1865        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1866    egl_context_t* c = egl_context_t::context(ctx);
1867    switch (attribute) {
1868        case EGL_CONFIG_ID:
1869            // Returns the ID of the EGL frame buffer configuration with
1870            // respect to which the context was created
1871            return getConfigAttrib(dpy, c->config, EGL_CONFIG_ID, value);
1872    }
1873    return setError(EGL_BAD_ATTRIBUTE, EGL_FALSE);
1874}
1875
1876EGLBoolean eglWaitGL(void)
1877{
1878    return EGL_TRUE;
1879}
1880
1881EGLBoolean eglWaitNative(EGLint engine)
1882{
1883    return EGL_TRUE;
1884}
1885
1886EGLBoolean eglSwapBuffers(EGLDisplay dpy, EGLSurface draw)
1887{
1888    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1889        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1890
1891    egl_surface_t* d = static_cast<egl_surface_t*>(draw);
1892    if (!d->isValid())
1893        return setError(EGL_BAD_SURFACE, EGL_FALSE);
1894    if (d->dpy != dpy)
1895        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1896
1897    // post the surface
1898    d->swapBuffers();
1899
1900    // if it's bound to a context, update the buffer
1901    if (d->ctx != EGL_NO_CONTEXT) {
1902        d->bindDrawSurface((ogles_context_t*)d->ctx);
1903        // if this surface is also the read surface of the context
1904        // it is bound to, make sure to update the read buffer as well.
1905        // The EGL spec is a little unclear about this.
1906        egl_context_t* c = egl_context_t::context(d->ctx);
1907        if (c->read == draw) {
1908            d->bindReadSurface((ogles_context_t*)d->ctx);
1909        }
1910    }
1911
1912    return EGL_TRUE;
1913}
1914
1915EGLBoolean eglCopyBuffers(  EGLDisplay dpy, EGLSurface surface,
1916                            NativePixmapType target)
1917{
1918    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1919        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1920    // TODO: eglCopyBuffers()
1921    return EGL_FALSE;
1922}
1923
1924EGLint eglGetError(void)
1925{
1926    return getError();
1927}
1928
1929const char* eglQueryString(EGLDisplay dpy, EGLint name)
1930{
1931    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1932        return setError(EGL_BAD_DISPLAY, (const char*)0);
1933
1934    switch (name) {
1935        case EGL_VENDOR:
1936            return gVendorString;
1937        case EGL_VERSION:
1938            return gVersionString;
1939        case EGL_EXTENSIONS:
1940            return gExtensionsString;
1941        case EGL_CLIENT_APIS:
1942            return gClientApiString;
1943    }
1944    return setError(EGL_BAD_PARAMETER, (const char *)0);
1945}
1946
1947// ----------------------------------------------------------------------------
1948// EGL 1.1
1949// ----------------------------------------------------------------------------
1950
1951EGLBoolean eglSurfaceAttrib(
1952        EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value)
1953{
1954    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1955        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1956    // TODO: eglSurfaceAttrib()
1957    return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1958}
1959
1960EGLBoolean eglBindTexImage(
1961        EGLDisplay dpy, EGLSurface surface, EGLint buffer)
1962{
1963    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1964        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1965    // TODO: eglBindTexImage()
1966    return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1967}
1968
1969EGLBoolean eglReleaseTexImage(
1970        EGLDisplay dpy, EGLSurface surface, EGLint buffer)
1971{
1972    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1973        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1974    // TODO: eglReleaseTexImage()
1975    return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1976}
1977
1978EGLBoolean eglSwapInterval(EGLDisplay dpy, EGLint interval)
1979{
1980    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
1981        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
1982    // TODO: eglSwapInterval()
1983    return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1984}
1985
1986// ----------------------------------------------------------------------------
1987// EGL 1.2
1988// ----------------------------------------------------------------------------
1989
1990EGLBoolean eglBindAPI(EGLenum api)
1991{
1992    if (api != EGL_OPENGL_ES_API)
1993        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
1994    return EGL_TRUE;
1995}
1996
1997EGLenum eglQueryAPI(void)
1998{
1999    return EGL_OPENGL_ES_API;
2000}
2001
2002EGLBoolean eglWaitClient(void)
2003{
2004    glFinish();
2005    return EGL_TRUE;
2006}
2007
2008EGLBoolean eglReleaseThread(void)
2009{
2010    // TODO: eglReleaseThread()
2011    return EGL_TRUE;
2012}
2013
2014EGLSurface eglCreatePbufferFromClientBuffer(
2015          EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer,
2016          EGLConfig config, const EGLint *attrib_list)
2017{
2018    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
2019        return setError(EGL_BAD_DISPLAY, EGL_NO_SURFACE);
2020    // TODO: eglCreatePbufferFromClientBuffer()
2021    return setError(EGL_BAD_PARAMETER, EGL_NO_SURFACE);
2022}
2023
2024// ----------------------------------------------------------------------------
2025// EGL_EGLEXT_VERSION 3
2026// ----------------------------------------------------------------------------
2027
2028void (*eglGetProcAddress (const char *procname))()
2029{
2030    extention_map_t const * const map = gExtentionMap;
2031    for (uint32_t i=0 ; i<NELEM(gExtentionMap) ; i++) {
2032        if (!strcmp(procname, map[i].name)) {
2033            return map[i].address;
2034        }
2035    }
2036    return NULL;
2037}
2038
2039EGLBoolean eglLockSurfaceKHR(EGLDisplay dpy, EGLSurface surface,
2040        const EGLint *attrib_list)
2041{
2042    EGLBoolean result = EGL_FALSE;
2043    return result;
2044}
2045
2046EGLBoolean eglUnlockSurfaceKHR(EGLDisplay dpy, EGLSurface surface)
2047{
2048    EGLBoolean result = EGL_FALSE;
2049    return result;
2050}
2051
2052EGLImageKHR eglCreateImageKHR(EGLDisplay dpy, EGLContext ctx, EGLenum target,
2053        EGLClientBuffer buffer, const EGLint *attrib_list)
2054{
2055    if (egl_display_t::is_valid(dpy) == EGL_FALSE) {
2056        return setError(EGL_BAD_DISPLAY, EGL_NO_IMAGE_KHR);
2057    }
2058    if (ctx != EGL_NO_CONTEXT) {
2059        return setError(EGL_BAD_CONTEXT, EGL_NO_IMAGE_KHR);
2060    }
2061    if (target != EGL_NATIVE_BUFFER_ANDROID) {
2062        return setError(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
2063    }
2064
2065    android_native_buffer_t* native_buffer = (android_native_buffer_t*)buffer;
2066
2067    if (native_buffer->common.magic != ANDROID_NATIVE_BUFFER_MAGIC)
2068        return setError(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
2069
2070    if (native_buffer->common.version != sizeof(android_native_buffer_t))
2071        return setError(EGL_BAD_PARAMETER, EGL_NO_IMAGE_KHR);
2072
2073    native_buffer->common.incRef(&native_buffer->common);
2074    return (EGLImageKHR)native_buffer;
2075}
2076
2077EGLBoolean eglDestroyImageKHR(EGLDisplay dpy, EGLImageKHR img)
2078{
2079    if (egl_display_t::is_valid(dpy) == EGL_FALSE) {
2080        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
2081    }
2082
2083    android_native_buffer_t* native_buffer = (android_native_buffer_t*)img;
2084
2085    if (native_buffer->common.magic != ANDROID_NATIVE_BUFFER_MAGIC)
2086        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
2087
2088    if (native_buffer->common.version != sizeof(android_native_buffer_t))
2089        return setError(EGL_BAD_PARAMETER, EGL_FALSE);
2090
2091    native_buffer->common.decRef(&native_buffer->common);
2092
2093    return EGL_TRUE;
2094}
2095
2096// ----------------------------------------------------------------------------
2097// ANDROID extensions
2098// ----------------------------------------------------------------------------
2099
2100EGLBoolean eglSetSwapRectangleANDROID(EGLDisplay dpy, EGLSurface draw,
2101        EGLint left, EGLint top, EGLint width, EGLint height)
2102{
2103    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
2104        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
2105
2106    egl_surface_t* d = static_cast<egl_surface_t*>(draw);
2107    if (!d->isValid())
2108        return setError(EGL_BAD_SURFACE, EGL_FALSE);
2109    if (d->dpy != dpy)
2110        return setError(EGL_BAD_DISPLAY, EGL_FALSE);
2111
2112    // post the surface
2113    d->setSwapRectangle(left, top, width, height);
2114
2115    return EGL_TRUE;
2116}
2117
2118EGLClientBuffer eglGetRenderBufferANDROID(EGLDisplay dpy, EGLSurface draw)
2119{
2120    if (egl_display_t::is_valid(dpy) == EGL_FALSE)
2121        return setError(EGL_BAD_DISPLAY, (EGLClientBuffer)0);
2122
2123    egl_surface_t* d = static_cast<egl_surface_t*>(draw);
2124    if (!d->isValid())
2125        return setError(EGL_BAD_SURFACE, (EGLClientBuffer)0);
2126    if (d->dpy != dpy)
2127        return setError(EGL_BAD_DISPLAY, (EGLClientBuffer)0);
2128
2129    // post the surface
2130    return d->getRenderBuffer();
2131}
2132