BookmarkManager: Fix 'new folder text field size changes on clicking it' issue.
[chromium-blink-merge.git] / cc / output / gl_renderer.cc
blob14a48bfe7c3ef466cff693ad7fd2ffb131964cbf
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/memory/scoped_ptr.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "build/build_config.h"
19 #include "base/trace_event/trace_event.h"
20 #include "cc/base/math_util.h"
21 #include "cc/output/compositor_frame.h"
22 #include "cc/output/compositor_frame_metadata.h"
23 #include "cc/output/context_provider.h"
24 #include "cc/output/copy_output_request.h"
25 #include "cc/output/dynamic_geometry_binding.h"
26 #include "cc/output/gl_frame_data.h"
27 #include "cc/output/layer_quad.h"
28 #include "cc/output/output_surface.h"
29 #include "cc/output/render_surface_filters.h"
30 #include "cc/output/static_geometry_binding.h"
31 #include "cc/output/texture_mailbox_deleter.h"
32 #include "cc/quads/draw_polygon.h"
33 #include "cc/quads/picture_draw_quad.h"
34 #include "cc/quads/render_pass.h"
35 #include "cc/quads/stream_video_draw_quad.h"
36 #include "cc/quads/texture_draw_quad.h"
37 #include "cc/raster/scoped_gpu_raster.h"
38 #include "cc/resources/scoped_resource.h"
39 #include "gpu/GLES2/gl2extchromium.h"
40 #include "gpu/command_buffer/client/context_support.h"
41 #include "gpu/command_buffer/client/gles2_interface.h"
42 #include "gpu/command_buffer/common/gpu_memory_allocation.h"
43 #include "third_party/skia/include/core/SkBitmap.h"
44 #include "third_party/skia/include/core/SkColor.h"
45 #include "third_party/skia/include/core/SkColorFilter.h"
46 #include "third_party/skia/include/core/SkImage.h"
47 #include "third_party/skia/include/core/SkSurface.h"
48 #include "third_party/skia/include/gpu/GrContext.h"
49 #include "third_party/skia/include/gpu/GrTexture.h"
50 #include "third_party/skia/include/gpu/GrTextureProvider.h"
51 #include "third_party/skia/include/gpu/SkGrTexturePixelRef.h"
52 #include "third_party/skia/include/gpu/gl/GrGLInterface.h"
53 #include "ui/gfx/geometry/quad_f.h"
54 #include "ui/gfx/geometry/rect_conversions.h"
56 using gpu::gles2::GLES2Interface;
58 namespace cc {
59 namespace {
61 bool NeedsIOSurfaceReadbackWorkaround() {
62 #if defined(OS_MACOSX)
63 // This isn't strictly required in DumpRenderTree-mode when Mesa is used,
64 // but it doesn't seem to hurt.
65 return true;
66 #else
67 return false;
68 #endif
71 Float4 UVTransform(const TextureDrawQuad* quad) {
72 gfx::PointF uv0 = quad->uv_top_left;
73 gfx::PointF uv1 = quad->uv_bottom_right;
74 Float4 xform = {{uv0.x(), uv0.y(), uv1.x() - uv0.x(), uv1.y() - uv0.y()}};
75 if (quad->y_flipped) {
76 xform.data[1] = 1.0f - xform.data[1];
77 xform.data[3] = -xform.data[3];
79 return xform;
82 Float4 PremultipliedColor(SkColor color) {
83 const float factor = 1.0f / 255.0f;
84 const float alpha = SkColorGetA(color) * factor;
86 Float4 result = {
87 {SkColorGetR(color) * factor * alpha, SkColorGetG(color) * factor * alpha,
88 SkColorGetB(color) * factor * alpha, alpha}};
89 return result;
92 SamplerType SamplerTypeFromTextureTarget(GLenum target) {
93 switch (target) {
94 case GL_TEXTURE_2D:
95 return SAMPLER_TYPE_2D;
96 case GL_TEXTURE_RECTANGLE_ARB:
97 return SAMPLER_TYPE_2D_RECT;
98 case GL_TEXTURE_EXTERNAL_OES:
99 return SAMPLER_TYPE_EXTERNAL_OES;
100 default:
101 NOTREACHED();
102 return SAMPLER_TYPE_2D;
106 BlendMode BlendModeFromSkXfermode(SkXfermode::Mode mode) {
107 switch (mode) {
108 case SkXfermode::kSrcOver_Mode:
109 return BLEND_MODE_NORMAL;
110 case SkXfermode::kScreen_Mode:
111 return BLEND_MODE_SCREEN;
112 case SkXfermode::kOverlay_Mode:
113 return BLEND_MODE_OVERLAY;
114 case SkXfermode::kDarken_Mode:
115 return BLEND_MODE_DARKEN;
116 case SkXfermode::kLighten_Mode:
117 return BLEND_MODE_LIGHTEN;
118 case SkXfermode::kColorDodge_Mode:
119 return BLEND_MODE_COLOR_DODGE;
120 case SkXfermode::kColorBurn_Mode:
121 return BLEND_MODE_COLOR_BURN;
122 case SkXfermode::kHardLight_Mode:
123 return BLEND_MODE_HARD_LIGHT;
124 case SkXfermode::kSoftLight_Mode:
125 return BLEND_MODE_SOFT_LIGHT;
126 case SkXfermode::kDifference_Mode:
127 return BLEND_MODE_DIFFERENCE;
128 case SkXfermode::kExclusion_Mode:
129 return BLEND_MODE_EXCLUSION;
130 case SkXfermode::kMultiply_Mode:
131 return BLEND_MODE_MULTIPLY;
132 case SkXfermode::kHue_Mode:
133 return BLEND_MODE_HUE;
134 case SkXfermode::kSaturation_Mode:
135 return BLEND_MODE_SATURATION;
136 case SkXfermode::kColor_Mode:
137 return BLEND_MODE_COLOR;
138 case SkXfermode::kLuminosity_Mode:
139 return BLEND_MODE_LUMINOSITY;
140 default:
141 NOTREACHED();
142 return BLEND_MODE_NONE;
146 // Smallest unit that impact anti-aliasing output. We use this to
147 // determine when anti-aliasing is unnecessary.
148 const float kAntiAliasingEpsilon = 1.0f / 1024.0f;
150 // Block or crash if the number of pending sync queries reach this high as
151 // something is seriously wrong on the service side if this happens.
152 const size_t kMaxPendingSyncQueries = 16;
154 } // anonymous namespace
156 static GLint GetActiveTextureUnit(GLES2Interface* gl) {
157 GLint active_unit = 0;
158 gl->GetIntegerv(GL_ACTIVE_TEXTURE, &active_unit);
159 return active_unit;
162 class GLRenderer::ScopedUseGrContext {
163 public:
164 static scoped_ptr<ScopedUseGrContext> Create(GLRenderer* renderer,
165 DrawingFrame* frame) {
166 // GrContext for filters is created lazily, and may fail if the context
167 // is lost.
168 // TODO(vmiura,bsalomon): crbug.com/487850 Ensure that
169 // ContextProvider::GrContext() does not return NULL.
170 if (renderer->output_surface_->context_provider()->GrContext())
171 return make_scoped_ptr(new ScopedUseGrContext(renderer, frame));
172 return nullptr;
175 ~ScopedUseGrContext() {
176 // Pass context control back to GLrenderer.
177 scoped_gpu_raster_ = nullptr;
178 renderer_->RestoreGLState();
179 renderer_->RestoreFramebuffer(frame_);
182 GrContext* context() const {
183 return renderer_->output_surface_->context_provider()->GrContext();
186 private:
187 ScopedUseGrContext(GLRenderer* renderer, DrawingFrame* frame)
188 : scoped_gpu_raster_(
189 new ScopedGpuRaster(renderer->output_surface_->context_provider())),
190 renderer_(renderer),
191 frame_(frame) {
192 // scoped_gpu_raster_ passes context control to Skia.
195 scoped_ptr<ScopedGpuRaster> scoped_gpu_raster_;
196 GLRenderer* renderer_;
197 DrawingFrame* frame_;
199 DISALLOW_COPY_AND_ASSIGN(ScopedUseGrContext);
202 struct GLRenderer::PendingAsyncReadPixels {
203 PendingAsyncReadPixels() : buffer(0) {}
205 scoped_ptr<CopyOutputRequest> copy_request;
206 base::CancelableClosure finished_read_pixels_callback;
207 unsigned buffer;
209 private:
210 DISALLOW_COPY_AND_ASSIGN(PendingAsyncReadPixels);
213 class GLRenderer::SyncQuery {
214 public:
215 explicit SyncQuery(gpu::gles2::GLES2Interface* gl)
216 : gl_(gl), query_id_(0u), is_pending_(false), weak_ptr_factory_(this) {
217 gl_->GenQueriesEXT(1, &query_id_);
219 virtual ~SyncQuery() { gl_->DeleteQueriesEXT(1, &query_id_); }
221 scoped_refptr<ResourceProvider::Fence> Begin() {
222 DCHECK(!IsPending());
223 // Invalidate weak pointer held by old fence.
224 weak_ptr_factory_.InvalidateWeakPtrs();
225 // Note: In case the set of drawing commands issued before End() do not
226 // depend on the query, defer BeginQueryEXT call until Set() is called and
227 // query is required.
228 return make_scoped_refptr<ResourceProvider::Fence>(
229 new Fence(weak_ptr_factory_.GetWeakPtr()));
232 void Set() {
233 if (is_pending_)
234 return;
236 // Note: BeginQueryEXT on GL_COMMANDS_COMPLETED_CHROMIUM is effectively a
237 // noop relative to GL, so it doesn't matter where it happens but we still
238 // make sure to issue this command when Set() is called (prior to issuing
239 // any drawing commands that depend on query), in case some future extension
240 // can take advantage of this.
241 gl_->BeginQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM, query_id_);
242 is_pending_ = true;
245 void End() {
246 if (!is_pending_)
247 return;
249 gl_->EndQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM);
252 bool IsPending() {
253 if (!is_pending_)
254 return false;
256 unsigned result_available = 1;
257 gl_->GetQueryObjectuivEXT(
258 query_id_, GL_QUERY_RESULT_AVAILABLE_EXT, &result_available);
259 is_pending_ = !result_available;
260 return is_pending_;
263 void Wait() {
264 if (!is_pending_)
265 return;
267 unsigned result = 0;
268 gl_->GetQueryObjectuivEXT(query_id_, GL_QUERY_RESULT_EXT, &result);
269 is_pending_ = false;
272 private:
273 class Fence : public ResourceProvider::Fence {
274 public:
275 explicit Fence(base::WeakPtr<GLRenderer::SyncQuery> query)
276 : query_(query) {}
278 // Overridden from ResourceProvider::Fence:
279 void Set() override {
280 DCHECK(query_);
281 query_->Set();
283 bool HasPassed() override { return !query_ || !query_->IsPending(); }
284 void Wait() override {
285 if (query_)
286 query_->Wait();
289 private:
290 ~Fence() override {}
292 base::WeakPtr<SyncQuery> query_;
294 DISALLOW_COPY_AND_ASSIGN(Fence);
297 gpu::gles2::GLES2Interface* gl_;
298 unsigned query_id_;
299 bool is_pending_;
300 base::WeakPtrFactory<SyncQuery> weak_ptr_factory_;
302 DISALLOW_COPY_AND_ASSIGN(SyncQuery);
305 scoped_ptr<GLRenderer> GLRenderer::Create(
306 RendererClient* client,
307 const RendererSettings* settings,
308 OutputSurface* output_surface,
309 ResourceProvider* resource_provider,
310 TextureMailboxDeleter* texture_mailbox_deleter,
311 int highp_threshold_min) {
312 return make_scoped_ptr(new GLRenderer(client,
313 settings,
314 output_surface,
315 resource_provider,
316 texture_mailbox_deleter,
317 highp_threshold_min));
320 GLRenderer::GLRenderer(RendererClient* client,
321 const RendererSettings* settings,
322 OutputSurface* output_surface,
323 ResourceProvider* resource_provider,
324 TextureMailboxDeleter* texture_mailbox_deleter,
325 int highp_threshold_min)
326 : DirectRenderer(client, settings, output_surface, resource_provider),
327 offscreen_framebuffer_id_(0),
328 shared_geometry_quad_(QuadVertexRect()),
329 gl_(output_surface->context_provider()->ContextGL()),
330 context_support_(output_surface->context_provider()->ContextSupport()),
331 texture_mailbox_deleter_(texture_mailbox_deleter),
332 is_backbuffer_discarded_(false),
333 is_scissor_enabled_(false),
334 scissor_rect_needs_reset_(true),
335 stencil_shadow_(false),
336 blend_shadow_(false),
337 highp_threshold_min_(highp_threshold_min),
338 highp_threshold_cache_(0),
339 use_sync_query_(false),
340 on_demand_tile_raster_resource_id_(0),
341 bound_geometry_(NO_BINDING) {
342 DCHECK(gl_);
343 DCHECK(context_support_);
345 ContextProvider::Capabilities context_caps =
346 output_surface_->context_provider()->ContextCapabilities();
348 capabilities_.using_partial_swap =
349 settings_->partial_swap_enabled && context_caps.gpu.post_sub_buffer;
351 DCHECK(!context_caps.gpu.iosurface || context_caps.gpu.texture_rectangle);
353 capabilities_.using_egl_image = context_caps.gpu.egl_image_external;
355 capabilities_.max_texture_size = resource_provider_->max_texture_size();
356 capabilities_.best_texture_format = resource_provider_->best_texture_format();
358 // The updater can access textures while the GLRenderer is using them.
359 capabilities_.allow_partial_texture_updates = true;
361 capabilities_.using_image = context_caps.gpu.image;
363 capabilities_.using_discard_framebuffer =
364 context_caps.gpu.discard_framebuffer;
366 capabilities_.allow_rasterize_on_demand = true;
367 capabilities_.max_msaa_samples = context_caps.gpu.max_samples;
369 use_sync_query_ = context_caps.gpu.sync_query;
370 use_blend_equation_advanced_ = context_caps.gpu.blend_equation_advanced;
371 use_blend_equation_advanced_coherent_ =
372 context_caps.gpu.blend_equation_advanced_coherent;
374 InitializeSharedObjects();
377 GLRenderer::~GLRenderer() {
378 while (!pending_async_read_pixels_.empty()) {
379 PendingAsyncReadPixels* pending_read = pending_async_read_pixels_.back();
380 pending_read->finished_read_pixels_callback.Cancel();
381 pending_async_read_pixels_.pop_back();
384 previous_swap_overlay_resources_.clear();
385 in_use_overlay_resources_.clear();
387 CleanupSharedObjects();
390 const RendererCapabilitiesImpl& GLRenderer::Capabilities() const {
391 return capabilities_;
394 void GLRenderer::DidChangeVisibility() {
395 EnforceMemoryPolicy();
397 context_support_->SetSurfaceVisible(visible());
399 // If we are not visible, we ask the context to aggressively free resources.
400 context_support_->SetAggressivelyFreeResources(!visible());
403 void GLRenderer::ReleaseRenderPassTextures() { render_pass_textures_.clear(); }
405 void GLRenderer::DiscardPixels() {
406 if (!capabilities_.using_discard_framebuffer)
407 return;
408 bool using_default_framebuffer =
409 !current_framebuffer_lock_ &&
410 output_surface_->capabilities().uses_default_gl_framebuffer;
411 GLenum attachments[] = {static_cast<GLenum>(
412 using_default_framebuffer ? GL_COLOR_EXT : GL_COLOR_ATTACHMENT0_EXT)};
413 gl_->DiscardFramebufferEXT(
414 GL_FRAMEBUFFER, arraysize(attachments), attachments);
417 void GLRenderer::PrepareSurfaceForPass(
418 DrawingFrame* frame,
419 SurfaceInitializationMode initialization_mode,
420 const gfx::Rect& render_pass_scissor) {
421 SetViewport();
423 switch (initialization_mode) {
424 case SURFACE_INITIALIZATION_MODE_PRESERVE:
425 EnsureScissorTestDisabled();
426 return;
427 case SURFACE_INITIALIZATION_MODE_FULL_SURFACE_CLEAR:
428 EnsureScissorTestDisabled();
429 DiscardPixels();
430 ClearFramebuffer(frame);
431 break;
432 case SURFACE_INITIALIZATION_MODE_SCISSORED_CLEAR:
433 SetScissorTestRect(render_pass_scissor);
434 ClearFramebuffer(frame);
435 break;
439 void GLRenderer::ClearFramebuffer(DrawingFrame* frame) {
440 // On DEBUG builds, opaque render passes are cleared to blue to easily see
441 // regions that were not drawn on the screen.
442 if (frame->current_render_pass->has_transparent_background)
443 gl_->ClearColor(0, 0, 0, 0);
444 else
445 gl_->ClearColor(0, 0, 1, 1);
447 bool always_clear = false;
448 #ifndef NDEBUG
449 always_clear = true;
450 #endif
451 if (always_clear || frame->current_render_pass->has_transparent_background) {
452 GLbitfield clear_bits = GL_COLOR_BUFFER_BIT;
453 if (always_clear)
454 clear_bits |= GL_STENCIL_BUFFER_BIT;
455 gl_->Clear(clear_bits);
459 void GLRenderer::BeginDrawingFrame(DrawingFrame* frame) {
460 TRACE_EVENT0("cc", "GLRenderer::BeginDrawingFrame");
462 scoped_refptr<ResourceProvider::Fence> read_lock_fence;
463 if (use_sync_query_) {
464 // Block until oldest sync query has passed if the number of pending queries
465 // ever reach kMaxPendingSyncQueries.
466 if (pending_sync_queries_.size() >= kMaxPendingSyncQueries) {
467 LOG(ERROR) << "Reached limit of pending sync queries.";
469 pending_sync_queries_.front()->Wait();
470 DCHECK(!pending_sync_queries_.front()->IsPending());
473 while (!pending_sync_queries_.empty()) {
474 if (pending_sync_queries_.front()->IsPending())
475 break;
477 available_sync_queries_.push_back(pending_sync_queries_.take_front());
480 current_sync_query_ = available_sync_queries_.empty()
481 ? make_scoped_ptr(new SyncQuery(gl_))
482 : available_sync_queries_.take_front();
484 read_lock_fence = current_sync_query_->Begin();
485 } else {
486 read_lock_fence =
487 make_scoped_refptr(new ResourceProvider::SynchronousFence(gl_));
489 resource_provider_->SetReadLockFence(read_lock_fence.get());
491 // Insert WaitSyncPointCHROMIUM on quad resources prior to drawing the frame,
492 // so that drawing can proceed without GL context switching interruptions.
493 ResourceProvider* resource_provider = resource_provider_;
494 for (const auto& pass : *frame->render_passes_in_draw_order) {
495 for (const auto& quad : pass->quad_list) {
496 for (ResourceId resource_id : quad->resources)
497 resource_provider->WaitSyncPointIfNeeded(resource_id);
501 // TODO(enne): Do we need to reinitialize all of this state per frame?
502 ReinitializeGLState();
505 void GLRenderer::DoNoOp() {
506 gl_->BindFramebuffer(GL_FRAMEBUFFER, 0);
507 gl_->Flush();
510 void GLRenderer::DoDrawQuad(DrawingFrame* frame,
511 const DrawQuad* quad,
512 const gfx::QuadF* clip_region) {
513 DCHECK(quad->rect.Contains(quad->visible_rect));
514 if (quad->material != DrawQuad::TEXTURE_CONTENT) {
515 FlushTextureQuadCache(SHARED_BINDING);
518 switch (quad->material) {
519 case DrawQuad::INVALID:
520 NOTREACHED();
521 break;
522 case DrawQuad::DEBUG_BORDER:
523 DrawDebugBorderQuad(frame, DebugBorderDrawQuad::MaterialCast(quad));
524 break;
525 case DrawQuad::IO_SURFACE_CONTENT:
526 DrawIOSurfaceQuad(frame, IOSurfaceDrawQuad::MaterialCast(quad),
527 clip_region);
528 break;
529 case DrawQuad::PICTURE_CONTENT:
530 // PictureDrawQuad should only be used for resourceless software draws.
531 NOTREACHED();
532 break;
533 case DrawQuad::RENDER_PASS:
534 DrawRenderPassQuad(frame, RenderPassDrawQuad::MaterialCast(quad),
535 clip_region);
536 break;
537 case DrawQuad::SOLID_COLOR:
538 DrawSolidColorQuad(frame, SolidColorDrawQuad::MaterialCast(quad),
539 clip_region);
540 break;
541 case DrawQuad::STREAM_VIDEO_CONTENT:
542 DrawStreamVideoQuad(frame, StreamVideoDrawQuad::MaterialCast(quad),
543 clip_region);
544 break;
545 case DrawQuad::SURFACE_CONTENT:
546 // Surface content should be fully resolved to other quad types before
547 // reaching a direct renderer.
548 NOTREACHED();
549 break;
550 case DrawQuad::TEXTURE_CONTENT:
551 EnqueueTextureQuad(frame, TextureDrawQuad::MaterialCast(quad),
552 clip_region);
553 break;
554 case DrawQuad::TILED_CONTENT:
555 DrawTileQuad(frame, TileDrawQuad::MaterialCast(quad), clip_region);
556 break;
557 case DrawQuad::YUV_VIDEO_CONTENT:
558 DrawYUVVideoQuad(frame, YUVVideoDrawQuad::MaterialCast(quad),
559 clip_region);
560 break;
564 // This function does not handle 3D sorting right now, since the debug border
565 // quads are just drawn as their original quads and not in split pieces. This
566 // results in some debug border quads drawing over foreground quads.
567 void GLRenderer::DrawDebugBorderQuad(const DrawingFrame* frame,
568 const DebugBorderDrawQuad* quad) {
569 SetBlendEnabled(quad->ShouldDrawWithBlending());
571 static float gl_matrix[16];
572 const DebugBorderProgram* program = GetDebugBorderProgram();
573 DCHECK(program && (program->initialized() || IsContextLost()));
574 SetUseProgram(program->program());
576 // Use the full quad_rect for debug quads to not move the edges based on
577 // partial swaps.
578 gfx::Rect layer_rect = quad->rect;
579 gfx::Transform render_matrix;
580 QuadRectTransform(&render_matrix,
581 quad->shared_quad_state->quad_to_target_transform,
582 gfx::RectF(layer_rect));
583 GLRenderer::ToGLMatrix(&gl_matrix[0],
584 frame->projection_matrix * render_matrix);
585 gl_->UniformMatrix4fv(program->vertex_shader().matrix_location(), 1, false,
586 &gl_matrix[0]);
588 SkColor color = quad->color;
589 float alpha = SkColorGetA(color) * (1.0f / 255.0f);
591 gl_->Uniform4f(program->fragment_shader().color_location(),
592 (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
593 (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
594 (SkColorGetB(color) * (1.0f / 255.0f)) * alpha, alpha);
596 gl_->LineWidth(quad->width);
598 // The indices for the line are stored in the same array as the triangle
599 // indices.
600 gl_->DrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, 0);
603 static skia::RefPtr<SkImage> ApplyImageFilter(
604 scoped_ptr<GLRenderer::ScopedUseGrContext> use_gr_context,
605 ResourceProvider* resource_provider,
606 const gfx::Rect& rect,
607 const gfx::Vector2dF& scale,
608 SkImageFilter* filter,
609 ScopedResource* source_texture_resource) {
610 if (!filter)
611 return skia::RefPtr<SkImage>();
613 if (!use_gr_context)
614 return skia::RefPtr<SkImage>();
616 ResourceProvider::ScopedReadLockGL lock(resource_provider,
617 source_texture_resource->id());
619 // Wrap the source texture in a Ganesh platform texture.
620 GrBackendTextureDesc backend_texture_description;
621 backend_texture_description.fWidth = source_texture_resource->size().width();
622 backend_texture_description.fHeight =
623 source_texture_resource->size().height();
624 backend_texture_description.fConfig = kSkia8888_GrPixelConfig;
625 backend_texture_description.fTextureHandle = lock.texture_id();
626 backend_texture_description.fOrigin = kBottomLeft_GrSurfaceOrigin;
627 skia::RefPtr<GrTexture> texture = skia::AdoptRef(
628 use_gr_context->context()->textureProvider()->wrapBackendTexture(
629 backend_texture_description));
630 if (!texture) {
631 TRACE_EVENT_INSTANT0("cc",
632 "ApplyImageFilter wrap background texture failed",
633 TRACE_EVENT_SCOPE_THREAD);
634 return skia::RefPtr<SkImage>();
637 SkImageInfo src_info =
638 SkImageInfo::MakeN32Premul(source_texture_resource->size().width(),
639 source_texture_resource->size().height());
640 // Place the platform texture inside an SkBitmap.
641 SkBitmap source;
642 source.setInfo(src_info);
643 skia::RefPtr<SkGrPixelRef> pixel_ref =
644 skia::AdoptRef(new SkGrPixelRef(src_info, texture.get()));
645 source.setPixelRef(pixel_ref.get());
647 // Create surface to draw into.
648 SkImageInfo dst_info =
649 SkImageInfo::MakeN32Premul(source.width(), source.height());
650 skia::RefPtr<SkSurface> surface = skia::AdoptRef(SkSurface::NewRenderTarget(
651 use_gr_context->context(), SkSurface::kYes_Budgeted, dst_info, 0));
652 if (!surface) {
653 TRACE_EVENT_INSTANT0("cc", "ApplyImageFilter surface allocation failed",
654 TRACE_EVENT_SCOPE_THREAD);
655 return skia::RefPtr<SkImage>();
657 skia::RefPtr<SkCanvas> canvas = skia::SharePtr(surface->getCanvas());
659 // Draw the source bitmap through the filter to the canvas.
660 SkPaint paint;
661 paint.setImageFilter(filter);
662 canvas->clear(SK_ColorTRANSPARENT);
664 // The origin of the filter is top-left and the origin of the source is
665 // bottom-left, but the orientation is the same, so we must translate the
666 // filter so that it renders at the bottom of the texture to avoid
667 // misregistration.
668 int y_translate = source.height() - rect.height() - rect.origin().y();
669 canvas->translate(-rect.origin().x(), y_translate);
670 canvas->scale(scale.x(), scale.y());
671 canvas->drawSprite(source, 0, 0, &paint);
673 skia::RefPtr<SkImage> image = skia::AdoptRef(surface->newImageSnapshot());
674 if (!image || !image->isTextureBacked()) {
675 return skia::RefPtr<SkImage>();
678 return image;
681 bool GLRenderer::CanApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode) {
682 return use_blend_equation_advanced_ ||
683 blend_mode == SkXfermode::kScreen_Mode ||
684 blend_mode == SkXfermode::kSrcOver_Mode;
687 void GLRenderer::ApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode) {
688 DCHECK(CanApplyBlendModeUsingBlendFunc(blend_mode));
690 // Any modes set here must be reset in RestoreBlendFuncToDefault
691 if (use_blend_equation_advanced_) {
692 GLenum equation = GL_FUNC_ADD;
694 switch (blend_mode) {
695 case SkXfermode::kScreen_Mode:
696 equation = GL_SCREEN_KHR;
697 break;
698 case SkXfermode::kOverlay_Mode:
699 equation = GL_OVERLAY_KHR;
700 break;
701 case SkXfermode::kDarken_Mode:
702 equation = GL_DARKEN_KHR;
703 break;
704 case SkXfermode::kLighten_Mode:
705 equation = GL_LIGHTEN_KHR;
706 break;
707 case SkXfermode::kColorDodge_Mode:
708 equation = GL_COLORDODGE_KHR;
709 break;
710 case SkXfermode::kColorBurn_Mode:
711 equation = GL_COLORBURN_KHR;
712 break;
713 case SkXfermode::kHardLight_Mode:
714 equation = GL_HARDLIGHT_KHR;
715 break;
716 case SkXfermode::kSoftLight_Mode:
717 equation = GL_SOFTLIGHT_KHR;
718 break;
719 case SkXfermode::kDifference_Mode:
720 equation = GL_DIFFERENCE_KHR;
721 break;
722 case SkXfermode::kExclusion_Mode:
723 equation = GL_EXCLUSION_KHR;
724 break;
725 case SkXfermode::kMultiply_Mode:
726 equation = GL_MULTIPLY_KHR;
727 break;
728 case SkXfermode::kHue_Mode:
729 equation = GL_HSL_HUE_KHR;
730 break;
731 case SkXfermode::kSaturation_Mode:
732 equation = GL_HSL_SATURATION_KHR;
733 break;
734 case SkXfermode::kColor_Mode:
735 equation = GL_HSL_COLOR_KHR;
736 break;
737 case SkXfermode::kLuminosity_Mode:
738 equation = GL_HSL_LUMINOSITY_KHR;
739 break;
740 default:
741 return;
744 gl_->BlendEquation(equation);
745 } else {
746 if (blend_mode == SkXfermode::kScreen_Mode) {
747 gl_->BlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE);
752 void GLRenderer::RestoreBlendFuncToDefault(SkXfermode::Mode blend_mode) {
753 if (blend_mode == SkXfermode::kSrcOver_Mode)
754 return;
756 if (use_blend_equation_advanced_) {
757 gl_->BlendEquation(GL_FUNC_ADD);
758 } else {
759 gl_->BlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
763 bool GLRenderer::ShouldApplyBackgroundFilters(const RenderPassDrawQuad* quad) {
764 if (quad->background_filters.IsEmpty())
765 return false;
767 // TODO(hendrikw): Look into allowing background filters to see pixels from
768 // other render targets. See crbug.com/314867.
770 return true;
773 // This takes a gfx::Rect and a clip region quad in the same space,
774 // and returns a quad with the same proportions in the space -0.5->0.5.
775 bool GetScaledRegion(const gfx::Rect& rect,
776 const gfx::QuadF* clip,
777 gfx::QuadF* scaled_region) {
778 if (!clip)
779 return false;
781 gfx::PointF p1(((clip->p1().x() - rect.x()) / rect.width()) - 0.5f,
782 ((clip->p1().y() - rect.y()) / rect.height()) - 0.5f);
783 gfx::PointF p2(((clip->p2().x() - rect.x()) / rect.width()) - 0.5f,
784 ((clip->p2().y() - rect.y()) / rect.height()) - 0.5f);
785 gfx::PointF p3(((clip->p3().x() - rect.x()) / rect.width()) - 0.5f,
786 ((clip->p3().y() - rect.y()) / rect.height()) - 0.5f);
787 gfx::PointF p4(((clip->p4().x() - rect.x()) / rect.width()) - 0.5f,
788 ((clip->p4().y() - rect.y()) / rect.height()) - 0.5f);
789 *scaled_region = gfx::QuadF(p1, p2, p3, p4);
790 return true;
793 // This takes a gfx::Rect and a clip region quad in the same space,
794 // and returns the proportional uv's in the space 0->1.
795 bool GetScaledUVs(const gfx::Rect& rect, const gfx::QuadF* clip, float uvs[8]) {
796 if (!clip)
797 return false;
799 uvs[0] = ((clip->p1().x() - rect.x()) / rect.width());
800 uvs[1] = ((clip->p1().y() - rect.y()) / rect.height());
801 uvs[2] = ((clip->p2().x() - rect.x()) / rect.width());
802 uvs[3] = ((clip->p2().y() - rect.y()) / rect.height());
803 uvs[4] = ((clip->p3().x() - rect.x()) / rect.width());
804 uvs[5] = ((clip->p3().y() - rect.y()) / rect.height());
805 uvs[6] = ((clip->p4().x() - rect.x()) / rect.width());
806 uvs[7] = ((clip->p4().y() - rect.y()) / rect.height());
807 return true;
810 gfx::Rect GLRenderer::GetBackdropBoundingBoxForRenderPassQuad(
811 DrawingFrame* frame,
812 const RenderPassDrawQuad* quad,
813 const gfx::Transform& contents_device_transform,
814 const gfx::QuadF* clip_region,
815 bool use_aa) {
816 gfx::QuadF scaled_region;
817 if (!GetScaledRegion(quad->rect, clip_region, &scaled_region)) {
818 scaled_region = SharedGeometryQuad().BoundingBox();
821 gfx::Rect backdrop_rect = gfx::ToEnclosingRect(MathUtil::MapClippedRect(
822 contents_device_transform, scaled_region.BoundingBox()));
824 if (ShouldApplyBackgroundFilters(quad)) {
825 int top, right, bottom, left;
826 quad->background_filters.GetOutsets(&top, &right, &bottom, &left);
827 backdrop_rect.Inset(-left, -top, -right, -bottom);
830 if (!backdrop_rect.IsEmpty() && use_aa) {
831 const int kOutsetForAntialiasing = 1;
832 backdrop_rect.Inset(-kOutsetForAntialiasing, -kOutsetForAntialiasing);
835 backdrop_rect.Intersect(MoveFromDrawToWindowSpace(
836 frame, frame->current_render_pass->output_rect));
837 return backdrop_rect;
840 scoped_ptr<ScopedResource> GLRenderer::GetBackdropTexture(
841 const gfx::Rect& bounding_rect) {
842 scoped_ptr<ScopedResource> device_background_texture =
843 ScopedResource::Create(resource_provider_);
844 // CopyTexImage2D fails when called on a texture having immutable storage.
845 device_background_texture->Allocate(
846 bounding_rect.size(), ResourceProvider::TEXTURE_HINT_DEFAULT, RGBA_8888);
848 ResourceProvider::ScopedWriteLockGL lock(resource_provider_,
849 device_background_texture->id());
850 GetFramebufferTexture(
851 lock.texture_id(), device_background_texture->format(), bounding_rect);
853 return device_background_texture.Pass();
856 skia::RefPtr<SkImage> GLRenderer::ApplyBackgroundFilters(
857 DrawingFrame* frame,
858 const RenderPassDrawQuad* quad,
859 ScopedResource* background_texture) {
860 DCHECK(ShouldApplyBackgroundFilters(quad));
861 skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
862 quad->background_filters, background_texture->size());
864 skia::RefPtr<SkImage> background_with_filters = ApplyImageFilter(
865 ScopedUseGrContext::Create(this, frame), resource_provider_, quad->rect,
866 quad->filters_scale, filter.get(), background_texture);
867 return background_with_filters;
870 void GLRenderer::DrawRenderPassQuad(DrawingFrame* frame,
871 const RenderPassDrawQuad* quad,
872 const gfx::QuadF* clip_region) {
873 ScopedResource* contents_texture =
874 render_pass_textures_.get(quad->render_pass_id);
875 DCHECK(contents_texture);
876 DCHECK(contents_texture->id());
878 gfx::Transform quad_rect_matrix;
879 QuadRectTransform(&quad_rect_matrix,
880 quad->shared_quad_state->quad_to_target_transform,
881 gfx::RectF(quad->rect));
882 gfx::Transform contents_device_transform =
883 frame->window_matrix * frame->projection_matrix * quad_rect_matrix;
884 contents_device_transform.FlattenTo2d();
886 // Can only draw surface if device matrix is invertible.
887 if (!contents_device_transform.IsInvertible())
888 return;
890 gfx::QuadF surface_quad = SharedGeometryQuad();
892 gfx::QuadF device_layer_quad;
893 bool use_aa = false;
894 if (settings_->allow_antialiasing) {
895 bool clipped = false;
896 device_layer_quad =
897 MathUtil::MapQuad(contents_device_transform, surface_quad, &clipped);
898 use_aa = ShouldAntialiasQuad(device_layer_quad, clipped,
899 settings_->force_antialiasing);
902 float edge[24];
903 const gfx::QuadF* aa_quad = use_aa ? &device_layer_quad : nullptr;
904 SetupRenderPassQuadForClippingAndAntialiasing(contents_device_transform, quad,
905 aa_quad, clip_region,
906 &surface_quad, edge);
907 SkXfermode::Mode blend_mode = quad->shared_quad_state->blend_mode;
908 bool use_shaders_for_blending =
909 !CanApplyBlendModeUsingBlendFunc(blend_mode) ||
910 ShouldApplyBackgroundFilters(quad) ||
911 settings_->force_blending_with_shaders;
913 scoped_ptr<ScopedResource> background_texture;
914 skia::RefPtr<SkImage> background_image;
915 GLuint background_image_id = 0;
916 gfx::Rect background_rect;
917 if (use_shaders_for_blending) {
918 // Compute a bounding box around the pixels that will be visible through
919 // the quad.
920 background_rect = GetBackdropBoundingBoxForRenderPassQuad(
921 frame, quad, contents_device_transform, clip_region, use_aa);
923 if (!background_rect.IsEmpty()) {
924 // The pixels from the filtered background should completely replace the
925 // current pixel values.
926 if (blend_enabled())
927 SetBlendEnabled(false);
929 // Read the pixels in the bounding box into a buffer R.
930 // This function allocates a texture, which should contribute to the
931 // amount of memory used by render surfaces:
932 // LayerTreeHost::CalculateMemoryForRenderSurfaces.
933 background_texture = GetBackdropTexture(background_rect);
935 if (ShouldApplyBackgroundFilters(quad) && background_texture) {
936 // Apply the background filters to R, so that it is applied in the
937 // pixels' coordinate space.
938 background_image =
939 ApplyBackgroundFilters(frame, quad, background_texture.get());
940 if (background_image)
941 background_image_id = background_image->getTextureHandle(true);
942 DCHECK(background_image_id);
946 if (!background_texture) {
947 // Something went wrong with reading the backdrop.
948 DCHECK(!background_image_id);
949 use_shaders_for_blending = false;
950 } else if (background_image_id) {
951 // Reset original background texture if there is not any mask
952 if (!quad->mask_resource_id())
953 background_texture.reset();
954 } else if (CanApplyBlendModeUsingBlendFunc(blend_mode) &&
955 ShouldApplyBackgroundFilters(quad)) {
956 // Something went wrong with applying background filters to the backdrop.
957 use_shaders_for_blending = false;
958 background_texture.reset();
961 // Need original background texture for mask?
962 bool mask_for_background =
963 background_texture && // Have original background texture
964 background_image_id && // Have filtered background texture
965 quad->mask_resource_id(); // Have mask texture
966 SetBlendEnabled(
967 !use_shaders_for_blending &&
968 (quad->ShouldDrawWithBlending() || !IsDefaultBlendMode(blend_mode)));
970 // TODO(senorblanco): Cache this value so that we don't have to do it for both
971 // the surface and its replica. Apply filters to the contents texture.
972 skia::RefPtr<SkImage> filter_image;
973 GLuint filter_image_id = 0;
974 SkScalar color_matrix[20];
975 bool use_color_matrix = false;
976 if (!quad->filters.IsEmpty()) {
977 skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
978 quad->filters, contents_texture->size());
979 if (filter) {
980 skia::RefPtr<SkColorFilter> cf;
983 SkColorFilter* colorfilter_rawptr = NULL;
984 filter->asColorFilter(&colorfilter_rawptr);
985 cf = skia::AdoptRef(colorfilter_rawptr);
988 if (cf && cf->asColorMatrix(color_matrix) && !filter->getInput(0)) {
989 // We have a single color matrix as a filter; apply it locally
990 // in the compositor.
991 use_color_matrix = true;
992 } else {
993 filter_image = ApplyImageFilter(
994 ScopedUseGrContext::Create(this, frame), resource_provider_,
995 quad->rect, quad->filters_scale, filter.get(), contents_texture);
996 if (filter_image) {
997 filter_image_id = filter_image->getTextureHandle(true);
998 DCHECK(filter_image_id);
1004 scoped_ptr<ResourceProvider::ScopedSamplerGL> mask_resource_lock;
1005 unsigned mask_texture_id = 0;
1006 SamplerType mask_sampler = SAMPLER_TYPE_NA;
1007 if (quad->mask_resource_id()) {
1008 mask_resource_lock.reset(new ResourceProvider::ScopedSamplerGL(
1009 resource_provider_, quad->mask_resource_id(), GL_TEXTURE1, GL_LINEAR));
1010 mask_texture_id = mask_resource_lock->texture_id();
1011 mask_sampler = SamplerTypeFromTextureTarget(mask_resource_lock->target());
1014 scoped_ptr<ResourceProvider::ScopedSamplerGL> contents_resource_lock;
1015 if (filter_image_id) {
1016 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
1017 gl_->BindTexture(GL_TEXTURE_2D, filter_image_id);
1018 } else {
1019 contents_resource_lock =
1020 make_scoped_ptr(new ResourceProvider::ScopedSamplerGL(
1021 resource_provider_, contents_texture->id(), GL_LINEAR));
1022 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
1023 contents_resource_lock->target());
1026 if (!use_shaders_for_blending) {
1027 if (!use_blend_equation_advanced_coherent_ && use_blend_equation_advanced_)
1028 gl_->BlendBarrierKHR();
1030 ApplyBlendModeUsingBlendFunc(blend_mode);
1033 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1034 gl_, &highp_threshold_cache_, highp_threshold_min_,
1035 quad->shared_quad_state->visible_quad_layer_rect.bottom_right());
1037 ShaderLocations locations;
1039 DCHECK_EQ(background_texture || background_image_id,
1040 use_shaders_for_blending);
1041 BlendMode shader_blend_mode = use_shaders_for_blending
1042 ? BlendModeFromSkXfermode(blend_mode)
1043 : BLEND_MODE_NONE;
1045 if (use_aa && mask_texture_id && !use_color_matrix) {
1046 const RenderPassMaskProgramAA* program = GetRenderPassMaskProgramAA(
1047 tex_coord_precision, mask_sampler,
1048 shader_blend_mode, mask_for_background);
1049 SetUseProgram(program->program());
1050 program->vertex_shader().FillLocations(&locations);
1051 program->fragment_shader().FillLocations(&locations);
1052 gl_->Uniform1i(locations.sampler, 0);
1053 } else if (!use_aa && mask_texture_id && !use_color_matrix) {
1054 const RenderPassMaskProgram* program = GetRenderPassMaskProgram(
1055 tex_coord_precision, mask_sampler,
1056 shader_blend_mode, mask_for_background);
1057 SetUseProgram(program->program());
1058 program->vertex_shader().FillLocations(&locations);
1059 program->fragment_shader().FillLocations(&locations);
1060 gl_->Uniform1i(locations.sampler, 0);
1061 } else if (use_aa && !mask_texture_id && !use_color_matrix) {
1062 const RenderPassProgramAA* program =
1063 GetRenderPassProgramAA(tex_coord_precision, shader_blend_mode);
1064 SetUseProgram(program->program());
1065 program->vertex_shader().FillLocations(&locations);
1066 program->fragment_shader().FillLocations(&locations);
1067 gl_->Uniform1i(locations.sampler, 0);
1068 } else if (use_aa && mask_texture_id && use_color_matrix) {
1069 const RenderPassMaskColorMatrixProgramAA* program =
1070 GetRenderPassMaskColorMatrixProgramAA(
1071 tex_coord_precision, mask_sampler,
1072 shader_blend_mode, mask_for_background);
1073 SetUseProgram(program->program());
1074 program->vertex_shader().FillLocations(&locations);
1075 program->fragment_shader().FillLocations(&locations);
1076 gl_->Uniform1i(locations.sampler, 0);
1077 } else if (use_aa && !mask_texture_id && use_color_matrix) {
1078 const RenderPassColorMatrixProgramAA* program =
1079 GetRenderPassColorMatrixProgramAA(tex_coord_precision,
1080 shader_blend_mode);
1081 SetUseProgram(program->program());
1082 program->vertex_shader().FillLocations(&locations);
1083 program->fragment_shader().FillLocations(&locations);
1084 gl_->Uniform1i(locations.sampler, 0);
1085 } else if (!use_aa && mask_texture_id && use_color_matrix) {
1086 const RenderPassMaskColorMatrixProgram* program =
1087 GetRenderPassMaskColorMatrixProgram(
1088 tex_coord_precision, mask_sampler,
1089 shader_blend_mode, mask_for_background);
1090 SetUseProgram(program->program());
1091 program->vertex_shader().FillLocations(&locations);
1092 program->fragment_shader().FillLocations(&locations);
1093 gl_->Uniform1i(locations.sampler, 0);
1094 } else if (!use_aa && !mask_texture_id && use_color_matrix) {
1095 const RenderPassColorMatrixProgram* program =
1096 GetRenderPassColorMatrixProgram(tex_coord_precision, shader_blend_mode);
1097 SetUseProgram(program->program());
1098 program->vertex_shader().FillLocations(&locations);
1099 program->fragment_shader().FillLocations(&locations);
1100 gl_->Uniform1i(locations.sampler, 0);
1101 } else {
1102 const RenderPassProgram* program =
1103 GetRenderPassProgram(tex_coord_precision, shader_blend_mode);
1104 SetUseProgram(program->program());
1105 program->vertex_shader().FillLocations(&locations);
1106 program->fragment_shader().FillLocations(&locations);
1107 gl_->Uniform1i(locations.sampler, 0);
1109 float tex_scale_x =
1110 quad->rect.width() / static_cast<float>(contents_texture->size().width());
1111 float tex_scale_y = quad->rect.height() /
1112 static_cast<float>(contents_texture->size().height());
1113 DCHECK_LE(tex_scale_x, 1.0f);
1114 DCHECK_LE(tex_scale_y, 1.0f);
1116 DCHECK(locations.tex_transform != -1 || IsContextLost());
1117 // Flip the content vertically in the shader, as the RenderPass input
1118 // texture is already oriented the same way as the framebuffer, but the
1119 // projection transform does a flip.
1120 gl_->Uniform4f(locations.tex_transform, 0.0f, tex_scale_y, tex_scale_x,
1121 -tex_scale_y);
1123 GLint last_texture_unit = 0;
1124 if (locations.mask_sampler != -1) {
1125 DCHECK_NE(locations.mask_tex_coord_scale, 1);
1126 DCHECK_NE(locations.mask_tex_coord_offset, 1);
1127 gl_->Uniform1i(locations.mask_sampler, 1);
1129 gfx::RectF mask_uv_rect = quad->MaskUVRect();
1130 if (mask_sampler != SAMPLER_TYPE_2D) {
1131 mask_uv_rect.Scale(quad->mask_texture_size.width(),
1132 quad->mask_texture_size.height());
1135 // Mask textures are oriented vertically flipped relative to the framebuffer
1136 // and the RenderPass contents texture, so we flip the tex coords from the
1137 // RenderPass texture to find the mask texture coords.
1138 gl_->Uniform2f(locations.mask_tex_coord_offset, mask_uv_rect.x(),
1139 mask_uv_rect.bottom());
1140 gl_->Uniform2f(locations.mask_tex_coord_scale,
1141 mask_uv_rect.width() / tex_scale_x,
1142 -mask_uv_rect.height() / tex_scale_y);
1144 last_texture_unit = 1;
1147 if (locations.edge != -1)
1148 gl_->Uniform3fv(locations.edge, 8, edge);
1150 if (locations.viewport != -1) {
1151 float viewport[4] = {
1152 static_cast<float>(current_window_space_viewport_.x()),
1153 static_cast<float>(current_window_space_viewport_.y()),
1154 static_cast<float>(current_window_space_viewport_.width()),
1155 static_cast<float>(current_window_space_viewport_.height()),
1157 gl_->Uniform4fv(locations.viewport, 1, viewport);
1160 if (locations.color_matrix != -1) {
1161 float matrix[16];
1162 for (int i = 0; i < 4; ++i) {
1163 for (int j = 0; j < 4; ++j)
1164 matrix[i * 4 + j] = SkScalarToFloat(color_matrix[j * 5 + i]);
1166 gl_->UniformMatrix4fv(locations.color_matrix, 1, false, matrix);
1168 static const float kScale = 1.0f / 255.0f;
1169 if (locations.color_offset != -1) {
1170 float offset[4];
1171 for (int i = 0; i < 4; ++i)
1172 offset[i] = SkScalarToFloat(color_matrix[i * 5 + 4]) * kScale;
1174 gl_->Uniform4fv(locations.color_offset, 1, offset);
1177 scoped_ptr<ResourceProvider::ScopedSamplerGL> shader_background_sampler_lock;
1178 if (locations.backdrop != -1) {
1179 DCHECK(background_texture || background_image_id);
1180 DCHECK_NE(locations.backdrop, 0);
1181 DCHECK_NE(locations.backdrop_rect, 0);
1183 gl_->Uniform1i(locations.backdrop, ++last_texture_unit);
1185 gl_->Uniform4f(locations.backdrop_rect, background_rect.x(),
1186 background_rect.y(), background_rect.width(),
1187 background_rect.height());
1189 if (background_image_id) {
1190 gl_->ActiveTexture(GL_TEXTURE0 + last_texture_unit);
1191 gl_->BindTexture(GL_TEXTURE_2D, background_image_id);
1192 gl_->ActiveTexture(GL_TEXTURE0);
1193 if (mask_for_background)
1194 gl_->Uniform1i(locations.original_backdrop, ++last_texture_unit);
1196 if (background_texture) {
1197 shader_background_sampler_lock = make_scoped_ptr(
1198 new ResourceProvider::ScopedSamplerGL(resource_provider_,
1199 background_texture->id(),
1200 GL_TEXTURE0 + last_texture_unit,
1201 GL_LINEAR));
1202 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
1203 shader_background_sampler_lock->target());
1207 SetShaderOpacity(quad->shared_quad_state->opacity, locations.alpha);
1208 SetShaderQuadF(surface_quad, locations.quad);
1209 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
1210 gfx::RectF(quad->rect), locations.matrix);
1212 // Flush the compositor context before the filter bitmap goes out of
1213 // scope, so the draw gets processed before the filter texture gets deleted.
1214 if (filter_image_id)
1215 gl_->Flush();
1217 if (!use_shaders_for_blending)
1218 RestoreBlendFuncToDefault(blend_mode);
1221 struct SolidColorProgramUniforms {
1222 unsigned program;
1223 unsigned matrix_location;
1224 unsigned viewport_location;
1225 unsigned quad_location;
1226 unsigned edge_location;
1227 unsigned color_location;
1230 template <class T>
1231 static void SolidColorUniformLocation(T program,
1232 SolidColorProgramUniforms* uniforms) {
1233 uniforms->program = program->program();
1234 uniforms->matrix_location = program->vertex_shader().matrix_location();
1235 uniforms->viewport_location = program->vertex_shader().viewport_location();
1236 uniforms->quad_location = program->vertex_shader().quad_location();
1237 uniforms->edge_location = program->vertex_shader().edge_location();
1238 uniforms->color_location = program->fragment_shader().color_location();
1241 namespace {
1242 // These functions determine if a quad, clipped by a clip_region contains
1243 // the entire {top|bottom|left|right} edge.
1244 bool is_top(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1245 if (!quad->IsTopEdge())
1246 return false;
1247 if (!clip_region)
1248 return true;
1250 return std::abs(clip_region->p1().y()) < kAntiAliasingEpsilon &&
1251 std::abs(clip_region->p2().y()) < kAntiAliasingEpsilon;
1254 bool is_bottom(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1255 if (!quad->IsBottomEdge())
1256 return false;
1257 if (!clip_region)
1258 return true;
1260 return std::abs(clip_region->p3().y() -
1261 quad->shared_quad_state->quad_layer_bounds.height()) <
1262 kAntiAliasingEpsilon &&
1263 std::abs(clip_region->p4().y() -
1264 quad->shared_quad_state->quad_layer_bounds.height()) <
1265 kAntiAliasingEpsilon;
1268 bool is_left(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1269 if (!quad->IsLeftEdge())
1270 return false;
1271 if (!clip_region)
1272 return true;
1274 return std::abs(clip_region->p1().x()) < kAntiAliasingEpsilon &&
1275 std::abs(clip_region->p4().x()) < kAntiAliasingEpsilon;
1278 bool is_right(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1279 if (!quad->IsRightEdge())
1280 return false;
1281 if (!clip_region)
1282 return true;
1284 return std::abs(clip_region->p2().x() -
1285 quad->shared_quad_state->quad_layer_bounds.width()) <
1286 kAntiAliasingEpsilon &&
1287 std::abs(clip_region->p3().x() -
1288 quad->shared_quad_state->quad_layer_bounds.width()) <
1289 kAntiAliasingEpsilon;
1291 } // anonymous namespace
1293 static gfx::QuadF GetDeviceQuadWithAntialiasingOnExteriorEdges(
1294 const LayerQuad& device_layer_edges,
1295 const gfx::Transform& device_transform,
1296 const gfx::QuadF& tile_quad,
1297 const gfx::QuadF* clip_region,
1298 const DrawQuad* quad) {
1299 gfx::RectF tile_rect = gfx::RectF(quad->visible_rect);
1301 gfx::PointF bottom_right = tile_quad.p3();
1302 gfx::PointF bottom_left = tile_quad.p4();
1303 gfx::PointF top_left = tile_quad.p1();
1304 gfx::PointF top_right = tile_quad.p2();
1305 bool clipped = false;
1307 // Map points to device space. We ignore |clipped|, since the result of
1308 // |MapPoint()| still produces a valid point to draw the quad with. When
1309 // clipped, the point will be outside of the viewport. See crbug.com/416367.
1310 bottom_right = MathUtil::MapPoint(device_transform, bottom_right, &clipped);
1311 bottom_left = MathUtil::MapPoint(device_transform, bottom_left, &clipped);
1312 top_left = MathUtil::MapPoint(device_transform, top_left, &clipped);
1313 top_right = MathUtil::MapPoint(device_transform, top_right, &clipped);
1315 LayerQuad::Edge bottom_edge(bottom_right, bottom_left);
1316 LayerQuad::Edge left_edge(bottom_left, top_left);
1317 LayerQuad::Edge top_edge(top_left, top_right);
1318 LayerQuad::Edge right_edge(top_right, bottom_right);
1320 // Only apply anti-aliasing to edges not clipped by culling or scissoring.
1321 // If an edge is degenerate we do not want to replace it with a "proper" edge
1322 // as that will cause the quad to possibly expand is strange ways.
1323 if (!top_edge.degenerate() && is_top(clip_region, quad) &&
1324 tile_rect.y() == quad->rect.y()) {
1325 top_edge = device_layer_edges.top();
1327 if (!left_edge.degenerate() && is_left(clip_region, quad) &&
1328 tile_rect.x() == quad->rect.x()) {
1329 left_edge = device_layer_edges.left();
1331 if (!right_edge.degenerate() && is_right(clip_region, quad) &&
1332 tile_rect.right() == quad->rect.right()) {
1333 right_edge = device_layer_edges.right();
1335 if (!bottom_edge.degenerate() && is_bottom(clip_region, quad) &&
1336 tile_rect.bottom() == quad->rect.bottom()) {
1337 bottom_edge = device_layer_edges.bottom();
1340 float sign = tile_quad.IsCounterClockwise() ? -1 : 1;
1341 bottom_edge.scale(sign);
1342 left_edge.scale(sign);
1343 top_edge.scale(sign);
1344 right_edge.scale(sign);
1346 // Create device space quad.
1347 return LayerQuad(left_edge, top_edge, right_edge, bottom_edge).ToQuadF();
1350 float GetTotalQuadError(const gfx::QuadF* clipped_quad,
1351 const gfx::QuadF* ideal_rect) {
1352 return (clipped_quad->p1() - ideal_rect->p1()).LengthSquared() +
1353 (clipped_quad->p2() - ideal_rect->p2()).LengthSquared() +
1354 (clipped_quad->p3() - ideal_rect->p3()).LengthSquared() +
1355 (clipped_quad->p4() - ideal_rect->p4()).LengthSquared();
1358 // Attempt to rotate the clipped quad until it lines up the most
1359 // correctly. This is necessary because we check the edges of this
1360 // quad against the expected left/right/top/bottom for anti-aliasing.
1361 void AlignQuadToBoundingBox(gfx::QuadF* clipped_quad) {
1362 gfx::QuadF bounding_quad = gfx::QuadF(clipped_quad->BoundingBox());
1363 gfx::QuadF best_rotation = *clipped_quad;
1364 float least_error_amount = GetTotalQuadError(clipped_quad, &bounding_quad);
1365 for (size_t i = 1; i < 4; ++i) {
1366 clipped_quad->Realign(1);
1367 float new_error = GetTotalQuadError(clipped_quad, &bounding_quad);
1368 if (new_error < least_error_amount) {
1369 least_error_amount = new_error;
1370 best_rotation = *clipped_quad;
1373 *clipped_quad = best_rotation;
1376 // Map device space quad to local space. Device_transform has no 3d
1377 // component since it was flattened, so we don't need to project. We should
1378 // have already checked that the transform was uninvertible before this call.
1379 gfx::QuadF MapQuadToLocalSpace(const gfx::Transform& device_transform,
1380 const gfx::QuadF& device_quad) {
1381 gfx::Transform inverse_device_transform(gfx::Transform::kSkipInitialization);
1382 DCHECK(device_transform.IsInvertible());
1383 bool did_invert = device_transform.GetInverse(&inverse_device_transform);
1384 DCHECK(did_invert);
1385 bool clipped = false;
1386 gfx::QuadF local_quad =
1387 MathUtil::MapQuad(inverse_device_transform, device_quad, &clipped);
1388 // We should not DCHECK(!clipped) here, because anti-aliasing inflation may
1389 // cause device_quad to become clipped. To our knowledge this scenario does
1390 // not need to be handled differently than the unclipped case.
1391 return local_quad;
1394 void InflateAntiAliasingDistances(const gfx::QuadF& quad,
1395 LayerQuad* device_layer_edges,
1396 float edge[24]) {
1397 DCHECK(!quad.BoundingBox().IsEmpty());
1398 LayerQuad device_layer_bounds(gfx::QuadF(quad.BoundingBox()));
1400 device_layer_edges->InflateAntiAliasingDistance();
1401 device_layer_edges->ToFloatArray(edge);
1403 device_layer_bounds.InflateAntiAliasingDistance();
1404 device_layer_bounds.ToFloatArray(&edge[12]);
1407 // static
1408 bool GLRenderer::ShouldAntialiasQuad(const gfx::QuadF& device_layer_quad,
1409 bool clipped,
1410 bool force_aa) {
1411 // AAing clipped quads is not supported by the code yet.
1412 if (clipped)
1413 return false;
1414 if (device_layer_quad.BoundingBox().IsEmpty())
1415 return false;
1416 if (force_aa)
1417 return true;
1419 bool is_axis_aligned_in_target = device_layer_quad.IsRectilinear();
1420 bool is_nearest_rect_within_epsilon =
1421 is_axis_aligned_in_target &&
1422 gfx::IsNearestRectWithinDistance(device_layer_quad.BoundingBox(),
1423 kAntiAliasingEpsilon);
1424 return !is_nearest_rect_within_epsilon;
1427 // static
1428 void GLRenderer::SetupQuadForClippingAndAntialiasing(
1429 const gfx::Transform& device_transform,
1430 const DrawQuad* quad,
1431 const gfx::QuadF* aa_quad,
1432 const gfx::QuadF* clip_region,
1433 gfx::QuadF* local_quad,
1434 float edge[24]) {
1435 gfx::QuadF rotated_clip;
1436 const gfx::QuadF* local_clip_region = clip_region;
1437 if (local_clip_region) {
1438 rotated_clip = *clip_region;
1439 AlignQuadToBoundingBox(&rotated_clip);
1440 local_clip_region = &rotated_clip;
1443 if (!aa_quad) {
1444 if (local_clip_region)
1445 *local_quad = *local_clip_region;
1446 return;
1449 LayerQuad device_layer_edges(*aa_quad);
1450 InflateAntiAliasingDistances(*aa_quad, &device_layer_edges, edge);
1452 // If we have a clip region then we are split, and therefore
1453 // by necessity, at least one of our edges is not an external
1454 // one.
1455 bool is_full_rect = quad->visible_rect == quad->rect;
1457 bool region_contains_all_outside_edges =
1458 is_full_rect &&
1459 (is_top(local_clip_region, quad) && is_left(local_clip_region, quad) &&
1460 is_bottom(local_clip_region, quad) && is_right(local_clip_region, quad));
1462 bool use_aa_on_all_four_edges =
1463 !local_clip_region && region_contains_all_outside_edges;
1465 gfx::QuadF device_quad;
1466 if (use_aa_on_all_four_edges) {
1467 device_quad = device_layer_edges.ToQuadF();
1468 } else {
1469 gfx::QuadF tile_quad(local_clip_region
1470 ? *local_clip_region
1471 : gfx::QuadF(gfx::RectF(quad->visible_rect)));
1472 device_quad = GetDeviceQuadWithAntialiasingOnExteriorEdges(
1473 device_layer_edges, device_transform, tile_quad, local_clip_region,
1474 quad);
1477 *local_quad = MapQuadToLocalSpace(device_transform, device_quad);
1480 // static
1481 void GLRenderer::SetupRenderPassQuadForClippingAndAntialiasing(
1482 const gfx::Transform& device_transform,
1483 const RenderPassDrawQuad* quad,
1484 const gfx::QuadF* aa_quad,
1485 const gfx::QuadF* clip_region,
1486 gfx::QuadF* local_quad,
1487 float edge[24]) {
1488 gfx::QuadF rotated_clip;
1489 const gfx::QuadF* local_clip_region = clip_region;
1490 if (local_clip_region) {
1491 rotated_clip = *clip_region;
1492 AlignQuadToBoundingBox(&rotated_clip);
1493 local_clip_region = &rotated_clip;
1496 if (!aa_quad) {
1497 GetScaledRegion(quad->rect, local_clip_region, local_quad);
1498 return;
1501 LayerQuad device_layer_edges(*aa_quad);
1502 InflateAntiAliasingDistances(*aa_quad, &device_layer_edges, edge);
1504 gfx::QuadF device_quad;
1506 // Apply anti-aliasing only to the edges that are not being clipped
1507 if (local_clip_region) {
1508 gfx::QuadF tile_quad(gfx::RectF(quad->visible_rect));
1509 GetScaledRegion(quad->rect, local_clip_region, &tile_quad);
1510 device_quad = GetDeviceQuadWithAntialiasingOnExteriorEdges(
1511 device_layer_edges, device_transform, tile_quad, local_clip_region,
1512 quad);
1513 } else {
1514 device_quad = device_layer_edges.ToQuadF();
1517 *local_quad = MapQuadToLocalSpace(device_transform, device_quad);
1520 void GLRenderer::DrawSolidColorQuad(const DrawingFrame* frame,
1521 const SolidColorDrawQuad* quad,
1522 const gfx::QuadF* clip_region) {
1523 gfx::Rect tile_rect = quad->visible_rect;
1525 SkColor color = quad->color;
1526 float opacity = quad->shared_quad_state->opacity;
1527 float alpha = (SkColorGetA(color) * (1.0f / 255.0f)) * opacity;
1529 // Early out if alpha is small enough that quad doesn't contribute to output.
1530 if (alpha < std::numeric_limits<float>::epsilon() &&
1531 quad->ShouldDrawWithBlending())
1532 return;
1534 gfx::Transform device_transform =
1535 frame->window_matrix * frame->projection_matrix *
1536 quad->shared_quad_state->quad_to_target_transform;
1537 device_transform.FlattenTo2d();
1538 if (!device_transform.IsInvertible())
1539 return;
1541 gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1543 gfx::QuadF device_layer_quad;
1544 bool use_aa = false;
1545 bool allow_aa = settings_->allow_antialiasing &&
1546 !quad->force_anti_aliasing_off && quad->IsEdge();
1548 if (allow_aa) {
1549 bool clipped = false;
1550 bool force_aa = false;
1551 device_layer_quad = MathUtil::MapQuad(
1552 device_transform,
1553 gfx::QuadF(
1554 gfx::RectF(quad->shared_quad_state->visible_quad_layer_rect)),
1555 &clipped);
1556 use_aa = ShouldAntialiasQuad(device_layer_quad, clipped, force_aa);
1559 float edge[24];
1560 const gfx::QuadF* aa_quad = use_aa ? &device_layer_quad : nullptr;
1561 SetupQuadForClippingAndAntialiasing(device_transform, quad, aa_quad,
1562 clip_region, &local_quad, edge);
1564 SolidColorProgramUniforms uniforms;
1565 if (use_aa) {
1566 SolidColorUniformLocation(GetSolidColorProgramAA(), &uniforms);
1567 } else {
1568 SolidColorUniformLocation(GetSolidColorProgram(), &uniforms);
1570 SetUseProgram(uniforms.program);
1572 gl_->Uniform4f(uniforms.color_location,
1573 (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
1574 (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
1575 (SkColorGetB(color) * (1.0f / 255.0f)) * alpha, alpha);
1576 if (use_aa) {
1577 float viewport[4] = {
1578 static_cast<float>(current_window_space_viewport_.x()),
1579 static_cast<float>(current_window_space_viewport_.y()),
1580 static_cast<float>(current_window_space_viewport_.width()),
1581 static_cast<float>(current_window_space_viewport_.height()),
1583 gl_->Uniform4fv(uniforms.viewport_location, 1, viewport);
1584 gl_->Uniform3fv(uniforms.edge_location, 8, edge);
1587 // Enable blending when the quad properties require it or if we decided
1588 // to use antialiasing.
1589 SetBlendEnabled(quad->ShouldDrawWithBlending() || use_aa);
1591 // Antialising requires a normalized quad, but this could lead to floating
1592 // point precision errors, so only normalize when antialising is on.
1593 if (use_aa) {
1594 // Normalize to tile_rect.
1595 local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1597 SetShaderQuadF(local_quad, uniforms.quad_location);
1599 // The transform and vertex data are used to figure out the extents that the
1600 // un-antialiased quad should have and which vertex this is and the float
1601 // quad passed in via uniform is the actual geometry that gets used to draw
1602 // it. This is why this centered rect is used and not the original
1603 // quad_rect.
1604 gfx::RectF centered_rect(
1605 gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1606 tile_rect.size());
1607 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
1608 centered_rect, uniforms.matrix_location);
1609 } else {
1610 PrepareGeometry(SHARED_BINDING);
1611 SetShaderQuadF(local_quad, uniforms.quad_location);
1612 static float gl_matrix[16];
1613 ToGLMatrix(&gl_matrix[0],
1614 frame->projection_matrix *
1615 quad->shared_quad_state->quad_to_target_transform);
1616 gl_->UniformMatrix4fv(uniforms.matrix_location, 1, false, &gl_matrix[0]);
1618 gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
1622 struct TileProgramUniforms {
1623 unsigned program;
1624 unsigned matrix_location;
1625 unsigned viewport_location;
1626 unsigned quad_location;
1627 unsigned edge_location;
1628 unsigned vertex_tex_transform_location;
1629 unsigned sampler_location;
1630 unsigned fragment_tex_transform_location;
1631 unsigned alpha_location;
1634 template <class T>
1635 static void TileUniformLocation(T program, TileProgramUniforms* uniforms) {
1636 uniforms->program = program->program();
1637 uniforms->matrix_location = program->vertex_shader().matrix_location();
1638 uniforms->viewport_location = program->vertex_shader().viewport_location();
1639 uniforms->quad_location = program->vertex_shader().quad_location();
1640 uniforms->edge_location = program->vertex_shader().edge_location();
1641 uniforms->vertex_tex_transform_location =
1642 program->vertex_shader().vertex_tex_transform_location();
1644 uniforms->sampler_location = program->fragment_shader().sampler_location();
1645 uniforms->alpha_location = program->fragment_shader().alpha_location();
1646 uniforms->fragment_tex_transform_location =
1647 program->fragment_shader().fragment_tex_transform_location();
1650 void GLRenderer::DrawTileQuad(const DrawingFrame* frame,
1651 const TileDrawQuad* quad,
1652 const gfx::QuadF* clip_region) {
1653 DrawContentQuad(frame, quad, quad->resource_id(), clip_region);
1656 void GLRenderer::DrawContentQuad(const DrawingFrame* frame,
1657 const ContentDrawQuadBase* quad,
1658 ResourceId resource_id,
1659 const gfx::QuadF* clip_region) {
1660 gfx::Transform device_transform =
1661 frame->window_matrix * frame->projection_matrix *
1662 quad->shared_quad_state->quad_to_target_transform;
1663 device_transform.FlattenTo2d();
1665 gfx::QuadF device_layer_quad;
1666 bool use_aa = false;
1667 bool allow_aa = settings_->allow_antialiasing && quad->IsEdge();
1668 if (allow_aa) {
1669 bool clipped = false;
1670 bool force_aa = false;
1671 device_layer_quad = MathUtil::MapQuad(
1672 device_transform,
1673 gfx::QuadF(
1674 gfx::RectF(quad->shared_quad_state->visible_quad_layer_rect)),
1675 &clipped);
1676 use_aa = ShouldAntialiasQuad(device_layer_quad, clipped, force_aa);
1679 // TODO(timav): simplify coordinate transformations in DrawContentQuadAA
1680 // similar to the way DrawContentQuadNoAA works and then consider
1681 // combining DrawContentQuadAA and DrawContentQuadNoAA into one method.
1682 if (use_aa)
1683 DrawContentQuadAA(frame, quad, resource_id, device_transform,
1684 device_layer_quad, clip_region);
1685 else
1686 DrawContentQuadNoAA(frame, quad, resource_id, clip_region);
1689 void GLRenderer::DrawContentQuadAA(const DrawingFrame* frame,
1690 const ContentDrawQuadBase* quad,
1691 ResourceId resource_id,
1692 const gfx::Transform& device_transform,
1693 const gfx::QuadF& aa_quad,
1694 const gfx::QuadF* clip_region) {
1695 if (!device_transform.IsInvertible())
1696 return;
1698 gfx::Rect tile_rect = quad->visible_rect;
1700 gfx::RectF tex_coord_rect = MathUtil::ScaleRectProportional(
1701 quad->tex_coord_rect, gfx::RectF(quad->rect), gfx::RectF(tile_rect));
1702 float tex_to_geom_scale_x = quad->rect.width() / quad->tex_coord_rect.width();
1703 float tex_to_geom_scale_y =
1704 quad->rect.height() / quad->tex_coord_rect.height();
1706 gfx::RectF clamp_geom_rect(tile_rect);
1707 gfx::RectF clamp_tex_rect(tex_coord_rect);
1708 // Clamp texture coordinates to avoid sampling outside the layer
1709 // by deflating the tile region half a texel or half a texel
1710 // minus epsilon for one pixel layers. The resulting clamp region
1711 // is mapped to the unit square by the vertex shader and mapped
1712 // back to normalized texture coordinates by the fragment shader
1713 // after being clamped to 0-1 range.
1714 float tex_clamp_x =
1715 std::min(0.5f, 0.5f * clamp_tex_rect.width() - kAntiAliasingEpsilon);
1716 float tex_clamp_y =
1717 std::min(0.5f, 0.5f * clamp_tex_rect.height() - kAntiAliasingEpsilon);
1718 float geom_clamp_x =
1719 std::min(tex_clamp_x * tex_to_geom_scale_x,
1720 0.5f * clamp_geom_rect.width() - kAntiAliasingEpsilon);
1721 float geom_clamp_y =
1722 std::min(tex_clamp_y * tex_to_geom_scale_y,
1723 0.5f * clamp_geom_rect.height() - kAntiAliasingEpsilon);
1724 clamp_geom_rect.Inset(geom_clamp_x, geom_clamp_y, geom_clamp_x, geom_clamp_y);
1725 clamp_tex_rect.Inset(tex_clamp_x, tex_clamp_y, tex_clamp_x, tex_clamp_y);
1727 // Map clamping rectangle to unit square.
1728 float vertex_tex_translate_x = -clamp_geom_rect.x() / clamp_geom_rect.width();
1729 float vertex_tex_translate_y =
1730 -clamp_geom_rect.y() / clamp_geom_rect.height();
1731 float vertex_tex_scale_x = tile_rect.width() / clamp_geom_rect.width();
1732 float vertex_tex_scale_y = tile_rect.height() / clamp_geom_rect.height();
1734 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1735 gl_, &highp_threshold_cache_, highp_threshold_min_, quad->texture_size);
1737 gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1738 float edge[24];
1739 SetupQuadForClippingAndAntialiasing(device_transform, quad, &aa_quad,
1740 clip_region, &local_quad, edge);
1741 ResourceProvider::ScopedSamplerGL quad_resource_lock(
1742 resource_provider_, resource_id,
1743 quad->nearest_neighbor ? GL_NEAREST : GL_LINEAR);
1744 SamplerType sampler =
1745 SamplerTypeFromTextureTarget(quad_resource_lock.target());
1747 float fragment_tex_translate_x = clamp_tex_rect.x();
1748 float fragment_tex_translate_y = clamp_tex_rect.y();
1749 float fragment_tex_scale_x = clamp_tex_rect.width();
1750 float fragment_tex_scale_y = clamp_tex_rect.height();
1752 // Map to normalized texture coordinates.
1753 if (sampler != SAMPLER_TYPE_2D_RECT) {
1754 gfx::Size texture_size = quad->texture_size;
1755 DCHECK(!texture_size.IsEmpty());
1756 fragment_tex_translate_x /= texture_size.width();
1757 fragment_tex_translate_y /= texture_size.height();
1758 fragment_tex_scale_x /= texture_size.width();
1759 fragment_tex_scale_y /= texture_size.height();
1762 TileProgramUniforms uniforms;
1763 if (quad->swizzle_contents) {
1764 TileUniformLocation(GetTileProgramSwizzleAA(tex_coord_precision, sampler),
1765 &uniforms);
1766 } else {
1767 TileUniformLocation(GetTileProgramAA(tex_coord_precision, sampler),
1768 &uniforms);
1771 SetUseProgram(uniforms.program);
1772 gl_->Uniform1i(uniforms.sampler_location, 0);
1774 float viewport[4] = {
1775 static_cast<float>(current_window_space_viewport_.x()),
1776 static_cast<float>(current_window_space_viewport_.y()),
1777 static_cast<float>(current_window_space_viewport_.width()),
1778 static_cast<float>(current_window_space_viewport_.height()),
1780 gl_->Uniform4fv(uniforms.viewport_location, 1, viewport);
1781 gl_->Uniform3fv(uniforms.edge_location, 8, edge);
1783 gl_->Uniform4f(uniforms.vertex_tex_transform_location, vertex_tex_translate_x,
1784 vertex_tex_translate_y, vertex_tex_scale_x,
1785 vertex_tex_scale_y);
1786 gl_->Uniform4f(uniforms.fragment_tex_transform_location,
1787 fragment_tex_translate_x, fragment_tex_translate_y,
1788 fragment_tex_scale_x, fragment_tex_scale_y);
1790 // Blending is required for antialiasing.
1791 SetBlendEnabled(true);
1793 // Normalize to tile_rect.
1794 local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1796 SetShaderOpacity(quad->shared_quad_state->opacity, uniforms.alpha_location);
1797 SetShaderQuadF(local_quad, uniforms.quad_location);
1799 // The transform and vertex data are used to figure out the extents that the
1800 // un-antialiased quad should have and which vertex this is and the float
1801 // quad passed in via uniform is the actual geometry that gets used to draw
1802 // it. This is why this centered rect is used and not the original quad_rect.
1803 gfx::RectF centered_rect(
1804 gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1805 tile_rect.size());
1806 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
1807 centered_rect, uniforms.matrix_location);
1810 void GLRenderer::DrawContentQuadNoAA(const DrawingFrame* frame,
1811 const ContentDrawQuadBase* quad,
1812 ResourceId resource_id,
1813 const gfx::QuadF* clip_region) {
1814 gfx::RectF tex_coord_rect = MathUtil::ScaleRectProportional(
1815 quad->tex_coord_rect, gfx::RectF(quad->rect),
1816 gfx::RectF(quad->visible_rect));
1817 float tex_to_geom_scale_x = quad->rect.width() / quad->tex_coord_rect.width();
1818 float tex_to_geom_scale_y =
1819 quad->rect.height() / quad->tex_coord_rect.height();
1821 bool scaled = (tex_to_geom_scale_x != 1.f || tex_to_geom_scale_y != 1.f);
1822 GLenum filter = (scaled ||
1823 !quad->shared_quad_state->quad_to_target_transform
1824 .IsIdentityOrIntegerTranslation()) &&
1825 !quad->nearest_neighbor
1826 ? GL_LINEAR
1827 : GL_NEAREST;
1829 ResourceProvider::ScopedSamplerGL quad_resource_lock(
1830 resource_provider_, resource_id, filter);
1831 SamplerType sampler =
1832 SamplerTypeFromTextureTarget(quad_resource_lock.target());
1834 float vertex_tex_translate_x = tex_coord_rect.x();
1835 float vertex_tex_translate_y = tex_coord_rect.y();
1836 float vertex_tex_scale_x = tex_coord_rect.width();
1837 float vertex_tex_scale_y = tex_coord_rect.height();
1839 // Map to normalized texture coordinates.
1840 if (sampler != SAMPLER_TYPE_2D_RECT) {
1841 gfx::Size texture_size = quad->texture_size;
1842 DCHECK(!texture_size.IsEmpty());
1843 vertex_tex_translate_x /= texture_size.width();
1844 vertex_tex_translate_y /= texture_size.height();
1845 vertex_tex_scale_x /= texture_size.width();
1846 vertex_tex_scale_y /= texture_size.height();
1849 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1850 gl_, &highp_threshold_cache_, highp_threshold_min_, quad->texture_size);
1852 TileProgramUniforms uniforms;
1853 if (quad->ShouldDrawWithBlending()) {
1854 if (quad->swizzle_contents) {
1855 TileUniformLocation(GetTileProgramSwizzle(tex_coord_precision, sampler),
1856 &uniforms);
1857 } else {
1858 TileUniformLocation(GetTileProgram(tex_coord_precision, sampler),
1859 &uniforms);
1861 } else {
1862 if (quad->swizzle_contents) {
1863 TileUniformLocation(
1864 GetTileProgramSwizzleOpaque(tex_coord_precision, sampler), &uniforms);
1865 } else {
1866 TileUniformLocation(GetTileProgramOpaque(tex_coord_precision, sampler),
1867 &uniforms);
1871 SetUseProgram(uniforms.program);
1872 gl_->Uniform1i(uniforms.sampler_location, 0);
1874 gl_->Uniform4f(uniforms.vertex_tex_transform_location, vertex_tex_translate_x,
1875 vertex_tex_translate_y, vertex_tex_scale_x,
1876 vertex_tex_scale_y);
1878 SetBlendEnabled(quad->ShouldDrawWithBlending());
1880 SetShaderOpacity(quad->shared_quad_state->opacity, uniforms.alpha_location);
1882 // Pass quad coordinates to the uniform in the same order as GeometryBinding
1883 // does, then vertices will match the texture mapping in the vertex buffer.
1884 // The method SetShaderQuadF() changes the order of vertices and so it's
1885 // not used here.
1886 gfx::QuadF tile_quad(gfx::RectF(quad->visible_rect));
1887 float width = quad->visible_rect.width();
1888 float height = quad->visible_rect.height();
1889 gfx::PointF top_left = quad->visible_rect.origin();
1890 if (clip_region) {
1891 tile_quad = *clip_region;
1892 float gl_uv[8] = {
1893 (tile_quad.p4().x() - top_left.x()) / width,
1894 (tile_quad.p4().y() - top_left.y()) / height,
1895 (tile_quad.p1().x() - top_left.x()) / width,
1896 (tile_quad.p1().y() - top_left.y()) / height,
1897 (tile_quad.p2().x() - top_left.x()) / width,
1898 (tile_quad.p2().y() - top_left.y()) / height,
1899 (tile_quad.p3().x() - top_left.x()) / width,
1900 (tile_quad.p3().y() - top_left.y()) / height,
1902 PrepareGeometry(CLIPPED_BINDING);
1903 clipped_geometry_->InitializeCustomQuadWithUVs(
1904 gfx::QuadF(gfx::RectF(quad->visible_rect)), gl_uv);
1905 } else {
1906 PrepareGeometry(SHARED_BINDING);
1908 float gl_quad[8] = {
1909 tile_quad.p4().x(), tile_quad.p4().y(), tile_quad.p1().x(),
1910 tile_quad.p1().y(), tile_quad.p2().x(), tile_quad.p2().y(),
1911 tile_quad.p3().x(), tile_quad.p3().y(),
1913 gl_->Uniform2fv(uniforms.quad_location, 4, gl_quad);
1915 static float gl_matrix[16];
1916 ToGLMatrix(&gl_matrix[0],
1917 frame->projection_matrix *
1918 quad->shared_quad_state->quad_to_target_transform);
1919 gl_->UniformMatrix4fv(uniforms.matrix_location, 1, false, &gl_matrix[0]);
1921 gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
1924 void GLRenderer::DrawYUVVideoQuad(const DrawingFrame* frame,
1925 const YUVVideoDrawQuad* quad,
1926 const gfx::QuadF* clip_region) {
1927 SetBlendEnabled(quad->ShouldDrawWithBlending());
1929 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1930 gl_, &highp_threshold_cache_, highp_threshold_min_,
1931 quad->shared_quad_state->visible_quad_layer_rect.bottom_right());
1933 bool use_alpha_plane = quad->a_plane_resource_id() != 0;
1935 ResourceProvider::ScopedSamplerGL y_plane_lock(
1936 resource_provider_, quad->y_plane_resource_id(), GL_TEXTURE1, GL_LINEAR);
1937 ResourceProvider::ScopedSamplerGL u_plane_lock(
1938 resource_provider_, quad->u_plane_resource_id(), GL_TEXTURE2, GL_LINEAR);
1939 DCHECK_EQ(y_plane_lock.target(), u_plane_lock.target());
1940 ResourceProvider::ScopedSamplerGL v_plane_lock(
1941 resource_provider_, quad->v_plane_resource_id(), GL_TEXTURE3, GL_LINEAR);
1942 DCHECK_EQ(y_plane_lock.target(), v_plane_lock.target());
1943 scoped_ptr<ResourceProvider::ScopedSamplerGL> a_plane_lock;
1944 if (use_alpha_plane) {
1945 a_plane_lock.reset(new ResourceProvider::ScopedSamplerGL(
1946 resource_provider_, quad->a_plane_resource_id(), GL_TEXTURE4,
1947 GL_LINEAR));
1948 DCHECK_EQ(y_plane_lock.target(), a_plane_lock->target());
1951 // All planes must have the same sampler type.
1952 SamplerType sampler = SamplerTypeFromTextureTarget(y_plane_lock.target());
1954 int matrix_location = -1;
1955 int ya_tex_scale_location = -1;
1956 int ya_tex_offset_location = -1;
1957 int uv_tex_scale_location = -1;
1958 int uv_tex_offset_location = -1;
1959 int ya_clamp_rect_location = -1;
1960 int uv_clamp_rect_location = -1;
1961 int y_texture_location = -1;
1962 int u_texture_location = -1;
1963 int v_texture_location = -1;
1964 int a_texture_location = -1;
1965 int yuv_matrix_location = -1;
1966 int yuv_adj_location = -1;
1967 int alpha_location = -1;
1968 if (use_alpha_plane) {
1969 const VideoYUVAProgram* program =
1970 GetVideoYUVAProgram(tex_coord_precision, sampler);
1971 DCHECK(program && (program->initialized() || IsContextLost()));
1972 SetUseProgram(program->program());
1973 matrix_location = program->vertex_shader().matrix_location();
1974 ya_tex_scale_location = program->vertex_shader().ya_tex_scale_location();
1975 ya_tex_offset_location = program->vertex_shader().ya_tex_offset_location();
1976 uv_tex_scale_location = program->vertex_shader().uv_tex_scale_location();
1977 uv_tex_offset_location = program->vertex_shader().uv_tex_offset_location();
1978 y_texture_location = program->fragment_shader().y_texture_location();
1979 u_texture_location = program->fragment_shader().u_texture_location();
1980 v_texture_location = program->fragment_shader().v_texture_location();
1981 a_texture_location = program->fragment_shader().a_texture_location();
1982 yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
1983 yuv_adj_location = program->fragment_shader().yuv_adj_location();
1984 ya_clamp_rect_location =
1985 program->fragment_shader().ya_clamp_rect_location();
1986 uv_clamp_rect_location =
1987 program->fragment_shader().uv_clamp_rect_location();
1988 alpha_location = program->fragment_shader().alpha_location();
1989 } else {
1990 const VideoYUVProgram* program =
1991 GetVideoYUVProgram(tex_coord_precision, sampler);
1992 DCHECK(program && (program->initialized() || IsContextLost()));
1993 SetUseProgram(program->program());
1994 matrix_location = program->vertex_shader().matrix_location();
1995 ya_tex_scale_location = program->vertex_shader().ya_tex_scale_location();
1996 ya_tex_offset_location = program->vertex_shader().ya_tex_offset_location();
1997 uv_tex_scale_location = program->vertex_shader().uv_tex_scale_location();
1998 uv_tex_offset_location = program->vertex_shader().uv_tex_offset_location();
1999 y_texture_location = program->fragment_shader().y_texture_location();
2000 u_texture_location = program->fragment_shader().u_texture_location();
2001 v_texture_location = program->fragment_shader().v_texture_location();
2002 yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
2003 yuv_adj_location = program->fragment_shader().yuv_adj_location();
2004 ya_clamp_rect_location =
2005 program->fragment_shader().ya_clamp_rect_location();
2006 uv_clamp_rect_location =
2007 program->fragment_shader().uv_clamp_rect_location();
2008 alpha_location = program->fragment_shader().alpha_location();
2011 gfx::SizeF ya_tex_scale(1.0f, 1.0f);
2012 gfx::SizeF uv_tex_scale(1.0f, 1.0f);
2013 if (sampler != SAMPLER_TYPE_2D_RECT) {
2014 DCHECK(!quad->ya_tex_size.IsEmpty());
2015 DCHECK(!quad->uv_tex_size.IsEmpty());
2016 ya_tex_scale = gfx::SizeF(1.0f / quad->ya_tex_size.width(),
2017 1.0f / quad->ya_tex_size.height());
2018 uv_tex_scale = gfx::SizeF(1.0f / quad->uv_tex_size.width(),
2019 1.0f / quad->uv_tex_size.height());
2022 float ya_vertex_tex_translate_x =
2023 quad->ya_tex_coord_rect.x() * ya_tex_scale.width();
2024 float ya_vertex_tex_translate_y =
2025 quad->ya_tex_coord_rect.y() * ya_tex_scale.height();
2026 float ya_vertex_tex_scale_x =
2027 quad->ya_tex_coord_rect.width() * ya_tex_scale.width();
2028 float ya_vertex_tex_scale_y =
2029 quad->ya_tex_coord_rect.height() * ya_tex_scale.height();
2031 float uv_vertex_tex_translate_x =
2032 quad->uv_tex_coord_rect.x() * uv_tex_scale.width();
2033 float uv_vertex_tex_translate_y =
2034 quad->uv_tex_coord_rect.y() * uv_tex_scale.height();
2035 float uv_vertex_tex_scale_x =
2036 quad->uv_tex_coord_rect.width() * uv_tex_scale.width();
2037 float uv_vertex_tex_scale_y =
2038 quad->uv_tex_coord_rect.height() * uv_tex_scale.height();
2040 gl_->Uniform2f(ya_tex_scale_location, ya_vertex_tex_scale_x,
2041 ya_vertex_tex_scale_y);
2042 gl_->Uniform2f(ya_tex_offset_location, ya_vertex_tex_translate_x,
2043 ya_vertex_tex_translate_y);
2044 gl_->Uniform2f(uv_tex_scale_location, uv_vertex_tex_scale_x,
2045 uv_vertex_tex_scale_y);
2046 gl_->Uniform2f(uv_tex_offset_location, uv_vertex_tex_translate_x,
2047 uv_vertex_tex_translate_y);
2049 gfx::RectF ya_clamp_rect(ya_vertex_tex_translate_x, ya_vertex_tex_translate_y,
2050 ya_vertex_tex_scale_x, ya_vertex_tex_scale_y);
2051 ya_clamp_rect.Inset(0.5f * ya_tex_scale.width(),
2052 0.5f * ya_tex_scale.height());
2053 gfx::RectF uv_clamp_rect(uv_vertex_tex_translate_x, uv_vertex_tex_translate_y,
2054 uv_vertex_tex_scale_x, uv_vertex_tex_scale_y);
2055 uv_clamp_rect.Inset(0.5f * uv_tex_scale.width(),
2056 0.5f * uv_tex_scale.height());
2057 gl_->Uniform4f(ya_clamp_rect_location, ya_clamp_rect.x(), ya_clamp_rect.y(),
2058 ya_clamp_rect.right(), ya_clamp_rect.bottom());
2059 gl_->Uniform4f(uv_clamp_rect_location, uv_clamp_rect.x(), uv_clamp_rect.y(),
2060 uv_clamp_rect.right(), uv_clamp_rect.bottom());
2062 gl_->Uniform1i(y_texture_location, 1);
2063 gl_->Uniform1i(u_texture_location, 2);
2064 gl_->Uniform1i(v_texture_location, 3);
2065 if (use_alpha_plane)
2066 gl_->Uniform1i(a_texture_location, 4);
2068 // These values are magic numbers that are used in the transformation from YUV
2069 // to RGB color values. They are taken from the following webpage:
2070 // http://www.fourcc.org/fccyvrgb.php
2071 float yuv_to_rgb_rec601[9] = {
2072 1.164f, 1.164f, 1.164f, 0.0f, -.391f, 2.018f, 1.596f, -.813f, 0.0f,
2074 float yuv_to_rgb_jpeg[9] = {
2075 1.f, 1.f, 1.f, 0.0f, -.34414f, 1.772f, 1.402f, -.71414f, 0.0f,
2077 float yuv_to_rgb_rec709[9] = {
2078 1.164f, 1.164f, 1.164f, 0.0f, -0.213f, 2.112f, 1.793f, -0.533f, 0.0f,
2081 // These values map to 16, 128, and 128 respectively, and are computed
2082 // as a fraction over 256 (e.g. 16 / 256 = 0.0625).
2083 // They are used in the YUV to RGBA conversion formula:
2084 // Y - 16 : Gives 16 values of head and footroom for overshooting
2085 // U - 128 : Turns unsigned U into signed U [-128,127]
2086 // V - 128 : Turns unsigned V into signed V [-128,127]
2087 float yuv_adjust_constrained[3] = {
2088 -0.0625f, -0.5f, -0.5f,
2091 // Same as above, but without the head and footroom.
2092 float yuv_adjust_full[3] = {
2093 0.0f, -0.5f, -0.5f,
2096 float* yuv_to_rgb = NULL;
2097 float* yuv_adjust = NULL;
2099 switch (quad->color_space) {
2100 case YUVVideoDrawQuad::REC_601:
2101 yuv_to_rgb = yuv_to_rgb_rec601;
2102 yuv_adjust = yuv_adjust_constrained;
2103 break;
2104 case YUVVideoDrawQuad::REC_709:
2105 yuv_to_rgb = yuv_to_rgb_rec709;
2106 yuv_adjust = yuv_adjust_constrained;
2107 break;
2108 case YUVVideoDrawQuad::JPEG:
2109 yuv_to_rgb = yuv_to_rgb_jpeg;
2110 yuv_adjust = yuv_adjust_full;
2111 break;
2114 // The transform and vertex data are used to figure out the extents that the
2115 // un-antialiased quad should have and which vertex this is and the float
2116 // quad passed in via uniform is the actual geometry that gets used to draw
2117 // it. This is why this centered rect is used and not the original quad_rect.
2118 gfx::RectF tile_rect = gfx::RectF(quad->rect);
2119 gl_->UniformMatrix3fv(yuv_matrix_location, 1, 0, yuv_to_rgb);
2120 gl_->Uniform3fv(yuv_adj_location, 1, yuv_adjust);
2122 SetShaderOpacity(quad->shared_quad_state->opacity, alpha_location);
2123 if (!clip_region) {
2124 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
2125 tile_rect, matrix_location);
2126 } else {
2127 float uvs[8] = {0};
2128 GetScaledUVs(quad->visible_rect, clip_region, uvs);
2129 gfx::QuadF region_quad = *clip_region;
2130 region_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
2131 region_quad -= gfx::Vector2dF(0.5f, 0.5f);
2132 DrawQuadGeometryClippedByQuadF(
2133 frame, quad->shared_quad_state->quad_to_target_transform, tile_rect,
2134 region_quad, matrix_location, uvs);
2138 void GLRenderer::DrawStreamVideoQuad(const DrawingFrame* frame,
2139 const StreamVideoDrawQuad* quad,
2140 const gfx::QuadF* clip_region) {
2141 SetBlendEnabled(quad->ShouldDrawWithBlending());
2143 static float gl_matrix[16];
2145 DCHECK(capabilities_.using_egl_image);
2147 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2148 gl_, &highp_threshold_cache_, highp_threshold_min_,
2149 quad->shared_quad_state->visible_quad_layer_rect.bottom_right());
2151 const VideoStreamTextureProgram* program =
2152 GetVideoStreamTextureProgram(tex_coord_precision);
2153 SetUseProgram(program->program());
2155 ToGLMatrix(&gl_matrix[0], quad->matrix);
2156 gl_->UniformMatrix4fv(program->vertex_shader().tex_matrix_location(), 1,
2157 false, gl_matrix);
2159 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
2160 quad->resource_id());
2161 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2162 gl_->BindTexture(GL_TEXTURE_EXTERNAL_OES, lock.texture_id());
2164 gl_->Uniform1i(program->fragment_shader().sampler_location(), 0);
2166 SetShaderOpacity(quad->shared_quad_state->opacity,
2167 program->fragment_shader().alpha_location());
2168 if (!clip_region) {
2169 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
2170 gfx::RectF(quad->rect),
2171 program->vertex_shader().matrix_location());
2172 } else {
2173 gfx::QuadF region_quad(*clip_region);
2174 region_quad.Scale(1.0f / quad->rect.width(), 1.0f / quad->rect.height());
2175 region_quad -= gfx::Vector2dF(0.5f, 0.5f);
2176 float uvs[8] = {0};
2177 GetScaledUVs(quad->visible_rect, clip_region, uvs);
2178 DrawQuadGeometryClippedByQuadF(
2179 frame, quad->shared_quad_state->quad_to_target_transform,
2180 gfx::RectF(quad->rect), region_quad,
2181 program->vertex_shader().matrix_location(), uvs);
2185 struct TextureProgramBinding {
2186 template <class Program>
2187 void Set(Program* program) {
2188 DCHECK(program);
2189 program_id = program->program();
2190 sampler_location = program->fragment_shader().sampler_location();
2191 matrix_location = program->vertex_shader().matrix_location();
2192 background_color_location =
2193 program->fragment_shader().background_color_location();
2195 int program_id;
2196 int sampler_location;
2197 int matrix_location;
2198 int transform_location;
2199 int background_color_location;
2202 struct TexTransformTextureProgramBinding : TextureProgramBinding {
2203 template <class Program>
2204 void Set(Program* program) {
2205 TextureProgramBinding::Set(program);
2206 tex_transform_location = program->vertex_shader().tex_transform_location();
2207 vertex_opacity_location =
2208 program->vertex_shader().vertex_opacity_location();
2210 int tex_transform_location;
2211 int vertex_opacity_location;
2214 void GLRenderer::FlushTextureQuadCache(BoundGeometry flush_binding) {
2215 // Check to see if we have anything to draw.
2216 if (draw_cache_.program_id == -1)
2217 return;
2219 PrepareGeometry(flush_binding);
2221 // Set the correct blending mode.
2222 SetBlendEnabled(draw_cache_.needs_blending);
2224 // Bind the program to the GL state.
2225 SetUseProgram(draw_cache_.program_id);
2227 // Bind the correct texture sampler location.
2228 gl_->Uniform1i(draw_cache_.sampler_location, 0);
2230 // Assume the current active textures is 0.
2231 ResourceProvider::ScopedSamplerGL locked_quad(
2232 resource_provider_,
2233 draw_cache_.resource_id,
2234 draw_cache_.nearest_neighbor ? GL_NEAREST : GL_LINEAR);
2235 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2236 gl_->BindTexture(locked_quad.target(), locked_quad.texture_id());
2238 static_assert(sizeof(Float4) == 4 * sizeof(float),
2239 "Float4 struct should be densely packed");
2240 static_assert(sizeof(Float16) == 16 * sizeof(float),
2241 "Float16 struct should be densely packed");
2243 // Upload the tranforms for both points and uvs.
2244 gl_->UniformMatrix4fv(
2245 static_cast<int>(draw_cache_.matrix_location),
2246 static_cast<int>(draw_cache_.matrix_data.size()), false,
2247 reinterpret_cast<float*>(&draw_cache_.matrix_data.front()));
2248 gl_->Uniform4fv(static_cast<int>(draw_cache_.uv_xform_location),
2249 static_cast<int>(draw_cache_.uv_xform_data.size()),
2250 reinterpret_cast<float*>(&draw_cache_.uv_xform_data.front()));
2252 if (draw_cache_.background_color != SK_ColorTRANSPARENT) {
2253 Float4 background_color = PremultipliedColor(draw_cache_.background_color);
2254 gl_->Uniform4fv(draw_cache_.background_color_location, 1,
2255 background_color.data);
2258 gl_->Uniform1fv(
2259 static_cast<int>(draw_cache_.vertex_opacity_location),
2260 static_cast<int>(draw_cache_.vertex_opacity_data.size()),
2261 static_cast<float*>(&draw_cache_.vertex_opacity_data.front()));
2263 DCHECK_LE(draw_cache_.matrix_data.size(),
2264 static_cast<size_t>(std::numeric_limits<int>::max()) / 6u);
2265 // Draw the quads!
2266 gl_->DrawElements(GL_TRIANGLES,
2267 6 * static_cast<int>(draw_cache_.matrix_data.size()),
2268 GL_UNSIGNED_SHORT, 0);
2270 // Clear the cache.
2271 draw_cache_.program_id = -1;
2272 draw_cache_.uv_xform_data.resize(0);
2273 draw_cache_.vertex_opacity_data.resize(0);
2274 draw_cache_.matrix_data.resize(0);
2276 // If we had a clipped binding, prepare the shared binding for the
2277 // next inserts.
2278 if (flush_binding == CLIPPED_BINDING) {
2279 PrepareGeometry(SHARED_BINDING);
2283 void GLRenderer::EnqueueTextureQuad(const DrawingFrame* frame,
2284 const TextureDrawQuad* quad,
2285 const gfx::QuadF* clip_region) {
2286 // If we have a clip_region then we have to render the next quad
2287 // with dynamic geometry, therefore we must flush all pending
2288 // texture quads.
2289 if (clip_region) {
2290 // We send in false here because we want to flush what's currently in the
2291 // queue using the shared_geometry and not clipped_geometry
2292 FlushTextureQuadCache(SHARED_BINDING);
2295 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2296 gl_, &highp_threshold_cache_, highp_threshold_min_,
2297 quad->shared_quad_state->visible_quad_layer_rect.bottom_right());
2299 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
2300 quad->resource_id());
2301 const SamplerType sampler = SamplerTypeFromTextureTarget(lock.target());
2302 // Choose the correct texture program binding
2303 TexTransformTextureProgramBinding binding;
2304 if (quad->premultiplied_alpha) {
2305 if (quad->background_color == SK_ColorTRANSPARENT) {
2306 binding.Set(GetTextureProgram(tex_coord_precision, sampler));
2307 } else {
2308 binding.Set(GetTextureBackgroundProgram(tex_coord_precision, sampler));
2310 } else {
2311 if (quad->background_color == SK_ColorTRANSPARENT) {
2312 binding.Set(
2313 GetNonPremultipliedTextureProgram(tex_coord_precision, sampler));
2314 } else {
2315 binding.Set(GetNonPremultipliedTextureBackgroundProgram(
2316 tex_coord_precision, sampler));
2320 int resource_id = quad->resource_id();
2322 if (draw_cache_.program_id != binding.program_id ||
2323 draw_cache_.resource_id != resource_id ||
2324 draw_cache_.needs_blending != quad->ShouldDrawWithBlending() ||
2325 draw_cache_.nearest_neighbor != quad->nearest_neighbor ||
2326 draw_cache_.background_color != quad->background_color ||
2327 draw_cache_.matrix_data.size() >= 8) {
2328 FlushTextureQuadCache(SHARED_BINDING);
2329 draw_cache_.program_id = binding.program_id;
2330 draw_cache_.resource_id = resource_id;
2331 draw_cache_.needs_blending = quad->ShouldDrawWithBlending();
2332 draw_cache_.nearest_neighbor = quad->nearest_neighbor;
2333 draw_cache_.background_color = quad->background_color;
2335 draw_cache_.uv_xform_location = binding.tex_transform_location;
2336 draw_cache_.background_color_location = binding.background_color_location;
2337 draw_cache_.vertex_opacity_location = binding.vertex_opacity_location;
2338 draw_cache_.matrix_location = binding.matrix_location;
2339 draw_cache_.sampler_location = binding.sampler_location;
2342 // Generate the uv-transform
2343 if (!clip_region) {
2344 draw_cache_.uv_xform_data.push_back(UVTransform(quad));
2345 } else {
2346 Float4 uv_transform = {{0.0f, 0.0f, 1.0f, 1.0f}};
2347 draw_cache_.uv_xform_data.push_back(uv_transform);
2350 // Generate the vertex opacity
2351 const float opacity = quad->shared_quad_state->opacity;
2352 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[0] * opacity);
2353 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[1] * opacity);
2354 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[2] * opacity);
2355 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[3] * opacity);
2357 // Generate the transform matrix
2358 gfx::Transform quad_rect_matrix;
2359 QuadRectTransform(&quad_rect_matrix,
2360 quad->shared_quad_state->quad_to_target_transform,
2361 gfx::RectF(quad->rect));
2362 quad_rect_matrix = frame->projection_matrix * quad_rect_matrix;
2364 Float16 m;
2365 quad_rect_matrix.matrix().asColMajorf(m.data);
2366 draw_cache_.matrix_data.push_back(m);
2368 if (clip_region) {
2369 gfx::QuadF scaled_region;
2370 if (!GetScaledRegion(quad->rect, clip_region, &scaled_region)) {
2371 scaled_region = SharedGeometryQuad().BoundingBox();
2373 // Both the scaled region and the SharedGeomtryQuad are in the space
2374 // -0.5->0.5. We need to move that to the space 0->1.
2375 float uv[8];
2376 uv[0] = scaled_region.p1().x() + 0.5f;
2377 uv[1] = scaled_region.p1().y() + 0.5f;
2378 uv[2] = scaled_region.p2().x() + 0.5f;
2379 uv[3] = scaled_region.p2().y() + 0.5f;
2380 uv[4] = scaled_region.p3().x() + 0.5f;
2381 uv[5] = scaled_region.p3().y() + 0.5f;
2382 uv[6] = scaled_region.p4().x() + 0.5f;
2383 uv[7] = scaled_region.p4().y() + 0.5f;
2384 PrepareGeometry(CLIPPED_BINDING);
2385 clipped_geometry_->InitializeCustomQuadWithUVs(scaled_region, uv);
2386 FlushTextureQuadCache(CLIPPED_BINDING);
2390 void GLRenderer::DrawIOSurfaceQuad(const DrawingFrame* frame,
2391 const IOSurfaceDrawQuad* quad,
2392 const gfx::QuadF* clip_region) {
2393 SetBlendEnabled(quad->ShouldDrawWithBlending());
2395 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2396 gl_, &highp_threshold_cache_, highp_threshold_min_,
2397 quad->shared_quad_state->visible_quad_layer_rect.bottom_right());
2399 TexTransformTextureProgramBinding binding;
2400 binding.Set(GetTextureIOSurfaceProgram(tex_coord_precision));
2402 SetUseProgram(binding.program_id);
2403 gl_->Uniform1i(binding.sampler_location, 0);
2404 if (quad->orientation == IOSurfaceDrawQuad::FLIPPED) {
2405 gl_->Uniform4f(
2406 binding.tex_transform_location, 0, quad->io_surface_size.height(),
2407 quad->io_surface_size.width(), quad->io_surface_size.height() * -1.0f);
2408 } else {
2409 gl_->Uniform4f(binding.tex_transform_location, 0, 0,
2410 quad->io_surface_size.width(),
2411 quad->io_surface_size.height());
2414 const float vertex_opacity[] = {quad->shared_quad_state->opacity,
2415 quad->shared_quad_state->opacity,
2416 quad->shared_quad_state->opacity,
2417 quad->shared_quad_state->opacity};
2418 gl_->Uniform1fv(binding.vertex_opacity_location, 4, vertex_opacity);
2420 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
2421 quad->io_surface_resource_id());
2422 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2423 gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, lock.texture_id());
2425 if (!clip_region) {
2426 DrawQuadGeometry(frame, quad->shared_quad_state->quad_to_target_transform,
2427 gfx::RectF(quad->rect), binding.matrix_location);
2428 } else {
2429 float uvs[8] = {0};
2430 GetScaledUVs(quad->visible_rect, clip_region, uvs);
2431 DrawQuadGeometryClippedByQuadF(
2432 frame, quad->shared_quad_state->quad_to_target_transform,
2433 gfx::RectF(quad->rect), *clip_region, binding.matrix_location, uvs);
2436 gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
2439 void GLRenderer::FinishDrawingFrame(DrawingFrame* frame) {
2440 if (use_sync_query_) {
2441 DCHECK(current_sync_query_);
2442 current_sync_query_->End();
2443 pending_sync_queries_.push_back(current_sync_query_.Pass());
2446 current_framebuffer_lock_ = nullptr;
2447 swap_buffer_rect_.Union(frame->root_damage_rect);
2449 gl_->Disable(GL_BLEND);
2450 blend_shadow_ = false;
2452 ScheduleOverlays(frame);
2455 void GLRenderer::FinishDrawingQuadList() {
2456 FlushTextureQuadCache(SHARED_BINDING);
2459 bool GLRenderer::FlippedFramebuffer(const DrawingFrame* frame) const {
2460 if (frame->current_render_pass != frame->root_render_pass)
2461 return true;
2462 return FlippedRootFramebuffer();
2465 bool GLRenderer::FlippedRootFramebuffer() const {
2466 // GL is normally flipped, so a flipped output results in an unflipping.
2467 return !output_surface_->capabilities().flipped_output_surface;
2470 void GLRenderer::EnsureScissorTestEnabled() {
2471 if (is_scissor_enabled_)
2472 return;
2474 FlushTextureQuadCache(SHARED_BINDING);
2475 gl_->Enable(GL_SCISSOR_TEST);
2476 is_scissor_enabled_ = true;
2479 void GLRenderer::EnsureScissorTestDisabled() {
2480 if (!is_scissor_enabled_)
2481 return;
2483 FlushTextureQuadCache(SHARED_BINDING);
2484 gl_->Disable(GL_SCISSOR_TEST);
2485 is_scissor_enabled_ = false;
2488 void GLRenderer::CopyCurrentRenderPassToBitmap(
2489 DrawingFrame* frame,
2490 scoped_ptr<CopyOutputRequest> request) {
2491 TRACE_EVENT0("cc", "GLRenderer::CopyCurrentRenderPassToBitmap");
2492 gfx::Rect copy_rect = frame->current_render_pass->output_rect;
2493 if (request->has_area())
2494 copy_rect.Intersect(request->area());
2495 GetFramebufferPixelsAsync(frame, copy_rect, request.Pass());
2498 void GLRenderer::ToGLMatrix(float* gl_matrix, const gfx::Transform& transform) {
2499 transform.matrix().asColMajorf(gl_matrix);
2502 void GLRenderer::SetShaderQuadF(const gfx::QuadF& quad, int quad_location) {
2503 if (quad_location == -1)
2504 return;
2506 float gl_quad[8];
2507 gl_quad[0] = quad.p1().x();
2508 gl_quad[1] = quad.p1().y();
2509 gl_quad[2] = quad.p2().x();
2510 gl_quad[3] = quad.p2().y();
2511 gl_quad[4] = quad.p3().x();
2512 gl_quad[5] = quad.p3().y();
2513 gl_quad[6] = quad.p4().x();
2514 gl_quad[7] = quad.p4().y();
2515 gl_->Uniform2fv(quad_location, 4, gl_quad);
2518 void GLRenderer::SetShaderOpacity(float opacity, int alpha_location) {
2519 if (alpha_location != -1)
2520 gl_->Uniform1f(alpha_location, opacity);
2523 void GLRenderer::SetStencilEnabled(bool enabled) {
2524 if (enabled == stencil_shadow_)
2525 return;
2527 if (enabled)
2528 gl_->Enable(GL_STENCIL_TEST);
2529 else
2530 gl_->Disable(GL_STENCIL_TEST);
2531 stencil_shadow_ = enabled;
2534 void GLRenderer::SetBlendEnabled(bool enabled) {
2535 if (enabled == blend_shadow_)
2536 return;
2538 if (enabled)
2539 gl_->Enable(GL_BLEND);
2540 else
2541 gl_->Disable(GL_BLEND);
2542 blend_shadow_ = enabled;
2545 void GLRenderer::SetUseProgram(unsigned program) {
2546 if (program == program_shadow_)
2547 return;
2548 gl_->UseProgram(program);
2549 program_shadow_ = program;
2552 void GLRenderer::DrawQuadGeometryClippedByQuadF(
2553 const DrawingFrame* frame,
2554 const gfx::Transform& draw_transform,
2555 const gfx::RectF& quad_rect,
2556 const gfx::QuadF& clipping_region_quad,
2557 int matrix_location,
2558 const float* uvs) {
2559 PrepareGeometry(CLIPPED_BINDING);
2560 if (uvs) {
2561 clipped_geometry_->InitializeCustomQuadWithUVs(clipping_region_quad, uvs);
2562 } else {
2563 clipped_geometry_->InitializeCustomQuad(clipping_region_quad);
2565 gfx::Transform quad_rect_matrix;
2566 QuadRectTransform(&quad_rect_matrix, draw_transform, quad_rect);
2567 static float gl_matrix[16];
2568 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad_rect_matrix);
2569 gl_->UniformMatrix4fv(matrix_location, 1, false, &gl_matrix[0]);
2571 gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT,
2572 reinterpret_cast<const void*>(0));
2575 void GLRenderer::DrawQuadGeometry(const DrawingFrame* frame,
2576 const gfx::Transform& draw_transform,
2577 const gfx::RectF& quad_rect,
2578 int matrix_location) {
2579 PrepareGeometry(SHARED_BINDING);
2580 gfx::Transform quad_rect_matrix;
2581 QuadRectTransform(&quad_rect_matrix, draw_transform, quad_rect);
2582 static float gl_matrix[16];
2583 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad_rect_matrix);
2584 gl_->UniformMatrix4fv(matrix_location, 1, false, &gl_matrix[0]);
2586 gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
2589 void GLRenderer::Finish() {
2590 TRACE_EVENT0("cc", "GLRenderer::Finish");
2591 gl_->Finish();
2594 void GLRenderer::SwapBuffers(const CompositorFrameMetadata& metadata) {
2595 DCHECK(!is_backbuffer_discarded_);
2597 TRACE_EVENT0("cc,benchmark", "GLRenderer::SwapBuffers");
2598 // We're done! Time to swapbuffers!
2600 gfx::Size surface_size = output_surface_->SurfaceSize();
2602 CompositorFrame compositor_frame;
2603 compositor_frame.metadata = metadata;
2604 compositor_frame.gl_frame_data = make_scoped_ptr(new GLFrameData);
2605 compositor_frame.gl_frame_data->size = surface_size;
2606 if (capabilities_.using_partial_swap) {
2607 // If supported, we can save significant bandwidth by only swapping the
2608 // damaged/scissored region (clamped to the viewport).
2609 swap_buffer_rect_.Intersect(gfx::Rect(surface_size));
2610 int flipped_y_pos_of_rect_bottom = surface_size.height() -
2611 swap_buffer_rect_.y() -
2612 swap_buffer_rect_.height();
2613 compositor_frame.gl_frame_data->sub_buffer_rect =
2614 gfx::Rect(swap_buffer_rect_.x(),
2615 FlippedRootFramebuffer() ? flipped_y_pos_of_rect_bottom
2616 : swap_buffer_rect_.y(),
2617 swap_buffer_rect_.width(),
2618 swap_buffer_rect_.height());
2619 } else {
2620 compositor_frame.gl_frame_data->sub_buffer_rect =
2621 gfx::Rect(output_surface_->SurfaceSize());
2623 output_surface_->SwapBuffers(&compositor_frame);
2625 // Release previously used overlay resources and hold onto the pending ones
2626 // until the next swap buffers. On some platforms, hold onto resources for
2627 // an extra frame.
2628 if (settings_->delay_releasing_overlay_resources) {
2629 previous_swap_overlay_resources_.clear();
2630 previous_swap_overlay_resources_.swap(in_use_overlay_resources_);
2631 } else {
2632 in_use_overlay_resources_.clear();
2634 in_use_overlay_resources_.swap(pending_overlay_resources_);
2636 swap_buffer_rect_ = gfx::Rect();
2639 void GLRenderer::EnforceMemoryPolicy() {
2640 if (!visible()) {
2641 TRACE_EVENT0("cc", "GLRenderer::EnforceMemoryPolicy dropping resources");
2642 ReleaseRenderPassTextures();
2643 DiscardBackbuffer();
2644 output_surface_->context_provider()->DeleteCachedResources();
2645 gl_->Flush();
2647 PrepareGeometry(NO_BINDING);
2650 void GLRenderer::DiscardBackbuffer() {
2651 if (is_backbuffer_discarded_)
2652 return;
2654 output_surface_->DiscardBackbuffer();
2656 is_backbuffer_discarded_ = true;
2658 // Damage tracker needs a full reset every time framebuffer is discarded.
2659 client_->SetFullRootLayerDamage();
2662 void GLRenderer::EnsureBackbuffer() {
2663 if (!is_backbuffer_discarded_)
2664 return;
2666 output_surface_->EnsureBackbuffer();
2667 is_backbuffer_discarded_ = false;
2670 void GLRenderer::GetFramebufferPixelsAsync(
2671 const DrawingFrame* frame,
2672 const gfx::Rect& rect,
2673 scoped_ptr<CopyOutputRequest> request) {
2674 DCHECK(!request->IsEmpty());
2675 if (request->IsEmpty())
2676 return;
2677 if (rect.IsEmpty())
2678 return;
2680 gfx::Rect window_rect = MoveFromDrawToWindowSpace(frame, rect);
2681 DCHECK_GE(window_rect.x(), 0);
2682 DCHECK_GE(window_rect.y(), 0);
2683 DCHECK_LE(window_rect.right(), current_surface_size_.width());
2684 DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2686 if (!request->force_bitmap_result()) {
2687 bool own_mailbox = !request->has_texture_mailbox();
2689 GLuint texture_id = 0;
2690 gpu::Mailbox mailbox;
2691 if (own_mailbox) {
2692 gl_->GenMailboxCHROMIUM(mailbox.name);
2693 gl_->GenTextures(1, &texture_id);
2694 gl_->BindTexture(GL_TEXTURE_2D, texture_id);
2696 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2697 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2698 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2699 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2700 gl_->ProduceTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name);
2701 } else {
2702 mailbox = request->texture_mailbox().mailbox();
2703 DCHECK_EQ(static_cast<unsigned>(GL_TEXTURE_2D),
2704 request->texture_mailbox().target());
2705 DCHECK(!mailbox.IsZero());
2706 unsigned incoming_sync_point = request->texture_mailbox().sync_point();
2707 if (incoming_sync_point)
2708 gl_->WaitSyncPointCHROMIUM(incoming_sync_point);
2710 texture_id =
2711 gl_->CreateAndConsumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name);
2713 GetFramebufferTexture(texture_id, RGBA_8888, window_rect);
2715 unsigned sync_point = gl_->InsertSyncPointCHROMIUM();
2716 TextureMailbox texture_mailbox(mailbox, GL_TEXTURE_2D, sync_point);
2718 scoped_ptr<SingleReleaseCallback> release_callback;
2719 if (own_mailbox) {
2720 gl_->BindTexture(GL_TEXTURE_2D, 0);
2721 release_callback = texture_mailbox_deleter_->GetReleaseCallback(
2722 output_surface_->context_provider(), texture_id);
2723 } else {
2724 gl_->DeleteTextures(1, &texture_id);
2727 request->SendTextureResult(
2728 window_rect.size(), texture_mailbox, release_callback.Pass());
2729 return;
2732 DCHECK(request->force_bitmap_result());
2734 scoped_ptr<PendingAsyncReadPixels> pending_read(new PendingAsyncReadPixels);
2735 pending_read->copy_request = request.Pass();
2736 pending_async_read_pixels_.insert(pending_async_read_pixels_.begin(),
2737 pending_read.Pass());
2739 bool do_workaround = NeedsIOSurfaceReadbackWorkaround();
2741 unsigned temporary_texture = 0;
2742 unsigned temporary_fbo = 0;
2744 if (do_workaround) {
2745 // On Mac OS X, calling glReadPixels() against an FBO whose color attachment
2746 // is an IOSurface-backed texture causes corruption of future glReadPixels()
2747 // calls, even those on different OpenGL contexts. It is believed that this
2748 // is the root cause of top crasher
2749 // http://crbug.com/99393. <rdar://problem/10949687>
2751 gl_->GenTextures(1, &temporary_texture);
2752 gl_->BindTexture(GL_TEXTURE_2D, temporary_texture);
2753 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2754 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2755 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2756 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2757 // Copy the contents of the current (IOSurface-backed) framebuffer into a
2758 // temporary texture.
2759 GetFramebufferTexture(
2760 temporary_texture, RGBA_8888, gfx::Rect(current_surface_size_));
2761 gl_->GenFramebuffers(1, &temporary_fbo);
2762 // Attach this texture to an FBO, and perform the readback from that FBO.
2763 gl_->BindFramebuffer(GL_FRAMEBUFFER, temporary_fbo);
2764 gl_->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
2765 GL_TEXTURE_2D, temporary_texture, 0);
2767 DCHECK_EQ(static_cast<unsigned>(GL_FRAMEBUFFER_COMPLETE),
2768 gl_->CheckFramebufferStatus(GL_FRAMEBUFFER));
2771 GLuint buffer = 0;
2772 gl_->GenBuffers(1, &buffer);
2773 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, buffer);
2774 gl_->BufferData(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM,
2775 4 * window_rect.size().GetArea(), NULL, GL_STREAM_READ);
2777 GLuint query = 0;
2778 gl_->GenQueriesEXT(1, &query);
2779 gl_->BeginQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM, query);
2781 gl_->ReadPixels(window_rect.x(), window_rect.y(), window_rect.width(),
2782 window_rect.height(), GL_RGBA, GL_UNSIGNED_BYTE, NULL);
2784 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0);
2786 if (do_workaround) {
2787 // Clean up.
2788 gl_->BindFramebuffer(GL_FRAMEBUFFER, 0);
2789 gl_->BindTexture(GL_TEXTURE_2D, 0);
2790 gl_->DeleteFramebuffers(1, &temporary_fbo);
2791 gl_->DeleteTextures(1, &temporary_texture);
2794 base::Closure finished_callback = base::Bind(&GLRenderer::FinishedReadback,
2795 base::Unretained(this),
2796 buffer,
2797 query,
2798 window_rect.size());
2799 // Save the finished_callback so it can be cancelled.
2800 pending_async_read_pixels_.front()->finished_read_pixels_callback.Reset(
2801 finished_callback);
2802 base::Closure cancelable_callback =
2803 pending_async_read_pixels_.front()->
2804 finished_read_pixels_callback.callback();
2806 // Save the buffer to verify the callbacks happen in the expected order.
2807 pending_async_read_pixels_.front()->buffer = buffer;
2809 gl_->EndQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM);
2810 context_support_->SignalQuery(query, cancelable_callback);
2812 EnforceMemoryPolicy();
2815 void GLRenderer::FinishedReadback(unsigned source_buffer,
2816 unsigned query,
2817 const gfx::Size& size) {
2818 DCHECK(!pending_async_read_pixels_.empty());
2820 if (query != 0) {
2821 gl_->DeleteQueriesEXT(1, &query);
2824 PendingAsyncReadPixels* current_read = pending_async_read_pixels_.back();
2825 // Make sure we service the readbacks in order.
2826 DCHECK_EQ(source_buffer, current_read->buffer);
2828 uint8* src_pixels = NULL;
2829 scoped_ptr<SkBitmap> bitmap;
2831 if (source_buffer != 0) {
2832 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, source_buffer);
2833 src_pixels = static_cast<uint8*>(gl_->MapBufferCHROMIUM(
2834 GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, GL_READ_ONLY));
2836 if (src_pixels) {
2837 bitmap.reset(new SkBitmap);
2838 bitmap->allocN32Pixels(size.width(), size.height());
2839 scoped_ptr<SkAutoLockPixels> lock(new SkAutoLockPixels(*bitmap));
2840 uint8* dest_pixels = static_cast<uint8*>(bitmap->getPixels());
2842 size_t row_bytes = size.width() * 4;
2843 int num_rows = size.height();
2844 size_t total_bytes = num_rows * row_bytes;
2845 for (size_t dest_y = 0; dest_y < total_bytes; dest_y += row_bytes) {
2846 // Flip Y axis.
2847 size_t src_y = total_bytes - dest_y - row_bytes;
2848 // Swizzle OpenGL -> Skia byte order.
2849 for (size_t x = 0; x < row_bytes; x += 4) {
2850 dest_pixels[dest_y + x + SK_R32_SHIFT / 8] =
2851 src_pixels[src_y + x + 0];
2852 dest_pixels[dest_y + x + SK_G32_SHIFT / 8] =
2853 src_pixels[src_y + x + 1];
2854 dest_pixels[dest_y + x + SK_B32_SHIFT / 8] =
2855 src_pixels[src_y + x + 2];
2856 dest_pixels[dest_y + x + SK_A32_SHIFT / 8] =
2857 src_pixels[src_y + x + 3];
2861 gl_->UnmapBufferCHROMIUM(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM);
2863 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0);
2864 gl_->DeleteBuffers(1, &source_buffer);
2867 if (bitmap)
2868 current_read->copy_request->SendBitmapResult(bitmap.Pass());
2869 pending_async_read_pixels_.pop_back();
2872 void GLRenderer::GetFramebufferTexture(unsigned texture_id,
2873 ResourceFormat texture_format,
2874 const gfx::Rect& window_rect) {
2875 DCHECK(texture_id);
2876 DCHECK_GE(window_rect.x(), 0);
2877 DCHECK_GE(window_rect.y(), 0);
2878 DCHECK_LE(window_rect.right(), current_surface_size_.width());
2879 DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2881 gl_->BindTexture(GL_TEXTURE_2D, texture_id);
2882 gl_->CopyTexImage2D(GL_TEXTURE_2D, 0, GLDataFormat(texture_format),
2883 window_rect.x(), window_rect.y(), window_rect.width(),
2884 window_rect.height(), 0);
2885 gl_->BindTexture(GL_TEXTURE_2D, 0);
2888 bool GLRenderer::UseScopedTexture(DrawingFrame* frame,
2889 const ScopedResource* texture,
2890 const gfx::Rect& viewport_rect) {
2891 DCHECK(texture->id());
2892 frame->current_render_pass = NULL;
2893 frame->current_texture = texture;
2895 return BindFramebufferToTexture(frame, texture, viewport_rect);
2898 void GLRenderer::BindFramebufferToOutputSurface(DrawingFrame* frame) {
2899 current_framebuffer_lock_ = nullptr;
2900 output_surface_->BindFramebuffer();
2902 if (output_surface_->HasExternalStencilTest()) {
2903 SetStencilEnabled(true);
2904 gl_->StencilFunc(GL_EQUAL, 1, 1);
2905 } else {
2906 SetStencilEnabled(false);
2910 bool GLRenderer::BindFramebufferToTexture(DrawingFrame* frame,
2911 const ScopedResource* texture,
2912 const gfx::Rect& target_rect) {
2913 DCHECK(texture->id());
2915 // Explicitly release lock, otherwise we can crash when try to lock
2916 // same texture again.
2917 current_framebuffer_lock_ = nullptr;
2919 SetStencilEnabled(false);
2920 gl_->BindFramebuffer(GL_FRAMEBUFFER, offscreen_framebuffer_id_);
2921 current_framebuffer_lock_ =
2922 make_scoped_ptr(new ResourceProvider::ScopedWriteLockGL(
2923 resource_provider_, texture->id()));
2924 unsigned texture_id = current_framebuffer_lock_->texture_id();
2925 gl_->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
2926 texture_id, 0);
2928 DCHECK(gl_->CheckFramebufferStatus(GL_FRAMEBUFFER) ==
2929 GL_FRAMEBUFFER_COMPLETE ||
2930 IsContextLost());
2931 return true;
2934 void GLRenderer::SetScissorTestRect(const gfx::Rect& scissor_rect) {
2935 EnsureScissorTestEnabled();
2937 // Don't unnecessarily ask the context to change the scissor, because it
2938 // may cause undesired GPU pipeline flushes.
2939 if (scissor_rect == scissor_rect_ && !scissor_rect_needs_reset_)
2940 return;
2942 scissor_rect_ = scissor_rect;
2943 FlushTextureQuadCache(SHARED_BINDING);
2944 gl_->Scissor(scissor_rect.x(), scissor_rect.y(), scissor_rect.width(),
2945 scissor_rect.height());
2947 scissor_rect_needs_reset_ = false;
2950 void GLRenderer::SetViewport() {
2951 gl_->Viewport(current_window_space_viewport_.x(),
2952 current_window_space_viewport_.y(),
2953 current_window_space_viewport_.width(),
2954 current_window_space_viewport_.height());
2957 void GLRenderer::InitializeSharedObjects() {
2958 TRACE_EVENT0("cc", "GLRenderer::InitializeSharedObjects");
2960 // Create an FBO for doing offscreen rendering.
2961 gl_->GenFramebuffers(1, &offscreen_framebuffer_id_);
2963 shared_geometry_ =
2964 make_scoped_ptr(new StaticGeometryBinding(gl_, QuadVertexRect()));
2965 clipped_geometry_ = make_scoped_ptr(new DynamicGeometryBinding(gl_));
2968 void GLRenderer::PrepareGeometry(BoundGeometry binding) {
2969 if (binding == bound_geometry_) {
2970 return;
2973 switch (binding) {
2974 case SHARED_BINDING:
2975 shared_geometry_->PrepareForDraw();
2976 break;
2977 case CLIPPED_BINDING:
2978 clipped_geometry_->PrepareForDraw();
2979 break;
2980 case NO_BINDING:
2981 break;
2983 bound_geometry_ = binding;
2986 const GLRenderer::DebugBorderProgram* GLRenderer::GetDebugBorderProgram() {
2987 if (!debug_border_program_.initialized()) {
2988 TRACE_EVENT0("cc", "GLRenderer::debugBorderProgram::initialize");
2989 debug_border_program_.Initialize(output_surface_->context_provider(),
2990 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
2992 return &debug_border_program_;
2995 const GLRenderer::SolidColorProgram* GLRenderer::GetSolidColorProgram() {
2996 if (!solid_color_program_.initialized()) {
2997 TRACE_EVENT0("cc", "GLRenderer::solidColorProgram::initialize");
2998 solid_color_program_.Initialize(output_surface_->context_provider(),
2999 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
3001 return &solid_color_program_;
3004 const GLRenderer::SolidColorProgramAA* GLRenderer::GetSolidColorProgramAA() {
3005 if (!solid_color_program_aa_.initialized()) {
3006 TRACE_EVENT0("cc", "GLRenderer::solidColorProgramAA::initialize");
3007 solid_color_program_aa_.Initialize(output_surface_->context_provider(),
3008 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
3010 return &solid_color_program_aa_;
3013 const GLRenderer::RenderPassProgram* GLRenderer::GetRenderPassProgram(
3014 TexCoordPrecision precision,
3015 BlendMode blend_mode) {
3016 DCHECK_GE(precision, 0);
3017 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3018 DCHECK_GE(blend_mode, 0);
3019 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3020 RenderPassProgram* program = &render_pass_program_[precision][blend_mode];
3021 if (!program->initialized()) {
3022 TRACE_EVENT0("cc", "GLRenderer::renderPassProgram::initialize");
3023 program->Initialize(output_surface_->context_provider(), precision,
3024 SAMPLER_TYPE_2D, blend_mode);
3026 return program;
3029 const GLRenderer::RenderPassProgramAA* GLRenderer::GetRenderPassProgramAA(
3030 TexCoordPrecision precision,
3031 BlendMode blend_mode) {
3032 DCHECK_GE(precision, 0);
3033 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3034 DCHECK_GE(blend_mode, 0);
3035 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3036 RenderPassProgramAA* program =
3037 &render_pass_program_aa_[precision][blend_mode];
3038 if (!program->initialized()) {
3039 TRACE_EVENT0("cc", "GLRenderer::renderPassProgramAA::initialize");
3040 program->Initialize(output_surface_->context_provider(), precision,
3041 SAMPLER_TYPE_2D, blend_mode);
3043 return program;
3046 const GLRenderer::RenderPassMaskProgram* GLRenderer::GetRenderPassMaskProgram(
3047 TexCoordPrecision precision,
3048 SamplerType sampler,
3049 BlendMode blend_mode,
3050 bool mask_for_background) {
3051 DCHECK_GE(precision, 0);
3052 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3053 DCHECK_GE(sampler, 0);
3054 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3055 DCHECK_GE(blend_mode, 0);
3056 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3057 RenderPassMaskProgram* program =
3058 &render_pass_mask_program_[precision][sampler][blend_mode]
3059 [mask_for_background ? HAS_MASK : NO_MASK];
3060 if (!program->initialized()) {
3061 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgram::initialize");
3062 program->Initialize(
3063 output_surface_->context_provider(), precision,
3064 sampler, blend_mode, mask_for_background);
3066 return program;
3069 const GLRenderer::RenderPassMaskProgramAA*
3070 GLRenderer::GetRenderPassMaskProgramAA(TexCoordPrecision precision,
3071 SamplerType sampler,
3072 BlendMode blend_mode,
3073 bool mask_for_background) {
3074 DCHECK_GE(precision, 0);
3075 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3076 DCHECK_GE(sampler, 0);
3077 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3078 DCHECK_GE(blend_mode, 0);
3079 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3080 RenderPassMaskProgramAA* program =
3081 &render_pass_mask_program_aa_[precision][sampler][blend_mode]
3082 [mask_for_background ? HAS_MASK : NO_MASK];
3083 if (!program->initialized()) {
3084 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgramAA::initialize");
3085 program->Initialize(
3086 output_surface_->context_provider(), precision,
3087 sampler, blend_mode, mask_for_background);
3089 return program;
3092 const GLRenderer::RenderPassColorMatrixProgram*
3093 GLRenderer::GetRenderPassColorMatrixProgram(TexCoordPrecision precision,
3094 BlendMode blend_mode) {
3095 DCHECK_GE(precision, 0);
3096 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3097 DCHECK_GE(blend_mode, 0);
3098 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3099 RenderPassColorMatrixProgram* program =
3100 &render_pass_color_matrix_program_[precision][blend_mode];
3101 if (!program->initialized()) {
3102 TRACE_EVENT0("cc", "GLRenderer::renderPassColorMatrixProgram::initialize");
3103 program->Initialize(output_surface_->context_provider(), precision,
3104 SAMPLER_TYPE_2D, blend_mode);
3106 return program;
3109 const GLRenderer::RenderPassColorMatrixProgramAA*
3110 GLRenderer::GetRenderPassColorMatrixProgramAA(TexCoordPrecision precision,
3111 BlendMode blend_mode) {
3112 DCHECK_GE(precision, 0);
3113 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3114 DCHECK_GE(blend_mode, 0);
3115 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3116 RenderPassColorMatrixProgramAA* program =
3117 &render_pass_color_matrix_program_aa_[precision][blend_mode];
3118 if (!program->initialized()) {
3119 TRACE_EVENT0("cc",
3120 "GLRenderer::renderPassColorMatrixProgramAA::initialize");
3121 program->Initialize(output_surface_->context_provider(), precision,
3122 SAMPLER_TYPE_2D, blend_mode);
3124 return program;
3127 const GLRenderer::RenderPassMaskColorMatrixProgram*
3128 GLRenderer::GetRenderPassMaskColorMatrixProgram(
3129 TexCoordPrecision precision,
3130 SamplerType sampler,
3131 BlendMode blend_mode,
3132 bool mask_for_background) {
3133 DCHECK_GE(precision, 0);
3134 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3135 DCHECK_GE(sampler, 0);
3136 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3137 DCHECK_GE(blend_mode, 0);
3138 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3139 RenderPassMaskColorMatrixProgram* program =
3140 &render_pass_mask_color_matrix_program_[precision][sampler][blend_mode]
3141 [mask_for_background ? HAS_MASK : NO_MASK];
3142 if (!program->initialized()) {
3143 TRACE_EVENT0("cc",
3144 "GLRenderer::renderPassMaskColorMatrixProgram::initialize");
3145 program->Initialize(
3146 output_surface_->context_provider(), precision,
3147 sampler, blend_mode, mask_for_background);
3149 return program;
3152 const GLRenderer::RenderPassMaskColorMatrixProgramAA*
3153 GLRenderer::GetRenderPassMaskColorMatrixProgramAA(
3154 TexCoordPrecision precision,
3155 SamplerType sampler,
3156 BlendMode blend_mode,
3157 bool mask_for_background) {
3158 DCHECK_GE(precision, 0);
3159 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3160 DCHECK_GE(sampler, 0);
3161 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3162 DCHECK_GE(blend_mode, 0);
3163 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3164 RenderPassMaskColorMatrixProgramAA* program =
3165 &render_pass_mask_color_matrix_program_aa_[precision][sampler][blend_mode]
3166 [mask_for_background ? HAS_MASK : NO_MASK];
3167 if (!program->initialized()) {
3168 TRACE_EVENT0("cc",
3169 "GLRenderer::renderPassMaskColorMatrixProgramAA::initialize");
3170 program->Initialize(
3171 output_surface_->context_provider(), precision,
3172 sampler, blend_mode, mask_for_background);
3174 return program;
3177 const GLRenderer::TileProgram* GLRenderer::GetTileProgram(
3178 TexCoordPrecision precision,
3179 SamplerType sampler) {
3180 DCHECK_GE(precision, 0);
3181 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3182 DCHECK_GE(sampler, 0);
3183 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3184 TileProgram* program = &tile_program_[precision][sampler];
3185 if (!program->initialized()) {
3186 TRACE_EVENT0("cc", "GLRenderer::tileProgram::initialize");
3187 program->Initialize(
3188 output_surface_->context_provider(), precision, sampler);
3190 return program;
3193 const GLRenderer::TileProgramOpaque* GLRenderer::GetTileProgramOpaque(
3194 TexCoordPrecision precision,
3195 SamplerType sampler) {
3196 DCHECK_GE(precision, 0);
3197 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3198 DCHECK_GE(sampler, 0);
3199 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3200 TileProgramOpaque* program = &tile_program_opaque_[precision][sampler];
3201 if (!program->initialized()) {
3202 TRACE_EVENT0("cc", "GLRenderer::tileProgramOpaque::initialize");
3203 program->Initialize(
3204 output_surface_->context_provider(), precision, sampler);
3206 return program;
3209 const GLRenderer::TileProgramAA* GLRenderer::GetTileProgramAA(
3210 TexCoordPrecision precision,
3211 SamplerType sampler) {
3212 DCHECK_GE(precision, 0);
3213 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3214 DCHECK_GE(sampler, 0);
3215 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3216 TileProgramAA* program = &tile_program_aa_[precision][sampler];
3217 if (!program->initialized()) {
3218 TRACE_EVENT0("cc", "GLRenderer::tileProgramAA::initialize");
3219 program->Initialize(
3220 output_surface_->context_provider(), precision, sampler);
3222 return program;
3225 const GLRenderer::TileProgramSwizzle* GLRenderer::GetTileProgramSwizzle(
3226 TexCoordPrecision precision,
3227 SamplerType sampler) {
3228 DCHECK_GE(precision, 0);
3229 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3230 DCHECK_GE(sampler, 0);
3231 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3232 TileProgramSwizzle* program = &tile_program_swizzle_[precision][sampler];
3233 if (!program->initialized()) {
3234 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzle::initialize");
3235 program->Initialize(
3236 output_surface_->context_provider(), precision, sampler);
3238 return program;
3241 const GLRenderer::TileProgramSwizzleOpaque*
3242 GLRenderer::GetTileProgramSwizzleOpaque(TexCoordPrecision precision,
3243 SamplerType sampler) {
3244 DCHECK_GE(precision, 0);
3245 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3246 DCHECK_GE(sampler, 0);
3247 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3248 TileProgramSwizzleOpaque* program =
3249 &tile_program_swizzle_opaque_[precision][sampler];
3250 if (!program->initialized()) {
3251 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleOpaque::initialize");
3252 program->Initialize(
3253 output_surface_->context_provider(), precision, sampler);
3255 return program;
3258 const GLRenderer::TileProgramSwizzleAA* GLRenderer::GetTileProgramSwizzleAA(
3259 TexCoordPrecision precision,
3260 SamplerType sampler) {
3261 DCHECK_GE(precision, 0);
3262 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3263 DCHECK_GE(sampler, 0);
3264 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3265 TileProgramSwizzleAA* program = &tile_program_swizzle_aa_[precision][sampler];
3266 if (!program->initialized()) {
3267 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleAA::initialize");
3268 program->Initialize(
3269 output_surface_->context_provider(), precision, sampler);
3271 return program;
3274 const GLRenderer::TextureProgram* GLRenderer::GetTextureProgram(
3275 TexCoordPrecision precision,
3276 SamplerType sampler) {
3277 DCHECK_GE(precision, 0);
3278 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3279 DCHECK_GE(sampler, 0);
3280 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3281 TextureProgram* program = &texture_program_[precision][sampler];
3282 if (!program->initialized()) {
3283 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3284 program->Initialize(output_surface_->context_provider(), precision,
3285 sampler);
3287 return program;
3290 const GLRenderer::NonPremultipliedTextureProgram*
3291 GLRenderer::GetNonPremultipliedTextureProgram(TexCoordPrecision precision,
3292 SamplerType sampler) {
3293 DCHECK_GE(precision, 0);
3294 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3295 DCHECK_GE(sampler, 0);
3296 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3297 NonPremultipliedTextureProgram* program =
3298 &nonpremultiplied_texture_program_[precision][sampler];
3299 if (!program->initialized()) {
3300 TRACE_EVENT0("cc",
3301 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3302 program->Initialize(output_surface_->context_provider(), precision,
3303 sampler);
3305 return program;
3308 const GLRenderer::TextureBackgroundProgram*
3309 GLRenderer::GetTextureBackgroundProgram(TexCoordPrecision precision,
3310 SamplerType sampler) {
3311 DCHECK_GE(precision, 0);
3312 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3313 DCHECK_GE(sampler, 0);
3314 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3315 TextureBackgroundProgram* program =
3316 &texture_background_program_[precision][sampler];
3317 if (!program->initialized()) {
3318 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3319 program->Initialize(output_surface_->context_provider(), precision,
3320 sampler);
3322 return program;
3325 const GLRenderer::NonPremultipliedTextureBackgroundProgram*
3326 GLRenderer::GetNonPremultipliedTextureBackgroundProgram(
3327 TexCoordPrecision precision,
3328 SamplerType sampler) {
3329 DCHECK_GE(precision, 0);
3330 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3331 DCHECK_GE(sampler, 0);
3332 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3333 NonPremultipliedTextureBackgroundProgram* program =
3334 &nonpremultiplied_texture_background_program_[precision][sampler];
3335 if (!program->initialized()) {
3336 TRACE_EVENT0("cc",
3337 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3338 program->Initialize(output_surface_->context_provider(), precision,
3339 sampler);
3341 return program;
3344 const GLRenderer::TextureProgram* GLRenderer::GetTextureIOSurfaceProgram(
3345 TexCoordPrecision precision) {
3346 DCHECK_GE(precision, 0);
3347 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3348 TextureProgram* program = &texture_io_surface_program_[precision];
3349 if (!program->initialized()) {
3350 TRACE_EVENT0("cc", "GLRenderer::textureIOSurfaceProgram::initialize");
3351 program->Initialize(output_surface_->context_provider(), precision,
3352 SAMPLER_TYPE_2D_RECT);
3354 return program;
3357 const GLRenderer::VideoYUVProgram* GLRenderer::GetVideoYUVProgram(
3358 TexCoordPrecision precision,
3359 SamplerType sampler) {
3360 DCHECK_GE(precision, 0);
3361 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3362 DCHECK_GE(sampler, 0);
3363 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3364 VideoYUVProgram* program = &video_yuv_program_[precision][sampler];
3365 if (!program->initialized()) {
3366 TRACE_EVENT0("cc", "GLRenderer::videoYUVProgram::initialize");
3367 program->Initialize(output_surface_->context_provider(), precision,
3368 sampler);
3370 return program;
3373 const GLRenderer::VideoYUVAProgram* GLRenderer::GetVideoYUVAProgram(
3374 TexCoordPrecision precision,
3375 SamplerType sampler) {
3376 DCHECK_GE(precision, 0);
3377 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3378 DCHECK_GE(sampler, 0);
3379 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3380 VideoYUVAProgram* program = &video_yuva_program_[precision][sampler];
3381 if (!program->initialized()) {
3382 TRACE_EVENT0("cc", "GLRenderer::videoYUVAProgram::initialize");
3383 program->Initialize(output_surface_->context_provider(), precision,
3384 sampler);
3386 return program;
3389 const GLRenderer::VideoStreamTextureProgram*
3390 GLRenderer::GetVideoStreamTextureProgram(TexCoordPrecision precision) {
3391 if (!Capabilities().using_egl_image)
3392 return NULL;
3393 DCHECK_GE(precision, 0);
3394 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3395 VideoStreamTextureProgram* program =
3396 &video_stream_texture_program_[precision];
3397 if (!program->initialized()) {
3398 TRACE_EVENT0("cc", "GLRenderer::streamTextureProgram::initialize");
3399 program->Initialize(output_surface_->context_provider(), precision,
3400 SAMPLER_TYPE_EXTERNAL_OES);
3402 return program;
3405 void GLRenderer::CleanupSharedObjects() {
3406 shared_geometry_ = nullptr;
3408 for (int i = 0; i <= LAST_TEX_COORD_PRECISION; ++i) {
3409 for (int j = 0; j <= LAST_SAMPLER_TYPE; ++j) {
3410 tile_program_[i][j].Cleanup(gl_);
3411 tile_program_opaque_[i][j].Cleanup(gl_);
3412 tile_program_swizzle_[i][j].Cleanup(gl_);
3413 tile_program_swizzle_opaque_[i][j].Cleanup(gl_);
3414 tile_program_aa_[i][j].Cleanup(gl_);
3415 tile_program_swizzle_aa_[i][j].Cleanup(gl_);
3417 for (int k = 0; k <= LAST_BLEND_MODE; k++) {
3418 for (int l = 0; l <= LAST_MASK_VALUE; ++l) {
3419 render_pass_mask_program_[i][j][k][l].Cleanup(gl_);
3420 render_pass_mask_program_aa_[i][j][k][l].Cleanup(gl_);
3421 render_pass_mask_color_matrix_program_aa_[i][j][k][l].Cleanup(gl_);
3422 render_pass_mask_color_matrix_program_[i][j][k][l].Cleanup(gl_);
3426 video_yuv_program_[i][j].Cleanup(gl_);
3427 video_yuva_program_[i][j].Cleanup(gl_);
3429 for (int j = 0; j <= LAST_BLEND_MODE; j++) {
3430 render_pass_program_[i][j].Cleanup(gl_);
3431 render_pass_program_aa_[i][j].Cleanup(gl_);
3432 render_pass_color_matrix_program_[i][j].Cleanup(gl_);
3433 render_pass_color_matrix_program_aa_[i][j].Cleanup(gl_);
3436 for (int j = 0; j <= LAST_SAMPLER_TYPE; ++j) {
3437 texture_program_[i][j].Cleanup(gl_);
3438 nonpremultiplied_texture_program_[i][j].Cleanup(gl_);
3439 texture_background_program_[i][j].Cleanup(gl_);
3440 nonpremultiplied_texture_background_program_[i][j].Cleanup(gl_);
3442 texture_io_surface_program_[i].Cleanup(gl_);
3444 video_stream_texture_program_[i].Cleanup(gl_);
3447 debug_border_program_.Cleanup(gl_);
3448 solid_color_program_.Cleanup(gl_);
3449 solid_color_program_aa_.Cleanup(gl_);
3451 if (offscreen_framebuffer_id_)
3452 gl_->DeleteFramebuffers(1, &offscreen_framebuffer_id_);
3454 if (on_demand_tile_raster_resource_id_)
3455 resource_provider_->DeleteResource(on_demand_tile_raster_resource_id_);
3457 ReleaseRenderPassTextures();
3460 void GLRenderer::ReinitializeGLState() {
3461 is_scissor_enabled_ = false;
3462 scissor_rect_needs_reset_ = true;
3463 stencil_shadow_ = false;
3464 blend_shadow_ = true;
3465 program_shadow_ = 0;
3467 RestoreGLState();
3470 void GLRenderer::RestoreGLState() {
3471 // This restores the current GLRenderer state to the GL context.
3472 bound_geometry_ = NO_BINDING;
3473 PrepareGeometry(SHARED_BINDING);
3475 gl_->Disable(GL_DEPTH_TEST);
3476 gl_->Disable(GL_CULL_FACE);
3477 gl_->ColorMask(true, true, true, true);
3478 gl_->BlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
3479 gl_->ActiveTexture(GL_TEXTURE0);
3481 if (program_shadow_)
3482 gl_->UseProgram(program_shadow_);
3484 if (stencil_shadow_)
3485 gl_->Enable(GL_STENCIL_TEST);
3486 else
3487 gl_->Disable(GL_STENCIL_TEST);
3489 if (blend_shadow_)
3490 gl_->Enable(GL_BLEND);
3491 else
3492 gl_->Disable(GL_BLEND);
3494 if (is_scissor_enabled_) {
3495 gl_->Enable(GL_SCISSOR_TEST);
3496 gl_->Scissor(scissor_rect_.x(), scissor_rect_.y(), scissor_rect_.width(),
3497 scissor_rect_.height());
3498 } else {
3499 gl_->Disable(GL_SCISSOR_TEST);
3503 void GLRenderer::RestoreFramebuffer(DrawingFrame* frame) {
3504 UseRenderPass(frame, frame->current_render_pass);
3506 // Call SetViewport directly, rather than through PrepareSurfaceForPass.
3507 // PrepareSurfaceForPass also clears the surface, which is not desired when
3508 // restoring.
3509 SetViewport();
3512 bool GLRenderer::IsContextLost() {
3513 return gl_->GetGraphicsResetStatusKHR() != GL_NO_ERROR;
3516 void GLRenderer::ScheduleOverlays(DrawingFrame* frame) {
3517 if (!frame->overlay_list.size())
3518 return;
3520 ResourceProvider::ResourceIdArray resources;
3521 OverlayCandidateList& overlays = frame->overlay_list;
3522 for (const OverlayCandidate& overlay : overlays) {
3523 // Skip primary plane.
3524 if (overlay.plane_z_order == 0)
3525 continue;
3527 unsigned texture_id = 0;
3528 if (overlay.use_output_surface_for_resource) {
3529 texture_id = output_surface_->GetOverlayTextureId();
3530 DCHECK(texture_id);
3531 } else {
3532 pending_overlay_resources_.push_back(
3533 make_scoped_ptr(new ResourceProvider::ScopedReadLockGL(
3534 resource_provider_, overlay.resource_id)));
3535 texture_id = pending_overlay_resources_.back()->texture_id();
3538 context_support_->ScheduleOverlayPlane(
3539 overlay.plane_z_order, overlay.transform, texture_id,
3540 ToNearestRect(overlay.display_rect), overlay.uv_rect);
3544 } // namespace cc