gl-renderer.c 89.1 KB
Newer Older
1 2
/*
 * Copyright © 2012 Intel Corporation
3
 * Copyright © 2015 Collabora, Ltd.
4
 * Copyright © 2016 NVIDIA Corporation
5
 *
6 7 8 9 10 11 12
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
13
 *
14 15 16 17 18 19 20 21 22 23 24 25
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
26 27
 */

28
#include "config.h"
29

30 31 32
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>

33
#include <stdbool.h>
34
#include <stdint.h>
35
#include <stdlib.h>
36 37
#include <string.h>
#include <ctype.h>
38 39
#include <float.h>
#include <assert.h>
40
#include <linux/input.h>
41
#include <drm_fourcc.h>
42

43
#include "gl-renderer.h"
44
#include "vertex-clipping.h"
45
#include "linux-dmabuf.h"
46
#include "linux-dmabuf-unstable-v1-server-protocol.h"
47

48
#include "shared/helpers.h"
49
#include "shared/platform.h"
50
#include "weston-egl-ext.h"
51

52
struct gl_shader {
53 54 55 56 57 58
	GLuint program;
	GLuint vertex_shader, fragment_shader;
	GLint proj_uniform;
	GLint tex_uniforms[3];
	GLint alpha_uniform;
	GLint color_uniform;
59
	const char *vertex_source, *fragment_source;
60 61
};

62 63
#define BUFFER_DAMAGE_COUNT 2

64 65 66 67 68 69 70 71 72 73
enum gl_border_status {
	BORDER_STATUS_CLEAN = 0,
	BORDER_TOP_DIRTY = 1 << GL_RENDERER_BORDER_TOP,
	BORDER_LEFT_DIRTY = 1 << GL_RENDERER_BORDER_LEFT,
	BORDER_RIGHT_DIRTY = 1 << GL_RENDERER_BORDER_RIGHT,
	BORDER_BOTTOM_DIRTY = 1 << GL_RENDERER_BORDER_BOTTOM,
	BORDER_ALL_DIRTY = 0xf,
	BORDER_SIZE_CHANGED = 0x10
};

74 75 76 77 78 79 80
struct gl_border_image {
	GLuint tex;
	int32_t width, height;
	int32_t tex_width;
	void *data;
};

81
struct gl_output_state {
82
	EGLSurface egl_surface;
83
	pixman_region32_t buffer_damage[BUFFER_DAMAGE_COUNT];
84
	int buffer_damage_index;
85
	enum gl_border_status border_damage[BUFFER_DAMAGE_COUNT];
86
	struct gl_border_image borders[4];
87
	enum gl_border_status border_status;
88 89

	struct weston_matrix output_matrix;
90 91
};

92 93
enum buffer_type {
	BUFFER_TYPE_NULL,
94
	BUFFER_TYPE_SOLID, /* internal solid color surfaces without a buffer */
95 96 97 98
	BUFFER_TYPE_SHM,
	BUFFER_TYPE_EGL
};

99 100 101 102 103 104
struct gl_renderer;

struct egl_image {
	struct gl_renderer *renderer;
	EGLImageKHR image;
	int refcount;
105
};
106

107 108 109 110 111 112
enum import_type {
	IMPORT_TYPE_INVALID,
	IMPORT_TYPE_DIRECT,
	IMPORT_TYPE_GL_CONVERSION
};

113
struct dmabuf_image {
114
	struct linux_dmabuf_buffer *dmabuf;
115 116
	int num_images;
	struct egl_image *images[3];
117
	struct wl_list link;
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

	enum import_type import_type;
	GLenum target;
	struct gl_shader *shader;
};

struct yuv_plane_descriptor {
	int width_divisor;
	int height_divisor;
	uint32_t format;
	int plane_index;
};

struct yuv_format_descriptor {
	uint32_t format;
	int input_planes;
	int output_planes;
	int texture_type;
	struct yuv_plane_descriptor plane[4];
137 138
};

139
struct gl_surface_state {
140
	GLfloat color[4];
141
	struct gl_shader *shader;
142 143 144

	GLuint textures[3];
	int num_textures;
145
	bool needs_full_upload;
146
	pixman_region32_t texture_damage;
147

148 149 150
	/* These are only used by SHM surfaces to detect when we need
	 * to do a full upload to specify a new internal texture
	 * format */
151
	GLenum gl_format[3];
152 153
	GLenum gl_pixel_type;

154
	struct egl_image* images[3];
155 156
	GLenum target;
	int num_images;
157 158

	struct weston_buffer_reference buffer_ref;
159
	enum buffer_type buffer_type;
160
	int pitch; /* in pixels */
161
	int height; /* in pixels */
162
	int y_inverted;
163

164 165
	/* Extension needed for SHM YUV texture */
	int offset[3]; /* offset per plane */
166 167
	int hsub[3];  /* horizontal subsampling per plane */
	int vsub[3];  /* vertical subsampling per plane */
168

169 170 171
	struct weston_surface *surface;

	struct wl_listener surface_destroy_listener;
172
	struct wl_listener renderer_destroy_listener;
173 174
};

175
struct gl_renderer {
176 177
	struct weston_renderer base;
	int fragment_shader_debug;
178
	int fan_debug;
179 180
	struct weston_binding *fragment_binding;
	struct weston_binding *fan_binding;
181

182 183 184
	EGLDisplay egl_display;
	EGLContext egl_context;
	EGLConfig egl_config;
185

186 187
	EGLSurface dummy_surface;

188 189 190
	struct wl_array vertices;
	struct wl_array vtxcnt;

191 192 193
	PFNGLEGLIMAGETARGETTEXTURE2DOESPROC image_target_texture_2d;
	PFNEGLCREATEIMAGEKHRPROC create_image;
	PFNEGLDESTROYIMAGEKHRPROC destroy_image;
194
	PFNEGLSWAPBUFFERSWITHDAMAGEEXTPROC swap_buffers_with_damage;
195 196
	PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC create_platform_window;

197 198 199 200 201 202 203 204 205
	int has_unpack_subimage;

	PFNEGLBINDWAYLANDDISPLAYWL bind_display;
	PFNEGLUNBINDWAYLANDDISPLAYWL unbind_display;
	PFNEGLQUERYWAYLANDBUFFERWL query_buffer;
	int has_bind_display;

	int has_egl_image_external;

206 207
	int has_egl_buffer_age;

208 209
	int has_configless_context;

210 211
	int has_surfaceless_context;

212 213 214
	int has_dmabuf_import;
	struct wl_list dmabuf_images;

215 216
	int has_gl_texture_rg;

217 218 219 220 221 222 223 224 225
	struct gl_shader texture_shader_rgba;
	struct gl_shader texture_shader_rgbx;
	struct gl_shader texture_shader_egl_external;
	struct gl_shader texture_shader_y_uv;
	struct gl_shader texture_shader_y_u_v;
	struct gl_shader texture_shader_y_xuxv;
	struct gl_shader invert_color_shader;
	struct gl_shader solid_shader;
	struct gl_shader *current_shader;
226 227

	struct wl_signal destroy_signal;
228 229

	struct wl_listener output_destroy_listener;
230 231
};

232 233
static PFNEGLGETPLATFORMDISPLAYEXTPROC get_platform_display = NULL;

234 235 236 237 238 239 240 241 242 243
static inline const char *
dump_format(uint32_t format, char out[4])
{
#if BYTE_ORDER == BIG_ENDIAN
	format = __builtin_bswap32(format);
#endif
	memcpy(out, &format, 4);
	return out;
}

244
static inline struct gl_output_state *
245 246
get_output_state(struct weston_output *output)
{
247
	return (struct gl_output_state *)output->renderer_state;
248 249
}

250 251 252
static int
gl_renderer_create_surface(struct weston_surface *surface);

253
static inline struct gl_surface_state *
254 255
get_surface_state(struct weston_surface *surface)
{
256 257 258
	if (!surface->renderer_state)
		gl_renderer_create_surface(surface);

259
	return (struct gl_surface_state *)surface->renderer_state;
260 261
}

262
static inline struct gl_renderer *
263 264
get_renderer(struct weston_compositor *ec)
{
265
	return (struct gl_renderer *)ec->renderer;
266 267
}

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
static struct egl_image*
egl_image_create(struct gl_renderer *gr, EGLenum target,
		 EGLClientBuffer buffer, const EGLint *attribs)
{
	struct egl_image *img;

	img = zalloc(sizeof *img);
	img->renderer = gr;
	img->refcount = 1;
	img->image = gr->create_image(gr->egl_display, EGL_NO_CONTEXT,
				      target, buffer, attribs);

	if (img->image == EGL_NO_IMAGE_KHR) {
		free(img);
		return NULL;
	}

	return img;
}

static struct egl_image*
egl_image_ref(struct egl_image *image)
{
	image->refcount++;

	return image;
}

static int
egl_image_unref(struct egl_image *image)
{
	struct gl_renderer *gr = image->renderer;

	assert(image->refcount > 0);

	image->refcount--;
	if (image->refcount > 0)
		return image->refcount;

	gr->destroy_image(gr->egl_display, image->image);
	free(image);

	return 0;
}

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
static struct dmabuf_image*
dmabuf_image_create(void)
{
	struct dmabuf_image *img;

	img = zalloc(sizeof *img);
	wl_list_init(&img->link);

	return img;
}

static void
dmabuf_image_destroy(struct dmabuf_image *image)
{
	int i;

	for (i = 0; i < image->num_images; ++i)
		egl_image_unref(image->images[i]);

	if (image->dmabuf)
		linux_dmabuf_buffer_set_user_data(image->dmabuf, NULL, NULL);

	wl_list_remove(&image->link);
}

338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
static const char *
egl_error_string(EGLint code)
{
#define MYERRCODE(x) case x: return #x;
	switch (code) {
	MYERRCODE(EGL_SUCCESS)
	MYERRCODE(EGL_NOT_INITIALIZED)
	MYERRCODE(EGL_BAD_ACCESS)
	MYERRCODE(EGL_BAD_ALLOC)
	MYERRCODE(EGL_BAD_ATTRIBUTE)
	MYERRCODE(EGL_BAD_CONTEXT)
	MYERRCODE(EGL_BAD_CONFIG)
	MYERRCODE(EGL_BAD_CURRENT_SURFACE)
	MYERRCODE(EGL_BAD_DISPLAY)
	MYERRCODE(EGL_BAD_SURFACE)
	MYERRCODE(EGL_BAD_MATCH)
	MYERRCODE(EGL_BAD_PARAMETER)
	MYERRCODE(EGL_BAD_NATIVE_PIXMAP)
	MYERRCODE(EGL_BAD_NATIVE_WINDOW)
	MYERRCODE(EGL_CONTEXT_LOST)
	default:
		return "unknown";
	}
#undef MYERRCODE
}

364
static void
365
gl_renderer_print_egl_error_state(void)
366 367 368 369 370 371 372 373
{
	EGLint code;

	code = eglGetError();
	weston_log("EGL error state: %s (0x%04lx)\n",
		egl_error_string(code), (long)code);
}

374 375 376
#define max(a, b) (((a) > (b)) ? (a) : (b))
#define min(a, b) (((a) > (b)) ? (b) : (a))

377 378 379 380 381 382 383 384 385
/*
 * Compute the boundary vertices of the intersection of the global coordinate
 * aligned rectangle 'rect', and an arbitrary quadrilateral produced from
 * 'surf_rect' when transformed from surface coordinates into global coordinates.
 * The vertices are written to 'ex' and 'ey', and the return value is the
 * number of vertices. Vertices are produced in clockwise winding order.
 * Guarantees to produce either zero vertices, or 3-8 vertices with non-zero
 * polygon area.
 */
386
static int
387
calculate_edges(struct weston_view *ev, pixman_box32_t *rect,
388 389
		pixman_box32_t *surf_rect, GLfloat *ex, GLfloat *ey)
{
390

391 392
	struct clip_context ctx;
	int i, n;
393
	GLfloat min_x, max_x, min_y, max_y;
394 395 396 397
	struct polygon8 surf = {
		{ surf_rect->x1, surf_rect->x2, surf_rect->x2, surf_rect->x1 },
		{ surf_rect->y1, surf_rect->y1, surf_rect->y2, surf_rect->y2 },
		4
398 399
	};

400 401 402 403
	ctx.clip.x1 = rect->x1;
	ctx.clip.y1 = rect->y1;
	ctx.clip.x2 = rect->x2;
	ctx.clip.y2 = rect->y2;
404 405

	/* transform surface to screen space: */
406
	for (i = 0; i < surf.n; i++)
407 408
		weston_view_to_global_float(ev, surf.x[i], surf.y[i],
					    &surf.x[i], &surf.y[i]);
409 410

	/* find bounding box: */
411 412 413 414 415 416 417 418
	min_x = max_x = surf.x[0];
	min_y = max_y = surf.y[0];

	for (i = 1; i < surf.n; i++) {
		min_x = min(min_x, surf.x[i]);
		max_x = max(max_x, surf.x[i]);
		min_y = min(min_y, surf.y[i]);
		max_y = max(max_y, surf.y[i]);
419 420 421 422 423
	}

	/* First, simple bounding box check to discard early transformed
	 * surface rects that do not intersect with the clip region:
	 */
424 425
	if ((min_x >= ctx.clip.x2) || (max_x <= ctx.clip.x1) ||
	    (min_y >= ctx.clip.y2) || (max_y <= ctx.clip.y1))
426 427 428 429 430 431
		return 0;

	/* Simple case, bounding box edges are parallel to surface edges,
	 * there will be only four edges.  We just need to clip the surface
	 * vertices to the clip rect bounds:
	 */
432
	if (!ev->transform.enabled)
433
		return clip_simple(&ctx, &surf, ex, ey);
434

435 436 437 438 439
	/* Transformed case: use a general polygon clipping algorithm to
	 * clip the surface rectangle with each side of 'rect'.
	 * The algorithm is Sutherland-Hodgman, as explained in
	 * http://www.codeguru.com/cpp/misc/misc/graphics/article.php/c8965/Polygon-Clipping.htm
	 * but without looking at any of that code.
440
	 */
441
	n = clip_transformed(&ctx, &surf, ex, ey);
442 443 444

	if (n < 3)
		return 0;
445 446 447 448

	return n;
}

449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
static bool
merge_down(pixman_box32_t *a, pixman_box32_t *b, pixman_box32_t *merge)
{
	if (a->x1 == b->x1 && a->x2 == b->x2 && a->y1 == b->y2) {
		merge->x1 = a->x1;
		merge->x2 = a->x2;
		merge->y1 = b->y1;
		merge->y2 = a->y2;
		return true;
	}
	return false;
}

static int
compress_bands(pixman_box32_t *inrects, int nrects,
		   pixman_box32_t **outrects)
{
466
	bool merged = false;
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
	pixman_box32_t *out, merge_rect;
	int i, j, nout;

	if (!nrects) {
		*outrects = NULL;
		return 0;
	}

	/* nrects is an upper bound - we're not too worried about
	 * allocating a little extra
	 */
	out = malloc(sizeof(pixman_box32_t) * nrects);
	out[0] = inrects[0];
	nout = 1;
	for (i = 1; i < nrects; i++) {
		for (j = 0; j < nout; j++) {
			merged = merge_down(&inrects[i], &out[j], &merge_rect);
			if (merged) {
				out[j] = merge_rect;
				break;
			}
		}
		if (!merged) {
			out[nout] = inrects[i];
			nout++;
		}
	}
	*outrects = out;
	return nout;
}

498
static int
499
texture_region(struct weston_view *ev, pixman_region32_t *region,
500 501
		pixman_region32_t *surf_region)
{
502 503
	struct gl_surface_state *gs = get_surface_state(ev->surface);
	struct weston_compositor *ec = ev->surface->compositor;
504
	struct gl_renderer *gr = get_renderer(ec);
505 506 507
	GLfloat *v, inv_width, inv_height;
	unsigned int *vtxcnt, nvtx = 0;
	pixman_box32_t *rects, *surf_rects;
508 509 510 511
	pixman_box32_t *raw_rects;
	int i, j, k, nrects, nsurf, raw_nrects;
	bool used_band_compression;
	raw_rects = pixman_region32_rectangles(region, &raw_nrects);
512 513
	surf_rects = pixman_region32_rectangles(surf_region, &nsurf);

514 515 516 517 518 519 520 521
	if (raw_nrects < 4) {
		used_band_compression = false;
		nrects = raw_nrects;
		rects = raw_rects;
	} else {
		nrects = compress_bands(raw_rects, raw_nrects, &rects);
		used_band_compression = true;
	}
522 523 524
	/* worst case we can have 8 vertices per rect (ie. clipped into
	 * an octagon):
	 */
525 526
	v = wl_array_add(&gr->vertices, nrects * nsurf * 8 * 4 * sizeof *v);
	vtxcnt = wl_array_add(&gr->vtxcnt, nrects * nsurf * sizeof *vtxcnt);
527

528
	inv_width = 1.0 / gs->pitch;
529
        inv_height = 1.0 / gs->height;
530 531 532 533 534

	for (i = 0; i < nrects; i++) {
		pixman_box32_t *rect = &rects[i];
		for (j = 0; j < nsurf; j++) {
			pixman_box32_t *surf_rect = &surf_rects[j];
535
			GLfloat sx, sy, bx, by;
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
			GLfloat ex[8], ey[8];          /* edge points in screen space */
			int n;

			/* The transformed surface, after clipping to the clip region,
			 * can have as many as eight sides, emitted as a triangle-fan.
			 * The first vertex in the triangle fan can be chosen arbitrarily,
			 * since the area is guaranteed to be convex.
			 *
			 * If a corner of the transformed surface falls outside of the
			 * clip region, instead of emitting one vertex for the corner
			 * of the surface, up to two are emitted for two corresponding
			 * intersection point(s) between the surface and the clip region.
			 *
			 * To do this, we first calculate the (up to eight) points that
			 * form the intersection of the clip rect and the transformed
			 * surface.
			 */
553
			n = calculate_edges(ev, rect, surf_rect, ex, ey);
554 555 556 557 558
			if (n < 3)
				continue;

			/* emit edge points: */
			for (k = 0; k < n; k++) {
559 560
				weston_view_from_global_float(ev, ex[k], ey[k],
							      &sx, &sy);
561 562 563 564
				/* position: */
				*(v++) = ex[k];
				*(v++) = ey[k];
				/* texcoord: */
565 566
				weston_surface_to_buffer_float(ev->surface,
							       sx, sy,
567 568
							       &bx, &by);
				*(v++) = bx * inv_width;
569 570 571 572 573
				if (gs->y_inverted) {
					*(v++) = by * inv_height;
				} else {
					*(v++) = (gs->height - by) * inv_height;
				}
574 575 576 577 578 579
			}

			vtxcnt[nvtx++] = n;
		}
	}

580 581
	if (used_band_compression)
		free(rects);
582 583 584 585
	return nvtx;
}

static void
586
triangle_fan_debug(struct weston_view *view, int first, int count)
587
{
588
	struct weston_compositor *compositor = view->surface->compositor;
589
	struct gl_renderer *gr = get_renderer(compositor);
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
	int i;
	GLushort *buffer;
	GLushort *index;
	int nelems;
	static int color_idx = 0;
	static const GLfloat color[][4] = {
			{ 1.0, 0.0, 0.0, 1.0 },
			{ 0.0, 1.0, 0.0, 1.0 },
			{ 0.0, 0.0, 1.0, 1.0 },
			{ 1.0, 1.0, 1.0, 1.0 },
	};

	nelems = (count - 1 + count - 2) * 2;

	buffer = malloc(sizeof(GLushort) * nelems);
	index = buffer;

	for (i = 1; i < count; i++) {
		*index++ = first;
		*index++ = first + i;
	}

	for (i = 2; i < count; i++) {
		*index++ = first + i - 1;
		*index++ = first + i;
	}

617 618
	glUseProgram(gr->solid_shader.program);
	glUniform4fv(gr->solid_shader.color_uniform, 1,
619 620
			color[color_idx++ % ARRAY_LENGTH(color)]);
	glDrawElements(GL_LINES, nelems, GL_UNSIGNED_SHORT, buffer);
621
	glUseProgram(gr->current_shader->program);
622 623 624 625
	free(buffer);
}

static void
626
repaint_region(struct weston_view *ev, pixman_region32_t *region,
627 628
		pixman_region32_t *surf_region)
{
629
	struct weston_compositor *ec = ev->surface->compositor;
630
	struct gl_renderer *gr = get_renderer(ec);
631 632 633 634 635 636 637 638 639 640
	GLfloat *v;
	unsigned int *vtxcnt;
	int i, first, nfans;

	/* The final region to be painted is the intersection of
	 * 'region' and 'surf_region'. However, 'region' is in the global
	 * coordinates, and 'surf_region' is in the surface-local
	 * coordinates. texture_region() will iterate over all pairs of
	 * rectangles from both regions, compute the intersection
	 * polygon for each pair, and store it as a triangle fan if
641
	 * it has a non-zero area (at least 3 vertices, actually).
642
	 */
643
	nfans = texture_region(ev, region, surf_region);
644

645 646
	v = gr->vertices.data;
	vtxcnt = gr->vtxcnt.data;
647 648 649 650 651 652 653 654 655 656 657

	/* position: */
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof *v, &v[0]);
	glEnableVertexAttribArray(0);

	/* texcoord: */
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof *v, &v[2]);
	glEnableVertexAttribArray(1);

	for (i = 0, first = 0; i < nfans; i++) {
		glDrawArrays(GL_TRIANGLE_FAN, first, vtxcnt[i]);
658
		if (gr->fan_debug)
659
			triangle_fan_debug(ev, first, vtxcnt[i]);
660 661 662 663 664 665
		first += vtxcnt[i];
	}

	glDisableVertexAttribArray(1);
	glDisableVertexAttribArray(0);

666 667
	gr->vertices.size = 0;
	gr->vtxcnt.size = 0;
668 669
}

670 671 672 673
static int
use_output(struct weston_output *output)
{
	static int errored;
674 675
	struct gl_output_state *go = get_output_state(output);
	struct gl_renderer *gr = get_renderer(output->compositor);
676 677 678 679 680 681 682 683 684 685
	EGLBoolean ret;

	ret = eglMakeCurrent(gr->egl_display, go->egl_surface,
			     go->egl_surface, gr->egl_context);

	if (ret == EGL_FALSE) {
		if (errored)
			return -1;
		errored = 1;
		weston_log("Failed to make EGL context current.\n");
686
		gl_renderer_print_egl_error_state();
687 688 689 690 691 692
		return -1;
	}

	return 0;
}

693 694 695 696
static int
shader_init(struct gl_shader *shader, struct gl_renderer *gr,
		   const char *vertex_source, const char *fragment_source);

697
static void
698
use_shader(struct gl_renderer *gr, struct gl_shader *shader)
699
{
700 701 702 703 704 705 706 707 708 709 710
	if (!shader->program) {
		int ret;

		ret =  shader_init(shader, gr,
				   shader->vertex_source,
				   shader->fragment_source);

		if (ret < 0)
			weston_log("warning: failed to compile shader\n");
	}

711
	if (gr->current_shader == shader)
712 713
		return;
	glUseProgram(shader->program);
714
	gr->current_shader = shader;
715 716 717
}

static void
718
shader_uniforms(struct gl_shader *shader,
719 720
		struct weston_view *view,
		struct weston_output *output)
721 722
{
	int i;
723
	struct gl_surface_state *gs = get_surface_state(view->surface);
724
	struct gl_output_state *go = get_output_state(output);
725 726

	glUniformMatrix4fv(shader->proj_uniform,
727
			   1, GL_FALSE, go->output_matrix.d);
728
	glUniform4fv(shader->color_uniform, 1, gs->color);
729
	glUniform1f(shader->alpha_uniform, view->alpha);
730

731
	for (i = 0; i < gs->num_textures; i++)
732 733 734 735
		glUniform1i(shader->tex_uniforms[i], i);
}

static void
736 737
draw_view(struct weston_view *ev, struct weston_output *output,
	  pixman_region32_t *damage) /* in global coordinates */
738
{
739
	struct weston_compositor *ec = ev->surface->compositor;
740
	struct gl_renderer *gr = get_renderer(ec);
741
	struct gl_surface_state *gs = get_surface_state(ev->surface);
742 743
	/* repaint bounding region in global coordinates: */
	pixman_region32_t repaint;
744 745
	/* opaque region in surface coordinates: */
	pixman_region32_t surface_opaque;
746 747 748 749 750
	/* non-opaque region in surface coordinates: */
	pixman_region32_t surface_blend;
	GLint filter;
	int i;

751 752 753 754 755 756
	/* In case of a runtime switch of renderers, we may not have received
	 * an attach for this surface since the switch. In that case we don't
	 * have a valid buffer or a proper shader set up so skip rendering. */
	if (!gs->shader)
		return;

757 758
	pixman_region32_init(&repaint);
	pixman_region32_intersect(&repaint,
759
				  &ev->transform.boundingbox, damage);
760
	pixman_region32_subtract(&repaint, &repaint, &ev->clip);
761 762 763 764 765 766

	if (!pixman_region32_not_empty(&repaint))
		goto out;

	glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

767
	if (gr->fan_debug) {
768
		use_shader(gr, &gr->solid_shader);
769
		shader_uniforms(&gr->solid_shader, ev, output);
770 771
	}

772
	use_shader(gr, gs->shader);
773
	shader_uniforms(gs->shader, ev, output);
774

775
	if (ev->transform.enabled || output->zoom.active ||
776
	    output->current_scale != ev->surface->buffer_viewport.buffer.scale)
777 778 779 780
		filter = GL_LINEAR;
	else
		filter = GL_NEAREST;

781
	for (i = 0; i < gs->num_textures; i++) {
782
		glActiveTexture(GL_TEXTURE0 + i);
783 784 785
		glBindTexture(gs->target, gs->textures[i]);
		glTexParameteri(gs->target, GL_TEXTURE_MIN_FILTER, filter);
		glTexParameteri(gs->target, GL_TEXTURE_MAG_FILTER, filter);
786 787 788 789
	}

	/* blended region is whole surface minus opaque region: */
	pixman_region32_init_rect(&surface_blend, 0, 0,
790
				  ev->surface->width, ev->surface->height);
791 792 793 794 795
	if (ev->geometry.scissor_enabled)
		pixman_region32_intersect(&surface_blend, &surface_blend,
					  &ev->geometry.scissor);
	pixman_region32_subtract(&surface_blend, &surface_blend,
				 &ev->surface->opaque);
796

797
	/* XXX: Should we be using ev->transform.opaque here? */
798 799 800 801 802 803 804 805 806
	pixman_region32_init(&surface_opaque);
	if (ev->geometry.scissor_enabled)
		pixman_region32_intersect(&surface_opaque,
					  &ev->surface->opaque,
					  &ev->geometry.scissor);
	else
		pixman_region32_copy(&surface_opaque, &ev->surface->opaque);

	if (pixman_region32_not_empty(&surface_opaque)) {
807
		if (gs->shader == &gr->texture_shader_rgba) {
808 809 810 811 812
			/* Special case for RGBA textures with possibly
			 * bad data in alpha channel: use the shader
			 * that forces texture alpha = 1.0.
			 * Xwayland surfaces need this.
			 */
813
			use_shader(gr, &gr->texture_shader_rgbx);
814
			shader_uniforms(&gr->texture_shader_rgbx, ev, output);
815 816
		}

817
		if (ev->alpha < 1.0)
818 819 820 821
			glEnable(GL_BLEND);
		else
			glDisable(GL_BLEND);

822
		repaint_region(ev, &repaint, &surface_opaque);
823 824 825
	}

	if (pixman_region32_not_empty(&surface_blend)) {
826
		use_shader(gr, gs->shader);
827
		glEnable(GL_BLEND);
828
		repaint_region(ev, &repaint, &surface_blend);
829 830 831
	}

	pixman_region32_fini(&surface_blend);
832
	pixman_region32_fini(&surface_opaque);
833 834 835 836 837

out:
	pixman_region32_fini(&repaint);
}

838
static void
839
repaint_views(struct weston_output *output, pixman_region32_t *damage)
840 841
{
	struct weston_compositor *compositor = output->compositor;
842
	struct weston_view *view;
843

844 845 846
	wl_list_for_each_reverse(view, &compositor->view_list, link)
		if (view->plane == &compositor->primary_plane)
			draw_view(view, output, damage);
847 848
}

849
static void
850 851 852
draw_output_border_texture(struct gl_output_state *go,
			   enum gl_renderer_border_side side,
			   int32_t x, int32_t y,
853 854
			   int32_t width, int32_t height)
{
855
	struct gl_border_image *img = &go->borders[side];
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
	static GLushort indices [] = { 0, 1, 3, 3, 1, 2 };

	if (!img->data) {
		if (img->tex) {
			glDeleteTextures(1, &img->tex);
			img->tex = 0;
		}

		return;
	}

	if (!img->tex) {
		glGenTextures(1, &img->tex);
		glBindTexture(GL_TEXTURE_2D, img->tex);

		glTexParameteri(GL_TEXTURE_2D,
				GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D,
				GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D,
				GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D,
				GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	} else {
		glBindTexture(GL_TEXTURE_2D, img->tex);
	}

883
	if (go->border_status & (1 << side)) {
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
		glPixelStorei(GL_UNPACK_ROW_LENGTH_EXT, 0);
		glPixelStorei(GL_UNPACK_SKIP_PIXELS_EXT, 0);
		glPixelStorei(GL_UNPACK_SKIP_ROWS_EXT, 0);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA_EXT,
			     img->tex_width, img->height, 0,
			     GL_BGRA_EXT, GL_UNSIGNED_BYTE, img->data);
	}

	GLfloat texcoord[] = {
		0.0f, 0.0f,
		(GLfloat)img->width / (GLfloat)img->tex_width, 0.0f,
		(GLfloat)img->width / (GLfloat)img->tex_width, 1.0f,
		0.0f, 1.0f,
	};

	GLfloat verts[] = {
		x, y,
		x + width, y,
		x + width, y + height,
		x, y + height
	};

	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, verts);
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, texcoord);
	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);

	glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices);

	glDisableVertexAttribArray(1);
	glDisableVertexAttribArray(0);
}

917 918 919 920 921 922 923 924 925 926 927
static int
output_has_borders(struct weston_output *output)
{
	struct gl_output_state *go = get_output_state(output);

	return go->borders[GL_RENDERER_BORDER_TOP].data ||
	       go->borders[GL_RENDERER_BORDER_RIGHT].data ||
	       go->borders[GL_RENDERER_BORDER_BOTTOM].data ||
	       go->borders[GL_RENDERER_BORDER_LEFT].data;
}

928
static void
929 930
draw_output_borders(struct weston_output *output,
		    enum gl_border_status border_status)
931 932 933 934
{
	struct gl_output_state *go = get_output_state(output);
	struct gl_renderer *gr = get_renderer(output->compositor);
	struct gl_shader *shader = &gr->texture_shader_rgba;
935 936 937 938
	struct gl_border_image *top, *bottom, *left, *right;
	struct weston_matrix matrix;
	int full_width, full_height;

939 940 941
	if (border_status == BORDER_STATUS_CLEAN)
		return; /* Clean. Nothing to do. */

942 943 944 945 946 947 948
	top = &go->borders[GL_RENDERER_BORDER_TOP];
	bottom = &go->borders[GL_RENDERER_BORDER_BOTTOM];
	left = &go->borders[GL_RENDERER_BORDER_LEFT];
	right = &go->borders[GL_RENDERER_BORDER_RIGHT];

	full_width = output->current_mode->width + left->width + right->width;
	full_height = output->current_mode->height + top->height + bottom->height;
949 950 951 952

	glDisable(GL_BLEND);
	use_shader(gr, shader);

953 954 955 956 957 958
	glViewport(0, 0, full_width, full_height);

	weston_matrix_init(&matrix);
	weston_matrix_translate(&matrix, -full_width/2.0, -full_height/2.0, 0);
	weston_matrix_scale(&matrix, 2.0/full_width, -2.0/full_height, 1);
	glUniformMatrix4fv(shader->proj_uniform, 1, GL_FALSE, matrix.d);
959 960 961 962 963

	glUniform1i(shader->tex_uniforms[0], 0);
	glUniform1f(shader->alpha_uniform, 1);
	glActiveTexture(GL_TEXTURE0);

964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
	if (border_status & BORDER_TOP_DIRTY)
		draw_output_border_texture(go, GL_RENDERER_BORDER_TOP,
					   0, 0,
					   full_width, top->height);
	if (border_status & BORDER_LEFT_DIRTY)
		draw_output_border_texture(go, GL_RENDERER_BORDER_LEFT,
					   0, top->height,
					   left->width, output->current_mode->height);
	if (border_status & BORDER_RIGHT_DIRTY)
		draw_output_border_texture(go, GL_RENDERER_BORDER_RIGHT,
					   full_width - right->width, top->height,
					   right->width, output->current_mode->height);
	if (border_status & BORDER_BOTTOM_DIRTY)
		draw_output_border_texture(go, GL_RENDERER_BORDER_BOTTOM,
					   0, full_height - bottom->height,
					   full_width, bottom->height);
980
}
981

982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
static void
output_get_border_damage(struct weston_output *output,
			 enum gl_border_status border_status,
			 pixman_region32_t *damage)
{
	struct gl_output_state *go = get_output_state(output);
	struct gl_border_image *top, *bottom, *left, *right;
	int full_width, full_height;

	if (border_status == BORDER_STATUS_CLEAN)
		return; /* Clean. Nothing to do. */

	top = &go->borders[GL_RENDERER_BORDER_TOP];
	bottom = &go->borders[GL_RENDERER_BORDER_BOTTOM];
	left = &go->borders[GL_RENDERER_BORDER_LEFT];
	right = &go->borders[GL_RENDERER_BORDER_RIGHT];

	full_width = output->current_mode->width + left->width + right->width;
	full_height = output->current_mode->height + top->height + bottom->height;
	if (border_status & BORDER_TOP_DIRTY)
		pixman_region32_union_rect(damage, damage,
					   0, 0,
					   full_width, top->height);
	if (border_status & BORDER_LEFT_DIRTY)
		pixman_region32_union_rect(damage, damage,
					   0, top->height,
					   left->width, output->current_mode->height);
	if (border_status & BORDER_RIGHT_DIRTY)
		pixman_region32_union_rect(damage, damage,
					   full_width - right->width, top->height,
					   right->width, output->current_mode->height);
	if (border_status & BORDER_BOTTOM_DIRTY)
		pixman_region32_union_rect(damage, damage,
					   0, full_height - bottom->height,
					   full_width, bottom->height);
}

1019
static void
1020 1021
output_get_damage(struct weston_output *output,
		  pixman_region32_t *buffer_damage, uint32_t *border_damage)
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
{
	struct gl_output_state *go = get_output_state(output);
	struct gl_renderer *gr = get_renderer(output->compositor);
	EGLint buffer_age = 0;
	EGLBoolean ret;
	int i;

	if (gr->has_egl_buffer_age) {
		ret = eglQuerySurface(gr->egl_display, go->egl_surface,
				      EGL_BUFFER_AGE_EXT, &buffer_age);
		if (ret == EGL_FALSE) {
			weston_log("buffer age query failed.\n");
			gl_renderer_print_egl_error_state();
		}
	}

1038
	if (buffer_age == 0 || buffer_age - 1 > BUFFER_DAMAGE_COUNT) {
1039
		pixman_region32_copy(buffer_damage, &output->region);
1040 1041
		*border_damage = BORDER_ALL_DIRTY;
	} else {
1042
		for (i = 0; i < buffer_age - 1; i++)
1043
			*border_damage |= go->border_damage[(go->buffer_damage_index + i) % BUFFER_DAMAGE_COUNT];
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053

		if (*border_damage & BORDER_SIZE_CHANGED) {
			/* If we've had a resize, we have to do a full
			 * repaint. */
			*border_damage |= BORDER_ALL_DIRTY;
			pixman_region32_copy(buffer_damage, &output->region);
		} else {
			for (i = 0; i < buffer_age - 1; i++)
				pixman_region32_union(buffer_damage,
						      buffer_damage,
1054
						      &go->buffer_damage[(go->buffer_damage_index + i) % BUFFER_DAMAGE_COUNT]);
1055 1056
		}
	}
1057 1058 1059 1060
}

static void
output_rotate_damage(struct weston_output *output,
1061 1062
		     pixman_region32_t *output_damage,
		     enum gl_border_status border_status)
1063 1064 1065 1066 1067 1068 1069
{
	struct gl_output_state *go = get_output_state(output);
	struct gl_renderer *gr = get_renderer(output->compositor);

	if (!gr->has_egl_buffer_age)
		return;

1070 1071
	go->buffer_damage_index += BUFFER_DAMAGE_COUNT - 1;
	go->buffer_damage_index %= BUFFER_DAMAGE_COUNT;
1072

1073 1074
	pixman_region32_copy(&go->buffer_damage[go->buffer_damage_index], output_damage);
	go->border_damage[go->buffer_damage_index] = border_status;
1075 1076
}

1077 1078 1079 1080 1081 1082 1083 1084
/* NOTE: We now allow falling back to ARGB gl visuals when XRGB is
 * unavailable, so we're assuming the background has no transparency
 * and that everything with a blend, like drop shadows, will have something
 * opaque (like the background) drawn underneath it.
 *
 * Depending on the underlying hardware, violating that assumption could
 * result in seeing through to another display plane.
 */
1085
static void
1086
gl_renderer_repaint_output(struct weston_output *output,
1087 1088
			      pixman_region32_t *output_damage)
{
1089
	struct gl_output_state *go = get_output_state(output);
1090
	struct weston_compositor *compositor = output->compositor;
1091
	struct gl_renderer *gr = get_renderer(compositor);
1092 1093
	EGLBoolean ret;
	static int errored;
1094 1095 1096
	int i, nrects, buffer_height;
	EGLint *egl_damage, *d;
	pixman_box32_t *rects;
1097
	pixman_region32_t buffer_damage, total_damage;
1098
	enum gl_border_status border_damage = BORDER_STATUS_CLEAN;
1099

1100 1101 1102
	if (use_output(output) < 0)
		return;

1103 1104 1105 1106 1107
	/* Calculate the viewport */
	glViewport(go->borders[GL_RENDERER_BORDER_LEFT].width,
		   go->borders[GL_RENDERER_BORDER_BOTTOM].height,
		   output->current_mode->width,
		   output->current_mode->height);
1108

1109 1110 1111 1112 1113 1114 1115 1116 1117
	/* Calculate the global GL matrix */
	go->output_matrix = output->matrix;
	weston_matrix_translate(&go->output_matrix,
				-(output->current_mode->width / 2.0),
				-(output->current_mode->height / 2.0), 0);
	weston_matrix_scale(&go->output_matrix,
			    2.0 / output->current_mode->width,
			    -2.0 / output->current_mode->height, 1);

1118 1119 1120
	/* if debugging, redraw everything outside the damage to clean up
	 * debug lines from the previous draw on this buffer:
	 */
1121
	if (gr->fan_debug) {
1122 1123 1124 1125
		pixman_region32_t undamaged;
		pixman_region32_init(&undamaged);
		pixman_region32_subtract(&undamaged, &output->region,
					 output_damage);
1126
		gr->fan_debug = 0;
1127
		repaint_views(output, &undamaged);
1128
		gr->fan_debug = 1;
1129 1130 1131
		pixman_region32_fini(&undamaged);
	}

1132
	pixman_region32_init(&total_damage);
1133 1134
	pixman_region32_init(&buffer_damage);

1135 1136
	output_get_damage(output, &buffer_damage, &border_damage);
	output_rotate_damage(output, output_damage, go->border_status);
1137 1138

	pixman_region32_union(&total_damage, &buffer_damage, output_damage);