input: Rename weston_device_repick() to weston_seat_repick()
[platform/upstream/weston.git] / src / gl-renderer.c
1 /*
2  * Copyright © 2012 Intel Corporation
3  *
4  * Permission to use, copy, modify, distribute, and sell this software and
5  * its documentation for any purpose is hereby granted without fee, provided
6  * that the above copyright notice appear in all copies and that both that
7  * copyright notice and this permission notice appear in supporting
8  * documentation, and that the name of the copyright holders not be used in
9  * advertising or publicity pertaining to distribution of the software
10  * without specific, written prior permission.  The copyright holders make
11  * no representations about the suitability of this software for any
12  * purpose.  It is provided "as is" without express or implied warranty.
13  *
14  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
15  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
16  * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
17  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
18  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
19  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
20  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21  */
22
23 #define _GNU_SOURCE
24
25 #include <GLES2/gl2.h>
26 #include <GLES2/gl2ext.h>
27
28 #include <stdlib.h>
29 #include <string.h>
30 #include <ctype.h>
31 #include <float.h>
32 #include <assert.h>
33 #include <linux/input.h>
34
35 #include "gl-renderer.h"
36
37 #include <EGL/eglext.h>
38 #include "weston-egl-ext.h"
39
40 struct gl_shader {
41         GLuint program;
42         GLuint vertex_shader, fragment_shader;
43         GLint proj_uniform;
44         GLint tex_uniforms[3];
45         GLint alpha_uniform;
46         GLint color_uniform;
47 };
48
49 #define BUFFER_DAMAGE_COUNT 2
50
51 struct gl_output_state {
52         EGLSurface egl_surface;
53         pixman_region32_t buffer_damage[BUFFER_DAMAGE_COUNT];
54 };
55
56 struct gl_surface_state {
57         GLfloat color[4];
58         struct gl_shader *shader;
59
60         GLuint textures[3];
61         int num_textures;
62         pixman_region32_t texture_damage;
63
64         EGLImageKHR images[3];
65         GLenum target;
66         int num_images;
67
68         struct weston_buffer_reference buffer_ref;
69         int pitch; /* in pixels */
70 };
71
72 struct gl_renderer {
73         struct weston_renderer base;
74         int fragment_shader_debug;
75
76         EGLDisplay egl_display;
77         EGLContext egl_context;
78         EGLConfig egl_config;
79
80         struct {
81                 int32_t top, bottom, left, right;
82                 GLuint texture;
83                 int32_t width, height;
84         } border;
85
86         PFNGLEGLIMAGETARGETTEXTURE2DOESPROC image_target_texture_2d;
87         PFNEGLCREATEIMAGEKHRPROC create_image;
88         PFNEGLDESTROYIMAGEKHRPROC destroy_image;
89
90         int has_unpack_subimage;
91
92         PFNEGLBINDWAYLANDDISPLAYWL bind_display;
93         PFNEGLUNBINDWAYLANDDISPLAYWL unbind_display;
94         PFNEGLQUERYWAYLANDBUFFERWL query_buffer;
95         int has_bind_display;
96
97         int has_egl_image_external;
98
99         int has_egl_buffer_age;
100
101         struct gl_shader texture_shader_rgba;
102         struct gl_shader texture_shader_rgbx;
103         struct gl_shader texture_shader_egl_external;
104         struct gl_shader texture_shader_y_uv;
105         struct gl_shader texture_shader_y_u_v;
106         struct gl_shader texture_shader_y_xuxv;
107         struct gl_shader invert_color_shader;
108         struct gl_shader solid_shader;
109         struct gl_shader *current_shader;
110 };
111
112 static inline struct gl_output_state *
113 get_output_state(struct weston_output *output)
114 {
115         return (struct gl_output_state *)output->renderer_state;
116 }
117
118 static inline struct gl_surface_state *
119 get_surface_state(struct weston_surface *surface)
120 {
121         return (struct gl_surface_state *)surface->renderer_state;
122 }
123
124 static inline struct gl_renderer *
125 get_renderer(struct weston_compositor *ec)
126 {
127         return (struct gl_renderer *)ec->renderer;
128 }
129
130 static const char *
131 egl_error_string(EGLint code)
132 {
133 #define MYERRCODE(x) case x: return #x;
134         switch (code) {
135         MYERRCODE(EGL_SUCCESS)
136         MYERRCODE(EGL_NOT_INITIALIZED)
137         MYERRCODE(EGL_BAD_ACCESS)
138         MYERRCODE(EGL_BAD_ALLOC)
139         MYERRCODE(EGL_BAD_ATTRIBUTE)
140         MYERRCODE(EGL_BAD_CONTEXT)
141         MYERRCODE(EGL_BAD_CONFIG)
142         MYERRCODE(EGL_BAD_CURRENT_SURFACE)
143         MYERRCODE(EGL_BAD_DISPLAY)
144         MYERRCODE(EGL_BAD_SURFACE)
145         MYERRCODE(EGL_BAD_MATCH)
146         MYERRCODE(EGL_BAD_PARAMETER)
147         MYERRCODE(EGL_BAD_NATIVE_PIXMAP)
148         MYERRCODE(EGL_BAD_NATIVE_WINDOW)
149         MYERRCODE(EGL_CONTEXT_LOST)
150         default:
151                 return "unknown";
152         }
153 #undef MYERRCODE
154 }
155
156 WL_EXPORT void
157 gl_renderer_print_egl_error_state(void)
158 {
159         EGLint code;
160
161         code = eglGetError();
162         weston_log("EGL error state: %s (0x%04lx)\n",
163                 egl_error_string(code), (long)code);
164 }
165
166 struct polygon8 {
167         GLfloat x[8];
168         GLfloat y[8];
169         int n;
170 };
171
172 struct clip_context {
173         struct {
174                 GLfloat x;
175                 GLfloat y;
176         } prev;
177
178         struct {
179                 GLfloat x1, y1;
180                 GLfloat x2, y2;
181         } clip;
182
183         struct {
184                 GLfloat *x;
185                 GLfloat *y;
186         } vertices;
187 };
188
189 static GLfloat
190 float_difference(GLfloat a, GLfloat b)
191 {
192         /* http://www.altdevblogaday.com/2012/02/22/comparing-floating-point-numbers-2012-edition/ */
193         static const GLfloat max_diff = 4.0f * FLT_MIN;
194         static const GLfloat max_rel_diff = 4.0e-5;
195         GLfloat diff = a - b;
196         GLfloat adiff = fabsf(diff);
197
198         if (adiff <= max_diff)
199                 return 0.0f;
200
201         a = fabsf(a);
202         b = fabsf(b);
203         if (adiff <= (a > b ? a : b) * max_rel_diff)
204                 return 0.0f;
205
206         return diff;
207 }
208
209 /* A line segment (p1x, p1y)-(p2x, p2y) intersects the line x = x_arg.
210  * Compute the y coordinate of the intersection.
211  */
212 static GLfloat
213 clip_intersect_y(GLfloat p1x, GLfloat p1y, GLfloat p2x, GLfloat p2y,
214                  GLfloat x_arg)
215 {
216         GLfloat a;
217         GLfloat diff = float_difference(p1x, p2x);
218
219         /* Practically vertical line segment, yet the end points have already
220          * been determined to be on different sides of the line. Therefore
221          * the line segment is part of the line and intersects everywhere.
222          * Return the end point, so we use the whole line segment.
223          */
224         if (diff == 0.0f)
225                 return p2y;
226
227         a = (x_arg - p2x) / diff;
228         return p2y + (p1y - p2y) * a;
229 }
230
231 /* A line segment (p1x, p1y)-(p2x, p2y) intersects the line y = y_arg.
232  * Compute the x coordinate of the intersection.
233  */
234 static GLfloat
235 clip_intersect_x(GLfloat p1x, GLfloat p1y, GLfloat p2x, GLfloat p2y,
236                  GLfloat y_arg)
237 {
238         GLfloat a;
239         GLfloat diff = float_difference(p1y, p2y);
240
241         /* Practically horizontal line segment, yet the end points have already
242          * been determined to be on different sides of the line. Therefore
243          * the line segment is part of the line and intersects everywhere.
244          * Return the end point, so we use the whole line segment.
245          */
246         if (diff == 0.0f)
247                 return p2x;
248
249         a = (y_arg - p2y) / diff;
250         return p2x + (p1x - p2x) * a;
251 }
252
253 enum path_transition {
254         PATH_TRANSITION_OUT_TO_OUT = 0,
255         PATH_TRANSITION_OUT_TO_IN = 1,
256         PATH_TRANSITION_IN_TO_OUT = 2,
257         PATH_TRANSITION_IN_TO_IN = 3,
258 };
259
260 static void
261 clip_append_vertex(struct clip_context *ctx, GLfloat x, GLfloat y)
262 {
263         *ctx->vertices.x++ = x;
264         *ctx->vertices.y++ = y;
265 }
266
267 static enum path_transition
268 path_transition_left_edge(struct clip_context *ctx, GLfloat x, GLfloat y)
269 {
270         return ((ctx->prev.x >= ctx->clip.x1) << 1) | (x >= ctx->clip.x1);
271 }
272
273 static enum path_transition
274 path_transition_right_edge(struct clip_context *ctx, GLfloat x, GLfloat y)
275 {
276         return ((ctx->prev.x < ctx->clip.x2) << 1) | (x < ctx->clip.x2);
277 }
278
279 static enum path_transition
280 path_transition_top_edge(struct clip_context *ctx, GLfloat x, GLfloat y)
281 {
282         return ((ctx->prev.y >= ctx->clip.y1) << 1) | (y >= ctx->clip.y1);
283 }
284
285 static enum path_transition
286 path_transition_bottom_edge(struct clip_context *ctx, GLfloat x, GLfloat y)
287 {
288         return ((ctx->prev.y < ctx->clip.y2) << 1) | (y < ctx->clip.y2);
289 }
290
291 static void
292 clip_polygon_leftright(struct clip_context *ctx,
293                        enum path_transition transition,
294                        GLfloat x, GLfloat y, GLfloat clip_x)
295 {
296         GLfloat yi;
297
298         switch (transition) {
299         case PATH_TRANSITION_IN_TO_IN:
300                 clip_append_vertex(ctx, x, y);
301                 break;
302         case PATH_TRANSITION_IN_TO_OUT:
303                 yi = clip_intersect_y(ctx->prev.x, ctx->prev.y, x, y, clip_x);
304                 clip_append_vertex(ctx, clip_x, yi);
305                 break;
306         case PATH_TRANSITION_OUT_TO_IN:
307                 yi = clip_intersect_y(ctx->prev.x, ctx->prev.y, x, y, clip_x);
308                 clip_append_vertex(ctx, clip_x, yi);
309                 clip_append_vertex(ctx, x, y);
310                 break;
311         case PATH_TRANSITION_OUT_TO_OUT:
312                 /* nothing */
313                 break;
314         default:
315                 assert(0 && "bad enum path_transition");
316         }
317
318         ctx->prev.x = x;
319         ctx->prev.y = y;
320 }
321
322 static void
323 clip_polygon_topbottom(struct clip_context *ctx,
324                        enum path_transition transition,
325                        GLfloat x, GLfloat y, GLfloat clip_y)
326 {
327         GLfloat xi;
328
329         switch (transition) {
330         case PATH_TRANSITION_IN_TO_IN:
331                 clip_append_vertex(ctx, x, y);
332                 break;
333         case PATH_TRANSITION_IN_TO_OUT:
334                 xi = clip_intersect_x(ctx->prev.x, ctx->prev.y, x, y, clip_y);
335                 clip_append_vertex(ctx, xi, clip_y);
336                 break;
337         case PATH_TRANSITION_OUT_TO_IN:
338                 xi = clip_intersect_x(ctx->prev.x, ctx->prev.y, x, y, clip_y);
339                 clip_append_vertex(ctx, xi, clip_y);
340                 clip_append_vertex(ctx, x, y);
341                 break;
342         case PATH_TRANSITION_OUT_TO_OUT:
343                 /* nothing */
344                 break;
345         default:
346                 assert(0 && "bad enum path_transition");
347         }
348
349         ctx->prev.x = x;
350         ctx->prev.y = y;
351 }
352
353 static void
354 clip_context_prepare(struct clip_context *ctx, const struct polygon8 *src,
355                       GLfloat *dst_x, GLfloat *dst_y)
356 {
357         ctx->prev.x = src->x[src->n - 1];
358         ctx->prev.y = src->y[src->n - 1];
359         ctx->vertices.x = dst_x;
360         ctx->vertices.y = dst_y;
361 }
362
363 static int
364 clip_polygon_left(struct clip_context *ctx, const struct polygon8 *src,
365                   GLfloat *dst_x, GLfloat *dst_y)
366 {
367         enum path_transition trans;
368         int i;
369
370         clip_context_prepare(ctx, src, dst_x, dst_y);
371         for (i = 0; i < src->n; i++) {
372                 trans = path_transition_left_edge(ctx, src->x[i], src->y[i]);
373                 clip_polygon_leftright(ctx, trans, src->x[i], src->y[i],
374                                        ctx->clip.x1);
375         }
376         return ctx->vertices.x - dst_x;
377 }
378
379 static int
380 clip_polygon_right(struct clip_context *ctx, const struct polygon8 *src,
381                    GLfloat *dst_x, GLfloat *dst_y)
382 {
383         enum path_transition trans;
384         int i;
385
386         clip_context_prepare(ctx, src, dst_x, dst_y);
387         for (i = 0; i < src->n; i++) {
388                 trans = path_transition_right_edge(ctx, src->x[i], src->y[i]);
389                 clip_polygon_leftright(ctx, trans, src->x[i], src->y[i],
390                                        ctx->clip.x2);
391         }
392         return ctx->vertices.x - dst_x;
393 }
394
395 static int
396 clip_polygon_top(struct clip_context *ctx, const struct polygon8 *src,
397                  GLfloat *dst_x, GLfloat *dst_y)
398 {
399         enum path_transition trans;
400         int i;
401
402         clip_context_prepare(ctx, src, dst_x, dst_y);
403         for (i = 0; i < src->n; i++) {
404                 trans = path_transition_top_edge(ctx, src->x[i], src->y[i]);
405                 clip_polygon_topbottom(ctx, trans, src->x[i], src->y[i],
406                                        ctx->clip.y1);
407         }
408         return ctx->vertices.x - dst_x;
409 }
410
411 static int
412 clip_polygon_bottom(struct clip_context *ctx, const struct polygon8 *src,
413                     GLfloat *dst_x, GLfloat *dst_y)
414 {
415         enum path_transition trans;
416         int i;
417
418         clip_context_prepare(ctx, src, dst_x, dst_y);
419         for (i = 0; i < src->n; i++) {
420                 trans = path_transition_bottom_edge(ctx, src->x[i], src->y[i]);
421                 clip_polygon_topbottom(ctx, trans, src->x[i], src->y[i],
422                                        ctx->clip.y2);
423         }
424         return ctx->vertices.x - dst_x;
425 }
426
427 #define max(a, b) (((a) > (b)) ? (a) : (b))
428 #define min(a, b) (((a) > (b)) ? (b) : (a))
429 #define clip(x, a, b)  min(max(x, a), b)
430
431 /*
432  * Compute the boundary vertices of the intersection of the global coordinate
433  * aligned rectangle 'rect', and an arbitrary quadrilateral produced from
434  * 'surf_rect' when transformed from surface coordinates into global coordinates.
435  * The vertices are written to 'ex' and 'ey', and the return value is the
436  * number of vertices. Vertices are produced in clockwise winding order.
437  * Guarantees to produce either zero vertices, or 3-8 vertices with non-zero
438  * polygon area.
439  */
440 static int
441 calculate_edges(struct weston_surface *es, pixman_box32_t *rect,
442                 pixman_box32_t *surf_rect, GLfloat *ex, GLfloat *ey)
443 {
444         struct polygon8 polygon;
445         struct clip_context ctx;
446         int i, n;
447         GLfloat min_x, max_x, min_y, max_y;
448         struct polygon8 surf = {
449                 { surf_rect->x1, surf_rect->x2, surf_rect->x2, surf_rect->x1 },
450                 { surf_rect->y1, surf_rect->y1, surf_rect->y2, surf_rect->y2 },
451                 4
452         };
453
454         ctx.clip.x1 = rect->x1;
455         ctx.clip.y1 = rect->y1;
456         ctx.clip.x2 = rect->x2;
457         ctx.clip.y2 = rect->y2;
458
459         /* transform surface to screen space: */
460         for (i = 0; i < surf.n; i++)
461                 weston_surface_to_global_float(es, surf.x[i], surf.y[i],
462                                                &surf.x[i], &surf.y[i]);
463
464         /* find bounding box: */
465         min_x = max_x = surf.x[0];
466         min_y = max_y = surf.y[0];
467
468         for (i = 1; i < surf.n; i++) {
469                 min_x = min(min_x, surf.x[i]);
470                 max_x = max(max_x, surf.x[i]);
471                 min_y = min(min_y, surf.y[i]);
472                 max_y = max(max_y, surf.y[i]);
473         }
474
475         /* First, simple bounding box check to discard early transformed
476          * surface rects that do not intersect with the clip region:
477          */
478         if ((min_x >= ctx.clip.x2) || (max_x <= ctx.clip.x1) ||
479             (min_y >= ctx.clip.y2) || (max_y <= ctx.clip.y1))
480                 return 0;
481
482         /* Simple case, bounding box edges are parallel to surface edges,
483          * there will be only four edges.  We just need to clip the surface
484          * vertices to the clip rect bounds:
485          */
486         if (!es->transform.enabled) {
487                 for (i = 0; i < surf.n; i++) {
488                         ex[i] = clip(surf.x[i], ctx.clip.x1, ctx.clip.x2);
489                         ey[i] = clip(surf.y[i], ctx.clip.y1, ctx.clip.y2);
490                 }
491                 return surf.n;
492         }
493
494         /* Transformed case: use a general polygon clipping algorithm to
495          * clip the surface rectangle with each side of 'rect'.
496          * The algorithm is Sutherland-Hodgman, as explained in
497          * http://www.codeguru.com/cpp/misc/misc/graphics/article.php/c8965/Polygon-Clipping.htm
498          * but without looking at any of that code.
499          */
500         polygon.n = clip_polygon_left(&ctx, &surf, polygon.x, polygon.y);
501         surf.n = clip_polygon_right(&ctx, &polygon, surf.x, surf.y);
502         polygon.n = clip_polygon_top(&ctx, &surf, polygon.x, polygon.y);
503         surf.n = clip_polygon_bottom(&ctx, &polygon, surf.x, surf.y);
504
505         /* Get rid of duplicate vertices */
506         ex[0] = surf.x[0];
507         ey[0] = surf.y[0];
508         n = 1;
509         for (i = 1; i < surf.n; i++) {
510                 if (float_difference(ex[n - 1], surf.x[i]) == 0.0f &&
511                     float_difference(ey[n - 1], surf.y[i]) == 0.0f)
512                         continue;
513                 ex[n] = surf.x[i];
514                 ey[n] = surf.y[i];
515                 n++;
516         }
517         if (float_difference(ex[n - 1], surf.x[0]) == 0.0f &&
518             float_difference(ey[n - 1], surf.y[0]) == 0.0f)
519                 n--;
520
521         if (n < 3)
522                 return 0;
523
524         return n;
525 }
526
527 static int
528 texture_region(struct weston_surface *es, pixman_region32_t *region,
529                 pixman_region32_t *surf_region)
530 {
531         struct gl_surface_state *gs = get_surface_state(es);
532         struct weston_compositor *ec = es->compositor;
533         GLfloat *v, inv_width, inv_height;
534         unsigned int *vtxcnt, nvtx = 0;
535         pixman_box32_t *rects, *surf_rects;
536         int i, j, k, nrects, nsurf;
537
538         rects = pixman_region32_rectangles(region, &nrects);
539         surf_rects = pixman_region32_rectangles(surf_region, &nsurf);
540
541         /* worst case we can have 8 vertices per rect (ie. clipped into
542          * an octagon):
543          */
544         v = wl_array_add(&ec->vertices, nrects * nsurf * 8 * 4 * sizeof *v);
545         vtxcnt = wl_array_add(&ec->vtxcnt, nrects * nsurf * sizeof *vtxcnt);
546
547         inv_width = 1.0 / gs->pitch;
548
549         switch (es->buffer_transform) {
550         case WL_OUTPUT_TRANSFORM_90:
551         case WL_OUTPUT_TRANSFORM_270:
552         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
553         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
554                 inv_height = 1.0 / es->geometry.width;
555                 break;
556         default:
557                 inv_height = 1.0 / es->geometry.height;
558         }
559
560         for (i = 0; i < nrects; i++) {
561                 pixman_box32_t *rect = &rects[i];
562                 for (j = 0; j < nsurf; j++) {
563                         pixman_box32_t *surf_rect = &surf_rects[j];
564                         GLfloat sx, sy, bx, by;
565                         GLfloat ex[8], ey[8];          /* edge points in screen space */
566                         int n;
567
568                         /* The transformed surface, after clipping to the clip region,
569                          * can have as many as eight sides, emitted as a triangle-fan.
570                          * The first vertex in the triangle fan can be chosen arbitrarily,
571                          * since the area is guaranteed to be convex.
572                          *
573                          * If a corner of the transformed surface falls outside of the
574                          * clip region, instead of emitting one vertex for the corner
575                          * of the surface, up to two are emitted for two corresponding
576                          * intersection point(s) between the surface and the clip region.
577                          *
578                          * To do this, we first calculate the (up to eight) points that
579                          * form the intersection of the clip rect and the transformed
580                          * surface.
581                          */
582                         n = calculate_edges(es, rect, surf_rect, ex, ey);
583                         if (n < 3)
584                                 continue;
585
586                         /* emit edge points: */
587                         for (k = 0; k < n; k++) {
588                                 weston_surface_from_global_float(es, ex[k], ey[k], &sx, &sy);
589                                 /* position: */
590                                 *(v++) = ex[k];
591                                 *(v++) = ey[k];
592                                 /* texcoord: */
593                                 weston_surface_to_buffer_float(es, sx, sy,
594                                                                &bx, &by);
595                                 *(v++) = bx * inv_width;
596                                 *(v++) = by * inv_height;
597                         }
598
599                         vtxcnt[nvtx++] = n;
600                 }
601         }
602
603         return nvtx;
604 }
605
606 static void
607 triangle_fan_debug(struct weston_surface *surface, int first, int count)
608 {
609         struct weston_compositor *compositor = surface->compositor;
610         struct gl_renderer *gr = get_renderer(compositor);
611         int i;
612         GLushort *buffer;
613         GLushort *index;
614         int nelems;
615         static int color_idx = 0;
616         static const GLfloat color[][4] = {
617                         { 1.0, 0.0, 0.0, 1.0 },
618                         { 0.0, 1.0, 0.0, 1.0 },
619                         { 0.0, 0.0, 1.0, 1.0 },
620                         { 1.0, 1.0, 1.0, 1.0 },
621         };
622
623         nelems = (count - 1 + count - 2) * 2;
624
625         buffer = malloc(sizeof(GLushort) * nelems);
626         index = buffer;
627
628         for (i = 1; i < count; i++) {
629                 *index++ = first;
630                 *index++ = first + i;
631         }
632
633         for (i = 2; i < count; i++) {
634                 *index++ = first + i - 1;
635                 *index++ = first + i;
636         }
637
638         glUseProgram(gr->solid_shader.program);
639         glUniform4fv(gr->solid_shader.color_uniform, 1,
640                         color[color_idx++ % ARRAY_LENGTH(color)]);
641         glDrawElements(GL_LINES, nelems, GL_UNSIGNED_SHORT, buffer);
642         glUseProgram(gr->current_shader->program);
643         free(buffer);
644 }
645
646 static void
647 repaint_region(struct weston_surface *es, pixman_region32_t *region,
648                 pixman_region32_t *surf_region)
649 {
650         struct weston_compositor *ec = es->compositor;
651         GLfloat *v;
652         unsigned int *vtxcnt;
653         int i, first, nfans;
654
655         /* The final region to be painted is the intersection of
656          * 'region' and 'surf_region'. However, 'region' is in the global
657          * coordinates, and 'surf_region' is in the surface-local
658          * coordinates. texture_region() will iterate over all pairs of
659          * rectangles from both regions, compute the intersection
660          * polygon for each pair, and store it as a triangle fan if
661          * it has a non-zero area (at least 3 vertices, actually).
662          */
663         nfans = texture_region(es, region, surf_region);
664
665         v = ec->vertices.data;
666         vtxcnt = ec->vtxcnt.data;
667
668         /* position: */
669         glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof *v, &v[0]);
670         glEnableVertexAttribArray(0);
671
672         /* texcoord: */
673         glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof *v, &v[2]);
674         glEnableVertexAttribArray(1);
675
676         for (i = 0, first = 0; i < nfans; i++) {
677                 glDrawArrays(GL_TRIANGLE_FAN, first, vtxcnt[i]);
678                 if (ec->fan_debug)
679                         triangle_fan_debug(es, first, vtxcnt[i]);
680                 first += vtxcnt[i];
681         }
682
683         glDisableVertexAttribArray(1);
684         glDisableVertexAttribArray(0);
685
686         ec->vertices.size = 0;
687         ec->vtxcnt.size = 0;
688 }
689
690 static int
691 use_output(struct weston_output *output)
692 {
693         static int errored;
694         struct gl_output_state *go = get_output_state(output);
695         struct gl_renderer *gr = get_renderer(output->compositor);
696         EGLBoolean ret;
697
698         ret = eglMakeCurrent(gr->egl_display, go->egl_surface,
699                              go->egl_surface, gr->egl_context);
700
701         if (ret == EGL_FALSE) {
702                 if (errored)
703                         return -1;
704                 errored = 1;
705                 weston_log("Failed to make EGL context current.\n");
706                 gl_renderer_print_egl_error_state();
707                 return -1;
708         }
709
710         return 0;
711 }
712
713 static void
714 use_shader(struct gl_renderer *gr,
715                              struct gl_shader *shader)
716 {
717         if (gr->current_shader == shader)
718                 return;
719
720         glUseProgram(shader->program);
721         gr->current_shader = shader;
722 }
723
724 static void
725 shader_uniforms(struct gl_shader *shader,
726                        struct weston_surface *surface,
727                        struct weston_output *output)
728 {
729         int i;
730         struct gl_surface_state *gs = get_surface_state(surface);
731
732         glUniformMatrix4fv(shader->proj_uniform,
733                            1, GL_FALSE, output->matrix.d);
734         glUniform4fv(shader->color_uniform, 1, gs->color);
735         glUniform1f(shader->alpha_uniform, surface->alpha);
736
737         for (i = 0; i < gs->num_textures; i++)
738                 glUniform1i(shader->tex_uniforms[i], i);
739 }
740
741 static void
742 draw_surface(struct weston_surface *es, struct weston_output *output,
743              pixman_region32_t *damage) /* in global coordinates */
744 {
745         struct weston_compositor *ec = es->compositor;
746         struct gl_renderer *gr = get_renderer(ec);
747         struct gl_surface_state *gs = get_surface_state(es);
748         /* repaint bounding region in global coordinates: */
749         pixman_region32_t repaint;
750         /* non-opaque region in surface coordinates: */
751         pixman_region32_t surface_blend;
752         GLint filter;
753         int i;
754
755         pixman_region32_init(&repaint);
756         pixman_region32_intersect(&repaint,
757                                   &es->transform.boundingbox, damage);
758         pixman_region32_subtract(&repaint, &repaint, &es->clip);
759
760         if (!pixman_region32_not_empty(&repaint))
761                 goto out;
762
763         glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
764
765         if (ec->fan_debug) {
766                 use_shader(gr, &gr->solid_shader);
767                 shader_uniforms(&gr->solid_shader, es, output);
768         }
769
770         use_shader(gr, gs->shader);
771         shader_uniforms(gs->shader, es, output);
772
773         if (es->transform.enabled || output->zoom.active)
774                 filter = GL_LINEAR;
775         else
776                 filter = GL_NEAREST;
777
778         for (i = 0; i < gs->num_textures; i++) {
779                 glActiveTexture(GL_TEXTURE0 + i);
780                 glBindTexture(gs->target, gs->textures[i]);
781                 glTexParameteri(gs->target, GL_TEXTURE_MIN_FILTER, filter);
782                 glTexParameteri(gs->target, GL_TEXTURE_MAG_FILTER, filter);
783         }
784
785         /* blended region is whole surface minus opaque region: */
786         pixman_region32_init_rect(&surface_blend, 0, 0,
787                                   es->geometry.width, es->geometry.height);
788         pixman_region32_subtract(&surface_blend, &surface_blend, &es->opaque);
789
790         if (pixman_region32_not_empty(&es->opaque)) {
791                 if (gs->shader == &gr->texture_shader_rgba) {
792                         /* Special case for RGBA textures with possibly
793                          * bad data in alpha channel: use the shader
794                          * that forces texture alpha = 1.0.
795                          * Xwayland surfaces need this.
796                          */
797                         use_shader(gr, &gr->texture_shader_rgbx);
798                         shader_uniforms(&gr->texture_shader_rgbx, es, output);
799                 }
800
801                 if (es->alpha < 1.0)
802                         glEnable(GL_BLEND);
803                 else
804                         glDisable(GL_BLEND);
805
806                 repaint_region(es, &repaint, &es->opaque);
807         }
808
809         if (pixman_region32_not_empty(&surface_blend)) {
810                 use_shader(gr, gs->shader);
811                 glEnable(GL_BLEND);
812                 repaint_region(es, &repaint, &surface_blend);
813         }
814
815         pixman_region32_fini(&surface_blend);
816
817 out:
818         pixman_region32_fini(&repaint);
819 }
820
821 static void
822 repaint_surfaces(struct weston_output *output, pixman_region32_t *damage)
823 {
824         struct weston_compositor *compositor = output->compositor;
825         struct weston_surface *surface;
826
827         wl_list_for_each_reverse(surface, &compositor->surface_list, link)
828                 if (surface->plane == &compositor->primary_plane)
829                         draw_surface(surface, output, damage);
830 }
831
832
833 static int
834 texture_border(struct weston_output *output)
835 {
836         struct weston_compositor *ec = output->compositor;
837         struct gl_renderer *gr = get_renderer(ec);
838         GLfloat *d;
839         unsigned int *p;
840         int i, j, k, n;
841         GLfloat x[4], y[4], u[4], v[4];
842
843         x[0] = -gr->border.left;
844         x[1] = 0;
845         x[2] = output->current->width;
846         x[3] = output->current->width + gr->border.right;
847
848         y[0] = -gr->border.top;
849         y[1] = 0;
850         y[2] = output->current->height;
851         y[3] = output->current->height + gr->border.bottom;
852
853         u[0] = 0.0;
854         u[1] = (GLfloat) gr->border.left / gr->border.width;
855         u[2] = (GLfloat) (gr->border.width - gr->border.right) / gr->border.width;
856         u[3] = 1.0;
857
858         v[0] = 0.0;
859         v[1] = (GLfloat) gr->border.top / gr->border.height;
860         v[2] = (GLfloat) (gr->border.height - gr->border.bottom) / gr->border.height;
861         v[3] = 1.0;
862
863         n = 8;
864         d = wl_array_add(&ec->vertices, n * 16 * sizeof *d);
865         p = wl_array_add(&ec->indices, n * 6 * sizeof *p);
866
867         k = 0;
868         for (i = 0; i < 3; i++)
869                 for (j = 0; j < 3; j++) {
870
871                         if (i == 1 && j == 1)
872                                 continue;
873
874                         d[ 0] = x[i];
875                         d[ 1] = y[j];
876                         d[ 2] = u[i];
877                         d[ 3] = v[j];
878
879                         d[ 4] = x[i];
880                         d[ 5] = y[j + 1];
881                         d[ 6] = u[i];
882                         d[ 7] = v[j + 1];
883
884                         d[ 8] = x[i + 1];
885                         d[ 9] = y[j];
886                         d[10] = u[i + 1];
887                         d[11] = v[j];
888
889                         d[12] = x[i + 1];
890                         d[13] = y[j + 1];
891                         d[14] = u[i + 1];
892                         d[15] = v[j + 1];
893
894                         p[0] = k + 0;
895                         p[1] = k + 1;
896                         p[2] = k + 2;
897                         p[3] = k + 2;
898                         p[4] = k + 1;
899                         p[5] = k + 3;
900
901                         d += 16;
902                         p += 6;
903                         k += 4;
904                 }
905
906         return k / 4;
907 }
908
909 static void
910 draw_border(struct weston_output *output)
911 {
912         struct weston_compositor *ec = output->compositor;
913         struct gl_renderer *gr = get_renderer(ec);
914         struct gl_shader *shader = &gr->texture_shader_rgba;
915         GLfloat *v;
916         int n;
917
918         glDisable(GL_BLEND);
919         use_shader(gr, shader);
920
921         glUniformMatrix4fv(shader->proj_uniform,
922                            1, GL_FALSE, output->matrix.d);
923
924         glUniform1i(shader->tex_uniforms[0], 0);
925         glUniform1f(shader->alpha_uniform, 1);
926
927         n = texture_border(output);
928
929         glActiveTexture(GL_TEXTURE0);
930         glBindTexture(GL_TEXTURE_2D, gr->border.texture);
931
932         v = ec->vertices.data;
933         glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof *v, &v[0]);
934         glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof *v, &v[2]);
935         glEnableVertexAttribArray(0);
936         glEnableVertexAttribArray(1);
937
938         glDrawElements(GL_TRIANGLES, n * 6,
939                        GL_UNSIGNED_INT, ec->indices.data);
940
941         glDisableVertexAttribArray(1);
942         glDisableVertexAttribArray(0);
943
944         ec->vertices.size = 0;
945         ec->indices.size = 0;
946 }
947
948 static void
949 output_get_buffer_damage(struct weston_output *output,
950                          pixman_region32_t *buffer_damage)
951 {
952         struct gl_output_state *go = get_output_state(output);
953         struct gl_renderer *gr = get_renderer(output->compositor);
954         EGLint buffer_age = 0;
955         EGLBoolean ret;
956         int i;
957
958         if (gr->has_egl_buffer_age) {
959                 ret = eglQuerySurface(gr->egl_display, go->egl_surface,
960                                       EGL_BUFFER_AGE_EXT, &buffer_age);
961                 if (ret == EGL_FALSE) {
962                         weston_log("buffer age query failed.\n");
963                         gl_renderer_print_egl_error_state();
964                 }
965         }
966
967         if (buffer_age == 0 || buffer_age - 1 > BUFFER_DAMAGE_COUNT)
968                 pixman_region32_copy(buffer_damage, &output->region);
969         else
970                 for (i = 0; i < buffer_age - 1; i++)
971                         pixman_region32_union(buffer_damage, buffer_damage,
972                                               &go->buffer_damage[i]);
973 }
974
975 static void
976 output_rotate_damage(struct weston_output *output,
977                      pixman_region32_t *output_damage)
978 {
979         struct gl_output_state *go = get_output_state(output);
980         struct gl_renderer *gr = get_renderer(output->compositor);
981         int i;
982
983         if (!gr->has_egl_buffer_age)
984                 return;
985
986         for (i = BUFFER_DAMAGE_COUNT - 1; i >= 1; i--)
987                 pixman_region32_copy(&go->buffer_damage[i],
988                                      &go->buffer_damage[i - 1]);
989
990         pixman_region32_copy(&go->buffer_damage[0], output_damage);
991 }
992
993 static void
994 gl_renderer_repaint_output(struct weston_output *output,
995                               pixman_region32_t *output_damage)
996 {
997         struct gl_output_state *go = get_output_state(output);
998         struct weston_compositor *compositor = output->compositor;
999         struct gl_renderer *gr = get_renderer(compositor);
1000         EGLBoolean ret;
1001         static int errored;
1002         int32_t width, height;
1003         pixman_region32_t buffer_damage, total_damage;
1004
1005         width = output->current->width +
1006                 output->border.left + output->border.right;
1007         height = output->current->height +
1008                 output->border.top + output->border.bottom;
1009
1010         glViewport(0, 0, width, height);
1011
1012         if (use_output(output) < 0)
1013                 return;
1014
1015         /* if debugging, redraw everything outside the damage to clean up
1016          * debug lines from the previous draw on this buffer:
1017          */
1018         if (compositor->fan_debug) {
1019                 pixman_region32_t undamaged;
1020                 pixman_region32_init(&undamaged);
1021                 pixman_region32_subtract(&undamaged, &output->region,
1022                                          output_damage);
1023                 compositor->fan_debug = 0;
1024                 repaint_surfaces(output, &undamaged);
1025                 compositor->fan_debug = 1;
1026                 pixman_region32_fini(&undamaged);
1027         }
1028
1029         pixman_region32_init(&total_damage);
1030         pixman_region32_init(&buffer_damage);
1031
1032         output_get_buffer_damage(output, &buffer_damage);
1033         output_rotate_damage(output, output_damage);
1034
1035         pixman_region32_union(&total_damage, &buffer_damage, output_damage);
1036
1037         repaint_surfaces(output, &total_damage);
1038
1039         pixman_region32_fini(&total_damage);
1040         pixman_region32_fini(&buffer_damage);
1041
1042         if (gr->border.texture)
1043                 draw_border(output);
1044
1045         pixman_region32_copy(&output->previous_damage, output_damage);
1046         wl_signal_emit(&output->frame_signal, output);
1047
1048         ret = eglSwapBuffers(gr->egl_display, go->egl_surface);
1049         if (ret == EGL_FALSE && !errored) {
1050                 errored = 1;
1051                 weston_log("Failed in eglSwapBuffers.\n");
1052                 gl_renderer_print_egl_error_state();
1053         }
1054
1055 }
1056
1057 static int
1058 gl_renderer_read_pixels(struct weston_output *output,
1059                                pixman_format_code_t format, void *pixels,
1060                                uint32_t x, uint32_t y,
1061                                uint32_t width, uint32_t height)
1062 {
1063         GLenum gl_format;
1064
1065         switch (format) {
1066         case PIXMAN_a8r8g8b8:
1067                 gl_format = GL_BGRA_EXT;
1068                 break;
1069         case PIXMAN_a8b8g8r8:
1070                 gl_format = GL_RGBA;
1071                 break;
1072         default:
1073                 return -1;
1074         }
1075
1076         if (use_output(output) < 0)
1077                 return -1;
1078
1079         glPixelStorei(GL_PACK_ALIGNMENT, 1);
1080         glReadPixels(x, y, width, height, gl_format,
1081                      GL_UNSIGNED_BYTE, pixels);
1082
1083         return 0;
1084 }
1085
1086 static void
1087 gl_renderer_flush_damage(struct weston_surface *surface)
1088 {
1089         struct gl_renderer *gr = get_renderer(surface->compositor);
1090         struct gl_surface_state *gs = get_surface_state(surface);
1091         struct wl_buffer *buffer = gs->buffer_ref.buffer;
1092
1093 #ifdef GL_UNPACK_ROW_LENGTH
1094         pixman_box32_t *rectangles;
1095         void *data;
1096         int i, n;
1097 #endif
1098
1099         pixman_region32_union(&gs->texture_damage,
1100                               &gs->texture_damage, &surface->damage);
1101
1102         if (!buffer)
1103                 return;
1104
1105         /* Avoid upload, if the texture won't be used this time.
1106          * We still accumulate the damage in texture_damage, and
1107          * hold the reference to the buffer, in case the surface
1108          * migrates back to the primary plane.
1109          */
1110         if (surface->plane != &surface->compositor->primary_plane)
1111                 return;
1112
1113         if (!pixman_region32_not_empty(&gs->texture_damage))
1114                 goto done;
1115
1116         glBindTexture(GL_TEXTURE_2D, gs->textures[0]);
1117
1118         if (!gr->has_unpack_subimage) {
1119                 glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA_EXT,
1120                              gs->pitch, buffer->height, 0,
1121                              GL_BGRA_EXT, GL_UNSIGNED_BYTE,
1122                              wl_shm_buffer_get_data(buffer));
1123
1124                 goto done;
1125         }
1126
1127 #ifdef GL_UNPACK_ROW_LENGTH
1128         /* Mesa does not define GL_EXT_unpack_subimage */
1129         glPixelStorei(GL_UNPACK_ROW_LENGTH, gs->pitch);
1130         data = wl_shm_buffer_get_data(buffer);
1131         rectangles = pixman_region32_rectangles(&gs->texture_damage, &n);
1132         for (i = 0; i < n; i++) {
1133                 pixman_box32_t r;
1134
1135                 r = weston_surface_to_buffer_rect(surface, rectangles[i]);
1136
1137                 glPixelStorei(GL_UNPACK_SKIP_PIXELS, r.x1);
1138                 glPixelStorei(GL_UNPACK_SKIP_ROWS, r.y1);
1139                 glTexSubImage2D(GL_TEXTURE_2D, 0, r.x1, r.y1,
1140                                 r.x2 - r.x1, r.y2 - r.y1,
1141                                 GL_BGRA_EXT, GL_UNSIGNED_BYTE, data);
1142         }
1143 #endif
1144
1145 done:
1146         pixman_region32_fini(&gs->texture_damage);
1147         pixman_region32_init(&gs->texture_damage);
1148
1149         weston_buffer_reference(&gs->buffer_ref, NULL);
1150 }
1151
1152 static void
1153 ensure_textures(struct gl_surface_state *gs, int num_textures)
1154 {
1155         int i;
1156
1157         if (num_textures <= gs->num_textures)
1158                 return;
1159
1160         for (i = gs->num_textures; i < num_textures; i++) {
1161                 glGenTextures(1, &gs->textures[i]);
1162                 glBindTexture(gs->target, gs->textures[i]);
1163                 glTexParameteri(gs->target,
1164                                 GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1165                 glTexParameteri(gs->target,
1166                                 GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1167         }
1168         gs->num_textures = num_textures;
1169         glBindTexture(gs->target, 0);
1170 }
1171
1172 static void
1173 gl_renderer_attach(struct weston_surface *es, struct wl_buffer *buffer)
1174 {
1175         struct weston_compositor *ec = es->compositor;
1176         struct gl_renderer *gr = get_renderer(ec);
1177         struct gl_surface_state *gs = get_surface_state(es);
1178         EGLint attribs[3], format;
1179         int i, num_planes;
1180
1181         weston_buffer_reference(&gs->buffer_ref, buffer);
1182
1183         if (!buffer) {
1184                 for (i = 0; i < gs->num_images; i++) {
1185                         gr->destroy_image(gr->egl_display, gs->images[i]);
1186                         gs->images[i] = NULL;
1187                 }
1188                 gs->num_images = 0;
1189                 glDeleteTextures(gs->num_textures, gs->textures);
1190                 gs->num_textures = 0;
1191                 return;
1192         }
1193
1194         if (wl_buffer_is_shm(buffer)) {
1195                 gs->pitch = wl_shm_buffer_get_stride(buffer) / 4;
1196                 gs->target = GL_TEXTURE_2D;
1197
1198                 ensure_textures(gs, 1);
1199                 glBindTexture(GL_TEXTURE_2D, gs->textures[0]);
1200                 glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA_EXT,
1201                              gs->pitch, buffer->height, 0,
1202                              GL_BGRA_EXT, GL_UNSIGNED_BYTE, NULL);
1203                 if (wl_shm_buffer_get_format(buffer) == WL_SHM_FORMAT_XRGB8888)
1204                         gs->shader = &gr->texture_shader_rgbx;
1205                 else
1206                         gs->shader = &gr->texture_shader_rgba;
1207         } else if (gr->query_buffer(gr->egl_display, buffer,
1208                                     EGL_TEXTURE_FORMAT, &format)) {
1209                 for (i = 0; i < gs->num_images; i++)
1210                         gr->destroy_image(gr->egl_display, gs->images[i]);
1211                 gs->num_images = 0;
1212                 gs->target = GL_TEXTURE_2D;
1213                 switch (format) {
1214                 case EGL_TEXTURE_RGB:
1215                 case EGL_TEXTURE_RGBA:
1216                 default:
1217                         num_planes = 1;
1218                         gs->shader = &gr->texture_shader_rgba;
1219                         break;
1220                 case EGL_TEXTURE_EXTERNAL_WL:
1221                         num_planes = 1;
1222                         gs->target = GL_TEXTURE_EXTERNAL_OES;
1223                         gs->shader = &gr->texture_shader_egl_external;
1224                         break;
1225                 case EGL_TEXTURE_Y_UV_WL:
1226                         num_planes = 2;
1227                         gs->shader = &gr->texture_shader_y_uv;
1228                         break;
1229                 case EGL_TEXTURE_Y_U_V_WL:
1230                         num_planes = 3;
1231                         gs->shader = &gr->texture_shader_y_u_v;
1232                         break;
1233                 case EGL_TEXTURE_Y_XUXV_WL:
1234                         num_planes = 2;
1235                         gs->shader = &gr->texture_shader_y_xuxv;
1236                         break;
1237                 }
1238
1239                 ensure_textures(gs, num_planes);
1240                 for (i = 0; i < num_planes; i++) {
1241                         attribs[0] = EGL_WAYLAND_PLANE_WL;
1242                         attribs[1] = i;
1243                         attribs[2] = EGL_NONE;
1244                         gs->images[i] = gr->create_image(gr->egl_display,
1245                                                          NULL,
1246                                                          EGL_WAYLAND_BUFFER_WL,
1247                                                          buffer, attribs);
1248                         if (!gs->images[i]) {
1249                                 weston_log("failed to create img for plane %d\n", i);
1250                                 continue;
1251                         }
1252                         gs->num_images++;
1253
1254                         glActiveTexture(GL_TEXTURE0 + i);
1255                         glBindTexture(gs->target, gs->textures[i]);
1256                         gr->image_target_texture_2d(gs->target,
1257                                                     gs->images[i]);
1258                 }
1259
1260                 gs->pitch = buffer->width;
1261         } else {
1262                 weston_log("unhandled buffer type!\n");
1263                 weston_buffer_reference(&gs->buffer_ref, NULL);
1264         }
1265 }
1266
1267 static void
1268 gl_renderer_surface_set_color(struct weston_surface *surface,
1269                  float red, float green, float blue, float alpha)
1270 {
1271         struct gl_surface_state *gs = get_surface_state(surface);
1272         struct gl_renderer *gr = get_renderer(surface->compositor);
1273
1274         gs->color[0] = red;
1275         gs->color[1] = green;
1276         gs->color[2] = blue;
1277         gs->color[3] = alpha;
1278
1279         gs->shader = &gr->solid_shader;
1280 }
1281
1282 static int
1283 gl_renderer_create_surface(struct weston_surface *surface)
1284 {
1285         struct gl_surface_state *gs;
1286
1287         gs = calloc(1, sizeof *gs);
1288         if (!gs)
1289                 return -1;
1290
1291         /* A buffer is never attached to solid color surfaces, yet
1292          * they still go through texcoord computations. Do not divide
1293          * by zero there.
1294          */
1295         gs->pitch = 1;
1296
1297         pixman_region32_init(&gs->texture_damage);
1298         surface->renderer_state = gs;
1299
1300         return 0;
1301 }
1302
1303 static void
1304 gl_renderer_destroy_surface(struct weston_surface *surface)
1305 {
1306         struct gl_surface_state *gs = get_surface_state(surface);
1307         struct gl_renderer *gr = get_renderer(surface->compositor);
1308         int i;
1309
1310         glDeleteTextures(gs->num_textures, gs->textures);
1311
1312         for (i = 0; i < gs->num_images; i++)
1313                 gr->destroy_image(gr->egl_display, gs->images[i]);
1314
1315         weston_buffer_reference(&gs->buffer_ref, NULL);
1316         pixman_region32_fini(&gs->texture_damage);
1317         free(gs);
1318 }
1319
1320 static const char vertex_shader[] =
1321         "uniform mat4 proj;\n"
1322         "attribute vec2 position;\n"
1323         "attribute vec2 texcoord;\n"
1324         "varying vec2 v_texcoord;\n"
1325         "void main()\n"
1326         "{\n"
1327         "   gl_Position = proj * vec4(position, 0.0, 1.0);\n"
1328         "   v_texcoord = texcoord;\n"
1329         "}\n";
1330
1331 /* Declare common fragment shader uniforms */
1332 #define FRAGMENT_CONVERT_YUV                                            \
1333         "  y *= alpha;\n"                                               \
1334         "  u *= alpha;\n"                                               \
1335         "  v *= alpha;\n"                                               \
1336         "  gl_FragColor.r = y + 1.59602678 * v;\n"                      \
1337         "  gl_FragColor.g = y - 0.39176229 * u - 0.81296764 * v;\n"     \
1338         "  gl_FragColor.b = y + 2.01723214 * u;\n"                      \
1339         "  gl_FragColor.a = alpha;\n"
1340
1341 static const char fragment_debug[] =
1342         "  gl_FragColor = vec4(0.0, 0.3, 0.0, 0.2) + gl_FragColor * 0.8;\n";
1343
1344 static const char fragment_brace[] =
1345         "}\n";
1346
1347 static const char texture_fragment_shader_rgba[] =
1348         "precision mediump float;\n"
1349         "varying vec2 v_texcoord;\n"
1350         "uniform sampler2D tex;\n"
1351         "uniform float alpha;\n"
1352         "void main()\n"
1353         "{\n"
1354         "   gl_FragColor = alpha * texture2D(tex, v_texcoord)\n;"
1355         ;
1356
1357 static const char texture_fragment_shader_rgbx[] =
1358         "precision mediump float;\n"
1359         "varying vec2 v_texcoord;\n"
1360         "uniform sampler2D tex;\n"
1361         "uniform float alpha;\n"
1362         "void main()\n"
1363         "{\n"
1364         "   gl_FragColor.rgb = alpha * texture2D(tex, v_texcoord).rgb\n;"
1365         "   gl_FragColor.a = alpha;\n"
1366         ;
1367
1368 static const char texture_fragment_shader_egl_external[] =
1369         "#extension GL_OES_EGL_image_external : require\n"
1370         "precision mediump float;\n"
1371         "varying vec2 v_texcoord;\n"
1372         "uniform samplerExternalOES tex;\n"
1373         "uniform float alpha;\n"
1374         "void main()\n"
1375         "{\n"
1376         "   gl_FragColor = alpha * texture2D(tex, v_texcoord)\n;"
1377         ;
1378
1379 static const char texture_fragment_shader_y_uv[] =
1380         "precision mediump float;\n"
1381         "uniform sampler2D tex;\n"
1382         "uniform sampler2D tex1;\n"
1383         "varying vec2 v_texcoord;\n"
1384         "uniform float alpha;\n"
1385         "void main() {\n"
1386         "  float y = 1.16438356 * (texture2D(tex, v_texcoord).x - 0.0625);\n"
1387         "  float u = texture2D(tex1, v_texcoord).r - 0.5;\n"
1388         "  float v = texture2D(tex1, v_texcoord).g - 0.5;\n"
1389         FRAGMENT_CONVERT_YUV
1390         ;
1391
1392 static const char texture_fragment_shader_y_u_v[] =
1393         "precision mediump float;\n"
1394         "uniform sampler2D tex;\n"
1395         "uniform sampler2D tex1;\n"
1396         "uniform sampler2D tex2;\n"
1397         "varying vec2 v_texcoord;\n"
1398         "uniform float alpha;\n"
1399         "void main() {\n"
1400         "  float y = 1.16438356 * (texture2D(tex, v_texcoord).x - 0.0625);\n"
1401         "  float u = texture2D(tex1, v_texcoord).x - 0.5;\n"
1402         "  float v = texture2D(tex2, v_texcoord).x - 0.5;\n"
1403         FRAGMENT_CONVERT_YUV
1404         ;
1405
1406 static const char texture_fragment_shader_y_xuxv[] =
1407         "precision mediump float;\n"
1408         "uniform sampler2D tex;\n"
1409         "uniform sampler2D tex1;\n"
1410         "varying vec2 v_texcoord;\n"
1411         "uniform float alpha;\n"
1412         "void main() {\n"
1413         "  float y = 1.16438356 * (texture2D(tex, v_texcoord).x - 0.0625);\n"
1414         "  float u = texture2D(tex1, v_texcoord).g - 0.5;\n"
1415         "  float v = texture2D(tex1, v_texcoord).a - 0.5;\n"
1416         FRAGMENT_CONVERT_YUV
1417         ;
1418
1419 static const char solid_fragment_shader[] =
1420         "precision mediump float;\n"
1421         "uniform vec4 color;\n"
1422         "uniform float alpha;\n"
1423         "void main()\n"
1424         "{\n"
1425         "   gl_FragColor = alpha * color\n;"
1426         ;
1427
1428 static int
1429 compile_shader(GLenum type, int count, const char **sources)
1430 {
1431         GLuint s;
1432         char msg[512];
1433         GLint status;
1434
1435         s = glCreateShader(type);
1436         glShaderSource(s, count, sources, NULL);
1437         glCompileShader(s);
1438         glGetShaderiv(s, GL_COMPILE_STATUS, &status);
1439         if (!status) {
1440                 glGetShaderInfoLog(s, sizeof msg, NULL, msg);
1441                 weston_log("shader info: %s\n", msg);
1442                 return GL_NONE;
1443         }
1444
1445         return s;
1446 }
1447
1448 static int
1449 shader_init(struct gl_shader *shader, struct weston_compositor *ec,
1450                    const char *vertex_source, const char *fragment_source)
1451 {
1452         char msg[512];
1453         GLint status;
1454         int count;
1455         const char *sources[3];
1456         struct gl_renderer *renderer = get_renderer(ec);
1457
1458         shader->vertex_shader =
1459                 compile_shader(GL_VERTEX_SHADER, 1, &vertex_source);
1460
1461         if (renderer->fragment_shader_debug) {
1462                 sources[0] = fragment_source;
1463                 sources[1] = fragment_debug;
1464                 sources[2] = fragment_brace;
1465                 count = 3;
1466         } else {
1467                 sources[0] = fragment_source;
1468                 sources[1] = fragment_brace;
1469                 count = 2;
1470         }
1471
1472         shader->fragment_shader =
1473                 compile_shader(GL_FRAGMENT_SHADER, count, sources);
1474
1475         shader->program = glCreateProgram();
1476         glAttachShader(shader->program, shader->vertex_shader);
1477         glAttachShader(shader->program, shader->fragment_shader);
1478         glBindAttribLocation(shader->program, 0, "position");
1479         glBindAttribLocation(shader->program, 1, "texcoord");
1480
1481         glLinkProgram(shader->program);
1482         glGetProgramiv(shader->program, GL_LINK_STATUS, &status);
1483         if (!status) {
1484                 glGetProgramInfoLog(shader->program, sizeof msg, NULL, msg);
1485                 weston_log("link info: %s\n", msg);
1486                 return -1;
1487         }
1488
1489         shader->proj_uniform = glGetUniformLocation(shader->program, "proj");
1490         shader->tex_uniforms[0] = glGetUniformLocation(shader->program, "tex");
1491         shader->tex_uniforms[1] = glGetUniformLocation(shader->program, "tex1");
1492         shader->tex_uniforms[2] = glGetUniformLocation(shader->program, "tex2");
1493         shader->alpha_uniform = glGetUniformLocation(shader->program, "alpha");
1494         shader->color_uniform = glGetUniformLocation(shader->program, "color");
1495
1496         return 0;
1497 }
1498
1499 static void
1500 shader_release(struct gl_shader *shader)
1501 {
1502         glDeleteShader(shader->vertex_shader);
1503         glDeleteShader(shader->fragment_shader);
1504         glDeleteProgram(shader->program);
1505
1506         shader->vertex_shader = 0;
1507         shader->fragment_shader = 0;
1508         shader->program = 0;
1509 }
1510
1511 static void
1512 log_extensions(const char *name, const char *extensions)
1513 {
1514         const char *p, *end;
1515         int l;
1516         int len;
1517
1518         l = weston_log("%s:", name);
1519         p = extensions;
1520         while (*p) {
1521                 end = strchrnul(p, ' ');
1522                 len = end - p;
1523                 if (l + len > 78)
1524                         l = weston_log_continue("\n" STAMP_SPACE "%.*s",
1525                                                 len, p);
1526                 else
1527                         l += weston_log_continue(" %.*s", len, p);
1528                 for (p = end; isspace(*p); p++)
1529                         ;
1530         }
1531         weston_log_continue("\n");
1532 }
1533
1534 static void
1535 log_egl_gl_info(EGLDisplay egldpy)
1536 {
1537         const char *str;
1538
1539         str = eglQueryString(egldpy, EGL_VERSION);
1540         weston_log("EGL version: %s\n", str ? str : "(null)");
1541
1542         str = eglQueryString(egldpy, EGL_VENDOR);
1543         weston_log("EGL vendor: %s\n", str ? str : "(null)");
1544
1545         str = eglQueryString(egldpy, EGL_CLIENT_APIS);
1546         weston_log("EGL client APIs: %s\n", str ? str : "(null)");
1547
1548         str = eglQueryString(egldpy, EGL_EXTENSIONS);
1549         log_extensions("EGL extensions", str ? str : "(null)");
1550
1551         str = (char *)glGetString(GL_VERSION);
1552         weston_log("GL version: %s\n", str ? str : "(null)");
1553
1554         str = (char *)glGetString(GL_SHADING_LANGUAGE_VERSION);
1555         weston_log("GLSL version: %s\n", str ? str : "(null)");
1556
1557         str = (char *)glGetString(GL_VENDOR);
1558         weston_log("GL vendor: %s\n", str ? str : "(null)");
1559
1560         str = (char *)glGetString(GL_RENDERER);
1561         weston_log("GL renderer: %s\n", str ? str : "(null)");
1562
1563         str = (char *)glGetString(GL_EXTENSIONS);
1564         log_extensions("GL extensions", str ? str : "(null)");
1565 }
1566
1567 static void
1568 log_egl_config_info(EGLDisplay egldpy, EGLConfig eglconfig)
1569 {
1570         EGLint r, g, b, a;
1571
1572         weston_log("Chosen EGL config details:\n");
1573
1574         weston_log_continue(STAMP_SPACE "RGBA bits");
1575         if (eglGetConfigAttrib(egldpy, eglconfig, EGL_RED_SIZE, &r) &&
1576             eglGetConfigAttrib(egldpy, eglconfig, EGL_GREEN_SIZE, &g) &&
1577             eglGetConfigAttrib(egldpy, eglconfig, EGL_BLUE_SIZE, &b) &&
1578             eglGetConfigAttrib(egldpy, eglconfig, EGL_ALPHA_SIZE, &a))
1579                 weston_log_continue(": %d %d %d %d\n", r, g, b, a);
1580         else
1581                 weston_log_continue(" unknown\n");
1582
1583         weston_log_continue(STAMP_SPACE "swap interval range");
1584         if (eglGetConfigAttrib(egldpy, eglconfig, EGL_MIN_SWAP_INTERVAL, &a) &&
1585             eglGetConfigAttrib(egldpy, eglconfig, EGL_MAX_SWAP_INTERVAL, &b))
1586                 weston_log_continue(": %d - %d\n", a, b);
1587         else
1588                 weston_log_continue(" unknown\n");
1589 }
1590
1591 static void
1592 output_apply_border(struct weston_output *output, struct gl_renderer *gr)
1593 {
1594         output->border.top = gr->border.top;
1595         output->border.bottom = gr->border.bottom;
1596         output->border.left = gr->border.left;
1597         output->border.right = gr->border.right;
1598 }
1599
1600 WL_EXPORT void
1601 gl_renderer_set_border(struct weston_compositor *ec, int32_t width, int32_t height, void *data,
1602                           int32_t *edges)
1603 {
1604         struct gl_renderer *gr = get_renderer(ec);
1605         struct weston_output *output;
1606
1607         gr->border.left = edges[0];
1608         gr->border.right = edges[1];
1609         gr->border.top = edges[2];
1610         gr->border.bottom = edges[3];
1611
1612         gr->border.width = width;
1613         gr->border.height = height;
1614
1615         glGenTextures(1, &gr->border.texture);
1616         glBindTexture(GL_TEXTURE_2D, gr->border.texture);
1617         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1618         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1619         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1620         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1621
1622         glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA_EXT,
1623                      width,
1624                      height,
1625                      0, GL_BGRA_EXT, GL_UNSIGNED_BYTE,
1626                      data);
1627
1628         wl_list_for_each(output, &ec->output_list, link)
1629                 output_apply_border(output, gr);
1630 }
1631
1632 static int
1633 gl_renderer_setup(struct weston_compositor *ec, EGLSurface egl_surface);
1634
1635 WL_EXPORT int
1636 gl_renderer_output_create(struct weston_output *output,
1637                                     EGLNativeWindowType window)
1638 {
1639         struct weston_compositor *ec = output->compositor;
1640         struct gl_renderer *gr = get_renderer(ec);
1641         struct gl_output_state *go = calloc(1, sizeof *go);
1642         int i;
1643
1644         if (!go)
1645                 return -1;
1646
1647         go->egl_surface =
1648                 eglCreateWindowSurface(gr->egl_display,
1649                                        gr->egl_config,
1650                                        window, NULL);
1651
1652         if (go->egl_surface == EGL_NO_SURFACE) {
1653                 weston_log("failed to create egl surface\n");
1654                 free(go);
1655                 return -1;
1656         }
1657
1658         if (gr->egl_context == NULL)
1659                 if (gl_renderer_setup(ec, go->egl_surface) < 0) {
1660                         free(go);
1661                         return -1;
1662                 }
1663
1664         for (i = 0; i < BUFFER_DAMAGE_COUNT; i++)
1665                 pixman_region32_init(&go->buffer_damage[i]);
1666
1667         output->renderer_state = go;
1668
1669         output_apply_border(output, gr);
1670
1671         return 0;
1672 }
1673
1674 WL_EXPORT void
1675 gl_renderer_output_destroy(struct weston_output *output)
1676 {
1677         struct gl_renderer *gr = get_renderer(output->compositor);
1678         struct gl_output_state *go = get_output_state(output);
1679         int i;
1680
1681         for (i = 0; i < 2; i++)
1682                 pixman_region32_fini(&go->buffer_damage[i]);
1683
1684         eglDestroySurface(gr->egl_display, go->egl_surface);
1685
1686         free(go);
1687 }
1688
1689 WL_EXPORT EGLSurface
1690 gl_renderer_output_surface(struct weston_output *output)
1691 {
1692         return get_output_state(output)->egl_surface;
1693 }
1694
1695 static void
1696 gl_renderer_destroy(struct weston_compositor *ec)
1697 {
1698         struct gl_renderer *gr = get_renderer(ec);
1699
1700         if (gr->has_bind_display)
1701                 gr->unbind_display(gr->egl_display, ec->wl_display);
1702
1703         /* Work around crash in egl_dri2.c's dri2_make_current() - when does this apply? */
1704         eglMakeCurrent(gr->egl_display,
1705                        EGL_NO_SURFACE, EGL_NO_SURFACE,
1706                        EGL_NO_CONTEXT);
1707
1708         eglTerminate(gr->egl_display);
1709         eglReleaseThread();
1710
1711         free(gr);
1712 }
1713
1714 static int
1715 egl_choose_config(struct gl_renderer *gr, const EGLint *attribs,
1716         const EGLint *visual_id)
1717 {
1718         EGLint count = 0;
1719         EGLint matched = 0;
1720         EGLConfig *configs;
1721         int i;
1722
1723         if (!eglGetConfigs(gr->egl_display, NULL, 0, &count) || count < 1)
1724                 return -1;
1725
1726         configs = calloc(count, sizeof *configs);
1727         if (!configs)
1728                 return -1;
1729
1730         if (!eglChooseConfig(gr->egl_display, attribs, configs,
1731                               count, &matched))
1732                 goto out;
1733
1734         for (i = 0; i < matched; ++i) {
1735                 EGLint id;
1736
1737                 if (visual_id) {
1738                         if (!eglGetConfigAttrib(gr->egl_display,
1739                                         configs[i], EGL_NATIVE_VISUAL_ID,
1740                                         &id))
1741                                 continue;
1742
1743                         if (id != *visual_id)
1744                                 continue;
1745                 }
1746
1747                 gr->egl_config = configs[i];
1748
1749                 free(configs);
1750                 return 0;
1751         }
1752
1753 out:
1754         free(configs);
1755         return -1;
1756 }
1757
1758 WL_EXPORT const EGLint gl_renderer_opaque_attribs[] = {
1759         EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
1760         EGL_RED_SIZE, 1,
1761         EGL_GREEN_SIZE, 1,
1762         EGL_BLUE_SIZE, 1,
1763         EGL_ALPHA_SIZE, 0,
1764         EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
1765         EGL_NONE
1766 };
1767
1768 WL_EXPORT const EGLint gl_renderer_alpha_attribs[] = {
1769         EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
1770         EGL_RED_SIZE, 1,
1771         EGL_GREEN_SIZE, 1,
1772         EGL_BLUE_SIZE, 1,
1773         EGL_ALPHA_SIZE, 1,
1774         EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
1775         EGL_NONE
1776 };
1777
1778 WL_EXPORT int
1779 gl_renderer_create(struct weston_compositor *ec, EGLNativeDisplayType display,
1780         const EGLint *attribs, const EGLint *visual_id)
1781 {
1782         struct gl_renderer *gr;
1783         EGLint major, minor;
1784
1785         gr = calloc(1, sizeof *gr);
1786
1787         if (gr == NULL)
1788                 return -1;
1789
1790         gr->base.read_pixels = gl_renderer_read_pixels;
1791         gr->base.repaint_output = gl_renderer_repaint_output;
1792         gr->base.flush_damage = gl_renderer_flush_damage;
1793         gr->base.attach = gl_renderer_attach;
1794         gr->base.create_surface = gl_renderer_create_surface;
1795         gr->base.surface_set_color = gl_renderer_surface_set_color;
1796         gr->base.destroy_surface = gl_renderer_destroy_surface;
1797         gr->base.destroy = gl_renderer_destroy;
1798
1799         gr->egl_display = eglGetDisplay(display);
1800         if (gr->egl_display == EGL_NO_DISPLAY) {
1801                 weston_log("failed to create display\n");
1802                 goto err_egl;
1803         }
1804
1805         if (!eglInitialize(gr->egl_display, &major, &minor)) {
1806                 weston_log("failed to initialize display\n");
1807                 goto err_egl;
1808         }
1809
1810         if (egl_choose_config(gr, attribs, visual_id) < 0) {
1811                 weston_log("failed to choose EGL config\n");
1812                 goto err_egl;
1813         }
1814
1815         ec->renderer = &gr->base;
1816
1817         return 0;
1818
1819 err_egl:
1820         gl_renderer_print_egl_error_state();
1821         free(gr);
1822         return -1;
1823 }
1824
1825 WL_EXPORT EGLDisplay
1826 gl_renderer_display(struct weston_compositor *ec)
1827 {
1828         return get_renderer(ec)->egl_display;
1829 }
1830
1831 static int
1832 compile_shaders(struct weston_compositor *ec)
1833 {
1834         struct gl_renderer *gr = get_renderer(ec);
1835
1836         if (shader_init(&gr->texture_shader_rgba, ec,
1837                              vertex_shader, texture_fragment_shader_rgba) < 0)
1838                 return -1;
1839         if (shader_init(&gr->texture_shader_rgbx, ec,
1840                              vertex_shader, texture_fragment_shader_rgbx) < 0)
1841                 return -1;
1842         if (gr->has_egl_image_external &&
1843                         shader_init(&gr->texture_shader_egl_external, ec,
1844                                 vertex_shader, texture_fragment_shader_egl_external) < 0)
1845                 return -1;
1846         if (shader_init(&gr->texture_shader_y_uv, ec,
1847                                vertex_shader, texture_fragment_shader_y_uv) < 0)
1848                 return -1;
1849         if (shader_init(&gr->texture_shader_y_u_v, ec,
1850                                vertex_shader, texture_fragment_shader_y_u_v) < 0)
1851                 return -1;
1852         if (shader_init(&gr->texture_shader_y_xuxv, ec,
1853                                vertex_shader, texture_fragment_shader_y_xuxv) < 0)
1854                 return -1;
1855         if (shader_init(&gr->solid_shader, ec,
1856                              vertex_shader, solid_fragment_shader) < 0)
1857                 return -1;
1858
1859         return 0;
1860 }
1861
1862 static void
1863 fragment_debug_binding(struct wl_seat *seat, uint32_t time, uint32_t key,
1864                        void *data)
1865 {
1866         struct weston_compositor *ec = data;
1867         struct gl_renderer *gr = get_renderer(ec);
1868         struct weston_output *output;
1869
1870         gr->fragment_shader_debug ^= 1;
1871
1872         shader_release(&gr->texture_shader_rgba);
1873         shader_release(&gr->texture_shader_rgbx);
1874         shader_release(&gr->texture_shader_egl_external);
1875         shader_release(&gr->texture_shader_y_uv);
1876         shader_release(&gr->texture_shader_y_u_v);
1877         shader_release(&gr->texture_shader_y_xuxv);
1878         shader_release(&gr->solid_shader);
1879
1880         compile_shaders(ec);
1881
1882         /* Force use_shader() to call glUseProgram(), since we need to use
1883          * the recompiled version of the shader. */
1884         gr->current_shader = NULL;
1885
1886         wl_list_for_each(output, &ec->output_list, link)
1887                 weston_output_damage(output);
1888 }
1889
1890 static int
1891 gl_renderer_setup(struct weston_compositor *ec, EGLSurface egl_surface)
1892 {
1893         struct gl_renderer *gr = get_renderer(ec);
1894         const char *extensions;
1895         EGLBoolean ret;
1896
1897         static const EGLint context_attribs[] = {
1898                 EGL_CONTEXT_CLIENT_VERSION, 2,
1899                 EGL_NONE
1900         };
1901
1902         if (!eglBindAPI(EGL_OPENGL_ES_API)) {
1903                 weston_log("failed to bind EGL_OPENGL_ES_API\n");
1904                 gl_renderer_print_egl_error_state();
1905                 return -1;
1906         }
1907
1908         log_egl_config_info(gr->egl_display, gr->egl_config);
1909
1910         gr->egl_context = eglCreateContext(gr->egl_display, gr->egl_config,
1911                                            EGL_NO_CONTEXT, context_attribs);
1912         if (gr->egl_context == NULL) {
1913                 weston_log("failed to create context\n");
1914                 gl_renderer_print_egl_error_state();
1915                 return -1;
1916         }
1917
1918         ret = eglMakeCurrent(gr->egl_display, egl_surface,
1919                              egl_surface, gr->egl_context);
1920         if (ret == EGL_FALSE) {
1921                 weston_log("Failed to make EGL context current.\n");
1922                 gl_renderer_print_egl_error_state();
1923                 return -1;
1924         }
1925
1926         log_egl_gl_info(gr->egl_display);
1927
1928         gr->image_target_texture_2d =
1929                 (void *) eglGetProcAddress("glEGLImageTargetTexture2DOES");
1930         gr->create_image = (void *) eglGetProcAddress("eglCreateImageKHR");
1931         gr->destroy_image = (void *) eglGetProcAddress("eglDestroyImageKHR");
1932         gr->bind_display =
1933                 (void *) eglGetProcAddress("eglBindWaylandDisplayWL");
1934         gr->unbind_display =
1935                 (void *) eglGetProcAddress("eglUnbindWaylandDisplayWL");
1936         gr->query_buffer =
1937                 (void *) eglGetProcAddress("eglQueryWaylandBufferWL");
1938
1939         extensions = (const char *) glGetString(GL_EXTENSIONS);
1940         if (!extensions) {
1941                 weston_log("Retrieving GL extension string failed.\n");
1942                 return -1;
1943         }
1944
1945         if (!strstr(extensions, "GL_EXT_texture_format_BGRA8888")) {
1946                 weston_log("GL_EXT_texture_format_BGRA8888 not available\n");
1947                 return -1;
1948         }
1949
1950         if (strstr(extensions, "GL_EXT_read_format_bgra"))
1951                 ec->read_format = PIXMAN_a8r8g8b8;
1952         else
1953                 ec->read_format = PIXMAN_a8b8g8r8;
1954
1955         if (strstr(extensions, "GL_EXT_unpack_subimage"))
1956                 gr->has_unpack_subimage = 1;
1957
1958         if (strstr(extensions, "GL_OES_EGL_image_external"))
1959                 gr->has_egl_image_external = 1;
1960
1961         extensions =
1962                 (const char *) eglQueryString(gr->egl_display, EGL_EXTENSIONS);
1963         if (!extensions) {
1964                 weston_log("Retrieving EGL extension string failed.\n");
1965                 return -1;
1966         }
1967
1968         if (strstr(extensions, "EGL_WL_bind_wayland_display"))
1969                 gr->has_bind_display = 1;
1970         if (gr->has_bind_display) {
1971                 ret = gr->bind_display(gr->egl_display, ec->wl_display);
1972                 if (!ret)
1973                         gr->has_bind_display = 0;
1974         }
1975
1976         if (strstr(extensions, "EGL_EXT_buffer_age"))
1977                 gr->has_egl_buffer_age = 1;
1978         else
1979                 weston_log("warning: EGL_EXT_buffer_age not supported. "
1980                            "Performance could be affected.\n");
1981
1982         glActiveTexture(GL_TEXTURE0);
1983
1984         if (compile_shaders(ec))
1985                 return -1;
1986
1987         weston_compositor_add_debug_binding(ec, KEY_S,
1988                                             fragment_debug_binding, ec);
1989
1990         weston_log("GL ES 2 renderer features:\n");
1991         weston_log_continue(STAMP_SPACE "read-back format: %s\n",
1992                 ec->read_format == PIXMAN_a8r8g8b8 ? "BGRA" : "RGBA");
1993         weston_log_continue(STAMP_SPACE "wl_shm sub-image to texture: %s\n",
1994                             gr->has_unpack_subimage ? "yes" : "no");
1995         weston_log_continue(STAMP_SPACE "EGL Wayland extension: %s\n",
1996                             gr->has_bind_display ? "yes" : "no");
1997
1998
1999         return 0;
2000 }