[MacViews] Frameless app windows: make content view cover title bar.
[chromium-blink-merge.git] / cc / output / gl_renderer.cc
blobb49ac8eefec9d79361aab1583bbc9e807bc61d0a
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/SkGrTexturePixelRef.h"
51 #include "third_party/skia/include/gpu/gl/GrGLInterface.h"
52 #include "ui/gfx/geometry/quad_f.h"
53 #include "ui/gfx/geometry/rect_conversions.h"
55 using gpu::gles2::GLES2Interface;
57 namespace cc {
58 namespace {
60 bool NeedsIOSurfaceReadbackWorkaround() {
61 #if defined(OS_MACOSX)
62 // This isn't strictly required in DumpRenderTree-mode when Mesa is used,
63 // but it doesn't seem to hurt.
64 return true;
65 #else
66 return false;
67 #endif
70 Float4 UVTransform(const TextureDrawQuad* quad) {
71 gfx::PointF uv0 = quad->uv_top_left;
72 gfx::PointF uv1 = quad->uv_bottom_right;
73 Float4 xform = {{uv0.x(), uv0.y(), uv1.x() - uv0.x(), uv1.y() - uv0.y()}};
74 if (quad->flipped) {
75 xform.data[1] = 1.0f - xform.data[1];
76 xform.data[3] = -xform.data[3];
78 return xform;
81 Float4 PremultipliedColor(SkColor color) {
82 const float factor = 1.0f / 255.0f;
83 const float alpha = SkColorGetA(color) * factor;
85 Float4 result = {
86 {SkColorGetR(color) * factor * alpha, SkColorGetG(color) * factor * alpha,
87 SkColorGetB(color) * factor * alpha, alpha}};
88 return result;
91 SamplerType SamplerTypeFromTextureTarget(GLenum target) {
92 switch (target) {
93 case GL_TEXTURE_2D:
94 return SAMPLER_TYPE_2D;
95 case GL_TEXTURE_RECTANGLE_ARB:
96 return SAMPLER_TYPE_2D_RECT;
97 case GL_TEXTURE_EXTERNAL_OES:
98 return SAMPLER_TYPE_EXTERNAL_OES;
99 default:
100 NOTREACHED();
101 return SAMPLER_TYPE_2D;
105 BlendMode BlendModeFromSkXfermode(SkXfermode::Mode mode) {
106 switch (mode) {
107 case SkXfermode::kSrcOver_Mode:
108 return BLEND_MODE_NORMAL;
109 case SkXfermode::kScreen_Mode:
110 return BLEND_MODE_SCREEN;
111 case SkXfermode::kOverlay_Mode:
112 return BLEND_MODE_OVERLAY;
113 case SkXfermode::kDarken_Mode:
114 return BLEND_MODE_DARKEN;
115 case SkXfermode::kLighten_Mode:
116 return BLEND_MODE_LIGHTEN;
117 case SkXfermode::kColorDodge_Mode:
118 return BLEND_MODE_COLOR_DODGE;
119 case SkXfermode::kColorBurn_Mode:
120 return BLEND_MODE_COLOR_BURN;
121 case SkXfermode::kHardLight_Mode:
122 return BLEND_MODE_HARD_LIGHT;
123 case SkXfermode::kSoftLight_Mode:
124 return BLEND_MODE_SOFT_LIGHT;
125 case SkXfermode::kDifference_Mode:
126 return BLEND_MODE_DIFFERENCE;
127 case SkXfermode::kExclusion_Mode:
128 return BLEND_MODE_EXCLUSION;
129 case SkXfermode::kMultiply_Mode:
130 return BLEND_MODE_MULTIPLY;
131 case SkXfermode::kHue_Mode:
132 return BLEND_MODE_HUE;
133 case SkXfermode::kSaturation_Mode:
134 return BLEND_MODE_SATURATION;
135 case SkXfermode::kColor_Mode:
136 return BLEND_MODE_COLOR;
137 case SkXfermode::kLuminosity_Mode:
138 return BLEND_MODE_LUMINOSITY;
139 default:
140 NOTREACHED();
141 return BLEND_MODE_NONE;
145 // Smallest unit that impact anti-aliasing output. We use this to
146 // determine when anti-aliasing is unnecessary.
147 const float kAntiAliasingEpsilon = 1.0f / 1024.0f;
149 // Block or crash if the number of pending sync queries reach this high as
150 // something is seriously wrong on the service side if this happens.
151 const size_t kMaxPendingSyncQueries = 16;
153 } // anonymous namespace
155 static GLint GetActiveTextureUnit(GLES2Interface* gl) {
156 GLint active_unit = 0;
157 gl->GetIntegerv(GL_ACTIVE_TEXTURE, &active_unit);
158 return active_unit;
161 class GLRenderer::ScopedUseGrContext {
162 public:
163 static scoped_ptr<ScopedUseGrContext> Create(GLRenderer* renderer,
164 DrawingFrame* frame) {
165 return make_scoped_ptr(new ScopedUseGrContext(renderer, frame));
168 ~ScopedUseGrContext() {
169 // Pass context control back to GLrenderer.
170 scoped_gpu_raster_ = nullptr;
171 renderer_->RestoreGLState();
172 renderer_->RestoreFramebuffer(frame_);
175 GrContext* context() const {
176 return renderer_->output_surface_->context_provider()->GrContext();
179 private:
180 ScopedUseGrContext(GLRenderer* renderer, DrawingFrame* frame)
181 : scoped_gpu_raster_(
182 new ScopedGpuRaster(renderer->output_surface_->context_provider())),
183 renderer_(renderer),
184 frame_(frame) {
185 // scoped_gpu_raster_ passes context control to Skia.
188 scoped_ptr<ScopedGpuRaster> scoped_gpu_raster_;
189 GLRenderer* renderer_;
190 DrawingFrame* frame_;
192 DISALLOW_COPY_AND_ASSIGN(ScopedUseGrContext);
195 struct GLRenderer::PendingAsyncReadPixels {
196 PendingAsyncReadPixels() : buffer(0) {}
198 scoped_ptr<CopyOutputRequest> copy_request;
199 base::CancelableClosure finished_read_pixels_callback;
200 unsigned buffer;
202 private:
203 DISALLOW_COPY_AND_ASSIGN(PendingAsyncReadPixels);
206 class GLRenderer::SyncQuery {
207 public:
208 explicit SyncQuery(gpu::gles2::GLES2Interface* gl)
209 : gl_(gl), query_id_(0u), is_pending_(false), weak_ptr_factory_(this) {
210 gl_->GenQueriesEXT(1, &query_id_);
212 virtual ~SyncQuery() { gl_->DeleteQueriesEXT(1, &query_id_); }
214 scoped_refptr<ResourceProvider::Fence> Begin() {
215 DCHECK(!IsPending());
216 // Invalidate weak pointer held by old fence.
217 weak_ptr_factory_.InvalidateWeakPtrs();
218 // Note: In case the set of drawing commands issued before End() do not
219 // depend on the query, defer BeginQueryEXT call until Set() is called and
220 // query is required.
221 return make_scoped_refptr<ResourceProvider::Fence>(
222 new Fence(weak_ptr_factory_.GetWeakPtr()));
225 void Set() {
226 if (is_pending_)
227 return;
229 // Note: BeginQueryEXT on GL_COMMANDS_COMPLETED_CHROMIUM is effectively a
230 // noop relative to GL, so it doesn't matter where it happens but we still
231 // make sure to issue this command when Set() is called (prior to issuing
232 // any drawing commands that depend on query), in case some future extension
233 // can take advantage of this.
234 gl_->BeginQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM, query_id_);
235 is_pending_ = true;
238 void End() {
239 if (!is_pending_)
240 return;
242 gl_->EndQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM);
245 bool IsPending() {
246 if (!is_pending_)
247 return false;
249 unsigned result_available = 1;
250 gl_->GetQueryObjectuivEXT(
251 query_id_, GL_QUERY_RESULT_AVAILABLE_EXT, &result_available);
252 is_pending_ = !result_available;
253 return is_pending_;
256 void Wait() {
257 if (!is_pending_)
258 return;
260 unsigned result = 0;
261 gl_->GetQueryObjectuivEXT(query_id_, GL_QUERY_RESULT_EXT, &result);
262 is_pending_ = false;
265 private:
266 class Fence : public ResourceProvider::Fence {
267 public:
268 explicit Fence(base::WeakPtr<GLRenderer::SyncQuery> query)
269 : query_(query) {}
271 // Overridden from ResourceProvider::Fence:
272 void Set() override {
273 DCHECK(query_);
274 query_->Set();
276 bool HasPassed() override { return !query_ || !query_->IsPending(); }
277 void Wait() override {
278 if (query_)
279 query_->Wait();
282 private:
283 ~Fence() override {}
285 base::WeakPtr<SyncQuery> query_;
287 DISALLOW_COPY_AND_ASSIGN(Fence);
290 gpu::gles2::GLES2Interface* gl_;
291 unsigned query_id_;
292 bool is_pending_;
293 base::WeakPtrFactory<SyncQuery> weak_ptr_factory_;
295 DISALLOW_COPY_AND_ASSIGN(SyncQuery);
298 scoped_ptr<GLRenderer> GLRenderer::Create(
299 RendererClient* client,
300 const RendererSettings* settings,
301 OutputSurface* output_surface,
302 ResourceProvider* resource_provider,
303 TextureMailboxDeleter* texture_mailbox_deleter,
304 int highp_threshold_min) {
305 return make_scoped_ptr(new GLRenderer(client,
306 settings,
307 output_surface,
308 resource_provider,
309 texture_mailbox_deleter,
310 highp_threshold_min));
313 GLRenderer::GLRenderer(RendererClient* client,
314 const RendererSettings* settings,
315 OutputSurface* output_surface,
316 ResourceProvider* resource_provider,
317 TextureMailboxDeleter* texture_mailbox_deleter,
318 int highp_threshold_min)
319 : DirectRenderer(client, settings, output_surface, resource_provider),
320 offscreen_framebuffer_id_(0),
321 shared_geometry_quad_(QuadVertexRect()),
322 gl_(output_surface->context_provider()->ContextGL()),
323 context_support_(output_surface->context_provider()->ContextSupport()),
324 texture_mailbox_deleter_(texture_mailbox_deleter),
325 is_backbuffer_discarded_(false),
326 is_scissor_enabled_(false),
327 scissor_rect_needs_reset_(true),
328 stencil_shadow_(false),
329 blend_shadow_(false),
330 highp_threshold_min_(highp_threshold_min),
331 highp_threshold_cache_(0),
332 use_sync_query_(false),
333 on_demand_tile_raster_resource_id_(0),
334 bound_geometry_(NO_BINDING) {
335 DCHECK(gl_);
336 DCHECK(context_support_);
338 ContextProvider::Capabilities context_caps =
339 output_surface_->context_provider()->ContextCapabilities();
341 capabilities_.using_partial_swap =
342 settings_->partial_swap_enabled && context_caps.gpu.post_sub_buffer;
344 DCHECK(!context_caps.gpu.iosurface || context_caps.gpu.texture_rectangle);
346 capabilities_.using_egl_image = context_caps.gpu.egl_image_external;
348 capabilities_.max_texture_size = resource_provider_->max_texture_size();
349 capabilities_.best_texture_format = resource_provider_->best_texture_format();
351 // The updater can access textures while the GLRenderer is using them.
352 capabilities_.allow_partial_texture_updates = true;
354 capabilities_.using_image = context_caps.gpu.image;
356 capabilities_.using_discard_framebuffer =
357 context_caps.gpu.discard_framebuffer;
359 capabilities_.allow_rasterize_on_demand = true;
361 use_sync_query_ = context_caps.gpu.sync_query;
362 use_blend_equation_advanced_ = context_caps.gpu.blend_equation_advanced;
363 use_blend_equation_advanced_coherent_ =
364 context_caps.gpu.blend_equation_advanced_coherent;
366 InitializeSharedObjects();
369 GLRenderer::~GLRenderer() {
370 while (!pending_async_read_pixels_.empty()) {
371 PendingAsyncReadPixels* pending_read = pending_async_read_pixels_.back();
372 pending_read->finished_read_pixels_callback.Cancel();
373 pending_async_read_pixels_.pop_back();
376 in_use_overlay_resources_.clear();
378 CleanupSharedObjects();
381 const RendererCapabilitiesImpl& GLRenderer::Capabilities() const {
382 return capabilities_;
385 void GLRenderer::DebugGLCall(GLES2Interface* gl,
386 const char* command,
387 const char* file,
388 int line) {
389 GLuint error = gl->GetError();
390 if (error != GL_NO_ERROR)
391 LOG(ERROR) << "GL command failed: File: " << file << "\n\tLine " << line
392 << "\n\tcommand: " << command << ", error "
393 << static_cast<int>(error) << "\n";
396 void GLRenderer::DidChangeVisibility() {
397 EnforceMemoryPolicy();
399 context_support_->SetSurfaceVisible(visible());
402 void GLRenderer::ReleaseRenderPassTextures() { render_pass_textures_.clear(); }
404 void GLRenderer::DiscardPixels(bool has_external_stencil_test,
405 bool draw_rect_covers_full_surface) {
406 if (has_external_stencil_test || !draw_rect_covers_full_surface ||
407 !capabilities_.using_discard_framebuffer)
408 return;
409 bool using_default_framebuffer =
410 !current_framebuffer_lock_ &&
411 output_surface_->capabilities().uses_default_gl_framebuffer;
412 GLenum attachments[] = {static_cast<GLenum>(
413 using_default_framebuffer ? GL_COLOR_EXT : GL_COLOR_ATTACHMENT0_EXT)};
414 gl_->DiscardFramebufferEXT(
415 GL_FRAMEBUFFER, arraysize(attachments), attachments);
418 void GLRenderer::ClearFramebuffer(DrawingFrame* frame,
419 bool has_external_stencil_test) {
420 // It's unsafe to clear when we have a stencil test because glClear ignores
421 // stencil.
422 if (has_external_stencil_test) {
423 DCHECK(!frame->current_render_pass->has_transparent_background);
424 return;
427 // On DEBUG builds, opaque render passes are cleared to blue to easily see
428 // regions that were not drawn on the screen.
429 if (frame->current_render_pass->has_transparent_background)
430 GLC(gl_, gl_->ClearColor(0, 0, 0, 0));
431 else
432 GLC(gl_, gl_->ClearColor(0, 0, 1, 1));
434 bool always_clear = false;
435 #ifndef NDEBUG
436 always_clear = true;
437 #endif
438 if (always_clear || frame->current_render_pass->has_transparent_background) {
439 GLbitfield clear_bits = GL_COLOR_BUFFER_BIT;
440 if (always_clear)
441 clear_bits |= GL_STENCIL_BUFFER_BIT;
442 gl_->Clear(clear_bits);
446 static ResourceProvider::ResourceId WaitOnResourceSyncPoints(
447 ResourceProvider* resource_provider,
448 ResourceProvider::ResourceId resource_id) {
449 resource_provider->WaitSyncPointIfNeeded(resource_id);
450 return resource_id;
453 void GLRenderer::BeginDrawingFrame(DrawingFrame* frame) {
454 TRACE_EVENT0("cc", "GLRenderer::BeginDrawingFrame");
456 scoped_refptr<ResourceProvider::Fence> read_lock_fence;
457 if (use_sync_query_) {
458 // Block until oldest sync query has passed if the number of pending queries
459 // ever reach kMaxPendingSyncQueries.
460 if (pending_sync_queries_.size() >= kMaxPendingSyncQueries) {
461 LOG(ERROR) << "Reached limit of pending sync queries.";
463 pending_sync_queries_.front()->Wait();
464 DCHECK(!pending_sync_queries_.front()->IsPending());
467 while (!pending_sync_queries_.empty()) {
468 if (pending_sync_queries_.front()->IsPending())
469 break;
471 available_sync_queries_.push_back(pending_sync_queries_.take_front());
474 current_sync_query_ = available_sync_queries_.empty()
475 ? make_scoped_ptr(new SyncQuery(gl_))
476 : available_sync_queries_.take_front();
478 read_lock_fence = current_sync_query_->Begin();
479 } else {
480 read_lock_fence =
481 make_scoped_refptr(new ResourceProvider::SynchronousFence(gl_));
483 resource_provider_->SetReadLockFence(read_lock_fence.get());
485 // Insert WaitSyncPointCHROMIUM on quad resources prior to drawing the frame,
486 // so that drawing can proceed without GL context switching interruptions.
487 DrawQuad::ResourceIteratorCallback wait_on_resource_syncpoints_callback =
488 base::Bind(&WaitOnResourceSyncPoints, resource_provider_);
490 for (const auto& pass : *frame->render_passes_in_draw_order) {
491 for (const auto& quad : pass->quad_list)
492 quad->IterateResources(wait_on_resource_syncpoints_callback);
495 // TODO(enne): Do we need to reinitialize all of this state per frame?
496 ReinitializeGLState();
499 void GLRenderer::DoNoOp() {
500 GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, 0));
501 GLC(gl_, gl_->Flush());
504 void GLRenderer::DoDrawQuad(DrawingFrame* frame,
505 const DrawQuad* quad,
506 const gfx::QuadF* clip_region) {
507 DCHECK(quad->rect.Contains(quad->visible_rect));
508 if (quad->material != DrawQuad::TEXTURE_CONTENT) {
509 FlushTextureQuadCache(SHARED_BINDING);
512 switch (quad->material) {
513 case DrawQuad::INVALID:
514 NOTREACHED();
515 break;
516 case DrawQuad::CHECKERBOARD:
517 DrawCheckerboardQuad(frame, CheckerboardDrawQuad::MaterialCast(quad),
518 clip_region);
519 break;
520 case DrawQuad::DEBUG_BORDER:
521 DrawDebugBorderQuad(frame, DebugBorderDrawQuad::MaterialCast(quad));
522 break;
523 case DrawQuad::IO_SURFACE_CONTENT:
524 DrawIOSurfaceQuad(frame, IOSurfaceDrawQuad::MaterialCast(quad),
525 clip_region);
526 break;
527 case DrawQuad::PICTURE_CONTENT:
528 // PictureDrawQuad should only be used for resourceless software draws.
529 NOTREACHED();
530 break;
531 case DrawQuad::RENDER_PASS:
532 DrawRenderPassQuad(frame, RenderPassDrawQuad::MaterialCast(quad),
533 clip_region);
534 break;
535 case DrawQuad::SOLID_COLOR:
536 DrawSolidColorQuad(frame, SolidColorDrawQuad::MaterialCast(quad),
537 clip_region);
538 break;
539 case DrawQuad::STREAM_VIDEO_CONTENT:
540 DrawStreamVideoQuad(frame, StreamVideoDrawQuad::MaterialCast(quad),
541 clip_region);
542 break;
543 case DrawQuad::SURFACE_CONTENT:
544 // Surface content should be fully resolved to other quad types before
545 // reaching a direct renderer.
546 NOTREACHED();
547 break;
548 case DrawQuad::TEXTURE_CONTENT:
549 EnqueueTextureQuad(frame, TextureDrawQuad::MaterialCast(quad),
550 clip_region);
551 break;
552 case DrawQuad::TILED_CONTENT:
553 DrawTileQuad(frame, TileDrawQuad::MaterialCast(quad), clip_region);
554 break;
555 case DrawQuad::YUV_VIDEO_CONTENT:
556 DrawYUVVideoQuad(frame, YUVVideoDrawQuad::MaterialCast(quad),
557 clip_region);
558 break;
562 void GLRenderer::DrawCheckerboardQuad(const DrawingFrame* frame,
563 const CheckerboardDrawQuad* quad,
564 const gfx::QuadF* clip_region) {
565 // TODO(enne) For now since checkerboards shouldn't be part of a 3D
566 // context, clipping regions aren't supported so we skip drawing them
567 // if this becomes the case.
568 if (clip_region) {
569 return;
571 SetBlendEnabled(quad->ShouldDrawWithBlending());
573 const TileCheckerboardProgram* program = GetTileCheckerboardProgram();
574 DCHECK(program && (program->initialized() || IsContextLost()));
575 SetUseProgram(program->program());
577 SkColor color = quad->color;
578 GLC(gl_,
579 gl_->Uniform4f(program->fragment_shader().color_location(),
580 SkColorGetR(color) * (1.0f / 255.0f),
581 SkColorGetG(color) * (1.0f / 255.0f),
582 SkColorGetB(color) * (1.0f / 255.0f),
583 1));
585 const int kCheckerboardWidth = 16;
586 float frequency = 1.0f / kCheckerboardWidth;
588 gfx::Rect tile_rect = quad->rect;
589 float tex_offset_x =
590 static_cast<int>(tile_rect.x() / quad->scale) % kCheckerboardWidth;
591 float tex_offset_y =
592 static_cast<int>(tile_rect.y() / quad->scale) % kCheckerboardWidth;
593 float tex_scale_x = tile_rect.width() / quad->scale;
594 float tex_scale_y = tile_rect.height() / quad->scale;
595 GLC(gl_,
596 gl_->Uniform4f(program->fragment_shader().tex_transform_location(),
597 tex_offset_x,
598 tex_offset_y,
599 tex_scale_x,
600 tex_scale_y));
602 GLC(gl_,
603 gl_->Uniform1f(program->fragment_shader().frequency_location(),
604 frequency));
606 SetShaderOpacity(quad->opacity(),
607 program->fragment_shader().alpha_location());
608 DrawQuadGeometry(frame,
609 quad->quadTransform(),
610 quad->rect,
611 program->vertex_shader().matrix_location());
614 // This function does not handle 3D sorting right now, since the debug border
615 // quads are just drawn as their original quads and not in split pieces. This
616 // results in some debug border quads drawing over foreground quads.
617 void GLRenderer::DrawDebugBorderQuad(const DrawingFrame* frame,
618 const DebugBorderDrawQuad* quad) {
619 SetBlendEnabled(quad->ShouldDrawWithBlending());
621 static float gl_matrix[16];
622 const DebugBorderProgram* program = GetDebugBorderProgram();
623 DCHECK(program && (program->initialized() || IsContextLost()));
624 SetUseProgram(program->program());
626 // Use the full quad_rect for debug quads to not move the edges based on
627 // partial swaps.
628 gfx::Rect layer_rect = quad->rect;
629 gfx::Transform render_matrix;
630 QuadRectTransform(&render_matrix, quad->quadTransform(), layer_rect);
631 GLRenderer::ToGLMatrix(&gl_matrix[0],
632 frame->projection_matrix * render_matrix);
633 GLC(gl_,
634 gl_->UniformMatrix4fv(
635 program->vertex_shader().matrix_location(), 1, false, &gl_matrix[0]));
637 SkColor color = quad->color;
638 float alpha = SkColorGetA(color) * (1.0f / 255.0f);
640 GLC(gl_,
641 gl_->Uniform4f(program->fragment_shader().color_location(),
642 (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
643 (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
644 (SkColorGetB(color) * (1.0f / 255.0f)) * alpha,
645 alpha));
647 GLC(gl_, gl_->LineWidth(quad->width));
649 // The indices for the line are stored in the same array as the triangle
650 // indices.
651 GLC(gl_, gl_->DrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, 0));
654 static skia::RefPtr<SkImage> ApplyImageFilter(
655 scoped_ptr<GLRenderer::ScopedUseGrContext> use_gr_context,
656 ResourceProvider* resource_provider,
657 const gfx::Rect& rect,
658 const gfx::Vector2dF& scale,
659 SkImageFilter* filter,
660 ScopedResource* source_texture_resource) {
661 if (!filter)
662 return skia::RefPtr<SkImage>();
664 if (!use_gr_context)
665 return skia::RefPtr<SkImage>();
667 ResourceProvider::ScopedReadLockGL lock(resource_provider,
668 source_texture_resource->id());
670 // Wrap the source texture in a Ganesh platform texture.
671 GrBackendTextureDesc backend_texture_description;
672 backend_texture_description.fWidth = source_texture_resource->size().width();
673 backend_texture_description.fHeight =
674 source_texture_resource->size().height();
675 backend_texture_description.fConfig = kSkia8888_GrPixelConfig;
676 backend_texture_description.fTextureHandle = lock.texture_id();
677 backend_texture_description.fOrigin = kBottomLeft_GrSurfaceOrigin;
678 skia::RefPtr<GrTexture> texture =
679 skia::AdoptRef(use_gr_context->context()->wrapBackendTexture(
680 backend_texture_description));
681 if (!texture) {
682 TRACE_EVENT_INSTANT0("cc",
683 "ApplyImageFilter wrap background texture failed",
684 TRACE_EVENT_SCOPE_THREAD);
685 return skia::RefPtr<SkImage>();
688 SkImageInfo info =
689 SkImageInfo::MakeN32Premul(source_texture_resource->size().width(),
690 source_texture_resource->size().height());
691 // Place the platform texture inside an SkBitmap.
692 SkBitmap source;
693 source.setInfo(info);
694 skia::RefPtr<SkGrPixelRef> pixel_ref =
695 skia::AdoptRef(new SkGrPixelRef(info, texture.get()));
696 source.setPixelRef(pixel_ref.get());
698 // Create a scratch texture for backing store.
699 GrTextureDesc desc;
700 desc.fFlags = kRenderTarget_GrTextureFlagBit | kNoStencil_GrTextureFlagBit;
701 desc.fSampleCnt = 0;
702 desc.fWidth = source.width();
703 desc.fHeight = source.height();
704 desc.fConfig = kSkia8888_GrPixelConfig;
705 desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
706 skia::RefPtr<GrTexture> backing_store =
707 skia::AdoptRef(use_gr_context->context()->refScratchTexture(
708 desc, GrContext::kExact_ScratchTexMatch));
709 if (!backing_store) {
710 TRACE_EVENT_INSTANT0("cc",
711 "ApplyImageFilter scratch texture allocation failed",
712 TRACE_EVENT_SCOPE_THREAD);
713 return skia::RefPtr<SkImage>();
716 // Create surface to draw into.
717 skia::RefPtr<SkSurface> surface = skia::AdoptRef(
718 SkSurface::NewRenderTargetDirect(backing_store->asRenderTarget()));
719 skia::RefPtr<SkCanvas> canvas = skia::SharePtr(surface->getCanvas());
721 // Draw the source bitmap through the filter to the canvas.
722 SkPaint paint;
723 paint.setImageFilter(filter);
724 canvas->clear(SK_ColorTRANSPARENT);
726 // The origin of the filter is top-left and the origin of the source is
727 // bottom-left, but the orientation is the same, so we must translate the
728 // filter so that it renders at the bottom of the texture to avoid
729 // misregistration.
730 int y_translate = source.height() - rect.height() - rect.origin().y();
731 canvas->translate(-rect.origin().x(), y_translate);
732 canvas->scale(scale.x(), scale.y());
733 canvas->drawSprite(source, 0, 0, &paint);
735 skia::RefPtr<SkImage> image = skia::AdoptRef(surface->newImageSnapshot());
736 if (!image || !image->getTexture()) {
737 return skia::RefPtr<SkImage>();
740 // Flush the GrContext to ensure all buffered GL calls are drawn to the
741 // backing store before we access and return it, and have cc begin using the
742 // GL context again.
743 canvas->flush();
745 return image;
748 bool GLRenderer::CanApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode) {
749 return use_blend_equation_advanced_ ||
750 blend_mode == SkXfermode::kScreen_Mode ||
751 blend_mode == SkXfermode::kSrcOver_Mode;
754 void GLRenderer::ApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode) {
755 DCHECK(CanApplyBlendModeUsingBlendFunc(blend_mode));
757 // Any modes set here must be reset in RestoreBlendFuncToDefault
758 if (use_blend_equation_advanced_) {
759 GLenum equation = GL_FUNC_ADD;
761 switch (blend_mode) {
762 case SkXfermode::kScreen_Mode:
763 equation = GL_SCREEN_KHR;
764 break;
765 case SkXfermode::kOverlay_Mode:
766 equation = GL_OVERLAY_KHR;
767 break;
768 case SkXfermode::kDarken_Mode:
769 equation = GL_DARKEN_KHR;
770 break;
771 case SkXfermode::kLighten_Mode:
772 equation = GL_LIGHTEN_KHR;
773 break;
774 case SkXfermode::kColorDodge_Mode:
775 equation = GL_COLORDODGE_KHR;
776 break;
777 case SkXfermode::kColorBurn_Mode:
778 equation = GL_COLORBURN_KHR;
779 break;
780 case SkXfermode::kHardLight_Mode:
781 equation = GL_HARDLIGHT_KHR;
782 break;
783 case SkXfermode::kSoftLight_Mode:
784 equation = GL_SOFTLIGHT_KHR;
785 break;
786 case SkXfermode::kDifference_Mode:
787 equation = GL_DIFFERENCE_KHR;
788 break;
789 case SkXfermode::kExclusion_Mode:
790 equation = GL_EXCLUSION_KHR;
791 break;
792 case SkXfermode::kMultiply_Mode:
793 equation = GL_MULTIPLY_KHR;
794 break;
795 case SkXfermode::kHue_Mode:
796 equation = GL_HSL_HUE_KHR;
797 break;
798 case SkXfermode::kSaturation_Mode:
799 equation = GL_HSL_SATURATION_KHR;
800 break;
801 case SkXfermode::kColor_Mode:
802 equation = GL_HSL_COLOR_KHR;
803 break;
804 case SkXfermode::kLuminosity_Mode:
805 equation = GL_HSL_LUMINOSITY_KHR;
806 break;
807 default:
808 return;
811 GLC(gl_, gl_->BlendEquation(equation));
812 } else {
813 if (blend_mode == SkXfermode::kScreen_Mode) {
814 GLC(gl_, gl_->BlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE));
819 void GLRenderer::RestoreBlendFuncToDefault(SkXfermode::Mode blend_mode) {
820 if (blend_mode == SkXfermode::kSrcOver_Mode)
821 return;
823 if (use_blend_equation_advanced_) {
824 GLC(gl_, gl_->BlendEquation(GL_FUNC_ADD));
825 } else {
826 GLC(gl_, gl_->BlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA));
830 bool GLRenderer::ShouldApplyBackgroundFilters(DrawingFrame* frame,
831 const RenderPassDrawQuad* quad) {
832 if (quad->background_filters.IsEmpty())
833 return false;
835 // TODO(danakj): We only allow background filters on an opaque render surface
836 // because other surfaces may contain translucent pixels, and the contents
837 // behind those translucent pixels wouldn't have the filter applied.
838 if (frame->current_render_pass->has_transparent_background)
839 return false;
841 // TODO(ajuma): Add support for reference filters once
842 // FilterOperations::GetOutsets supports reference filters.
843 if (quad->background_filters.HasReferenceFilter())
844 return false;
845 return true;
848 // This takes a gfx::Rect and a clip region quad in the same space,
849 // and returns a quad with the same proportions in the space -0.5->0.5.
850 bool GetScaledRegion(const gfx::Rect& rect,
851 const gfx::QuadF* clip,
852 gfx::QuadF* scaled_region) {
853 if (!clip)
854 return false;
856 gfx::PointF p1(((clip->p1().x() - rect.x()) / rect.width()) - 0.5f,
857 ((clip->p1().y() - rect.y()) / rect.height()) - 0.5f);
858 gfx::PointF p2(((clip->p2().x() - rect.x()) / rect.width()) - 0.5f,
859 ((clip->p2().y() - rect.y()) / rect.height()) - 0.5f);
860 gfx::PointF p3(((clip->p3().x() - rect.x()) / rect.width()) - 0.5f,
861 ((clip->p3().y() - rect.y()) / rect.height()) - 0.5f);
862 gfx::PointF p4(((clip->p4().x() - rect.x()) / rect.width()) - 0.5f,
863 ((clip->p4().y() - rect.y()) / rect.height()) - 0.5f);
864 *scaled_region = gfx::QuadF(p1, p2, p3, p4);
865 return true;
868 // This takes a gfx::Rect and a clip region quad in the same space,
869 // and returns the proportional uv's in the space 0->1.
870 bool GetScaledUVs(const gfx::Rect& rect, const gfx::QuadF* clip, float uvs[8]) {
871 if (!clip)
872 return false;
874 uvs[0] = ((clip->p1().x() - rect.x()) / rect.width());
875 uvs[1] = ((clip->p1().y() - rect.y()) / rect.height());
876 uvs[2] = ((clip->p2().x() - rect.x()) / rect.width());
877 uvs[3] = ((clip->p2().y() - rect.y()) / rect.height());
878 uvs[4] = ((clip->p3().x() - rect.x()) / rect.width());
879 uvs[5] = ((clip->p3().y() - rect.y()) / rect.height());
880 uvs[6] = ((clip->p4().x() - rect.x()) / rect.width());
881 uvs[7] = ((clip->p4().y() - rect.y()) / rect.height());
882 return true;
885 gfx::Rect GLRenderer::GetBackdropBoundingBoxForRenderPassQuad(
886 DrawingFrame* frame,
887 const RenderPassDrawQuad* quad,
888 const gfx::Transform& contents_device_transform,
889 const gfx::QuadF* clip_region,
890 bool use_aa) {
891 gfx::QuadF scaled_region;
892 if (!GetScaledRegion(quad->rect, clip_region, &scaled_region)) {
893 scaled_region = SharedGeometryQuad().BoundingBox();
896 gfx::Rect backdrop_rect = gfx::ToEnclosingRect(MathUtil::MapClippedRect(
897 contents_device_transform, scaled_region.BoundingBox()));
899 if (ShouldApplyBackgroundFilters(frame, quad)) {
900 int top, right, bottom, left;
901 quad->background_filters.GetOutsets(&top, &right, &bottom, &left);
902 backdrop_rect.Inset(-left, -top, -right, -bottom);
905 if (!backdrop_rect.IsEmpty() && use_aa) {
906 const int kOutsetForAntialiasing = 1;
907 backdrop_rect.Inset(-kOutsetForAntialiasing, -kOutsetForAntialiasing);
910 backdrop_rect.Intersect(MoveFromDrawToWindowSpace(
911 frame, frame->current_render_pass->output_rect));
912 return backdrop_rect;
915 scoped_ptr<ScopedResource> GLRenderer::GetBackdropTexture(
916 const gfx::Rect& bounding_rect) {
917 scoped_ptr<ScopedResource> device_background_texture =
918 ScopedResource::Create(resource_provider_);
919 // CopyTexImage2D fails when called on a texture having immutable storage.
920 device_background_texture->Allocate(
921 bounding_rect.size(), ResourceProvider::TEXTURE_HINT_DEFAULT, RGBA_8888);
923 ResourceProvider::ScopedWriteLockGL lock(resource_provider_,
924 device_background_texture->id());
925 GetFramebufferTexture(
926 lock.texture_id(), device_background_texture->format(), bounding_rect);
928 return device_background_texture.Pass();
931 skia::RefPtr<SkImage> GLRenderer::ApplyBackgroundFilters(
932 DrawingFrame* frame,
933 const RenderPassDrawQuad* quad,
934 ScopedResource* background_texture) {
935 DCHECK(ShouldApplyBackgroundFilters(frame, quad));
936 skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
937 quad->background_filters, background_texture->size());
939 skia::RefPtr<SkImage> background_with_filters = ApplyImageFilter(
940 ScopedUseGrContext::Create(this, frame), resource_provider_, quad->rect,
941 quad->filters_scale, filter.get(), background_texture);
942 return background_with_filters;
945 void GLRenderer::DrawRenderPassQuad(DrawingFrame* frame,
946 const RenderPassDrawQuad* quad,
947 const gfx::QuadF* clip_region) {
948 ScopedResource* contents_texture =
949 render_pass_textures_.get(quad->render_pass_id);
950 if (!contents_texture || !contents_texture->id())
951 return;
953 gfx::Transform quad_rect_matrix;
954 QuadRectTransform(&quad_rect_matrix, quad->quadTransform(), quad->rect);
955 gfx::Transform contents_device_transform =
956 frame->window_matrix * frame->projection_matrix * quad_rect_matrix;
957 contents_device_transform.FlattenTo2d();
959 // Can only draw surface if device matrix is invertible.
960 if (!contents_device_transform.IsInvertible())
961 return;
963 gfx::QuadF surface_quad = SharedGeometryQuad();
964 float edge[24];
965 bool use_aa = settings_->allow_antialiasing &&
966 ShouldAntialiasQuad(contents_device_transform, quad,
967 settings_->force_antialiasing);
969 SetupQuadForClippingAndAntialiasing(contents_device_transform, quad, use_aa,
970 clip_region, &surface_quad, edge);
971 SkXfermode::Mode blend_mode = quad->shared_quad_state->blend_mode;
972 bool use_shaders_for_blending =
973 !CanApplyBlendModeUsingBlendFunc(blend_mode) ||
974 ShouldApplyBackgroundFilters(frame, quad) ||
975 settings_->force_blending_with_shaders;
977 scoped_ptr<ScopedResource> background_texture;
978 skia::RefPtr<SkImage> background_image;
979 gfx::Rect background_rect;
980 if (use_shaders_for_blending) {
981 // Compute a bounding box around the pixels that will be visible through
982 // the quad.
983 background_rect = GetBackdropBoundingBoxForRenderPassQuad(
984 frame, quad, contents_device_transform, clip_region, use_aa);
986 if (!background_rect.IsEmpty()) {
987 // The pixels from the filtered background should completely replace the
988 // current pixel values.
989 if (blend_enabled())
990 SetBlendEnabled(false);
992 // Read the pixels in the bounding box into a buffer R.
993 // This function allocates a texture, which should contribute to the
994 // amount of memory used by render surfaces:
995 // LayerTreeHost::CalculateMemoryForRenderSurfaces.
996 background_texture = GetBackdropTexture(background_rect);
998 if (ShouldApplyBackgroundFilters(frame, quad) && background_texture) {
999 // Apply the background filters to R, so that it is applied in the
1000 // pixels' coordinate space.
1001 background_image =
1002 ApplyBackgroundFilters(frame, quad, background_texture.get());
1006 if (!background_texture) {
1007 // Something went wrong with reading the backdrop.
1008 DCHECK(!background_image);
1009 use_shaders_for_blending = false;
1010 } else if (background_image) {
1011 // Reset original background texture if there is not any mask
1012 if (!quad->mask_resource_id)
1013 background_texture.reset();
1014 } else if (CanApplyBlendModeUsingBlendFunc(blend_mode) &&
1015 ShouldApplyBackgroundFilters(frame, quad)) {
1016 // Something went wrong with applying background filters to the backdrop.
1017 use_shaders_for_blending = false;
1018 background_texture.reset();
1021 // Need original background texture for mask?
1022 bool mask_for_background =
1023 background_texture && // Have original background texture
1024 background_image && // Have filtered background texture
1025 quad->mask_resource_id; // Have mask texture
1026 SetBlendEnabled(
1027 !use_shaders_for_blending &&
1028 (quad->ShouldDrawWithBlending() || !IsDefaultBlendMode(blend_mode)));
1030 // TODO(senorblanco): Cache this value so that we don't have to do it for both
1031 // the surface and its replica. Apply filters to the contents texture.
1032 skia::RefPtr<SkImage> filter_image;
1033 SkScalar color_matrix[20];
1034 bool use_color_matrix = false;
1035 if (!quad->filters.IsEmpty()) {
1036 skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
1037 quad->filters, contents_texture->size());
1038 if (filter) {
1039 skia::RefPtr<SkColorFilter> cf;
1042 SkColorFilter* colorfilter_rawptr = NULL;
1043 filter->asColorFilter(&colorfilter_rawptr);
1044 cf = skia::AdoptRef(colorfilter_rawptr);
1047 if (cf && cf->asColorMatrix(color_matrix) && !filter->getInput(0)) {
1048 // We have a single color matrix as a filter; apply it locally
1049 // in the compositor.
1050 use_color_matrix = true;
1051 } else {
1052 filter_image = ApplyImageFilter(
1053 ScopedUseGrContext::Create(this, frame), resource_provider_,
1054 quad->rect, quad->filters_scale, filter.get(), contents_texture);
1059 scoped_ptr<ResourceProvider::ScopedSamplerGL> mask_resource_lock;
1060 unsigned mask_texture_id = 0;
1061 SamplerType mask_sampler = SAMPLER_TYPE_NA;
1062 if (quad->mask_resource_id) {
1063 mask_resource_lock.reset(new ResourceProvider::ScopedSamplerGL(
1064 resource_provider_, quad->mask_resource_id, GL_TEXTURE1, GL_LINEAR));
1065 mask_texture_id = mask_resource_lock->texture_id();
1066 mask_sampler = SamplerTypeFromTextureTarget(mask_resource_lock->target());
1069 scoped_ptr<ResourceProvider::ScopedSamplerGL> contents_resource_lock;
1070 if (filter_image) {
1071 GrTexture* texture = filter_image->getTexture();
1072 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
1073 gl_->BindTexture(GL_TEXTURE_2D, texture->getTextureHandle());
1074 } else {
1075 contents_resource_lock =
1076 make_scoped_ptr(new ResourceProvider::ScopedSamplerGL(
1077 resource_provider_, contents_texture->id(), GL_LINEAR));
1078 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
1079 contents_resource_lock->target());
1082 if (!use_shaders_for_blending) {
1083 if (!use_blend_equation_advanced_coherent_ && use_blend_equation_advanced_)
1084 GLC(gl_, gl_->BlendBarrierKHR());
1086 ApplyBlendModeUsingBlendFunc(blend_mode);
1089 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1090 gl_,
1091 &highp_threshold_cache_,
1092 highp_threshold_min_,
1093 quad->shared_quad_state->visible_content_rect.bottom_right());
1095 ShaderLocations locations;
1097 DCHECK_EQ(background_texture || background_image, use_shaders_for_blending);
1098 BlendMode shader_blend_mode = use_shaders_for_blending
1099 ? BlendModeFromSkXfermode(blend_mode)
1100 : BLEND_MODE_NONE;
1102 if (use_aa && mask_texture_id && !use_color_matrix) {
1103 const RenderPassMaskProgramAA* program = GetRenderPassMaskProgramAA(
1104 tex_coord_precision, mask_sampler,
1105 shader_blend_mode, mask_for_background);
1106 SetUseProgram(program->program());
1107 program->vertex_shader().FillLocations(&locations);
1108 program->fragment_shader().FillLocations(&locations);
1109 GLC(gl_, gl_->Uniform1i(locations.sampler, 0));
1110 } else if (!use_aa && mask_texture_id && !use_color_matrix) {
1111 const RenderPassMaskProgram* program = GetRenderPassMaskProgram(
1112 tex_coord_precision, mask_sampler,
1113 shader_blend_mode, mask_for_background);
1114 SetUseProgram(program->program());
1115 program->vertex_shader().FillLocations(&locations);
1116 program->fragment_shader().FillLocations(&locations);
1117 GLC(gl_, gl_->Uniform1i(locations.sampler, 0));
1118 } else if (use_aa && !mask_texture_id && !use_color_matrix) {
1119 const RenderPassProgramAA* program =
1120 GetRenderPassProgramAA(tex_coord_precision, shader_blend_mode);
1121 SetUseProgram(program->program());
1122 program->vertex_shader().FillLocations(&locations);
1123 program->fragment_shader().FillLocations(&locations);
1124 GLC(gl_, gl_->Uniform1i(locations.sampler, 0));
1125 } else if (use_aa && mask_texture_id && use_color_matrix) {
1126 const RenderPassMaskColorMatrixProgramAA* program =
1127 GetRenderPassMaskColorMatrixProgramAA(
1128 tex_coord_precision, mask_sampler,
1129 shader_blend_mode, mask_for_background);
1130 SetUseProgram(program->program());
1131 program->vertex_shader().FillLocations(&locations);
1132 program->fragment_shader().FillLocations(&locations);
1133 GLC(gl_, gl_->Uniform1i(locations.sampler, 0));
1134 } else if (use_aa && !mask_texture_id && use_color_matrix) {
1135 const RenderPassColorMatrixProgramAA* program =
1136 GetRenderPassColorMatrixProgramAA(tex_coord_precision,
1137 shader_blend_mode);
1138 SetUseProgram(program->program());
1139 program->vertex_shader().FillLocations(&locations);
1140 program->fragment_shader().FillLocations(&locations);
1141 GLC(gl_, gl_->Uniform1i(locations.sampler, 0));
1142 } else if (!use_aa && mask_texture_id && use_color_matrix) {
1143 const RenderPassMaskColorMatrixProgram* program =
1144 GetRenderPassMaskColorMatrixProgram(
1145 tex_coord_precision, mask_sampler,
1146 shader_blend_mode, mask_for_background);
1147 SetUseProgram(program->program());
1148 program->vertex_shader().FillLocations(&locations);
1149 program->fragment_shader().FillLocations(&locations);
1150 GLC(gl_, gl_->Uniform1i(locations.sampler, 0));
1151 } else if (!use_aa && !mask_texture_id && use_color_matrix) {
1152 const RenderPassColorMatrixProgram* program =
1153 GetRenderPassColorMatrixProgram(tex_coord_precision, shader_blend_mode);
1154 SetUseProgram(program->program());
1155 program->vertex_shader().FillLocations(&locations);
1156 program->fragment_shader().FillLocations(&locations);
1157 GLC(gl_, gl_->Uniform1i(locations.sampler, 0));
1158 } else {
1159 const RenderPassProgram* program =
1160 GetRenderPassProgram(tex_coord_precision, shader_blend_mode);
1161 SetUseProgram(program->program());
1162 program->vertex_shader().FillLocations(&locations);
1163 program->fragment_shader().FillLocations(&locations);
1164 GLC(gl_, gl_->Uniform1i(locations.sampler, 0));
1166 float tex_scale_x =
1167 quad->rect.width() / static_cast<float>(contents_texture->size().width());
1168 float tex_scale_y = quad->rect.height() /
1169 static_cast<float>(contents_texture->size().height());
1170 DCHECK_LE(tex_scale_x, 1.0f);
1171 DCHECK_LE(tex_scale_y, 1.0f);
1173 DCHECK(locations.tex_transform != -1 || IsContextLost());
1174 // Flip the content vertically in the shader, as the RenderPass input
1175 // texture is already oriented the same way as the framebuffer, but the
1176 // projection transform does a flip.
1177 GLC(gl_,
1178 gl_->Uniform4f(locations.tex_transform,
1179 0.0f,
1180 tex_scale_y,
1181 tex_scale_x,
1182 -tex_scale_y));
1184 GLint last_texture_unit = 0;
1185 if (locations.mask_sampler != -1) {
1186 DCHECK_NE(locations.mask_tex_coord_scale, 1);
1187 DCHECK_NE(locations.mask_tex_coord_offset, 1);
1188 GLC(gl_, gl_->Uniform1i(locations.mask_sampler, 1));
1190 gfx::RectF mask_uv_rect = quad->MaskUVRect();
1191 if (mask_sampler != SAMPLER_TYPE_2D) {
1192 mask_uv_rect.Scale(quad->mask_texture_size.width(),
1193 quad->mask_texture_size.height());
1196 // Mask textures are oriented vertically flipped relative to the framebuffer
1197 // and the RenderPass contents texture, so we flip the tex coords from the
1198 // RenderPass texture to find the mask texture coords.
1199 GLC(gl_,
1200 gl_->Uniform2f(locations.mask_tex_coord_offset,
1201 mask_uv_rect.x(),
1202 mask_uv_rect.bottom()));
1203 GLC(gl_,
1204 gl_->Uniform2f(locations.mask_tex_coord_scale,
1205 mask_uv_rect.width() / tex_scale_x,
1206 -mask_uv_rect.height() / tex_scale_y));
1208 last_texture_unit = 1;
1211 if (locations.edge != -1)
1212 GLC(gl_, gl_->Uniform3fv(locations.edge, 8, edge));
1214 if (locations.viewport != -1) {
1215 float viewport[4] = {static_cast<float>(viewport_.x()),
1216 static_cast<float>(viewport_.y()),
1217 static_cast<float>(viewport_.width()),
1218 static_cast<float>(viewport_.height()), };
1219 GLC(gl_, gl_->Uniform4fv(locations.viewport, 1, viewport));
1222 if (locations.color_matrix != -1) {
1223 float matrix[16];
1224 for (int i = 0; i < 4; ++i) {
1225 for (int j = 0; j < 4; ++j)
1226 matrix[i * 4 + j] = SkScalarToFloat(color_matrix[j * 5 + i]);
1228 GLC(gl_,
1229 gl_->UniformMatrix4fv(locations.color_matrix, 1, false, matrix));
1231 static const float kScale = 1.0f / 255.0f;
1232 if (locations.color_offset != -1) {
1233 float offset[4];
1234 for (int i = 0; i < 4; ++i)
1235 offset[i] = SkScalarToFloat(color_matrix[i * 5 + 4]) * kScale;
1237 GLC(gl_, gl_->Uniform4fv(locations.color_offset, 1, offset));
1240 scoped_ptr<ResourceProvider::ScopedSamplerGL> shader_background_sampler_lock;
1241 if (locations.backdrop != -1) {
1242 DCHECK(background_texture || background_image);
1243 DCHECK_NE(locations.backdrop, 0);
1244 DCHECK_NE(locations.backdrop_rect, 0);
1246 GLC(gl_, gl_->Uniform1i(locations.backdrop, ++last_texture_unit));
1248 GLC(gl_,
1249 gl_->Uniform4f(locations.backdrop_rect,
1250 background_rect.x(),
1251 background_rect.y(),
1252 background_rect.width(),
1253 background_rect.height()));
1255 if (background_image) {
1256 GrTexture* texture = background_image->getTexture();
1257 GLC(gl_, gl_->ActiveTexture(GL_TEXTURE0 + last_texture_unit));
1258 gl_->BindTexture(GL_TEXTURE_2D, texture->getTextureHandle());
1259 GLC(gl_, gl_->ActiveTexture(GL_TEXTURE0));
1260 if (mask_for_background)
1261 GLC(gl_, gl_->Uniform1i(locations.original_backdrop,
1262 ++last_texture_unit));
1264 if (background_texture) {
1265 shader_background_sampler_lock = make_scoped_ptr(
1266 new ResourceProvider::ScopedSamplerGL(resource_provider_,
1267 background_texture->id(),
1268 GL_TEXTURE0 + last_texture_unit,
1269 GL_LINEAR));
1270 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
1271 shader_background_sampler_lock->target());
1275 SetShaderOpacity(quad->opacity(), locations.alpha);
1276 SetShaderQuadF(surface_quad, locations.quad);
1277 DrawQuadGeometry(
1278 frame, quad->quadTransform(), quad->rect, locations.matrix);
1280 // Flush the compositor context before the filter bitmap goes out of
1281 // scope, so the draw gets processed before the filter texture gets deleted.
1282 if (filter_image)
1283 GLC(gl_, gl_->Flush());
1285 if (!use_shaders_for_blending)
1286 RestoreBlendFuncToDefault(blend_mode);
1289 struct SolidColorProgramUniforms {
1290 unsigned program;
1291 unsigned matrix_location;
1292 unsigned viewport_location;
1293 unsigned quad_location;
1294 unsigned edge_location;
1295 unsigned color_location;
1298 template <class T>
1299 static void SolidColorUniformLocation(T program,
1300 SolidColorProgramUniforms* uniforms) {
1301 uniforms->program = program->program();
1302 uniforms->matrix_location = program->vertex_shader().matrix_location();
1303 uniforms->viewport_location = program->vertex_shader().viewport_location();
1304 uniforms->quad_location = program->vertex_shader().quad_location();
1305 uniforms->edge_location = program->vertex_shader().edge_location();
1306 uniforms->color_location = program->fragment_shader().color_location();
1309 namespace {
1310 // These functions determine if a quad, clipped by a clip_region contains
1311 // the entire {top|bottom|left|right} edge.
1312 bool is_top(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1313 if (!quad->IsTopEdge())
1314 return false;
1315 if (!clip_region)
1316 return true;
1318 return std::abs(clip_region->p1().y()) < kAntiAliasingEpsilon &&
1319 std::abs(clip_region->p2().y()) < kAntiAliasingEpsilon;
1322 bool is_bottom(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1323 if (!quad->IsBottomEdge())
1324 return false;
1325 if (!clip_region)
1326 return true;
1328 return std::abs(clip_region->p3().y() -
1329 quad->shared_quad_state->content_bounds.height()) <
1330 kAntiAliasingEpsilon &&
1331 std::abs(clip_region->p4().y() -
1332 quad->shared_quad_state->content_bounds.height()) <
1333 kAntiAliasingEpsilon;
1336 bool is_left(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1337 if (!quad->IsLeftEdge())
1338 return false;
1339 if (!clip_region)
1340 return true;
1342 return std::abs(clip_region->p1().x()) < kAntiAliasingEpsilon &&
1343 std::abs(clip_region->p4().x()) < kAntiAliasingEpsilon;
1346 bool is_right(const gfx::QuadF* clip_region, const DrawQuad* quad) {
1347 if (!quad->IsRightEdge())
1348 return false;
1349 if (!clip_region)
1350 return true;
1352 return std::abs(clip_region->p2().x() -
1353 quad->shared_quad_state->content_bounds.width()) <
1354 kAntiAliasingEpsilon &&
1355 std::abs(clip_region->p3().x() -
1356 quad->shared_quad_state->content_bounds.width()) <
1357 kAntiAliasingEpsilon;
1359 } // anonymous namespace
1361 static gfx::QuadF GetDeviceQuadWithAntialiasingOnExteriorEdges(
1362 const LayerQuad& device_layer_edges,
1363 const gfx::Transform& device_transform,
1364 const gfx::QuadF* clip_region,
1365 const DrawQuad* quad) {
1366 gfx::RectF tile_rect = quad->visible_rect;
1367 gfx::QuadF tile_quad(tile_rect);
1369 if (clip_region) {
1370 if (quad->material != DrawQuad::RENDER_PASS) {
1371 tile_quad = *clip_region;
1372 } else {
1373 GetScaledRegion(quad->rect, clip_region, &tile_quad);
1377 gfx::PointF bottom_right = tile_quad.p3();
1378 gfx::PointF bottom_left = tile_quad.p4();
1379 gfx::PointF top_left = tile_quad.p1();
1380 gfx::PointF top_right = tile_quad.p2();
1381 bool clipped = false;
1383 // Map points to device space. We ignore |clipped|, since the result of
1384 // |MapPoint()| still produces a valid point to draw the quad with. When
1385 // clipped, the point will be outside of the viewport. See crbug.com/416367.
1386 bottom_right = MathUtil::MapPoint(device_transform, bottom_right, &clipped);
1387 bottom_left = MathUtil::MapPoint(device_transform, bottom_left, &clipped);
1388 top_left = MathUtil::MapPoint(device_transform, top_left, &clipped);
1389 top_right = MathUtil::MapPoint(device_transform, top_right, &clipped);
1391 LayerQuad::Edge bottom_edge(bottom_right, bottom_left);
1392 LayerQuad::Edge left_edge(bottom_left, top_left);
1393 LayerQuad::Edge top_edge(top_left, top_right);
1394 LayerQuad::Edge right_edge(top_right, bottom_right);
1396 // Only apply anti-aliasing to edges not clipped by culling or scissoring.
1397 // If an edge is degenerate we do not want to replace it with a "proper" edge
1398 // as that will cause the quad to possibly expand is strange ways.
1399 if (!top_edge.degenerate() && is_top(clip_region, quad) &&
1400 tile_rect.y() == quad->rect.y()) {
1401 top_edge = device_layer_edges.top();
1403 if (!left_edge.degenerate() && is_left(clip_region, quad) &&
1404 tile_rect.x() == quad->rect.x()) {
1405 left_edge = device_layer_edges.left();
1407 if (!right_edge.degenerate() && is_right(clip_region, quad) &&
1408 tile_rect.right() == quad->rect.right()) {
1409 right_edge = device_layer_edges.right();
1411 if (!bottom_edge.degenerate() && is_bottom(clip_region, quad) &&
1412 tile_rect.bottom() == quad->rect.bottom()) {
1413 bottom_edge = device_layer_edges.bottom();
1416 float sign = tile_quad.IsCounterClockwise() ? -1 : 1;
1417 bottom_edge.scale(sign);
1418 left_edge.scale(sign);
1419 top_edge.scale(sign);
1420 right_edge.scale(sign);
1422 // Create device space quad.
1423 return LayerQuad(left_edge, top_edge, right_edge, bottom_edge).ToQuadF();
1426 float GetTotalQuadError(const gfx::QuadF* clipped_quad,
1427 const gfx::QuadF* ideal_rect) {
1428 return (clipped_quad->p1() - ideal_rect->p1()).LengthSquared() +
1429 (clipped_quad->p2() - ideal_rect->p2()).LengthSquared() +
1430 (clipped_quad->p3() - ideal_rect->p3()).LengthSquared() +
1431 (clipped_quad->p4() - ideal_rect->p4()).LengthSquared();
1434 // Attempt to rotate the clipped quad until it lines up the most
1435 // correctly. This is necessary because we check the edges of this
1436 // quad against the expected left/right/top/bottom for anti-aliasing.
1437 void AlignQuadToBoundingBox(gfx::QuadF* clipped_quad) {
1438 gfx::QuadF bounding_quad = gfx::QuadF(clipped_quad->BoundingBox());
1439 gfx::QuadF best_rotation = *clipped_quad;
1440 float least_error_amount = GetTotalQuadError(clipped_quad, &bounding_quad);
1441 for (size_t i = 1; i < 4; ++i) {
1442 clipped_quad->Realign(1);
1443 float new_error = GetTotalQuadError(clipped_quad, &bounding_quad);
1444 if (new_error < least_error_amount) {
1445 least_error_amount = new_error;
1446 best_rotation = *clipped_quad;
1449 *clipped_quad = best_rotation;
1452 // static
1453 bool GLRenderer::ShouldAntialiasQuad(const gfx::Transform& device_transform,
1454 const DrawQuad* quad,
1455 bool force_antialiasing) {
1456 bool is_render_pass_quad = (quad->material == DrawQuad::RENDER_PASS);
1457 // For render pass quads, |device_transform| already contains quad's rect.
1458 // TODO(rosca@adobe.com): remove branching on is_render_pass_quad
1459 // crbug.com/429702
1460 if (!is_render_pass_quad && !quad->IsEdge())
1461 return false;
1462 gfx::RectF content_rect =
1463 is_render_pass_quad ? QuadVertexRect() : quad->visibleContentRect();
1465 bool clipped = false;
1466 gfx::QuadF device_layer_quad =
1467 MathUtil::MapQuad(device_transform, gfx::QuadF(content_rect), &clipped);
1469 if (device_layer_quad.BoundingBox().IsEmpty())
1470 return false;
1472 bool is_axis_aligned_in_target = device_layer_quad.IsRectilinear();
1473 bool is_nearest_rect_within_epsilon =
1474 is_axis_aligned_in_target &&
1475 gfx::IsNearestRectWithinDistance(device_layer_quad.BoundingBox(),
1476 kAntiAliasingEpsilon);
1477 // AAing clipped quads is not supported by the code yet.
1478 bool use_aa = !clipped && !is_nearest_rect_within_epsilon;
1479 return use_aa || force_antialiasing;
1482 // static
1483 void GLRenderer::SetupQuadForClippingAndAntialiasing(
1484 const gfx::Transform& device_transform,
1485 const DrawQuad* quad,
1486 bool use_aa,
1487 const gfx::QuadF* clip_region,
1488 gfx::QuadF* local_quad,
1489 float edge[24]) {
1490 bool is_render_pass_quad = (quad->material == DrawQuad::RENDER_PASS);
1491 gfx::QuadF rotated_clip;
1492 const gfx::QuadF* local_clip_region = clip_region;
1493 if (local_clip_region) {
1494 rotated_clip = *clip_region;
1495 AlignQuadToBoundingBox(&rotated_clip);
1496 local_clip_region = &rotated_clip;
1499 gfx::QuadF content_rect = is_render_pass_quad
1500 ? gfx::QuadF(QuadVertexRect())
1501 : gfx::QuadF(quad->visibleContentRect());
1502 if (!use_aa) {
1503 if (local_clip_region) {
1504 if (!is_render_pass_quad) {
1505 content_rect = *local_clip_region;
1506 } else {
1507 GetScaledRegion(quad->rect, local_clip_region, &content_rect);
1509 *local_quad = content_rect;
1511 return;
1513 bool clipped = false;
1514 gfx::QuadF device_layer_quad =
1515 MathUtil::MapQuad(device_transform, content_rect, &clipped);
1517 LayerQuad device_layer_bounds(gfx::QuadF(device_layer_quad.BoundingBox()));
1518 device_layer_bounds.InflateAntiAliasingDistance();
1520 LayerQuad device_layer_edges(device_layer_quad);
1521 device_layer_edges.InflateAntiAliasingDistance();
1523 device_layer_edges.ToFloatArray(edge);
1524 device_layer_bounds.ToFloatArray(&edge[12]);
1526 // If we have a clip region then we are split, and therefore
1527 // by necessity, at least one of our edges is not an external
1528 // one.
1529 bool is_full_rect = quad->visible_rect == quad->rect;
1531 bool region_contains_all_outside_edges =
1532 is_full_rect &&
1533 (is_top(local_clip_region, quad) && is_left(local_clip_region, quad) &&
1534 is_bottom(local_clip_region, quad) && is_right(local_clip_region, quad));
1536 bool use_aa_on_all_four_edges =
1537 !local_clip_region &&
1538 (is_render_pass_quad || region_contains_all_outside_edges);
1540 gfx::QuadF device_quad =
1541 use_aa_on_all_four_edges
1542 ? device_layer_edges.ToQuadF()
1543 : GetDeviceQuadWithAntialiasingOnExteriorEdges(
1544 device_layer_edges, device_transform, local_clip_region, quad);
1546 // Map device space quad to local space. device_transform has no 3d
1547 // component since it was flattened, so we don't need to project. We should
1548 // have already checked that the transform was uninvertible above.
1549 gfx::Transform inverse_device_transform(gfx::Transform::kSkipInitialization);
1550 bool did_invert = device_transform.GetInverse(&inverse_device_transform);
1551 DCHECK(did_invert);
1552 *local_quad =
1553 MathUtil::MapQuad(inverse_device_transform, device_quad, &clipped);
1554 // We should not DCHECK(!clipped) here, because anti-aliasing inflation may
1555 // cause device_quad to become clipped. To our knowledge this scenario does
1556 // not need to be handled differently than the unclipped case.
1559 void GLRenderer::DrawSolidColorQuad(const DrawingFrame* frame,
1560 const SolidColorDrawQuad* quad,
1561 const gfx::QuadF* clip_region) {
1562 gfx::Rect tile_rect = quad->visible_rect;
1564 SkColor color = quad->color;
1565 float opacity = quad->opacity();
1566 float alpha = (SkColorGetA(color) * (1.0f / 255.0f)) * opacity;
1568 // Early out if alpha is small enough that quad doesn't contribute to output.
1569 if (alpha < std::numeric_limits<float>::epsilon() &&
1570 quad->ShouldDrawWithBlending())
1571 return;
1573 gfx::Transform device_transform =
1574 frame->window_matrix * frame->projection_matrix * quad->quadTransform();
1575 device_transform.FlattenTo2d();
1576 if (!device_transform.IsInvertible())
1577 return;
1579 bool force_aa = false;
1580 gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1581 float edge[24];
1582 bool use_aa = settings_->allow_antialiasing &&
1583 !quad->force_anti_aliasing_off &&
1584 ShouldAntialiasQuad(device_transform, quad, force_aa);
1585 SetupQuadForClippingAndAntialiasing(device_transform, quad, use_aa,
1586 clip_region, &local_quad, edge);
1588 SolidColorProgramUniforms uniforms;
1589 if (use_aa) {
1590 SolidColorUniformLocation(GetSolidColorProgramAA(), &uniforms);
1591 } else {
1592 SolidColorUniformLocation(GetSolidColorProgram(), &uniforms);
1594 SetUseProgram(uniforms.program);
1596 GLC(gl_,
1597 gl_->Uniform4f(uniforms.color_location,
1598 (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
1599 (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
1600 (SkColorGetB(color) * (1.0f / 255.0f)) * alpha,
1601 alpha));
1602 if (use_aa) {
1603 float viewport[4] = {static_cast<float>(viewport_.x()),
1604 static_cast<float>(viewport_.y()),
1605 static_cast<float>(viewport_.width()),
1606 static_cast<float>(viewport_.height()), };
1607 GLC(gl_, gl_->Uniform4fv(uniforms.viewport_location, 1, viewport));
1608 GLC(gl_, gl_->Uniform3fv(uniforms.edge_location, 8, edge));
1611 // Enable blending when the quad properties require it or if we decided
1612 // to use antialiasing.
1613 SetBlendEnabled(quad->ShouldDrawWithBlending() || use_aa);
1615 // Normalize to tile_rect.
1616 local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1618 SetShaderQuadF(local_quad, uniforms.quad_location);
1620 // The transform and vertex data are used to figure out the extents that the
1621 // un-antialiased quad should have and which vertex this is and the float
1622 // quad passed in via uniform is the actual geometry that gets used to draw
1623 // it. This is why this centered rect is used and not the original quad_rect.
1624 gfx::RectF centered_rect(
1625 gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1626 tile_rect.size());
1627 DrawQuadGeometry(
1628 frame, quad->quadTransform(), centered_rect, uniforms.matrix_location);
1631 struct TileProgramUniforms {
1632 unsigned program;
1633 unsigned matrix_location;
1634 unsigned viewport_location;
1635 unsigned quad_location;
1636 unsigned edge_location;
1637 unsigned vertex_tex_transform_location;
1638 unsigned sampler_location;
1639 unsigned fragment_tex_transform_location;
1640 unsigned alpha_location;
1643 template <class T>
1644 static void TileUniformLocation(T program, TileProgramUniforms* uniforms) {
1645 uniforms->program = program->program();
1646 uniforms->matrix_location = program->vertex_shader().matrix_location();
1647 uniforms->viewport_location = program->vertex_shader().viewport_location();
1648 uniforms->quad_location = program->vertex_shader().quad_location();
1649 uniforms->edge_location = program->vertex_shader().edge_location();
1650 uniforms->vertex_tex_transform_location =
1651 program->vertex_shader().vertex_tex_transform_location();
1653 uniforms->sampler_location = program->fragment_shader().sampler_location();
1654 uniforms->alpha_location = program->fragment_shader().alpha_location();
1655 uniforms->fragment_tex_transform_location =
1656 program->fragment_shader().fragment_tex_transform_location();
1659 void GLRenderer::DrawTileQuad(const DrawingFrame* frame,
1660 const TileDrawQuad* quad,
1661 const gfx::QuadF* clip_region) {
1662 DrawContentQuad(frame, quad, quad->resource_id, clip_region);
1665 void GLRenderer::DrawContentQuad(const DrawingFrame* frame,
1666 const ContentDrawQuadBase* quad,
1667 ResourceProvider::ResourceId resource_id,
1668 const gfx::QuadF* clip_region) {
1669 gfx::Transform device_transform =
1670 frame->window_matrix * frame->projection_matrix * quad->quadTransform();
1671 device_transform.FlattenTo2d();
1673 bool use_aa = settings_->allow_antialiasing &&
1674 ShouldAntialiasQuad(device_transform, quad, false);
1676 // TODO(timav): simplify coordinate transformations in DrawContentQuadAA
1677 // similar to the way DrawContentQuadNoAA works and then consider
1678 // combining DrawContentQuadAA and DrawContentQuadNoAA into one method.
1679 if (use_aa)
1680 DrawContentQuadAA(frame, quad, resource_id, device_transform, clip_region);
1681 else
1682 DrawContentQuadNoAA(frame, quad, resource_id, clip_region);
1685 void GLRenderer::DrawContentQuadAA(const DrawingFrame* frame,
1686 const ContentDrawQuadBase* quad,
1687 ResourceProvider::ResourceId resource_id,
1688 const gfx::Transform& device_transform,
1689 const gfx::QuadF* clip_region) {
1690 if (!device_transform.IsInvertible())
1691 return;
1693 gfx::Rect tile_rect = quad->visible_rect;
1695 gfx::RectF tex_coord_rect = MathUtil::ScaleRectProportional(
1696 quad->tex_coord_rect, quad->rect, tile_rect);
1697 float tex_to_geom_scale_x = quad->rect.width() / quad->tex_coord_rect.width();
1698 float tex_to_geom_scale_y =
1699 quad->rect.height() / quad->tex_coord_rect.height();
1701 gfx::RectF clamp_geom_rect(tile_rect);
1702 gfx::RectF clamp_tex_rect(tex_coord_rect);
1703 // Clamp texture coordinates to avoid sampling outside the layer
1704 // by deflating the tile region half a texel or half a texel
1705 // minus epsilon for one pixel layers. The resulting clamp region
1706 // is mapped to the unit square by the vertex shader and mapped
1707 // back to normalized texture coordinates by the fragment shader
1708 // after being clamped to 0-1 range.
1709 float tex_clamp_x =
1710 std::min(0.5f, 0.5f * clamp_tex_rect.width() - kAntiAliasingEpsilon);
1711 float tex_clamp_y =
1712 std::min(0.5f, 0.5f * clamp_tex_rect.height() - kAntiAliasingEpsilon);
1713 float geom_clamp_x =
1714 std::min(tex_clamp_x * tex_to_geom_scale_x,
1715 0.5f * clamp_geom_rect.width() - kAntiAliasingEpsilon);
1716 float geom_clamp_y =
1717 std::min(tex_clamp_y * tex_to_geom_scale_y,
1718 0.5f * clamp_geom_rect.height() - kAntiAliasingEpsilon);
1719 clamp_geom_rect.Inset(geom_clamp_x, geom_clamp_y, geom_clamp_x, geom_clamp_y);
1720 clamp_tex_rect.Inset(tex_clamp_x, tex_clamp_y, tex_clamp_x, tex_clamp_y);
1722 // Map clamping rectangle to unit square.
1723 float vertex_tex_translate_x = -clamp_geom_rect.x() / clamp_geom_rect.width();
1724 float vertex_tex_translate_y =
1725 -clamp_geom_rect.y() / clamp_geom_rect.height();
1726 float vertex_tex_scale_x = tile_rect.width() / clamp_geom_rect.width();
1727 float vertex_tex_scale_y = tile_rect.height() / clamp_geom_rect.height();
1729 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1730 gl_, &highp_threshold_cache_, highp_threshold_min_, quad->texture_size);
1732 gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1733 float edge[24];
1734 SetupQuadForClippingAndAntialiasing(device_transform, quad, true, clip_region,
1735 &local_quad, edge);
1736 ResourceProvider::ScopedSamplerGL quad_resource_lock(
1737 resource_provider_, resource_id,
1738 quad->nearest_neighbor ? GL_NEAREST : GL_LINEAR);
1739 SamplerType sampler =
1740 SamplerTypeFromTextureTarget(quad_resource_lock.target());
1742 float fragment_tex_translate_x = clamp_tex_rect.x();
1743 float fragment_tex_translate_y = clamp_tex_rect.y();
1744 float fragment_tex_scale_x = clamp_tex_rect.width();
1745 float fragment_tex_scale_y = clamp_tex_rect.height();
1747 // Map to normalized texture coordinates.
1748 if (sampler != SAMPLER_TYPE_2D_RECT) {
1749 gfx::Size texture_size = quad->texture_size;
1750 DCHECK(!texture_size.IsEmpty());
1751 fragment_tex_translate_x /= texture_size.width();
1752 fragment_tex_translate_y /= texture_size.height();
1753 fragment_tex_scale_x /= texture_size.width();
1754 fragment_tex_scale_y /= texture_size.height();
1757 TileProgramUniforms uniforms;
1758 if (quad->swizzle_contents) {
1759 TileUniformLocation(GetTileProgramSwizzleAA(tex_coord_precision, sampler),
1760 &uniforms);
1761 } else {
1762 TileUniformLocation(GetTileProgramAA(tex_coord_precision, sampler),
1763 &uniforms);
1766 SetUseProgram(uniforms.program);
1767 GLC(gl_, gl_->Uniform1i(uniforms.sampler_location, 0));
1769 float viewport[4] = {
1770 static_cast<float>(viewport_.x()),
1771 static_cast<float>(viewport_.y()),
1772 static_cast<float>(viewport_.width()),
1773 static_cast<float>(viewport_.height()),
1775 GLC(gl_, gl_->Uniform4fv(uniforms.viewport_location, 1, viewport));
1776 GLC(gl_, gl_->Uniform3fv(uniforms.edge_location, 8, edge));
1778 GLC(gl_,
1779 gl_->Uniform4f(uniforms.vertex_tex_transform_location,
1780 vertex_tex_translate_x,
1781 vertex_tex_translate_y,
1782 vertex_tex_scale_x,
1783 vertex_tex_scale_y));
1784 GLC(gl_,
1785 gl_->Uniform4f(uniforms.fragment_tex_transform_location,
1786 fragment_tex_translate_x,
1787 fragment_tex_translate_y,
1788 fragment_tex_scale_x,
1789 fragment_tex_scale_y));
1791 // Blending is required for antialiasing.
1792 SetBlendEnabled(true);
1794 // Normalize to tile_rect.
1795 local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1797 SetShaderOpacity(quad->opacity(), uniforms.alpha_location);
1798 SetShaderQuadF(local_quad, uniforms.quad_location);
1800 // The transform and vertex data are used to figure out the extents that the
1801 // un-antialiased quad should have and which vertex this is and the float
1802 // quad passed in via uniform is the actual geometry that gets used to draw
1803 // it. This is why this centered rect is used and not the original quad_rect.
1804 gfx::RectF centered_rect(
1805 gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1806 tile_rect.size());
1807 DrawQuadGeometry(
1808 frame, quad->quadTransform(), centered_rect, uniforms.matrix_location);
1811 void GLRenderer::DrawContentQuadNoAA(const DrawingFrame* frame,
1812 const ContentDrawQuadBase* quad,
1813 ResourceProvider::ResourceId resource_id,
1814 const gfx::QuadF* clip_region) {
1815 gfx::RectF tex_coord_rect = MathUtil::ScaleRectProportional(
1816 quad->tex_coord_rect, quad->rect, quad->visible_rect);
1817 float tex_to_geom_scale_x = quad->rect.width() / quad->tex_coord_rect.width();
1818 float tex_to_geom_scale_y =
1819 quad->rect.height() / quad->tex_coord_rect.height();
1821 bool scaled = (tex_to_geom_scale_x != 1.f || tex_to_geom_scale_y != 1.f);
1822 GLenum filter =
1823 (scaled || !quad->quadTransform().IsIdentityOrIntegerTranslation()) &&
1824 !quad->nearest_neighbor
1825 ? GL_LINEAR
1826 : GL_NEAREST;
1828 ResourceProvider::ScopedSamplerGL quad_resource_lock(
1829 resource_provider_, resource_id, filter);
1830 SamplerType sampler =
1831 SamplerTypeFromTextureTarget(quad_resource_lock.target());
1833 float vertex_tex_translate_x = tex_coord_rect.x();
1834 float vertex_tex_translate_y = tex_coord_rect.y();
1835 float vertex_tex_scale_x = tex_coord_rect.width();
1836 float vertex_tex_scale_y = tex_coord_rect.height();
1838 // Map to normalized texture coordinates.
1839 if (sampler != SAMPLER_TYPE_2D_RECT) {
1840 gfx::Size texture_size = quad->texture_size;
1841 DCHECK(!texture_size.IsEmpty());
1842 vertex_tex_translate_x /= texture_size.width();
1843 vertex_tex_translate_y /= texture_size.height();
1844 vertex_tex_scale_x /= texture_size.width();
1845 vertex_tex_scale_y /= texture_size.height();
1848 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1849 gl_, &highp_threshold_cache_, highp_threshold_min_, quad->texture_size);
1851 TileProgramUniforms uniforms;
1852 if (quad->ShouldDrawWithBlending()) {
1853 if (quad->swizzle_contents) {
1854 TileUniformLocation(GetTileProgramSwizzle(tex_coord_precision, sampler),
1855 &uniforms);
1856 } else {
1857 TileUniformLocation(GetTileProgram(tex_coord_precision, sampler),
1858 &uniforms);
1860 } else {
1861 if (quad->swizzle_contents) {
1862 TileUniformLocation(
1863 GetTileProgramSwizzleOpaque(tex_coord_precision, sampler), &uniforms);
1864 } else {
1865 TileUniformLocation(GetTileProgramOpaque(tex_coord_precision, sampler),
1866 &uniforms);
1870 SetUseProgram(uniforms.program);
1871 GLC(gl_, gl_->Uniform1i(uniforms.sampler_location, 0));
1873 GLC(gl_,
1874 gl_->Uniform4f(uniforms.vertex_tex_transform_location,
1875 vertex_tex_translate_x,
1876 vertex_tex_translate_y,
1877 vertex_tex_scale_x,
1878 vertex_tex_scale_y));
1880 SetBlendEnabled(quad->ShouldDrawWithBlending());
1882 SetShaderOpacity(quad->opacity(), uniforms.alpha_location);
1884 // Pass quad coordinates to the uniform in the same order as GeometryBinding
1885 // does, then vertices will match the texture mapping in the vertex buffer.
1886 // The method SetShaderQuadF() changes the order of vertices and so it's
1887 // not used here.
1888 gfx::QuadF tile_rect(quad->visible_rect);
1889 float width = quad->visible_rect.width();
1890 float height = quad->visible_rect.height();
1891 gfx::PointF top_left = quad->visible_rect.origin();
1892 if (clip_region) {
1893 tile_rect = *clip_region;
1894 float gl_uv[8] = {
1895 (tile_rect.p4().x() - top_left.x()) / width,
1896 (tile_rect.p4().y() - top_left.y()) / height,
1897 (tile_rect.p1().x() - top_left.x()) / width,
1898 (tile_rect.p1().y() - top_left.y()) / height,
1899 (tile_rect.p2().x() - top_left.x()) / width,
1900 (tile_rect.p2().y() - top_left.y()) / height,
1901 (tile_rect.p3().x() - top_left.x()) / width,
1902 (tile_rect.p3().y() - top_left.y()) / height,
1904 PrepareGeometry(CLIPPED_BINDING);
1905 clipped_geometry_->InitializeCustomQuadWithUVs(
1906 gfx::QuadF(quad->visible_rect), gl_uv);
1907 } else {
1908 PrepareGeometry(SHARED_BINDING);
1910 float gl_quad[8] = {
1911 tile_rect.p4().x(),
1912 tile_rect.p4().y(),
1913 tile_rect.p1().x(),
1914 tile_rect.p1().y(),
1915 tile_rect.p2().x(),
1916 tile_rect.p2().y(),
1917 tile_rect.p3().x(),
1918 tile_rect.p3().y(),
1920 GLC(gl_, gl_->Uniform2fv(uniforms.quad_location, 4, gl_quad));
1922 static float gl_matrix[16];
1923 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad->quadTransform());
1924 GLC(gl_,
1925 gl_->UniformMatrix4fv(uniforms.matrix_location, 1, false, &gl_matrix[0]));
1927 GLC(gl_, gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0));
1930 void GLRenderer::DrawYUVVideoQuad(const DrawingFrame* frame,
1931 const YUVVideoDrawQuad* quad,
1932 const gfx::QuadF* clip_region) {
1933 SetBlendEnabled(quad->ShouldDrawWithBlending());
1935 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1936 gl_,
1937 &highp_threshold_cache_,
1938 highp_threshold_min_,
1939 quad->shared_quad_state->visible_content_rect.bottom_right());
1941 bool use_alpha_plane = quad->a_plane_resource_id != 0;
1943 ResourceProvider::ScopedSamplerGL y_plane_lock(
1944 resource_provider_, quad->y_plane_resource_id, GL_TEXTURE1, GL_LINEAR);
1945 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), y_plane_lock.target());
1946 ResourceProvider::ScopedSamplerGL u_plane_lock(
1947 resource_provider_, quad->u_plane_resource_id, GL_TEXTURE2, GL_LINEAR);
1948 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), u_plane_lock.target());
1949 ResourceProvider::ScopedSamplerGL v_plane_lock(
1950 resource_provider_, quad->v_plane_resource_id, GL_TEXTURE3, GL_LINEAR);
1951 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), v_plane_lock.target());
1952 scoped_ptr<ResourceProvider::ScopedSamplerGL> a_plane_lock;
1953 if (use_alpha_plane) {
1954 a_plane_lock.reset(new ResourceProvider::ScopedSamplerGL(
1955 resource_provider_, quad->a_plane_resource_id, GL_TEXTURE4, GL_LINEAR));
1956 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), a_plane_lock->target());
1959 int matrix_location = -1;
1960 int tex_scale_location = -1;
1961 int tex_offset_location = -1;
1962 int clamp_rect_location = -1;
1963 int y_texture_location = -1;
1964 int u_texture_location = -1;
1965 int v_texture_location = -1;
1966 int a_texture_location = -1;
1967 int yuv_matrix_location = -1;
1968 int yuv_adj_location = -1;
1969 int alpha_location = -1;
1970 if (use_alpha_plane) {
1971 const VideoYUVAProgram* program = GetVideoYUVAProgram(tex_coord_precision);
1972 DCHECK(program && (program->initialized() || IsContextLost()));
1973 SetUseProgram(program->program());
1974 matrix_location = program->vertex_shader().matrix_location();
1975 tex_scale_location = program->vertex_shader().tex_scale_location();
1976 tex_offset_location = program->vertex_shader().tex_offset_location();
1977 y_texture_location = program->fragment_shader().y_texture_location();
1978 u_texture_location = program->fragment_shader().u_texture_location();
1979 v_texture_location = program->fragment_shader().v_texture_location();
1980 a_texture_location = program->fragment_shader().a_texture_location();
1981 yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
1982 yuv_adj_location = program->fragment_shader().yuv_adj_location();
1983 clamp_rect_location = program->fragment_shader().clamp_rect_location();
1984 alpha_location = program->fragment_shader().alpha_location();
1985 } else {
1986 const VideoYUVProgram* program = GetVideoYUVProgram(tex_coord_precision);
1987 DCHECK(program && (program->initialized() || IsContextLost()));
1988 SetUseProgram(program->program());
1989 matrix_location = program->vertex_shader().matrix_location();
1990 tex_scale_location = program->vertex_shader().tex_scale_location();
1991 tex_offset_location = program->vertex_shader().tex_offset_location();
1992 y_texture_location = program->fragment_shader().y_texture_location();
1993 u_texture_location = program->fragment_shader().u_texture_location();
1994 v_texture_location = program->fragment_shader().v_texture_location();
1995 yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
1996 yuv_adj_location = program->fragment_shader().yuv_adj_location();
1997 clamp_rect_location = program->fragment_shader().clamp_rect_location();
1998 alpha_location = program->fragment_shader().alpha_location();
2001 GLC(gl_,
2002 gl_->Uniform2f(tex_scale_location,
2003 quad->tex_coord_rect.width(),
2004 quad->tex_coord_rect.height()));
2005 GLC(gl_,
2006 gl_->Uniform2f(tex_offset_location,
2007 quad->tex_coord_rect.x(),
2008 quad->tex_coord_rect.y()));
2009 // Clamping to half a texel inside the tex coord rect prevents bilinear
2010 // filtering from filtering outside the tex coord rect.
2011 gfx::RectF clamp_rect(quad->tex_coord_rect);
2012 // Special case: empty texture size implies no clamping.
2013 if (!quad->tex_size.IsEmpty()) {
2014 clamp_rect.Inset(0.5f / quad->tex_size.width(),
2015 0.5f / quad->tex_size.height());
2017 GLC(gl_, gl_->Uniform4f(clamp_rect_location, clamp_rect.x(), clamp_rect.y(),
2018 clamp_rect.right(), clamp_rect.bottom()));
2020 GLC(gl_, gl_->Uniform1i(y_texture_location, 1));
2021 GLC(gl_, gl_->Uniform1i(u_texture_location, 2));
2022 GLC(gl_, gl_->Uniform1i(v_texture_location, 3));
2023 if (use_alpha_plane)
2024 GLC(gl_, gl_->Uniform1i(a_texture_location, 4));
2026 // These values are magic numbers that are used in the transformation from YUV
2027 // to RGB color values. They are taken from the following webpage:
2028 // http://www.fourcc.org/fccyvrgb.php
2029 float yuv_to_rgb_rec601[9] = {
2030 1.164f, 1.164f, 1.164f, 0.0f, -.391f, 2.018f, 1.596f, -.813f, 0.0f,
2032 float yuv_to_rgb_jpeg[9] = {
2033 1.f, 1.f, 1.f, 0.0f, -.34414f, 1.772f, 1.402f, -.71414f, 0.0f,
2035 float yuv_to_rgb_rec709[9] = {
2036 1.164f, 1.164f, 1.164f, 0.0f, -0.213f, 2.112f, 1.793f, -0.533f, 0.0f,
2039 // These values map to 16, 128, and 128 respectively, and are computed
2040 // as a fraction over 256 (e.g. 16 / 256 = 0.0625).
2041 // They are used in the YUV to RGBA conversion formula:
2042 // Y - 16 : Gives 16 values of head and footroom for overshooting
2043 // U - 128 : Turns unsigned U into signed U [-128,127]
2044 // V - 128 : Turns unsigned V into signed V [-128,127]
2045 float yuv_adjust_constrained[3] = {
2046 -0.0625f, -0.5f, -0.5f,
2049 // Same as above, but without the head and footroom.
2050 float yuv_adjust_full[3] = {
2051 0.0f, -0.5f, -0.5f,
2054 float* yuv_to_rgb = NULL;
2055 float* yuv_adjust = NULL;
2057 switch (quad->color_space) {
2058 case YUVVideoDrawQuad::REC_601:
2059 yuv_to_rgb = yuv_to_rgb_rec601;
2060 yuv_adjust = yuv_adjust_constrained;
2061 break;
2062 case YUVVideoDrawQuad::REC_709:
2063 yuv_to_rgb = yuv_to_rgb_rec709;
2064 yuv_adjust = yuv_adjust_constrained;
2065 break;
2066 case YUVVideoDrawQuad::JPEG:
2067 yuv_to_rgb = yuv_to_rgb_jpeg;
2068 yuv_adjust = yuv_adjust_full;
2069 break;
2072 // The transform and vertex data are used to figure out the extents that the
2073 // un-antialiased quad should have and which vertex this is and the float
2074 // quad passed in via uniform is the actual geometry that gets used to draw
2075 // it. This is why this centered rect is used and not the original quad_rect.
2076 gfx::RectF tile_rect = quad->rect;
2077 GLC(gl_, gl_->UniformMatrix3fv(yuv_matrix_location, 1, 0, yuv_to_rgb));
2078 GLC(gl_, gl_->Uniform3fv(yuv_adj_location, 1, yuv_adjust));
2080 SetShaderOpacity(quad->opacity(), alpha_location);
2081 if (!clip_region) {
2082 DrawQuadGeometry(frame, quad->quadTransform(), tile_rect, matrix_location);
2083 } else {
2084 float uvs[8] = {0};
2085 GetScaledUVs(quad->visible_rect, clip_region, uvs);
2086 gfx::QuadF region_quad = *clip_region;
2087 region_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
2088 region_quad -= gfx::Vector2dF(0.5f, 0.5f);
2089 DrawQuadGeometryClippedByQuadF(frame, quad->quadTransform(), tile_rect,
2090 region_quad, matrix_location, uvs);
2094 void GLRenderer::DrawStreamVideoQuad(const DrawingFrame* frame,
2095 const StreamVideoDrawQuad* quad,
2096 const gfx::QuadF* clip_region) {
2097 SetBlendEnabled(quad->ShouldDrawWithBlending());
2099 static float gl_matrix[16];
2101 DCHECK(capabilities_.using_egl_image);
2103 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2104 gl_,
2105 &highp_threshold_cache_,
2106 highp_threshold_min_,
2107 quad->shared_quad_state->visible_content_rect.bottom_right());
2109 const VideoStreamTextureProgram* program =
2110 GetVideoStreamTextureProgram(tex_coord_precision);
2111 SetUseProgram(program->program());
2113 ToGLMatrix(&gl_matrix[0], quad->matrix);
2114 GLC(gl_,
2115 gl_->UniformMatrix4fv(
2116 program->vertex_shader().tex_matrix_location(), 1, false, gl_matrix));
2118 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
2119 quad->resource_id);
2120 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2121 GLC(gl_, gl_->BindTexture(GL_TEXTURE_EXTERNAL_OES, lock.texture_id()));
2123 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
2125 SetShaderOpacity(quad->opacity(),
2126 program->fragment_shader().alpha_location());
2127 if (!clip_region) {
2128 DrawQuadGeometry(frame, quad->quadTransform(), quad->rect,
2129 program->vertex_shader().matrix_location());
2130 } else {
2131 gfx::QuadF region_quad(*clip_region);
2132 region_quad.Scale(1.0f / quad->rect.width(), 1.0f / quad->rect.height());
2133 region_quad -= gfx::Vector2dF(0.5f, 0.5f);
2134 float uvs[8] = {0};
2135 GetScaledUVs(quad->visible_rect, clip_region, uvs);
2136 DrawQuadGeometryClippedByQuadF(
2137 frame, quad->quadTransform(), quad->rect, region_quad,
2138 program->vertex_shader().matrix_location(), uvs);
2142 struct TextureProgramBinding {
2143 template <class Program>
2144 void Set(Program* program) {
2145 DCHECK(program);
2146 program_id = program->program();
2147 sampler_location = program->fragment_shader().sampler_location();
2148 matrix_location = program->vertex_shader().matrix_location();
2149 background_color_location =
2150 program->fragment_shader().background_color_location();
2152 int program_id;
2153 int sampler_location;
2154 int matrix_location;
2155 int transform_location;
2156 int background_color_location;
2159 struct TexTransformTextureProgramBinding : TextureProgramBinding {
2160 template <class Program>
2161 void Set(Program* program) {
2162 TextureProgramBinding::Set(program);
2163 tex_transform_location = program->vertex_shader().tex_transform_location();
2164 vertex_opacity_location =
2165 program->vertex_shader().vertex_opacity_location();
2167 int tex_transform_location;
2168 int vertex_opacity_location;
2171 void GLRenderer::FlushTextureQuadCache(BoundGeometry flush_binding) {
2172 // Check to see if we have anything to draw.
2173 if (draw_cache_.program_id == -1)
2174 return;
2176 PrepareGeometry(flush_binding);
2178 // Set the correct blending mode.
2179 SetBlendEnabled(draw_cache_.needs_blending);
2181 // Bind the program to the GL state.
2182 SetUseProgram(draw_cache_.program_id);
2184 // Bind the correct texture sampler location.
2185 GLC(gl_, gl_->Uniform1i(draw_cache_.sampler_location, 0));
2187 // Assume the current active textures is 0.
2188 ResourceProvider::ScopedSamplerGL locked_quad(
2189 resource_provider_,
2190 draw_cache_.resource_id,
2191 draw_cache_.nearest_neighbor ? GL_NEAREST : GL_LINEAR);
2192 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2193 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, locked_quad.texture_id()));
2195 static_assert(sizeof(Float4) == 4 * sizeof(float),
2196 "Float4 struct should be densely packed");
2197 static_assert(sizeof(Float16) == 16 * sizeof(float),
2198 "Float16 struct should be densely packed");
2200 // Upload the tranforms for both points and uvs.
2201 GLC(gl_,
2202 gl_->UniformMatrix4fv(
2203 static_cast<int>(draw_cache_.matrix_location),
2204 static_cast<int>(draw_cache_.matrix_data.size()),
2205 false,
2206 reinterpret_cast<float*>(&draw_cache_.matrix_data.front())));
2207 GLC(gl_,
2208 gl_->Uniform4fv(
2209 static_cast<int>(draw_cache_.uv_xform_location),
2210 static_cast<int>(draw_cache_.uv_xform_data.size()),
2211 reinterpret_cast<float*>(&draw_cache_.uv_xform_data.front())));
2213 if (draw_cache_.background_color != SK_ColorTRANSPARENT) {
2214 Float4 background_color = PremultipliedColor(draw_cache_.background_color);
2215 GLC(gl_,
2216 gl_->Uniform4fv(
2217 draw_cache_.background_color_location, 1, background_color.data));
2220 GLC(gl_,
2221 gl_->Uniform1fv(
2222 static_cast<int>(draw_cache_.vertex_opacity_location),
2223 static_cast<int>(draw_cache_.vertex_opacity_data.size()),
2224 static_cast<float*>(&draw_cache_.vertex_opacity_data.front())));
2226 // Draw the quads!
2227 GLC(gl_,
2228 gl_->DrawElements(GL_TRIANGLES,
2229 6 * draw_cache_.matrix_data.size(),
2230 GL_UNSIGNED_SHORT,
2231 0));
2233 // Clear the cache.
2234 draw_cache_.program_id = -1;
2235 draw_cache_.uv_xform_data.resize(0);
2236 draw_cache_.vertex_opacity_data.resize(0);
2237 draw_cache_.matrix_data.resize(0);
2239 // If we had a clipped binding, prepare the shared binding for the
2240 // next inserts.
2241 if (flush_binding == CLIPPED_BINDING) {
2242 PrepareGeometry(SHARED_BINDING);
2246 void GLRenderer::EnqueueTextureQuad(const DrawingFrame* frame,
2247 const TextureDrawQuad* quad,
2248 const gfx::QuadF* clip_region) {
2249 // If we have a clip_region then we have to render the next quad
2250 // with dynamic geometry, therefore we must flush all pending
2251 // texture quads.
2252 if (clip_region) {
2253 // We send in false here because we want to flush what's currently in the
2254 // queue using the shared_geometry and not clipped_geometry
2255 FlushTextureQuadCache(SHARED_BINDING);
2258 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2259 gl_,
2260 &highp_threshold_cache_,
2261 highp_threshold_min_,
2262 quad->shared_quad_state->visible_content_rect.bottom_right());
2264 // Choose the correct texture program binding
2265 TexTransformTextureProgramBinding binding;
2266 if (quad->premultiplied_alpha) {
2267 if (quad->background_color == SK_ColorTRANSPARENT) {
2268 binding.Set(GetTextureProgram(tex_coord_precision));
2269 } else {
2270 binding.Set(GetTextureBackgroundProgram(tex_coord_precision));
2272 } else {
2273 if (quad->background_color == SK_ColorTRANSPARENT) {
2274 binding.Set(GetNonPremultipliedTextureProgram(tex_coord_precision));
2275 } else {
2276 binding.Set(
2277 GetNonPremultipliedTextureBackgroundProgram(tex_coord_precision));
2281 int resource_id = quad->resource_id;
2283 if (draw_cache_.program_id != binding.program_id ||
2284 draw_cache_.resource_id != resource_id ||
2285 draw_cache_.needs_blending != quad->ShouldDrawWithBlending() ||
2286 draw_cache_.nearest_neighbor != quad->nearest_neighbor ||
2287 draw_cache_.background_color != quad->background_color ||
2288 draw_cache_.matrix_data.size() >= 8) {
2289 FlushTextureQuadCache(SHARED_BINDING);
2290 draw_cache_.program_id = binding.program_id;
2291 draw_cache_.resource_id = resource_id;
2292 draw_cache_.needs_blending = quad->ShouldDrawWithBlending();
2293 draw_cache_.nearest_neighbor = quad->nearest_neighbor;
2294 draw_cache_.background_color = quad->background_color;
2296 draw_cache_.uv_xform_location = binding.tex_transform_location;
2297 draw_cache_.background_color_location = binding.background_color_location;
2298 draw_cache_.vertex_opacity_location = binding.vertex_opacity_location;
2299 draw_cache_.matrix_location = binding.matrix_location;
2300 draw_cache_.sampler_location = binding.sampler_location;
2303 // Generate the uv-transform
2304 if (!clip_region) {
2305 draw_cache_.uv_xform_data.push_back(UVTransform(quad));
2306 } else {
2307 Float4 uv_transform = {{0.0f, 0.0f, 1.0f, 1.0f}};
2308 draw_cache_.uv_xform_data.push_back(uv_transform);
2311 // Generate the vertex opacity
2312 const float opacity = quad->opacity();
2313 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[0] * opacity);
2314 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[1] * opacity);
2315 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[2] * opacity);
2316 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[3] * opacity);
2318 // Generate the transform matrix
2319 gfx::Transform quad_rect_matrix;
2320 QuadRectTransform(&quad_rect_matrix, quad->quadTransform(), quad->rect);
2321 quad_rect_matrix = frame->projection_matrix * quad_rect_matrix;
2323 Float16 m;
2324 quad_rect_matrix.matrix().asColMajorf(m.data);
2325 draw_cache_.matrix_data.push_back(m);
2327 if (clip_region) {
2328 gfx::QuadF scaled_region;
2329 if (!GetScaledRegion(quad->rect, clip_region, &scaled_region)) {
2330 scaled_region = SharedGeometryQuad().BoundingBox();
2332 // Both the scaled region and the SharedGeomtryQuad are in the space
2333 // -0.5->0.5. We need to move that to the space 0->1.
2334 float uv[8];
2335 uv[0] = scaled_region.p1().x() + 0.5f;
2336 uv[1] = scaled_region.p1().y() + 0.5f;
2337 uv[2] = scaled_region.p2().x() + 0.5f;
2338 uv[3] = scaled_region.p2().y() + 0.5f;
2339 uv[4] = scaled_region.p3().x() + 0.5f;
2340 uv[5] = scaled_region.p3().y() + 0.5f;
2341 uv[6] = scaled_region.p4().x() + 0.5f;
2342 uv[7] = scaled_region.p4().y() + 0.5f;
2343 PrepareGeometry(CLIPPED_BINDING);
2344 clipped_geometry_->InitializeCustomQuadWithUVs(scaled_region, uv);
2345 FlushTextureQuadCache(CLIPPED_BINDING);
2349 void GLRenderer::DrawIOSurfaceQuad(const DrawingFrame* frame,
2350 const IOSurfaceDrawQuad* quad,
2351 const gfx::QuadF* clip_region) {
2352 SetBlendEnabled(quad->ShouldDrawWithBlending());
2354 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2355 gl_,
2356 &highp_threshold_cache_,
2357 highp_threshold_min_,
2358 quad->shared_quad_state->visible_content_rect.bottom_right());
2360 TexTransformTextureProgramBinding binding;
2361 binding.Set(GetTextureIOSurfaceProgram(tex_coord_precision));
2363 SetUseProgram(binding.program_id);
2364 GLC(gl_, gl_->Uniform1i(binding.sampler_location, 0));
2365 if (quad->orientation == IOSurfaceDrawQuad::FLIPPED) {
2366 GLC(gl_,
2367 gl_->Uniform4f(binding.tex_transform_location,
2369 quad->io_surface_size.height(),
2370 quad->io_surface_size.width(),
2371 quad->io_surface_size.height() * -1.0f));
2372 } else {
2373 GLC(gl_,
2374 gl_->Uniform4f(binding.tex_transform_location,
2377 quad->io_surface_size.width(),
2378 quad->io_surface_size.height()));
2381 const float vertex_opacity[] = {quad->opacity(), quad->opacity(),
2382 quad->opacity(), quad->opacity()};
2383 GLC(gl_, gl_->Uniform1fv(binding.vertex_opacity_location, 4, vertex_opacity));
2385 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
2386 quad->io_surface_resource_id);
2387 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2388 GLC(gl_, gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, lock.texture_id()));
2390 if (!clip_region) {
2391 DrawQuadGeometry(frame, quad->quadTransform(), quad->rect,
2392 binding.matrix_location);
2393 } else {
2394 float uvs[8] = {0};
2395 GetScaledUVs(quad->visible_rect, clip_region, uvs);
2396 DrawQuadGeometryClippedByQuadF(frame, quad->quadTransform(), quad->rect,
2397 *clip_region, binding.matrix_location, uvs);
2400 GLC(gl_, gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, 0));
2403 void GLRenderer::FinishDrawingFrame(DrawingFrame* frame) {
2404 if (use_sync_query_) {
2405 DCHECK(current_sync_query_);
2406 current_sync_query_->End();
2407 pending_sync_queries_.push_back(current_sync_query_.Pass());
2410 current_framebuffer_lock_ = nullptr;
2411 swap_buffer_rect_.Union(gfx::ToEnclosingRect(frame->root_damage_rect));
2413 GLC(gl_, gl_->Disable(GL_BLEND));
2414 blend_shadow_ = false;
2416 ScheduleOverlays(frame);
2419 void GLRenderer::FinishDrawingQuadList() {
2420 FlushTextureQuadCache(SHARED_BINDING);
2423 bool GLRenderer::FlippedFramebuffer(const DrawingFrame* frame) const {
2424 if (frame->current_render_pass != frame->root_render_pass)
2425 return true;
2426 return FlippedRootFramebuffer();
2429 bool GLRenderer::FlippedRootFramebuffer() const {
2430 // GL is normally flipped, so a flipped output results in an unflipping.
2431 return !output_surface_->capabilities().flipped_output_surface;
2434 void GLRenderer::EnsureScissorTestEnabled() {
2435 if (is_scissor_enabled_)
2436 return;
2438 FlushTextureQuadCache(SHARED_BINDING);
2439 GLC(gl_, gl_->Enable(GL_SCISSOR_TEST));
2440 is_scissor_enabled_ = true;
2443 void GLRenderer::EnsureScissorTestDisabled() {
2444 if (!is_scissor_enabled_)
2445 return;
2447 FlushTextureQuadCache(SHARED_BINDING);
2448 GLC(gl_, gl_->Disable(GL_SCISSOR_TEST));
2449 is_scissor_enabled_ = false;
2452 void GLRenderer::CopyCurrentRenderPassToBitmap(
2453 DrawingFrame* frame,
2454 scoped_ptr<CopyOutputRequest> request) {
2455 TRACE_EVENT0("cc", "GLRenderer::CopyCurrentRenderPassToBitmap");
2456 gfx::Rect copy_rect = frame->current_render_pass->output_rect;
2457 if (request->has_area())
2458 copy_rect.Intersect(request->area());
2459 GetFramebufferPixelsAsync(frame, copy_rect, request.Pass());
2462 void GLRenderer::ToGLMatrix(float* gl_matrix, const gfx::Transform& transform) {
2463 transform.matrix().asColMajorf(gl_matrix);
2466 void GLRenderer::SetShaderQuadF(const gfx::QuadF& quad, int quad_location) {
2467 if (quad_location == -1)
2468 return;
2470 float gl_quad[8];
2471 gl_quad[0] = quad.p1().x();
2472 gl_quad[1] = quad.p1().y();
2473 gl_quad[2] = quad.p2().x();
2474 gl_quad[3] = quad.p2().y();
2475 gl_quad[4] = quad.p3().x();
2476 gl_quad[5] = quad.p3().y();
2477 gl_quad[6] = quad.p4().x();
2478 gl_quad[7] = quad.p4().y();
2479 GLC(gl_, gl_->Uniform2fv(quad_location, 4, gl_quad));
2482 void GLRenderer::SetShaderOpacity(float opacity, int alpha_location) {
2483 if (alpha_location != -1)
2484 GLC(gl_, gl_->Uniform1f(alpha_location, opacity));
2487 void GLRenderer::SetStencilEnabled(bool enabled) {
2488 if (enabled == stencil_shadow_)
2489 return;
2491 if (enabled)
2492 GLC(gl_, gl_->Enable(GL_STENCIL_TEST));
2493 else
2494 GLC(gl_, gl_->Disable(GL_STENCIL_TEST));
2495 stencil_shadow_ = enabled;
2498 void GLRenderer::SetBlendEnabled(bool enabled) {
2499 if (enabled == blend_shadow_)
2500 return;
2502 if (enabled)
2503 GLC(gl_, gl_->Enable(GL_BLEND));
2504 else
2505 GLC(gl_, gl_->Disable(GL_BLEND));
2506 blend_shadow_ = enabled;
2509 void GLRenderer::SetUseProgram(unsigned program) {
2510 if (program == program_shadow_)
2511 return;
2512 gl_->UseProgram(program);
2513 program_shadow_ = program;
2516 void GLRenderer::DrawQuadGeometryClippedByQuadF(
2517 const DrawingFrame* frame,
2518 const gfx::Transform& draw_transform,
2519 const gfx::RectF& quad_rect,
2520 const gfx::QuadF& clipping_region_quad,
2521 int matrix_location,
2522 const float* uvs) {
2523 PrepareGeometry(CLIPPED_BINDING);
2524 if (uvs) {
2525 clipped_geometry_->InitializeCustomQuadWithUVs(clipping_region_quad, uvs);
2526 } else {
2527 clipped_geometry_->InitializeCustomQuad(clipping_region_quad);
2529 gfx::Transform quad_rect_matrix;
2530 QuadRectTransform(&quad_rect_matrix, draw_transform, quad_rect);
2531 static float gl_matrix[16];
2532 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad_rect_matrix);
2533 GLC(gl_, gl_->UniformMatrix4fv(matrix_location, 1, false, &gl_matrix[0]));
2535 GLC(gl_, gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT,
2536 reinterpret_cast<const void*>(0)));
2539 void GLRenderer::DrawQuadGeometry(const DrawingFrame* frame,
2540 const gfx::Transform& draw_transform,
2541 const gfx::RectF& quad_rect,
2542 int matrix_location) {
2543 PrepareGeometry(SHARED_BINDING);
2544 gfx::Transform quad_rect_matrix;
2545 QuadRectTransform(&quad_rect_matrix, draw_transform, quad_rect);
2546 static float gl_matrix[16];
2547 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad_rect_matrix);
2548 GLC(gl_, gl_->UniformMatrix4fv(matrix_location, 1, false, &gl_matrix[0]));
2550 GLC(gl_, gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0));
2553 void GLRenderer::Finish() {
2554 TRACE_EVENT0("cc", "GLRenderer::Finish");
2555 GLC(gl_, gl_->Finish());
2558 void GLRenderer::SwapBuffers(const CompositorFrameMetadata& metadata) {
2559 DCHECK(!is_backbuffer_discarded_);
2561 TRACE_EVENT0("cc,benchmark", "GLRenderer::SwapBuffers");
2562 // We're done! Time to swapbuffers!
2564 gfx::Size surface_size = output_surface_->SurfaceSize();
2566 CompositorFrame compositor_frame;
2567 compositor_frame.metadata = metadata;
2568 compositor_frame.gl_frame_data = make_scoped_ptr(new GLFrameData);
2569 compositor_frame.gl_frame_data->size = surface_size;
2570 if (capabilities_.using_partial_swap) {
2571 // If supported, we can save significant bandwidth by only swapping the
2572 // damaged/scissored region (clamped to the viewport).
2573 swap_buffer_rect_.Intersect(gfx::Rect(surface_size));
2574 int flipped_y_pos_of_rect_bottom = surface_size.height() -
2575 swap_buffer_rect_.y() -
2576 swap_buffer_rect_.height();
2577 compositor_frame.gl_frame_data->sub_buffer_rect =
2578 gfx::Rect(swap_buffer_rect_.x(),
2579 FlippedRootFramebuffer() ? flipped_y_pos_of_rect_bottom
2580 : swap_buffer_rect_.y(),
2581 swap_buffer_rect_.width(),
2582 swap_buffer_rect_.height());
2583 } else {
2584 compositor_frame.gl_frame_data->sub_buffer_rect =
2585 gfx::Rect(output_surface_->SurfaceSize());
2587 output_surface_->SwapBuffers(&compositor_frame);
2589 // Release previously used overlay resources and hold onto the pending ones
2590 // until the next swap buffers.
2591 in_use_overlay_resources_.clear();
2592 in_use_overlay_resources_.swap(pending_overlay_resources_);
2594 swap_buffer_rect_ = gfx::Rect();
2597 void GLRenderer::EnforceMemoryPolicy() {
2598 if (!visible()) {
2599 TRACE_EVENT0("cc", "GLRenderer::EnforceMemoryPolicy dropping resources");
2600 ReleaseRenderPassTextures();
2601 DiscardBackbuffer();
2602 resource_provider_->ReleaseCachedData();
2603 output_surface_->context_provider()->DeleteCachedResources();
2604 GLC(gl_, gl_->Flush());
2606 PrepareGeometry(NO_BINDING);
2609 void GLRenderer::DiscardBackbuffer() {
2610 if (is_backbuffer_discarded_)
2611 return;
2613 output_surface_->DiscardBackbuffer();
2615 is_backbuffer_discarded_ = true;
2617 // Damage tracker needs a full reset every time framebuffer is discarded.
2618 client_->SetFullRootLayerDamage();
2621 void GLRenderer::EnsureBackbuffer() {
2622 if (!is_backbuffer_discarded_)
2623 return;
2625 output_surface_->EnsureBackbuffer();
2626 is_backbuffer_discarded_ = false;
2629 void GLRenderer::GetFramebufferPixelsAsync(
2630 const DrawingFrame* frame,
2631 const gfx::Rect& rect,
2632 scoped_ptr<CopyOutputRequest> request) {
2633 DCHECK(!request->IsEmpty());
2634 if (request->IsEmpty())
2635 return;
2636 if (rect.IsEmpty())
2637 return;
2639 gfx::Rect window_rect = MoveFromDrawToWindowSpace(frame, rect);
2640 DCHECK_GE(window_rect.x(), 0);
2641 DCHECK_GE(window_rect.y(), 0);
2642 DCHECK_LE(window_rect.right(), current_surface_size_.width());
2643 DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2645 if (!request->force_bitmap_result()) {
2646 bool own_mailbox = !request->has_texture_mailbox();
2648 GLuint texture_id = 0;
2649 gpu::Mailbox mailbox;
2650 if (own_mailbox) {
2651 GLC(gl_, gl_->GenMailboxCHROMIUM(mailbox.name));
2652 gl_->GenTextures(1, &texture_id);
2653 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, texture_id));
2655 GLC(gl_,
2656 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
2657 GLC(gl_,
2658 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
2659 GLC(gl_,
2660 gl_->TexParameteri(
2661 GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
2662 GLC(gl_,
2663 gl_->TexParameteri(
2664 GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
2665 GLC(gl_, gl_->ProduceTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name));
2666 } else {
2667 mailbox = request->texture_mailbox().mailbox();
2668 DCHECK_EQ(static_cast<unsigned>(GL_TEXTURE_2D),
2669 request->texture_mailbox().target());
2670 DCHECK(!mailbox.IsZero());
2671 unsigned incoming_sync_point = request->texture_mailbox().sync_point();
2672 if (incoming_sync_point)
2673 GLC(gl_, gl_->WaitSyncPointCHROMIUM(incoming_sync_point));
2675 texture_id = GLC(
2676 gl_,
2677 gl_->CreateAndConsumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name));
2679 GetFramebufferTexture(texture_id, RGBA_8888, window_rect);
2681 unsigned sync_point = gl_->InsertSyncPointCHROMIUM();
2682 TextureMailbox texture_mailbox(mailbox, GL_TEXTURE_2D, sync_point);
2684 scoped_ptr<SingleReleaseCallback> release_callback;
2685 if (own_mailbox) {
2686 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, 0));
2687 release_callback = texture_mailbox_deleter_->GetReleaseCallback(
2688 output_surface_->context_provider(), texture_id);
2689 } else {
2690 gl_->DeleteTextures(1, &texture_id);
2693 request->SendTextureResult(
2694 window_rect.size(), texture_mailbox, release_callback.Pass());
2695 return;
2698 DCHECK(request->force_bitmap_result());
2700 scoped_ptr<PendingAsyncReadPixels> pending_read(new PendingAsyncReadPixels);
2701 pending_read->copy_request = request.Pass();
2702 pending_async_read_pixels_.insert(pending_async_read_pixels_.begin(),
2703 pending_read.Pass());
2705 bool do_workaround = NeedsIOSurfaceReadbackWorkaround();
2707 unsigned temporary_texture = 0;
2708 unsigned temporary_fbo = 0;
2710 if (do_workaround) {
2711 // On Mac OS X, calling glReadPixels() against an FBO whose color attachment
2712 // is an IOSurface-backed texture causes corruption of future glReadPixels()
2713 // calls, even those on different OpenGL contexts. It is believed that this
2714 // is the root cause of top crasher
2715 // http://crbug.com/99393. <rdar://problem/10949687>
2717 gl_->GenTextures(1, &temporary_texture);
2718 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, temporary_texture));
2719 GLC(gl_,
2720 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
2721 GLC(gl_,
2722 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
2723 GLC(gl_,
2724 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
2725 GLC(gl_,
2726 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
2727 // Copy the contents of the current (IOSurface-backed) framebuffer into a
2728 // temporary texture.
2729 GetFramebufferTexture(
2730 temporary_texture, RGBA_8888, gfx::Rect(current_surface_size_));
2731 gl_->GenFramebuffers(1, &temporary_fbo);
2732 // Attach this texture to an FBO, and perform the readback from that FBO.
2733 GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, temporary_fbo));
2734 GLC(gl_,
2735 gl_->FramebufferTexture2D(GL_FRAMEBUFFER,
2736 GL_COLOR_ATTACHMENT0,
2737 GL_TEXTURE_2D,
2738 temporary_texture,
2739 0));
2741 DCHECK_EQ(static_cast<unsigned>(GL_FRAMEBUFFER_COMPLETE),
2742 gl_->CheckFramebufferStatus(GL_FRAMEBUFFER));
2745 GLuint buffer = 0;
2746 gl_->GenBuffers(1, &buffer);
2747 GLC(gl_, gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, buffer));
2748 GLC(gl_,
2749 gl_->BufferData(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM,
2750 4 * window_rect.size().GetArea(),
2751 NULL,
2752 GL_STREAM_READ));
2754 GLuint query = 0;
2755 gl_->GenQueriesEXT(1, &query);
2756 GLC(gl_, gl_->BeginQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM, query));
2758 GLC(gl_,
2759 gl_->ReadPixels(window_rect.x(),
2760 window_rect.y(),
2761 window_rect.width(),
2762 window_rect.height(),
2763 GL_RGBA,
2764 GL_UNSIGNED_BYTE,
2765 NULL));
2767 GLC(gl_, gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0));
2769 if (do_workaround) {
2770 // Clean up.
2771 GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, 0));
2772 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, 0));
2773 GLC(gl_, gl_->DeleteFramebuffers(1, &temporary_fbo));
2774 GLC(gl_, gl_->DeleteTextures(1, &temporary_texture));
2777 base::Closure finished_callback = base::Bind(&GLRenderer::FinishedReadback,
2778 base::Unretained(this),
2779 buffer,
2780 query,
2781 window_rect.size());
2782 // Save the finished_callback so it can be cancelled.
2783 pending_async_read_pixels_.front()->finished_read_pixels_callback.Reset(
2784 finished_callback);
2785 base::Closure cancelable_callback =
2786 pending_async_read_pixels_.front()->
2787 finished_read_pixels_callback.callback();
2789 // Save the buffer to verify the callbacks happen in the expected order.
2790 pending_async_read_pixels_.front()->buffer = buffer;
2792 GLC(gl_, gl_->EndQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM));
2793 context_support_->SignalQuery(query, cancelable_callback);
2795 EnforceMemoryPolicy();
2798 void GLRenderer::FinishedReadback(unsigned source_buffer,
2799 unsigned query,
2800 const gfx::Size& size) {
2801 DCHECK(!pending_async_read_pixels_.empty());
2803 if (query != 0) {
2804 GLC(gl_, gl_->DeleteQueriesEXT(1, &query));
2807 PendingAsyncReadPixels* current_read = pending_async_read_pixels_.back();
2808 // Make sure we service the readbacks in order.
2809 DCHECK_EQ(source_buffer, current_read->buffer);
2811 uint8* src_pixels = NULL;
2812 scoped_ptr<SkBitmap> bitmap;
2814 if (source_buffer != 0) {
2815 GLC(gl_,
2816 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, source_buffer));
2817 src_pixels = static_cast<uint8*>(gl_->MapBufferCHROMIUM(
2818 GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, GL_READ_ONLY));
2820 if (src_pixels) {
2821 bitmap.reset(new SkBitmap);
2822 bitmap->allocN32Pixels(size.width(), size.height());
2823 scoped_ptr<SkAutoLockPixels> lock(new SkAutoLockPixels(*bitmap));
2824 uint8* dest_pixels = static_cast<uint8*>(bitmap->getPixels());
2826 size_t row_bytes = size.width() * 4;
2827 int num_rows = size.height();
2828 size_t total_bytes = num_rows * row_bytes;
2829 for (size_t dest_y = 0; dest_y < total_bytes; dest_y += row_bytes) {
2830 // Flip Y axis.
2831 size_t src_y = total_bytes - dest_y - row_bytes;
2832 // Swizzle OpenGL -> Skia byte order.
2833 for (size_t x = 0; x < row_bytes; x += 4) {
2834 dest_pixels[dest_y + x + SK_R32_SHIFT / 8] =
2835 src_pixels[src_y + x + 0];
2836 dest_pixels[dest_y + x + SK_G32_SHIFT / 8] =
2837 src_pixels[src_y + x + 1];
2838 dest_pixels[dest_y + x + SK_B32_SHIFT / 8] =
2839 src_pixels[src_y + x + 2];
2840 dest_pixels[dest_y + x + SK_A32_SHIFT / 8] =
2841 src_pixels[src_y + x + 3];
2845 GLC(gl_,
2846 gl_->UnmapBufferCHROMIUM(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM));
2848 GLC(gl_, gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0));
2849 GLC(gl_, gl_->DeleteBuffers(1, &source_buffer));
2852 if (bitmap)
2853 current_read->copy_request->SendBitmapResult(bitmap.Pass());
2854 pending_async_read_pixels_.pop_back();
2857 void GLRenderer::GetFramebufferTexture(unsigned texture_id,
2858 ResourceFormat texture_format,
2859 const gfx::Rect& window_rect) {
2860 DCHECK(texture_id);
2861 DCHECK_GE(window_rect.x(), 0);
2862 DCHECK_GE(window_rect.y(), 0);
2863 DCHECK_LE(window_rect.right(), current_surface_size_.width());
2864 DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2866 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, texture_id));
2867 GLC(gl_,
2868 gl_->CopyTexImage2D(GL_TEXTURE_2D,
2870 GLDataFormat(texture_format),
2871 window_rect.x(),
2872 window_rect.y(),
2873 window_rect.width(),
2874 window_rect.height(),
2875 0));
2876 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, 0));
2879 bool GLRenderer::UseScopedTexture(DrawingFrame* frame,
2880 const ScopedResource* texture,
2881 const gfx::Rect& viewport_rect) {
2882 DCHECK(texture->id());
2883 frame->current_render_pass = NULL;
2884 frame->current_texture = texture;
2886 return BindFramebufferToTexture(frame, texture, viewport_rect);
2889 void GLRenderer::BindFramebufferToOutputSurface(DrawingFrame* frame) {
2890 current_framebuffer_lock_ = nullptr;
2891 output_surface_->BindFramebuffer();
2893 if (output_surface_->HasExternalStencilTest()) {
2894 SetStencilEnabled(true);
2895 GLC(gl_, gl_->StencilFunc(GL_EQUAL, 1, 1));
2896 } else {
2897 SetStencilEnabled(false);
2901 bool GLRenderer::BindFramebufferToTexture(DrawingFrame* frame,
2902 const ScopedResource* texture,
2903 const gfx::Rect& target_rect) {
2904 DCHECK(texture->id());
2906 // Explicitly release lock, otherwise we can crash when try to lock
2907 // same texture again.
2908 current_framebuffer_lock_ = nullptr;
2910 SetStencilEnabled(false);
2911 GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, offscreen_framebuffer_id_));
2912 current_framebuffer_lock_ =
2913 make_scoped_ptr(new ResourceProvider::ScopedWriteLockGL(
2914 resource_provider_, texture->id()));
2915 unsigned texture_id = current_framebuffer_lock_->texture_id();
2916 GLC(gl_,
2917 gl_->FramebufferTexture2D(
2918 GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_id, 0));
2920 DCHECK(gl_->CheckFramebufferStatus(GL_FRAMEBUFFER) ==
2921 GL_FRAMEBUFFER_COMPLETE ||
2922 IsContextLost());
2924 InitializeViewport(
2925 frame, target_rect, gfx::Rect(target_rect.size()), target_rect.size());
2926 return true;
2929 void GLRenderer::SetScissorTestRect(const gfx::Rect& scissor_rect) {
2930 EnsureScissorTestEnabled();
2932 // Don't unnecessarily ask the context to change the scissor, because it
2933 // may cause undesired GPU pipeline flushes.
2934 if (scissor_rect == scissor_rect_ && !scissor_rect_needs_reset_)
2935 return;
2937 scissor_rect_ = scissor_rect;
2938 FlushTextureQuadCache(SHARED_BINDING);
2939 GLC(gl_,
2940 gl_->Scissor(scissor_rect.x(),
2941 scissor_rect.y(),
2942 scissor_rect.width(),
2943 scissor_rect.height()));
2945 scissor_rect_needs_reset_ = false;
2948 void GLRenderer::SetDrawViewport(const gfx::Rect& window_space_viewport) {
2949 viewport_ = window_space_viewport;
2950 GLC(gl_,
2951 gl_->Viewport(window_space_viewport.x(),
2952 window_space_viewport.y(),
2953 window_space_viewport.width(),
2954 window_space_viewport.height()));
2957 void GLRenderer::InitializeSharedObjects() {
2958 TRACE_EVENT0("cc", "GLRenderer::InitializeSharedObjects");
2960 // Create an FBO for doing offscreen rendering.
2961 GLC(gl_, gl_->GenFramebuffers(1, &offscreen_framebuffer_id_));
2963 shared_geometry_ =
2964 make_scoped_ptr(new StaticGeometryBinding(gl_, QuadVertexRect()));
2965 clipped_geometry_ = make_scoped_ptr(new DynamicGeometryBinding(gl_));
2968 void GLRenderer::PrepareGeometry(BoundGeometry binding) {
2969 if (binding == bound_geometry_) {
2970 return;
2973 switch (binding) {
2974 case SHARED_BINDING:
2975 shared_geometry_->PrepareForDraw();
2976 break;
2977 case CLIPPED_BINDING:
2978 clipped_geometry_->PrepareForDraw();
2979 break;
2980 case NO_BINDING:
2981 break;
2983 bound_geometry_ = binding;
2986 const GLRenderer::TileCheckerboardProgram*
2987 GLRenderer::GetTileCheckerboardProgram() {
2988 if (!tile_checkerboard_program_.initialized()) {
2989 TRACE_EVENT0("cc", "GLRenderer::checkerboardProgram::initalize");
2990 tile_checkerboard_program_.Initialize(output_surface_->context_provider(),
2991 TEX_COORD_PRECISION_NA,
2992 SAMPLER_TYPE_NA);
2994 return &tile_checkerboard_program_;
2997 const GLRenderer::DebugBorderProgram* GLRenderer::GetDebugBorderProgram() {
2998 if (!debug_border_program_.initialized()) {
2999 TRACE_EVENT0("cc", "GLRenderer::debugBorderProgram::initialize");
3000 debug_border_program_.Initialize(output_surface_->context_provider(),
3001 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
3003 return &debug_border_program_;
3006 const GLRenderer::SolidColorProgram* GLRenderer::GetSolidColorProgram() {
3007 if (!solid_color_program_.initialized()) {
3008 TRACE_EVENT0("cc", "GLRenderer::solidColorProgram::initialize");
3009 solid_color_program_.Initialize(output_surface_->context_provider(),
3010 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
3012 return &solid_color_program_;
3015 const GLRenderer::SolidColorProgramAA* GLRenderer::GetSolidColorProgramAA() {
3016 if (!solid_color_program_aa_.initialized()) {
3017 TRACE_EVENT0("cc", "GLRenderer::solidColorProgramAA::initialize");
3018 solid_color_program_aa_.Initialize(output_surface_->context_provider(),
3019 TEX_COORD_PRECISION_NA, SAMPLER_TYPE_NA);
3021 return &solid_color_program_aa_;
3024 const GLRenderer::RenderPassProgram* GLRenderer::GetRenderPassProgram(
3025 TexCoordPrecision precision,
3026 BlendMode blend_mode) {
3027 DCHECK_GE(precision, 0);
3028 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3029 DCHECK_GE(blend_mode, 0);
3030 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3031 RenderPassProgram* program = &render_pass_program_[precision][blend_mode];
3032 if (!program->initialized()) {
3033 TRACE_EVENT0("cc", "GLRenderer::renderPassProgram::initialize");
3034 program->Initialize(output_surface_->context_provider(), precision,
3035 SAMPLER_TYPE_2D, blend_mode);
3037 return program;
3040 const GLRenderer::RenderPassProgramAA* GLRenderer::GetRenderPassProgramAA(
3041 TexCoordPrecision precision,
3042 BlendMode blend_mode) {
3043 DCHECK_GE(precision, 0);
3044 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3045 DCHECK_GE(blend_mode, 0);
3046 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3047 RenderPassProgramAA* program =
3048 &render_pass_program_aa_[precision][blend_mode];
3049 if (!program->initialized()) {
3050 TRACE_EVENT0("cc", "GLRenderer::renderPassProgramAA::initialize");
3051 program->Initialize(output_surface_->context_provider(), precision,
3052 SAMPLER_TYPE_2D, blend_mode);
3054 return program;
3057 const GLRenderer::RenderPassMaskProgram* GLRenderer::GetRenderPassMaskProgram(
3058 TexCoordPrecision precision,
3059 SamplerType sampler,
3060 BlendMode blend_mode,
3061 bool mask_for_background) {
3062 DCHECK_GE(precision, 0);
3063 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3064 DCHECK_GE(sampler, 0);
3065 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3066 DCHECK_GE(blend_mode, 0);
3067 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3068 RenderPassMaskProgram* program =
3069 &render_pass_mask_program_[precision][sampler][blend_mode]
3070 [mask_for_background ? HAS_MASK : NO_MASK];
3071 if (!program->initialized()) {
3072 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgram::initialize");
3073 program->Initialize(
3074 output_surface_->context_provider(), precision,
3075 sampler, blend_mode, mask_for_background);
3077 return program;
3080 const GLRenderer::RenderPassMaskProgramAA*
3081 GLRenderer::GetRenderPassMaskProgramAA(TexCoordPrecision precision,
3082 SamplerType sampler,
3083 BlendMode blend_mode,
3084 bool mask_for_background) {
3085 DCHECK_GE(precision, 0);
3086 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3087 DCHECK_GE(sampler, 0);
3088 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3089 DCHECK_GE(blend_mode, 0);
3090 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3091 RenderPassMaskProgramAA* program =
3092 &render_pass_mask_program_aa_[precision][sampler][blend_mode]
3093 [mask_for_background ? HAS_MASK : NO_MASK];
3094 if (!program->initialized()) {
3095 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgramAA::initialize");
3096 program->Initialize(
3097 output_surface_->context_provider(), precision,
3098 sampler, blend_mode, mask_for_background);
3100 return program;
3103 const GLRenderer::RenderPassColorMatrixProgram*
3104 GLRenderer::GetRenderPassColorMatrixProgram(TexCoordPrecision precision,
3105 BlendMode blend_mode) {
3106 DCHECK_GE(precision, 0);
3107 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3108 DCHECK_GE(blend_mode, 0);
3109 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3110 RenderPassColorMatrixProgram* program =
3111 &render_pass_color_matrix_program_[precision][blend_mode];
3112 if (!program->initialized()) {
3113 TRACE_EVENT0("cc", "GLRenderer::renderPassColorMatrixProgram::initialize");
3114 program->Initialize(output_surface_->context_provider(), precision,
3115 SAMPLER_TYPE_2D, blend_mode);
3117 return program;
3120 const GLRenderer::RenderPassColorMatrixProgramAA*
3121 GLRenderer::GetRenderPassColorMatrixProgramAA(TexCoordPrecision precision,
3122 BlendMode blend_mode) {
3123 DCHECK_GE(precision, 0);
3124 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3125 DCHECK_GE(blend_mode, 0);
3126 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3127 RenderPassColorMatrixProgramAA* program =
3128 &render_pass_color_matrix_program_aa_[precision][blend_mode];
3129 if (!program->initialized()) {
3130 TRACE_EVENT0("cc",
3131 "GLRenderer::renderPassColorMatrixProgramAA::initialize");
3132 program->Initialize(output_surface_->context_provider(), precision,
3133 SAMPLER_TYPE_2D, blend_mode);
3135 return program;
3138 const GLRenderer::RenderPassMaskColorMatrixProgram*
3139 GLRenderer::GetRenderPassMaskColorMatrixProgram(
3140 TexCoordPrecision precision,
3141 SamplerType sampler,
3142 BlendMode blend_mode,
3143 bool mask_for_background) {
3144 DCHECK_GE(precision, 0);
3145 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3146 DCHECK_GE(sampler, 0);
3147 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3148 DCHECK_GE(blend_mode, 0);
3149 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3150 RenderPassMaskColorMatrixProgram* program =
3151 &render_pass_mask_color_matrix_program_[precision][sampler][blend_mode]
3152 [mask_for_background ? HAS_MASK : NO_MASK];
3153 if (!program->initialized()) {
3154 TRACE_EVENT0("cc",
3155 "GLRenderer::renderPassMaskColorMatrixProgram::initialize");
3156 program->Initialize(
3157 output_surface_->context_provider(), precision,
3158 sampler, blend_mode, mask_for_background);
3160 return program;
3163 const GLRenderer::RenderPassMaskColorMatrixProgramAA*
3164 GLRenderer::GetRenderPassMaskColorMatrixProgramAA(
3165 TexCoordPrecision precision,
3166 SamplerType sampler,
3167 BlendMode blend_mode,
3168 bool mask_for_background) {
3169 DCHECK_GE(precision, 0);
3170 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3171 DCHECK_GE(sampler, 0);
3172 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3173 DCHECK_GE(blend_mode, 0);
3174 DCHECK_LE(blend_mode, LAST_BLEND_MODE);
3175 RenderPassMaskColorMatrixProgramAA* program =
3176 &render_pass_mask_color_matrix_program_aa_[precision][sampler][blend_mode]
3177 [mask_for_background ? HAS_MASK : NO_MASK];
3178 if (!program->initialized()) {
3179 TRACE_EVENT0("cc",
3180 "GLRenderer::renderPassMaskColorMatrixProgramAA::initialize");
3181 program->Initialize(
3182 output_surface_->context_provider(), precision,
3183 sampler, blend_mode, mask_for_background);
3185 return program;
3188 const GLRenderer::TileProgram* GLRenderer::GetTileProgram(
3189 TexCoordPrecision precision,
3190 SamplerType sampler) {
3191 DCHECK_GE(precision, 0);
3192 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3193 DCHECK_GE(sampler, 0);
3194 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3195 TileProgram* program = &tile_program_[precision][sampler];
3196 if (!program->initialized()) {
3197 TRACE_EVENT0("cc", "GLRenderer::tileProgram::initialize");
3198 program->Initialize(
3199 output_surface_->context_provider(), precision, sampler);
3201 return program;
3204 const GLRenderer::TileProgramOpaque* GLRenderer::GetTileProgramOpaque(
3205 TexCoordPrecision precision,
3206 SamplerType sampler) {
3207 DCHECK_GE(precision, 0);
3208 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3209 DCHECK_GE(sampler, 0);
3210 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3211 TileProgramOpaque* program = &tile_program_opaque_[precision][sampler];
3212 if (!program->initialized()) {
3213 TRACE_EVENT0("cc", "GLRenderer::tileProgramOpaque::initialize");
3214 program->Initialize(
3215 output_surface_->context_provider(), precision, sampler);
3217 return program;
3220 const GLRenderer::TileProgramAA* GLRenderer::GetTileProgramAA(
3221 TexCoordPrecision precision,
3222 SamplerType sampler) {
3223 DCHECK_GE(precision, 0);
3224 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3225 DCHECK_GE(sampler, 0);
3226 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3227 TileProgramAA* program = &tile_program_aa_[precision][sampler];
3228 if (!program->initialized()) {
3229 TRACE_EVENT0("cc", "GLRenderer::tileProgramAA::initialize");
3230 program->Initialize(
3231 output_surface_->context_provider(), precision, sampler);
3233 return program;
3236 const GLRenderer::TileProgramSwizzle* GLRenderer::GetTileProgramSwizzle(
3237 TexCoordPrecision precision,
3238 SamplerType sampler) {
3239 DCHECK_GE(precision, 0);
3240 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3241 DCHECK_GE(sampler, 0);
3242 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3243 TileProgramSwizzle* program = &tile_program_swizzle_[precision][sampler];
3244 if (!program->initialized()) {
3245 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzle::initialize");
3246 program->Initialize(
3247 output_surface_->context_provider(), precision, sampler);
3249 return program;
3252 const GLRenderer::TileProgramSwizzleOpaque*
3253 GLRenderer::GetTileProgramSwizzleOpaque(TexCoordPrecision precision,
3254 SamplerType sampler) {
3255 DCHECK_GE(precision, 0);
3256 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3257 DCHECK_GE(sampler, 0);
3258 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3259 TileProgramSwizzleOpaque* program =
3260 &tile_program_swizzle_opaque_[precision][sampler];
3261 if (!program->initialized()) {
3262 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleOpaque::initialize");
3263 program->Initialize(
3264 output_surface_->context_provider(), precision, sampler);
3266 return program;
3269 const GLRenderer::TileProgramSwizzleAA* GLRenderer::GetTileProgramSwizzleAA(
3270 TexCoordPrecision precision,
3271 SamplerType sampler) {
3272 DCHECK_GE(precision, 0);
3273 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3274 DCHECK_GE(sampler, 0);
3275 DCHECK_LE(sampler, LAST_SAMPLER_TYPE);
3276 TileProgramSwizzleAA* program = &tile_program_swizzle_aa_[precision][sampler];
3277 if (!program->initialized()) {
3278 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleAA::initialize");
3279 program->Initialize(
3280 output_surface_->context_provider(), precision, sampler);
3282 return program;
3285 const GLRenderer::TextureProgram* GLRenderer::GetTextureProgram(
3286 TexCoordPrecision precision) {
3287 DCHECK_GE(precision, 0);
3288 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3289 TextureProgram* program = &texture_program_[precision];
3290 if (!program->initialized()) {
3291 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3292 program->Initialize(output_surface_->context_provider(), precision,
3293 SAMPLER_TYPE_2D);
3295 return program;
3298 const GLRenderer::NonPremultipliedTextureProgram*
3299 GLRenderer::GetNonPremultipliedTextureProgram(TexCoordPrecision precision) {
3300 DCHECK_GE(precision, 0);
3301 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3302 NonPremultipliedTextureProgram* program =
3303 &nonpremultiplied_texture_program_[precision];
3304 if (!program->initialized()) {
3305 TRACE_EVENT0("cc",
3306 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3307 program->Initialize(output_surface_->context_provider(), precision,
3308 SAMPLER_TYPE_2D);
3310 return program;
3313 const GLRenderer::TextureBackgroundProgram*
3314 GLRenderer::GetTextureBackgroundProgram(TexCoordPrecision precision) {
3315 DCHECK_GE(precision, 0);
3316 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3317 TextureBackgroundProgram* program = &texture_background_program_[precision];
3318 if (!program->initialized()) {
3319 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3320 program->Initialize(output_surface_->context_provider(), precision,
3321 SAMPLER_TYPE_2D);
3323 return program;
3326 const GLRenderer::NonPremultipliedTextureBackgroundProgram*
3327 GLRenderer::GetNonPremultipliedTextureBackgroundProgram(
3328 TexCoordPrecision precision) {
3329 DCHECK_GE(precision, 0);
3330 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3331 NonPremultipliedTextureBackgroundProgram* program =
3332 &nonpremultiplied_texture_background_program_[precision];
3333 if (!program->initialized()) {
3334 TRACE_EVENT0("cc",
3335 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3336 program->Initialize(output_surface_->context_provider(), precision,
3337 SAMPLER_TYPE_2D);
3339 return program;
3342 const GLRenderer::TextureProgram* GLRenderer::GetTextureIOSurfaceProgram(
3343 TexCoordPrecision precision) {
3344 DCHECK_GE(precision, 0);
3345 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3346 TextureProgram* program = &texture_io_surface_program_[precision];
3347 if (!program->initialized()) {
3348 TRACE_EVENT0("cc", "GLRenderer::textureIOSurfaceProgram::initialize");
3349 program->Initialize(output_surface_->context_provider(), precision,
3350 SAMPLER_TYPE_2D_RECT);
3352 return program;
3355 const GLRenderer::VideoYUVProgram* GLRenderer::GetVideoYUVProgram(
3356 TexCoordPrecision precision) {
3357 DCHECK_GE(precision, 0);
3358 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3359 VideoYUVProgram* program = &video_yuv_program_[precision];
3360 if (!program->initialized()) {
3361 TRACE_EVENT0("cc", "GLRenderer::videoYUVProgram::initialize");
3362 program->Initialize(output_surface_->context_provider(), precision,
3363 SAMPLER_TYPE_2D);
3365 return program;
3368 const GLRenderer::VideoYUVAProgram* GLRenderer::GetVideoYUVAProgram(
3369 TexCoordPrecision precision) {
3370 DCHECK_GE(precision, 0);
3371 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3372 VideoYUVAProgram* program = &video_yuva_program_[precision];
3373 if (!program->initialized()) {
3374 TRACE_EVENT0("cc", "GLRenderer::videoYUVAProgram::initialize");
3375 program->Initialize(output_surface_->context_provider(), precision,
3376 SAMPLER_TYPE_2D);
3378 return program;
3381 const GLRenderer::VideoStreamTextureProgram*
3382 GLRenderer::GetVideoStreamTextureProgram(TexCoordPrecision precision) {
3383 if (!Capabilities().using_egl_image)
3384 return NULL;
3385 DCHECK_GE(precision, 0);
3386 DCHECK_LE(precision, LAST_TEX_COORD_PRECISION);
3387 VideoStreamTextureProgram* program =
3388 &video_stream_texture_program_[precision];
3389 if (!program->initialized()) {
3390 TRACE_EVENT0("cc", "GLRenderer::streamTextureProgram::initialize");
3391 program->Initialize(output_surface_->context_provider(), precision,
3392 SAMPLER_TYPE_EXTERNAL_OES);
3394 return program;
3397 void GLRenderer::CleanupSharedObjects() {
3398 shared_geometry_ = nullptr;
3400 for (int i = 0; i <= LAST_TEX_COORD_PRECISION; ++i) {
3401 for (int j = 0; j <= LAST_SAMPLER_TYPE; ++j) {
3402 tile_program_[i][j].Cleanup(gl_);
3403 tile_program_opaque_[i][j].Cleanup(gl_);
3404 tile_program_swizzle_[i][j].Cleanup(gl_);
3405 tile_program_swizzle_opaque_[i][j].Cleanup(gl_);
3406 tile_program_aa_[i][j].Cleanup(gl_);
3407 tile_program_swizzle_aa_[i][j].Cleanup(gl_);
3409 for (int k = 0; k <= LAST_BLEND_MODE; k++) {
3410 for (int l = 0; l <= LAST_MASK_VALUE; ++l) {
3411 render_pass_mask_program_[i][j][k][l].Cleanup(gl_);
3412 render_pass_mask_program_aa_[i][j][k][l].Cleanup(gl_);
3413 render_pass_mask_color_matrix_program_aa_[i][j][k][l].Cleanup(gl_);
3414 render_pass_mask_color_matrix_program_[i][j][k][l].Cleanup(gl_);
3418 for (int j = 0; j <= LAST_BLEND_MODE; j++) {
3419 render_pass_program_[i][j].Cleanup(gl_);
3420 render_pass_program_aa_[i][j].Cleanup(gl_);
3421 render_pass_color_matrix_program_[i][j].Cleanup(gl_);
3422 render_pass_color_matrix_program_aa_[i][j].Cleanup(gl_);
3425 texture_program_[i].Cleanup(gl_);
3426 nonpremultiplied_texture_program_[i].Cleanup(gl_);
3427 texture_background_program_[i].Cleanup(gl_);
3428 nonpremultiplied_texture_background_program_[i].Cleanup(gl_);
3429 texture_io_surface_program_[i].Cleanup(gl_);
3431 video_yuv_program_[i].Cleanup(gl_);
3432 video_yuva_program_[i].Cleanup(gl_);
3433 video_stream_texture_program_[i].Cleanup(gl_);
3436 tile_checkerboard_program_.Cleanup(gl_);
3438 debug_border_program_.Cleanup(gl_);
3439 solid_color_program_.Cleanup(gl_);
3440 solid_color_program_aa_.Cleanup(gl_);
3442 if (offscreen_framebuffer_id_)
3443 GLC(gl_, gl_->DeleteFramebuffers(1, &offscreen_framebuffer_id_));
3445 if (on_demand_tile_raster_resource_id_)
3446 resource_provider_->DeleteResource(on_demand_tile_raster_resource_id_);
3448 ReleaseRenderPassTextures();
3451 void GLRenderer::ReinitializeGLState() {
3452 is_scissor_enabled_ = false;
3453 scissor_rect_needs_reset_ = true;
3454 stencil_shadow_ = false;
3455 blend_shadow_ = true;
3456 program_shadow_ = 0;
3458 RestoreGLState();
3461 void GLRenderer::RestoreGLState() {
3462 // This restores the current GLRenderer state to the GL context.
3463 bound_geometry_ = NO_BINDING;
3464 PrepareGeometry(SHARED_BINDING);
3466 GLC(gl_, gl_->Disable(GL_DEPTH_TEST));
3467 GLC(gl_, gl_->Disable(GL_CULL_FACE));
3468 GLC(gl_, gl_->ColorMask(true, true, true, true));
3469 GLC(gl_, gl_->BlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA));
3470 GLC(gl_, gl_->ActiveTexture(GL_TEXTURE0));
3472 if (program_shadow_)
3473 gl_->UseProgram(program_shadow_);
3475 if (stencil_shadow_)
3476 GLC(gl_, gl_->Enable(GL_STENCIL_TEST));
3477 else
3478 GLC(gl_, gl_->Disable(GL_STENCIL_TEST));
3480 if (blend_shadow_)
3481 GLC(gl_, gl_->Enable(GL_BLEND));
3482 else
3483 GLC(gl_, gl_->Disable(GL_BLEND));
3485 if (is_scissor_enabled_) {
3486 GLC(gl_, gl_->Enable(GL_SCISSOR_TEST));
3487 GLC(gl_,
3488 gl_->Scissor(scissor_rect_.x(),
3489 scissor_rect_.y(),
3490 scissor_rect_.width(),
3491 scissor_rect_.height()));
3492 } else {
3493 GLC(gl_, gl_->Disable(GL_SCISSOR_TEST));
3497 void GLRenderer::RestoreFramebuffer(DrawingFrame* frame) {
3498 UseRenderPass(frame, frame->current_render_pass);
3501 bool GLRenderer::IsContextLost() {
3502 return output_surface_->context_provider()->IsContextLost();
3505 void GLRenderer::ScheduleOverlays(DrawingFrame* frame) {
3506 if (!frame->overlay_list.size())
3507 return;
3509 ResourceProvider::ResourceIdArray resources;
3510 OverlayCandidateList& overlays = frame->overlay_list;
3511 OverlayCandidateList::iterator it;
3512 for (it = overlays.begin(); it != overlays.end(); ++it) {
3513 const OverlayCandidate& overlay = *it;
3514 // Skip primary plane.
3515 if (overlay.plane_z_order == 0)
3516 continue;
3518 pending_overlay_resources_.push_back(
3519 make_scoped_ptr(new ResourceProvider::ScopedReadLockGL(
3520 resource_provider_, overlay.resource_id)));
3522 context_support_->ScheduleOverlayPlane(
3523 overlay.plane_z_order,
3524 overlay.transform,
3525 pending_overlay_resources_.back()->texture_id(),
3526 overlay.display_rect,
3527 overlay.uv_rect);
3531 } // namespace cc