ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / cc / output / gl_renderer.cc
blob6142d96408d22e51d47489f905c1280e62ffa635
1 // Copyright 2010 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "cc/output/gl_renderer.h"
7 #include <algorithm>
8 #include <limits>
9 #include <set>
10 #include <string>
11 #include <vector>
13 #include "base/logging.h"
14 #include "base/trace_event/trace_event.h"
15 #include "cc/base/math_util.h"
16 #include "cc/layers/video_layer_impl.h"
17 #include "cc/output/compositor_frame.h"
18 #include "cc/output/compositor_frame_metadata.h"
19 #include "cc/output/context_provider.h"
20 #include "cc/output/copy_output_request.h"
21 #include "cc/output/geometry_binding.h"
22 #include "cc/output/gl_frame_data.h"
23 #include "cc/output/output_surface.h"
24 #include "cc/output/render_surface_filters.h"
25 #include "cc/quads/picture_draw_quad.h"
26 #include "cc/quads/render_pass.h"
27 #include "cc/quads/stream_video_draw_quad.h"
28 #include "cc/quads/texture_draw_quad.h"
29 #include "cc/resources/layer_quad.h"
30 #include "cc/resources/scoped_gpu_raster.h"
31 #include "cc/resources/scoped_resource.h"
32 #include "cc/resources/texture_mailbox_deleter.h"
33 #include "gpu/GLES2/gl2extchromium.h"
34 #include "gpu/command_buffer/client/context_support.h"
35 #include "gpu/command_buffer/client/gles2_interface.h"
36 #include "gpu/command_buffer/common/gpu_memory_allocation.h"
37 #include "third_party/skia/include/core/SkBitmap.h"
38 #include "third_party/skia/include/core/SkColor.h"
39 #include "third_party/skia/include/core/SkColorFilter.h"
40 #include "third_party/skia/include/core/SkImage.h"
41 #include "third_party/skia/include/core/SkSurface.h"
42 #include "third_party/skia/include/gpu/GrContext.h"
43 #include "third_party/skia/include/gpu/GrTexture.h"
44 #include "third_party/skia/include/gpu/SkGrTexturePixelRef.h"
45 #include "third_party/skia/include/gpu/gl/GrGLInterface.h"
46 #include "ui/gfx/geometry/quad_f.h"
47 #include "ui/gfx/geometry/rect_conversions.h"
49 using gpu::gles2::GLES2Interface;
51 namespace cc {
52 namespace {
54 bool NeedsIOSurfaceReadbackWorkaround() {
55 #if defined(OS_MACOSX)
56 // This isn't strictly required in DumpRenderTree-mode when Mesa is used,
57 // but it doesn't seem to hurt.
58 return true;
59 #else
60 return false;
61 #endif
64 Float4 UVTransform(const TextureDrawQuad* quad) {
65 gfx::PointF uv0 = quad->uv_top_left;
66 gfx::PointF uv1 = quad->uv_bottom_right;
67 Float4 xform = {{uv0.x(), uv0.y(), uv1.x() - uv0.x(), uv1.y() - uv0.y()}};
68 if (quad->flipped) {
69 xform.data[1] = 1.0f - xform.data[1];
70 xform.data[3] = -xform.data[3];
72 return xform;
75 Float4 PremultipliedColor(SkColor color) {
76 const float factor = 1.0f / 255.0f;
77 const float alpha = SkColorGetA(color) * factor;
79 Float4 result = {
80 {SkColorGetR(color) * factor * alpha, SkColorGetG(color) * factor * alpha,
81 SkColorGetB(color) * factor * alpha, alpha}};
82 return result;
85 SamplerType SamplerTypeFromTextureTarget(GLenum target) {
86 switch (target) {
87 case GL_TEXTURE_2D:
88 return SAMPLER_TYPE_2D;
89 case GL_TEXTURE_RECTANGLE_ARB:
90 return SAMPLER_TYPE_2D_RECT;
91 case GL_TEXTURE_EXTERNAL_OES:
92 return SAMPLER_TYPE_EXTERNAL_OES;
93 default:
94 NOTREACHED();
95 return SAMPLER_TYPE_2D;
99 BlendMode BlendModeFromSkXfermode(SkXfermode::Mode mode) {
100 switch (mode) {
101 case SkXfermode::kSrcOver_Mode:
102 return BLEND_MODE_NORMAL;
103 case SkXfermode::kScreen_Mode:
104 return BLEND_MODE_SCREEN;
105 case SkXfermode::kOverlay_Mode:
106 return BLEND_MODE_OVERLAY;
107 case SkXfermode::kDarken_Mode:
108 return BLEND_MODE_DARKEN;
109 case SkXfermode::kLighten_Mode:
110 return BLEND_MODE_LIGHTEN;
111 case SkXfermode::kColorDodge_Mode:
112 return BLEND_MODE_COLOR_DODGE;
113 case SkXfermode::kColorBurn_Mode:
114 return BLEND_MODE_COLOR_BURN;
115 case SkXfermode::kHardLight_Mode:
116 return BLEND_MODE_HARD_LIGHT;
117 case SkXfermode::kSoftLight_Mode:
118 return BLEND_MODE_SOFT_LIGHT;
119 case SkXfermode::kDifference_Mode:
120 return BLEND_MODE_DIFFERENCE;
121 case SkXfermode::kExclusion_Mode:
122 return BLEND_MODE_EXCLUSION;
123 case SkXfermode::kMultiply_Mode:
124 return BLEND_MODE_MULTIPLY;
125 case SkXfermode::kHue_Mode:
126 return BLEND_MODE_HUE;
127 case SkXfermode::kSaturation_Mode:
128 return BLEND_MODE_SATURATION;
129 case SkXfermode::kColor_Mode:
130 return BLEND_MODE_COLOR;
131 case SkXfermode::kLuminosity_Mode:
132 return BLEND_MODE_LUMINOSITY;
133 default:
134 NOTREACHED();
135 return BLEND_MODE_NONE;
139 // Smallest unit that impact anti-aliasing output. We use this to
140 // determine when anti-aliasing is unnecessary.
141 const float kAntiAliasingEpsilon = 1.0f / 1024.0f;
143 // Block or crash if the number of pending sync queries reach this high as
144 // something is seriously wrong on the service side if this happens.
145 const size_t kMaxPendingSyncQueries = 16;
147 } // anonymous namespace
149 static GLint GetActiveTextureUnit(GLES2Interface* gl) {
150 GLint active_unit = 0;
151 gl->GetIntegerv(GL_ACTIVE_TEXTURE, &active_unit);
152 return active_unit;
155 class GLRenderer::ScopedUseGrContext {
156 public:
157 static scoped_ptr<ScopedUseGrContext> Create(GLRenderer* renderer,
158 DrawingFrame* frame) {
159 return make_scoped_ptr(new ScopedUseGrContext(renderer, frame));
162 ~ScopedUseGrContext() {
163 // Pass context control back to GLrenderer.
164 scoped_gpu_raster_ = nullptr;
165 renderer_->RestoreGLState();
166 renderer_->RestoreFramebuffer(frame_);
169 GrContext* context() const {
170 return renderer_->output_surface_->context_provider()->GrContext();
173 private:
174 ScopedUseGrContext(GLRenderer* renderer, DrawingFrame* frame)
175 : scoped_gpu_raster_(
176 new ScopedGpuRaster(renderer->output_surface_->context_provider())),
177 renderer_(renderer),
178 frame_(frame) {
179 // scoped_gpu_raster_ passes context control to Skia.
182 scoped_ptr<ScopedGpuRaster> scoped_gpu_raster_;
183 GLRenderer* renderer_;
184 DrawingFrame* frame_;
186 DISALLOW_COPY_AND_ASSIGN(ScopedUseGrContext);
189 struct GLRenderer::PendingAsyncReadPixels {
190 PendingAsyncReadPixels() : buffer(0) {}
192 scoped_ptr<CopyOutputRequest> copy_request;
193 base::CancelableClosure finished_read_pixels_callback;
194 unsigned buffer;
196 private:
197 DISALLOW_COPY_AND_ASSIGN(PendingAsyncReadPixels);
200 class GLRenderer::SyncQuery {
201 public:
202 explicit SyncQuery(gpu::gles2::GLES2Interface* gl)
203 : gl_(gl), query_id_(0u), is_pending_(false), weak_ptr_factory_(this) {
204 gl_->GenQueriesEXT(1, &query_id_);
206 virtual ~SyncQuery() { gl_->DeleteQueriesEXT(1, &query_id_); }
208 scoped_refptr<ResourceProvider::Fence> Begin() {
209 DCHECK(!IsPending());
210 // Invalidate weak pointer held by old fence.
211 weak_ptr_factory_.InvalidateWeakPtrs();
212 // Note: In case the set of drawing commands issued before End() do not
213 // depend on the query, defer BeginQueryEXT call until Set() is called and
214 // query is required.
215 return make_scoped_refptr<ResourceProvider::Fence>(
216 new Fence(weak_ptr_factory_.GetWeakPtr()));
219 void Set() {
220 if (is_pending_)
221 return;
223 // Note: BeginQueryEXT on GL_COMMANDS_COMPLETED_CHROMIUM is effectively a
224 // noop relative to GL, so it doesn't matter where it happens but we still
225 // make sure to issue this command when Set() is called (prior to issuing
226 // any drawing commands that depend on query), in case some future extension
227 // can take advantage of this.
228 gl_->BeginQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM, query_id_);
229 is_pending_ = true;
232 void End() {
233 if (!is_pending_)
234 return;
236 gl_->EndQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM);
239 bool IsPending() {
240 if (!is_pending_)
241 return false;
243 unsigned result_available = 1;
244 gl_->GetQueryObjectuivEXT(
245 query_id_, GL_QUERY_RESULT_AVAILABLE_EXT, &result_available);
246 is_pending_ = !result_available;
247 return is_pending_;
250 void Wait() {
251 if (!is_pending_)
252 return;
254 unsigned result = 0;
255 gl_->GetQueryObjectuivEXT(query_id_, GL_QUERY_RESULT_EXT, &result);
256 is_pending_ = false;
259 private:
260 class Fence : public ResourceProvider::Fence {
261 public:
262 explicit Fence(base::WeakPtr<GLRenderer::SyncQuery> query)
263 : query_(query) {}
265 // Overridden from ResourceProvider::Fence:
266 void Set() override {
267 DCHECK(query_);
268 query_->Set();
270 bool HasPassed() override { return !query_ || !query_->IsPending(); }
271 void Wait() override {
272 if (query_)
273 query_->Wait();
276 private:
277 ~Fence() override {}
279 base::WeakPtr<SyncQuery> query_;
281 DISALLOW_COPY_AND_ASSIGN(Fence);
284 gpu::gles2::GLES2Interface* gl_;
285 unsigned query_id_;
286 bool is_pending_;
287 base::WeakPtrFactory<SyncQuery> weak_ptr_factory_;
289 DISALLOW_COPY_AND_ASSIGN(SyncQuery);
292 scoped_ptr<GLRenderer> GLRenderer::Create(
293 RendererClient* client,
294 const RendererSettings* settings,
295 OutputSurface* output_surface,
296 ResourceProvider* resource_provider,
297 TextureMailboxDeleter* texture_mailbox_deleter,
298 int highp_threshold_min) {
299 return make_scoped_ptr(new GLRenderer(client,
300 settings,
301 output_surface,
302 resource_provider,
303 texture_mailbox_deleter,
304 highp_threshold_min));
307 GLRenderer::GLRenderer(RendererClient* client,
308 const RendererSettings* settings,
309 OutputSurface* output_surface,
310 ResourceProvider* resource_provider,
311 TextureMailboxDeleter* texture_mailbox_deleter,
312 int highp_threshold_min)
313 : DirectRenderer(client, settings, output_surface, resource_provider),
314 offscreen_framebuffer_id_(0),
315 shared_geometry_quad_(QuadVertexRect()),
316 gl_(output_surface->context_provider()->ContextGL()),
317 context_support_(output_surface->context_provider()->ContextSupport()),
318 texture_mailbox_deleter_(texture_mailbox_deleter),
319 is_backbuffer_discarded_(false),
320 is_scissor_enabled_(false),
321 scissor_rect_needs_reset_(true),
322 stencil_shadow_(false),
323 blend_shadow_(false),
324 highp_threshold_min_(highp_threshold_min),
325 highp_threshold_cache_(0),
326 use_sync_query_(false),
327 on_demand_tile_raster_resource_id_(0) {
328 DCHECK(gl_);
329 DCHECK(context_support_);
331 ContextProvider::Capabilities context_caps =
332 output_surface_->context_provider()->ContextCapabilities();
334 capabilities_.using_partial_swap =
335 settings_->partial_swap_enabled && context_caps.gpu.post_sub_buffer;
337 DCHECK(!context_caps.gpu.iosurface || context_caps.gpu.texture_rectangle);
339 capabilities_.using_egl_image = context_caps.gpu.egl_image_external;
341 capabilities_.max_texture_size = resource_provider_->max_texture_size();
342 capabilities_.best_texture_format = resource_provider_->best_texture_format();
344 // The updater can access textures while the GLRenderer is using them.
345 capabilities_.allow_partial_texture_updates = true;
347 capabilities_.using_image = context_caps.gpu.image;
349 capabilities_.using_discard_framebuffer =
350 context_caps.gpu.discard_framebuffer;
352 capabilities_.allow_rasterize_on_demand = true;
354 use_sync_query_ = context_caps.gpu.sync_query;
355 use_blend_equation_advanced_ = context_caps.gpu.blend_equation_advanced;
356 use_blend_equation_advanced_coherent_ =
357 context_caps.gpu.blend_equation_advanced_coherent;
359 InitializeSharedObjects();
362 GLRenderer::~GLRenderer() {
363 while (!pending_async_read_pixels_.empty()) {
364 PendingAsyncReadPixels* pending_read = pending_async_read_pixels_.back();
365 pending_read->finished_read_pixels_callback.Cancel();
366 pending_async_read_pixels_.pop_back();
369 in_use_overlay_resources_.clear();
371 CleanupSharedObjects();
374 const RendererCapabilitiesImpl& GLRenderer::Capabilities() const {
375 return capabilities_;
378 void GLRenderer::DebugGLCall(GLES2Interface* gl,
379 const char* command,
380 const char* file,
381 int line) {
382 GLuint error = gl->GetError();
383 if (error != GL_NO_ERROR)
384 LOG(ERROR) << "GL command failed: File: " << file << "\n\tLine " << line
385 << "\n\tcommand: " << command << ", error "
386 << static_cast<int>(error) << "\n";
389 void GLRenderer::DidChangeVisibility() {
390 EnforceMemoryPolicy();
392 context_support_->SetSurfaceVisible(visible());
395 void GLRenderer::ReleaseRenderPassTextures() { render_pass_textures_.clear(); }
397 void GLRenderer::DiscardPixels(bool has_external_stencil_test,
398 bool draw_rect_covers_full_surface) {
399 if (has_external_stencil_test || !draw_rect_covers_full_surface ||
400 !capabilities_.using_discard_framebuffer)
401 return;
402 bool using_default_framebuffer =
403 !current_framebuffer_lock_ &&
404 output_surface_->capabilities().uses_default_gl_framebuffer;
405 GLenum attachments[] = {static_cast<GLenum>(
406 using_default_framebuffer ? GL_COLOR_EXT : GL_COLOR_ATTACHMENT0_EXT)};
407 gl_->DiscardFramebufferEXT(
408 GL_FRAMEBUFFER, arraysize(attachments), attachments);
411 void GLRenderer::ClearFramebuffer(DrawingFrame* frame,
412 bool has_external_stencil_test) {
413 // It's unsafe to clear when we have a stencil test because glClear ignores
414 // stencil.
415 if (has_external_stencil_test) {
416 DCHECK(!frame->current_render_pass->has_transparent_background);
417 return;
420 // On DEBUG builds, opaque render passes are cleared to blue to easily see
421 // regions that were not drawn on the screen.
422 if (frame->current_render_pass->has_transparent_background)
423 GLC(gl_, gl_->ClearColor(0, 0, 0, 0));
424 else
425 GLC(gl_, gl_->ClearColor(0, 0, 1, 1));
427 bool always_clear = false;
428 #ifndef NDEBUG
429 always_clear = true;
430 #endif
431 if (always_clear || frame->current_render_pass->has_transparent_background) {
432 GLbitfield clear_bits = GL_COLOR_BUFFER_BIT;
433 if (always_clear)
434 clear_bits |= GL_STENCIL_BUFFER_BIT;
435 gl_->Clear(clear_bits);
439 static ResourceProvider::ResourceId WaitOnResourceSyncPoints(
440 ResourceProvider* resource_provider,
441 ResourceProvider::ResourceId resource_id) {
442 resource_provider->WaitSyncPointIfNeeded(resource_id);
443 return resource_id;
446 void GLRenderer::BeginDrawingFrame(DrawingFrame* frame) {
447 TRACE_EVENT0("cc", "GLRenderer::BeginDrawingFrame");
449 scoped_refptr<ResourceProvider::Fence> read_lock_fence;
450 if (use_sync_query_) {
451 // Block until oldest sync query has passed if the number of pending queries
452 // ever reach kMaxPendingSyncQueries.
453 if (pending_sync_queries_.size() >= kMaxPendingSyncQueries) {
454 LOG(ERROR) << "Reached limit of pending sync queries.";
456 pending_sync_queries_.front()->Wait();
457 DCHECK(!pending_sync_queries_.front()->IsPending());
460 while (!pending_sync_queries_.empty()) {
461 if (pending_sync_queries_.front()->IsPending())
462 break;
464 available_sync_queries_.push_back(pending_sync_queries_.take_front());
467 current_sync_query_ = available_sync_queries_.empty()
468 ? make_scoped_ptr(new SyncQuery(gl_))
469 : available_sync_queries_.take_front();
471 read_lock_fence = current_sync_query_->Begin();
472 } else {
473 read_lock_fence =
474 make_scoped_refptr(new ResourceProvider::SynchronousFence(gl_));
476 resource_provider_->SetReadLockFence(read_lock_fence.get());
478 // Insert WaitSyncPointCHROMIUM on quad resources prior to drawing the frame,
479 // so that drawing can proceed without GL context switching interruptions.
480 DrawQuad::ResourceIteratorCallback wait_on_resource_syncpoints_callback =
481 base::Bind(&WaitOnResourceSyncPoints, resource_provider_);
483 for (const auto& pass : *frame->render_passes_in_draw_order) {
484 for (const auto& quad : pass->quad_list)
485 quad->IterateResources(wait_on_resource_syncpoints_callback);
488 // TODO(enne): Do we need to reinitialize all of this state per frame?
489 ReinitializeGLState();
492 void GLRenderer::DoNoOp() {
493 GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, 0));
494 GLC(gl_, gl_->Flush());
497 void GLRenderer::DoDrawQuad(DrawingFrame* frame, const DrawQuad* quad) {
498 DCHECK(quad->rect.Contains(quad->visible_rect));
499 if (quad->material != DrawQuad::TEXTURE_CONTENT) {
500 FlushTextureQuadCache();
503 switch (quad->material) {
504 case DrawQuad::INVALID:
505 NOTREACHED();
506 break;
507 case DrawQuad::CHECKERBOARD:
508 DrawCheckerboardQuad(frame, CheckerboardDrawQuad::MaterialCast(quad));
509 break;
510 case DrawQuad::DEBUG_BORDER:
511 DrawDebugBorderQuad(frame, DebugBorderDrawQuad::MaterialCast(quad));
512 break;
513 case DrawQuad::IO_SURFACE_CONTENT:
514 DrawIOSurfaceQuad(frame, IOSurfaceDrawQuad::MaterialCast(quad));
515 break;
516 case DrawQuad::PICTURE_CONTENT:
517 // PictureDrawQuad should only be used for resourceless software draws.
518 NOTREACHED();
519 break;
520 case DrawQuad::RENDER_PASS:
521 DrawRenderPassQuad(frame, RenderPassDrawQuad::MaterialCast(quad));
522 break;
523 case DrawQuad::SOLID_COLOR:
524 DrawSolidColorQuad(frame, SolidColorDrawQuad::MaterialCast(quad));
525 break;
526 case DrawQuad::STREAM_VIDEO_CONTENT:
527 DrawStreamVideoQuad(frame, StreamVideoDrawQuad::MaterialCast(quad));
528 break;
529 case DrawQuad::SURFACE_CONTENT:
530 // Surface content should be fully resolved to other quad types before
531 // reaching a direct renderer.
532 NOTREACHED();
533 break;
534 case DrawQuad::TEXTURE_CONTENT:
535 EnqueueTextureQuad(frame, TextureDrawQuad::MaterialCast(quad));
536 break;
537 case DrawQuad::TILED_CONTENT:
538 DrawTileQuad(frame, TileDrawQuad::MaterialCast(quad));
539 break;
540 case DrawQuad::YUV_VIDEO_CONTENT:
541 DrawYUVVideoQuad(frame, YUVVideoDrawQuad::MaterialCast(quad));
542 break;
546 void GLRenderer::DrawCheckerboardQuad(const DrawingFrame* frame,
547 const CheckerboardDrawQuad* quad) {
548 SetBlendEnabled(quad->ShouldDrawWithBlending());
550 const TileCheckerboardProgram* program = GetTileCheckerboardProgram();
551 DCHECK(program && (program->initialized() || IsContextLost()));
552 SetUseProgram(program->program());
554 SkColor color = quad->color;
555 GLC(gl_,
556 gl_->Uniform4f(program->fragment_shader().color_location(),
557 SkColorGetR(color) * (1.0f / 255.0f),
558 SkColorGetG(color) * (1.0f / 255.0f),
559 SkColorGetB(color) * (1.0f / 255.0f),
560 1));
562 const int checkerboard_width = 16;
563 float frequency = 1.0f / checkerboard_width;
565 gfx::Rect tile_rect = quad->rect;
566 float tex_offset_x = tile_rect.x() % checkerboard_width;
567 float tex_offset_y = tile_rect.y() % checkerboard_width;
568 float tex_scale_x = tile_rect.width();
569 float tex_scale_y = tile_rect.height();
570 GLC(gl_,
571 gl_->Uniform4f(program->fragment_shader().tex_transform_location(),
572 tex_offset_x,
573 tex_offset_y,
574 tex_scale_x,
575 tex_scale_y));
577 GLC(gl_,
578 gl_->Uniform1f(program->fragment_shader().frequency_location(),
579 frequency));
581 SetShaderOpacity(quad->opacity(),
582 program->fragment_shader().alpha_location());
583 DrawQuadGeometry(frame,
584 quad->quadTransform(),
585 quad->rect,
586 program->vertex_shader().matrix_location());
589 void GLRenderer::DrawDebugBorderQuad(const DrawingFrame* frame,
590 const DebugBorderDrawQuad* quad) {
591 SetBlendEnabled(quad->ShouldDrawWithBlending());
593 static float gl_matrix[16];
594 const DebugBorderProgram* program = GetDebugBorderProgram();
595 DCHECK(program && (program->initialized() || IsContextLost()));
596 SetUseProgram(program->program());
598 // Use the full quad_rect for debug quads to not move the edges based on
599 // partial swaps.
600 gfx::Rect layer_rect = quad->rect;
601 gfx::Transform render_matrix;
602 QuadRectTransform(&render_matrix, quad->quadTransform(), layer_rect);
603 GLRenderer::ToGLMatrix(&gl_matrix[0],
604 frame->projection_matrix * render_matrix);
605 GLC(gl_,
606 gl_->UniformMatrix4fv(
607 program->vertex_shader().matrix_location(), 1, false, &gl_matrix[0]));
609 SkColor color = quad->color;
610 float alpha = SkColorGetA(color) * (1.0f / 255.0f);
612 GLC(gl_,
613 gl_->Uniform4f(program->fragment_shader().color_location(),
614 (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
615 (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
616 (SkColorGetB(color) * (1.0f / 255.0f)) * alpha,
617 alpha));
619 GLC(gl_, gl_->LineWidth(quad->width));
621 // The indices for the line are stored in the same array as the triangle
622 // indices.
623 GLC(gl_, gl_->DrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, 0));
626 static skia::RefPtr<SkImage> ApplyImageFilter(
627 scoped_ptr<GLRenderer::ScopedUseGrContext> use_gr_context,
628 ResourceProvider* resource_provider,
629 const gfx::Rect& rect,
630 const gfx::Vector2dF& scale,
631 SkImageFilter* filter,
632 ScopedResource* source_texture_resource) {
633 if (!filter)
634 return skia::RefPtr<SkImage>();
636 if (!use_gr_context)
637 return skia::RefPtr<SkImage>();
639 ResourceProvider::ScopedReadLockGL lock(resource_provider,
640 source_texture_resource->id());
642 // Wrap the source texture in a Ganesh platform texture.
643 GrBackendTextureDesc backend_texture_description;
644 backend_texture_description.fWidth = source_texture_resource->size().width();
645 backend_texture_description.fHeight =
646 source_texture_resource->size().height();
647 backend_texture_description.fConfig = kSkia8888_GrPixelConfig;
648 backend_texture_description.fTextureHandle = lock.texture_id();
649 backend_texture_description.fOrigin = kBottomLeft_GrSurfaceOrigin;
650 skia::RefPtr<GrTexture> texture =
651 skia::AdoptRef(use_gr_context->context()->wrapBackendTexture(
652 backend_texture_description));
653 if (!texture) {
654 TRACE_EVENT_INSTANT0("cc",
655 "ApplyImageFilter wrap background texture failed",
656 TRACE_EVENT_SCOPE_THREAD);
657 return skia::RefPtr<SkImage>();
660 SkImageInfo info =
661 SkImageInfo::MakeN32Premul(source_texture_resource->size().width(),
662 source_texture_resource->size().height());
663 // Place the platform texture inside an SkBitmap.
664 SkBitmap source;
665 source.setInfo(info);
666 skia::RefPtr<SkGrPixelRef> pixel_ref =
667 skia::AdoptRef(new SkGrPixelRef(info, texture.get()));
668 source.setPixelRef(pixel_ref.get());
670 // Create a scratch texture for backing store.
671 GrTextureDesc desc;
672 desc.fFlags = kRenderTarget_GrTextureFlagBit | kNoStencil_GrTextureFlagBit;
673 desc.fSampleCnt = 0;
674 desc.fWidth = source.width();
675 desc.fHeight = source.height();
676 desc.fConfig = kSkia8888_GrPixelConfig;
677 desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
678 skia::RefPtr<GrTexture> backing_store =
679 skia::AdoptRef(use_gr_context->context()->refScratchTexture(
680 desc, GrContext::kExact_ScratchTexMatch));
681 if (!backing_store) {
682 TRACE_EVENT_INSTANT0("cc",
683 "ApplyImageFilter scratch texture allocation failed",
684 TRACE_EVENT_SCOPE_THREAD);
685 return skia::RefPtr<SkImage>();
688 // Create surface to draw into.
689 skia::RefPtr<SkSurface> surface = skia::AdoptRef(
690 SkSurface::NewRenderTargetDirect(backing_store->asRenderTarget()));
691 skia::RefPtr<SkCanvas> canvas = skia::SharePtr(surface->getCanvas());
693 // Draw the source bitmap through the filter to the canvas.
694 SkPaint paint;
695 paint.setImageFilter(filter);
696 canvas->clear(SK_ColorTRANSPARENT);
698 // The origin of the filter is top-left and the origin of the source is
699 // bottom-left, but the orientation is the same, so we must translate the
700 // filter so that it renders at the bottom of the texture to avoid
701 // misregistration.
702 int y_translate = source.height() - rect.height() - rect.origin().y();
703 canvas->translate(-rect.origin().x(), y_translate);
704 canvas->scale(scale.x(), scale.y());
705 canvas->drawSprite(source, 0, 0, &paint);
707 skia::RefPtr<SkImage> image = skia::AdoptRef(surface->newImageSnapshot());
708 if (!image || !image->getTexture()) {
709 return skia::RefPtr<SkImage>();
712 // Flush the GrContext to ensure all buffered GL calls are drawn to the
713 // backing store before we access and return it, and have cc begin using the
714 // GL context again.
715 canvas->flush();
717 return image;
720 bool GLRenderer::CanApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode) {
721 return use_blend_equation_advanced_ ||
722 blend_mode == SkXfermode::kScreen_Mode ||
723 blend_mode == SkXfermode::kSrcOver_Mode;
726 void GLRenderer::ApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode) {
727 DCHECK(CanApplyBlendModeUsingBlendFunc(blend_mode));
729 // Any modes set here must be reset in RestoreBlendFuncToDefault
730 if (use_blend_equation_advanced_) {
731 GLenum equation = GL_FUNC_ADD;
733 switch (blend_mode) {
734 case SkXfermode::kScreen_Mode:
735 equation = GL_SCREEN_KHR;
736 break;
737 case SkXfermode::kOverlay_Mode:
738 equation = GL_OVERLAY_KHR;
739 break;
740 case SkXfermode::kDarken_Mode:
741 equation = GL_DARKEN_KHR;
742 break;
743 case SkXfermode::kLighten_Mode:
744 equation = GL_LIGHTEN_KHR;
745 break;
746 case SkXfermode::kColorDodge_Mode:
747 equation = GL_COLORDODGE_KHR;
748 break;
749 case SkXfermode::kColorBurn_Mode:
750 equation = GL_COLORBURN_KHR;
751 break;
752 case SkXfermode::kHardLight_Mode:
753 equation = GL_HARDLIGHT_KHR;
754 break;
755 case SkXfermode::kSoftLight_Mode:
756 equation = GL_SOFTLIGHT_KHR;
757 break;
758 case SkXfermode::kDifference_Mode:
759 equation = GL_DIFFERENCE_KHR;
760 break;
761 case SkXfermode::kExclusion_Mode:
762 equation = GL_EXCLUSION_KHR;
763 break;
764 case SkXfermode::kMultiply_Mode:
765 equation = GL_MULTIPLY_KHR;
766 break;
767 case SkXfermode::kHue_Mode:
768 equation = GL_HSL_HUE_KHR;
769 break;
770 case SkXfermode::kSaturation_Mode:
771 equation = GL_HSL_SATURATION_KHR;
772 break;
773 case SkXfermode::kColor_Mode:
774 equation = GL_HSL_COLOR_KHR;
775 break;
776 case SkXfermode::kLuminosity_Mode:
777 equation = GL_HSL_LUMINOSITY_KHR;
778 break;
779 default:
780 return;
783 GLC(gl_, gl_->BlendEquation(equation));
784 } else {
785 if (blend_mode == SkXfermode::kScreen_Mode) {
786 GLC(gl_, gl_->BlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE));
791 void GLRenderer::RestoreBlendFuncToDefault(SkXfermode::Mode blend_mode) {
792 if (blend_mode == SkXfermode::kSrcOver_Mode)
793 return;
795 if (use_blend_equation_advanced_) {
796 GLC(gl_, gl_->BlendEquation(GL_FUNC_ADD));
797 } else {
798 GLC(gl_, gl_->BlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA));
802 bool GLRenderer::ShouldApplyBackgroundFilters(DrawingFrame* frame,
803 const RenderPassDrawQuad* quad) {
804 if (quad->background_filters.IsEmpty())
805 return false;
807 // TODO(danakj): We only allow background filters on an opaque render surface
808 // because other surfaces may contain translucent pixels, and the contents
809 // behind those translucent pixels wouldn't have the filter applied.
810 if (frame->current_render_pass->has_transparent_background)
811 return false;
813 // TODO(ajuma): Add support for reference filters once
814 // FilterOperations::GetOutsets supports reference filters.
815 if (quad->background_filters.HasReferenceFilter())
816 return false;
817 return true;
820 gfx::Rect GLRenderer::GetBackdropBoundingBoxForRenderPassQuad(
821 DrawingFrame* frame,
822 const RenderPassDrawQuad* quad,
823 const gfx::Transform& contents_device_transform,
824 bool use_aa) {
825 gfx::Rect backdrop_rect = gfx::ToEnclosingRect(MathUtil::MapClippedRect(
826 contents_device_transform, SharedGeometryQuad().BoundingBox()));
828 if (ShouldApplyBackgroundFilters(frame, quad)) {
829 int top, right, bottom, left;
830 quad->background_filters.GetOutsets(&top, &right, &bottom, &left);
831 backdrop_rect.Inset(-left, -top, -right, -bottom);
834 if (!backdrop_rect.IsEmpty() && use_aa) {
835 const int kOutsetForAntialiasing = 1;
836 backdrop_rect.Inset(-kOutsetForAntialiasing, -kOutsetForAntialiasing);
839 backdrop_rect.Intersect(MoveFromDrawToWindowSpace(
840 frame, frame->current_render_pass->output_rect));
841 return backdrop_rect;
844 scoped_ptr<ScopedResource> GLRenderer::GetBackdropTexture(
845 const gfx::Rect& bounding_rect) {
846 scoped_ptr<ScopedResource> device_background_texture =
847 ScopedResource::Create(resource_provider_);
848 // CopyTexImage2D fails when called on a texture having immutable storage.
849 device_background_texture->Allocate(
850 bounding_rect.size(), ResourceProvider::TEXTURE_HINT_DEFAULT, RGBA_8888);
852 ResourceProvider::ScopedWriteLockGL lock(resource_provider_,
853 device_background_texture->id());
854 GetFramebufferTexture(
855 lock.texture_id(), device_background_texture->format(), bounding_rect);
857 return device_background_texture.Pass();
860 skia::RefPtr<SkImage> GLRenderer::ApplyBackgroundFilters(
861 DrawingFrame* frame,
862 const RenderPassDrawQuad* quad,
863 ScopedResource* background_texture) {
864 DCHECK(ShouldApplyBackgroundFilters(frame, quad));
865 skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
866 quad->background_filters, background_texture->size());
868 skia::RefPtr<SkImage> background_with_filters = ApplyImageFilter(
869 ScopedUseGrContext::Create(this, frame), resource_provider_, quad->rect,
870 quad->filters_scale, filter.get(), background_texture);
871 return background_with_filters;
874 void GLRenderer::DrawRenderPassQuad(DrawingFrame* frame,
875 const RenderPassDrawQuad* quad) {
876 ScopedResource* contents_texture =
877 render_pass_textures_.get(quad->render_pass_id);
878 if (!contents_texture || !contents_texture->id())
879 return;
881 gfx::Transform quad_rect_matrix;
882 QuadRectTransform(&quad_rect_matrix, quad->quadTransform(), quad->rect);
883 gfx::Transform contents_device_transform =
884 frame->window_matrix * frame->projection_matrix * quad_rect_matrix;
885 contents_device_transform.FlattenTo2d();
887 // Can only draw surface if device matrix is invertible.
888 if (!contents_device_transform.IsInvertible())
889 return;
891 gfx::QuadF surface_quad = SharedGeometryQuad();
892 float edge[24];
893 bool use_aa = settings_->allow_antialiasing &&
894 ShouldAntialiasQuad(contents_device_transform, quad,
895 settings_->force_antialiasing);
897 if (use_aa)
898 SetupQuadForAntialiasing(contents_device_transform, quad,
899 &surface_quad, edge);
901 SkXfermode::Mode blend_mode = quad->shared_quad_state->blend_mode;
902 bool use_shaders_for_blending =
903 !CanApplyBlendModeUsingBlendFunc(blend_mode) ||
904 ShouldApplyBackgroundFilters(frame, quad) ||
905 settings_->force_blending_with_shaders;
907 scoped_ptr<ScopedResource> background_texture;
908 skia::RefPtr<SkImage> background_image;
909 gfx::Rect background_rect;
910 if (use_shaders_for_blending) {
911 // Compute a bounding box around the pixels that will be visible through
912 // the quad.
913 background_rect = GetBackdropBoundingBoxForRenderPassQuad(
914 frame, quad, contents_device_transform, use_aa);
916 if (!background_rect.IsEmpty()) {
917 // The pixels from the filtered background should completely replace the
918 // current pixel values.
919 if (blend_enabled())
920 SetBlendEnabled(false);
922 // Read the pixels in the bounding box into a buffer R.
923 // This function allocates a texture, which should contribute to the
924 // amount of memory used by render surfaces:
925 // LayerTreeHost::CalculateMemoryForRenderSurfaces.
926 background_texture = GetBackdropTexture(background_rect);
928 if (ShouldApplyBackgroundFilters(frame, quad) && background_texture) {
929 // Apply the background filters to R, so that it is applied in the
930 // pixels' coordinate space.
931 background_image =
932 ApplyBackgroundFilters(frame, quad, background_texture.get());
936 if (!background_texture) {
937 // Something went wrong with reading the backdrop.
938 DCHECK(!background_image);
939 use_shaders_for_blending = false;
940 } else if (background_image) {
941 background_texture.reset();
942 } else if (CanApplyBlendModeUsingBlendFunc(blend_mode) &&
943 ShouldApplyBackgroundFilters(frame, quad)) {
944 // Something went wrong with applying background filters to the backdrop.
945 use_shaders_for_blending = false;
946 background_texture.reset();
950 SetBlendEnabled(
951 !use_shaders_for_blending &&
952 (quad->ShouldDrawWithBlending() || !IsDefaultBlendMode(blend_mode)));
954 // TODO(senorblanco): Cache this value so that we don't have to do it for both
955 // the surface and its replica. Apply filters to the contents texture.
956 skia::RefPtr<SkImage> filter_image;
957 SkScalar color_matrix[20];
958 bool use_color_matrix = false;
959 if (!quad->filters.IsEmpty()) {
960 skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
961 quad->filters, contents_texture->size());
962 if (filter) {
963 skia::RefPtr<SkColorFilter> cf;
966 SkColorFilter* colorfilter_rawptr = NULL;
967 filter->asColorFilter(&colorfilter_rawptr);
968 cf = skia::AdoptRef(colorfilter_rawptr);
971 if (cf && cf->asColorMatrix(color_matrix) && !filter->getInput(0)) {
972 // We have a single color matrix as a filter; apply it locally
973 // in the compositor.
974 use_color_matrix = true;
975 } else {
976 filter_image = ApplyImageFilter(
977 ScopedUseGrContext::Create(this, frame), resource_provider_,
978 quad->rect, quad->filters_scale, filter.get(), contents_texture);
983 scoped_ptr<ResourceProvider::ScopedSamplerGL> mask_resource_lock;
984 unsigned mask_texture_id = 0;
985 SamplerType mask_sampler = SAMPLER_TYPE_NA;
986 if (quad->mask_resource_id) {
987 mask_resource_lock.reset(new ResourceProvider::ScopedSamplerGL(
988 resource_provider_, quad->mask_resource_id, GL_TEXTURE1, GL_LINEAR));
989 mask_texture_id = mask_resource_lock->texture_id();
990 mask_sampler = SamplerTypeFromTextureTarget(mask_resource_lock->target());
993 scoped_ptr<ResourceProvider::ScopedSamplerGL> contents_resource_lock;
994 if (filter_image) {
995 GrTexture* texture = filter_image->getTexture();
996 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
997 gl_->BindTexture(GL_TEXTURE_2D, texture->getTextureHandle());
998 } else {
999 contents_resource_lock =
1000 make_scoped_ptr(new ResourceProvider::ScopedSamplerGL(
1001 resource_provider_, contents_texture->id(), GL_LINEAR));
1002 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
1003 contents_resource_lock->target());
1006 if (!use_shaders_for_blending) {
1007 if (!use_blend_equation_advanced_coherent_ && use_blend_equation_advanced_)
1008 GLC(gl_, gl_->BlendBarrierKHR());
1010 ApplyBlendModeUsingBlendFunc(blend_mode);
1013 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1014 gl_,
1015 &highp_threshold_cache_,
1016 highp_threshold_min_,
1017 quad->shared_quad_state->visible_content_rect.bottom_right());
1019 int shader_quad_location = -1;
1020 int shader_edge_location = -1;
1021 int shader_viewport_location = -1;
1022 int shader_mask_sampler_location = -1;
1023 int shader_mask_tex_coord_scale_location = -1;
1024 int shader_mask_tex_coord_offset_location = -1;
1025 int shader_matrix_location = -1;
1026 int shader_alpha_location = -1;
1027 int shader_color_matrix_location = -1;
1028 int shader_color_offset_location = -1;
1029 int shader_tex_transform_location = -1;
1030 int shader_backdrop_location = -1;
1031 int shader_backdrop_rect_location = -1;
1033 DCHECK_EQ(background_texture || background_image, use_shaders_for_blending);
1034 BlendMode shader_blend_mode = use_shaders_for_blending
1035 ? BlendModeFromSkXfermode(blend_mode)
1036 : BLEND_MODE_NONE;
1038 if (use_aa && mask_texture_id && !use_color_matrix) {
1039 const RenderPassMaskProgramAA* program = GetRenderPassMaskProgramAA(
1040 tex_coord_precision, mask_sampler, shader_blend_mode);
1041 SetUseProgram(program->program());
1042 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1044 shader_quad_location = program->vertex_shader().quad_location();
1045 shader_edge_location = program->vertex_shader().edge_location();
1046 shader_viewport_location = program->vertex_shader().viewport_location();
1047 shader_mask_sampler_location =
1048 program->fragment_shader().mask_sampler_location();
1049 shader_mask_tex_coord_scale_location =
1050 program->fragment_shader().mask_tex_coord_scale_location();
1051 shader_mask_tex_coord_offset_location =
1052 program->fragment_shader().mask_tex_coord_offset_location();
1053 shader_matrix_location = program->vertex_shader().matrix_location();
1054 shader_alpha_location = program->fragment_shader().alpha_location();
1055 shader_tex_transform_location =
1056 program->vertex_shader().tex_transform_location();
1057 shader_backdrop_location = program->fragment_shader().backdrop_location();
1058 shader_backdrop_rect_location =
1059 program->fragment_shader().backdrop_rect_location();
1060 } else if (!use_aa && mask_texture_id && !use_color_matrix) {
1061 const RenderPassMaskProgram* program = GetRenderPassMaskProgram(
1062 tex_coord_precision, mask_sampler, shader_blend_mode);
1063 SetUseProgram(program->program());
1064 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1066 shader_mask_sampler_location =
1067 program->fragment_shader().mask_sampler_location();
1068 shader_mask_tex_coord_scale_location =
1069 program->fragment_shader().mask_tex_coord_scale_location();
1070 shader_mask_tex_coord_offset_location =
1071 program->fragment_shader().mask_tex_coord_offset_location();
1072 shader_matrix_location = program->vertex_shader().matrix_location();
1073 shader_alpha_location = program->fragment_shader().alpha_location();
1074 shader_tex_transform_location =
1075 program->vertex_shader().tex_transform_location();
1076 shader_backdrop_location = program->fragment_shader().backdrop_location();
1077 shader_backdrop_rect_location =
1078 program->fragment_shader().backdrop_rect_location();
1079 } else if (use_aa && !mask_texture_id && !use_color_matrix) {
1080 const RenderPassProgramAA* program =
1081 GetRenderPassProgramAA(tex_coord_precision, shader_blend_mode);
1082 SetUseProgram(program->program());
1083 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1085 shader_quad_location = program->vertex_shader().quad_location();
1086 shader_edge_location = program->vertex_shader().edge_location();
1087 shader_viewport_location = program->vertex_shader().viewport_location();
1088 shader_matrix_location = program->vertex_shader().matrix_location();
1089 shader_alpha_location = program->fragment_shader().alpha_location();
1090 shader_tex_transform_location =
1091 program->vertex_shader().tex_transform_location();
1092 shader_backdrop_location = program->fragment_shader().backdrop_location();
1093 shader_backdrop_rect_location =
1094 program->fragment_shader().backdrop_rect_location();
1095 } else if (use_aa && mask_texture_id && use_color_matrix) {
1096 const RenderPassMaskColorMatrixProgramAA* program =
1097 GetRenderPassMaskColorMatrixProgramAA(
1098 tex_coord_precision, mask_sampler, shader_blend_mode);
1099 SetUseProgram(program->program());
1100 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1102 shader_matrix_location = program->vertex_shader().matrix_location();
1103 shader_quad_location = program->vertex_shader().quad_location();
1104 shader_tex_transform_location =
1105 program->vertex_shader().tex_transform_location();
1106 shader_edge_location = program->vertex_shader().edge_location();
1107 shader_viewport_location = program->vertex_shader().viewport_location();
1108 shader_alpha_location = program->fragment_shader().alpha_location();
1109 shader_mask_sampler_location =
1110 program->fragment_shader().mask_sampler_location();
1111 shader_mask_tex_coord_scale_location =
1112 program->fragment_shader().mask_tex_coord_scale_location();
1113 shader_mask_tex_coord_offset_location =
1114 program->fragment_shader().mask_tex_coord_offset_location();
1115 shader_color_matrix_location =
1116 program->fragment_shader().color_matrix_location();
1117 shader_color_offset_location =
1118 program->fragment_shader().color_offset_location();
1119 shader_backdrop_location = program->fragment_shader().backdrop_location();
1120 shader_backdrop_rect_location =
1121 program->fragment_shader().backdrop_rect_location();
1122 } else if (use_aa && !mask_texture_id && use_color_matrix) {
1123 const RenderPassColorMatrixProgramAA* program =
1124 GetRenderPassColorMatrixProgramAA(tex_coord_precision,
1125 shader_blend_mode);
1126 SetUseProgram(program->program());
1127 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1129 shader_matrix_location = program->vertex_shader().matrix_location();
1130 shader_quad_location = program->vertex_shader().quad_location();
1131 shader_tex_transform_location =
1132 program->vertex_shader().tex_transform_location();
1133 shader_edge_location = program->vertex_shader().edge_location();
1134 shader_viewport_location = program->vertex_shader().viewport_location();
1135 shader_alpha_location = program->fragment_shader().alpha_location();
1136 shader_color_matrix_location =
1137 program->fragment_shader().color_matrix_location();
1138 shader_color_offset_location =
1139 program->fragment_shader().color_offset_location();
1140 shader_backdrop_location = program->fragment_shader().backdrop_location();
1141 shader_backdrop_rect_location =
1142 program->fragment_shader().backdrop_rect_location();
1143 } else if (!use_aa && mask_texture_id && use_color_matrix) {
1144 const RenderPassMaskColorMatrixProgram* program =
1145 GetRenderPassMaskColorMatrixProgram(
1146 tex_coord_precision, mask_sampler, shader_blend_mode);
1147 SetUseProgram(program->program());
1148 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1150 shader_matrix_location = program->vertex_shader().matrix_location();
1151 shader_tex_transform_location =
1152 program->vertex_shader().tex_transform_location();
1153 shader_mask_sampler_location =
1154 program->fragment_shader().mask_sampler_location();
1155 shader_mask_tex_coord_scale_location =
1156 program->fragment_shader().mask_tex_coord_scale_location();
1157 shader_mask_tex_coord_offset_location =
1158 program->fragment_shader().mask_tex_coord_offset_location();
1159 shader_alpha_location = program->fragment_shader().alpha_location();
1160 shader_color_matrix_location =
1161 program->fragment_shader().color_matrix_location();
1162 shader_color_offset_location =
1163 program->fragment_shader().color_offset_location();
1164 shader_backdrop_location = program->fragment_shader().backdrop_location();
1165 shader_backdrop_rect_location =
1166 program->fragment_shader().backdrop_rect_location();
1167 } else if (!use_aa && !mask_texture_id && use_color_matrix) {
1168 const RenderPassColorMatrixProgram* program =
1169 GetRenderPassColorMatrixProgram(tex_coord_precision, shader_blend_mode);
1170 SetUseProgram(program->program());
1171 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1173 shader_matrix_location = program->vertex_shader().matrix_location();
1174 shader_tex_transform_location =
1175 program->vertex_shader().tex_transform_location();
1176 shader_alpha_location = program->fragment_shader().alpha_location();
1177 shader_color_matrix_location =
1178 program->fragment_shader().color_matrix_location();
1179 shader_color_offset_location =
1180 program->fragment_shader().color_offset_location();
1181 shader_backdrop_location = program->fragment_shader().backdrop_location();
1182 shader_backdrop_rect_location =
1183 program->fragment_shader().backdrop_rect_location();
1184 } else {
1185 const RenderPassProgram* program =
1186 GetRenderPassProgram(tex_coord_precision, shader_blend_mode);
1187 SetUseProgram(program->program());
1188 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1190 shader_matrix_location = program->vertex_shader().matrix_location();
1191 shader_alpha_location = program->fragment_shader().alpha_location();
1192 shader_tex_transform_location =
1193 program->vertex_shader().tex_transform_location();
1194 shader_backdrop_location = program->fragment_shader().backdrop_location();
1195 shader_backdrop_rect_location =
1196 program->fragment_shader().backdrop_rect_location();
1198 float tex_scale_x =
1199 quad->rect.width() / static_cast<float>(contents_texture->size().width());
1200 float tex_scale_y = quad->rect.height() /
1201 static_cast<float>(contents_texture->size().height());
1202 DCHECK_LE(tex_scale_x, 1.0f);
1203 DCHECK_LE(tex_scale_y, 1.0f);
1205 DCHECK(shader_tex_transform_location != -1 || IsContextLost());
1206 // Flip the content vertically in the shader, as the RenderPass input
1207 // texture is already oriented the same way as the framebuffer, but the
1208 // projection transform does a flip.
1209 GLC(gl_,
1210 gl_->Uniform4f(shader_tex_transform_location,
1211 0.0f,
1212 tex_scale_y,
1213 tex_scale_x,
1214 -tex_scale_y));
1216 GLint last_texture_unit = 0;
1217 if (shader_mask_sampler_location != -1) {
1218 DCHECK_NE(shader_mask_tex_coord_scale_location, 1);
1219 DCHECK_NE(shader_mask_tex_coord_offset_location, 1);
1220 GLC(gl_, gl_->Uniform1i(shader_mask_sampler_location, 1));
1222 gfx::RectF mask_uv_rect = quad->MaskUVRect();
1223 if (mask_sampler != SAMPLER_TYPE_2D) {
1224 mask_uv_rect.Scale(quad->mask_texture_size.width(),
1225 quad->mask_texture_size.height());
1228 // Mask textures are oriented vertically flipped relative to the framebuffer
1229 // and the RenderPass contents texture, so we flip the tex coords from the
1230 // RenderPass texture to find the mask texture coords.
1231 GLC(gl_,
1232 gl_->Uniform2f(shader_mask_tex_coord_offset_location,
1233 mask_uv_rect.x(),
1234 mask_uv_rect.bottom()));
1235 GLC(gl_,
1236 gl_->Uniform2f(shader_mask_tex_coord_scale_location,
1237 mask_uv_rect.width() / tex_scale_x,
1238 -mask_uv_rect.height() / tex_scale_y));
1240 last_texture_unit = 1;
1243 if (shader_edge_location != -1)
1244 GLC(gl_, gl_->Uniform3fv(shader_edge_location, 8, edge));
1246 if (shader_viewport_location != -1) {
1247 float viewport[4] = {static_cast<float>(viewport_.x()),
1248 static_cast<float>(viewport_.y()),
1249 static_cast<float>(viewport_.width()),
1250 static_cast<float>(viewport_.height()), };
1251 GLC(gl_, gl_->Uniform4fv(shader_viewport_location, 1, viewport));
1254 if (shader_color_matrix_location != -1) {
1255 float matrix[16];
1256 for (int i = 0; i < 4; ++i) {
1257 for (int j = 0; j < 4; ++j)
1258 matrix[i * 4 + j] = SkScalarToFloat(color_matrix[j * 5 + i]);
1260 GLC(gl_,
1261 gl_->UniformMatrix4fv(shader_color_matrix_location, 1, false, matrix));
1263 static const float kScale = 1.0f / 255.0f;
1264 if (shader_color_offset_location != -1) {
1265 float offset[4];
1266 for (int i = 0; i < 4; ++i)
1267 offset[i] = SkScalarToFloat(color_matrix[i * 5 + 4]) * kScale;
1269 GLC(gl_, gl_->Uniform4fv(shader_color_offset_location, 1, offset));
1272 scoped_ptr<ResourceProvider::ScopedSamplerGL> shader_background_sampler_lock;
1273 if (shader_backdrop_location != -1) {
1274 DCHECK(background_texture || background_image);
1275 DCHECK_NE(shader_backdrop_location, 0);
1276 DCHECK_NE(shader_backdrop_rect_location, 0);
1278 GLC(gl_, gl_->Uniform1i(shader_backdrop_location, ++last_texture_unit));
1280 GLC(gl_,
1281 gl_->Uniform4f(shader_backdrop_rect_location,
1282 background_rect.x(),
1283 background_rect.y(),
1284 background_rect.width(),
1285 background_rect.height()));
1287 if (background_image) {
1288 GrTexture* texture = background_image->getTexture();
1289 GLC(gl_, gl_->ActiveTexture(GL_TEXTURE0 + last_texture_unit));
1290 gl_->BindTexture(GL_TEXTURE_2D, texture->getTextureHandle());
1291 GLC(gl_, gl_->ActiveTexture(GL_TEXTURE0));
1292 } else {
1293 shader_background_sampler_lock = make_scoped_ptr(
1294 new ResourceProvider::ScopedSamplerGL(resource_provider_,
1295 background_texture->id(),
1296 GL_TEXTURE0 + last_texture_unit,
1297 GL_LINEAR));
1298 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
1299 shader_background_sampler_lock->target());
1303 SetShaderOpacity(quad->opacity(), shader_alpha_location);
1304 SetShaderQuadF(surface_quad, shader_quad_location);
1305 DrawQuadGeometry(
1306 frame, quad->quadTransform(), quad->rect, shader_matrix_location);
1308 // Flush the compositor context before the filter bitmap goes out of
1309 // scope, so the draw gets processed before the filter texture gets deleted.
1310 if (filter_image)
1311 GLC(gl_, gl_->Flush());
1313 if (!use_shaders_for_blending)
1314 RestoreBlendFuncToDefault(blend_mode);
1317 struct SolidColorProgramUniforms {
1318 unsigned program;
1319 unsigned matrix_location;
1320 unsigned viewport_location;
1321 unsigned quad_location;
1322 unsigned edge_location;
1323 unsigned color_location;
1326 template <class T>
1327 static void SolidColorUniformLocation(T program,
1328 SolidColorProgramUniforms* uniforms) {
1329 uniforms->program = program->program();
1330 uniforms->matrix_location = program->vertex_shader().matrix_location();
1331 uniforms->viewport_location = program->vertex_shader().viewport_location();
1332 uniforms->quad_location = program->vertex_shader().quad_location();
1333 uniforms->edge_location = program->vertex_shader().edge_location();
1334 uniforms->color_location = program->fragment_shader().color_location();
1337 static gfx::QuadF GetDeviceQuadWithAntialiasingOnExteriorEdges(
1338 const LayerQuad& device_layer_edges,
1339 const gfx::Transform& device_transform,
1340 const DrawQuad* quad) {
1341 gfx::Rect tile_rect = quad->visible_rect;
1342 gfx::PointF bottom_right = tile_rect.bottom_right();
1343 gfx::PointF bottom_left = tile_rect.bottom_left();
1344 gfx::PointF top_left = tile_rect.origin();
1345 gfx::PointF top_right = tile_rect.top_right();
1346 bool clipped = false;
1348 // Map points to device space. We ignore |clipped|, since the result of
1349 // |MapPoint()| still produces a valid point to draw the quad with. When
1350 // clipped, the point will be outside of the viewport. See crbug.com/416367.
1351 bottom_right = MathUtil::MapPoint(device_transform, bottom_right, &clipped);
1352 bottom_left = MathUtil::MapPoint(device_transform, bottom_left, &clipped);
1353 top_left = MathUtil::MapPoint(device_transform, top_left, &clipped);
1354 top_right = MathUtil::MapPoint(device_transform, top_right, &clipped);
1356 LayerQuad::Edge bottom_edge(bottom_right, bottom_left);
1357 LayerQuad::Edge left_edge(bottom_left, top_left);
1358 LayerQuad::Edge top_edge(top_left, top_right);
1359 LayerQuad::Edge right_edge(top_right, bottom_right);
1361 // Only apply anti-aliasing to edges not clipped by culling or scissoring.
1362 if (quad->IsTopEdge() && tile_rect.y() == quad->rect.y())
1363 top_edge = device_layer_edges.top();
1364 if (quad->IsLeftEdge() && tile_rect.x() == quad->rect.x())
1365 left_edge = device_layer_edges.left();
1366 if (quad->IsRightEdge() && tile_rect.right() == quad->rect.right())
1367 right_edge = device_layer_edges.right();
1368 if (quad->IsBottomEdge() && tile_rect.bottom() == quad->rect.bottom())
1369 bottom_edge = device_layer_edges.bottom();
1371 float sign = gfx::QuadF(tile_rect).IsCounterClockwise() ? -1 : 1;
1372 bottom_edge.scale(sign);
1373 left_edge.scale(sign);
1374 top_edge.scale(sign);
1375 right_edge.scale(sign);
1377 // Create device space quad.
1378 return LayerQuad(left_edge, top_edge, right_edge, bottom_edge).ToQuadF();
1381 // static
1382 bool GLRenderer::ShouldAntialiasQuad(const gfx::Transform& device_transform,
1383 const DrawQuad* quad,
1384 bool force_antialiasing) {
1385 bool is_render_pass_quad = (quad->material == DrawQuad::RENDER_PASS);
1386 // For render pass quads, |device_transform| already contains quad's rect.
1387 // TODO(rosca@adobe.com): remove branching on is_render_pass_quad
1388 // crbug.com/429702
1389 if (!is_render_pass_quad && !quad->IsEdge())
1390 return false;
1391 gfx::RectF content_rect =
1392 is_render_pass_quad ? QuadVertexRect() : quad->visibleContentRect();
1394 bool clipped = false;
1395 gfx::QuadF device_layer_quad =
1396 MathUtil::MapQuad(device_transform, gfx::QuadF(content_rect), &clipped);
1398 if (device_layer_quad.BoundingBox().IsEmpty())
1399 return false;
1401 bool is_axis_aligned_in_target = device_layer_quad.IsRectilinear();
1402 bool is_nearest_rect_within_epsilon =
1403 is_axis_aligned_in_target &&
1404 gfx::IsNearestRectWithinDistance(device_layer_quad.BoundingBox(),
1405 kAntiAliasingEpsilon);
1406 // AAing clipped quads is not supported by the code yet.
1407 bool use_aa = !clipped && !is_nearest_rect_within_epsilon;
1408 return use_aa || force_antialiasing;
1411 // static
1412 void GLRenderer::SetupQuadForAntialiasing(
1413 const gfx::Transform& device_transform,
1414 const DrawQuad* quad,
1415 gfx::QuadF* local_quad,
1416 float edge[24]) {
1417 bool is_render_pass_quad = (quad->material == DrawQuad::RENDER_PASS);
1418 gfx::RectF content_rect =
1419 is_render_pass_quad ? QuadVertexRect() : quad->visibleContentRect();
1421 bool clipped = false;
1422 gfx::QuadF device_layer_quad =
1423 MathUtil::MapQuad(device_transform, gfx::QuadF(content_rect), &clipped);
1425 LayerQuad device_layer_bounds(gfx::QuadF(device_layer_quad.BoundingBox()));
1426 device_layer_bounds.InflateAntiAliasingDistance();
1428 LayerQuad device_layer_edges(device_layer_quad);
1429 device_layer_edges.InflateAntiAliasingDistance();
1431 device_layer_edges.ToFloatArray(edge);
1432 device_layer_bounds.ToFloatArray(&edge[12]);
1434 bool use_aa_on_all_four_edges =
1435 is_render_pass_quad ||
1436 (quad->IsTopEdge() && quad->IsLeftEdge() && quad->IsBottomEdge() &&
1437 quad->IsRightEdge() && quad->visible_rect == quad->rect);
1439 gfx::QuadF device_quad =
1440 use_aa_on_all_four_edges
1441 ? device_layer_edges.ToQuadF()
1442 : GetDeviceQuadWithAntialiasingOnExteriorEdges(
1443 device_layer_edges, device_transform, quad);
1445 // Map device space quad to local space. device_transform has no 3d
1446 // component since it was flattened, so we don't need to project. We should
1447 // have already checked that the transform was uninvertible above.
1448 gfx::Transform inverse_device_transform(gfx::Transform::kSkipInitialization);
1449 bool did_invert = device_transform.GetInverse(&inverse_device_transform);
1450 DCHECK(did_invert);
1451 *local_quad =
1452 MathUtil::MapQuad(inverse_device_transform, device_quad, &clipped);
1453 // We should not DCHECK(!clipped) here, because anti-aliasing inflation may
1454 // cause device_quad to become clipped. To our knowledge this scenario does
1455 // not need to be handled differently than the unclipped case.
1458 void GLRenderer::DrawSolidColorQuad(const DrawingFrame* frame,
1459 const SolidColorDrawQuad* quad) {
1460 gfx::Rect tile_rect = quad->visible_rect;
1462 SkColor color = quad->color;
1463 float opacity = quad->opacity();
1464 float alpha = (SkColorGetA(color) * (1.0f / 255.0f)) * opacity;
1466 // Early out if alpha is small enough that quad doesn't contribute to output.
1467 if (alpha < std::numeric_limits<float>::epsilon() &&
1468 quad->ShouldDrawWithBlending())
1469 return;
1471 gfx::Transform device_transform =
1472 frame->window_matrix * frame->projection_matrix * quad->quadTransform();
1473 device_transform.FlattenTo2d();
1474 if (!device_transform.IsInvertible())
1475 return;
1477 bool force_aa = false;
1478 gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1479 float edge[24];
1480 bool use_aa = settings_->allow_antialiasing &&
1481 !quad->force_anti_aliasing_off &&
1482 ShouldAntialiasQuad(device_transform, quad, force_aa);
1484 SolidColorProgramUniforms uniforms;
1485 if (use_aa) {
1486 SetupQuadForAntialiasing(device_transform, quad, &local_quad, edge);
1487 SolidColorUniformLocation(GetSolidColorProgramAA(), &uniforms);
1488 } else {
1489 SolidColorUniformLocation(GetSolidColorProgram(), &uniforms);
1491 SetUseProgram(uniforms.program);
1493 GLC(gl_,
1494 gl_->Uniform4f(uniforms.color_location,
1495 (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
1496 (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
1497 (SkColorGetB(color) * (1.0f / 255.0f)) * alpha,
1498 alpha));
1499 if (use_aa) {
1500 float viewport[4] = {static_cast<float>(viewport_.x()),
1501 static_cast<float>(viewport_.y()),
1502 static_cast<float>(viewport_.width()),
1503 static_cast<float>(viewport_.height()), };
1504 GLC(gl_, gl_->Uniform4fv(uniforms.viewport_location, 1, viewport));
1505 GLC(gl_, gl_->Uniform3fv(uniforms.edge_location, 8, edge));
1508 // Enable blending when the quad properties require it or if we decided
1509 // to use antialiasing.
1510 SetBlendEnabled(quad->ShouldDrawWithBlending() || use_aa);
1512 // Normalize to tile_rect.
1513 local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1515 SetShaderQuadF(local_quad, uniforms.quad_location);
1517 // The transform and vertex data are used to figure out the extents that the
1518 // un-antialiased quad should have and which vertex this is and the float
1519 // quad passed in via uniform is the actual geometry that gets used to draw
1520 // it. This is why this centered rect is used and not the original quad_rect.
1521 gfx::RectF centered_rect(
1522 gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1523 tile_rect.size());
1524 DrawQuadGeometry(
1525 frame, quad->quadTransform(), centered_rect, uniforms.matrix_location);
1528 struct TileProgramUniforms {
1529 unsigned program;
1530 unsigned matrix_location;
1531 unsigned viewport_location;
1532 unsigned quad_location;
1533 unsigned edge_location;
1534 unsigned vertex_tex_transform_location;
1535 unsigned sampler_location;
1536 unsigned fragment_tex_transform_location;
1537 unsigned alpha_location;
1540 template <class T>
1541 static void TileUniformLocation(T program, TileProgramUniforms* uniforms) {
1542 uniforms->program = program->program();
1543 uniforms->matrix_location = program->vertex_shader().matrix_location();
1544 uniforms->viewport_location = program->vertex_shader().viewport_location();
1545 uniforms->quad_location = program->vertex_shader().quad_location();
1546 uniforms->edge_location = program->vertex_shader().edge_location();
1547 uniforms->vertex_tex_transform_location =
1548 program->vertex_shader().vertex_tex_transform_location();
1550 uniforms->sampler_location = program->fragment_shader().sampler_location();
1551 uniforms->alpha_location = program->fragment_shader().alpha_location();
1552 uniforms->fragment_tex_transform_location =
1553 program->fragment_shader().fragment_tex_transform_location();
1556 void GLRenderer::DrawTileQuad(const DrawingFrame* frame,
1557 const TileDrawQuad* quad) {
1558 DrawContentQuad(frame, quad, quad->resource_id);
1561 void GLRenderer::DrawContentQuad(const DrawingFrame* frame,
1562 const ContentDrawQuadBase* quad,
1563 ResourceProvider::ResourceId resource_id) {
1564 gfx::Transform device_transform =
1565 frame->window_matrix * frame->projection_matrix * quad->quadTransform();
1566 device_transform.FlattenTo2d();
1568 bool use_aa = settings_->allow_antialiasing &&
1569 ShouldAntialiasQuad(device_transform, quad, false);
1571 // TODO(timav): simplify coordinate transformations in DrawContentQuadAA
1572 // similar to the way DrawContentQuadNoAA works and then consider
1573 // combining DrawContentQuadAA and DrawContentQuadNoAA into one method.
1574 if (use_aa)
1575 DrawContentQuadAA(frame, quad, resource_id, device_transform);
1576 else
1577 DrawContentQuadNoAA(frame, quad, resource_id);
1580 void GLRenderer::DrawContentQuadAA(const DrawingFrame* frame,
1581 const ContentDrawQuadBase* quad,
1582 ResourceProvider::ResourceId resource_id,
1583 const gfx::Transform& device_transform) {
1584 if (!device_transform.IsInvertible())
1585 return;
1587 gfx::Rect tile_rect = quad->visible_rect;
1589 gfx::RectF tex_coord_rect = MathUtil::ScaleRectProportional(
1590 quad->tex_coord_rect, quad->rect, tile_rect);
1591 float tex_to_geom_scale_x = quad->rect.width() / quad->tex_coord_rect.width();
1592 float tex_to_geom_scale_y =
1593 quad->rect.height() / quad->tex_coord_rect.height();
1595 gfx::RectF clamp_geom_rect(tile_rect);
1596 gfx::RectF clamp_tex_rect(tex_coord_rect);
1597 // Clamp texture coordinates to avoid sampling outside the layer
1598 // by deflating the tile region half a texel or half a texel
1599 // minus epsilon for one pixel layers. The resulting clamp region
1600 // is mapped to the unit square by the vertex shader and mapped
1601 // back to normalized texture coordinates by the fragment shader
1602 // after being clamped to 0-1 range.
1603 float tex_clamp_x =
1604 std::min(0.5f, 0.5f * clamp_tex_rect.width() - kAntiAliasingEpsilon);
1605 float tex_clamp_y =
1606 std::min(0.5f, 0.5f * clamp_tex_rect.height() - kAntiAliasingEpsilon);
1607 float geom_clamp_x =
1608 std::min(tex_clamp_x * tex_to_geom_scale_x,
1609 0.5f * clamp_geom_rect.width() - kAntiAliasingEpsilon);
1610 float geom_clamp_y =
1611 std::min(tex_clamp_y * tex_to_geom_scale_y,
1612 0.5f * clamp_geom_rect.height() - kAntiAliasingEpsilon);
1613 clamp_geom_rect.Inset(geom_clamp_x, geom_clamp_y, geom_clamp_x, geom_clamp_y);
1614 clamp_tex_rect.Inset(tex_clamp_x, tex_clamp_y, tex_clamp_x, tex_clamp_y);
1616 // Map clamping rectangle to unit square.
1617 float vertex_tex_translate_x = -clamp_geom_rect.x() / clamp_geom_rect.width();
1618 float vertex_tex_translate_y =
1619 -clamp_geom_rect.y() / clamp_geom_rect.height();
1620 float vertex_tex_scale_x = tile_rect.width() / clamp_geom_rect.width();
1621 float vertex_tex_scale_y = tile_rect.height() / clamp_geom_rect.height();
1623 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1624 gl_, &highp_threshold_cache_, highp_threshold_min_, quad->texture_size);
1626 gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1627 float edge[24];
1628 SetupQuadForAntialiasing(device_transform, quad, &local_quad, edge);
1630 ResourceProvider::ScopedSamplerGL quad_resource_lock(
1631 resource_provider_, resource_id,
1632 quad->nearest_neighbor ? GL_NEAREST : GL_LINEAR);
1633 SamplerType sampler =
1634 SamplerTypeFromTextureTarget(quad_resource_lock.target());
1636 float fragment_tex_translate_x = clamp_tex_rect.x();
1637 float fragment_tex_translate_y = clamp_tex_rect.y();
1638 float fragment_tex_scale_x = clamp_tex_rect.width();
1639 float fragment_tex_scale_y = clamp_tex_rect.height();
1641 // Map to normalized texture coordinates.
1642 if (sampler != SAMPLER_TYPE_2D_RECT) {
1643 gfx::Size texture_size = quad->texture_size;
1644 DCHECK(!texture_size.IsEmpty());
1645 fragment_tex_translate_x /= texture_size.width();
1646 fragment_tex_translate_y /= texture_size.height();
1647 fragment_tex_scale_x /= texture_size.width();
1648 fragment_tex_scale_y /= texture_size.height();
1651 TileProgramUniforms uniforms;
1652 if (quad->swizzle_contents) {
1653 TileUniformLocation(GetTileProgramSwizzleAA(tex_coord_precision, sampler),
1654 &uniforms);
1655 } else {
1656 TileUniformLocation(GetTileProgramAA(tex_coord_precision, sampler),
1657 &uniforms);
1660 SetUseProgram(uniforms.program);
1661 GLC(gl_, gl_->Uniform1i(uniforms.sampler_location, 0));
1663 float viewport[4] = {
1664 static_cast<float>(viewport_.x()),
1665 static_cast<float>(viewport_.y()),
1666 static_cast<float>(viewport_.width()),
1667 static_cast<float>(viewport_.height()),
1669 GLC(gl_, gl_->Uniform4fv(uniforms.viewport_location, 1, viewport));
1670 GLC(gl_, gl_->Uniform3fv(uniforms.edge_location, 8, edge));
1672 GLC(gl_,
1673 gl_->Uniform4f(uniforms.vertex_tex_transform_location,
1674 vertex_tex_translate_x,
1675 vertex_tex_translate_y,
1676 vertex_tex_scale_x,
1677 vertex_tex_scale_y));
1678 GLC(gl_,
1679 gl_->Uniform4f(uniforms.fragment_tex_transform_location,
1680 fragment_tex_translate_x,
1681 fragment_tex_translate_y,
1682 fragment_tex_scale_x,
1683 fragment_tex_scale_y));
1685 // Blending is required for antialiasing.
1686 SetBlendEnabled(true);
1688 // Normalize to tile_rect.
1689 local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1691 SetShaderOpacity(quad->opacity(), uniforms.alpha_location);
1692 SetShaderQuadF(local_quad, uniforms.quad_location);
1694 // The transform and vertex data are used to figure out the extents that the
1695 // un-antialiased quad should have and which vertex this is and the float
1696 // quad passed in via uniform is the actual geometry that gets used to draw
1697 // it. This is why this centered rect is used and not the original quad_rect.
1698 gfx::RectF centered_rect(
1699 gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1700 tile_rect.size());
1701 DrawQuadGeometry(
1702 frame, quad->quadTransform(), centered_rect, uniforms.matrix_location);
1705 void GLRenderer::DrawContentQuadNoAA(const DrawingFrame* frame,
1706 const ContentDrawQuadBase* quad,
1707 ResourceProvider::ResourceId resource_id) {
1708 gfx::RectF tex_coord_rect = MathUtil::ScaleRectProportional(
1709 quad->tex_coord_rect, quad->rect, quad->visible_rect);
1710 float tex_to_geom_scale_x = quad->rect.width() / quad->tex_coord_rect.width();
1711 float tex_to_geom_scale_y =
1712 quad->rect.height() / quad->tex_coord_rect.height();
1714 bool scaled = (tex_to_geom_scale_x != 1.f || tex_to_geom_scale_y != 1.f);
1715 GLenum filter =
1716 (scaled || !quad->quadTransform().IsIdentityOrIntegerTranslation()) &&
1717 !quad->nearest_neighbor
1718 ? GL_LINEAR
1719 : GL_NEAREST;
1721 ResourceProvider::ScopedSamplerGL quad_resource_lock(
1722 resource_provider_, resource_id, filter);
1723 SamplerType sampler =
1724 SamplerTypeFromTextureTarget(quad_resource_lock.target());
1726 float vertex_tex_translate_x = tex_coord_rect.x();
1727 float vertex_tex_translate_y = tex_coord_rect.y();
1728 float vertex_tex_scale_x = tex_coord_rect.width();
1729 float vertex_tex_scale_y = tex_coord_rect.height();
1731 // Map to normalized texture coordinates.
1732 if (sampler != SAMPLER_TYPE_2D_RECT) {
1733 gfx::Size texture_size = quad->texture_size;
1734 DCHECK(!texture_size.IsEmpty());
1735 vertex_tex_translate_x /= texture_size.width();
1736 vertex_tex_translate_y /= texture_size.height();
1737 vertex_tex_scale_x /= texture_size.width();
1738 vertex_tex_scale_y /= texture_size.height();
1741 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1742 gl_, &highp_threshold_cache_, highp_threshold_min_, quad->texture_size);
1744 TileProgramUniforms uniforms;
1745 if (quad->ShouldDrawWithBlending()) {
1746 if (quad->swizzle_contents) {
1747 TileUniformLocation(GetTileProgramSwizzle(tex_coord_precision, sampler),
1748 &uniforms);
1749 } else {
1750 TileUniformLocation(GetTileProgram(tex_coord_precision, sampler),
1751 &uniforms);
1753 } else {
1754 if (quad->swizzle_contents) {
1755 TileUniformLocation(
1756 GetTileProgramSwizzleOpaque(tex_coord_precision, sampler), &uniforms);
1757 } else {
1758 TileUniformLocation(GetTileProgramOpaque(tex_coord_precision, sampler),
1759 &uniforms);
1763 SetUseProgram(uniforms.program);
1764 GLC(gl_, gl_->Uniform1i(uniforms.sampler_location, 0));
1766 GLC(gl_,
1767 gl_->Uniform4f(uniforms.vertex_tex_transform_location,
1768 vertex_tex_translate_x,
1769 vertex_tex_translate_y,
1770 vertex_tex_scale_x,
1771 vertex_tex_scale_y));
1773 SetBlendEnabled(quad->ShouldDrawWithBlending());
1775 SetShaderOpacity(quad->opacity(), uniforms.alpha_location);
1777 // Pass quad coordinates to the uniform in the same order as GeometryBinding
1778 // does, then vertices will match the texture mapping in the vertex buffer.
1779 // The method SetShaderQuadF() changes the order of vertices and so it's
1780 // not used here.
1782 gfx::RectF tile_rect = quad->visible_rect;
1783 float gl_quad[8] = {
1784 tile_rect.x(),
1785 tile_rect.bottom(),
1786 tile_rect.x(),
1787 tile_rect.y(),
1788 tile_rect.right(),
1789 tile_rect.y(),
1790 tile_rect.right(),
1791 tile_rect.bottom(),
1793 GLC(gl_, gl_->Uniform2fv(uniforms.quad_location, 4, gl_quad));
1795 static float gl_matrix[16];
1796 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad->quadTransform());
1797 GLC(gl_,
1798 gl_->UniformMatrix4fv(uniforms.matrix_location, 1, false, &gl_matrix[0]));
1800 GLC(gl_, gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0));
1803 void GLRenderer::DrawYUVVideoQuad(const DrawingFrame* frame,
1804 const YUVVideoDrawQuad* quad) {
1805 SetBlendEnabled(quad->ShouldDrawWithBlending());
1807 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1808 gl_,
1809 &highp_threshold_cache_,
1810 highp_threshold_min_,
1811 quad->shared_quad_state->visible_content_rect.bottom_right());
1813 bool use_alpha_plane = quad->a_plane_resource_id != 0;
1815 ResourceProvider::ScopedSamplerGL y_plane_lock(
1816 resource_provider_, quad->y_plane_resource_id, GL_TEXTURE1, GL_LINEAR);
1817 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), y_plane_lock.target());
1818 ResourceProvider::ScopedSamplerGL u_plane_lock(
1819 resource_provider_, quad->u_plane_resource_id, GL_TEXTURE2, GL_LINEAR);
1820 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), u_plane_lock.target());
1821 ResourceProvider::ScopedSamplerGL v_plane_lock(
1822 resource_provider_, quad->v_plane_resource_id, GL_TEXTURE3, GL_LINEAR);
1823 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), v_plane_lock.target());
1824 scoped_ptr<ResourceProvider::ScopedSamplerGL> a_plane_lock;
1825 if (use_alpha_plane) {
1826 a_plane_lock.reset(new ResourceProvider::ScopedSamplerGL(
1827 resource_provider_, quad->a_plane_resource_id, GL_TEXTURE4, GL_LINEAR));
1828 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), a_plane_lock->target());
1831 int matrix_location = -1;
1832 int tex_scale_location = -1;
1833 int tex_offset_location = -1;
1834 int clamp_rect_location = -1;
1835 int y_texture_location = -1;
1836 int u_texture_location = -1;
1837 int v_texture_location = -1;
1838 int a_texture_location = -1;
1839 int yuv_matrix_location = -1;
1840 int yuv_adj_location = -1;
1841 int alpha_location = -1;
1842 if (use_alpha_plane) {
1843 const VideoYUVAProgram* program = GetVideoYUVAProgram(tex_coord_precision);
1844 DCHECK(program && (program->initialized() || IsContextLost()));
1845 SetUseProgram(program->program());
1846 matrix_location = program->vertex_shader().matrix_location();
1847 tex_scale_location = program->vertex_shader().tex_scale_location();
1848 tex_offset_location = program->vertex_shader().tex_offset_location();
1849 y_texture_location = program->fragment_shader().y_texture_location();
1850 u_texture_location = program->fragment_shader().u_texture_location();
1851 v_texture_location = program->fragment_shader().v_texture_location();
1852 a_texture_location = program->fragment_shader().a_texture_location();
1853 yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
1854 yuv_adj_location = program->fragment_shader().yuv_adj_location();
1855 clamp_rect_location = program->fragment_shader().clamp_rect_location();
1856 alpha_location = program->fragment_shader().alpha_location();
1857 } else {
1858 const VideoYUVProgram* program = GetVideoYUVProgram(tex_coord_precision);
1859 DCHECK(program && (program->initialized() || IsContextLost()));
1860 SetUseProgram(program->program());
1861 matrix_location = program->vertex_shader().matrix_location();
1862 tex_scale_location = program->vertex_shader().tex_scale_location();
1863 tex_offset_location = program->vertex_shader().tex_offset_location();
1864 y_texture_location = program->fragment_shader().y_texture_location();
1865 u_texture_location = program->fragment_shader().u_texture_location();
1866 v_texture_location = program->fragment_shader().v_texture_location();
1867 yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
1868 yuv_adj_location = program->fragment_shader().yuv_adj_location();
1869 clamp_rect_location = program->fragment_shader().clamp_rect_location();
1870 alpha_location = program->fragment_shader().alpha_location();
1873 GLC(gl_,
1874 gl_->Uniform2f(tex_scale_location,
1875 quad->tex_coord_rect.width(),
1876 quad->tex_coord_rect.height()));
1877 GLC(gl_,
1878 gl_->Uniform2f(tex_offset_location,
1879 quad->tex_coord_rect.x(),
1880 quad->tex_coord_rect.y()));
1881 // Clamping to half a texel inside the tex coord rect prevents bilinear
1882 // filtering from filtering outside the tex coord rect.
1883 gfx::RectF clamp_rect(quad->tex_coord_rect);
1884 // Special case: empty texture size implies no clamping.
1885 if (!quad->tex_size.IsEmpty()) {
1886 clamp_rect.Inset(0.5f / quad->tex_size.width(),
1887 0.5f / quad->tex_size.height());
1889 GLC(gl_, gl_->Uniform4f(clamp_rect_location, clamp_rect.x(), clamp_rect.y(),
1890 clamp_rect.right(), clamp_rect.bottom()));
1892 GLC(gl_, gl_->Uniform1i(y_texture_location, 1));
1893 GLC(gl_, gl_->Uniform1i(u_texture_location, 2));
1894 GLC(gl_, gl_->Uniform1i(v_texture_location, 3));
1895 if (use_alpha_plane)
1896 GLC(gl_, gl_->Uniform1i(a_texture_location, 4));
1898 // These values are magic numbers that are used in the transformation from YUV
1899 // to RGB color values. They are taken from the following webpage:
1900 // http://www.fourcc.org/fccyvrgb.php
1901 float yuv_to_rgb_rec601[9] = {
1902 1.164f, 1.164f, 1.164f, 0.0f, -.391f, 2.018f, 1.596f, -.813f, 0.0f,
1904 float yuv_to_rgb_jpeg[9] = {
1905 1.f, 1.f, 1.f, 0.0f, -.34414f, 1.772f, 1.402f, -.71414f, 0.0f,
1907 float yuv_to_rgb_rec709[9] = {
1908 1.164f, 1.164f, 1.164f, 0.0f, -0.213f, 2.112f, 1.793f, -0.533f, 0.0f,
1911 // These values map to 16, 128, and 128 respectively, and are computed
1912 // as a fraction over 256 (e.g. 16 / 256 = 0.0625).
1913 // They are used in the YUV to RGBA conversion formula:
1914 // Y - 16 : Gives 16 values of head and footroom for overshooting
1915 // U - 128 : Turns unsigned U into signed U [-128,127]
1916 // V - 128 : Turns unsigned V into signed V [-128,127]
1917 float yuv_adjust_constrained[3] = {
1918 -0.0625f, -0.5f, -0.5f,
1921 // Same as above, but without the head and footroom.
1922 float yuv_adjust_full[3] = {
1923 0.0f, -0.5f, -0.5f,
1926 float* yuv_to_rgb = NULL;
1927 float* yuv_adjust = NULL;
1929 switch (quad->color_space) {
1930 case YUVVideoDrawQuad::REC_601:
1931 yuv_to_rgb = yuv_to_rgb_rec601;
1932 yuv_adjust = yuv_adjust_constrained;
1933 break;
1934 case YUVVideoDrawQuad::REC_709:
1935 yuv_to_rgb = yuv_to_rgb_rec709;
1936 yuv_adjust = yuv_adjust_constrained;
1937 break;
1938 case YUVVideoDrawQuad::JPEG:
1939 yuv_to_rgb = yuv_to_rgb_jpeg;
1940 yuv_adjust = yuv_adjust_full;
1941 break;
1944 GLC(gl_, gl_->UniformMatrix3fv(yuv_matrix_location, 1, 0, yuv_to_rgb));
1945 GLC(gl_, gl_->Uniform3fv(yuv_adj_location, 1, yuv_adjust));
1947 SetShaderOpacity(quad->opacity(), alpha_location);
1948 DrawQuadGeometry(frame, quad->quadTransform(), quad->rect, matrix_location);
1951 void GLRenderer::DrawStreamVideoQuad(const DrawingFrame* frame,
1952 const StreamVideoDrawQuad* quad) {
1953 SetBlendEnabled(quad->ShouldDrawWithBlending());
1955 static float gl_matrix[16];
1957 DCHECK(capabilities_.using_egl_image);
1959 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1960 gl_,
1961 &highp_threshold_cache_,
1962 highp_threshold_min_,
1963 quad->shared_quad_state->visible_content_rect.bottom_right());
1965 const VideoStreamTextureProgram* program =
1966 GetVideoStreamTextureProgram(tex_coord_precision);
1967 SetUseProgram(program->program());
1969 ToGLMatrix(&gl_matrix[0], quad->matrix);
1970 GLC(gl_,
1971 gl_->UniformMatrix4fv(
1972 program->vertex_shader().tex_matrix_location(), 1, false, gl_matrix));
1974 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
1975 quad->resource_id);
1976 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
1977 GLC(gl_, gl_->BindTexture(GL_TEXTURE_EXTERNAL_OES, lock.texture_id()));
1979 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1981 SetShaderOpacity(quad->opacity(),
1982 program->fragment_shader().alpha_location());
1983 DrawQuadGeometry(frame,
1984 quad->quadTransform(),
1985 quad->rect,
1986 program->vertex_shader().matrix_location());
1989 struct TextureProgramBinding {
1990 template <class Program>
1991 void Set(Program* program) {
1992 DCHECK(program);
1993 program_id = program->program();
1994 sampler_location = program->fragment_shader().sampler_location();
1995 matrix_location = program->vertex_shader().matrix_location();
1996 background_color_location =
1997 program->fragment_shader().background_color_location();
1999 int program_id;
2000 int sampler_location;
2001 int matrix_location;
2002 int background_color_location;
2005 struct TexTransformTextureProgramBinding : TextureProgramBinding {
2006 template <class Program>
2007 void Set(Program* program) {
2008 TextureProgramBinding::Set(program);
2009 tex_transform_location = program->vertex_shader().tex_transform_location();
2010 vertex_opacity_location =
2011 program->vertex_shader().vertex_opacity_location();
2013 int tex_transform_location;
2014 int vertex_opacity_location;
2017 void GLRenderer::FlushTextureQuadCache() {
2018 // Check to see if we have anything to draw.
2019 if (draw_cache_.program_id == -1)
2020 return;
2022 // Set the correct blending mode.
2023 SetBlendEnabled(draw_cache_.needs_blending);
2025 // Bind the program to the GL state.
2026 SetUseProgram(draw_cache_.program_id);
2028 // Bind the correct texture sampler location.
2029 GLC(gl_, gl_->Uniform1i(draw_cache_.sampler_location, 0));
2031 // Assume the current active textures is 0.
2032 ResourceProvider::ScopedSamplerGL locked_quad(
2033 resource_provider_,
2034 draw_cache_.resource_id,
2035 draw_cache_.nearest_neighbor ? GL_NEAREST : GL_LINEAR);
2036 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2037 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, locked_quad.texture_id()));
2039 static_assert(sizeof(Float4) == 4 * sizeof(float),
2040 "Float4 struct should be densely packed");
2041 static_assert(sizeof(Float16) == 16 * sizeof(float),
2042 "Float16 struct should be densely packed");
2044 // Upload the tranforms for both points and uvs.
2045 GLC(gl_,
2046 gl_->UniformMatrix4fv(
2047 static_cast<int>(draw_cache_.matrix_location),
2048 static_cast<int>(draw_cache_.matrix_data.size()),
2049 false,
2050 reinterpret_cast<float*>(&draw_cache_.matrix_data.front())));
2051 GLC(gl_,
2052 gl_->Uniform4fv(
2053 static_cast<int>(draw_cache_.uv_xform_location),
2054 static_cast<int>(draw_cache_.uv_xform_data.size()),
2055 reinterpret_cast<float*>(&draw_cache_.uv_xform_data.front())));
2057 if (draw_cache_.background_color != SK_ColorTRANSPARENT) {
2058 Float4 background_color = PremultipliedColor(draw_cache_.background_color);
2059 GLC(gl_,
2060 gl_->Uniform4fv(
2061 draw_cache_.background_color_location, 1, background_color.data));
2064 GLC(gl_,
2065 gl_->Uniform1fv(
2066 static_cast<int>(draw_cache_.vertex_opacity_location),
2067 static_cast<int>(draw_cache_.vertex_opacity_data.size()),
2068 static_cast<float*>(&draw_cache_.vertex_opacity_data.front())));
2070 // Draw the quads!
2071 GLC(gl_,
2072 gl_->DrawElements(GL_TRIANGLES,
2073 6 * draw_cache_.matrix_data.size(),
2074 GL_UNSIGNED_SHORT,
2075 0));
2077 // Clear the cache.
2078 draw_cache_.program_id = -1;
2079 draw_cache_.uv_xform_data.resize(0);
2080 draw_cache_.vertex_opacity_data.resize(0);
2081 draw_cache_.matrix_data.resize(0);
2084 void GLRenderer::EnqueueTextureQuad(const DrawingFrame* frame,
2085 const TextureDrawQuad* quad) {
2086 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2087 gl_,
2088 &highp_threshold_cache_,
2089 highp_threshold_min_,
2090 quad->shared_quad_state->visible_content_rect.bottom_right());
2092 // Choose the correct texture program binding
2093 TexTransformTextureProgramBinding binding;
2094 if (quad->premultiplied_alpha) {
2095 if (quad->background_color == SK_ColorTRANSPARENT) {
2096 binding.Set(GetTextureProgram(tex_coord_precision));
2097 } else {
2098 binding.Set(GetTextureBackgroundProgram(tex_coord_precision));
2100 } else {
2101 if (quad->background_color == SK_ColorTRANSPARENT) {
2102 binding.Set(GetNonPremultipliedTextureProgram(tex_coord_precision));
2103 } else {
2104 binding.Set(
2105 GetNonPremultipliedTextureBackgroundProgram(tex_coord_precision));
2109 int resource_id = quad->resource_id;
2111 if (draw_cache_.program_id != binding.program_id ||
2112 draw_cache_.resource_id != resource_id ||
2113 draw_cache_.needs_blending != quad->ShouldDrawWithBlending() ||
2114 draw_cache_.nearest_neighbor != quad->nearest_neighbor ||
2115 draw_cache_.background_color != quad->background_color ||
2116 draw_cache_.matrix_data.size() >= 8) {
2117 FlushTextureQuadCache();
2118 draw_cache_.program_id = binding.program_id;
2119 draw_cache_.resource_id = resource_id;
2120 draw_cache_.needs_blending = quad->ShouldDrawWithBlending();
2121 draw_cache_.nearest_neighbor = quad->nearest_neighbor;
2122 draw_cache_.background_color = quad->background_color;
2124 draw_cache_.uv_xform_location = binding.tex_transform_location;
2125 draw_cache_.background_color_location = binding.background_color_location;
2126 draw_cache_.vertex_opacity_location = binding.vertex_opacity_location;
2127 draw_cache_.matrix_location = binding.matrix_location;
2128 draw_cache_.sampler_location = binding.sampler_location;
2131 // Generate the uv-transform
2132 draw_cache_.uv_xform_data.push_back(UVTransform(quad));
2134 // Generate the vertex opacity
2135 const float opacity = quad->opacity();
2136 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[0] * opacity);
2137 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[1] * opacity);
2138 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[2] * opacity);
2139 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[3] * opacity);
2141 // Generate the transform matrix
2142 gfx::Transform quad_rect_matrix;
2143 QuadRectTransform(&quad_rect_matrix, quad->quadTransform(), quad->rect);
2144 quad_rect_matrix = frame->projection_matrix * quad_rect_matrix;
2146 Float16 m;
2147 quad_rect_matrix.matrix().asColMajorf(m.data);
2148 draw_cache_.matrix_data.push_back(m);
2151 void GLRenderer::DrawIOSurfaceQuad(const DrawingFrame* frame,
2152 const IOSurfaceDrawQuad* quad) {
2153 SetBlendEnabled(quad->ShouldDrawWithBlending());
2155 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2156 gl_,
2157 &highp_threshold_cache_,
2158 highp_threshold_min_,
2159 quad->shared_quad_state->visible_content_rect.bottom_right());
2161 TexTransformTextureProgramBinding binding;
2162 binding.Set(GetTextureIOSurfaceProgram(tex_coord_precision));
2164 SetUseProgram(binding.program_id);
2165 GLC(gl_, gl_->Uniform1i(binding.sampler_location, 0));
2166 if (quad->orientation == IOSurfaceDrawQuad::FLIPPED) {
2167 GLC(gl_,
2168 gl_->Uniform4f(binding.tex_transform_location,
2170 quad->io_surface_size.height(),
2171 quad->io_surface_size.width(),
2172 quad->io_surface_size.height() * -1.0f));
2173 } else {
2174 GLC(gl_,
2175 gl_->Uniform4f(binding.tex_transform_location,
2178 quad->io_surface_size.width(),
2179 quad->io_surface_size.height()));
2182 const float vertex_opacity[] = {quad->opacity(), quad->opacity(),
2183 quad->opacity(), quad->opacity()};
2184 GLC(gl_, gl_->Uniform1fv(binding.vertex_opacity_location, 4, vertex_opacity));
2186 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
2187 quad->io_surface_resource_id);
2188 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2189 GLC(gl_, gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, lock.texture_id()));
2191 DrawQuadGeometry(
2192 frame, quad->quadTransform(), quad->rect, binding.matrix_location);
2194 GLC(gl_, gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, 0));
2197 void GLRenderer::FinishDrawingFrame(DrawingFrame* frame) {
2198 if (use_sync_query_) {
2199 DCHECK(current_sync_query_);
2200 current_sync_query_->End();
2201 pending_sync_queries_.push_back(current_sync_query_.Pass());
2204 current_framebuffer_lock_ = nullptr;
2205 swap_buffer_rect_.Union(gfx::ToEnclosingRect(frame->root_damage_rect));
2207 GLC(gl_, gl_->Disable(GL_BLEND));
2208 blend_shadow_ = false;
2210 ScheduleOverlays(frame);
2213 void GLRenderer::FinishDrawingQuadList() { FlushTextureQuadCache(); }
2215 bool GLRenderer::FlippedFramebuffer(const DrawingFrame* frame) const {
2216 if (frame->current_render_pass != frame->root_render_pass)
2217 return true;
2218 return FlippedRootFramebuffer();
2221 bool GLRenderer::FlippedRootFramebuffer() const {
2222 // GL is normally flipped, so a flipped output results in an unflipping.
2223 return !output_surface_->capabilities().flipped_output_surface;
2226 void GLRenderer::EnsureScissorTestEnabled() {
2227 if (is_scissor_enabled_)
2228 return;
2230 FlushTextureQuadCache();
2231 GLC(gl_, gl_->Enable(GL_SCISSOR_TEST));
2232 is_scissor_enabled_ = true;
2235 void GLRenderer::EnsureScissorTestDisabled() {
2236 if (!is_scissor_enabled_)
2237 return;
2239 FlushTextureQuadCache();
2240 GLC(gl_, gl_->Disable(GL_SCISSOR_TEST));
2241 is_scissor_enabled_ = false;
2244 void GLRenderer::CopyCurrentRenderPassToBitmap(
2245 DrawingFrame* frame,
2246 scoped_ptr<CopyOutputRequest> request) {
2247 TRACE_EVENT0("cc", "GLRenderer::CopyCurrentRenderPassToBitmap");
2248 gfx::Rect copy_rect = frame->current_render_pass->output_rect;
2249 if (request->has_area())
2250 copy_rect.Intersect(request->area());
2251 GetFramebufferPixelsAsync(frame, copy_rect, request.Pass());
2254 void GLRenderer::ToGLMatrix(float* gl_matrix, const gfx::Transform& transform) {
2255 transform.matrix().asColMajorf(gl_matrix);
2258 void GLRenderer::SetShaderQuadF(const gfx::QuadF& quad, int quad_location) {
2259 if (quad_location == -1)
2260 return;
2262 float gl_quad[8];
2263 gl_quad[0] = quad.p1().x();
2264 gl_quad[1] = quad.p1().y();
2265 gl_quad[2] = quad.p2().x();
2266 gl_quad[3] = quad.p2().y();
2267 gl_quad[4] = quad.p3().x();
2268 gl_quad[5] = quad.p3().y();
2269 gl_quad[6] = quad.p4().x();
2270 gl_quad[7] = quad.p4().y();
2271 GLC(gl_, gl_->Uniform2fv(quad_location, 4, gl_quad));
2274 void GLRenderer::SetShaderOpacity(float opacity, int alpha_location) {
2275 if (alpha_location != -1)
2276 GLC(gl_, gl_->Uniform1f(alpha_location, opacity));
2279 void GLRenderer::SetStencilEnabled(bool enabled) {
2280 if (enabled == stencil_shadow_)
2281 return;
2283 if (enabled)
2284 GLC(gl_, gl_->Enable(GL_STENCIL_TEST));
2285 else
2286 GLC(gl_, gl_->Disable(GL_STENCIL_TEST));
2287 stencil_shadow_ = enabled;
2290 void GLRenderer::SetBlendEnabled(bool enabled) {
2291 if (enabled == blend_shadow_)
2292 return;
2294 if (enabled)
2295 GLC(gl_, gl_->Enable(GL_BLEND));
2296 else
2297 GLC(gl_, gl_->Disable(GL_BLEND));
2298 blend_shadow_ = enabled;
2301 void GLRenderer::SetUseProgram(unsigned program) {
2302 if (program == program_shadow_)
2303 return;
2304 gl_->UseProgram(program);
2305 program_shadow_ = program;
2308 void GLRenderer::DrawQuadGeometry(const DrawingFrame* frame,
2309 const gfx::Transform& draw_transform,
2310 const gfx::RectF& quad_rect,
2311 int matrix_location) {
2312 gfx::Transform quad_rect_matrix;
2313 QuadRectTransform(&quad_rect_matrix, draw_transform, quad_rect);
2314 static float gl_matrix[16];
2315 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad_rect_matrix);
2316 GLC(gl_, gl_->UniformMatrix4fv(matrix_location, 1, false, &gl_matrix[0]));
2318 GLC(gl_, gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0));
2321 void GLRenderer::Finish() {
2322 TRACE_EVENT0("cc", "GLRenderer::Finish");
2323 GLC(gl_, gl_->Finish());
2326 void GLRenderer::SwapBuffers(const CompositorFrameMetadata& metadata) {
2327 DCHECK(!is_backbuffer_discarded_);
2329 TRACE_EVENT0("cc,benchmark", "GLRenderer::SwapBuffers");
2330 // We're done! Time to swapbuffers!
2332 gfx::Size surface_size = output_surface_->SurfaceSize();
2334 CompositorFrame compositor_frame;
2335 compositor_frame.metadata = metadata;
2336 compositor_frame.gl_frame_data = make_scoped_ptr(new GLFrameData);
2337 compositor_frame.gl_frame_data->size = surface_size;
2338 if (capabilities_.using_partial_swap) {
2339 // If supported, we can save significant bandwidth by only swapping the
2340 // damaged/scissored region (clamped to the viewport).
2341 swap_buffer_rect_.Intersect(gfx::Rect(surface_size));
2342 int flipped_y_pos_of_rect_bottom = surface_size.height() -
2343 swap_buffer_rect_.y() -
2344 swap_buffer_rect_.height();
2345 compositor_frame.gl_frame_data->sub_buffer_rect =
2346 gfx::Rect(swap_buffer_rect_.x(),
2347 FlippedRootFramebuffer() ? flipped_y_pos_of_rect_bottom
2348 : swap_buffer_rect_.y(),
2349 swap_buffer_rect_.width(),
2350 swap_buffer_rect_.height());
2351 } else {
2352 compositor_frame.gl_frame_data->sub_buffer_rect =
2353 gfx::Rect(output_surface_->SurfaceSize());
2355 output_surface_->SwapBuffers(&compositor_frame);
2357 // Release previously used overlay resources and hold onto the pending ones
2358 // until the next swap buffers.
2359 in_use_overlay_resources_.clear();
2360 in_use_overlay_resources_.swap(pending_overlay_resources_);
2362 swap_buffer_rect_ = gfx::Rect();
2365 void GLRenderer::EnforceMemoryPolicy() {
2366 if (!visible()) {
2367 TRACE_EVENT0("cc", "GLRenderer::EnforceMemoryPolicy dropping resources");
2368 ReleaseRenderPassTextures();
2369 DiscardBackbuffer();
2370 resource_provider_->ReleaseCachedData();
2371 output_surface_->context_provider()->DeleteCachedResources();
2372 GLC(gl_, gl_->Flush());
2376 void GLRenderer::DiscardBackbuffer() {
2377 if (is_backbuffer_discarded_)
2378 return;
2380 output_surface_->DiscardBackbuffer();
2382 is_backbuffer_discarded_ = true;
2384 // Damage tracker needs a full reset every time framebuffer is discarded.
2385 client_->SetFullRootLayerDamage();
2388 void GLRenderer::EnsureBackbuffer() {
2389 if (!is_backbuffer_discarded_)
2390 return;
2392 output_surface_->EnsureBackbuffer();
2393 is_backbuffer_discarded_ = false;
2396 void GLRenderer::GetFramebufferPixelsAsync(
2397 const DrawingFrame* frame,
2398 const gfx::Rect& rect,
2399 scoped_ptr<CopyOutputRequest> request) {
2400 DCHECK(!request->IsEmpty());
2401 if (request->IsEmpty())
2402 return;
2403 if (rect.IsEmpty())
2404 return;
2406 gfx::Rect window_rect = MoveFromDrawToWindowSpace(frame, rect);
2407 DCHECK_GE(window_rect.x(), 0);
2408 DCHECK_GE(window_rect.y(), 0);
2409 DCHECK_LE(window_rect.right(), current_surface_size_.width());
2410 DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2412 if (!request->force_bitmap_result()) {
2413 bool own_mailbox = !request->has_texture_mailbox();
2415 GLuint texture_id = 0;
2416 gpu::Mailbox mailbox;
2417 if (own_mailbox) {
2418 GLC(gl_, gl_->GenMailboxCHROMIUM(mailbox.name));
2419 gl_->GenTextures(1, &texture_id);
2420 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, texture_id));
2422 GLC(gl_,
2423 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
2424 GLC(gl_,
2425 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
2426 GLC(gl_,
2427 gl_->TexParameteri(
2428 GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
2429 GLC(gl_,
2430 gl_->TexParameteri(
2431 GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
2432 GLC(gl_, gl_->ProduceTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name));
2433 } else {
2434 mailbox = request->texture_mailbox().mailbox();
2435 DCHECK_EQ(static_cast<unsigned>(GL_TEXTURE_2D),
2436 request->texture_mailbox().target());
2437 DCHECK(!mailbox.IsZero());
2438 unsigned incoming_sync_point = request->texture_mailbox().sync_point();
2439 if (incoming_sync_point)
2440 GLC(gl_, gl_->WaitSyncPointCHROMIUM(incoming_sync_point));
2442 texture_id = GLC(
2443 gl_,
2444 gl_->CreateAndConsumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name));
2446 GetFramebufferTexture(texture_id, RGBA_8888, window_rect);
2448 unsigned sync_point = gl_->InsertSyncPointCHROMIUM();
2449 TextureMailbox texture_mailbox(mailbox, GL_TEXTURE_2D, sync_point);
2451 scoped_ptr<SingleReleaseCallback> release_callback;
2452 if (own_mailbox) {
2453 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, 0));
2454 release_callback = texture_mailbox_deleter_->GetReleaseCallback(
2455 output_surface_->context_provider(), texture_id);
2456 } else {
2457 gl_->DeleteTextures(1, &texture_id);
2460 request->SendTextureResult(
2461 window_rect.size(), texture_mailbox, release_callback.Pass());
2462 return;
2465 DCHECK(request->force_bitmap_result());
2467 scoped_ptr<PendingAsyncReadPixels> pending_read(new PendingAsyncReadPixels);
2468 pending_read->copy_request = request.Pass();
2469 pending_async_read_pixels_.insert(pending_async_read_pixels_.begin(),
2470 pending_read.Pass());
2472 bool do_workaround = NeedsIOSurfaceReadbackWorkaround();
2474 unsigned temporary_texture = 0;
2475 unsigned temporary_fbo = 0;
2477 if (do_workaround) {
2478 // On Mac OS X, calling glReadPixels() against an FBO whose color attachment
2479 // is an IOSurface-backed texture causes corruption of future glReadPixels()
2480 // calls, even those on different OpenGL contexts. It is believed that this
2481 // is the root cause of top crasher
2482 // http://crbug.com/99393. <rdar://problem/10949687>
2484 gl_->GenTextures(1, &temporary_texture);
2485 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, temporary_texture));
2486 GLC(gl_,
2487 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
2488 GLC(gl_,
2489 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
2490 GLC(gl_,
2491 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
2492 GLC(gl_,
2493 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
2494 // Copy the contents of the current (IOSurface-backed) framebuffer into a
2495 // temporary texture.
2496 GetFramebufferTexture(
2497 temporary_texture, RGBA_8888, gfx::Rect(current_surface_size_));
2498 gl_->GenFramebuffers(1, &temporary_fbo);
2499 // Attach this texture to an FBO, and perform the readback from that FBO.
2500 GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, temporary_fbo));
2501 GLC(gl_,
2502 gl_->FramebufferTexture2D(GL_FRAMEBUFFER,
2503 GL_COLOR_ATTACHMENT0,
2504 GL_TEXTURE_2D,
2505 temporary_texture,
2506 0));
2508 DCHECK_EQ(static_cast<unsigned>(GL_FRAMEBUFFER_COMPLETE),
2509 gl_->CheckFramebufferStatus(GL_FRAMEBUFFER));
2512 GLuint buffer = 0;
2513 gl_->GenBuffers(1, &buffer);
2514 GLC(gl_, gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, buffer));
2515 GLC(gl_,
2516 gl_->BufferData(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM,
2517 4 * window_rect.size().GetArea(),
2518 NULL,
2519 GL_STREAM_READ));
2521 GLuint query = 0;
2522 gl_->GenQueriesEXT(1, &query);
2523 GLC(gl_, gl_->BeginQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM, query));
2525 GLC(gl_,
2526 gl_->ReadPixels(window_rect.x(),
2527 window_rect.y(),
2528 window_rect.width(),
2529 window_rect.height(),
2530 GL_RGBA,
2531 GL_UNSIGNED_BYTE,
2532 NULL));
2534 GLC(gl_, gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0));
2536 if (do_workaround) {
2537 // Clean up.
2538 GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, 0));
2539 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, 0));
2540 GLC(gl_, gl_->DeleteFramebuffers(1, &temporary_fbo));
2541 GLC(gl_, gl_->DeleteTextures(1, &temporary_texture));
2544 base::Closure finished_callback = base::Bind(&GLRenderer::FinishedReadback,
2545 base::Unretained(this),
2546 buffer,
2547 query,
2548 window_rect.size());
2549 // Save the finished_callback so it can be cancelled.
2550 pending_async_read_pixels_.front()->finished_read_pixels_callback.Reset(
2551 finished_callback);
2552 base::Closure cancelable_callback =
2553 pending_async_read_pixels_.front()->
2554 finished_read_pixels_callback.callback();
2556 // Save the buffer to verify the callbacks happen in the expected order.
2557 pending_async_read_pixels_.front()->buffer = buffer;
2559 GLC(gl_, gl_->EndQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM));
2560 context_support_->SignalQuery(query, cancelable_callback);
2562 EnforceMemoryPolicy();
2565 void GLRenderer::FinishedReadback(unsigned source_buffer,
2566 unsigned query,
2567 const gfx::Size& size) {
2568 DCHECK(!pending_async_read_pixels_.empty());
2570 if (query != 0) {
2571 GLC(gl_, gl_->DeleteQueriesEXT(1, &query));
2574 PendingAsyncReadPixels* current_read = pending_async_read_pixels_.back();
2575 // Make sure we service the readbacks in order.
2576 DCHECK_EQ(source_buffer, current_read->buffer);
2578 uint8* src_pixels = NULL;
2579 scoped_ptr<SkBitmap> bitmap;
2581 if (source_buffer != 0) {
2582 GLC(gl_,
2583 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, source_buffer));
2584 src_pixels = static_cast<uint8*>(gl_->MapBufferCHROMIUM(
2585 GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, GL_READ_ONLY));
2587 if (src_pixels) {
2588 bitmap.reset(new SkBitmap);
2589 bitmap->allocN32Pixels(size.width(), size.height());
2590 scoped_ptr<SkAutoLockPixels> lock(new SkAutoLockPixels(*bitmap));
2591 uint8* dest_pixels = static_cast<uint8*>(bitmap->getPixels());
2593 size_t row_bytes = size.width() * 4;
2594 int num_rows = size.height();
2595 size_t total_bytes = num_rows * row_bytes;
2596 for (size_t dest_y = 0; dest_y < total_bytes; dest_y += row_bytes) {
2597 // Flip Y axis.
2598 size_t src_y = total_bytes - dest_y - row_bytes;
2599 // Swizzle OpenGL -> Skia byte order.
2600 for (size_t x = 0; x < row_bytes; x += 4) {
2601 dest_pixels[dest_y + x + SK_R32_SHIFT / 8] =
2602 src_pixels[src_y + x + 0];
2603 dest_pixels[dest_y + x + SK_G32_SHIFT / 8] =
2604 src_pixels[src_y + x + 1];
2605 dest_pixels[dest_y + x + SK_B32_SHIFT / 8] =
2606 src_pixels[src_y + x + 2];
2607 dest_pixels[dest_y + x + SK_A32_SHIFT / 8] =
2608 src_pixels[src_y + x + 3];
2612 GLC(gl_,
2613 gl_->UnmapBufferCHROMIUM(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM));
2615 GLC(gl_, gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0));
2616 GLC(gl_, gl_->DeleteBuffers(1, &source_buffer));
2619 if (bitmap)
2620 current_read->copy_request->SendBitmapResult(bitmap.Pass());
2621 pending_async_read_pixels_.pop_back();
2624 void GLRenderer::GetFramebufferTexture(unsigned texture_id,
2625 ResourceFormat texture_format,
2626 const gfx::Rect& window_rect) {
2627 DCHECK(texture_id);
2628 DCHECK_GE(window_rect.x(), 0);
2629 DCHECK_GE(window_rect.y(), 0);
2630 DCHECK_LE(window_rect.right(), current_surface_size_.width());
2631 DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2633 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, texture_id));
2634 GLC(gl_,
2635 gl_->CopyTexImage2D(GL_TEXTURE_2D,
2637 GLDataFormat(texture_format),
2638 window_rect.x(),
2639 window_rect.y(),
2640 window_rect.width(),
2641 window_rect.height(),
2642 0));
2643 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, 0));
2646 bool GLRenderer::UseScopedTexture(DrawingFrame* frame,
2647 const ScopedResource* texture,
2648 const gfx::Rect& viewport_rect) {
2649 DCHECK(texture->id());
2650 frame->current_render_pass = NULL;
2651 frame->current_texture = texture;
2653 return BindFramebufferToTexture(frame, texture, viewport_rect);
2656 void GLRenderer::BindFramebufferToOutputSurface(DrawingFrame* frame) {
2657 current_framebuffer_lock_ = nullptr;
2658 output_surface_->BindFramebuffer();
2660 if (output_surface_->HasExternalStencilTest()) {
2661 SetStencilEnabled(true);
2662 GLC(gl_, gl_->StencilFunc(GL_EQUAL, 1, 1));
2663 } else {
2664 SetStencilEnabled(false);
2668 bool GLRenderer::BindFramebufferToTexture(DrawingFrame* frame,
2669 const ScopedResource* texture,
2670 const gfx::Rect& target_rect) {
2671 DCHECK(texture->id());
2673 // Explicitly release lock, otherwise we can crash when try to lock
2674 // same texture again.
2675 current_framebuffer_lock_ = nullptr;
2677 SetStencilEnabled(false);
2678 GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, offscreen_framebuffer_id_));
2679 current_framebuffer_lock_ =
2680 make_scoped_ptr(new ResourceProvider::ScopedWriteLockGL(
2681 resource_provider_, texture->id()));
2682 unsigned texture_id = current_framebuffer_lock_->texture_id();
2683 GLC(gl_,
2684 gl_->FramebufferTexture2D(
2685 GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_id, 0));
2687 DCHECK(gl_->CheckFramebufferStatus(GL_FRAMEBUFFER) ==
2688 GL_FRAMEBUFFER_COMPLETE ||
2689 IsContextLost());
2691 InitializeViewport(
2692 frame, target_rect, gfx::Rect(target_rect.size()), target_rect.size());
2693 return true;
2696 void GLRenderer::SetScissorTestRect(const gfx::Rect& scissor_rect) {
2697 EnsureScissorTestEnabled();
2699 // Don't unnecessarily ask the context to change the scissor, because it
2700 // may cause undesired GPU pipeline flushes.
2701 if (scissor_rect == scissor_rect_ && !scissor_rect_needs_reset_)
2702 return;
2704 scissor_rect_ = scissor_rect;
2705 FlushTextureQuadCache();
2706 GLC(gl_,
2707 gl_->Scissor(scissor_rect.x(),
2708 scissor_rect.y(),
2709 scissor_rect.width(),
2710 scissor_rect.height()));
2712 scissor_rect_needs_reset_ = false;
2715 void GLRenderer::SetDrawViewport(const gfx::Rect& window_space_viewport) {
2716 viewport_ = window_space_viewport;
2717 GLC(gl_,
2718 gl_->Viewport(window_space_viewport.x(),
2719 window_space_viewport.y(),
2720 window_space_viewport.width(),
2721 window_space_viewport.height()));
2724 void GLRenderer::InitializeSharedObjects() {
2725 TRACE_EVENT0("cc", "GLRenderer::InitializeSharedObjects");
2727 // Create an FBO for doing offscreen rendering.
2728 GLC(gl_, gl_->GenFramebuffers(1, &offscreen_framebuffer_id_));
2730 shared_geometry_ = make_scoped_ptr(
2731 new GeometryBinding(gl_, QuadVertexRect()));
2734 const GLRenderer::TileCheckerboardProgram*
2735 GLRenderer::GetTileCheckerboardProgram() {
2736 if (!tile_checkerboard_program_.initialized()) {
2737 TRACE_EVENT0("cc", "GLRenderer::checkerboardProgram::initalize");
2738 tile_checkerboard_program_.Initialize(output_surface_->context_provider(),
2739 TEX_COORD_PRECISION_NA,
2740 SAMPLER_TYPE_NA);
2742 return &tile_checkerboard_program_;
2745 const GLRenderer::DebugBorderProgram* GLRenderer::GetDebugBorderProgram() {
2746 if (!debug_border_program_.initialized()) {
2747 TRACE_EVENT0("cc", "GLRenderer::debugBorderProgram::initialize");
2748 debug_border_program_.Initialize(output_surface_->context_provider(),
2749 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
2751 return &debug_border_program_;
2754 const GLRenderer::SolidColorProgram* GLRenderer::GetSolidColorProgram() {
2755 if (!solid_color_program_.initialized()) {
2756 TRACE_EVENT0("cc", "GLRenderer::solidColorProgram::initialize");
2757 solid_color_program_.Initialize(output_surface_->context_provider(),
2758 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
2760 return &solid_color_program_;
2763 const GLRenderer::SolidColorProgramAA* GLRenderer::GetSolidColorProgramAA() {
2764 if (!solid_color_program_aa_.initialized()) {
2765 TRACE_EVENT0("cc", "GLRenderer::solidColorProgramAA::initialize");
2766 solid_color_program_aa_.Initialize(output_surface_->context_provider(),
2767 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
2769 return &solid_color_program_aa_;
2772 const GLRenderer::RenderPassProgram* GLRenderer::GetRenderPassProgram(
2773 TexCoordPrecision precision,
2774 BlendMode blend_mode) {
2775 DCHECK_GE(precision, 0);
2776 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
2777 DCHECK_GE(blend_mode, 0);
2778 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
2779 RenderPassProgram* program = &render_pass_program_[precision][blend_mode];
2780 if (!program->initialized()) {
2781 TRACE_EVENT0("cc", "GLRenderer::renderPassProgram::initialize");
2782 program->Initialize(output_surface_->context_provider(), precision,
2783 SAMPLER_TYPE_2D, blend_mode);
2785 return program;
2788 const GLRenderer::RenderPassProgramAA* GLRenderer::GetRenderPassProgramAA(
2789 TexCoordPrecision precision,
2790 BlendMode blend_mode) {
2791 DCHECK_GE(precision, 0);
2792 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
2793 DCHECK_GE(blend_mode, 0);
2794 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
2795 RenderPassProgramAA* program =
2796 &render_pass_program_aa_[precision][blend_mode];
2797 if (!program->initialized()) {
2798 TRACE_EVENT0("cc", "GLRenderer::renderPassProgramAA::initialize");
2799 program->Initialize(output_surface_->context_provider(), precision,
2800 SAMPLER_TYPE_2D, blend_mode);
2802 return program;
2805 const GLRenderer::RenderPassMaskProgram* GLRenderer::GetRenderPassMaskProgram(
2806 TexCoordPrecision precision,
2807 SamplerType sampler,
2808 BlendMode blend_mode) {
2809 DCHECK_GE(precision, 0);
2810 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
2811 DCHECK_GE(sampler, 0);
2812 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
2813 DCHECK_GE(blend_mode, 0);
2814 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
2815 RenderPassMaskProgram* program =
2816 &render_pass_mask_program_[precision][sampler][blend_mode];
2817 if (!program->initialized()) {
2818 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgram::initialize");
2819 program->Initialize(
2820 output_surface_->context_provider(), precision, sampler, blend_mode);
2822 return program;
2825 const GLRenderer::RenderPassMaskProgramAA*
2826 GLRenderer::GetRenderPassMaskProgramAA(TexCoordPrecision precision,
2827 SamplerType sampler,
2828 BlendMode blend_mode) {
2829 DCHECK_GE(precision, 0);
2830 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
2831 DCHECK_GE(sampler, 0);
2832 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
2833 DCHECK_GE(blend_mode, 0);
2834 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
2835 RenderPassMaskProgramAA* program =
2836 &render_pass_mask_program_aa_[precision][sampler][blend_mode];
2837 if (!program->initialized()) {
2838 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgramAA::initialize");
2839 program->Initialize(
2840 output_surface_->context_provider(), precision, sampler, blend_mode);
2842 return program;
2845 const GLRenderer::RenderPassColorMatrixProgram*
2846 GLRenderer::GetRenderPassColorMatrixProgram(TexCoordPrecision precision,
2847 BlendMode blend_mode) {
2848 DCHECK_GE(precision, 0);
2849 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
2850 DCHECK_GE(blend_mode, 0);
2851 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
2852 RenderPassColorMatrixProgram* program =
2853 &render_pass_color_matrix_program_[precision][blend_mode];
2854 if (!program->initialized()) {
2855 TRACE_EVENT0("cc", "GLRenderer::renderPassColorMatrixProgram::initialize");
2856 program->Initialize(output_surface_->context_provider(), precision,
2857 SAMPLER_TYPE_2D, blend_mode);
2859 return program;
2862 const GLRenderer::RenderPassColorMatrixProgramAA*
2863 GLRenderer::GetRenderPassColorMatrixProgramAA(TexCoordPrecision precision,
2864 BlendMode blend_mode) {
2865 DCHECK_GE(precision, 0);
2866 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
2867 DCHECK_GE(blend_mode, 0);
2868 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
2869 RenderPassColorMatrixProgramAA* program =
2870 &render_pass_color_matrix_program_aa_[precision][blend_mode];
2871 if (!program->initialized()) {
2872 TRACE_EVENT0("cc",
2873 "GLRenderer::renderPassColorMatrixProgramAA::initialize");
2874 program->Initialize(output_surface_->context_provider(), precision,
2875 SAMPLER_TYPE_2D, blend_mode);
2877 return program;
2880 const GLRenderer::RenderPassMaskColorMatrixProgram*
2881 GLRenderer::GetRenderPassMaskColorMatrixProgram(TexCoordPrecision precision,
2882 SamplerType sampler,
2883 BlendMode blend_mode) {
2884 DCHECK_GE(precision, 0);
2885 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
2886 DCHECK_GE(sampler, 0);
2887 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
2888 DCHECK_GE(blend_mode, 0);
2889 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
2890 RenderPassMaskColorMatrixProgram* program =
2891 &render_pass_mask_color_matrix_program_[precision][sampler][blend_mode];
2892 if (!program->initialized()) {
2893 TRACE_EVENT0("cc",
2894 "GLRenderer::renderPassMaskColorMatrixProgram::initialize");
2895 program->Initialize(
2896 output_surface_->context_provider(), precision, sampler, blend_mode);
2898 return program;
2901 const GLRenderer::RenderPassMaskColorMatrixProgramAA*
2902 GLRenderer::GetRenderPassMaskColorMatrixProgramAA(TexCoordPrecision precision,
2903 SamplerType sampler,
2904 BlendMode blend_mode) {
2905 DCHECK_GE(precision, 0);
2906 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
2907 DCHECK_GE(sampler, 0);
2908 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
2909 DCHECK_GE(blend_mode, 0);
2910 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
2911 RenderPassMaskColorMatrixProgramAA* program =
2912 &render_pass_mask_color_matrix_program_aa_[precision][sampler]
2913 [blend_mode];
2914 if (!program->initialized()) {
2915 TRACE_EVENT0("cc",
2916 "GLRenderer::renderPassMaskColorMatrixProgramAA::initialize");
2917 program->Initialize(
2918 output_surface_->context_provider(), precision, sampler, blend_mode);
2920 return program;
2923 const GLRenderer::TileProgram* GLRenderer::GetTileProgram(
2924 TexCoordPrecision precision,
2925 SamplerType sampler) {
2926 DCHECK_GE(precision, 0);
2927 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
2928 DCHECK_GE(sampler, 0);
2929 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
2930 TileProgram* program = &tile_program_[precision][sampler];
2931 if (!program->initialized()) {
2932 TRACE_EVENT0("cc", "GLRenderer::tileProgram::initialize");
2933 program->Initialize(
2934 output_surface_->context_provider(), precision, sampler);
2936 return program;
2939 const GLRenderer::TileProgramOpaque* GLRenderer::GetTileProgramOpaque(
2940 TexCoordPrecision precision,
2941 SamplerType sampler) {
2942 DCHECK_GE(precision, 0);
2943 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
2944 DCHECK_GE(sampler, 0);
2945 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
2946 TileProgramOpaque* program = &tile_program_opaque_[precision][sampler];
2947 if (!program->initialized()) {
2948 TRACE_EVENT0("cc", "GLRenderer::tileProgramOpaque::initialize");
2949 program->Initialize(
2950 output_surface_->context_provider(), precision, sampler);
2952 return program;
2955 const GLRenderer::TileProgramAA* GLRenderer::GetTileProgramAA(
2956 TexCoordPrecision precision,
2957 SamplerType sampler) {
2958 DCHECK_GE(precision, 0);
2959 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
2960 DCHECK_GE(sampler, 0);
2961 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
2962 TileProgramAA* program = &tile_program_aa_[precision][sampler];
2963 if (!program->initialized()) {
2964 TRACE_EVENT0("cc", "GLRenderer::tileProgramAA::initialize");
2965 program->Initialize(
2966 output_surface_->context_provider(), precision, sampler);
2968 return program;
2971 const GLRenderer::TileProgramSwizzle* GLRenderer::GetTileProgramSwizzle(
2972 TexCoordPrecision precision,
2973 SamplerType sampler) {
2974 DCHECK_GE(precision, 0);
2975 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
2976 DCHECK_GE(sampler, 0);
2977 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
2978 TileProgramSwizzle* program = &tile_program_swizzle_[precision][sampler];
2979 if (!program->initialized()) {
2980 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzle::initialize");
2981 program->Initialize(
2982 output_surface_->context_provider(), precision, sampler);
2984 return program;
2987 const GLRenderer::TileProgramSwizzleOpaque*
2988 GLRenderer::GetTileProgramSwizzleOpaque(TexCoordPrecision precision,
2989 SamplerType sampler) {
2990 DCHECK_GE(precision, 0);
2991 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
2992 DCHECK_GE(sampler, 0);
2993 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
2994 TileProgramSwizzleOpaque* program =
2995 &tile_program_swizzle_opaque_[precision][sampler];
2996 if (!program->initialized()) {
2997 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleOpaque::initialize");
2998 program->Initialize(
2999 output_surface_->context_provider(), precision, sampler);
3001 return program;
3004 const GLRenderer::TileProgramSwizzleAA* GLRenderer::GetTileProgramSwizzleAA(
3005 TexCoordPrecision precision,
3006 SamplerType sampler) {
3007 DCHECK_GE(precision, 0);
3008 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3009 DCHECK_GE(sampler, 0);
3010 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3011 TileProgramSwizzleAA* program = &tile_program_swizzle_aa_[precision][sampler];
3012 if (!program->initialized()) {
3013 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleAA::initialize");
3014 program->Initialize(
3015 output_surface_->context_provider(), precision, sampler);
3017 return program;
3020 const GLRenderer::TextureProgram* GLRenderer::GetTextureProgram(
3021 TexCoordPrecision precision) {
3022 DCHECK_GE(precision, 0);
3023 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3024 TextureProgram* program = &texture_program_[precision];
3025 if (!program->initialized()) {
3026 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3027 program->Initialize(output_surface_->context_provider(), precision,
3028 SAMPLER_TYPE_2D);
3030 return program;
3033 const GLRenderer::NonPremultipliedTextureProgram*
3034 GLRenderer::GetNonPremultipliedTextureProgram(TexCoordPrecision precision) {
3035 DCHECK_GE(precision, 0);
3036 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3037 NonPremultipliedTextureProgram* program =
3038 &nonpremultiplied_texture_program_[precision];
3039 if (!program->initialized()) {
3040 TRACE_EVENT0("cc",
3041 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3042 program->Initialize(output_surface_->context_provider(), precision,
3043 SAMPLER_TYPE_2D);
3045 return program;
3048 const GLRenderer::TextureBackgroundProgram*
3049 GLRenderer::GetTextureBackgroundProgram(TexCoordPrecision precision) {
3050 DCHECK_GE(precision, 0);
3051 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3052 TextureBackgroundProgram* program = &texture_background_program_[precision];
3053 if (!program->initialized()) {
3054 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3055 program->Initialize(output_surface_->context_provider(), precision,
3056 SAMPLER_TYPE_2D);
3058 return program;
3061 const GLRenderer::NonPremultipliedTextureBackgroundProgram*
3062 GLRenderer::GetNonPremultipliedTextureBackgroundProgram(
3063 TexCoordPrecision precision) {
3064 DCHECK_GE(precision, 0);
3065 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3066 NonPremultipliedTextureBackgroundProgram* program =
3067 &nonpremultiplied_texture_background_program_[precision];
3068 if (!program->initialized()) {
3069 TRACE_EVENT0("cc",
3070 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3071 program->Initialize(output_surface_->context_provider(), precision,
3072 SAMPLER_TYPE_2D);
3074 return program;
3077 const GLRenderer::TextureProgram* GLRenderer::GetTextureIOSurfaceProgram(
3078 TexCoordPrecision precision) {
3079 DCHECK_GE(precision, 0);
3080 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3081 TextureProgram* program = &texture_io_surface_program_[precision];
3082 if (!program->initialized()) {
3083 TRACE_EVENT0("cc", "GLRenderer::textureIOSurfaceProgram::initialize");
3084 program->Initialize(output_surface_->context_provider(), precision,
3085 SAMPLER_TYPE_2D_RECT);
3087 return program;
3090 const GLRenderer::VideoYUVProgram* GLRenderer::GetVideoYUVProgram(
3091 TexCoordPrecision precision) {
3092 DCHECK_GE(precision, 0);
3093 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3094 VideoYUVProgram* program = &video_yuv_program_[precision];
3095 if (!program->initialized()) {
3096 TRACE_EVENT0("cc", "GLRenderer::videoYUVProgram::initialize");
3097 program->Initialize(output_surface_->context_provider(), precision,
3098 SAMPLER_TYPE_2D);
3100 return program;
3103 const GLRenderer::VideoYUVAProgram* GLRenderer::GetVideoYUVAProgram(
3104 TexCoordPrecision precision) {
3105 DCHECK_GE(precision, 0);
3106 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3107 VideoYUVAProgram* program = &video_yuva_program_[precision];
3108 if (!program->initialized()) {
3109 TRACE_EVENT0("cc", "GLRenderer::videoYUVAProgram::initialize");
3110 program->Initialize(output_surface_->context_provider(), precision,
3111 SAMPLER_TYPE_2D);
3113 return program;
3116 const GLRenderer::VideoStreamTextureProgram*
3117 GLRenderer::GetVideoStreamTextureProgram(TexCoordPrecision precision) {
3118 if (!Capabilities().using_egl_image)
3119 return NULL;
3120 DCHECK_GE(precision, 0);
3121 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3122 VideoStreamTextureProgram* program =
3123 &video_stream_texture_program_[precision];
3124 if (!program->initialized()) {
3125 TRACE_EVENT0("cc", "GLRenderer::streamTextureProgram::initialize");
3126 program->Initialize(output_surface_->context_provider(), precision,
3127 SAMPLER_TYPE_EXTERNAL_OES);
3129 return program;
3132 void GLRenderer::CleanupSharedObjects() {
3133 shared_geometry_ = nullptr;
3135 for (int i = 0; i <= LAST_TEX_COORD_PRECISION; ++i) {
3136 for (int j = 0; j <= LAST_SAMPLER_TYPE; ++j) {
3137 tile_program_[i][j].Cleanup(gl_);
3138 tile_program_opaque_[i][j].Cleanup(gl_);
3139 tile_program_swizzle_[i][j].Cleanup(gl_);
3140 tile_program_swizzle_opaque_[i][j].Cleanup(gl_);
3141 tile_program_aa_[i][j].Cleanup(gl_);
3142 tile_program_swizzle_aa_[i][j].Cleanup(gl_);
3144 for (int k = 0; k <= LAST_BLEND_MODE; k++) {
3145 render_pass_mask_program_[i][j][k].Cleanup(gl_);
3146 render_pass_mask_program_aa_[i][j][k].Cleanup(gl_);
3147 render_pass_mask_color_matrix_program_aa_[i][j][k].Cleanup(gl_);
3148 render_pass_mask_color_matrix_program_[i][j][k].Cleanup(gl_);
3151 for (int j = 0; j <= LAST_BLEND_MODE; j++) {
3152 render_pass_program_[i][j].Cleanup(gl_);
3153 render_pass_program_aa_[i][j].Cleanup(gl_);
3154 render_pass_color_matrix_program_[i][j].Cleanup(gl_);
3155 render_pass_color_matrix_program_aa_[i][j].Cleanup(gl_);
3158 texture_program_[i].Cleanup(gl_);
3159 nonpremultiplied_texture_program_[i].Cleanup(gl_);
3160 texture_background_program_[i].Cleanup(gl_);
3161 nonpremultiplied_texture_background_program_[i].Cleanup(gl_);
3162 texture_io_surface_program_[i].Cleanup(gl_);
3164 video_yuv_program_[i].Cleanup(gl_);
3165 video_yuva_program_[i].Cleanup(gl_);
3166 video_stream_texture_program_[i].Cleanup(gl_);
3169 tile_checkerboard_program_.Cleanup(gl_);
3171 debug_border_program_.Cleanup(gl_);
3172 solid_color_program_.Cleanup(gl_);
3173 solid_color_program_aa_.Cleanup(gl_);
3175 if (offscreen_framebuffer_id_)
3176 GLC(gl_, gl_->DeleteFramebuffers(1, &offscreen_framebuffer_id_));
3178 if (on_demand_tile_raster_resource_id_)
3179 resource_provider_->DeleteResource(on_demand_tile_raster_resource_id_);
3181 ReleaseRenderPassTextures();
3184 void GLRenderer::ReinitializeGLState() {
3185 is_scissor_enabled_ = false;
3186 scissor_rect_needs_reset_ = true;
3187 stencil_shadow_ = false;
3188 blend_shadow_ = true;
3189 program_shadow_ = 0;
3191 RestoreGLState();
3194 void GLRenderer::RestoreGLState() {
3195 // This restores the current GLRenderer state to the GL context.
3197 shared_geometry_->PrepareForDraw();
3199 GLC(gl_, gl_->Disable(GL_DEPTH_TEST));
3200 GLC(gl_, gl_->Disable(GL_CULL_FACE));
3201 GLC(gl_, gl_->ColorMask(true, true, true, true));
3202 GLC(gl_, gl_->BlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA));
3203 GLC(gl_, gl_->ActiveTexture(GL_TEXTURE0));
3205 if (program_shadow_)
3206 gl_->UseProgram(program_shadow_);
3208 if (stencil_shadow_)
3209 GLC(gl_, gl_->Enable(GL_STENCIL_TEST));
3210 else
3211 GLC(gl_, gl_->Disable(GL_STENCIL_TEST));
3213 if (blend_shadow_)
3214 GLC(gl_, gl_->Enable(GL_BLEND));
3215 else
3216 GLC(gl_, gl_->Disable(GL_BLEND));
3218 if (is_scissor_enabled_) {
3219 GLC(gl_, gl_->Enable(GL_SCISSOR_TEST));
3220 GLC(gl_,
3221 gl_->Scissor(scissor_rect_.x(),
3222 scissor_rect_.y(),
3223 scissor_rect_.width(),
3224 scissor_rect_.height()));
3225 } else {
3226 GLC(gl_, gl_->Disable(GL_SCISSOR_TEST));
3230 void GLRenderer::RestoreFramebuffer(DrawingFrame* frame) {
3231 UseRenderPass(frame, frame->current_render_pass);
3234 bool GLRenderer::IsContextLost() {
3235 return output_surface_->context_provider()->IsContextLost();
3238 void GLRenderer::ScheduleOverlays(DrawingFrame* frame) {
3239 if (!frame->overlay_list.size())
3240 return;
3242 ResourceProvider::ResourceIdArray resources;
3243 OverlayCandidateList& overlays = frame->overlay_list;
3244 OverlayCandidateList::iterator it;
3245 for (it = overlays.begin(); it != overlays.end(); ++it) {
3246 const OverlayCandidate& overlay = *it;
3247 // Skip primary plane.
3248 if (overlay.plane_z_order == 0)
3249 continue;
3251 pending_overlay_resources_.push_back(
3252 make_scoped_ptr(new ResourceProvider::ScopedReadLockGL(
3253 resource_provider_, overlay.resource_id)));
3255 context_support_->ScheduleOverlayPlane(
3256 overlay.plane_z_order,
3257 overlay.transform,
3258 pending_overlay_resources_.back()->texture_id(),
3259 overlay.display_rect,
3260 overlay.uv_rect);
3264 } // namespace cc