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