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