summaryrefslogtreecommitdiff
path: root/stream-servers/glestranslator/EGL/EglOsApi_egl.cpp
blob: 3d3037df784e277f102f7de860565f2f850b52d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "EglOsApi.h"

#include "base/System.h"
#include "base/SharedLibrary.h"
#include "host-common/misc.h"
#include "GLcommon/GLLibrary.h"
#include "apigen-codec-common/ErrorLog.h"
#include "ShaderCache.h"

#ifdef ANDROID
#include <android/native_window.h>
#endif

#ifdef __linux__
#include "apigen-codec-common/X11Support.h"
#endif

#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <EGL/eglext_angle.h>
#include <GLES2/gl2.h>
#include <memory>
#include <vector>

#define DEBUG 0
#if DEBUG
#define D(...) fprintf(stderr, __VA_ARGS__);
#define CHECK_EGL_ERR                                                 \
    {                                                                 \
        EGLint err = mDispatcher.eglGetError();                       \
        if (err != EGL_SUCCESS)                                       \
            D("%s: %s %d get egl error %d\n", __FUNCTION__, __FILE__, \
              __LINE__, err);                                         \
    }
#else
#define D(...) ((void)0);
#define CHECK_EGL_ERR ((void)0);
#endif

#if defined(__WIN32) || defined(_MSC_VER)

static const char* kEGLLibName = "libEGL.dll";
static const char* kGLES2LibName = "libGLESv2.dll";

#elif defined(__linux__)


static const char* kEGLLibName = "libEGL.so";
static const char* kGLES2LibName = "libGLESv2.so";

static const char* kEGLLibNameAlt = "libEGL.so.1";
static const char* kGLES2LibNameAlt = "libGLESv2.so.2";

#else // __APPLE__

#include "MacNative.h"

static const char* kEGLLibName = "libEGL.dylib";
static const char* kGLES2LibName = "libGLESv2.dylib";

#endif // __APPLE__

// List of EGL functions of interest to probe with GetProcAddress()
#define LIST_EGL_FUNCTIONS(X)                                                  \
    X(void*, eglGetProcAddress,                                           \
      (const char* procname))                                                  \
    X(const char*, eglQueryString,                                             \
      (EGLDisplay dpy, EGLint id))                                             \
    X(EGLDisplay, eglGetPlatformDisplay,                                    \
      (EGLenum platform, void *native_display, const EGLAttrib *attrib_list))  \
    X(EGLDisplay, eglGetPlatformDisplayEXT,                                    \
      (EGLenum platform, void *native_display, const EGLint *attrib_list))     \
    X(EGLBoolean, eglBindAPI,                                    \
      (EGLenum api)) \
    X(EGLBoolean, eglChooseConfig,                                             \
      (EGLDisplay display, EGLint const* attrib_list, EGLConfig* configs,      \
       EGLint config_size, EGLint* num_config))                                \
    X(EGLContext, eglCreateContext,                                            \
      (EGLDisplay display, EGLConfig config, EGLContext share_context,         \
       EGLint const* attrib_list))                                             \
    X(EGLSurface, eglCreatePbufferSurface,                                     \
      (EGLDisplay display, EGLConfig config, EGLint const* attrib_list))       \
    X(EGLBoolean, eglDestroyContext, (EGLDisplay display, EGLContext context)) \
    X(EGLBoolean, eglDestroySurface, (EGLDisplay display, EGLSurface surface)) \
    X(EGLBoolean, eglGetConfigAttrib,                                          \
      (EGLDisplay display, EGLConfig config, EGLint attribute,                 \
       EGLint * value))                                                        \
    X(EGLDisplay, eglGetDisplay, (NativeDisplayType native_display))           \
    X(EGLint, eglGetError, (void))                                             \
    X(EGLBoolean, eglInitialize,                                               \
      (EGLDisplay display, EGLint * major, EGLint * minor))                    \
    X(EGLBoolean, eglMakeCurrent,                                              \
      (EGLDisplay display, EGLSurface draw, EGLSurface read,                   \
       EGLContext context))                                                    \
    X(EGLBoolean, eglSwapBuffers, (EGLDisplay display, EGLSurface surface))    \
    X(EGLSurface, eglCreateWindowSurface,                                      \
      (EGLDisplay display, EGLConfig config,                                   \
       EGLNativeWindowType native_window, EGLint const* attrib_list))          \
    X(EGLBoolean, eglSwapInterval,                                             \
      (EGLDisplay display, EGLint interval))                                   \
    X(void, eglSetBlobCacheFuncsANDROID, (EGLDisplay display,                  \
        EGLSetBlobFuncANDROID set, EGLGetBlobFuncANDROID get))

namespace {
using namespace EglOS;

class EglOsEglDispatcher {
public:
#define DECLARE_EGL_POINTER(return_type, function_name, signature) \
    return_type(EGLAPIENTRY* function_name) signature = nullptr;
    LIST_EGL_FUNCTIONS(DECLARE_EGL_POINTER);

    EglOsEglDispatcher() {
        D("loading %s\n", kEGLLibName);
        char error[256];
        mLib = android::base::SharedLibrary::open(kEGLLibName, error, sizeof(error));
        if (!mLib) {
#ifdef __linux__
            ERR("%s: Could not open EGL library %s [%s]. Trying again with [%s]\n", __FUNCTION__,
                kEGLLibName, error, kEGLLibNameAlt);
            mLib = android::base::SharedLibrary::open(kEGLLibNameAlt, error, sizeof(error));
            if (!mLib) {
                ERR("%s: Could not open EGL library %s [%s]\n", __FUNCTION__,
                    kEGLLibNameAlt, error);
            }
#else
            ERR("%s: Could not open EGL library %s [%s]\n", __FUNCTION__,
                kEGLLibName, error);
#endif
        }

#define LOAD_EGL_POINTER(return_type, function_name, signature)        \
    this->function_name =                                              \
            reinterpret_cast<return_type(GL_APIENTRY*) signature>(     \
                    mLib->findSymbol(#function_name));                 \
    if (!this->function_name) {                                        \
        this->function_name =                                          \
                reinterpret_cast<return_type(GL_APIENTRY*) signature>( \
                        this->eglGetProcAddress(#function_name));      \
    } \
    if (!this->function_name) {                                        \
        D("%s: Could not find %s in underlying EGL library\n",         \
          __FUNCTION__,                                                \
          #function_name);                                             \
    }

        LIST_EGL_FUNCTIONS(LOAD_EGL_POINTER);
    }
    ~EglOsEglDispatcher() = default;

private:
    android::base::SharedLibrary* mLib = nullptr;
};

class EglOsGlLibrary : public GlLibrary {
public:
    EglOsGlLibrary() {
        char error[256];
        mLib = android::base::SharedLibrary::open(kGLES2LibName, error, sizeof(error));
        if (!mLib) {
#ifdef __linux__
            ERR("%s: Could not open GL library %s [%s]. Trying again with [%s]\n", __FUNCTION__,
                kGLES2LibName, error, kGLES2LibNameAlt);
            mLib = android::base::SharedLibrary::open(kGLES2LibNameAlt, error, sizeof(error));
            if (!mLib) {
                ERR("%s: Could not open GL library %s [%s]\n", __FUNCTION__,
                    kGLES2LibNameAlt, error);
            }
#else
            ERR("%s: Could not open GL library %s [%s]\n", __FUNCTION__,
                kGLES2LibName, error);
#endif
        }
    }
    GlFunctionPointer findSymbol(const char* name) {
        if (!mLib) {
            return NULL;
        }
        return reinterpret_cast<GlFunctionPointer>(mLib->findSymbol(name));
    }
    ~EglOsGlLibrary() = default;

private:
    android::base::SharedLibrary* mLib = nullptr;
};

class EglOsEglPixelFormat : public EglOS::PixelFormat {
public:
    EglOsEglPixelFormat(EGLConfig configId, EGLint clientCtxVer)
        : mConfigId(configId), mClientCtxVer(clientCtxVer) {}
    PixelFormat* clone() {
        return new EglOsEglPixelFormat(mConfigId, mClientCtxVer);
    }
    EGLConfig mConfigId;
    EGLint mClientCtxVer;
#ifdef __APPLE__
    int mRedSize = 0;
    int mGreenSize = 0;
    int mBlueSize = 0;
#endif // __APPLE__
};

class EglOsEglContext : public EglOS::Context {
public:
    EglOsEglContext(EglOsEglDispatcher* dispatcher,
                    EGLDisplay display,
                    EGLContext context) :
        mDispatcher(dispatcher),
        mDisplay(display),
        mNativeCtx(context) { }

    ~EglOsEglContext() {
        D("%s %p\n", __FUNCTION__, mNativeCtx);
        if (!mDispatcher->eglDestroyContext(mDisplay, mNativeCtx)) {
            // TODO: print a better error message
        }
    }

    EGLContext context() const {
        return mNativeCtx;
    }

private:
    EglOsEglDispatcher* mDispatcher = nullptr;
    EGLDisplay mDisplay;
    EGLContext mNativeCtx;
};

class EglOsEglSurface : public EglOS::Surface {
public:
    EglOsEglSurface(SurfaceType type,
                    EGLSurface eglSurface,
                    EGLNativeWindowType win = 0)
        : EglOS::Surface(type), mHndl(eglSurface), mWin(win) {}
    EGLSurface getHndl() { return mHndl; }
    EGLNativeWindowType getWin() { return mWin; }

private:
    EGLSurface mHndl;
    EGLNativeWindowType mWin;
};

class EglOsEglDisplay : public EglOS::Display {
public:
    EglOsEglDisplay();
    ~EglOsEglDisplay();
    virtual EglOS::GlesVersion getMaxGlesVersion();
    void queryConfigs(int renderableType,
                      AddConfigCallback* addConfigFunc,
                      void* addConfigOpaque);
    virtual std::shared_ptr<Context>
    createContext(EGLint profileMask,
                  const PixelFormat* pixelFormat,
                  Context* sharedContext) override;
    Surface* createPbufferSurface(const PixelFormat* pixelFormat,
                                  const PbufferInfo* info);
    Surface* createWindowSurface(PixelFormat* pf, EGLNativeWindowType win);
    bool releasePbuffer(Surface* pb);
    bool makeCurrent(Surface* read, Surface* draw, Context* context);
    void swapBuffers(Surface* srfc);
    bool isValidNativeWin(Surface* win);
    bool isValidNativeWin(EGLNativeWindowType win);
    bool checkWindowPixelFormatMatch(EGLNativeWindowType win,
                                     const PixelFormat* pixelFormat,
                                     unsigned int* width,
                                     unsigned int* height);
    void* eglGetProcAddress(const char* func) {
        return mDispatcher.eglGetProcAddress(func);
    }

private:
    bool mVerbose = false;
    EGLDisplay mDisplay;
    EglOsEglDispatcher mDispatcher;
    bool mHeadless = false;

#ifdef __linux__
    ::Display* mGlxDisplay = nullptr;
#endif // __linux__
};

EglOsEglDisplay::EglOsEglDisplay() {
    mVerbose = android::base::getEnvironmentVariable("ANDROID_EMUGL_VERBOSE") == "1";

    if (android::base::getEnvironmentVariable("ANDROID_EMUGL_EXPERIMENTAL_FAST_PATH") == "1") {
        const EGLAttrib attr[] = {
            EGL_PLATFORM_ANGLE_TYPE_ANGLE,
            EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE,
            EGL_EXPERIMENTAL_PRESENT_PATH_ANGLE,
            EGL_EXPERIMENTAL_PRESENT_PATH_FAST_ANGLE,
            EGL_NONE
        };

        mDisplay = mDispatcher.eglGetPlatformDisplay(EGL_PLATFORM_ANGLE_ANGLE,
            (void*)EGL_DEFAULT_DISPLAY,
            attr);

        if (mDisplay == EGL_NO_DISPLAY) {
            fprintf(stderr, "%s: no display found that supports the requested extensions\n", __func__);
        }
    }
    else {
        mDisplay = mDispatcher.eglGetDisplay(EGL_DEFAULT_DISPLAY);
    }

    mDispatcher.eglInitialize(mDisplay, nullptr, nullptr);
    mDispatcher.eglSwapInterval(mDisplay, 0);
    auto clientExts = mDispatcher.eglQueryString(mDisplay, EGL_EXTENSIONS);

    if (mVerbose) {
        fprintf(stderr, "%s: client exts: [%s]\n", __func__, clientExts);
    }

    mDispatcher.eglBindAPI(EGL_OPENGL_ES_API);
    CHECK_EGL_ERR

    mHeadless = android::base::getEnvironmentVariable("ANDROID_EMU_HEADLESS") == "1";

#ifdef ANDROID
    mGlxDisplay = nullptr;
#elif defined(__linux__)
    if (mHeadless) mGlxDisplay = nullptr;
    else mGlxDisplay = getX11Api()->XOpenDisplay(0);
#endif // __linux__

    if (clientExts != nullptr && emugl::hasExtension(clientExts, "EGL_ANDROID_blob_cache")) {
        mDispatcher.eglSetBlobCacheFuncsANDROID(mDisplay, SetBlob, GetBlob);
    }
};

EglOsEglDisplay::~EglOsEglDisplay() {
#ifdef ANDROID
#elif defined(__linux__)
    if (mGlxDisplay) getX11Api()->XCloseDisplay(mGlxDisplay);
#endif // __linux__
}

EglOS::GlesVersion EglOsEglDisplay::getMaxGlesVersion() {
    // TODO: Detect and return the highest version like in GLESVersionDetector.cpp
    return EglOS::GlesVersion::ES30;
}

void EglOsEglDisplay::queryConfigs(int renderableType,
                                   AddConfigCallback* addConfigFunc,
                                   void* addConfigOpaque) {
    D("%s\n", __FUNCTION__);
    // ANGLE does not support GLES1 uses core profile engine.
    // Querying underlying EGL with a conservative set of bits.
    renderableType &= ~EGL_OPENGL_ES_BIT;

    const EGLint framebuffer_config_attributes[] = {
        EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
        EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT,
        EGL_RED_SIZE, 1,
        EGL_GREEN_SIZE, 1,
        EGL_BLUE_SIZE, 1,
        EGL_ALPHA_SIZE, 0,
        EGL_NONE,
    };

    EGLint numConfigs = 0;
    mDispatcher.eglChooseConfig(mDisplay, framebuffer_config_attributes, nullptr, 0, &numConfigs);
    CHECK_EGL_ERR
    std::unique_ptr<EGLConfig[]> configs(new EGLConfig[numConfigs]);
    mDispatcher.eglChooseConfig(mDisplay, framebuffer_config_attributes, configs.get(), numConfigs,
                                &numConfigs);
    CHECK_EGL_ERR

    if (mVerbose) {
        fprintf(stderr, "%s: num configs: %d\n", __func__, numConfigs);
    }

    for (int i = 0; i < numConfigs; i++) {
        const EGLConfig cfg = configs.get()[i];
        ConfigInfo configInfo;
        // We do not have recordable_android
        configInfo.recordable_android = 0;
        EGLint _renderableType;
        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_RENDERABLE_TYPE,
                                       &_renderableType);
        // We do emulate GLES1
        configInfo.renderable_type = _renderableType | EGL_OPENGL_ES_BIT;

        configInfo.frmt = new EglOsEglPixelFormat(cfg, _renderableType);
        D("config %p renderable type 0x%x\n", cfg, _renderableType);

        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_RED_SIZE,
                                       &configInfo.red_size);
        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_GREEN_SIZE,
                                       &configInfo.green_size);
        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_BLUE_SIZE,
                                       &configInfo.blue_size);
        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_ALPHA_SIZE,
                                       &configInfo.alpha_size);

        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_CONFIG_CAVEAT,
                                       (EGLint*)&configInfo.caveat);
        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_DEPTH_SIZE,
                                       &configInfo.depth_size);
        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_LEVEL,
                                       &configInfo.frame_buffer_level);

        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_MAX_PBUFFER_WIDTH,
                                       &configInfo.max_pbuffer_width);
        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_MAX_PBUFFER_HEIGHT,
                                       &configInfo.max_pbuffer_height);
        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_MAX_PBUFFER_PIXELS,
                                       &configInfo.max_pbuffer_size);

        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_NATIVE_RENDERABLE,
                                       (EGLint*)&configInfo.native_renderable);
        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_NATIVE_VISUAL_ID,
                                       &configInfo.native_visual_id);
        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_NATIVE_VISUAL_TYPE,
                                       &configInfo.native_visual_type);

        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_SAMPLES,
                                       &configInfo.samples_per_pixel);
        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_STENCIL_SIZE,
                                       &configInfo.stencil_size);

        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_SURFACE_TYPE,
                                       &configInfo.surface_type);
        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_TRANSPARENT_TYPE,
                                       (EGLint*)&configInfo.transparent_type);
        mDispatcher.eglGetConfigAttrib(mDisplay, cfg, EGL_TRANSPARENT_RED_VALUE,
                                       &configInfo.trans_red_val);
        mDispatcher.eglGetConfigAttrib(mDisplay, cfg,
                                       EGL_TRANSPARENT_GREEN_VALUE,
                                       &configInfo.trans_green_val);
        mDispatcher.eglGetConfigAttrib(mDisplay, cfg,
                                       EGL_TRANSPARENT_BLUE_VALUE,
                                       &configInfo.trans_blue_val);
        CHECK_EGL_ERR
#ifdef __APPLE__
        ((EglOsEglPixelFormat*)configInfo.frmt)->mRedSize = configInfo.red_size;
        ((EglOsEglPixelFormat*)configInfo.frmt)->mGreenSize = configInfo.green_size;
        ((EglOsEglPixelFormat*)configInfo.frmt)->mBlueSize = configInfo.blue_size;
#endif // __APPLE__
        addConfigFunc(addConfigOpaque, &configInfo);
    }
    D("Host gets %d configs\n", numConfigs);
}

std::shared_ptr<Context>
EglOsEglDisplay::createContext(EGLint profileMask,
                               const PixelFormat* pixelFormat,
                               Context* sharedContext) {
    (void)profileMask;

    D("%s\n", __FUNCTION__);
    const EglOsEglPixelFormat* format = (const EglOsEglPixelFormat*)pixelFormat;
    D("with config %p\n", format->mConfigId);

    // Always GLES3
    std::vector<EGLint> attributes = { EGL_CONTEXT_CLIENT_VERSION, 3 };
    auto exts = mDispatcher.eglQueryString(mDisplay, EGL_EXTENSIONS);
    if (exts != nullptr && emugl::hasExtension(exts, "EGL_KHR_create_context_no_error")) {
        attributes.push_back(EGL_CONTEXT_OPENGL_NO_ERROR_KHR);
        attributes.push_back(EGL_TRUE);
    }

    if (exts != nullptr && emugl::hasExtension(exts, "EGL_EXT_create_context_robustness")) {
        attributes.push_back(EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_EXT);
        attributes.push_back(EGL_LOSE_CONTEXT_ON_RESET_EXT);
    }
    attributes.push_back(EGL_NONE);

    // TODO: support GLES3.1
    EglOsEglContext* nativeSharedCtx = (EglOsEglContext*)sharedContext;
    EGLContext newNativeCtx = mDispatcher.eglCreateContext(
            mDisplay, format->mConfigId,
            nativeSharedCtx ? nativeSharedCtx->context() : nullptr,
            attributes.data());
    CHECK_EGL_ERR
    std::shared_ptr<Context> res =
        std::make_shared<EglOsEglContext>(
            &mDispatcher, mDisplay, newNativeCtx);
    D("%s done\n", __FUNCTION__);
    return res;
}

Surface* EglOsEglDisplay::createPbufferSurface(const PixelFormat* pixelFormat,
                                               const PbufferInfo* info) {
    // D("%s\n", __FUNCTION__);
    // const EglOsEglPixelFormat* format = (const EglOsEglPixelFormat*)pixelFormat;
    // EGLint attrib[] = {EGL_WIDTH,
    //                    info->width,
    //                    EGL_HEIGHT,
    //                    info->height,
    //                    EGL_LARGEST_PBUFFER,
    //                    info->largest,
    //                    EGL_TEXTURE_FORMAT,
    //                    info->format,
    //                    EGL_TEXTURE_TARGET,
    //                    info->target,
    //                    EGL_MIPMAP_TEXTURE,
    //                    info->hasMipmap,
    //                    EGL_NONE};
    // EGLSurface surface = mDispatcher.eglCreatePbufferSurface(
    //         mDisplay, format->mConfigId, attrib);
    // CHECK_EGL_ERR
    // if (surface == EGL_NO_SURFACE) {
    //     D("create pbuffer surface failed\n");
    //     return nullptr;
    // }
    // return new EglOsEglSurface(EglOS::Surface::PBUFFER, surface);
    return new EglOsEglSurface(EglOS::Surface::PBUFFER, 0);
}

Surface* EglOsEglDisplay::createWindowSurface(PixelFormat* pf,
                                              EGLNativeWindowType win) {
    D("%s\n", __FUNCTION__);
    std::vector<EGLint> surface_attribs;
    auto exts = mDispatcher.eglQueryString(mDisplay, EGL_EXTENSIONS);
    if (exts != nullptr && emugl::hasExtension(exts, "EGL_ANGLE_direct_composition")) {
        surface_attribs.push_back(EGL_DIRECT_COMPOSITION_ANGLE);
        surface_attribs.push_back(EGL_TRUE);
    }
    surface_attribs.push_back(EGL_NONE);
    EGLSurface surface = mDispatcher.eglCreateWindowSurface(
            mDisplay, ((EglOsEglPixelFormat*)pf)->mConfigId, win, surface_attribs.data());
    CHECK_EGL_ERR
    if (surface == EGL_NO_SURFACE) {
        D("create window surface failed\n");
        return nullptr;
    }
    return new EglOsEglSurface(EglOS::Surface::WINDOW, surface, win);
}

bool EglOsEglDisplay::releasePbuffer(Surface* pb) {
    D("%s\n", __FUNCTION__);
    if (!pb)
        return false;
    EglOsEglSurface* surface = (EglOsEglSurface*)pb;

    if (!surface->getHndl()) {
        delete surface;
        return true;
    }

    bool ret = mDispatcher.eglDestroySurface(mDisplay, surface->getHndl());
    CHECK_EGL_ERR
    D("%s done\n", __FUNCTION__);
    delete surface;
    return ret;
}

bool EglOsEglDisplay::makeCurrent(Surface* read,
                                  Surface* draw,
                                  Context* context) {
    D("%s\n", __FUNCTION__);
    EglOsEglSurface* readSfc = (EglOsEglSurface*)read;
    EglOsEglSurface* drawSfc = (EglOsEglSurface*)draw;
    EglOsEglContext* ctx = (EglOsEglContext*)context;
    if (ctx && !readSfc) {
        D("warning: makeCurrent a context without surface\n");
        return false;
    }
    D("%s %p\n", __FUNCTION__, ctx ? ctx->context() : nullptr);
    bool ret = mDispatcher.eglMakeCurrent(
            mDisplay, drawSfc ? drawSfc->getHndl() : EGL_NO_SURFACE,
            readSfc ? readSfc->getHndl() : EGL_NO_SURFACE,
            ctx ? ctx->context() : EGL_NO_CONTEXT);
    if (readSfc) {
        D("make current surface type %d %d\n", readSfc->type(),
          drawSfc->type());
    }
    D("make current %d\n", ret);
    CHECK_EGL_ERR
    return ret;
}

void EglOsEglDisplay::swapBuffers(Surface* surface) {
    D("%s\n", __FUNCTION__);
    EglOsEglSurface* sfc = (EglOsEglSurface*)surface;
    mDispatcher.eglSwapBuffers(mDisplay, sfc->getHndl());
}

bool EglOsEglDisplay::isValidNativeWin(Surface* win) {
    if (!win)
        return false;
    EglOsEglSurface* surface = (EglOsEglSurface*)win;
    return surface->type() == EglOsEglSurface::WINDOW &&
           isValidNativeWin(surface->getWin());
}

bool EglOsEglDisplay::isValidNativeWin(EGLNativeWindowType win) {
#ifdef _WIN32
    return IsWindow(win);
#elif defined(ANDROID)
    return true;
#elif defined(__linux__)
    Window root;
    int t;
    unsigned int u;
    return getX11Api()->XGetGeometry(mGlxDisplay, win, &root, &t, &t, &u, &u, &u, &u) != 0;
#else // __APPLE__
    unsigned int width, height;
    return nsGetWinDims(win, &width, &height);
#endif // __APPLE__
}

bool EglOsEglDisplay::checkWindowPixelFormatMatch(EGLNativeWindowType win,
                                 const PixelFormat* pixelFormat,
                                 unsigned int* width,
                                 unsigned int* height) {
#ifdef _WIN32
    RECT r;
    if (!GetClientRect(win, &r)) {
        return false;
    }
    *width = r.right - r.left;
    *height = r.bottom - r.top;
    return true;
#elif defined(ANDROID)
    *width = ANativeWindow_getWidth((ANativeWindow*)win);
    *height = ANativeWindow_getHeight((ANativeWindow*)win);
    return true;
#elif defined(__linux__)
    //TODO: to check what does ATI & NVIDIA enforce on win pixelformat
    unsigned int depth, border;
    int x, y;
    Window root;
    return getX11Api()->XGetGeometry(
            mGlxDisplay, win, &root, &x, &y, width, height, &border, &depth);
#else // __APPLE__
    bool ret = nsGetWinDims(win, width, height);

    const EglOsEglPixelFormat* format = (EglOsEglPixelFormat*)pixelFormat;
    int r = format->mRedSize;
    int g = format->mGreenSize;
    int b = format->mBlueSize;

    bool match = nsCheckColor(win, r + g + b);

    return ret && match;
#endif // __APPLE__
}

static EglOsEglDisplay* sHostDisplay() {
    static EglOsEglDisplay* d = new EglOsEglDisplay;
    return d;
}

class EglEngine : public EglOS::Engine {
public:
    EglEngine() = default;
    ~EglEngine() = default;

    EglOS::Display* getDefaultDisplay() {
        D("%s\n", __FUNCTION__);
        return sHostDisplay();
    }
    GlLibrary* getGlLibrary() {
        D("%s\n", __FUNCTION__);
        return &mGlLib;
    }
    void* eglGetProcAddress(const char* func) {
        return sHostDisplay()->eglGetProcAddress(func);
    }
    virtual EglOS::Surface* createWindowSurface(PixelFormat* pf,
                                                EGLNativeWindowType wnd) {
        D("%s\n", __FUNCTION__);
        return sHostDisplay()->createWindowSurface(pf, wnd);
    }

private:
    EglOsGlLibrary mGlLib;
};

}  // namespace

static EglEngine* sHostEngine() {
    static EglEngine* res = new EglEngine;
    return res;
}

namespace EglOS {
Engine* getEgl2EglHostInstance() {
    D("%s\n", __FUNCTION__);
    return sHostEngine();
}
}  // namespace EglOS