~alan-griffiths/mir/fix-1654023

« back to all changes in this revision

Viewing changes to examples/eglsquare.cpp

  • Committer: Daniel van Vugt
  • Date: 2015-04-28 07:54:10 UTC
  • mfrom: (2517 development-branch)
  • mto: This revision was merged to the branch mainline in revision 2673.
  • Revision ID: daniel.van.vugt@canonical.com-20150428075410-rwskshfuar7voesp
Merge latest trunk and fix conflicts.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * Copyright © 2015 Canonical Ltd.
 
3
 *
 
4
 * This program is free software: you can redistribute it and/or modify
 
5
 * it under the terms of the GNU General Public License version 3 as
 
6
 * published by the Free Software Foundation.
 
7
 *
 
8
 * This program is distributed in the hope that it will be useful,
 
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
 * GNU General Public License for more details.
 
12
 *
 
13
 * You should have received a copy of the GNU General Public License
 
14
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
15
 *
 
16
 * Authored by: Kevin DuBois <kevin.dubois@canonical.com>
 
17
 */
 
18
 
 
19
#include "mir_toolkit/mir_client_library.h"
 
20
#include <EGL/egl.h>
 
21
#include <GLES2/gl2.h>
 
22
#include <thread>
 
23
#include <memory>
 
24
#include <chrono>
 
25
#include <iostream>
 
26
#include <cstring>
 
27
#include <unistd.h>
 
28
#include <signal.h>
 
29
 
 
30
namespace
 
31
{
 
32
class Connection
 
33
{
 
34
public:
 
35
    Connection(char const* socket_file) :
 
36
        connection(mir_connect_sync(socket_file, __PRETTY_FUNCTION__))
 
37
    {
 
38
        if (!mir_connection_is_valid(connection))
 
39
            throw std::runtime_error(std::string("could not connect to server: ") +
 
40
                                     mir_connection_get_error_message(connection));
 
41
    }
 
42
    ~Connection()
 
43
    {
 
44
        mir_connection_release(connection);
 
45
    }
 
46
    operator MirConnection*() { return connection; }
 
47
    Connection(Connection const&) = delete;
 
48
    Connection& operator=(Connection const&) = delete;
 
49
private:
 
50
    MirConnection* connection;
 
51
};
 
52
 
 
53
class Context
 
54
{
 
55
public:
 
56
    Context(Connection& connection, MirSurface* surface, int swap_interval) :
 
57
        native_display(reinterpret_cast<EGLNativeDisplayType>(
 
58
            mir_connection_get_egl_native_display(connection))),
 
59
        native_window(reinterpret_cast<EGLNativeWindowType>(
 
60
            mir_buffer_stream_get_egl_native_window(mir_surface_get_buffer_stream(surface)))),
 
61
        display(native_display),
 
62
        config(chooseconfig(display.disp)),
 
63
        surface(display.disp, config, native_window),
 
64
        context(display.disp, config)
 
65
    {
 
66
        make_current();
 
67
        eglSwapInterval(display.disp, swap_interval);
 
68
    }
 
69
    void make_current()
 
70
    {
 
71
        if (eglMakeCurrent(display.disp, surface.surface, surface.surface, context.context) == EGL_FALSE)
 
72
            throw(std::runtime_error("could not makecurrent"));
 
73
    }
 
74
    void release_current()
 
75
    {
 
76
        if (eglMakeCurrent(display.disp, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT) == EGL_FALSE)
 
77
            throw(std::runtime_error("could not makecurrent"));
 
78
    }
 
79
    void swapbuffers()
 
80
    {
 
81
        if (eglSwapBuffers(display.disp, surface.surface) == EGL_FALSE)
 
82
            throw(std::runtime_error("could not swapbuffers"));
 
83
    }
 
84
    Context(Context const&) = delete;
 
85
    Context& operator=(Context const&) = delete;
 
86
private:
 
87
    EGLConfig chooseconfig(EGLDisplay disp)
 
88
    {
 
89
        int n{0};
 
90
        EGLConfig egl_config;
 
91
        EGLint attribs[] = {
 
92
            EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
 
93
            EGL_RED_SIZE, 8,
 
94
            EGL_GREEN_SIZE, 8,
 
95
            EGL_BLUE_SIZE, 8,
 
96
            EGL_ALPHA_SIZE, 8,
 
97
            EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
 
98
            EGL_NONE };
 
99
        if (eglChooseConfig(disp, attribs, &egl_config, 1, &n) != EGL_TRUE || n != 1)
 
100
            throw std::runtime_error("could not find egl config");
 
101
        return egl_config;
 
102
    }
 
103
    EGLNativeDisplayType native_display;
 
104
    EGLNativeWindowType native_window;
 
105
    struct Display
 
106
    {
 
107
        Display(EGLNativeDisplayType native) :
 
108
            disp(eglGetDisplay(native))
 
109
        {
 
110
            int major{0}, minor{0};
 
111
            if (disp == EGL_NO_DISPLAY)
 
112
                throw std::runtime_error("no egl display");
 
113
            if (eglInitialize(disp, &major, &minor) != EGL_TRUE || major != 1 || minor != 4)
 
114
                throw std::runtime_error("could not init egl");
 
115
        }
 
116
        ~Display()
 
117
        {
 
118
            eglTerminate(disp);
 
119
        }
 
120
        EGLDisplay disp;
 
121
    } display;
 
122
    EGLConfig config;
 
123
    struct Surface
 
124
    {
 
125
        Surface(EGLDisplay display, EGLConfig config, EGLNativeWindowType native_window) :
 
126
            disp(display),
 
127
            surface(eglCreateWindowSurface(disp, config, native_window, NULL))
 
128
        {
 
129
            if (surface == EGL_NO_SURFACE)
 
130
                throw std::runtime_error("could not create egl surface");
 
131
        }
 
132
        ~Surface() {
 
133
            if (eglGetCurrentSurface(EGL_DRAW) == surface)
 
134
                eglMakeCurrent(disp, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
 
135
            eglDestroySurface(disp, surface);
 
136
         }
 
137
        EGLDisplay disp;
 
138
        EGLSurface surface;
 
139
    } surface;
 
140
    struct EglContext
 
141
    {
 
142
        EglContext(EGLDisplay disp, EGLConfig config) :
 
143
            disp(disp),
 
144
            context(eglCreateContext(disp, config, EGL_NO_CONTEXT, context_attribs))
 
145
        {
 
146
            if (context == EGL_NO_CONTEXT)
 
147
                throw std::runtime_error("could not create egl context");
 
148
        }
 
149
        ~EglContext()
 
150
        {
 
151
            eglDestroyContext(disp, context);
 
152
        }
 
153
        EGLint context_attribs[3] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
 
154
        EGLDisplay disp;
 
155
        EGLContext context;
 
156
    } context;
 
157
};
 
158
 
 
159
class RenderProgram
 
160
{
 
161
public:
 
162
    RenderProgram(Context& context, unsigned int width, unsigned int height) :
 
163
        vertex(&vtex_shader_src, GL_VERTEX_SHADER),
 
164
        fragment(&frag_shader_src, GL_FRAGMENT_SHADER),
 
165
        program(vertex, fragment)
 
166
    {
 
167
        float square_side = 400.0f;
 
168
        float scale[2] {square_side/width, square_side/height};
 
169
        glUseProgram(program.program);
 
170
        vPositionAttr = glGetAttribLocation(program.program, "vPosition");
 
171
        glVertexAttribPointer(vPositionAttr, 4, GL_FLOAT, GL_FALSE, 0, vertex_data);
 
172
        posUniform = glGetUniformLocation(program.program, "pos");
 
173
        glClearColor(0.1, 0.1, 0.4, 1.0); //light blue
 
174
        glClear(GL_COLOR_BUFFER_BIT);
 
175
        auto scaleUniform = glGetUniformLocation(program.program, "scale");
 
176
        glUniform2fv(scaleUniform, 1, scale);
 
177
 
 
178
        context.swapbuffers();
 
179
        context.release_current();
 
180
    }
 
181
 
 
182
    void draw(float x, float y)
 
183
    {
 
184
        float pos[2] = {x, y}; 
 
185
        glUseProgram(program.program);
 
186
        glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
 
187
        glUniform2fv(posUniform, 1, pos);
 
188
        glEnableVertexAttribArray(vPositionAttr);
 
189
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
 
190
        glDisableVertexAttribArray(vPositionAttr);
 
191
    }
 
192
 
 
193
    RenderProgram(RenderProgram const&) = delete;
 
194
    RenderProgram& operator=(RenderProgram const&) = delete; 
 
195
private:
 
196
    GLchar const*const frag_shader_src =
 
197
    {
 
198
        "precision mediump float;"
 
199
        "void main() {"
 
200
        "   gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);"
 
201
        "}"
 
202
    };
 
203
    GLchar const*const vtex_shader_src =
 
204
    {
 
205
        "attribute vec4 vPosition;"
 
206
        "uniform vec2 pos;"
 
207
        "uniform vec2 scale;"
 
208
        "void main() {"
 
209
        "   gl_Position = vec4(vPosition.xy * scale + pos, 0.0, 1.0);"
 
210
        "}"
 
211
    };
 
212
    struct Shader
 
213
    {
 
214
        Shader(GLchar const* const* src, GLuint type) :
 
215
            shader(glCreateShader(type))
 
216
        {
 
217
            glShaderSource(shader, 1, src, 0);
 
218
            glCompileShader(shader);
 
219
        }
 
220
        ~Shader()
 
221
        {
 
222
            glDeleteShader(shader);
 
223
        }
 
224
        GLuint shader;
 
225
    } vertex, fragment;
 
226
    struct Program
 
227
    {
 
228
        Program(Shader& vertex, Shader& fragment) :
 
229
            program(glCreateProgram())
 
230
        {
 
231
            glAttachShader(program, vertex.shader);
 
232
            glAttachShader(program, fragment.shader);
 
233
            glLinkProgram(program);
 
234
        }
 
235
        ~Program()
 
236
        {
 
237
            glDeleteProgram(program);
 
238
        }
 
239
        GLuint program;
 
240
    } program;
 
241
    GLfloat vertex_data[16]
 
242
    {
 
243
        -1.0, -1.0f, 0.0f, 1.0f,
 
244
        -1.0f,  1.0f, 0.0f, 1.0f,
 
245
         1.0f, -1.0f, 0.0f, 1.0f,
 
246
         1.0f,  1.0f, 0.0f, 1.0f,
 
247
    };
 
248
    GLuint vPositionAttr;
 
249
    GLuint posUniform; 
 
250
};
 
251
 
 
252
class Surface
 
253
{
 
254
public:
 
255
    Surface(Connection& connection, int swap_interval) :
 
256
        dimensions(active_output_dimensions(connection)),
 
257
        surface{create_surface(connection, dimensions), surface_deleter},
 
258
        context{connection, surface.get(), swap_interval},
 
259
        program{context, dimensions.width, dimensions.height}
 
260
    {
 
261
    }
 
262
 
 
263
    void on_event(MirEvent const* ev)
 
264
    {
 
265
        if (mir_event_get_type(ev) != mir_event_type_input)
 
266
            return;
 
267
        float x{0.0f};
 
268
        float y{0.0f};
 
269
        auto ievent = mir_event_get_input_event(ev);
 
270
        if (mir_input_event_get_type(ievent) == mir_input_event_type_touch)
 
271
        {
 
272
            auto tev = mir_input_event_get_touch_event(ievent);
 
273
            x = mir_touch_event_axis_value(tev, 0, mir_touch_axis_x);
 
274
            y = mir_touch_event_axis_value(tev, 0, mir_touch_axis_y);
 
275
        }
 
276
        else if (mir_input_event_get_type(ievent) == mir_input_event_type_pointer)
 
277
        {
 
278
            auto pev = mir_input_event_get_pointer_event(ievent);
 
279
            x = mir_pointer_event_axis_value(pev, mir_pointer_axis_x);
 
280
            y = mir_pointer_event_axis_value(pev, mir_pointer_axis_y);
 
281
        }
 
282
        else
 
283
        {
 
284
            return;
 
285
        }
 
286
        context.make_current();
 
287
        program.draw(
 
288
            x/static_cast<float>(dimensions.width)*2.0 - 1.0,
 
289
            y/static_cast<float>(dimensions.height)*-2.0 + 1.0);
 
290
        context.swapbuffers();
 
291
    }
 
292
 
 
293
    Surface(Surface const&) = delete;
 
294
    Surface& operator=(Surface const&) = delete;
 
295
private:
 
296
    struct OutputDimensions
 
297
    {
 
298
        unsigned int const width;
 
299
        unsigned int const height;
 
300
    } const dimensions;
 
301
 
 
302
 
 
303
    std::function<void(MirSurface*)> const surface_deleter{
 
304
        [](MirSurface* surface)
 
305
        {
 
306
            mir_surface_release_sync(surface);
 
307
        }
 
308
    };
 
309
    std::unique_ptr<MirSurface, decltype(surface_deleter)> surface;
 
310
    Context context;
 
311
    RenderProgram program;
 
312
 
 
313
    OutputDimensions active_output_dimensions(MirConnection* connection)
 
314
    {
 
315
        unsigned int width{0};
 
316
        unsigned int height{0};
 
317
        auto display_config = mir_connection_create_display_config(connection);
 
318
        for (auto i = 0u; i < display_config->num_outputs; i++)
 
319
        {
 
320
            MirDisplayOutput const* out = display_config->outputs + i;
 
321
            if (out->used &&
 
322
                out->connected &&
 
323
                out->num_modes &&
 
324
                out->current_mode < out->num_modes)
 
325
            {
 
326
                width = out->modes[out->current_mode].horizontal_resolution;
 
327
                height = out->modes[out->current_mode].vertical_resolution;
 
328
                break;
 
329
            }
 
330
        }
 
331
        mir_display_config_destroy(display_config);
 
332
        if (width == 0 || height == 0)
 
333
            throw std::logic_error("could not determine display size");
 
334
        return {width, height};
 
335
    }
 
336
 
 
337
    MirSurface* create_surface(MirConnection* connection, OutputDimensions const& dim)
 
338
    {
 
339
        MirPixelFormat selected_format;
 
340
        unsigned int valid_formats{0};
 
341
        MirPixelFormat pixel_formats[mir_pixel_formats];
 
342
        mir_connection_get_available_surface_formats(connection, pixel_formats, mir_pixel_formats, &valid_formats);
 
343
        if (valid_formats == 0)
 
344
            throw std::runtime_error("no pixel formats for surface");
 
345
        selected_format = pixel_formats[0]; 
 
346
        //select an 8 bit opaque format if we can
 
347
        for(auto i = 0u; i < valid_formats; i++)
 
348
        {
 
349
            if (pixel_formats[i] == mir_pixel_format_xbgr_8888 ||
 
350
                pixel_formats[i] == mir_pixel_format_xrgb_8888)
 
351
            {
 
352
                selected_format = pixel_formats[i];
 
353
                break;
 
354
            }
 
355
        }
 
356
 
 
357
        auto deleter = [](MirSurfaceSpec *spec) { mir_surface_spec_release(spec); };
 
358
        std::unique_ptr<MirSurfaceSpec, decltype(deleter)> spec{
 
359
            mir_connection_create_spec_for_normal_surface(connection, dim.width, dim.height, selected_format),
 
360
            deleter
 
361
        };
 
362
 
 
363
        mir_surface_spec_set_name(spec.get(), __PRETTY_FUNCTION__);
 
364
        mir_surface_spec_set_buffer_usage(spec.get(), mir_buffer_usage_hardware);
 
365
        auto surface = mir_surface_create_sync(spec.get());
 
366
        mir_surface_set_event_handler(surface, &on_event, this);
 
367
        return surface;
 
368
    }
 
369
    static void on_event(MirSurface*, const MirEvent *event, void *context)
 
370
    {
 
371
        auto surface = reinterpret_cast<Surface*>(context);
 
372
        if (surface) surface->on_event(event);
 
373
    }
 
374
};
 
375
 
 
376
}
 
377
 
 
378
int main(int argc, char *argv[])
 
379
try
 
380
{
 
381
    using namespace std::literals::chrono_literals;
 
382
 
 
383
    auto arg = 0;
 
384
    char const* socket_file = nullptr;
 
385
    int swap_interval = 1;
 
386
    while ((arg = getopt (argc, argv, "nm:")) != -1)
 
387
    {
 
388
        switch (arg)
 
389
        {
 
390
        case 'm':
 
391
            socket_file = optarg;
 
392
            break;
 
393
        case 'n':
 
394
            swap_interval = 0;
 
395
            break;
 
396
        default:
 
397
            throw std::invalid_argument("invalid command line argument");
 
398
        }
 
399
    }
 
400
 
 
401
    Connection connection(socket_file);
 
402
    Surface surface(connection, swap_interval);
 
403
 
 
404
    sigset_t sigset;
 
405
    siginfo_t siginfo;
 
406
    sigemptyset(&sigset);
 
407
    sigaddset(&sigset, SIGTERM);
 
408
    sigaddset(&sigset, SIGINT);
 
409
    sigprocmask(SIG_BLOCK, &sigset, nullptr);
 
410
    sigwaitinfo(&sigset, &siginfo);
 
411
    return 0;
 
412
}
 
413
catch(std::exception& e)
 
414
{
 
415
    std::cerr << "error : " << e.what() << std::endl;
 
416
    return 1;
 
417
}