Disable flaky UnloadTest.CrossSiteInfiniteBeforeUnloadSync on Mac.
[chromium-blink-merge.git] / cc / output / gl_renderer.cc
blob93a4114e2b204f9a5454740b94882eebacef8b7b
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/output_surface.h"
28 #include "cc/output/render_surface_filters.h"
29 #include "cc/output/static_geometry_binding.h"
30 #include "cc/quads/draw_polygon.h"
31 #include "cc/quads/picture_draw_quad.h"
32 #include "cc/quads/render_pass.h"
33 #include "cc/quads/stream_video_draw_quad.h"
34 #include "cc/quads/texture_draw_quad.h"
35 #include "cc/resources/layer_quad.h"
36 #include "cc/resources/scoped_gpu_raster.h"
37 #include "cc/resources/scoped_resource.h"
38 #include "cc/resources/texture_mailbox_deleter.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 in_use_overlay_resources_.clear();
386 CleanupSharedObjects();
389 const RendererCapabilitiesImpl& GLRenderer::Capabilities() const {
390 return capabilities_;
393 void GLRenderer::DidChangeVisibility() {
394 EnforceMemoryPolicy();
396 context_support_->SetSurfaceVisible(visible());
399 void GLRenderer::ReleaseRenderPassTextures() { render_pass_textures_.clear(); }
401 void GLRenderer::DiscardPixels() {
402 if (!capabilities_.using_discard_framebuffer)
403 return;
404 bool using_default_framebuffer =
405 !current_framebuffer_lock_ &&
406 output_surface_->capabilities().uses_default_gl_framebuffer;
407 GLenum attachments[] = {static_cast<GLenum>(
408 using_default_framebuffer ? GL_COLOR_EXT : GL_COLOR_ATTACHMENT0_EXT)};
409 gl_->DiscardFramebufferEXT(
410 GL_FRAMEBUFFER, arraysize(attachments), attachments);
413 void GLRenderer::PrepareSurfaceForPass(
414 DrawingFrame* frame,
415 SurfaceInitializationMode initialization_mode,
416 const gfx::Rect& render_pass_scissor) {
417 SetViewport();
419 switch (initialization_mode) {
420 case SURFACE_INITIALIZATION_MODE_PRESERVE:
421 EnsureScissorTestDisabled();
422 return;
423 case SURFACE_INITIALIZATION_MODE_FULL_SURFACE_CLEAR:
424 EnsureScissorTestDisabled();
425 DiscardPixels();
426 ClearFramebuffer(frame);
427 break;
428 case SURFACE_INITIALIZATION_MODE_SCISSORED_CLEAR:
429 SetScissorTestRect(render_pass_scissor);
430 ClearFramebuffer(frame);
431 break;
435 void GLRenderer::ClearFramebuffer(DrawingFrame* frame) {
436 // On DEBUG builds, opaque render passes are cleared to blue to easily see
437 // regions that were not drawn on the screen.
438 if (frame->current_render_pass->has_transparent_background)
439 gl_->ClearColor(0, 0, 0, 0);
440 else
441 gl_->ClearColor(0, 0, 1, 1);
443 bool always_clear = false;
444 #ifndef NDEBUG
445 always_clear = true;
446 #endif
447 if (always_clear || frame->current_render_pass->has_transparent_background) {
448 GLbitfield clear_bits = GL_COLOR_BUFFER_BIT;
449 if (always_clear)
450 clear_bits |= GL_STENCIL_BUFFER_BIT;
451 gl_->Clear(clear_bits);
455 static ResourceProvider::ResourceId WaitOnResourceSyncPoints(
456 ResourceProvider* resource_provider,
457 ResourceProvider::ResourceId resource_id) {
458 resource_provider->WaitSyncPointIfNeeded(resource_id);
459 return resource_id;
462 void GLRenderer::BeginDrawingFrame(DrawingFrame* frame) {
463 TRACE_EVENT0("cc", "GLRenderer::BeginDrawingFrame");
465 scoped_refptr<ResourceProvider::Fence> read_lock_fence;
466 if (use_sync_query_) {
467 // Block until oldest sync query has passed if the number of pending queries
468 // ever reach kMaxPendingSyncQueries.
469 if (pending_sync_queries_.size() >= kMaxPendingSyncQueries) {
470 LOG(ERROR) << "Reached limit of pending sync queries.";
472 pending_sync_queries_.front()->Wait();
473 DCHECK(!pending_sync_queries_.front()->IsPending());
476 while (!pending_sync_queries_.empty()) {
477 if (pending_sync_queries_.front()->IsPending())
478 break;
480 available_sync_queries_.push_back(pending_sync_queries_.take_front());
483 current_sync_query_ = available_sync_queries_.empty()
484 ? make_scoped_ptr(new SyncQuery(gl_))
485 : available_sync_queries_.take_front();
487 read_lock_fence = current_sync_query_->Begin();
488 } else {
489 read_lock_fence =
490 make_scoped_refptr(new ResourceProvider::SynchronousFence(gl_));
492 resource_provider_->SetReadLockFence(read_lock_fence.get());
494 // Insert WaitSyncPointCHROMIUM on quad resources prior to drawing the frame,
495 // so that drawing can proceed without GL context switching interruptions.
496 DrawQuad::ResourceIteratorCallback wait_on_resource_syncpoints_callback =
497 base::Bind(&WaitOnResourceSyncPoints, resource_provider_);
499 for (const auto& pass : *frame->render_passes_in_draw_order) {
500 for (const auto& quad : pass->quad_list)
501 quad->IterateResources(wait_on_resource_syncpoints_callback);
504 // TODO(enne): Do we need to reinitialize all of this state per frame?
505 ReinitializeGLState();
508 void GLRenderer::DoNoOp() {
509 gl_->BindFramebuffer(GL_FRAMEBUFFER, 0);
510 gl_->Flush();
513 void GLRenderer::DoDrawQuad(DrawingFrame* frame,
514 const DrawQuad* quad,
515 const gfx::QuadF* clip_region) {
516 DCHECK(quad->rect.Contains(quad->visible_rect));
517 if (quad->material != DrawQuad::TEXTURE_CONTENT) {
518 FlushTextureQuadCache(SHARED_BINDING);
521 switch (quad->material) {
522 case DrawQuad::INVALID:
523 NOTREACHED();
524 break;
525 case DrawQuad::CHECKERBOARD:
526 DrawCheckerboardQuad(frame, CheckerboardDrawQuad::MaterialCast(quad),
527 clip_region);
528 break;
529 case DrawQuad::DEBUG_BORDER:
530 DrawDebugBorderQuad(frame, DebugBorderDrawQuad::MaterialCast(quad));
531 break;
532 case DrawQuad::IO_SURFACE_CONTENT:
533 DrawIOSurfaceQuad(frame, IOSurfaceDrawQuad::MaterialCast(quad),
534 clip_region);
535 break;
536 case DrawQuad::PICTURE_CONTENT:
537 // PictureDrawQuad should only be used for resourceless software draws.
538 NOTREACHED();
539 break;
540 case DrawQuad::RENDER_PASS:
541 DrawRenderPassQuad(frame, RenderPassDrawQuad::MaterialCast(quad),
542 clip_region);
543 break;
544 case DrawQuad::SOLID_COLOR:
545 DrawSolidColorQuad(frame, SolidColorDrawQuad::MaterialCast(quad),
546 clip_region);
547 break;
548 case DrawQuad::STREAM_VIDEO_CONTENT:
549 DrawStreamVideoQuad(frame, StreamVideoDrawQuad::MaterialCast(quad),
550 clip_region);
551 break;
552 case DrawQuad::SURFACE_CONTENT:
553 // Surface content should be fully resolved to other quad types before
554 // reaching a direct renderer.
555 NOTREACHED();
556 break;
557 case DrawQuad::TEXTURE_CONTENT:
558 EnqueueTextureQuad(frame, TextureDrawQuad::MaterialCast(quad),
559 clip_region);
560 break;
561 case DrawQuad::TILED_CONTENT:
562 DrawTileQuad(frame, TileDrawQuad::MaterialCast(quad), clip_region);
563 break;
564 case DrawQuad::YUV_VIDEO_CONTENT:
565 DrawYUVVideoQuad(frame, YUVVideoDrawQuad::MaterialCast(quad),
566 clip_region);
567 break;
571 void GLRenderer::DrawCheckerboardQuad(const DrawingFrame* frame,
572 const CheckerboardDrawQuad* quad,
573 const gfx::QuadF* clip_region) {
574 // TODO(enne) For now since checkerboards shouldn't be part of a 3D
575 // context, clipping regions aren't supported so we skip drawing them
576 // if this becomes the case.
577 if (clip_region) {
578 return;
580 SetBlendEnabled(quad->ShouldDrawWithBlending());
582 const TileCheckerboardProgram* program = GetTileCheckerboardProgram();
583 DCHECK(program && (program->initialized() || IsContextLost()));
584 SetUseProgram(program->program());
586 SkColor color = quad->color;
587 gl_->Uniform4f(program->fragment_shader().color_location(),
588 SkColorGetR(color) * (1.0f / 255.0f),
589 SkColorGetG(color) * (1.0f / 255.0f),
590 SkColorGetB(color) * (1.0f / 255.0f), 1);
592 const int kCheckerboardWidth = 16;
593 float frequency = 1.0f / kCheckerboardWidth;
595 gfx::Rect tile_rect = quad->rect;
596 float tex_offset_x =
597 static_cast<int>(tile_rect.x() / quad->scale) % kCheckerboardWidth;
598 float tex_offset_y =
599 static_cast<int>(tile_rect.y() / quad->scale) % kCheckerboardWidth;
600 float tex_scale_x = tile_rect.width() / quad->scale;
601 float tex_scale_y = tile_rect.height() / quad->scale;
602 gl_->Uniform4f(program->fragment_shader().tex_transform_location(),
603 tex_offset_x, tex_offset_y, tex_scale_x, tex_scale_y);
605 gl_->Uniform1f(program->fragment_shader().frequency_location(), frequency);
607 SetShaderOpacity(quad->opacity(),
608 program->fragment_shader().alpha_location());
609 DrawQuadGeometry(frame,
610 quad->quadTransform(),
611 quad->rect,
612 program->vertex_shader().matrix_location());
615 // This function does not handle 3D sorting right now, since the debug border
616 // quads are just drawn as their original quads and not in split pieces. This
617 // results in some debug border quads drawing over foreground quads.
618 void GLRenderer::DrawDebugBorderQuad(const DrawingFrame* frame,
619 const DebugBorderDrawQuad* quad) {
620 SetBlendEnabled(quad->ShouldDrawWithBlending());
622 static float gl_matrix[16];
623 const DebugBorderProgram* program = GetDebugBorderProgram();
624 DCHECK(program && (program->initialized() || IsContextLost()));
625 SetUseProgram(program->program());
627 // Use the full quad_rect for debug quads to not move the edges based on
628 // partial swaps.
629 gfx::Rect layer_rect = quad->rect;
630 gfx::Transform render_matrix;
631 QuadRectTransform(&render_matrix, quad->quadTransform(), layer_rect);
632 GLRenderer::ToGLMatrix(&gl_matrix[0],
633 frame->projection_matrix * render_matrix);
634 gl_->UniformMatrix4fv(program->vertex_shader().matrix_location(), 1, false,
635 &gl_matrix[0]);
637 SkColor color = quad->color;
638 float alpha = SkColorGetA(color) * (1.0f / 255.0f);
640 gl_->Uniform4f(program->fragment_shader().color_location(),
641 (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
642 (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
643 (SkColorGetB(color) * (1.0f / 255.0f)) * alpha, alpha);
645 gl_->LineWidth(quad->width);
647 // The indices for the line are stored in the same array as the triangle
648 // indices.
649 gl_->DrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, 0);
652 static skia::RefPtr<SkImage> ApplyImageFilter(
653 scoped_ptr<GLRenderer::ScopedUseGrContext> use_gr_context,
654 ResourceProvider* resource_provider,
655 const gfx::Rect& rect,
656 const gfx::Vector2dF& scale,
657 SkImageFilter* filter,
658 ScopedResource* source_texture_resource) {
659 if (!filter)
660 return skia::RefPtr<SkImage>();
662 if (!use_gr_context)
663 return skia::RefPtr<SkImage>();
665 ResourceProvider::ScopedReadLockGL lock(resource_provider,
666 source_texture_resource->id());
668 // Wrap the source texture in a Ganesh platform texture.
669 GrBackendTextureDesc backend_texture_description;
670 backend_texture_description.fWidth = source_texture_resource->size().width();
671 backend_texture_description.fHeight =
672 source_texture_resource->size().height();
673 backend_texture_description.fConfig = kSkia8888_GrPixelConfig;
674 backend_texture_description.fTextureHandle = lock.texture_id();
675 backend_texture_description.fOrigin = kBottomLeft_GrSurfaceOrigin;
676 skia::RefPtr<GrTexture> texture = skia::AdoptRef(
677 use_gr_context->context()->textureProvider()->wrapBackendTexture(
678 backend_texture_description));
679 if (!texture) {
680 TRACE_EVENT_INSTANT0("cc",
681 "ApplyImageFilter wrap background texture failed",
682 TRACE_EVENT_SCOPE_THREAD);
683 return skia::RefPtr<SkImage>();
686 SkImageInfo src_info =
687 SkImageInfo::MakeN32Premul(source_texture_resource->size().width(),
688 source_texture_resource->size().height());
689 // Place the platform texture inside an SkBitmap.
690 SkBitmap source;
691 source.setInfo(src_info);
692 skia::RefPtr<SkGrPixelRef> pixel_ref =
693 skia::AdoptRef(new SkGrPixelRef(src_info, texture.get()));
694 source.setPixelRef(pixel_ref.get());
696 // Create surface to draw into.
697 SkImageInfo dst_info =
698 SkImageInfo::MakeN32Premul(source.width(), source.height());
699 skia::RefPtr<SkSurface> surface = skia::AdoptRef(SkSurface::NewRenderTarget(
700 use_gr_context->context(), SkSurface::kYes_Budgeted, dst_info, 0));
701 if (!surface) {
702 TRACE_EVENT_INSTANT0("cc", "ApplyImageFilter surface allocation failed",
703 TRACE_EVENT_SCOPE_THREAD);
704 return skia::RefPtr<SkImage>();
706 skia::RefPtr<SkCanvas> canvas = skia::SharePtr(surface->getCanvas());
708 // Draw the source bitmap through the filter to the canvas.
709 SkPaint paint;
710 paint.setImageFilter(filter);
711 canvas->clear(SK_ColorTRANSPARENT);
713 // The origin of the filter is top-left and the origin of the source is
714 // bottom-left, but the orientation is the same, so we must translate the
715 // filter so that it renders at the bottom of the texture to avoid
716 // misregistration.
717 int y_translate = source.height() - rect.height() - rect.origin().y();
718 canvas->translate(-rect.origin().x(), y_translate);
719 canvas->scale(scale.x(), scale.y());
720 canvas->drawSprite(source, 0, 0, &paint);
722 skia::RefPtr<SkImage> image = skia::AdoptRef(surface->newImageSnapshot());
723 if (!image || !image->getTexture()) {
724 return skia::RefPtr<SkImage>();
727 // Flush the GrContext to ensure all buffered GL calls are drawn to the
728 // backing store before we access and return it, and have cc begin using the
729 // GL context again.
730 canvas->flush();
732 return image;
735 bool GLRenderer::CanApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode) {
736 return use_blend_equation_advanced_ ||
737 blend_mode == SkXfermode::kScreen_Mode ||
738 blend_mode == SkXfermode::kSrcOver_Mode;
741 void GLRenderer::ApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode) {
742 DCHECK(CanApplyBlendModeUsingBlendFunc(blend_mode));
744 // Any modes set here must be reset in RestoreBlendFuncToDefault
745 if (use_blend_equation_advanced_) {
746 GLenum equation = GL_FUNC_ADD;
748 switch (blend_mode) {
749 case SkXfermode::kScreen_Mode:
750 equation = GL_SCREEN_KHR;
751 break;
752 case SkXfermode::kOverlay_Mode:
753 equation = GL_OVERLAY_KHR;
754 break;
755 case SkXfermode::kDarken_Mode:
756 equation = GL_DARKEN_KHR;
757 break;
758 case SkXfermode::kLighten_Mode:
759 equation = GL_LIGHTEN_KHR;
760 break;
761 case SkXfermode::kColorDodge_Mode:
762 equation = GL_COLORDODGE_KHR;
763 break;
764 case SkXfermode::kColorBurn_Mode:
765 equation = GL_COLORBURN_KHR;
766 break;
767 case SkXfermode::kHardLight_Mode:
768 equation = GL_HARDLIGHT_KHR;
769 break;
770 case SkXfermode::kSoftLight_Mode:
771 equation = GL_SOFTLIGHT_KHR;
772 break;
773 case SkXfermode::kDifference_Mode:
774 equation = GL_DIFFERENCE_KHR;
775 break;
776 case SkXfermode::kExclusion_Mode:
777 equation = GL_EXCLUSION_KHR;
778 break;
779 case SkXfermode::kMultiply_Mode:
780 equation = GL_MULTIPLY_KHR;
781 break;
782 case SkXfermode::kHue_Mode:
783 equation = GL_HSL_HUE_KHR;
784 break;
785 case SkXfermode::kSaturation_Mode:
786 equation = GL_HSL_SATURATION_KHR;
787 break;
788 case SkXfermode::kColor_Mode:
789 equation = GL_HSL_COLOR_KHR;
790 break;
791 case SkXfermode::kLuminosity_Mode:
792 equation = GL_HSL_LUMINOSITY_KHR;
793 break;
794 default:
795 return;
798 gl_->BlendEquation(equation);
799 } else {
800 if (blend_mode == SkXfermode::kScreen_Mode) {
801 gl_->BlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE);
806 void GLRenderer::RestoreBlendFuncToDefault(SkXfermode::Mode blend_mode) {
807 if (blend_mode == SkXfermode::kSrcOver_Mode)
808 return;
810 if (use_blend_equation_advanced_) {
811 gl_->BlendEquation(GL_FUNC_ADD);
812 } else {
813 gl_->BlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
817 bool GLRenderer::ShouldApplyBackgroundFilters(DrawingFrame* frame,
818 const RenderPassDrawQuad* quad) {
819 if (quad->background_filters.IsEmpty())
820 return false;
822 // TODO(danakj): We only allow background filters on an opaque render surface
823 // because other surfaces may contain translucent pixels, and the contents
824 // behind those translucent pixels wouldn't have the filter applied.
825 if (frame->current_render_pass->has_transparent_background)
826 return false;
828 // TODO(ajuma): Add support for reference filters once
829 // FilterOperations::GetOutsets supports reference filters.
830 if (quad->background_filters.HasReferenceFilter())
831 return false;
832 return true;
835 // This takes a gfx::Rect and a clip region quad in the same space,
836 // and returns a quad with the same proportions in the space -0.5->0.5.
837 bool GetScaledRegion(const gfx::Rect& rect,
838 const gfx::QuadF* clip,
839 gfx::QuadF* scaled_region) {
840 if (!clip)
841 return false;
843 gfx::PointF p1(((clip->p1().x() - rect.x()) / rect.width()) - 0.5f,
844 ((clip->p1().y() - rect.y()) / rect.height()) - 0.5f);
845 gfx::PointF p2(((clip->p2().x() - rect.x()) / rect.width()) - 0.5f,
846 ((clip->p2().y() - rect.y()) / rect.height()) - 0.5f);
847 gfx::PointF p3(((clip->p3().x() - rect.x()) / rect.width()) - 0.5f,
848 ((clip->p3().y() - rect.y()) / rect.height()) - 0.5f);
849 gfx::PointF p4(((clip->p4().x() - rect.x()) / rect.width()) - 0.5f,
850 ((clip->p4().y() - rect.y()) / rect.height()) - 0.5f);
851 *scaled_region = gfx::QuadF(p1, p2, p3, p4);
852 return true;
855 // This takes a gfx::Rect and a clip region quad in the same space,
856 // and returns the proportional uv's in the space 0->1.
857 bool GetScaledUVs(const gfx::Rect& rect, const gfx::QuadF* clip, float uvs[8]) {
858 if (!clip)
859 return false;
861 uvs[0] = ((clip->p1().x() - rect.x()) / rect.width());
862 uvs[1] = ((clip->p1().y() - rect.y()) / rect.height());
863 uvs[2] = ((clip->p2().x() - rect.x()) / rect.width());
864 uvs[3] = ((clip->p2().y() - rect.y()) / rect.height());
865 uvs[4] = ((clip->p3().x() - rect.x()) / rect.width());
866 uvs[5] = ((clip->p3().y() - rect.y()) / rect.height());
867 uvs[6] = ((clip->p4().x() - rect.x()) / rect.width());
868 uvs[7] = ((clip->p4().y() - rect.y()) / rect.height());
869 return true;
872 gfx::Rect GLRenderer::GetBackdropBoundingBoxForRenderPassQuad(
873 DrawingFrame* frame,
874 const RenderPassDrawQuad* quad,
875 const gfx::Transform& contents_device_transform,
876 const gfx::QuadF* clip_region,
877 bool use_aa) {
878 gfx::QuadF scaled_region;
879 if (!GetScaledRegion(quad->rect, clip_region, &scaled_region)) {
880 scaled_region = SharedGeometryQuad().BoundingBox();
883 gfx::Rect backdrop_rect = gfx::ToEnclosingRect(MathUtil::MapClippedRect(
884 contents_device_transform, scaled_region.BoundingBox()));
886 if (ShouldApplyBackgroundFilters(frame, quad)) {
887 int top, right, bottom, left;
888 quad->background_filters.GetOutsets(&top, &right, &bottom, &left);
889 backdrop_rect.Inset(-left, -top, -right, -bottom);
892 if (!backdrop_rect.IsEmpty() && use_aa) {
893 const int kOutsetForAntialiasing = 1;
894 backdrop_rect.Inset(-kOutsetForAntialiasing, -kOutsetForAntialiasing);
897 backdrop_rect.Intersect(MoveFromDrawToWindowSpace(
898 frame, frame->current_render_pass->output_rect));
899 return backdrop_rect;
902 scoped_ptr<ScopedResource> GLRenderer::GetBackdropTexture(
903 const gfx::Rect& bounding_rect) {
904 scoped_ptr<ScopedResource> device_background_texture =
905 ScopedResource::Create(resource_provider_);
906 // CopyTexImage2D fails when called on a texture having immutable storage.
907 device_background_texture->Allocate(
908 bounding_rect.size(), ResourceProvider::TEXTURE_HINT_DEFAULT, RGBA_8888);
910 ResourceProvider::ScopedWriteLockGL lock(resource_provider_,
911 device_background_texture->id());
912 GetFramebufferTexture(
913 lock.texture_id(), device_background_texture->format(), bounding_rect);
915 return device_background_texture.Pass();
918 skia::RefPtr<SkImage> GLRenderer::ApplyBackgroundFilters(
919 DrawingFrame* frame,
920 const RenderPassDrawQuad* quad,
921 ScopedResource* background_texture) {
922 DCHECK(ShouldApplyBackgroundFilters(frame, quad));
923 skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
924 quad->background_filters, background_texture->size());
926 skia::RefPtr<SkImage> background_with_filters = ApplyImageFilter(
927 ScopedUseGrContext::Create(this, frame), resource_provider_, quad->rect,
928 quad->filters_scale, filter.get(), background_texture);
929 return background_with_filters;
932 void GLRenderer::DrawRenderPassQuad(DrawingFrame* frame,
933 const RenderPassDrawQuad* quad,
934 const gfx::QuadF* clip_region) {
935 ScopedResource* contents_texture =
936 render_pass_textures_.get(quad->render_pass_id);
937 DCHECK(contents_texture);
938 DCHECK(contents_texture->id());
940 gfx::Transform quad_rect_matrix;
941 QuadRectTransform(&quad_rect_matrix, quad->quadTransform(), quad->rect);
942 gfx::Transform contents_device_transform =
943 frame->window_matrix * frame->projection_matrix * quad_rect_matrix;
944 contents_device_transform.FlattenTo2d();
946 // Can only draw surface if device matrix is invertible.
947 if (!contents_device_transform.IsInvertible())
948 return;
950 gfx::QuadF surface_quad = SharedGeometryQuad();
951 float edge[24];
952 bool use_aa = settings_->allow_antialiasing &&
953 ShouldAntialiasQuad(contents_device_transform, quad,
954 settings_->force_antialiasing);
956 SetupQuadForClippingAndAntialiasing(contents_device_transform, quad, use_aa,
957 clip_region, &surface_quad, edge);
958 SkXfermode::Mode blend_mode = quad->shared_quad_state->blend_mode;
959 bool use_shaders_for_blending =
960 !CanApplyBlendModeUsingBlendFunc(blend_mode) ||
961 ShouldApplyBackgroundFilters(frame, quad) ||
962 settings_->force_blending_with_shaders;
964 scoped_ptr<ScopedResource> background_texture;
965 skia::RefPtr<SkImage> background_image;
966 gfx::Rect background_rect;
967 if (use_shaders_for_blending) {
968 // Compute a bounding box around the pixels that will be visible through
969 // the quad.
970 background_rect = GetBackdropBoundingBoxForRenderPassQuad(
971 frame, quad, contents_device_transform, clip_region, use_aa);
973 if (!background_rect.IsEmpty()) {
974 // The pixels from the filtered background should completely replace the
975 // current pixel values.
976 if (blend_enabled())
977 SetBlendEnabled(false);
979 // Read the pixels in the bounding box into a buffer R.
980 // This function allocates a texture, which should contribute to the
981 // amount of memory used by render surfaces:
982 // LayerTreeHost::CalculateMemoryForRenderSurfaces.
983 background_texture = GetBackdropTexture(background_rect);
985 if (ShouldApplyBackgroundFilters(frame, quad) && background_texture) {
986 // Apply the background filters to R, so that it is applied in the
987 // pixels' coordinate space.
988 background_image =
989 ApplyBackgroundFilters(frame, quad, background_texture.get());
993 if (!background_texture) {
994 // Something went wrong with reading the backdrop.
995 DCHECK(!background_image);
996 use_shaders_for_blending = false;
997 } else if (background_image) {
998 // Reset original background texture if there is not any mask
999 if (!quad->mask_resource_id)
1000 background_texture.reset();
1001 } else if (CanApplyBlendModeUsingBlendFunc(blend_mode) &&
1002 ShouldApplyBackgroundFilters(frame, quad)) {
1003 // Something went wrong with applying background filters to the backdrop.
1004 use_shaders_for_blending = false;
1005 background_texture.reset();
1008 // Need original background texture for mask?
1009 bool mask_for_background =
1010 background_texture && // Have original background texture
1011 background_image && // Have filtered background texture
1012 quad->mask_resource_id; // Have mask texture
1013 SetBlendEnabled(
1014 !use_shaders_for_blending &&
1015 (quad->ShouldDrawWithBlending() || !IsDefaultBlendMode(blend_mode)));
1017 // TODO(senorblanco): Cache this value so that we don't have to do it for both
1018 // the surface and its replica. Apply filters to the contents texture.
1019 skia::RefPtr<SkImage> filter_image;
1020 SkScalar color_matrix[20];
1021 bool use_color_matrix = false;
1022 if (!quad->filters.IsEmpty()) {
1023 skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
1024 quad->filters, contents_texture->size());
1025 if (filter) {
1026 skia::RefPtr<SkColorFilter> cf;
1029 SkColorFilter* colorfilter_rawptr = NULL;
1030 filter->asColorFilter(&colorfilter_rawptr);
1031 cf = skia::AdoptRef(colorfilter_rawptr);
1034 if (cf && cf->asColorMatrix(color_matrix) && !filter->getInput(0)) {
1035 // We have a single color matrix as a filter; apply it locally
1036 // in the compositor.
1037 use_color_matrix = true;
1038 } else {
1039 filter_image = ApplyImageFilter(
1040 ScopedUseGrContext::Create(this, frame), resource_provider_,
1041 quad->rect, quad->filters_scale, filter.get(), contents_texture);
1046 scoped_ptr<ResourceProvider::ScopedSamplerGL> mask_resource_lock;
1047 unsigned mask_texture_id = 0;
1048 SamplerType mask_sampler = SAMPLER_TYPE_NA;
1049 if (quad->mask_resource_id) {
1050 mask_resource_lock.reset(new ResourceProvider::ScopedSamplerGL(
1051 resource_provider_, quad->mask_resource_id, GL_TEXTURE1, GL_LINEAR));
1052 mask_texture_id = mask_resource_lock->texture_id();
1053 mask_sampler = SamplerTypeFromTextureTarget(mask_resource_lock->target());
1056 scoped_ptr<ResourceProvider::ScopedSamplerGL> contents_resource_lock;
1057 if (filter_image) {
1058 GrTexture* texture = filter_image->getTexture();
1059 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
1060 gl_->BindTexture(GL_TEXTURE_2D, texture->getTextureHandle());
1061 } else {
1062 contents_resource_lock =
1063 make_scoped_ptr(new ResourceProvider::ScopedSamplerGL(
1064 resource_provider_, contents_texture->id(), GL_LINEAR));
1065 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
1066 contents_resource_lock->target());
1069 if (!use_shaders_for_blending) {
1070 if (!use_blend_equation_advanced_coherent_ && use_blend_equation_advanced_)
1071 gl_->BlendBarrierKHR();
1073 ApplyBlendModeUsingBlendFunc(blend_mode);
1076 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1077 gl_,
1078 &highp_threshold_cache_,
1079 highp_threshold_min_,
1080 quad->shared_quad_state->visible_content_rect.bottom_right());
1082 ShaderLocations locations;
1084 DCHECK_EQ(background_texture || background_image, use_shaders_for_blending);
1085 BlendMode shader_blend_mode = use_shaders_for_blending
1086 ? BlendModeFromSkXfermode(blend_mode)
1087 : BLEND_MODE_NONE;
1089 if (use_aa && mask_texture_id && !use_color_matrix) {
1090 const RenderPassMaskProgramAA* program = GetRenderPassMaskProgramAA(
1091 tex_coord_precision, mask_sampler,
1092 shader_blend_mode, mask_for_background);
1093 SetUseProgram(program->program());
1094 program->vertex_shader().FillLocations(&locations);
1095 program->fragment_shader().FillLocations(&locations);
1096 gl_->Uniform1i(locations.sampler, 0);
1097 } else if (!use_aa && mask_texture_id && !use_color_matrix) {
1098 const RenderPassMaskProgram* program = GetRenderPassMaskProgram(
1099 tex_coord_precision, mask_sampler,
1100 shader_blend_mode, mask_for_background);
1101 SetUseProgram(program->program());
1102 program->vertex_shader().FillLocations(&locations);
1103 program->fragment_shader().FillLocations(&locations);
1104 gl_->Uniform1i(locations.sampler, 0);
1105 } else if (use_aa && !mask_texture_id && !use_color_matrix) {
1106 const RenderPassProgramAA* program =
1107 GetRenderPassProgramAA(tex_coord_precision, shader_blend_mode);
1108 SetUseProgram(program->program());
1109 program->vertex_shader().FillLocations(&locations);
1110 program->fragment_shader().FillLocations(&locations);
1111 gl_->Uniform1i(locations.sampler, 0);
1112 } else if (use_aa && mask_texture_id && use_color_matrix) {
1113 const RenderPassMaskColorMatrixProgramAA* program =
1114 GetRenderPassMaskColorMatrixProgramAA(
1115 tex_coord_precision, mask_sampler,
1116 shader_blend_mode, mask_for_background);
1117 SetUseProgram(program->program());
1118 program->vertex_shader().FillLocations(&locations);
1119 program->fragment_shader().FillLocations(&locations);
1120 gl_->Uniform1i(locations.sampler, 0);
1121 } else if (use_aa && !mask_texture_id && use_color_matrix) {
1122 const RenderPassColorMatrixProgramAA* program =
1123 GetRenderPassColorMatrixProgramAA(tex_coord_precision,
1124 shader_blend_mode);
1125 SetUseProgram(program->program());
1126 program->vertex_shader().FillLocations(&locations);
1127 program->fragment_shader().FillLocations(&locations);
1128 gl_->Uniform1i(locations.sampler, 0);
1129 } else if (!use_aa && mask_texture_id && use_color_matrix) {
1130 const RenderPassMaskColorMatrixProgram* program =
1131 GetRenderPassMaskColorMatrixProgram(
1132 tex_coord_precision, mask_sampler,
1133 shader_blend_mode, mask_for_background);
1134 SetUseProgram(program->program());
1135 program->vertex_shader().FillLocations(&locations);
1136 program->fragment_shader().FillLocations(&locations);
1137 gl_->Uniform1i(locations.sampler, 0);
1138 } else if (!use_aa && !mask_texture_id && use_color_matrix) {
1139 const RenderPassColorMatrixProgram* program =
1140 GetRenderPassColorMatrixProgram(tex_coord_precision, shader_blend_mode);
1141 SetUseProgram(program->program());
1142 program->vertex_shader().FillLocations(&locations);
1143 program->fragment_shader().FillLocations(&locations);
1144 gl_->Uniform1i(locations.sampler, 0);
1145 } else {
1146 const RenderPassProgram* program =
1147 GetRenderPassProgram(tex_coord_precision, shader_blend_mode);
1148 SetUseProgram(program->program());
1149 program->vertex_shader().FillLocations(&locations);
1150 program->fragment_shader().FillLocations(&locations);
1151 gl_->Uniform1i(locations.sampler, 0);
1153 float tex_scale_x =
1154 quad->rect.width() / static_cast<float>(contents_texture->size().width());
1155 float tex_scale_y = quad->rect.height() /
1156 static_cast<float>(contents_texture->size().height());
1157 DCHECK_LE(tex_scale_x, 1.0f);
1158 DCHECK_LE(tex_scale_y, 1.0f);
1160 DCHECK(locations.tex_transform != -1 || IsContextLost());
1161 // Flip the content vertically in the shader, as the RenderPass input
1162 // texture is already oriented the same way as the framebuffer, but the
1163 // projection transform does a flip.
1164 gl_->Uniform4f(locations.tex_transform, 0.0f, tex_scale_y, tex_scale_x,
1165 -tex_scale_y);
1167 GLint last_texture_unit = 0;
1168 if (locations.mask_sampler != -1) {
1169 DCHECK_NE(locations.mask_tex_coord_scale, 1);
1170 DCHECK_NE(locations.mask_tex_coord_offset, 1);
1171 gl_->Uniform1i(locations.mask_sampler, 1);
1173 gfx::RectF mask_uv_rect = quad->MaskUVRect();
1174 if (mask_sampler != SAMPLER_TYPE_2D) {
1175 mask_uv_rect.Scale(quad->mask_texture_size.width(),
1176 quad->mask_texture_size.height());
1179 // Mask textures are oriented vertically flipped relative to the framebuffer
1180 // and the RenderPass contents texture, so we flip the tex coords from the
1181 // RenderPass texture to find the mask texture coords.
1182 gl_->Uniform2f(locations.mask_tex_coord_offset, mask_uv_rect.x(),
1183 mask_uv_rect.bottom());
1184 gl_->Uniform2f(locations.mask_tex_coord_scale,
1185 mask_uv_rect.width() / tex_scale_x,
1186 -mask_uv_rect.height() / tex_scale_y);
1188 last_texture_unit = 1;
1191 if (locations.edge != -1)
1192 gl_->Uniform3fv(locations.edge, 8, edge);
1194 if (locations.viewport != -1) {
1195 float viewport[4] = {
1196 static_cast<float>(current_window_space_viewport_.x()),
1197 static_cast<float>(current_window_space_viewport_.y()),
1198 static_cast<float>(current_window_space_viewport_.width()),
1199 static_cast<float>(current_window_space_viewport_.height()),
1201 gl_->Uniform4fv(locations.viewport, 1, viewport);
1204 if (locations.color_matrix != -1) {
1205 float matrix[16];
1206 for (int i = 0; i < 4; ++i) {
1207 for (int j = 0; j < 4; ++j)
1208 matrix[i * 4 + j] = SkScalarToFloat(color_matrix[j * 5 + i]);
1210 gl_->UniformMatrix4fv(locations.color_matrix, 1, false, matrix);
1212 static const float kScale = 1.0f / 255.0f;
1213 if (locations.color_offset != -1) {
1214 float offset[4];
1215 for (int i = 0; i < 4; ++i)
1216 offset[i] = SkScalarToFloat(color_matrix[i * 5 + 4]) * kScale;
1218 gl_->Uniform4fv(locations.color_offset, 1, offset);
1221 scoped_ptr<ResourceProvider::ScopedSamplerGL> shader_background_sampler_lock;
1222 if (locations.backdrop != -1) {
1223 DCHECK(background_texture || background_image);
1224 DCHECK_NE(locations.backdrop, 0);
1225 DCHECK_NE(locations.backdrop_rect, 0);
1227 gl_->Uniform1i(locations.backdrop, ++last_texture_unit);
1229 gl_->Uniform4f(locations.backdrop_rect, background_rect.x(),
1230 background_rect.y(), background_rect.width(),
1231 background_rect.height());
1233 if (background_image) {
1234 GrTexture* texture = background_image->getTexture();
1235 gl_->ActiveTexture(GL_TEXTURE0 + last_texture_unit);
1236 gl_->BindTexture(GL_TEXTURE_2D, texture->getTextureHandle());
1237 gl_->ActiveTexture(GL_TEXTURE0);
1238 if (mask_for_background)
1239 gl_->Uniform1i(locations.original_backdrop, ++last_texture_unit);
1241 if (background_texture) {
1242 shader_background_sampler_lock = make_scoped_ptr(
1243 new ResourceProvider::ScopedSamplerGL(resource_provider_,
1244 background_texture->id(),
1245 GL_TEXTURE0 + last_texture_unit,
1246 GL_LINEAR));
1247 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
1248 shader_background_sampler_lock->target());
1252 SetShaderOpacity(quad->opacity(), locations.alpha);
1253 SetShaderQuadF(surface_quad, locations.quad);
1254 DrawQuadGeometry(
1255 frame, quad->quadTransform(), quad->rect, locations.matrix);
1257 // Flush the compositor context before the filter bitmap goes out of
1258 // scope, so the draw gets processed before the filter texture gets deleted.
1259 if (filter_image)
1260 gl_->Flush();
1262 if (!use_shaders_for_blending)
1263 RestoreBlendFuncToDefault(blend_mode);
1266 struct SolidColorProgramUniforms {
1267 unsigned program;
1268 unsigned matrix_location;
1269 unsigned viewport_location;
1270 unsigned quad_location;
1271 unsigned edge_location;
1272 unsigned color_location;
1275 template <class T>
1276 static void SolidColorUniformLocation(T program,
1277 SolidColorProgramUniforms* uniforms) {
1278 uniforms->program = program->program();
1279 uniforms->matrix_location = program->vertex_shader().matrix_location();
1280 uniforms->viewport_location = program->vertex_shader().viewport_location();
1281 uniforms->quad_location = program->vertex_shader().quad_location();
1282 uniforms->edge_location = program->vertex_shader().edge_location();
1283 uniforms->color_location = program->fragment_shader().color_location();
1286 namespace {
1287 // These functions determine if a quad, clipped by a clip_region contains
1288 // the entire {top|bottom|left|right} edge.
1289 bool is_top(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1290 if (!quad->IsTopEdge())
1291 return false;
1292 if (!clip_region)
1293 return true;
1295 return std::abs(clip_region->p1().y()) < kAntiAliasingEpsilon &&
1296 std::abs(clip_region->p2().y()) < kAntiAliasingEpsilon;
1299 bool is_bottom(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1300 if (!quad->IsBottomEdge())
1301 return false;
1302 if (!clip_region)
1303 return true;
1305 return std::abs(clip_region->p3().y() -
1306 quad->shared_quad_state->content_bounds.height()) <
1307 kAntiAliasingEpsilon &&
1308 std::abs(clip_region->p4().y() -
1309 quad->shared_quad_state->content_bounds.height()) <
1310 kAntiAliasingEpsilon;
1313 bool is_left(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1314 if (!quad->IsLeftEdge())
1315 return false;
1316 if (!clip_region)
1317 return true;
1319 return std::abs(clip_region->p1().x()) < kAntiAliasingEpsilon &&
1320 std::abs(clip_region->p4().x()) < kAntiAliasingEpsilon;
1323 bool is_right(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1324 if (!quad->IsRightEdge())
1325 return false;
1326 if (!clip_region)
1327 return true;
1329 return std::abs(clip_region->p2().x() -
1330 quad->shared_quad_state->content_bounds.width()) <
1331 kAntiAliasingEpsilon &&
1332 std::abs(clip_region->p3().x() -
1333 quad->shared_quad_state->content_bounds.width()) <
1334 kAntiAliasingEpsilon;
1336 } // anonymous namespace
1338 static gfx::QuadF GetDeviceQuadWithAntialiasingOnExteriorEdges(
1339 const LayerQuad& device_layer_edges,
1340 const gfx::Transform& device_transform,
1341 const gfx::QuadF* clip_region,
1342 const DrawQuad* quad) {
1343 gfx::RectF tile_rect = quad->visible_rect;
1344 gfx::QuadF tile_quad(tile_rect);
1346 if (clip_region) {
1347 if (quad->material != DrawQuad::RENDER_PASS) {
1348 tile_quad = *clip_region;
1349 } else {
1350 GetScaledRegion(quad->rect, clip_region, &tile_quad);
1354 gfx::PointF bottom_right = tile_quad.p3();
1355 gfx::PointF bottom_left = tile_quad.p4();
1356 gfx::PointF top_left = tile_quad.p1();
1357 gfx::PointF top_right = tile_quad.p2();
1358 bool clipped = false;
1360 // Map points to device space. We ignore |clipped|, since the result of
1361 // |MapPoint()| still produces a valid point to draw the quad with. When
1362 // clipped, the point will be outside of the viewport. See crbug.com/416367.
1363 bottom_right = MathUtil::MapPoint(device_transform, bottom_right, &clipped);
1364 bottom_left = MathUtil::MapPoint(device_transform, bottom_left, &clipped);
1365 top_left = MathUtil::MapPoint(device_transform, top_left, &clipped);
1366 top_right = MathUtil::MapPoint(device_transform, top_right, &clipped);
1368 LayerQuad::Edge bottom_edge(bottom_right, bottom_left);
1369 LayerQuad::Edge left_edge(bottom_left, top_left);
1370 LayerQuad::Edge top_edge(top_left, top_right);
1371 LayerQuad::Edge right_edge(top_right, bottom_right);
1373 // Only apply anti-aliasing to edges not clipped by culling or scissoring.
1374 // If an edge is degenerate we do not want to replace it with a "proper" edge
1375 // as that will cause the quad to possibly expand is strange ways.
1376 if (!top_edge.degenerate() && is_top(clip_region, quad) &&
1377 tile_rect.y() == quad->rect.y()) {
1378 top_edge = device_layer_edges.top();
1380 if (!left_edge.degenerate() && is_left(clip_region, quad) &&
1381 tile_rect.x() == quad->rect.x()) {
1382 left_edge = device_layer_edges.left();
1384 if (!right_edge.degenerate() && is_right(clip_region, quad) &&
1385 tile_rect.right() == quad->rect.right()) {
1386 right_edge = device_layer_edges.right();
1388 if (!bottom_edge.degenerate() && is_bottom(clip_region, quad) &&
1389 tile_rect.bottom() == quad->rect.bottom()) {
1390 bottom_edge = device_layer_edges.bottom();
1393 float sign = tile_quad.IsCounterClockwise() ? -1 : 1;
1394 bottom_edge.scale(sign);
1395 left_edge.scale(sign);
1396 top_edge.scale(sign);
1397 right_edge.scale(sign);
1399 // Create device space quad.
1400 return LayerQuad(left_edge, top_edge, right_edge, bottom_edge).ToQuadF();
1403 float GetTotalQuadError(const gfx::QuadF* clipped_quad,
1404 const gfx::QuadF* ideal_rect) {
1405 return (clipped_quad->p1() - ideal_rect->p1()).LengthSquared() +
1406 (clipped_quad->p2() - ideal_rect->p2()).LengthSquared() +
1407 (clipped_quad->p3() - ideal_rect->p3()).LengthSquared() +
1408 (clipped_quad->p4() - ideal_rect->p4()).LengthSquared();
1411 // Attempt to rotate the clipped quad until it lines up the most
1412 // correctly. This is necessary because we check the edges of this
1413 // quad against the expected left/right/top/bottom for anti-aliasing.
1414 void AlignQuadToBoundingBox(gfx::QuadF* clipped_quad) {
1415 gfx::QuadF bounding_quad = gfx::QuadF(clipped_quad->BoundingBox());
1416 gfx::QuadF best_rotation = *clipped_quad;
1417 float least_error_amount = GetTotalQuadError(clipped_quad, &bounding_quad);
1418 for (size_t i = 1; i < 4; ++i) {
1419 clipped_quad->Realign(1);
1420 float new_error = GetTotalQuadError(clipped_quad, &bounding_quad);
1421 if (new_error < least_error_amount) {
1422 least_error_amount = new_error;
1423 best_rotation = *clipped_quad;
1426 *clipped_quad = best_rotation;
1429 // static
1430 bool GLRenderer::ShouldAntialiasQuad(const gfx::Transform& device_transform,
1431 const DrawQuad* quad,
1432 bool force_antialiasing) {
1433 bool is_render_pass_quad = (quad->material == DrawQuad::RENDER_PASS);
1434 // For render pass quads, |device_transform| already contains quad's rect.
1435 // TODO(rosca@adobe.com): remove branching on is_render_pass_quad
1436 // crbug.com/429702
1437 if (!is_render_pass_quad && !quad->IsEdge())
1438 return false;
1439 gfx::RectF content_rect =
1440 is_render_pass_quad ? QuadVertexRect() : quad->visibleContentRect();
1442 bool clipped = false;
1443 gfx::QuadF device_layer_quad =
1444 MathUtil::MapQuad(device_transform, gfx::QuadF(content_rect), &clipped);
1446 if (device_layer_quad.BoundingBox().IsEmpty())
1447 return false;
1449 bool is_axis_aligned_in_target = device_layer_quad.IsRectilinear();
1450 bool is_nearest_rect_within_epsilon =
1451 is_axis_aligned_in_target &&
1452 gfx::IsNearestRectWithinDistance(device_layer_quad.BoundingBox(),
1453 kAntiAliasingEpsilon);
1454 // AAing clipped quads is not supported by the code yet.
1455 bool use_aa = !clipped && !is_nearest_rect_within_epsilon;
1456 return use_aa || force_antialiasing;
1459 // static
1460 void GLRenderer::SetupQuadForClippingAndAntialiasing(
1461 const gfx::Transform& device_transform,
1462 const DrawQuad* quad,
1463 bool use_aa,
1464 const gfx::QuadF* clip_region,
1465 gfx::QuadF* local_quad,
1466 float edge[24]) {
1467 bool is_render_pass_quad = (quad->material == DrawQuad::RENDER_PASS);
1468 gfx::QuadF rotated_clip;
1469 const gfx::QuadF* local_clip_region = clip_region;
1470 if (local_clip_region) {
1471 rotated_clip = *clip_region;
1472 AlignQuadToBoundingBox(&rotated_clip);
1473 local_clip_region = &rotated_clip;
1476 gfx::QuadF content_rect = is_render_pass_quad
1477 ? gfx::QuadF(QuadVertexRect())
1478 : gfx::QuadF(quad->visibleContentRect());
1479 if (!use_aa) {
1480 if (local_clip_region) {
1481 if (!is_render_pass_quad) {
1482 content_rect = *local_clip_region;
1483 } else {
1484 GetScaledRegion(quad->rect, local_clip_region, &content_rect);
1486 *local_quad = content_rect;
1488 return;
1490 bool clipped = false;
1491 gfx::QuadF device_layer_quad =
1492 MathUtil::MapQuad(device_transform, content_rect, &clipped);
1494 LayerQuad device_layer_bounds(gfx::QuadF(device_layer_quad.BoundingBox()));
1495 device_layer_bounds.InflateAntiAliasingDistance();
1497 LayerQuad device_layer_edges(device_layer_quad);
1498 device_layer_edges.InflateAntiAliasingDistance();
1500 device_layer_edges.ToFloatArray(edge);
1501 device_layer_bounds.ToFloatArray(&edge[12]);
1503 // If we have a clip region then we are split, and therefore
1504 // by necessity, at least one of our edges is not an external
1505 // one.
1506 bool is_full_rect = quad->visible_rect == quad->rect;
1508 bool region_contains_all_outside_edges =
1509 is_full_rect &&
1510 (is_top(local_clip_region, quad) && is_left(local_clip_region, quad) &&
1511 is_bottom(local_clip_region, quad) && is_right(local_clip_region, quad));
1513 bool use_aa_on_all_four_edges =
1514 !local_clip_region &&
1515 (is_render_pass_quad || region_contains_all_outside_edges);
1517 gfx::QuadF device_quad =
1518 use_aa_on_all_four_edges
1519 ? device_layer_edges.ToQuadF()
1520 : GetDeviceQuadWithAntialiasingOnExteriorEdges(
1521 device_layer_edges, device_transform, local_clip_region, quad);
1523 // Map device space quad to local space. device_transform has no 3d
1524 // component since it was flattened, so we don't need to project. We should
1525 // have already checked that the transform was uninvertible above.
1526 gfx::Transform inverse_device_transform(gfx::Transform::kSkipInitialization);
1527 bool did_invert = device_transform.GetInverse(&inverse_device_transform);
1528 DCHECK(did_invert);
1529 *local_quad =
1530 MathUtil::MapQuad(inverse_device_transform, device_quad, &clipped);
1531 // We should not DCHECK(!clipped) here, because anti-aliasing inflation may
1532 // cause device_quad to become clipped. To our knowledge this scenario does
1533 // not need to be handled differently than the unclipped case.
1536 void GLRenderer::DrawSolidColorQuad(const DrawingFrame* frame,
1537 const SolidColorDrawQuad* quad,
1538 const gfx::QuadF* clip_region) {
1539 gfx::Rect tile_rect = quad->visible_rect;
1541 SkColor color = quad->color;
1542 float opacity = quad->opacity();
1543 float alpha = (SkColorGetA(color) * (1.0f / 255.0f)) * opacity;
1545 // Early out if alpha is small enough that quad doesn't contribute to output.
1546 if (alpha < std::numeric_limits<float>::epsilon() &&
1547 quad->ShouldDrawWithBlending())
1548 return;
1550 gfx::Transform device_transform =
1551 frame->window_matrix * frame->projection_matrix * quad->quadTransform();
1552 device_transform.FlattenTo2d();
1553 if (!device_transform.IsInvertible())
1554 return;
1556 bool force_aa = false;
1557 gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1558 float edge[24];
1559 bool use_aa = settings_->allow_antialiasing &&
1560 !quad->force_anti_aliasing_off &&
1561 ShouldAntialiasQuad(device_transform, quad, force_aa);
1562 SetupQuadForClippingAndAntialiasing(device_transform, quad, use_aa,
1563 clip_region, &local_quad, edge);
1565 SolidColorProgramUniforms uniforms;
1566 if (use_aa) {
1567 SolidColorUniformLocation(GetSolidColorProgramAA(), &uniforms);
1568 } else {
1569 SolidColorUniformLocation(GetSolidColorProgram(), &uniforms);
1571 SetUseProgram(uniforms.program);
1573 gl_->Uniform4f(uniforms.color_location,
1574 (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
1575 (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
1576 (SkColorGetB(color) * (1.0f / 255.0f)) * alpha, alpha);
1577 if (use_aa) {
1578 float viewport[4] = {
1579 static_cast<float>(current_window_space_viewport_.x()),
1580 static_cast<float>(current_window_space_viewport_.y()),
1581 static_cast<float>(current_window_space_viewport_.width()),
1582 static_cast<float>(current_window_space_viewport_.height()),
1584 gl_->Uniform4fv(uniforms.viewport_location, 1, viewport);
1585 gl_->Uniform3fv(uniforms.edge_location, 8, edge);
1588 // Enable blending when the quad properties require it or if we decided
1589 // to use antialiasing.
1590 SetBlendEnabled(quad->ShouldDrawWithBlending() || use_aa);
1592 // Normalize to tile_rect.
1593 local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1595 SetShaderQuadF(local_quad, uniforms.quad_location);
1597 // The transform and vertex data are used to figure out the extents that the
1598 // un-antialiased quad should have and which vertex this is and the float
1599 // quad passed in via uniform is the actual geometry that gets used to draw
1600 // it. This is why this centered rect is used and not the original quad_rect.
1601 gfx::RectF centered_rect(
1602 gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1603 tile_rect.size());
1604 DrawQuadGeometry(
1605 frame, quad->quadTransform(), centered_rect, uniforms.matrix_location);
1608 struct TileProgramUniforms {
1609 unsigned program;
1610 unsigned matrix_location;
1611 unsigned viewport_location;
1612 unsigned quad_location;
1613 unsigned edge_location;
1614 unsigned vertex_tex_transform_location;
1615 unsigned sampler_location;
1616 unsigned fragment_tex_transform_location;
1617 unsigned alpha_location;
1620 template <class T>
1621 static void TileUniformLocation(T program, TileProgramUniforms* uniforms) {
1622 uniforms->program = program->program();
1623 uniforms->matrix_location = program->vertex_shader().matrix_location();
1624 uniforms->viewport_location = program->vertex_shader().viewport_location();
1625 uniforms->quad_location = program->vertex_shader().quad_location();
1626 uniforms->edge_location = program->vertex_shader().edge_location();
1627 uniforms->vertex_tex_transform_location =
1628 program->vertex_shader().vertex_tex_transform_location();
1630 uniforms->sampler_location = program->fragment_shader().sampler_location();
1631 uniforms->alpha_location = program->fragment_shader().alpha_location();
1632 uniforms->fragment_tex_transform_location =
1633 program->fragment_shader().fragment_tex_transform_location();
1636 void GLRenderer::DrawTileQuad(const DrawingFrame* frame,
1637 const TileDrawQuad* quad,
1638 const gfx::QuadF* clip_region) {
1639 DrawContentQuad(frame, quad, quad->resource_id, clip_region);
1642 void GLRenderer::DrawContentQuad(const DrawingFrame* frame,
1643 const ContentDrawQuadBase* quad,
1644 ResourceProvider::ResourceId resource_id,
1645 const gfx::QuadF* clip_region) {
1646 gfx::Transform device_transform =
1647 frame->window_matrix * frame->projection_matrix * quad->quadTransform();
1648 device_transform.FlattenTo2d();
1650 bool use_aa = settings_->allow_antialiasing &&
1651 ShouldAntialiasQuad(device_transform, quad, false);
1653 // TODO(timav): simplify coordinate transformations in DrawContentQuadAA
1654 // similar to the way DrawContentQuadNoAA works and then consider
1655 // combining DrawContentQuadAA and DrawContentQuadNoAA into one method.
1656 if (use_aa)
1657 DrawContentQuadAA(frame, quad, resource_id, device_transform, clip_region);
1658 else
1659 DrawContentQuadNoAA(frame, quad, resource_id, clip_region);
1662 void GLRenderer::DrawContentQuadAA(const DrawingFrame* frame,
1663 const ContentDrawQuadBase* quad,
1664 ResourceProvider::ResourceId resource_id,
1665 const gfx::Transform& device_transform,
1666 const gfx::QuadF* clip_region) {
1667 if (!device_transform.IsInvertible())
1668 return;
1670 gfx::Rect tile_rect = quad->visible_rect;
1672 gfx::RectF tex_coord_rect = MathUtil::ScaleRectProportional(
1673 quad->tex_coord_rect, quad->rect, tile_rect);
1674 float tex_to_geom_scale_x = quad->rect.width() / quad->tex_coord_rect.width();
1675 float tex_to_geom_scale_y =
1676 quad->rect.height() / quad->tex_coord_rect.height();
1678 gfx::RectF clamp_geom_rect(tile_rect);
1679 gfx::RectF clamp_tex_rect(tex_coord_rect);
1680 // Clamp texture coordinates to avoid sampling outside the layer
1681 // by deflating the tile region half a texel or half a texel
1682 // minus epsilon for one pixel layers. The resulting clamp region
1683 // is mapped to the unit square by the vertex shader and mapped
1684 // back to normalized texture coordinates by the fragment shader
1685 // after being clamped to 0-1 range.
1686 float tex_clamp_x =
1687 std::min(0.5f, 0.5f * clamp_tex_rect.width() - kAntiAliasingEpsilon);
1688 float tex_clamp_y =
1689 std::min(0.5f, 0.5f * clamp_tex_rect.height() - kAntiAliasingEpsilon);
1690 float geom_clamp_x =
1691 std::min(tex_clamp_x * tex_to_geom_scale_x,
1692 0.5f * clamp_geom_rect.width() - kAntiAliasingEpsilon);
1693 float geom_clamp_y =
1694 std::min(tex_clamp_y * tex_to_geom_scale_y,
1695 0.5f * clamp_geom_rect.height() - kAntiAliasingEpsilon);
1696 clamp_geom_rect.Inset(geom_clamp_x, geom_clamp_y, geom_clamp_x, geom_clamp_y);
1697 clamp_tex_rect.Inset(tex_clamp_x, tex_clamp_y, tex_clamp_x, tex_clamp_y);
1699 // Map clamping rectangle to unit square.
1700 float vertex_tex_translate_x = -clamp_geom_rect.x() / clamp_geom_rect.width();
1701 float vertex_tex_translate_y =
1702 -clamp_geom_rect.y() / clamp_geom_rect.height();
1703 float vertex_tex_scale_x = tile_rect.width() / clamp_geom_rect.width();
1704 float vertex_tex_scale_y = tile_rect.height() / clamp_geom_rect.height();
1706 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1707 gl_, &highp_threshold_cache_, highp_threshold_min_, quad->texture_size);
1709 gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1710 float edge[24];
1711 SetupQuadForClippingAndAntialiasing(device_transform, quad, true, clip_region,
1712 &local_quad, edge);
1713 ResourceProvider::ScopedSamplerGL quad_resource_lock(
1714 resource_provider_, resource_id,
1715 quad->nearest_neighbor ? GL_NEAREST : GL_LINEAR);
1716 SamplerType sampler =
1717 SamplerTypeFromTextureTarget(quad_resource_lock.target());
1719 float fragment_tex_translate_x = clamp_tex_rect.x();
1720 float fragment_tex_translate_y = clamp_tex_rect.y();
1721 float fragment_tex_scale_x = clamp_tex_rect.width();
1722 float fragment_tex_scale_y = clamp_tex_rect.height();
1724 // Map to normalized texture coordinates.
1725 if (sampler != SAMPLER_TYPE_2D_RECT) {
1726 gfx::Size texture_size = quad->texture_size;
1727 DCHECK(!texture_size.IsEmpty());
1728 fragment_tex_translate_x /= texture_size.width();
1729 fragment_tex_translate_y /= texture_size.height();
1730 fragment_tex_scale_x /= texture_size.width();
1731 fragment_tex_scale_y /= texture_size.height();
1734 TileProgramUniforms uniforms;
1735 if (quad->swizzle_contents) {
1736 TileUniformLocation(GetTileProgramSwizzleAA(tex_coord_precision, sampler),
1737 &uniforms);
1738 } else {
1739 TileUniformLocation(GetTileProgramAA(tex_coord_precision, sampler),
1740 &uniforms);
1743 SetUseProgram(uniforms.program);
1744 gl_->Uniform1i(uniforms.sampler_location, 0);
1746 float viewport[4] = {
1747 static_cast<float>(current_window_space_viewport_.x()),
1748 static_cast<float>(current_window_space_viewport_.y()),
1749 static_cast<float>(current_window_space_viewport_.width()),
1750 static_cast<float>(current_window_space_viewport_.height()),
1752 gl_->Uniform4fv(uniforms.viewport_location, 1, viewport);
1753 gl_->Uniform3fv(uniforms.edge_location, 8, edge);
1755 gl_->Uniform4f(uniforms.vertex_tex_transform_location, vertex_tex_translate_x,
1756 vertex_tex_translate_y, vertex_tex_scale_x,
1757 vertex_tex_scale_y);
1758 gl_->Uniform4f(uniforms.fragment_tex_transform_location,
1759 fragment_tex_translate_x, fragment_tex_translate_y,
1760 fragment_tex_scale_x, fragment_tex_scale_y);
1762 // Blending is required for antialiasing.
1763 SetBlendEnabled(true);
1765 // Normalize to tile_rect.
1766 local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1768 SetShaderOpacity(quad->opacity(), uniforms.alpha_location);
1769 SetShaderQuadF(local_quad, uniforms.quad_location);
1771 // The transform and vertex data are used to figure out the extents that the
1772 // un-antialiased quad should have and which vertex this is and the float
1773 // quad passed in via uniform is the actual geometry that gets used to draw
1774 // it. This is why this centered rect is used and not the original quad_rect.
1775 gfx::RectF centered_rect(
1776 gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1777 tile_rect.size());
1778 DrawQuadGeometry(
1779 frame, quad->quadTransform(), centered_rect, uniforms.matrix_location);
1782 void GLRenderer::DrawContentQuadNoAA(const DrawingFrame* frame,
1783 const ContentDrawQuadBase* quad,
1784 ResourceProvider::ResourceId resource_id,
1785 const gfx::QuadF* clip_region) {
1786 gfx::RectF tex_coord_rect = MathUtil::ScaleRectProportional(
1787 quad->tex_coord_rect, quad->rect, quad->visible_rect);
1788 float tex_to_geom_scale_x = quad->rect.width() / quad->tex_coord_rect.width();
1789 float tex_to_geom_scale_y =
1790 quad->rect.height() / quad->tex_coord_rect.height();
1792 bool scaled = (tex_to_geom_scale_x != 1.f || tex_to_geom_scale_y != 1.f);
1793 GLenum filter =
1794 (scaled || !quad->quadTransform().IsIdentityOrIntegerTranslation()) &&
1795 !quad->nearest_neighbor
1796 ? GL_LINEAR
1797 : GL_NEAREST;
1799 ResourceProvider::ScopedSamplerGL quad_resource_lock(
1800 resource_provider_, resource_id, filter);
1801 SamplerType sampler =
1802 SamplerTypeFromTextureTarget(quad_resource_lock.target());
1804 float vertex_tex_translate_x = tex_coord_rect.x();
1805 float vertex_tex_translate_y = tex_coord_rect.y();
1806 float vertex_tex_scale_x = tex_coord_rect.width();
1807 float vertex_tex_scale_y = tex_coord_rect.height();
1809 // Map to normalized texture coordinates.
1810 if (sampler != SAMPLER_TYPE_2D_RECT) {
1811 gfx::Size texture_size = quad->texture_size;
1812 DCHECK(!texture_size.IsEmpty());
1813 vertex_tex_translate_x /= texture_size.width();
1814 vertex_tex_translate_y /= texture_size.height();
1815 vertex_tex_scale_x /= texture_size.width();
1816 vertex_tex_scale_y /= texture_size.height();
1819 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1820 gl_, &highp_threshold_cache_, highp_threshold_min_, quad->texture_size);
1822 TileProgramUniforms uniforms;
1823 if (quad->ShouldDrawWithBlending()) {
1824 if (quad->swizzle_contents) {
1825 TileUniformLocation(GetTileProgramSwizzle(tex_coord_precision, sampler),
1826 &uniforms);
1827 } else {
1828 TileUniformLocation(GetTileProgram(tex_coord_precision, sampler),
1829 &uniforms);
1831 } else {
1832 if (quad->swizzle_contents) {
1833 TileUniformLocation(
1834 GetTileProgramSwizzleOpaque(tex_coord_precision, sampler), &uniforms);
1835 } else {
1836 TileUniformLocation(GetTileProgramOpaque(tex_coord_precision, sampler),
1837 &uniforms);
1841 SetUseProgram(uniforms.program);
1842 gl_->Uniform1i(uniforms.sampler_location, 0);
1844 gl_->Uniform4f(uniforms.vertex_tex_transform_location, vertex_tex_translate_x,
1845 vertex_tex_translate_y, vertex_tex_scale_x,
1846 vertex_tex_scale_y);
1848 SetBlendEnabled(quad->ShouldDrawWithBlending());
1850 SetShaderOpacity(quad->opacity(), uniforms.alpha_location);
1852 // Pass quad coordinates to the uniform in the same order as GeometryBinding
1853 // does, then vertices will match the texture mapping in the vertex buffer.
1854 // The method SetShaderQuadF() changes the order of vertices and so it's
1855 // not used here.
1856 gfx::QuadF tile_rect(quad->visible_rect);
1857 float width = quad->visible_rect.width();
1858 float height = quad->visible_rect.height();
1859 gfx::PointF top_left = quad->visible_rect.origin();
1860 if (clip_region) {
1861 tile_rect = *clip_region;
1862 float gl_uv[8] = {
1863 (tile_rect.p4().x() - top_left.x()) / width,
1864 (tile_rect.p4().y() - top_left.y()) / height,
1865 (tile_rect.p1().x() - top_left.x()) / width,
1866 (tile_rect.p1().y() - top_left.y()) / height,
1867 (tile_rect.p2().x() - top_left.x()) / width,
1868 (tile_rect.p2().y() - top_left.y()) / height,
1869 (tile_rect.p3().x() - top_left.x()) / width,
1870 (tile_rect.p3().y() - top_left.y()) / height,
1872 PrepareGeometry(CLIPPED_BINDING);
1873 clipped_geometry_->InitializeCustomQuadWithUVs(
1874 gfx::QuadF(quad->visible_rect), gl_uv);
1875 } else {
1876 PrepareGeometry(SHARED_BINDING);
1878 float gl_quad[8] = {
1879 tile_rect.p4().x(),
1880 tile_rect.p4().y(),
1881 tile_rect.p1().x(),
1882 tile_rect.p1().y(),
1883 tile_rect.p2().x(),
1884 tile_rect.p2().y(),
1885 tile_rect.p3().x(),
1886 tile_rect.p3().y(),
1888 gl_->Uniform2fv(uniforms.quad_location, 4, gl_quad);
1890 static float gl_matrix[16];
1891 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad->quadTransform());
1892 gl_->UniformMatrix4fv(uniforms.matrix_location, 1, false, &gl_matrix[0]);
1894 gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
1897 void GLRenderer::DrawYUVVideoQuad(const DrawingFrame* frame,
1898 const YUVVideoDrawQuad* quad,
1899 const gfx::QuadF* clip_region) {
1900 SetBlendEnabled(quad->ShouldDrawWithBlending());
1902 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1903 gl_,
1904 &highp_threshold_cache_,
1905 highp_threshold_min_,
1906 quad->shared_quad_state->visible_content_rect.bottom_right());
1908 bool use_alpha_plane = quad->a_plane_resource_id != 0;
1910 ResourceProvider::ScopedSamplerGL y_plane_lock(
1911 resource_provider_, quad->y_plane_resource_id, GL_TEXTURE1, GL_LINEAR);
1912 ResourceProvider::ScopedSamplerGL u_plane_lock(
1913 resource_provider_, quad->u_plane_resource_id, GL_TEXTURE2, GL_LINEAR);
1914 DCHECK_EQ(y_plane_lock.target(), u_plane_lock.target());
1915 ResourceProvider::ScopedSamplerGL v_plane_lock(
1916 resource_provider_, quad->v_plane_resource_id, GL_TEXTURE3, GL_LINEAR);
1917 DCHECK_EQ(y_plane_lock.target(), v_plane_lock.target());
1918 scoped_ptr<ResourceProvider::ScopedSamplerGL> a_plane_lock;
1919 if (use_alpha_plane) {
1920 a_plane_lock.reset(new ResourceProvider::ScopedSamplerGL(
1921 resource_provider_, quad->a_plane_resource_id, GL_TEXTURE4, GL_LINEAR));
1922 DCHECK_EQ(y_plane_lock.target(), a_plane_lock->target());
1925 // All planes must have the same sampler type.
1926 SamplerType sampler = SamplerTypeFromTextureTarget(y_plane_lock.target());
1928 int matrix_location = -1;
1929 int ya_tex_scale_location = -1;
1930 int ya_tex_offset_location = -1;
1931 int uv_tex_scale_location = -1;
1932 int uv_tex_offset_location = -1;
1933 int ya_clamp_rect_location = -1;
1934 int uv_clamp_rect_location = -1;
1935 int y_texture_location = -1;
1936 int u_texture_location = -1;
1937 int v_texture_location = -1;
1938 int a_texture_location = -1;
1939 int yuv_matrix_location = -1;
1940 int yuv_adj_location = -1;
1941 int alpha_location = -1;
1942 if (use_alpha_plane) {
1943 const VideoYUVAProgram* program =
1944 GetVideoYUVAProgram(tex_coord_precision, sampler);
1945 DCHECK(program && (program->initialized() || IsContextLost()));
1946 SetUseProgram(program->program());
1947 matrix_location = program->vertex_shader().matrix_location();
1948 ya_tex_scale_location = program->vertex_shader().ya_tex_scale_location();
1949 ya_tex_offset_location = program->vertex_shader().ya_tex_offset_location();
1950 uv_tex_scale_location = program->vertex_shader().uv_tex_scale_location();
1951 uv_tex_offset_location = program->vertex_shader().uv_tex_offset_location();
1952 y_texture_location = program->fragment_shader().y_texture_location();
1953 u_texture_location = program->fragment_shader().u_texture_location();
1954 v_texture_location = program->fragment_shader().v_texture_location();
1955 a_texture_location = program->fragment_shader().a_texture_location();
1956 yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
1957 yuv_adj_location = program->fragment_shader().yuv_adj_location();
1958 ya_clamp_rect_location =
1959 program->fragment_shader().ya_clamp_rect_location();
1960 uv_clamp_rect_location =
1961 program->fragment_shader().uv_clamp_rect_location();
1962 alpha_location = program->fragment_shader().alpha_location();
1963 } else {
1964 const VideoYUVProgram* program =
1965 GetVideoYUVProgram(tex_coord_precision, sampler);
1966 DCHECK(program && (program->initialized() || IsContextLost()));
1967 SetUseProgram(program->program());
1968 matrix_location = program->vertex_shader().matrix_location();
1969 ya_tex_scale_location = program->vertex_shader().ya_tex_scale_location();
1970 ya_tex_offset_location = program->vertex_shader().ya_tex_offset_location();
1971 uv_tex_scale_location = program->vertex_shader().uv_tex_scale_location();
1972 uv_tex_offset_location = program->vertex_shader().uv_tex_offset_location();
1973 y_texture_location = program->fragment_shader().y_texture_location();
1974 u_texture_location = program->fragment_shader().u_texture_location();
1975 v_texture_location = program->fragment_shader().v_texture_location();
1976 yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
1977 yuv_adj_location = program->fragment_shader().yuv_adj_location();
1978 ya_clamp_rect_location =
1979 program->fragment_shader().ya_clamp_rect_location();
1980 uv_clamp_rect_location =
1981 program->fragment_shader().uv_clamp_rect_location();
1982 alpha_location = program->fragment_shader().alpha_location();
1985 gfx::SizeF ya_tex_scale(1.0f, 1.0f);
1986 gfx::SizeF uv_tex_scale(1.0f, 1.0f);
1987 if (sampler != SAMPLER_TYPE_2D_RECT) {
1988 DCHECK(!quad->ya_tex_size.IsEmpty());
1989 DCHECK(!quad->uv_tex_size.IsEmpty());
1990 ya_tex_scale = gfx::SizeF(1.0f / quad->ya_tex_size.width(),
1991 1.0f / quad->ya_tex_size.height());
1992 uv_tex_scale = gfx::SizeF(1.0f / quad->uv_tex_size.width(),
1993 1.0f / quad->uv_tex_size.height());
1996 float ya_vertex_tex_translate_x =
1997 quad->ya_tex_coord_rect.x() * ya_tex_scale.width();
1998 float ya_vertex_tex_translate_y =
1999 quad->ya_tex_coord_rect.y() * ya_tex_scale.height();
2000 float ya_vertex_tex_scale_x =
2001 quad->ya_tex_coord_rect.width() * ya_tex_scale.width();
2002 float ya_vertex_tex_scale_y =
2003 quad->ya_tex_coord_rect.height() * ya_tex_scale.height();
2005 float uv_vertex_tex_translate_x =
2006 quad->uv_tex_coord_rect.x() * uv_tex_scale.width();
2007 float uv_vertex_tex_translate_y =
2008 quad->uv_tex_coord_rect.y() * uv_tex_scale.height();
2009 float uv_vertex_tex_scale_x =
2010 quad->uv_tex_coord_rect.width() * uv_tex_scale.width();
2011 float uv_vertex_tex_scale_y =
2012 quad->uv_tex_coord_rect.height() * uv_tex_scale.height();
2014 gl_->Uniform2f(ya_tex_scale_location, ya_vertex_tex_scale_x,
2015 ya_vertex_tex_scale_y);
2016 gl_->Uniform2f(ya_tex_offset_location, ya_vertex_tex_translate_x,
2017 ya_vertex_tex_translate_y);
2018 gl_->Uniform2f(uv_tex_scale_location, uv_vertex_tex_scale_x,
2019 uv_vertex_tex_scale_y);
2020 gl_->Uniform2f(uv_tex_offset_location, uv_vertex_tex_translate_x,
2021 uv_vertex_tex_translate_y);
2023 gfx::RectF ya_clamp_rect(ya_vertex_tex_translate_x, ya_vertex_tex_translate_y,
2024 ya_vertex_tex_scale_x, ya_vertex_tex_scale_y);
2025 ya_clamp_rect.Inset(0.5f * ya_tex_scale.width(),
2026 0.5f * ya_tex_scale.height());
2027 gfx::RectF uv_clamp_rect(uv_vertex_tex_translate_x, uv_vertex_tex_translate_y,
2028 uv_vertex_tex_scale_x, uv_vertex_tex_scale_y);
2029 uv_clamp_rect.Inset(0.5f * uv_tex_scale.width(),
2030 0.5f * uv_tex_scale.height());
2031 gl_->Uniform4f(ya_clamp_rect_location, ya_clamp_rect.x(), ya_clamp_rect.y(),
2032 ya_clamp_rect.right(), ya_clamp_rect.bottom());
2033 gl_->Uniform4f(uv_clamp_rect_location, uv_clamp_rect.x(), uv_clamp_rect.y(),
2034 uv_clamp_rect.right(), uv_clamp_rect.bottom());
2036 gl_->Uniform1i(y_texture_location, 1);
2037 gl_->Uniform1i(u_texture_location, 2);
2038 gl_->Uniform1i(v_texture_location, 3);
2039 if (use_alpha_plane)
2040 gl_->Uniform1i(a_texture_location, 4);
2042 // These values are magic numbers that are used in the transformation from YUV
2043 // to RGB color values. They are taken from the following webpage:
2044 // http://www.fourcc.org/fccyvrgb.php
2045 float yuv_to_rgb_rec601[9] = {
2046 1.164f, 1.164f, 1.164f, 0.0f, -.391f, 2.018f, 1.596f, -.813f, 0.0f,
2048 float yuv_to_rgb_jpeg[9] = {
2049 1.f, 1.f, 1.f, 0.0f, -.34414f, 1.772f, 1.402f, -.71414f, 0.0f,
2051 float yuv_to_rgb_rec709[9] = {
2052 1.164f, 1.164f, 1.164f, 0.0f, -0.213f, 2.112f, 1.793f, -0.533f, 0.0f,
2055 // These values map to 16, 128, and 128 respectively, and are computed
2056 // as a fraction over 256 (e.g. 16 / 256 = 0.0625).
2057 // They are used in the YUV to RGBA conversion formula:
2058 // Y - 16 : Gives 16 values of head and footroom for overshooting
2059 // U - 128 : Turns unsigned U into signed U [-128,127]
2060 // V - 128 : Turns unsigned V into signed V [-128,127]
2061 float yuv_adjust_constrained[3] = {
2062 -0.0625f, -0.5f, -0.5f,
2065 // Same as above, but without the head and footroom.
2066 float yuv_adjust_full[3] = {
2067 0.0f, -0.5f, -0.5f,
2070 float* yuv_to_rgb = NULL;
2071 float* yuv_adjust = NULL;
2073 switch (quad->color_space) {
2074 case YUVVideoDrawQuad::REC_601:
2075 yuv_to_rgb = yuv_to_rgb_rec601;
2076 yuv_adjust = yuv_adjust_constrained;
2077 break;
2078 case YUVVideoDrawQuad::REC_709:
2079 yuv_to_rgb = yuv_to_rgb_rec709;
2080 yuv_adjust = yuv_adjust_constrained;
2081 break;
2082 case YUVVideoDrawQuad::JPEG:
2083 yuv_to_rgb = yuv_to_rgb_jpeg;
2084 yuv_adjust = yuv_adjust_full;
2085 break;
2088 // The transform and vertex data are used to figure out the extents that the
2089 // un-antialiased quad should have and which vertex this is and the float
2090 // quad passed in via uniform is the actual geometry that gets used to draw
2091 // it. This is why this centered rect is used and not the original quad_rect.
2092 gfx::RectF tile_rect = quad->rect;
2093 gl_->UniformMatrix3fv(yuv_matrix_location, 1, 0, yuv_to_rgb);
2094 gl_->Uniform3fv(yuv_adj_location, 1, yuv_adjust);
2096 SetShaderOpacity(quad->opacity(), alpha_location);
2097 if (!clip_region) {
2098 DrawQuadGeometry(frame, quad->quadTransform(), tile_rect, matrix_location);
2099 } else {
2100 float uvs[8] = {0};
2101 GetScaledUVs(quad->visible_rect, clip_region, uvs);
2102 gfx::QuadF region_quad = *clip_region;
2103 region_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
2104 region_quad -= gfx::Vector2dF(0.5f, 0.5f);
2105 DrawQuadGeometryClippedByQuadF(frame, quad->quadTransform(), tile_rect,
2106 region_quad, matrix_location, uvs);
2110 void GLRenderer::DrawStreamVideoQuad(const DrawingFrame* frame,
2111 const StreamVideoDrawQuad* quad,
2112 const gfx::QuadF* clip_region) {
2113 SetBlendEnabled(quad->ShouldDrawWithBlending());
2115 static float gl_matrix[16];
2117 DCHECK(capabilities_.using_egl_image);
2119 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2120 gl_,
2121 &highp_threshold_cache_,
2122 highp_threshold_min_,
2123 quad->shared_quad_state->visible_content_rect.bottom_right());
2125 const VideoStreamTextureProgram* program =
2126 GetVideoStreamTextureProgram(tex_coord_precision);
2127 SetUseProgram(program->program());
2129 ToGLMatrix(&gl_matrix[0], quad->matrix);
2130 gl_->UniformMatrix4fv(program->vertex_shader().tex_matrix_location(), 1,
2131 false, gl_matrix);
2133 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
2134 quad->resource_id);
2135 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2136 gl_->BindTexture(GL_TEXTURE_EXTERNAL_OES, lock.texture_id());
2138 gl_->Uniform1i(program->fragment_shader().sampler_location(), 0);
2140 SetShaderOpacity(quad->opacity(),
2141 program->fragment_shader().alpha_location());
2142 if (!clip_region) {
2143 DrawQuadGeometry(frame, quad->quadTransform(), quad->rect,
2144 program->vertex_shader().matrix_location());
2145 } else {
2146 gfx::QuadF region_quad(*clip_region);
2147 region_quad.Scale(1.0f / quad->rect.width(), 1.0f / quad->rect.height());
2148 region_quad -= gfx::Vector2dF(0.5f, 0.5f);
2149 float uvs[8] = {0};
2150 GetScaledUVs(quad->visible_rect, clip_region, uvs);
2151 DrawQuadGeometryClippedByQuadF(
2152 frame, quad->quadTransform(), quad->rect, region_quad,
2153 program->vertex_shader().matrix_location(), uvs);
2157 struct TextureProgramBinding {
2158 template <class Program>
2159 void Set(Program* program) {
2160 DCHECK(program);
2161 program_id = program->program();
2162 sampler_location = program->fragment_shader().sampler_location();
2163 matrix_location = program->vertex_shader().matrix_location();
2164 background_color_location =
2165 program->fragment_shader().background_color_location();
2167 int program_id;
2168 int sampler_location;
2169 int matrix_location;
2170 int transform_location;
2171 int background_color_location;
2174 struct TexTransformTextureProgramBinding : TextureProgramBinding {
2175 template <class Program>
2176 void Set(Program* program) {
2177 TextureProgramBinding::Set(program);
2178 tex_transform_location = program->vertex_shader().tex_transform_location();
2179 vertex_opacity_location =
2180 program->vertex_shader().vertex_opacity_location();
2182 int tex_transform_location;
2183 int vertex_opacity_location;
2186 void GLRenderer::FlushTextureQuadCache(BoundGeometry flush_binding) {
2187 // Check to see if we have anything to draw.
2188 if (draw_cache_.program_id == -1)
2189 return;
2191 PrepareGeometry(flush_binding);
2193 // Set the correct blending mode.
2194 SetBlendEnabled(draw_cache_.needs_blending);
2196 // Bind the program to the GL state.
2197 SetUseProgram(draw_cache_.program_id);
2199 // Bind the correct texture sampler location.
2200 gl_->Uniform1i(draw_cache_.sampler_location, 0);
2202 // Assume the current active textures is 0.
2203 ResourceProvider::ScopedSamplerGL locked_quad(
2204 resource_provider_,
2205 draw_cache_.resource_id,
2206 draw_cache_.nearest_neighbor ? GL_NEAREST : GL_LINEAR);
2207 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2208 gl_->BindTexture(locked_quad.target(), locked_quad.texture_id());
2210 static_assert(sizeof(Float4) == 4 * sizeof(float),
2211 "Float4 struct should be densely packed");
2212 static_assert(sizeof(Float16) == 16 * sizeof(float),
2213 "Float16 struct should be densely packed");
2215 // Upload the tranforms for both points and uvs.
2216 gl_->UniformMatrix4fv(
2217 static_cast<int>(draw_cache_.matrix_location),
2218 static_cast<int>(draw_cache_.matrix_data.size()), false,
2219 reinterpret_cast<float*>(&draw_cache_.matrix_data.front()));
2220 gl_->Uniform4fv(static_cast<int>(draw_cache_.uv_xform_location),
2221 static_cast<int>(draw_cache_.uv_xform_data.size()),
2222 reinterpret_cast<float*>(&draw_cache_.uv_xform_data.front()));
2224 if (draw_cache_.background_color != SK_ColorTRANSPARENT) {
2225 Float4 background_color = PremultipliedColor(draw_cache_.background_color);
2226 gl_->Uniform4fv(draw_cache_.background_color_location, 1,
2227 background_color.data);
2230 gl_->Uniform1fv(
2231 static_cast<int>(draw_cache_.vertex_opacity_location),
2232 static_cast<int>(draw_cache_.vertex_opacity_data.size()),
2233 static_cast<float*>(&draw_cache_.vertex_opacity_data.front()));
2235 // Draw the quads!
2236 gl_->DrawElements(GL_TRIANGLES, 6 * draw_cache_.matrix_data.size(),
2237 GL_UNSIGNED_SHORT, 0);
2239 // Clear the cache.
2240 draw_cache_.program_id = -1;
2241 draw_cache_.uv_xform_data.resize(0);
2242 draw_cache_.vertex_opacity_data.resize(0);
2243 draw_cache_.matrix_data.resize(0);
2245 // If we had a clipped binding, prepare the shared binding for the
2246 // next inserts.
2247 if (flush_binding == CLIPPED_BINDING) {
2248 PrepareGeometry(SHARED_BINDING);
2252 void GLRenderer::EnqueueTextureQuad(const DrawingFrame* frame,
2253 const TextureDrawQuad* quad,
2254 const gfx::QuadF* clip_region) {
2255 // If we have a clip_region then we have to render the next quad
2256 // with dynamic geometry, therefore we must flush all pending
2257 // texture quads.
2258 if (clip_region) {
2259 // We send in false here because we want to flush what's currently in the
2260 // queue using the shared_geometry and not clipped_geometry
2261 FlushTextureQuadCache(SHARED_BINDING);
2264 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2265 gl_,
2266 &highp_threshold_cache_,
2267 highp_threshold_min_,
2268 quad->shared_quad_state->visible_content_rect.bottom_right());
2270 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
2271 quad->resource_id);
2272 const SamplerType sampler = SamplerTypeFromTextureTarget(lock.target());
2273 // Choose the correct texture program binding
2274 TexTransformTextureProgramBinding binding;
2275 if (quad->premultiplied_alpha) {
2276 if (quad->background_color == SK_ColorTRANSPARENT) {
2277 binding.Set(GetTextureProgram(tex_coord_precision, sampler));
2278 } else {
2279 binding.Set(GetTextureBackgroundProgram(tex_coord_precision, sampler));
2281 } else {
2282 if (quad->background_color == SK_ColorTRANSPARENT) {
2283 binding.Set(
2284 GetNonPremultipliedTextureProgram(tex_coord_precision, sampler));
2285 } else {
2286 binding.Set(GetNonPremultipliedTextureBackgroundProgram(
2287 tex_coord_precision, sampler));
2291 int resource_id = quad->resource_id;
2293 if (draw_cache_.program_id != binding.program_id ||
2294 draw_cache_.resource_id != resource_id ||
2295 draw_cache_.needs_blending != quad->ShouldDrawWithBlending() ||
2296 draw_cache_.nearest_neighbor != quad->nearest_neighbor ||
2297 draw_cache_.background_color != quad->background_color ||
2298 draw_cache_.matrix_data.size() >= 8) {
2299 FlushTextureQuadCache(SHARED_BINDING);
2300 draw_cache_.program_id = binding.program_id;
2301 draw_cache_.resource_id = resource_id;
2302 draw_cache_.needs_blending = quad->ShouldDrawWithBlending();
2303 draw_cache_.nearest_neighbor = quad->nearest_neighbor;
2304 draw_cache_.background_color = quad->background_color;
2306 draw_cache_.uv_xform_location = binding.tex_transform_location;
2307 draw_cache_.background_color_location = binding.background_color_location;
2308 draw_cache_.vertex_opacity_location = binding.vertex_opacity_location;
2309 draw_cache_.matrix_location = binding.matrix_location;
2310 draw_cache_.sampler_location = binding.sampler_location;
2313 // Generate the uv-transform
2314 if (!clip_region) {
2315 draw_cache_.uv_xform_data.push_back(UVTransform(quad));
2316 } else {
2317 Float4 uv_transform = {{0.0f, 0.0f, 1.0f, 1.0f}};
2318 draw_cache_.uv_xform_data.push_back(uv_transform);
2321 // Generate the vertex opacity
2322 const float opacity = quad->opacity();
2323 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[0] * opacity);
2324 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[1] * opacity);
2325 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[2] * opacity);
2326 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[3] * opacity);
2328 // Generate the transform matrix
2329 gfx::Transform quad_rect_matrix;
2330 QuadRectTransform(&quad_rect_matrix, quad->quadTransform(), quad->rect);
2331 quad_rect_matrix = frame->projection_matrix * quad_rect_matrix;
2333 Float16 m;
2334 quad_rect_matrix.matrix().asColMajorf(m.data);
2335 draw_cache_.matrix_data.push_back(m);
2337 if (clip_region) {
2338 gfx::QuadF scaled_region;
2339 if (!GetScaledRegion(quad->rect, clip_region, &scaled_region)) {
2340 scaled_region = SharedGeometryQuad().BoundingBox();
2342 // Both the scaled region and the SharedGeomtryQuad are in the space
2343 // -0.5->0.5. We need to move that to the space 0->1.
2344 float uv[8];
2345 uv[0] = scaled_region.p1().x() + 0.5f;
2346 uv[1] = scaled_region.p1().y() + 0.5f;
2347 uv[2] = scaled_region.p2().x() + 0.5f;
2348 uv[3] = scaled_region.p2().y() + 0.5f;
2349 uv[4] = scaled_region.p3().x() + 0.5f;
2350 uv[5] = scaled_region.p3().y() + 0.5f;
2351 uv[6] = scaled_region.p4().x() + 0.5f;
2352 uv[7] = scaled_region.p4().y() + 0.5f;
2353 PrepareGeometry(CLIPPED_BINDING);
2354 clipped_geometry_->InitializeCustomQuadWithUVs(scaled_region, uv);
2355 FlushTextureQuadCache(CLIPPED_BINDING);
2359 void GLRenderer::DrawIOSurfaceQuad(const DrawingFrame* frame,
2360 const IOSurfaceDrawQuad* quad,
2361 const gfx::QuadF* clip_region) {
2362 SetBlendEnabled(quad->ShouldDrawWithBlending());
2364 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2365 gl_,
2366 &highp_threshold_cache_,
2367 highp_threshold_min_,
2368 quad->shared_quad_state->visible_content_rect.bottom_right());
2370 TexTransformTextureProgramBinding binding;
2371 binding.Set(GetTextureIOSurfaceProgram(tex_coord_precision));
2373 SetUseProgram(binding.program_id);
2374 gl_->Uniform1i(binding.sampler_location, 0);
2375 if (quad->orientation == IOSurfaceDrawQuad::FLIPPED) {
2376 gl_->Uniform4f(
2377 binding.tex_transform_location, 0, quad->io_surface_size.height(),
2378 quad->io_surface_size.width(), quad->io_surface_size.height() * -1.0f);
2379 } else {
2380 gl_->Uniform4f(binding.tex_transform_location, 0, 0,
2381 quad->io_surface_size.width(),
2382 quad->io_surface_size.height());
2385 const float vertex_opacity[] = {quad->opacity(), quad->opacity(),
2386 quad->opacity(), quad->opacity()};
2387 gl_->Uniform1fv(binding.vertex_opacity_location, 4, vertex_opacity);
2389 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
2390 quad->io_surface_resource_id);
2391 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2392 gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, lock.texture_id());
2394 if (!clip_region) {
2395 DrawQuadGeometry(frame, quad->quadTransform(), quad->rect,
2396 binding.matrix_location);
2397 } else {
2398 float uvs[8] = {0};
2399 GetScaledUVs(quad->visible_rect, clip_region, uvs);
2400 DrawQuadGeometryClippedByQuadF(frame, quad->quadTransform(), quad->rect,
2401 *clip_region, binding.matrix_location, uvs);
2404 gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
2407 void GLRenderer::FinishDrawingFrame(DrawingFrame* frame) {
2408 if (use_sync_query_) {
2409 DCHECK(current_sync_query_);
2410 current_sync_query_->End();
2411 pending_sync_queries_.push_back(current_sync_query_.Pass());
2414 current_framebuffer_lock_ = nullptr;
2415 swap_buffer_rect_.Union(gfx::ToEnclosingRect(frame->root_damage_rect));
2417 gl_->Disable(GL_BLEND);
2418 blend_shadow_ = false;
2420 ScheduleOverlays(frame);
2423 void GLRenderer::FinishDrawingQuadList() {
2424 FlushTextureQuadCache(SHARED_BINDING);
2427 bool GLRenderer::FlippedFramebuffer(const DrawingFrame* frame) const {
2428 if (frame->current_render_pass != frame->root_render_pass)
2429 return true;
2430 return FlippedRootFramebuffer();
2433 bool GLRenderer::FlippedRootFramebuffer() const {
2434 // GL is normally flipped, so a flipped output results in an unflipping.
2435 return !output_surface_->capabilities().flipped_output_surface;
2438 void GLRenderer::EnsureScissorTestEnabled() {
2439 if (is_scissor_enabled_)
2440 return;
2442 FlushTextureQuadCache(SHARED_BINDING);
2443 gl_->Enable(GL_SCISSOR_TEST);
2444 is_scissor_enabled_ = true;
2447 void GLRenderer::EnsureScissorTestDisabled() {
2448 if (!is_scissor_enabled_)
2449 return;
2451 FlushTextureQuadCache(SHARED_BINDING);
2452 gl_->Disable(GL_SCISSOR_TEST);
2453 is_scissor_enabled_ = false;
2456 void GLRenderer::CopyCurrentRenderPassToBitmap(
2457 DrawingFrame* frame,
2458 scoped_ptr<CopyOutputRequest> request) {
2459 TRACE_EVENT0("cc", "GLRenderer::CopyCurrentRenderPassToBitmap");
2460 gfx::Rect copy_rect = frame->current_render_pass->output_rect;
2461 if (request->has_area())
2462 copy_rect.Intersect(request->area());
2463 GetFramebufferPixelsAsync(frame, copy_rect, request.Pass());
2466 void GLRenderer::ToGLMatrix(float* gl_matrix, const gfx::Transform& transform) {
2467 transform.matrix().asColMajorf(gl_matrix);
2470 void GLRenderer::SetShaderQuadF(const gfx::QuadF& quad, int quad_location) {
2471 if (quad_location == -1)
2472 return;
2474 float gl_quad[8];
2475 gl_quad[0] = quad.p1().x();
2476 gl_quad[1] = quad.p1().y();
2477 gl_quad[2] = quad.p2().x();
2478 gl_quad[3] = quad.p2().y();
2479 gl_quad[4] = quad.p3().x();
2480 gl_quad[5] = quad.p3().y();
2481 gl_quad[6] = quad.p4().x();
2482 gl_quad[7] = quad.p4().y();
2483 gl_->Uniform2fv(quad_location, 4, gl_quad);
2486 void GLRenderer::SetShaderOpacity(float opacity, int alpha_location) {
2487 if (alpha_location != -1)
2488 gl_->Uniform1f(alpha_location, opacity);
2491 void GLRenderer::SetStencilEnabled(bool enabled) {
2492 if (enabled == stencil_shadow_)
2493 return;
2495 if (enabled)
2496 gl_->Enable(GL_STENCIL_TEST);
2497 else
2498 gl_->Disable(GL_STENCIL_TEST);
2499 stencil_shadow_ = enabled;
2502 void GLRenderer::SetBlendEnabled(bool enabled) {
2503 if (enabled == blend_shadow_)
2504 return;
2506 if (enabled)
2507 gl_->Enable(GL_BLEND);
2508 else
2509 gl_->Disable(GL_BLEND);
2510 blend_shadow_ = enabled;
2513 void GLRenderer::SetUseProgram(unsigned program) {
2514 if (program == program_shadow_)
2515 return;
2516 gl_->UseProgram(program);
2517 program_shadow_ = program;
2520 void GLRenderer::DrawQuadGeometryClippedByQuadF(
2521 const DrawingFrame* frame,
2522 const gfx::Transform& draw_transform,
2523 const gfx::RectF& quad_rect,
2524 const gfx::QuadF& clipping_region_quad,
2525 int matrix_location,
2526 const float* uvs) {
2527 PrepareGeometry(CLIPPED_BINDING);
2528 if (uvs) {
2529 clipped_geometry_->InitializeCustomQuadWithUVs(clipping_region_quad, uvs);
2530 } else {
2531 clipped_geometry_->InitializeCustomQuad(clipping_region_quad);
2533 gfx::Transform quad_rect_matrix;
2534 QuadRectTransform(&quad_rect_matrix, draw_transform, quad_rect);
2535 static float gl_matrix[16];
2536 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad_rect_matrix);
2537 gl_->UniformMatrix4fv(matrix_location, 1, false, &gl_matrix[0]);
2539 gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT,
2540 reinterpret_cast<const void*>(0));
2543 void GLRenderer::DrawQuadGeometry(const DrawingFrame* frame,
2544 const gfx::Transform& draw_transform,
2545 const gfx::RectF& quad_rect,
2546 int matrix_location) {
2547 PrepareGeometry(SHARED_BINDING);
2548 gfx::Transform quad_rect_matrix;
2549 QuadRectTransform(&quad_rect_matrix, draw_transform, quad_rect);
2550 static float gl_matrix[16];
2551 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad_rect_matrix);
2552 gl_->UniformMatrix4fv(matrix_location, 1, false, &gl_matrix[0]);
2554 gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);
2557 void GLRenderer::Finish() {
2558 TRACE_EVENT0("cc", "GLRenderer::Finish");
2559 gl_->Finish();
2562 void GLRenderer::SwapBuffers(const CompositorFrameMetadata& metadata) {
2563 DCHECK(!is_backbuffer_discarded_);
2565 TRACE_EVENT0("cc,benchmark", "GLRenderer::SwapBuffers");
2566 // We're done! Time to swapbuffers!
2568 gfx::Size surface_size = output_surface_->SurfaceSize();
2570 CompositorFrame compositor_frame;
2571 compositor_frame.metadata = metadata;
2572 compositor_frame.gl_frame_data = make_scoped_ptr(new GLFrameData);
2573 compositor_frame.gl_frame_data->size = surface_size;
2574 if (capabilities_.using_partial_swap) {
2575 // If supported, we can save significant bandwidth by only swapping the
2576 // damaged/scissored region (clamped to the viewport).
2577 swap_buffer_rect_.Intersect(gfx::Rect(surface_size));
2578 int flipped_y_pos_of_rect_bottom = surface_size.height() -
2579 swap_buffer_rect_.y() -
2580 swap_buffer_rect_.height();
2581 compositor_frame.gl_frame_data->sub_buffer_rect =
2582 gfx::Rect(swap_buffer_rect_.x(),
2583 FlippedRootFramebuffer() ? flipped_y_pos_of_rect_bottom
2584 : swap_buffer_rect_.y(),
2585 swap_buffer_rect_.width(),
2586 swap_buffer_rect_.height());
2587 } else {
2588 compositor_frame.gl_frame_data->sub_buffer_rect =
2589 gfx::Rect(output_surface_->SurfaceSize());
2591 output_surface_->SwapBuffers(&compositor_frame);
2593 // Release previously used overlay resources and hold onto the pending ones
2594 // until the next swap buffers.
2595 in_use_overlay_resources_.clear();
2596 in_use_overlay_resources_.swap(pending_overlay_resources_);
2598 swap_buffer_rect_ = gfx::Rect();
2601 void GLRenderer::EnforceMemoryPolicy() {
2602 if (!visible()) {
2603 TRACE_EVENT0("cc", "GLRenderer::EnforceMemoryPolicy dropping resources");
2604 ReleaseRenderPassTextures();
2605 DiscardBackbuffer();
2606 resource_provider_->ReleaseCachedData();
2607 output_surface_->context_provider()->DeleteCachedResources();
2608 gl_->Flush();
2610 PrepareGeometry(NO_BINDING);
2613 void GLRenderer::DiscardBackbuffer() {
2614 if (is_backbuffer_discarded_)
2615 return;
2617 output_surface_->DiscardBackbuffer();
2619 is_backbuffer_discarded_ = true;
2621 // Damage tracker needs a full reset every time framebuffer is discarded.
2622 client_->SetFullRootLayerDamage();
2625 void GLRenderer::EnsureBackbuffer() {
2626 if (!is_backbuffer_discarded_)
2627 return;
2629 output_surface_->EnsureBackbuffer();
2630 is_backbuffer_discarded_ = false;
2633 void GLRenderer::GetFramebufferPixelsAsync(
2634 const DrawingFrame* frame,
2635 const gfx::Rect& rect,
2636 scoped_ptr<CopyOutputRequest> request) {
2637 DCHECK(!request->IsEmpty());
2638 if (request->IsEmpty())
2639 return;
2640 if (rect.IsEmpty())
2641 return;
2643 gfx::Rect window_rect = MoveFromDrawToWindowSpace(frame, rect);
2644 DCHECK_GE(window_rect.x(), 0);
2645 DCHECK_GE(window_rect.y(), 0);
2646 DCHECK_LE(window_rect.right(), current_surface_size_.width());
2647 DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2649 if (!request->force_bitmap_result()) {
2650 bool own_mailbox = !request->has_texture_mailbox();
2652 GLuint texture_id = 0;
2653 gpu::Mailbox mailbox;
2654 if (own_mailbox) {
2655 gl_->GenMailboxCHROMIUM(mailbox.name);
2656 gl_->GenTextures(1, &texture_id);
2657 gl_->BindTexture(GL_TEXTURE_2D, texture_id);
2659 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2660 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2661 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2662 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2663 gl_->ProduceTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name);
2664 } else {
2665 mailbox = request->texture_mailbox().mailbox();
2666 DCHECK_EQ(static_cast<unsigned>(GL_TEXTURE_2D),
2667 request->texture_mailbox().target());
2668 DCHECK(!mailbox.IsZero());
2669 unsigned incoming_sync_point = request->texture_mailbox().sync_point();
2670 if (incoming_sync_point)
2671 gl_->WaitSyncPointCHROMIUM(incoming_sync_point);
2673 texture_id =
2674 gl_->CreateAndConsumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name);
2676 GetFramebufferTexture(texture_id, RGBA_8888, window_rect);
2678 unsigned sync_point = gl_->InsertSyncPointCHROMIUM();
2679 TextureMailbox texture_mailbox(mailbox, GL_TEXTURE_2D, sync_point);
2681 scoped_ptr<SingleReleaseCallback> release_callback;
2682 if (own_mailbox) {
2683 gl_->BindTexture(GL_TEXTURE_2D, 0);
2684 release_callback = texture_mailbox_deleter_->GetReleaseCallback(
2685 output_surface_->context_provider(), texture_id);
2686 } else {
2687 gl_->DeleteTextures(1, &texture_id);
2690 request->SendTextureResult(
2691 window_rect.size(), texture_mailbox, release_callback.Pass());
2692 return;
2695 DCHECK(request->force_bitmap_result());
2697 scoped_ptr<PendingAsyncReadPixels> pending_read(new PendingAsyncReadPixels);
2698 pending_read->copy_request = request.Pass();
2699 pending_async_read_pixels_.insert(pending_async_read_pixels_.begin(),
2700 pending_read.Pass());
2702 bool do_workaround = NeedsIOSurfaceReadbackWorkaround();
2704 unsigned temporary_texture = 0;
2705 unsigned temporary_fbo = 0;
2707 if (do_workaround) {
2708 // On Mac OS X, calling glReadPixels() against an FBO whose color attachment
2709 // is an IOSurface-backed texture causes corruption of future glReadPixels()
2710 // calls, even those on different OpenGL contexts. It is believed that this
2711 // is the root cause of top crasher
2712 // http://crbug.com/99393. <rdar://problem/10949687>
2714 gl_->GenTextures(1, &temporary_texture);
2715 gl_->BindTexture(GL_TEXTURE_2D, temporary_texture);
2716 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2717 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
2718 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2719 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2720 // Copy the contents of the current (IOSurface-backed) framebuffer into a
2721 // temporary texture.
2722 GetFramebufferTexture(
2723 temporary_texture, RGBA_8888, gfx::Rect(current_surface_size_));
2724 gl_->GenFramebuffers(1, &temporary_fbo);
2725 // Attach this texture to an FBO, and perform the readback from that FBO.
2726 gl_->BindFramebuffer(GL_FRAMEBUFFER, temporary_fbo);
2727 gl_->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
2728 GL_TEXTURE_2D, temporary_texture, 0);
2730 DCHECK_EQ(static_cast<unsigned>(GL_FRAMEBUFFER_COMPLETE),
2731 gl_->CheckFramebufferStatus(GL_FRAMEBUFFER));
2734 GLuint buffer = 0;
2735 gl_->GenBuffers(1, &buffer);
2736 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, buffer);
2737 gl_->BufferData(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM,
2738 4 * window_rect.size().GetArea(), NULL, GL_STREAM_READ);
2740 GLuint query = 0;
2741 gl_->GenQueriesEXT(1, &query);
2742 gl_->BeginQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM, query);
2744 gl_->ReadPixels(window_rect.x(), window_rect.y(), window_rect.width(),
2745 window_rect.height(), GL_RGBA, GL_UNSIGNED_BYTE, NULL);
2747 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0);
2749 if (do_workaround) {
2750 // Clean up.
2751 gl_->BindFramebuffer(GL_FRAMEBUFFER, 0);
2752 gl_->BindTexture(GL_TEXTURE_2D, 0);
2753 gl_->DeleteFramebuffers(1, &temporary_fbo);
2754 gl_->DeleteTextures(1, &temporary_texture);
2757 base::Closure finished_callback = base::Bind(&GLRenderer::FinishedReadback,
2758 base::Unretained(this),
2759 buffer,
2760 query,
2761 window_rect.size());
2762 // Save the finished_callback so it can be cancelled.
2763 pending_async_read_pixels_.front()->finished_read_pixels_callback.Reset(
2764 finished_callback);
2765 base::Closure cancelable_callback =
2766 pending_async_read_pixels_.front()->
2767 finished_read_pixels_callback.callback();
2769 // Save the buffer to verify the callbacks happen in the expected order.
2770 pending_async_read_pixels_.front()->buffer = buffer;
2772 gl_->EndQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM);
2773 context_support_->SignalQuery(query, cancelable_callback);
2775 EnforceMemoryPolicy();
2778 void GLRenderer::FinishedReadback(unsigned source_buffer,
2779 unsigned query,
2780 const gfx::Size& size) {
2781 DCHECK(!pending_async_read_pixels_.empty());
2783 if (query != 0) {
2784 gl_->DeleteQueriesEXT(1, &query);
2787 PendingAsyncReadPixels* current_read = pending_async_read_pixels_.back();
2788 // Make sure we service the readbacks in order.
2789 DCHECK_EQ(source_buffer, current_read->buffer);
2791 uint8* src_pixels = NULL;
2792 scoped_ptr<SkBitmap> bitmap;
2794 if (source_buffer != 0) {
2795 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, source_buffer);
2796 src_pixels = static_cast<uint8*>(gl_->MapBufferCHROMIUM(
2797 GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, GL_READ_ONLY));
2799 if (src_pixels) {
2800 bitmap.reset(new SkBitmap);
2801 bitmap->allocN32Pixels(size.width(), size.height());
2802 scoped_ptr<SkAutoLockPixels> lock(new SkAutoLockPixels(*bitmap));
2803 uint8* dest_pixels = static_cast<uint8*>(bitmap->getPixels());
2805 size_t row_bytes = size.width() * 4;
2806 int num_rows = size.height();
2807 size_t total_bytes = num_rows * row_bytes;
2808 for (size_t dest_y = 0; dest_y < total_bytes; dest_y += row_bytes) {
2809 // Flip Y axis.
2810 size_t src_y = total_bytes - dest_y - row_bytes;
2811 // Swizzle OpenGL -> Skia byte order.
2812 for (size_t x = 0; x < row_bytes; x += 4) {
2813 dest_pixels[dest_y + x + SK_R32_SHIFT / 8] =
2814 src_pixels[src_y + x + 0];
2815 dest_pixels[dest_y + x + SK_G32_SHIFT / 8] =
2816 src_pixels[src_y + x + 1];
2817 dest_pixels[dest_y + x + SK_B32_SHIFT / 8] =
2818 src_pixels[src_y + x + 2];
2819 dest_pixels[dest_y + x + SK_A32_SHIFT / 8] =
2820 src_pixels[src_y + x + 3];
2824 gl_->UnmapBufferCHROMIUM(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM);
2826 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0);
2827 gl_->DeleteBuffers(1, &source_buffer);
2830 if (bitmap)
2831 current_read->copy_request->SendBitmapResult(bitmap.Pass());
2832 pending_async_read_pixels_.pop_back();
2835 void GLRenderer::GetFramebufferTexture(unsigned texture_id,
2836 ResourceFormat texture_format,
2837 const gfx::Rect& window_rect) {
2838 DCHECK(texture_id);
2839 DCHECK_GE(window_rect.x(), 0);
2840 DCHECK_GE(window_rect.y(), 0);
2841 DCHECK_LE(window_rect.right(), current_surface_size_.width());
2842 DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2844 gl_->BindTexture(GL_TEXTURE_2D, texture_id);
2845 gl_->CopyTexImage2D(GL_TEXTURE_2D, 0, GLDataFormat(texture_format),
2846 window_rect.x(), window_rect.y(), window_rect.width(),
2847 window_rect.height(), 0);
2848 gl_->BindTexture(GL_TEXTURE_2D, 0);
2851 bool GLRenderer::UseScopedTexture(DrawingFrame* frame,
2852 const ScopedResource* texture,
2853 const gfx::Rect& viewport_rect) {
2854 DCHECK(texture->id());
2855 frame->current_render_pass = NULL;
2856 frame->current_texture = texture;
2858 return BindFramebufferToTexture(frame, texture, viewport_rect);
2861 void GLRenderer::BindFramebufferToOutputSurface(DrawingFrame* frame) {
2862 current_framebuffer_lock_ = nullptr;
2863 output_surface_->BindFramebuffer();
2865 if (output_surface_->HasExternalStencilTest()) {
2866 SetStencilEnabled(true);
2867 gl_->StencilFunc(GL_EQUAL, 1, 1);
2868 } else {
2869 SetStencilEnabled(false);
2873 bool GLRenderer::BindFramebufferToTexture(DrawingFrame* frame,
2874 const ScopedResource* texture,
2875 const gfx::Rect& target_rect) {
2876 DCHECK(texture->id());
2878 // Explicitly release lock, otherwise we can crash when try to lock
2879 // same texture again.
2880 current_framebuffer_lock_ = nullptr;
2882 SetStencilEnabled(false);
2883 gl_->BindFramebuffer(GL_FRAMEBUFFER, offscreen_framebuffer_id_);
2884 current_framebuffer_lock_ =
2885 make_scoped_ptr(new ResourceProvider::ScopedWriteLockGL(
2886 resource_provider_, texture->id()));
2887 unsigned texture_id = current_framebuffer_lock_->texture_id();
2888 gl_->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
2889 texture_id, 0);
2891 DCHECK(gl_->CheckFramebufferStatus(GL_FRAMEBUFFER) ==
2892 GL_FRAMEBUFFER_COMPLETE ||
2893 IsContextLost());
2894 return true;
2897 void GLRenderer::SetScissorTestRect(const gfx::Rect& scissor_rect) {
2898 EnsureScissorTestEnabled();
2900 // Don't unnecessarily ask the context to change the scissor, because it
2901 // may cause undesired GPU pipeline flushes.
2902 if (scissor_rect == scissor_rect_ && !scissor_rect_needs_reset_)
2903 return;
2905 scissor_rect_ = scissor_rect;
2906 FlushTextureQuadCache(SHARED_BINDING);
2907 gl_->Scissor(scissor_rect.x(), scissor_rect.y(), scissor_rect.width(),
2908 scissor_rect.height());
2910 scissor_rect_needs_reset_ = false;
2913 void GLRenderer::SetViewport() {
2914 gl_->Viewport(current_window_space_viewport_.x(),
2915 current_window_space_viewport_.y(),
2916 current_window_space_viewport_.width(),
2917 current_window_space_viewport_.height());
2920 void GLRenderer::InitializeSharedObjects() {
2921 TRACE_EVENT0("cc", "GLRenderer::InitializeSharedObjects");
2923 // Create an FBO for doing offscreen rendering.
2924 gl_->GenFramebuffers(1, &offscreen_framebuffer_id_);
2926 shared_geometry_ =
2927 make_scoped_ptr(new StaticGeometryBinding(gl_, QuadVertexRect()));
2928 clipped_geometry_ = make_scoped_ptr(new DynamicGeometryBinding(gl_));
2931 void GLRenderer::PrepareGeometry(BoundGeometry binding) {
2932 if (binding == bound_geometry_) {
2933 return;
2936 switch (binding) {
2937 case SHARED_BINDING:
2938 shared_geometry_->PrepareForDraw();
2939 break;
2940 case CLIPPED_BINDING:
2941 clipped_geometry_->PrepareForDraw();
2942 break;
2943 case NO_BINDING:
2944 break;
2946 bound_geometry_ = binding;
2949 const GLRenderer::TileCheckerboardProgram*
2950 GLRenderer::GetTileCheckerboardProgram() {
2951 if (!tile_checkerboard_program_.initialized()) {
2952 TRACE_EVENT0("cc", "GLRenderer::checkerboardProgram::initalize");
2953 tile_checkerboard_program_.Initialize(output_surface_->context_provider(),
2954 TEX_COORD_PRECISION_NA,
2955 SAMPLER_TYPE_NA);
2957 return &tile_checkerboard_program_;
2960 const GLRenderer::DebugBorderProgram* GLRenderer::GetDebugBorderProgram() {
2961 if (!debug_border_program_.initialized()) {
2962 TRACE_EVENT0("cc", "GLRenderer::debugBorderProgram::initialize");
2963 debug_border_program_.Initialize(output_surface_->context_provider(),
2964 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
2966 return &debug_border_program_;
2969 const GLRenderer::SolidColorProgram* GLRenderer::GetSolidColorProgram() {
2970 if (!solid_color_program_.initialized()) {
2971 TRACE_EVENT0("cc", "GLRenderer::solidColorProgram::initialize");
2972 solid_color_program_.Initialize(output_surface_->context_provider(),
2973 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
2975 return &solid_color_program_;
2978 const GLRenderer::SolidColorProgramAA* GLRenderer::GetSolidColorProgramAA() {
2979 if (!solid_color_program_aa_.initialized()) {
2980 TRACE_EVENT0("cc", "GLRenderer::solidColorProgramAA::initialize");
2981 solid_color_program_aa_.Initialize(output_surface_->context_provider(),
2982 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
2984 return &solid_color_program_aa_;
2987 const GLRenderer::RenderPassProgram* GLRenderer::GetRenderPassProgram(
2988 TexCoordPrecision precision,
2989 BlendMode blend_mode) {
2990 DCHECK_GE(precision, 0);
2991 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
2992 DCHECK_GE(blend_mode, 0);
2993 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
2994 RenderPassProgram* program = &render_pass_program_[precision][blend_mode];
2995 if (!program->initialized()) {
2996 TRACE_EVENT0("cc", "GLRenderer::renderPassProgram::initialize");
2997 program->Initialize(output_surface_->context_provider(), precision,
2998 SAMPLER_TYPE_2D, blend_mode);
3000 return program;
3003 const GLRenderer::RenderPassProgramAA* GLRenderer::GetRenderPassProgramAA(
3004 TexCoordPrecision precision,
3005 BlendMode blend_mode) {
3006 DCHECK_GE(precision, 0);
3007 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3008 DCHECK_GE(blend_mode, 0);
3009 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3010 RenderPassProgramAA* program =
3011 &render_pass_program_aa_[precision][blend_mode];
3012 if (!program->initialized()) {
3013 TRACE_EVENT0("cc", "GLRenderer::renderPassProgramAA::initialize");
3014 program->Initialize(output_surface_->context_provider(), precision,
3015 SAMPLER_TYPE_2D, blend_mode);
3017 return program;
3020 const GLRenderer::RenderPassMaskProgram* GLRenderer::GetRenderPassMaskProgram(
3021 TexCoordPrecision precision,
3022 SamplerType sampler,
3023 BlendMode blend_mode,
3024 bool mask_for_background) {
3025 DCHECK_GE(precision, 0);
3026 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3027 DCHECK_GE(sampler, 0);
3028 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3029 DCHECK_GE(blend_mode, 0);
3030 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3031 RenderPassMaskProgram* program =
3032 &render_pass_mask_program_[precision][sampler][blend_mode]
3033 [mask_for_background ? HAS_MASK : NO_MASK];
3034 if (!program->initialized()) {
3035 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgram::initialize");
3036 program->Initialize(
3037 output_surface_->context_provider(), precision,
3038 sampler, blend_mode, mask_for_background);
3040 return program;
3043 const GLRenderer::RenderPassMaskProgramAA*
3044 GLRenderer::GetRenderPassMaskProgramAA(TexCoordPrecision precision,
3045 SamplerType sampler,
3046 BlendMode blend_mode,
3047 bool mask_for_background) {
3048 DCHECK_GE(precision, 0);
3049 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3050 DCHECK_GE(sampler, 0);
3051 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3052 DCHECK_GE(blend_mode, 0);
3053 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3054 RenderPassMaskProgramAA* program =
3055 &render_pass_mask_program_aa_[precision][sampler][blend_mode]
3056 [mask_for_background ? HAS_MASK : NO_MASK];
3057 if (!program->initialized()) {
3058 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgramAA::initialize");
3059 program->Initialize(
3060 output_surface_->context_provider(), precision,
3061 sampler, blend_mode, mask_for_background);
3063 return program;
3066 const GLRenderer::RenderPassColorMatrixProgram*
3067 GLRenderer::GetRenderPassColorMatrixProgram(TexCoordPrecision precision,
3068 BlendMode blend_mode) {
3069 DCHECK_GE(precision, 0);
3070 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3071 DCHECK_GE(blend_mode, 0);
3072 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3073 RenderPassColorMatrixProgram* program =
3074 &render_pass_color_matrix_program_[precision][blend_mode];
3075 if (!program->initialized()) {
3076 TRACE_EVENT0("cc", "GLRenderer::renderPassColorMatrixProgram::initialize");
3077 program->Initialize(output_surface_->context_provider(), precision,
3078 SAMPLER_TYPE_2D, blend_mode);
3080 return program;
3083 const GLRenderer::RenderPassColorMatrixProgramAA*
3084 GLRenderer::GetRenderPassColorMatrixProgramAA(TexCoordPrecision precision,
3085 BlendMode blend_mode) {
3086 DCHECK_GE(precision, 0);
3087 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3088 DCHECK_GE(blend_mode, 0);
3089 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3090 RenderPassColorMatrixProgramAA* program =
3091 &render_pass_color_matrix_program_aa_[precision][blend_mode];
3092 if (!program->initialized()) {
3093 TRACE_EVENT0("cc",
3094 "GLRenderer::renderPassColorMatrixProgramAA::initialize");
3095 program->Initialize(output_surface_->context_provider(), precision,
3096 SAMPLER_TYPE_2D, blend_mode);
3098 return program;
3101 const GLRenderer::RenderPassMaskColorMatrixProgram*
3102 GLRenderer::GetRenderPassMaskColorMatrixProgram(
3103 TexCoordPrecision precision,
3104 SamplerType sampler,
3105 BlendMode blend_mode,
3106 bool mask_for_background) {
3107 DCHECK_GE(precision, 0);
3108 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3109 DCHECK_GE(sampler, 0);
3110 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3111 DCHECK_GE(blend_mode, 0);
3112 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3113 RenderPassMaskColorMatrixProgram* program =
3114 &render_pass_mask_color_matrix_program_[precision][sampler][blend_mode]
3115 [mask_for_background ? HAS_MASK : NO_MASK];
3116 if (!program->initialized()) {
3117 TRACE_EVENT0("cc",
3118 "GLRenderer::renderPassMaskColorMatrixProgram::initialize");
3119 program->Initialize(
3120 output_surface_->context_provider(), precision,
3121 sampler, blend_mode, mask_for_background);
3123 return program;
3126 const GLRenderer::RenderPassMaskColorMatrixProgramAA*
3127 GLRenderer::GetRenderPassMaskColorMatrixProgramAA(
3128 TexCoordPrecision precision,
3129 SamplerType sampler,
3130 BlendMode blend_mode,
3131 bool mask_for_background) {
3132 DCHECK_GE(precision, 0);
3133 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3134 DCHECK_GE(sampler, 0);
3135 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3136 DCHECK_GE(blend_mode, 0);
3137 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3138 RenderPassMaskColorMatrixProgramAA* program =
3139 &render_pass_mask_color_matrix_program_aa_[precision][sampler][blend_mode]
3140 [mask_for_background ? HAS_MASK : NO_MASK];
3141 if (!program->initialized()) {
3142 TRACE_EVENT0("cc",
3143 "GLRenderer::renderPassMaskColorMatrixProgramAA::initialize");
3144 program->Initialize(
3145 output_surface_->context_provider(), precision,
3146 sampler, blend_mode, mask_for_background);
3148 return program;
3151 const GLRenderer::TileProgram* GLRenderer::GetTileProgram(
3152 TexCoordPrecision precision,
3153 SamplerType sampler) {
3154 DCHECK_GE(precision, 0);
3155 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3156 DCHECK_GE(sampler, 0);
3157 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3158 TileProgram* program = &tile_program_[precision][sampler];
3159 if (!program->initialized()) {
3160 TRACE_EVENT0("cc", "GLRenderer::tileProgram::initialize");
3161 program->Initialize(
3162 output_surface_->context_provider(), precision, sampler);
3164 return program;
3167 const GLRenderer::TileProgramOpaque* GLRenderer::GetTileProgramOpaque(
3168 TexCoordPrecision precision,
3169 SamplerType sampler) {
3170 DCHECK_GE(precision, 0);
3171 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3172 DCHECK_GE(sampler, 0);
3173 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3174 TileProgramOpaque* program = &tile_program_opaque_[precision][sampler];
3175 if (!program->initialized()) {
3176 TRACE_EVENT0("cc", "GLRenderer::tileProgramOpaque::initialize");
3177 program->Initialize(
3178 output_surface_->context_provider(), precision, sampler);
3180 return program;
3183 const GLRenderer::TileProgramAA* GLRenderer::GetTileProgramAA(
3184 TexCoordPrecision precision,
3185 SamplerType sampler) {
3186 DCHECK_GE(precision, 0);
3187 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3188 DCHECK_GE(sampler, 0);
3189 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3190 TileProgramAA* program = &tile_program_aa_[precision][sampler];
3191 if (!program->initialized()) {
3192 TRACE_EVENT0("cc", "GLRenderer::tileProgramAA::initialize");
3193 program->Initialize(
3194 output_surface_->context_provider(), precision, sampler);
3196 return program;
3199 const GLRenderer::TileProgramSwizzle* GLRenderer::GetTileProgramSwizzle(
3200 TexCoordPrecision precision,
3201 SamplerType sampler) {
3202 DCHECK_GE(precision, 0);
3203 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3204 DCHECK_GE(sampler, 0);
3205 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3206 TileProgramSwizzle* program = &tile_program_swizzle_[precision][sampler];
3207 if (!program->initialized()) {
3208 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzle::initialize");
3209 program->Initialize(
3210 output_surface_->context_provider(), precision, sampler);
3212 return program;
3215 const GLRenderer::TileProgramSwizzleOpaque*
3216 GLRenderer::GetTileProgramSwizzleOpaque(TexCoordPrecision precision,
3217 SamplerType sampler) {
3218 DCHECK_GE(precision, 0);
3219 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3220 DCHECK_GE(sampler, 0);
3221 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3222 TileProgramSwizzleOpaque* program =
3223 &tile_program_swizzle_opaque_[precision][sampler];
3224 if (!program->initialized()) {
3225 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleOpaque::initialize");
3226 program->Initialize(
3227 output_surface_->context_provider(), precision, sampler);
3229 return program;
3232 const GLRenderer::TileProgramSwizzleAA* GLRenderer::GetTileProgramSwizzleAA(
3233 TexCoordPrecision precision,
3234 SamplerType sampler) {
3235 DCHECK_GE(precision, 0);
3236 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3237 DCHECK_GE(sampler, 0);
3238 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3239 TileProgramSwizzleAA* program = &tile_program_swizzle_aa_[precision][sampler];
3240 if (!program->initialized()) {
3241 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleAA::initialize");
3242 program->Initialize(
3243 output_surface_->context_provider(), precision, sampler);
3245 return program;
3248 const GLRenderer::TextureProgram* GLRenderer::GetTextureProgram(
3249 TexCoordPrecision precision,
3250 SamplerType sampler) {
3251 DCHECK_GE(precision, 0);
3252 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3253 DCHECK_GE(sampler, 0);
3254 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3255 TextureProgram* program = &texture_program_[precision][sampler];
3256 if (!program->initialized()) {
3257 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3258 program->Initialize(output_surface_->context_provider(), precision,
3259 sampler);
3261 return program;
3264 const GLRenderer::NonPremultipliedTextureProgram*
3265 GLRenderer::GetNonPremultipliedTextureProgram(TexCoordPrecision precision,
3266 SamplerType sampler) {
3267 DCHECK_GE(precision, 0);
3268 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3269 DCHECK_GE(sampler, 0);
3270 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3271 NonPremultipliedTextureProgram* program =
3272 &nonpremultiplied_texture_program_[precision][sampler];
3273 if (!program->initialized()) {
3274 TRACE_EVENT0("cc",
3275 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3276 program->Initialize(output_surface_->context_provider(), precision,
3277 sampler);
3279 return program;
3282 const GLRenderer::TextureBackgroundProgram*
3283 GLRenderer::GetTextureBackgroundProgram(TexCoordPrecision precision,
3284 SamplerType sampler) {
3285 DCHECK_GE(precision, 0);
3286 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3287 DCHECK_GE(sampler, 0);
3288 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3289 TextureBackgroundProgram* program =
3290 &texture_background_program_[precision][sampler];
3291 if (!program->initialized()) {
3292 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3293 program->Initialize(output_surface_->context_provider(), precision,
3294 sampler);
3296 return program;
3299 const GLRenderer::NonPremultipliedTextureBackgroundProgram*
3300 GLRenderer::GetNonPremultipliedTextureBackgroundProgram(
3301 TexCoordPrecision precision,
3302 SamplerType sampler) {
3303 DCHECK_GE(precision, 0);
3304 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3305 DCHECK_GE(sampler, 0);
3306 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3307 NonPremultipliedTextureBackgroundProgram* program =
3308 &nonpremultiplied_texture_background_program_[precision][sampler];
3309 if (!program->initialized()) {
3310 TRACE_EVENT0("cc",
3311 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3312 program->Initialize(output_surface_->context_provider(), precision,
3313 sampler);
3315 return program;
3318 const GLRenderer::TextureProgram* GLRenderer::GetTextureIOSurfaceProgram(
3319 TexCoordPrecision precision) {
3320 DCHECK_GE(precision, 0);
3321 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3322 TextureProgram* program = &texture_io_surface_program_[precision];
3323 if (!program->initialized()) {
3324 TRACE_EVENT0("cc", "GLRenderer::textureIOSurfaceProgram::initialize");
3325 program->Initialize(output_surface_->context_provider(), precision,
3326 SAMPLER_TYPE_2D_RECT);
3328 return program;
3331 const GLRenderer::VideoYUVProgram* GLRenderer::GetVideoYUVProgram(
3332 TexCoordPrecision precision,
3333 SamplerType sampler) {
3334 DCHECK_GE(precision, 0);
3335 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3336 DCHECK_GE(sampler, 0);
3337 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3338 VideoYUVProgram* program = &video_yuv_program_[precision][sampler];
3339 if (!program->initialized()) {
3340 TRACE_EVENT0("cc", "GLRenderer::videoYUVProgram::initialize");
3341 program->Initialize(output_surface_->context_provider(), precision,
3342 sampler);
3344 return program;
3347 const GLRenderer::VideoYUVAProgram* GLRenderer::GetVideoYUVAProgram(
3348 TexCoordPrecision precision,
3349 SamplerType sampler) {
3350 DCHECK_GE(precision, 0);
3351 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3352 DCHECK_GE(sampler, 0);
3353 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3354 VideoYUVAProgram* program = &video_yuva_program_[precision][sampler];
3355 if (!program->initialized()) {
3356 TRACE_EVENT0("cc", "GLRenderer::videoYUVAProgram::initialize");
3357 program->Initialize(output_surface_->context_provider(), precision,
3358 sampler);
3360 return program;
3363 const GLRenderer::VideoStreamTextureProgram*
3364 GLRenderer::GetVideoStreamTextureProgram(TexCoordPrecision precision) {
3365 if (!Capabilities().using_egl_image)
3366 return NULL;
3367 DCHECK_GE(precision, 0);
3368 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3369 VideoStreamTextureProgram* program =
3370 &video_stream_texture_program_[precision];
3371 if (!program->initialized()) {
3372 TRACE_EVENT0("cc", "GLRenderer::streamTextureProgram::initialize");
3373 program->Initialize(output_surface_->context_provider(), precision,
3374 SAMPLER_TYPE_EXTERNAL_OES);
3376 return program;
3379 void GLRenderer::CleanupSharedObjects() {
3380 shared_geometry_ = nullptr;
3382 for (int i = 0; i <= LAST_TEX_COORD_PRECISION; ++i) {
3383 for (int j = 0; j <= LAST_SAMPLER_TYPE; ++j) {
3384 tile_program_[i][j].Cleanup(gl_);
3385 tile_program_opaque_[i][j].Cleanup(gl_);
3386 tile_program_swizzle_[i][j].Cleanup(gl_);
3387 tile_program_swizzle_opaque_[i][j].Cleanup(gl_);
3388 tile_program_aa_[i][j].Cleanup(gl_);
3389 tile_program_swizzle_aa_[i][j].Cleanup(gl_);
3391 for (int k = 0; k <= LAST_BLEND_MODE; k++) {
3392 for (int l = 0; l <= LAST_MASK_VALUE; ++l) {
3393 render_pass_mask_program_[i][j][k][l].Cleanup(gl_);
3394 render_pass_mask_program_aa_[i][j][k][l].Cleanup(gl_);
3395 render_pass_mask_color_matrix_program_aa_[i][j][k][l].Cleanup(gl_);
3396 render_pass_mask_color_matrix_program_[i][j][k][l].Cleanup(gl_);
3400 video_yuv_program_[i][j].Cleanup(gl_);
3401 video_yuva_program_[i][j].Cleanup(gl_);
3403 for (int j = 0; j <= LAST_BLEND_MODE; j++) {
3404 render_pass_program_[i][j].Cleanup(gl_);
3405 render_pass_program_aa_[i][j].Cleanup(gl_);
3406 render_pass_color_matrix_program_[i][j].Cleanup(gl_);
3407 render_pass_color_matrix_program_aa_[i][j].Cleanup(gl_);
3410 for (int j = 0; j <= LAST_SAMPLER_TYPE; ++j) {
3411 texture_program_[i][j].Cleanup(gl_);
3412 nonpremultiplied_texture_program_[i][j].Cleanup(gl_);
3413 texture_background_program_[i][j].Cleanup(gl_);
3414 nonpremultiplied_texture_background_program_[i][j].Cleanup(gl_);
3416 texture_io_surface_program_[i].Cleanup(gl_);
3418 video_stream_texture_program_[i].Cleanup(gl_);
3421 tile_checkerboard_program_.Cleanup(gl_);
3423 debug_border_program_.Cleanup(gl_);
3424 solid_color_program_.Cleanup(gl_);
3425 solid_color_program_aa_.Cleanup(gl_);
3427 if (offscreen_framebuffer_id_)
3428 gl_->DeleteFramebuffers(1, &offscreen_framebuffer_id_);
3430 if (on_demand_tile_raster_resource_id_)
3431 resource_provider_->DeleteResource(on_demand_tile_raster_resource_id_);
3433 ReleaseRenderPassTextures();
3436 void GLRenderer::ReinitializeGLState() {
3437 is_scissor_enabled_ = false;
3438 scissor_rect_needs_reset_ = true;
3439 stencil_shadow_ = false;
3440 blend_shadow_ = true;
3441 program_shadow_ = 0;
3443 RestoreGLState();
3446 void GLRenderer::RestoreGLState() {
3447 // This restores the current GLRenderer state to the GL context.
3448 bound_geometry_ = NO_BINDING;
3449 PrepareGeometry(SHARED_BINDING);
3451 gl_->Disable(GL_DEPTH_TEST);
3452 gl_->Disable(GL_CULL_FACE);
3453 gl_->ColorMask(true, true, true, true);
3454 gl_->BlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
3455 gl_->ActiveTexture(GL_TEXTURE0);
3457 if (program_shadow_)
3458 gl_->UseProgram(program_shadow_);
3460 if (stencil_shadow_)
3461 gl_->Enable(GL_STENCIL_TEST);
3462 else
3463 gl_->Disable(GL_STENCIL_TEST);
3465 if (blend_shadow_)
3466 gl_->Enable(GL_BLEND);
3467 else
3468 gl_->Disable(GL_BLEND);
3470 if (is_scissor_enabled_) {
3471 gl_->Enable(GL_SCISSOR_TEST);
3472 gl_->Scissor(scissor_rect_.x(), scissor_rect_.y(), scissor_rect_.width(),
3473 scissor_rect_.height());
3474 } else {
3475 gl_->Disable(GL_SCISSOR_TEST);
3479 void GLRenderer::RestoreFramebuffer(DrawingFrame* frame) {
3480 UseRenderPass(frame, frame->current_render_pass);
3482 // Call SetViewport directly, rather than through PrepareSurfaceForPass.
3483 // PrepareSurfaceForPass also clears the surface, which is not desired when
3484 // restoring.
3485 SetViewport();
3488 bool GLRenderer::IsContextLost() {
3489 return output_surface_->context_provider()->IsContextLost();
3492 void GLRenderer::ScheduleOverlays(DrawingFrame* frame) {
3493 if (!frame->overlay_list.size())
3494 return;
3496 ResourceProvider::ResourceIdArray resources;
3497 OverlayCandidateList& overlays = frame->overlay_list;
3498 for (const OverlayCandidate& overlay : overlays) {
3499 // Skip primary plane.
3500 if (overlay.plane_z_order == 0)
3501 continue;
3503 pending_overlay_resources_.push_back(
3504 make_scoped_ptr(new ResourceProvider::ScopedReadLockGL(
3505 resource_provider_, overlay.resource_id)));
3507 context_support_->ScheduleOverlayPlane(
3508 overlay.plane_z_order,
3509 overlay.transform,
3510 pending_overlay_resources_.back()->texture_id(),
3511 ToNearestRect(overlay.display_rect),
3512 overlay.uv_rect);
3516 } // namespace cc