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