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