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