gl-renderer.c 69.2 KB
Newer Older
1 2
/*
 * Copyright © 2012 Intel Corporation
3
 * Copyright © 2015 Collabora, Ltd.
4
 *
5 6 7 8 9 10 11
 * 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:
12
 *
13 14 15 16 17 18 19 20 21 22 23 24
 * 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.
25 26
 */

27
#include "config.h"
28

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

32
#include <stdbool.h>
33
#include <stdlib.h>
34 35
#include <string.h>
#include <ctype.h>
36 37
#include <float.h>
#include <assert.h>
38
#include <linux/input.h>
39

40
#include "gl-renderer.h"
41
#include "vertex-clipping.h"
42

43
#include "shared/helpers.h"
44
#include "weston-egl-ext.h"
45

46
struct gl_shader {
47 48 49 50 51 52
	GLuint program;
	GLuint vertex_shader, fragment_shader;
	GLint proj_uniform;
	GLint tex_uniforms[3];
	GLint alpha_uniform;
	GLint color_uniform;
53
	const char *vertex_source, *fragment_source;
54 55
};

56 57
#define BUFFER_DAMAGE_COUNT 2

58 59 60 61 62 63 64 65 66 67
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
};

68 69 70 71 72 73 74
struct gl_border_image {
	GLuint tex;
	int32_t width, height;
	int32_t tex_width;
	void *data;
};

75
struct gl_output_state {
76
	EGLSurface egl_surface;
77
	pixman_region32_t buffer_damage[BUFFER_DAMAGE_COUNT];
78
	int buffer_damage_index;
79
	enum gl_border_status border_damage[BUFFER_DAMAGE_COUNT];
80
	struct gl_border_image borders[4];
81
	enum gl_border_status border_status;
82 83

	struct weston_matrix output_matrix;
84 85
};

86 87
enum buffer_type {
	BUFFER_TYPE_NULL,
88
	BUFFER_TYPE_SOLID, /* internal solid color surfaces without a buffer */
89 90 91 92
	BUFFER_TYPE_SHM,
	BUFFER_TYPE_EGL
};

93
struct gl_surface_state {
94
	GLfloat color[4];
95
	struct gl_shader *shader;
96 97 98

	GLuint textures[3];
	int num_textures;
99
	int needs_full_upload;
100
	pixman_region32_t texture_damage;
101

102 103 104 105 106 107
	/* These are only used by SHM surfaces to detect when we need
	 * to do a full upload to specify a new internal texture
	 * format */
	GLenum gl_format;
	GLenum gl_pixel_type;

108 109 110
	EGLImageKHR images[3];
	GLenum target;
	int num_images;
111 112

	struct weston_buffer_reference buffer_ref;
113
	enum buffer_type buffer_type;
114
	int pitch; /* in pixels */
115
	int height; /* in pixels */
116
	int y_inverted;
117 118 119 120

	struct weston_surface *surface;

	struct wl_listener surface_destroy_listener;
121
	struct wl_listener renderer_destroy_listener;
122 123
};

124
struct gl_renderer {
125 126
	struct weston_renderer base;
	int fragment_shader_debug;
127
	int fan_debug;
128 129
	struct weston_binding *fragment_binding;
	struct weston_binding *fan_binding;
130

131 132 133
	EGLDisplay egl_display;
	EGLContext egl_context;
	EGLConfig egl_config;
134

135 136 137
	struct wl_array vertices;
	struct wl_array vtxcnt;

138 139 140 141
	PFNGLEGLIMAGETARGETTEXTURE2DOESPROC image_target_texture_2d;
	PFNEGLCREATEIMAGEKHRPROC create_image;
	PFNEGLDESTROYIMAGEKHRPROC destroy_image;

142 143 144 145
#ifdef EGL_EXT_swap_buffers_with_damage
	PFNEGLSWAPBUFFERSWITHDAMAGEEXTPROC swap_buffers_with_damage;
#endif

146 147
	PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC create_platform_window;

148 149 150 151 152 153 154 155 156
	int has_unpack_subimage;

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

	int has_egl_image_external;

157 158
	int has_egl_buffer_age;

159 160
	int has_configless_context;

161 162 163 164 165 166 167 168 169
	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;
170 171

	struct wl_signal destroy_signal;
172 173
};

174 175
static PFNEGLGETPLATFORMDISPLAYEXTPROC get_platform_display = NULL;

176
static inline struct gl_output_state *
177 178
get_output_state(struct weston_output *output)
{
179
	return (struct gl_output_state *)output->renderer_state;
180 181
}

182 183 184
static int
gl_renderer_create_surface(struct weston_surface *surface);

185
static inline struct gl_surface_state *
186 187
get_surface_state(struct weston_surface *surface)
{
188 189 190
	if (!surface->renderer_state)
		gl_renderer_create_surface(surface);

191
	return (struct gl_surface_state *)surface->renderer_state;
192 193
}

194
static inline struct gl_renderer *
195 196
get_renderer(struct weston_compositor *ec)
{
197
	return (struct gl_renderer *)ec->renderer;
198 199
}

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
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
}

226
static void
227
gl_renderer_print_egl_error_state(void)
228 229 230 231 232 233 234 235
{
	EGLint code;

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

236 237 238
#define max(a, b) (((a) > (b)) ? (a) : (b))
#define min(a, b) (((a) > (b)) ? (b) : (a))

239 240 241 242 243 244 245 246 247
/*
 * 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.
 */
248
static int
249
calculate_edges(struct weston_view *ev, pixman_box32_t *rect,
250 251
		pixman_box32_t *surf_rect, GLfloat *ex, GLfloat *ey)
{
252

253 254
	struct clip_context ctx;
	int i, n;
255
	GLfloat min_x, max_x, min_y, max_y;
256 257 258 259
	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
260 261
	};

262 263 264 265
	ctx.clip.x1 = rect->x1;
	ctx.clip.y1 = rect->y1;
	ctx.clip.x2 = rect->x2;
	ctx.clip.y2 = rect->y2;
266 267

	/* transform surface to screen space: */
268
	for (i = 0; i < surf.n; i++)
269 270
		weston_view_to_global_float(ev, surf.x[i], surf.y[i],
					    &surf.x[i], &surf.y[i]);
271 272

	/* find bounding box: */
273 274 275 276 277 278 279 280
	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]);
281 282 283 284 285
	}

	/* First, simple bounding box check to discard early transformed
	 * surface rects that do not intersect with the clip region:
	 */
286 287
	if ((min_x >= ctx.clip.x2) || (max_x <= ctx.clip.x1) ||
	    (min_y >= ctx.clip.y2) || (max_y <= ctx.clip.y1))
288 289 290 291 292 293
		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:
	 */
294
	if (!ev->transform.enabled)
295
		return clip_simple(&ctx, &surf, ex, ey);
296

297 298 299 300 301
	/* 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.
302
	 */
303
	n = clip_transformed(&ctx, &surf, ex, ey);
304 305 306

	if (n < 3)
		return 0;
307 308 309 310

	return n;
}

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
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)
{
	bool merged;
	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;
}

360
static int
361
texture_region(struct weston_view *ev, pixman_region32_t *region,
362 363
		pixman_region32_t *surf_region)
{
364 365
	struct gl_surface_state *gs = get_surface_state(ev->surface);
	struct weston_compositor *ec = ev->surface->compositor;
366
	struct gl_renderer *gr = get_renderer(ec);
367 368 369
	GLfloat *v, inv_width, inv_height;
	unsigned int *vtxcnt, nvtx = 0;
	pixman_box32_t *rects, *surf_rects;
370 371 372 373
	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);
374 375
	surf_rects = pixman_region32_rectangles(surf_region, &nsurf);

376 377 378 379 380 381 382 383
	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;
	}
384 385 386
	/* worst case we can have 8 vertices per rect (ie. clipped into
	 * an octagon):
	 */
387 388
	v = wl_array_add(&gr->vertices, nrects * nsurf * 8 * 4 * sizeof *v);
	vtxcnt = wl_array_add(&gr->vtxcnt, nrects * nsurf * sizeof *vtxcnt);
389

390
	inv_width = 1.0 / gs->pitch;
391
        inv_height = 1.0 / gs->height;
392 393 394 395 396

	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];
397
			GLfloat sx, sy, bx, by;
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
			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.
			 */
415
			n = calculate_edges(ev, rect, surf_rect, ex, ey);
416 417 418 419 420
			if (n < 3)
				continue;

			/* emit edge points: */
			for (k = 0; k < n; k++) {
421 422
				weston_view_from_global_float(ev, ex[k], ey[k],
							      &sx, &sy);
423 424 425 426
				/* position: */
				*(v++) = ex[k];
				*(v++) = ey[k];
				/* texcoord: */
427 428
				weston_surface_to_buffer_float(ev->surface,
							       sx, sy,
429 430
							       &bx, &by);
				*(v++) = bx * inv_width;
431 432 433 434 435
				if (gs->y_inverted) {
					*(v++) = by * inv_height;
				} else {
					*(v++) = (gs->height - by) * inv_height;
				}
436 437 438 439 440 441
			}

			vtxcnt[nvtx++] = n;
		}
	}

442 443
	if (used_band_compression)
		free(rects);
444 445 446 447
	return nvtx;
}

static void
448
triangle_fan_debug(struct weston_view *view, int first, int count)
449
{
450
	struct weston_compositor *compositor = view->surface->compositor;
451
	struct gl_renderer *gr = get_renderer(compositor);
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
	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;
	}

479 480
	glUseProgram(gr->solid_shader.program);
	glUniform4fv(gr->solid_shader.color_uniform, 1,
481 482
			color[color_idx++ % ARRAY_LENGTH(color)]);
	glDrawElements(GL_LINES, nelems, GL_UNSIGNED_SHORT, buffer);
483
	glUseProgram(gr->current_shader->program);
484 485 486 487
	free(buffer);
}

static void
488
repaint_region(struct weston_view *ev, pixman_region32_t *region,
489 490
		pixman_region32_t *surf_region)
{
491
	struct weston_compositor *ec = ev->surface->compositor;
492
	struct gl_renderer *gr = get_renderer(ec);
493 494 495 496 497 498 499 500 501 502
	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
503
	 * it has a non-zero area (at least 3 vertices1, actually).
504
	 */
505
	nfans = texture_region(ev, region, surf_region);
506

507 508
	v = gr->vertices.data;
	vtxcnt = gr->vtxcnt.data;
509 510 511 512 513 514 515 516 517 518 519

	/* 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]);
520
		if (gr->fan_debug)
521
			triangle_fan_debug(ev, first, vtxcnt[i]);
522 523 524 525 526 527
		first += vtxcnt[i];
	}

	glDisableVertexAttribArray(1);
	glDisableVertexAttribArray(0);

528 529
	gr->vertices.size = 0;
	gr->vtxcnt.size = 0;
530 531
}

532 533 534 535
static int
use_output(struct weston_output *output)
{
	static int errored;
536 537
	struct gl_output_state *go = get_output_state(output);
	struct gl_renderer *gr = get_renderer(output->compositor);
538 539 540 541 542 543 544 545 546 547
	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");
548
		gl_renderer_print_egl_error_state();
549 550 551 552 553 554
		return -1;
	}

	return 0;
}

555 556 557 558
static int
shader_init(struct gl_shader *shader, struct gl_renderer *gr,
		   const char *vertex_source, const char *fragment_source);

559
static void
560
use_shader(struct gl_renderer *gr, struct gl_shader *shader)
561
{
562 563 564 565 566 567 568 569 570 571 572
	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");
	}

573
	if (gr->current_shader == shader)
574 575
		return;
	glUseProgram(shader->program);
576
	gr->current_shader = shader;
577 578 579
}

static void
580
shader_uniforms(struct gl_shader *shader,
581 582
		struct weston_view *view,
		struct weston_output *output)
583 584
{
	int i;
585
	struct gl_surface_state *gs = get_surface_state(view->surface);
586
	struct gl_output_state *go = get_output_state(output);
587 588

	glUniformMatrix4fv(shader->proj_uniform,
589
			   1, GL_FALSE, go->output_matrix.d);
590
	glUniform4fv(shader->color_uniform, 1, gs->color);
591
	glUniform1f(shader->alpha_uniform, view->alpha);
592

593
	for (i = 0; i < gs->num_textures; i++)
594 595 596 597
		glUniform1i(shader->tex_uniforms[i], i);
}

static void
598 599
draw_view(struct weston_view *ev, struct weston_output *output,
	  pixman_region32_t *damage) /* in global coordinates */
600
{
601
	struct weston_compositor *ec = ev->surface->compositor;
602
	struct gl_renderer *gr = get_renderer(ec);
603
	struct gl_surface_state *gs = get_surface_state(ev->surface);
604 605
	/* repaint bounding region in global coordinates: */
	pixman_region32_t repaint;
606 607
	/* opaque region in surface coordinates: */
	pixman_region32_t surface_opaque;
608 609 610 611 612
	/* non-opaque region in surface coordinates: */
	pixman_region32_t surface_blend;
	GLint filter;
	int i;

613 614 615 616 617 618
	/* 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;

619 620
	pixman_region32_init(&repaint);
	pixman_region32_intersect(&repaint,
621
				  &ev->transform.boundingbox, damage);
622
	pixman_region32_subtract(&repaint, &repaint, &ev->clip);
623 624 625 626 627 628

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

	glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

629
	if (gr->fan_debug) {
630
		use_shader(gr, &gr->solid_shader);
631
		shader_uniforms(&gr->solid_shader, ev, output);
632 633
	}

634
	use_shader(gr, gs->shader);
635
	shader_uniforms(gs->shader, ev, output);
636

637
	if (ev->transform.enabled || output->zoom.active ||
638
	    output->current_scale != ev->surface->buffer_viewport.buffer.scale)
639 640 641 642
		filter = GL_LINEAR;
	else
		filter = GL_NEAREST;

643
	for (i = 0; i < gs->num_textures; i++) {
644
		glActiveTexture(GL_TEXTURE0 + i);
645 646 647
		glBindTexture(gs->target, gs->textures[i]);
		glTexParameteri(gs->target, GL_TEXTURE_MIN_FILTER, filter);
		glTexParameteri(gs->target, GL_TEXTURE_MAG_FILTER, filter);
648 649 650 651
	}

	/* blended region is whole surface minus opaque region: */
	pixman_region32_init_rect(&surface_blend, 0, 0,
652
				  ev->surface->width, ev->surface->height);
653 654 655 656 657
	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);
658

659
	/* XXX: Should we be using ev->transform.opaque here? */
660 661 662 663 664 665 666 667 668
	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)) {
669
		if (gs->shader == &gr->texture_shader_rgba) {
670 671 672 673 674
			/* 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.
			 */
675
			use_shader(gr, &gr->texture_shader_rgbx);
676
			shader_uniforms(&gr->texture_shader_rgbx, ev, output);
677 678
		}

679
		if (ev->alpha < 1.0)
680 681 682 683
			glEnable(GL_BLEND);
		else
			glDisable(GL_BLEND);

684
		repaint_region(ev, &repaint, &surface_opaque);
685 686 687
	}

	if (pixman_region32_not_empty(&surface_blend)) {
688
		use_shader(gr, gs->shader);
689
		glEnable(GL_BLEND);
690
		repaint_region(ev, &repaint, &surface_blend);
691 692 693
	}

	pixman_region32_fini(&surface_blend);
694
	pixman_region32_fini(&surface_opaque);
695 696 697 698 699

out:
	pixman_region32_fini(&repaint);
}

700
static void
701
repaint_views(struct weston_output *output, pixman_region32_t *damage)
702 703
{
	struct weston_compositor *compositor = output->compositor;
704
	struct weston_view *view;
705

706 707 708
	wl_list_for_each_reverse(view, &compositor->view_list, link)
		if (view->plane == &compositor->primary_plane)
			draw_view(view, output, damage);
709 710
}

711
static void
712 713 714
draw_output_border_texture(struct gl_output_state *go,
			   enum gl_renderer_border_side side,
			   int32_t x, int32_t y,
715 716
			   int32_t width, int32_t height)
{
717
	struct gl_border_image *img = &go->borders[side];
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
	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);
	}

745
	if (go->border_status & (1 << side)) {
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
#ifdef GL_EXT_unpack_subimage
		glPixelStorei(GL_UNPACK_ROW_LENGTH_EXT, 0);
		glPixelStorei(GL_UNPACK_SKIP_PIXELS_EXT, 0);
		glPixelStorei(GL_UNPACK_SKIP_ROWS_EXT, 0);
#endif
		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);
}

781 782 783 784 785 786 787 788 789 790 791
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;
}

792
static void
793 794
draw_output_borders(struct weston_output *output,
		    enum gl_border_status border_status)
795 796 797 798
{
	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;
799 800 801 802
	struct gl_border_image *top, *bottom, *left, *right;
	struct weston_matrix matrix;
	int full_width, full_height;

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

806 807 808 809 810 811 812
	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;
813 814 815 816

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

817 818 819 820 821 822
	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);
823 824 825 826 827

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

828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
	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);
844
}
845

846 847 848 849 850 851 852 853 854 855 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 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);
}

883
static void
884 885
output_get_damage(struct weston_output *output,
		  pixman_region32_t *buffer_damage, uint32_t *border_damage)
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
{
	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();
		}
	}

902
	if (buffer_age == 0 || buffer_age - 1 > BUFFER_DAMAGE_COUNT) {
903
		pixman_region32_copy(buffer_damage, &output->region);
904 905
		*border_damage = BORDER_ALL_DIRTY;
	} else {
906
		for (i = 0; i < buffer_age - 1; i++)
907
			*border_damage |= go->border_damage[(go->buffer_damage_index + i) % BUFFER_DAMAGE_COUNT];
908 909 910 911 912 913 914 915 916 917

		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,
918
						      &go->buffer_damage[(go->buffer_damage_index + i) % BUFFER_DAMAGE_COUNT]);
919 920
		}
	}
921 922 923 924
}

static void
output_rotate_damage(struct weston_output *output,
925 926
		     pixman_region32_t *output_damage,
		     enum gl_border_status border_status)
927 928 929 930 931 932 933
{
	struct gl_output_state *go = get_output_state(output);
	struct gl_renderer *gr = get_renderer(output->compositor);

	if (!gr->has_egl_buffer_age)
		return;

934 935
	go->buffer_damage_index += BUFFER_DAMAGE_COUNT - 1;
	go->buffer_damage_index %= BUFFER_DAMAGE_COUNT;
936

937 938
	pixman_region32_copy(&go->buffer_damage[go->buffer_damage_index], output_damage);
	go->border_damage[go->buffer_damage_index] = border_status;
939 940
}

941 942 943 944 945 946 947 948
/* 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.
 */
949
static void
950
gl_renderer_repaint_output(struct weston_output *output,
951 952
			      pixman_region32_t *output_damage)
{
953
	struct gl_output_state *go = get_output_state(output);
954
	struct weston_compositor *compositor = output->compositor;
955
	struct gl_renderer *gr = get_renderer(compositor);
956 957
	EGLBoolean ret;
	static int errored;
958 959 960 961 962
#ifdef EGL_EXT_swap_buffers_with_damage
	int i, nrects, buffer_height;
	EGLint *egl_damage, *d;
	pixman_box32_t *rects;
#endif
963
	pixman_region32_t buffer_damage, total_damage;
964
	enum gl_border_status border_damage = BORDER_STATUS_CLEAN;
965

966 967 968
	if (use_output(output) < 0)
		return;

969 970 971 972 973
	/* 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);
974

975 976 977 978 979 980 981 982 983
	/* 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);

984 985 986
	/* if debugging, redraw everything outside the damage to clean up
	 * debug lines from the previous draw on this buffer:
	 */
987
	if (gr->fan_debug) {
988 989 990 991
		pixman_region32_t undamaged;
		pixman_region32_init(&undamaged);
		pixman_region32_subtract(&undamaged, &output->region,
					 output_damage);
992
		gr->fan_debug = 0;
993
		repaint_views(output, &undamaged);
994
		gr->fan_debug = 1;
995 996 997
		pixman_region32_fini(&undamaged);
	}

998
	pixman_region32_init(&total_damage);
999 1000
	pixman_region32_init(&buffer_damage);

1001 1002
	output_get_damage(output, &buffer_damage, &border_damage);
	output_rotate_damage(output, output_damage, go->border_status);
1003 1004

	pixman_region32_union(&total_damage, &buffer_damage, output_damage);
1005
	border_damage |= go->border_status;
1006

1007
	repaint_views(output, &total_damage);
1008 1009

	pixman_region32_fini(&total_damage);
1010
	pixman_region32_fini(&buffer_damage);
1011

1012
	draw_output_borders(output, border_damage);
1013

1014
	pixman_region32_copy(&output->previous_damage, output_damage);
1015 1016
	wl_signal_emit(&output->frame_signal, output);

1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
#ifdef EGL_EXT_swap_buffers_with_damage
	if (gr->swap_buffers_with_damage) {
		pixman_region32_init(&buffer_damage);
		weston_transformed_region(output->width, output->height,
					  output->transform,
					  output->current_scale,
					  output_damage, &buffer_damage);

		if (output_has_borders(output)) {
			pixman_region32_translate(&buffer_damage,
						  go->borders[GL_RENDERER_BORDER_LEFT].width,
						  go->borders[GL_RENDERER_BORDER_TOP].height);
			output_get_border_damage(output, go->border_status,
						 &buffer_damage);
		}

		rects = pixman_region32_rectangles(&buffer_damage, &nrects);
		egl_damage = malloc(nrects * 4 * sizeof(EGLint));

		buffer_height = go->borders[GL_RENDERER_BORDER_TOP].height +
				output->current_mode->height +
				go->borders[GL_RENDERER_BORDER_BOTTOM].height;

		d = egl_damage;
		for (i = 0; i < nrects; ++i) {
			*d++ = rects[i].x1;
			*d++ = buffer_height - rects[i].y2;
			*d++ = rects[i].x2 - rects[i].x1;
			*d++ = rects[i].y2 - rects[i].y1;
		}
		ret = gr->swap_buffers_with_damage(gr->egl_display,
						   go->egl_surface,
						   egl_damage, nrects);
		free(egl_damage);
		pixman_region32_fini(&buffer_damage);
	} else {
		ret = eglSwapBuffers(gr->egl_display, go->egl_surface);
	}
#else /* ! defined EGL_EXT_swap_buffers_with_damage */
1056
	ret = eglSwapBuffers(gr->egl_display, go->egl_surface);
1057 1058
#endif

1059 1060 1061
	if (ret == EGL_FALSE && !errored) {
		errored = 1;
		weston_log("Failed in eglSwapBuffers.\n");
1062
		gl_renderer_print_egl_error_state();
1063 1064
	}

1065
	go->border_status = BORDER_STATUS_CLEAN;
1066
}
1067

1068
static int
1069
gl_renderer_read_pixels(struct weston_output *output,
1070 1071 1072 1073 1074
			       pixman_format_code_t format, void *pixels,
			       uint32_t x, uint32_t y,
			       uint32_t width, uint32_t height)
{
	GLenum gl_format;
1075 1076 1077 1078
	struct gl_output_state *go = get_output_state(output);

	x += go->borders[GL_RENDERER_BORDER_LEFT].width;
	y += go->borders[GL_RENDERER_BORDER_BOTTOM].height;
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100

	switch (format) {
	case PIXMAN_a8r8g8b8:
		gl_format = GL_BGRA_EXT;
		break;
	case PIXMAN_a8b8g8r8:
		gl_format = GL_RGBA;
		break;
	default:
		return -1;
	}

	if (use_output(output) < 0)
		return -1;

	glPixelStorei(GL_PACK_ALIGNMENT, 1);
	glReadPixels(x, y, width, height, gl_format,
		     GL_UNSIGNED_BYTE, pixels);

	return 0;
}

1101
static void
1102
gl_renderer_flush_damage(struct weston_surface *surface)
1103
{
1104 1105
	struct gl_renderer *gr = get_renderer(surface->compositor);
	struct gl_surface_state *gs = get_surface_state(surface);
1106
	struct weston_buffer *buffer = gs->buffer_ref.buffer;
1107 1108
	struct weston_view *view;
	int texture_used;
1109

1110
#ifdef GL_EXT_unpack_subimage
1111 1112 1113 1114 1115
	pixman_box32_t *rectangles;
	void *data;
	int i, n;
#endif

1116 1117
	pixman_region32_union(&gs->texture_damage,
			      &gs->texture_damage, &surface->damage);
1118

1119 1120 1121
	if (!buffer)
		return;

1122
	/* Avoid upload, if the texture won't be used this time.
1123 1124 1125
	 * We still accumulate the damage in texture_damage, and
	 * hold the reference to the buffer, in case the surface
	 * migrates back to the primary plane.
1126
	 */
1127 1128 1129 1130 1131 1132 1133 1134
	texture_used = 0;
	wl_list_for_each(view, &surface->views, surface_link) {
		if (view->plane == &surface->compositor->primary_plane) {
			texture_used = 1;
			break;
		}
	}
	if (!texture_used)
1135 1136
		return;

1137 1138
	if (!pixman_region32_not_empty(&gs->texture_damage) &&
	    !gs->needs_full_upload)
1139
		goto done;
1140

1141
	glBindTexture(GL_TEXTURE_2D, gs->textures[0]);
1142

1143
	if (!gr->has_unpack_subimage) {
1144
		wl_shm_buffer_begin_access(buffer->shm_buffer);
1145
		glTexImage2D(GL_TEXTURE_2D, 0, gs->gl_format,
1146
			     gs->pitch, buffer->height, 0,
1147
			     gs->gl_format, gs->gl_pixel_type,
1148
			     wl_shm_buffer_get_data(buffer->shm_buffer));
1149
		wl_shm_buffer_end_access(buffer->shm_buffer);
1150

1151
		goto done;
1152 1153
	}

1154 1155
#ifdef GL_EXT_unpack_subimage
	glPixelStorei(GL_UNPACK_ROW_LENGTH_EXT, gs->pitch);
1156
	data = wl_shm_buffer_get_data(buffer->shm_buffer);
1157 1158

	if (gs->needs_full_upload) {
1159 1160
		glPixelStorei(GL_UNPACK_SKIP_PIXELS_EXT, 0);
		glPixelStorei(GL_UNPACK_SKIP_ROWS_EXT, 0);
1161
		wl_shm_buffer_begin_access(buffer->shm_buffer);
1162
		glTexImage2D(GL_TEXTURE_2D, 0, gs->gl_format,
1163
			     gs->pitch, buffer->height, 0,
1164
			     gs->gl_format, gs->gl_pixel_type, data);
1165
		wl_shm_buffer_end_access(buffer->shm_buffer);
1166 1167 1168
		goto done;
	}

1169
	rectangles = pixman_region32_rectangles(&gs->texture_damage, &n);
1170
	wl_shm_buffer_begin_access(buffer->shm_buffer);
1171
	for (i = 0; i < n; i++) {
1172 1173 1174 1175
		pixman_box32_t r;

		r = weston_surface_to_buffer_rect(surface, rectangles[i]);

1176 1177
		glPixelStorei(GL_UNPACK_SKIP_PIXELS_EXT, r.x1);
		glPixelStorei(GL_UNPACK_SKIP_ROWS_EXT, r.y1);
1178 1179
		glTexSubImage2D(GL_TEXTURE_2D, 0, r.x1, r.y1,
				r.x2 - r.x1, r.y2 - r.y1,
1180
				gs->gl_format, gs->gl_pixel_type, data);
1181
	}
1182
	wl_shm_buffer_end_access(buffer->shm_buffer);
1183
#endif
1184 1185

done:
1186 1187
	pixman_region32_fini(&gs->texture_damage);
	pixman_region32_init(&gs->texture_damage);
1188
	gs->needs_full_upload = 0;
1189 1190

	weston_buffer_reference(&gs->buffer_ref, NULL);
1191 1192
}

1193
static void
1194
ensure_textures(struct gl_surface_state *gs, int num_textures)
1195 1196 1197
{
	int i;

1198
	if (num_textures <= gs->num_textures)
1199 1200
		return;

1201 1202 1203 1204
	for (i = gs->num_textures; i < num_textures; i++) {
		glGenTextures(1, &gs->textures[i]);
		glBindTexture(gs->target, gs->textures[i]);
		glTexParameteri(gs->target,
1205
				GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1206
		glTexParameteri(gs->target,
1207 1208
				GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	}
1209 1210
	gs->num_textures = num_textures;
	glBindTexture(gs->target, 0);
1211 1212
}

1213 1214 1215 1216 1217 1218 1219
static void
gl_renderer_attach_shm(struct weston_surface *es, struct weston_buffer *buffer,
		       struct wl_shm_buffer *shm_buffer)
{
	struct weston_compositor *ec = es->compositor;
	struct gl_renderer *gr = get_renderer(ec);
	struct gl_surface_state *gs = get_surface_state(es);
1220
	GLenum gl_format, gl_pixel_type;
1221
	int pitch;
Ander Conselvan de Oliveira's avatar