[NaCl SDK] Fix mysterious gtest failure in Html5FsTest::OpenForCreate
[chromium-blink-merge.git] / cc / output / gl_renderer.cc
blob75dcfe8466c7549381198376fa3207b4f1af858b
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/debug/trace_event.h"
14 #include "base/logging.h"
15 #include "cc/base/math_util.h"
16 #include "cc/layers/video_layer_impl.h"
17 #include "cc/output/compositor_frame.h"
18 #include "cc/output/compositor_frame_metadata.h"
19 #include "cc/output/context_provider.h"
20 #include "cc/output/copy_output_request.h"
21 #include "cc/output/geometry_binding.h"
22 #include "cc/output/gl_frame_data.h"
23 #include "cc/output/output_surface.h"
24 #include "cc/output/render_surface_filters.h"
25 #include "cc/quads/picture_draw_quad.h"
26 #include "cc/quads/render_pass.h"
27 #include "cc/quads/stream_video_draw_quad.h"
28 #include "cc/quads/texture_draw_quad.h"
29 #include "cc/resources/layer_quad.h"
30 #include "cc/resources/scoped_resource.h"
31 #include "cc/resources/texture_mailbox_deleter.h"
32 #include "gpu/GLES2/gl2extchromium.h"
33 #include "gpu/command_buffer/client/context_support.h"
34 #include "gpu/command_buffer/client/gles2_interface.h"
35 #include "gpu/command_buffer/common/gpu_memory_allocation.h"
36 #include "third_party/skia/include/core/SkBitmap.h"
37 #include "third_party/skia/include/core/SkColor.h"
38 #include "third_party/skia/include/core/SkColorFilter.h"
39 #include "third_party/skia/include/core/SkImage.h"
40 #include "third_party/skia/include/core/SkSurface.h"
41 #include "third_party/skia/include/gpu/GrContext.h"
42 #include "third_party/skia/include/gpu/GrTexture.h"
43 #include "third_party/skia/include/gpu/SkGrTexturePixelRef.h"
44 #include "third_party/skia/include/gpu/gl/GrGLInterface.h"
45 #include "ui/gfx/geometry/quad_f.h"
46 #include "ui/gfx/geometry/rect_conversions.h"
48 using gpu::gles2::GLES2Interface;
50 namespace cc {
51 namespace {
53 bool NeedsIOSurfaceReadbackWorkaround() {
54 #if defined(OS_MACOSX)
55 // This isn't strictly required in DumpRenderTree-mode when Mesa is used,
56 // but it doesn't seem to hurt.
57 return true;
58 #else
59 return false;
60 #endif
63 Float4 UVTransform(const TextureDrawQuad* quad) {
64 gfx::PointF uv0 = quad->uv_top_left;
65 gfx::PointF uv1 = quad->uv_bottom_right;
66 Float4 xform = {{uv0.x(), uv0.y(), uv1.x() - uv0.x(), uv1.y() - uv0.y()}};
67 if (quad->flipped) {
68 xform.data[1] = 1.0f - xform.data[1];
69 xform.data[3] = -xform.data[3];
71 return xform;
74 Float4 PremultipliedColor(SkColor color) {
75 const float factor = 1.0f / 255.0f;
76 const float alpha = SkColorGetA(color) * factor;
78 Float4 result = {
79 {SkColorGetR(color) * factor * alpha, SkColorGetG(color) * factor * alpha,
80 SkColorGetB(color) * factor * alpha, alpha}};
81 return result;
84 SamplerType SamplerTypeFromTextureTarget(GLenum target) {
85 switch (target) {
86 case GL_TEXTURE_2D:
87 return SamplerType2D;
88 case GL_TEXTURE_RECTANGLE_ARB:
89 return SamplerType2DRect;
90 case GL_TEXTURE_EXTERNAL_OES:
91 return SamplerTypeExternalOES;
92 default:
93 NOTREACHED();
94 return SamplerType2D;
98 BlendMode BlendModeFromSkXfermode(SkXfermode::Mode mode) {
99 switch (mode) {
100 case SkXfermode::kSrcOver_Mode:
101 return BlendModeNormal;
102 case SkXfermode::kScreen_Mode:
103 return BlendModeScreen;
104 case SkXfermode::kOverlay_Mode:
105 return BlendModeOverlay;
106 case SkXfermode::kDarken_Mode:
107 return BlendModeDarken;
108 case SkXfermode::kLighten_Mode:
109 return BlendModeLighten;
110 case SkXfermode::kColorDodge_Mode:
111 return BlendModeColorDodge;
112 case SkXfermode::kColorBurn_Mode:
113 return BlendModeColorBurn;
114 case SkXfermode::kHardLight_Mode:
115 return BlendModeHardLight;
116 case SkXfermode::kSoftLight_Mode:
117 return BlendModeSoftLight;
118 case SkXfermode::kDifference_Mode:
119 return BlendModeDifference;
120 case SkXfermode::kExclusion_Mode:
121 return BlendModeExclusion;
122 case SkXfermode::kMultiply_Mode:
123 return BlendModeMultiply;
124 case SkXfermode::kHue_Mode:
125 return BlendModeHue;
126 case SkXfermode::kSaturation_Mode:
127 return BlendModeSaturation;
128 case SkXfermode::kColor_Mode:
129 return BlendModeColor;
130 case SkXfermode::kLuminosity_Mode:
131 return BlendModeLuminosity;
132 default:
133 NOTREACHED();
134 return BlendModeNone;
138 // Smallest unit that impact anti-aliasing output. We use this to
139 // determine when anti-aliasing is unnecessary.
140 const float kAntiAliasingEpsilon = 1.0f / 1024.0f;
142 // Block or crash if the number of pending sync queries reach this high as
143 // something is seriously wrong on the service side if this happens.
144 const size_t kMaxPendingSyncQueries = 16;
146 } // anonymous namespace
148 static GLint GetActiveTextureUnit(GLES2Interface* gl) {
149 GLint active_unit = 0;
150 gl->GetIntegerv(GL_ACTIVE_TEXTURE, &active_unit);
151 return active_unit;
154 class GLRenderer::ScopedUseGrContext {
155 public:
156 static scoped_ptr<ScopedUseGrContext> Create(GLRenderer* renderer,
157 DrawingFrame* frame) {
158 if (!renderer->output_surface_->context_provider()->GrContext())
159 return nullptr;
160 return make_scoped_ptr(new ScopedUseGrContext(renderer, frame));
163 ~ScopedUseGrContext() { PassControlToGLRenderer(); }
165 GrContext* context() const {
166 return renderer_->output_surface_->context_provider()->GrContext();
169 private:
170 ScopedUseGrContext(GLRenderer* renderer, DrawingFrame* frame)
171 : renderer_(renderer), frame_(frame) {
172 PassControlToSkia();
175 void PassControlToSkia() { context()->resetContext(); }
177 void PassControlToGLRenderer() {
178 renderer_->RestoreGLState();
179 renderer_->RestoreFramebuffer(frame_);
182 GLRenderer* renderer_;
183 DrawingFrame* frame_;
185 DISALLOW_COPY_AND_ASSIGN(ScopedUseGrContext);
188 struct GLRenderer::PendingAsyncReadPixels {
189 PendingAsyncReadPixels() : buffer(0) {}
191 scoped_ptr<CopyOutputRequest> copy_request;
192 base::CancelableClosure finished_read_pixels_callback;
193 unsigned buffer;
195 private:
196 DISALLOW_COPY_AND_ASSIGN(PendingAsyncReadPixels);
199 class GLRenderer::SyncQuery {
200 public:
201 explicit SyncQuery(gpu::gles2::GLES2Interface* gl)
202 : gl_(gl), query_id_(0u), is_pending_(false), weak_ptr_factory_(this) {
203 gl_->GenQueriesEXT(1, &query_id_);
205 virtual ~SyncQuery() { gl_->DeleteQueriesEXT(1, &query_id_); }
207 scoped_refptr<ResourceProvider::Fence> Begin() {
208 DCHECK(!IsPending());
209 // Invalidate weak pointer held by old fence.
210 weak_ptr_factory_.InvalidateWeakPtrs();
211 // Note: In case the set of drawing commands issued before End() do not
212 // depend on the query, defer BeginQueryEXT call until Set() is called and
213 // query is required.
214 return make_scoped_refptr<ResourceProvider::Fence>(
215 new Fence(weak_ptr_factory_.GetWeakPtr()));
218 void Set() {
219 if (is_pending_)
220 return;
222 // Note: BeginQueryEXT on GL_COMMANDS_COMPLETED_CHROMIUM is effectively a
223 // noop relative to GL, so it doesn't matter where it happens but we still
224 // make sure to issue this command when Set() is called (prior to issuing
225 // any drawing commands that depend on query), in case some future extension
226 // can take advantage of this.
227 gl_->BeginQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM, query_id_);
228 is_pending_ = true;
231 void End() {
232 if (!is_pending_)
233 return;
235 gl_->EndQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM);
238 bool IsPending() {
239 if (!is_pending_)
240 return false;
242 unsigned result_available = 1;
243 gl_->GetQueryObjectuivEXT(
244 query_id_, GL_QUERY_RESULT_AVAILABLE_EXT, &result_available);
245 is_pending_ = !result_available;
246 return is_pending_;
249 void Wait() {
250 if (!is_pending_)
251 return;
253 unsigned result = 0;
254 gl_->GetQueryObjectuivEXT(query_id_, GL_QUERY_RESULT_EXT, &result);
255 is_pending_ = false;
258 private:
259 class Fence : public ResourceProvider::Fence {
260 public:
261 explicit Fence(base::WeakPtr<GLRenderer::SyncQuery> query)
262 : query_(query) {}
264 // Overridden from ResourceProvider::Fence:
265 void Set() override {
266 DCHECK(query_);
267 query_->Set();
269 bool HasPassed() override { return !query_ || !query_->IsPending(); }
270 void Wait() override {
271 if (query_)
272 query_->Wait();
275 private:
276 ~Fence() override {}
278 base::WeakPtr<SyncQuery> query_;
280 DISALLOW_COPY_AND_ASSIGN(Fence);
283 gpu::gles2::GLES2Interface* gl_;
284 unsigned query_id_;
285 bool is_pending_;
286 base::WeakPtrFactory<SyncQuery> weak_ptr_factory_;
288 DISALLOW_COPY_AND_ASSIGN(SyncQuery);
291 scoped_ptr<GLRenderer> GLRenderer::Create(
292 RendererClient* client,
293 const LayerTreeSettings* settings,
294 OutputSurface* output_surface,
295 ResourceProvider* resource_provider,
296 TextureMailboxDeleter* texture_mailbox_deleter,
297 int highp_threshold_min) {
298 return make_scoped_ptr(new GLRenderer(client,
299 settings,
300 output_surface,
301 resource_provider,
302 texture_mailbox_deleter,
303 highp_threshold_min));
306 GLRenderer::GLRenderer(RendererClient* client,
307 const LayerTreeSettings* settings,
308 OutputSurface* output_surface,
309 ResourceProvider* resource_provider,
310 TextureMailboxDeleter* texture_mailbox_deleter,
311 int highp_threshold_min)
312 : DirectRenderer(client, settings, output_surface, resource_provider),
313 offscreen_framebuffer_id_(0),
314 shared_geometry_quad_(QuadVertexRect()),
315 gl_(output_surface->context_provider()->ContextGL()),
316 context_support_(output_surface->context_provider()->ContextSupport()),
317 texture_mailbox_deleter_(texture_mailbox_deleter),
318 is_backbuffer_discarded_(false),
319 is_scissor_enabled_(false),
320 scissor_rect_needs_reset_(true),
321 stencil_shadow_(false),
322 blend_shadow_(false),
323 highp_threshold_min_(highp_threshold_min),
324 highp_threshold_cache_(0),
325 use_sync_query_(false),
326 on_demand_tile_raster_resource_id_(0) {
327 DCHECK(gl_);
328 DCHECK(context_support_);
330 ContextProvider::Capabilities context_caps =
331 output_surface_->context_provider()->ContextCapabilities();
333 capabilities_.using_partial_swap =
334 settings_->partial_swap_enabled && context_caps.gpu.post_sub_buffer;
336 DCHECK(!context_caps.gpu.iosurface || context_caps.gpu.texture_rectangle);
338 capabilities_.using_egl_image = context_caps.gpu.egl_image_external;
340 capabilities_.max_texture_size = resource_provider_->max_texture_size();
341 capabilities_.best_texture_format = resource_provider_->best_texture_format();
343 // The updater can access textures while the GLRenderer is using them.
344 capabilities_.allow_partial_texture_updates = true;
346 capabilities_.using_image = context_caps.gpu.image;
348 capabilities_.using_discard_framebuffer =
349 context_caps.gpu.discard_framebuffer;
351 capabilities_.allow_rasterize_on_demand = true;
353 use_sync_query_ = context_caps.gpu.sync_query;
354 use_blend_equation_advanced_ = context_caps.gpu.blend_equation_advanced;
355 use_blend_equation_advanced_coherent_ =
356 context_caps.gpu.blend_equation_advanced_coherent;
358 InitializeSharedObjects();
361 GLRenderer::~GLRenderer() {
362 while (!pending_async_read_pixels_.empty()) {
363 PendingAsyncReadPixels* pending_read = pending_async_read_pixels_.back();
364 pending_read->finished_read_pixels_callback.Cancel();
365 pending_async_read_pixels_.pop_back();
368 in_use_overlay_resources_.clear();
370 CleanupSharedObjects();
373 const RendererCapabilitiesImpl& GLRenderer::Capabilities() const {
374 return capabilities_;
377 void GLRenderer::DebugGLCall(GLES2Interface* gl,
378 const char* command,
379 const char* file,
380 int line) {
381 GLuint error = gl->GetError();
382 if (error != GL_NO_ERROR)
383 LOG(ERROR) << "GL command failed: File: " << file << "\n\tLine " << line
384 << "\n\tcommand: " << command << ", error "
385 << static_cast<int>(error) << "\n";
388 void GLRenderer::DidChangeVisibility() {
389 EnforceMemoryPolicy();
391 context_support_->SetSurfaceVisible(visible());
394 void GLRenderer::ReleaseRenderPassTextures() { render_pass_textures_.clear(); }
396 void GLRenderer::DiscardPixels(bool has_external_stencil_test,
397 bool draw_rect_covers_full_surface) {
398 if (has_external_stencil_test || !draw_rect_covers_full_surface ||
399 !capabilities_.using_discard_framebuffer)
400 return;
401 bool using_default_framebuffer =
402 !current_framebuffer_lock_ &&
403 output_surface_->capabilities().uses_default_gl_framebuffer;
404 GLenum attachments[] = {static_cast<GLenum>(
405 using_default_framebuffer ? GL_COLOR_EXT : GL_COLOR_ATTACHMENT0_EXT)};
406 gl_->DiscardFramebufferEXT(
407 GL_FRAMEBUFFER, arraysize(attachments), attachments);
410 void GLRenderer::ClearFramebuffer(DrawingFrame* frame,
411 bool has_external_stencil_test) {
412 // It's unsafe to clear when we have a stencil test because glClear ignores
413 // stencil.
414 if (has_external_stencil_test) {
415 DCHECK(!frame->current_render_pass->has_transparent_background);
416 return;
419 // On DEBUG builds, opaque render passes are cleared to blue to easily see
420 // regions that were not drawn on the screen.
421 if (frame->current_render_pass->has_transparent_background)
422 GLC(gl_, gl_->ClearColor(0, 0, 0, 0));
423 else
424 GLC(gl_, gl_->ClearColor(0, 0, 1, 1));
426 bool always_clear = false;
427 #ifndef NDEBUG
428 always_clear = true;
429 #endif
430 if (always_clear || frame->current_render_pass->has_transparent_background) {
431 GLbitfield clear_bits = GL_COLOR_BUFFER_BIT;
432 if (always_clear)
433 clear_bits |= GL_STENCIL_BUFFER_BIT;
434 gl_->Clear(clear_bits);
438 static ResourceProvider::ResourceId WaitOnResourceSyncPoints(
439 ResourceProvider* resource_provider,
440 ResourceProvider::ResourceId resource_id) {
441 resource_provider->WaitSyncPointIfNeeded(resource_id);
442 return resource_id;
445 void GLRenderer::BeginDrawingFrame(DrawingFrame* frame) {
446 TRACE_EVENT0("cc", "GLRenderer::BeginDrawingFrame");
448 scoped_refptr<ResourceProvider::Fence> read_lock_fence;
449 if (use_sync_query_) {
450 // Block until oldest sync query has passed if the number of pending queries
451 // ever reach kMaxPendingSyncQueries.
452 if (pending_sync_queries_.size() >= kMaxPendingSyncQueries) {
453 LOG(ERROR) << "Reached limit of pending sync queries.";
455 pending_sync_queries_.front()->Wait();
456 DCHECK(!pending_sync_queries_.front()->IsPending());
459 while (!pending_sync_queries_.empty()) {
460 if (pending_sync_queries_.front()->IsPending())
461 break;
463 available_sync_queries_.push_back(pending_sync_queries_.take_front());
466 current_sync_query_ = available_sync_queries_.empty()
467 ? make_scoped_ptr(new SyncQuery(gl_))
468 : available_sync_queries_.take_front();
470 read_lock_fence = current_sync_query_->Begin();
471 } else {
472 read_lock_fence =
473 make_scoped_refptr(new ResourceProvider::SynchronousFence(gl_));
475 resource_provider_->SetReadLockFence(read_lock_fence.get());
477 // Insert WaitSyncPointCHROMIUM on quad resources prior to drawing the frame,
478 // so that drawing can proceed without GL context switching interruptions.
479 DrawQuad::ResourceIteratorCallback wait_on_resource_syncpoints_callback =
480 base::Bind(&WaitOnResourceSyncPoints, resource_provider_);
482 for (const auto& pass : *frame->render_passes_in_draw_order) {
483 for (const auto& quad : pass->quad_list)
484 quad->IterateResources(wait_on_resource_syncpoints_callback);
487 // TODO(enne): Do we need to reinitialize all of this state per frame?
488 ReinitializeGLState();
491 void GLRenderer::DoNoOp() {
492 GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, 0));
493 GLC(gl_, gl_->Flush());
496 void GLRenderer::DoDrawQuad(DrawingFrame* frame, const DrawQuad* quad) {
497 DCHECK(quad->rect.Contains(quad->visible_rect));
498 if (quad->material != DrawQuad::TEXTURE_CONTENT) {
499 FlushTextureQuadCache();
502 switch (quad->material) {
503 case DrawQuad::INVALID:
504 NOTREACHED();
505 break;
506 case DrawQuad::CHECKERBOARD:
507 DrawCheckerboardQuad(frame, CheckerboardDrawQuad::MaterialCast(quad));
508 break;
509 case DrawQuad::DEBUG_BORDER:
510 DrawDebugBorderQuad(frame, DebugBorderDrawQuad::MaterialCast(quad));
511 break;
512 case DrawQuad::IO_SURFACE_CONTENT:
513 DrawIOSurfaceQuad(frame, IOSurfaceDrawQuad::MaterialCast(quad));
514 break;
515 case DrawQuad::PICTURE_CONTENT:
516 DrawPictureQuad(frame, PictureDrawQuad::MaterialCast(quad));
517 break;
518 case DrawQuad::RENDER_PASS:
519 DrawRenderPassQuad(frame, RenderPassDrawQuad::MaterialCast(quad));
520 break;
521 case DrawQuad::SOLID_COLOR:
522 DrawSolidColorQuad(frame, SolidColorDrawQuad::MaterialCast(quad));
523 break;
524 case DrawQuad::STREAM_VIDEO_CONTENT:
525 DrawStreamVideoQuad(frame, StreamVideoDrawQuad::MaterialCast(quad));
526 break;
527 case DrawQuad::SURFACE_CONTENT:
528 // Surface content should be fully resolved to other quad types before
529 // reaching a direct renderer.
530 NOTREACHED();
531 break;
532 case DrawQuad::TEXTURE_CONTENT:
533 EnqueueTextureQuad(frame, TextureDrawQuad::MaterialCast(quad));
534 break;
535 case DrawQuad::TILED_CONTENT:
536 DrawTileQuad(frame, TileDrawQuad::MaterialCast(quad));
537 break;
538 case DrawQuad::YUV_VIDEO_CONTENT:
539 DrawYUVVideoQuad(frame, YUVVideoDrawQuad::MaterialCast(quad));
540 break;
544 void GLRenderer::DrawCheckerboardQuad(const DrawingFrame* frame,
545 const CheckerboardDrawQuad* quad) {
546 SetBlendEnabled(quad->ShouldDrawWithBlending());
548 const TileCheckerboardProgram* program = GetTileCheckerboardProgram();
549 DCHECK(program && (program->initialized() || IsContextLost()));
550 SetUseProgram(program->program());
552 SkColor color = quad->color;
553 GLC(gl_,
554 gl_->Uniform4f(program->fragment_shader().color_location(),
555 SkColorGetR(color) * (1.0f / 255.0f),
556 SkColorGetG(color) * (1.0f / 255.0f),
557 SkColorGetB(color) * (1.0f / 255.0f),
558 1));
560 const int checkerboard_width = 16;
561 float frequency = 1.0f / checkerboard_width;
563 gfx::Rect tile_rect = quad->rect;
564 float tex_offset_x = tile_rect.x() % checkerboard_width;
565 float tex_offset_y = tile_rect.y() % checkerboard_width;
566 float tex_scale_x = tile_rect.width();
567 float tex_scale_y = tile_rect.height();
568 GLC(gl_,
569 gl_->Uniform4f(program->fragment_shader().tex_transform_location(),
570 tex_offset_x,
571 tex_offset_y,
572 tex_scale_x,
573 tex_scale_y));
575 GLC(gl_,
576 gl_->Uniform1f(program->fragment_shader().frequency_location(),
577 frequency));
579 SetShaderOpacity(quad->opacity(),
580 program->fragment_shader().alpha_location());
581 DrawQuadGeometry(frame,
582 quad->quadTransform(),
583 quad->rect,
584 program->vertex_shader().matrix_location());
587 void GLRenderer::DrawDebugBorderQuad(const DrawingFrame* frame,
588 const DebugBorderDrawQuad* quad) {
589 SetBlendEnabled(quad->ShouldDrawWithBlending());
591 static float gl_matrix[16];
592 const DebugBorderProgram* program = GetDebugBorderProgram();
593 DCHECK(program && (program->initialized() || IsContextLost()));
594 SetUseProgram(program->program());
596 // Use the full quad_rect for debug quads to not move the edges based on
597 // partial swaps.
598 gfx::Rect layer_rect = quad->rect;
599 gfx::Transform render_matrix;
600 QuadRectTransform(&render_matrix, quad->quadTransform(), layer_rect);
601 GLRenderer::ToGLMatrix(&gl_matrix[0],
602 frame->projection_matrix * render_matrix);
603 GLC(gl_,
604 gl_->UniformMatrix4fv(
605 program->vertex_shader().matrix_location(), 1, false, &gl_matrix[0]));
607 SkColor color = quad->color;
608 float alpha = SkColorGetA(color) * (1.0f / 255.0f);
610 GLC(gl_,
611 gl_->Uniform4f(program->fragment_shader().color_location(),
612 (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
613 (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
614 (SkColorGetB(color) * (1.0f / 255.0f)) * alpha,
615 alpha));
617 GLC(gl_, gl_->LineWidth(quad->width));
619 // The indices for the line are stored in the same array as the triangle
620 // indices.
621 GLC(gl_, gl_->DrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, 0));
624 static skia::RefPtr<SkImage> ApplyImageFilter(
625 scoped_ptr<GLRenderer::ScopedUseGrContext> use_gr_context,
626 ResourceProvider* resource_provider,
627 const gfx::Point& origin,
628 const gfx::Vector2dF& scale,
629 SkImageFilter* filter,
630 ScopedResource* source_texture_resource) {
631 if (!filter)
632 return skia::RefPtr<SkImage>();
634 if (!use_gr_context)
635 return skia::RefPtr<SkImage>();
637 ResourceProvider::ScopedReadLockGL lock(resource_provider,
638 source_texture_resource->id());
640 // Wrap the source texture in a Ganesh platform texture.
641 GrBackendTextureDesc backend_texture_description;
642 backend_texture_description.fWidth = source_texture_resource->size().width();
643 backend_texture_description.fHeight =
644 source_texture_resource->size().height();
645 backend_texture_description.fConfig = kSkia8888_GrPixelConfig;
646 backend_texture_description.fTextureHandle = lock.texture_id();
647 backend_texture_description.fOrigin = kBottomLeft_GrSurfaceOrigin;
648 skia::RefPtr<GrTexture> texture =
649 skia::AdoptRef(use_gr_context->context()->wrapBackendTexture(
650 backend_texture_description));
651 if (!texture) {
652 TRACE_EVENT_INSTANT0("cc",
653 "ApplyImageFilter wrap background texture failed",
654 TRACE_EVENT_SCOPE_THREAD);
655 return skia::RefPtr<SkImage>();
658 SkImageInfo info =
659 SkImageInfo::MakeN32Premul(source_texture_resource->size().width(),
660 source_texture_resource->size().height());
661 // Place the platform texture inside an SkBitmap.
662 SkBitmap source;
663 source.setInfo(info);
664 skia::RefPtr<SkGrPixelRef> pixel_ref =
665 skia::AdoptRef(new SkGrPixelRef(info, texture.get()));
666 source.setPixelRef(pixel_ref.get());
668 // Create a scratch texture for backing store.
669 GrTextureDesc desc;
670 desc.fFlags = kRenderTarget_GrTextureFlagBit | kNoStencil_GrTextureFlagBit;
671 desc.fSampleCnt = 0;
672 desc.fWidth = source.width();
673 desc.fHeight = source.height();
674 desc.fConfig = kSkia8888_GrPixelConfig;
675 desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
676 skia::RefPtr<GrTexture> backing_store =
677 skia::AdoptRef(use_gr_context->context()->refScratchTexture(
678 desc, GrContext::kExact_ScratchTexMatch));
679 if (!backing_store) {
680 TRACE_EVENT_INSTANT0("cc",
681 "ApplyImageFilter scratch texture allocation failed",
682 TRACE_EVENT_SCOPE_THREAD);
683 return skia::RefPtr<SkImage>();
686 // Create surface to draw into.
687 skia::RefPtr<SkSurface> surface = skia::AdoptRef(
688 SkSurface::NewRenderTargetDirect(backing_store->asRenderTarget()));
689 skia::RefPtr<SkCanvas> canvas = skia::SharePtr(surface->getCanvas());
691 // Draw the source bitmap through the filter to the canvas.
692 SkPaint paint;
693 paint.setImageFilter(filter);
694 canvas->clear(SK_ColorTRANSPARENT);
696 canvas->translate(SkIntToScalar(-origin.x()), SkIntToScalar(-origin.y()));
697 canvas->scale(scale.x(), scale.y());
698 canvas->drawSprite(source, 0, 0, &paint);
700 skia::RefPtr<SkImage> image = skia::AdoptRef(surface->newImageSnapshot());
701 if (!image || !image->getTexture()) {
702 return skia::RefPtr<SkImage>();
705 // Flush the GrContext to ensure all buffered GL calls are drawn to the
706 // backing store before we access and return it, and have cc begin using the
707 // GL context again.
708 canvas->flush();
710 return image;
713 bool GLRenderer::CanApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode) {
714 return use_blend_equation_advanced_ ||
715 blend_mode == SkXfermode::kScreen_Mode ||
716 blend_mode == SkXfermode::kSrcOver_Mode;
719 void GLRenderer::ApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode) {
720 DCHECK(CanApplyBlendModeUsingBlendFunc(blend_mode));
722 // Any modes set here must be reset in RestoreBlendFuncToDefault
723 if (use_blend_equation_advanced_) {
724 GLenum equation = GL_FUNC_ADD;
726 switch (blend_mode) {
727 case SkXfermode::kScreen_Mode:
728 equation = GL_SCREEN_KHR;
729 break;
730 case SkXfermode::kOverlay_Mode:
731 equation = GL_OVERLAY_KHR;
732 break;
733 case SkXfermode::kDarken_Mode:
734 equation = GL_DARKEN_KHR;
735 break;
736 case SkXfermode::kLighten_Mode:
737 equation = GL_LIGHTEN_KHR;
738 break;
739 case SkXfermode::kColorDodge_Mode:
740 equation = GL_COLORDODGE_KHR;
741 break;
742 case SkXfermode::kColorBurn_Mode:
743 equation = GL_COLORBURN_KHR;
744 break;
745 case SkXfermode::kHardLight_Mode:
746 equation = GL_HARDLIGHT_KHR;
747 break;
748 case SkXfermode::kSoftLight_Mode:
749 equation = GL_SOFTLIGHT_KHR;
750 break;
751 case SkXfermode::kDifference_Mode:
752 equation = GL_DIFFERENCE_KHR;
753 break;
754 case SkXfermode::kExclusion_Mode:
755 equation = GL_EXCLUSION_KHR;
756 break;
757 case SkXfermode::kMultiply_Mode:
758 equation = GL_MULTIPLY_KHR;
759 break;
760 case SkXfermode::kHue_Mode:
761 equation = GL_HSL_HUE_KHR;
762 break;
763 case SkXfermode::kSaturation_Mode:
764 equation = GL_HSL_SATURATION_KHR;
765 break;
766 case SkXfermode::kColor_Mode:
767 equation = GL_HSL_COLOR_KHR;
768 break;
769 case SkXfermode::kLuminosity_Mode:
770 equation = GL_HSL_LUMINOSITY_KHR;
771 break;
772 default:
773 return;
776 GLC(gl_, gl_->BlendEquation(equation));
777 } else {
778 if (blend_mode == SkXfermode::kScreen_Mode) {
779 GLC(gl_, gl_->BlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE));
784 void GLRenderer::RestoreBlendFuncToDefault(SkXfermode::Mode blend_mode) {
785 if (blend_mode == SkXfermode::kSrcOver_Mode)
786 return;
788 if (use_blend_equation_advanced_) {
789 GLC(gl_, gl_->BlendEquation(GL_FUNC_ADD));
790 } else {
791 GLC(gl_, gl_->BlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA));
795 bool GLRenderer::ShouldApplyBackgroundFilters(DrawingFrame* frame,
796 const RenderPassDrawQuad* quad) {
797 if (quad->background_filters.IsEmpty())
798 return false;
800 // TODO(danakj): We only allow background filters on an opaque render surface
801 // because other surfaces may contain translucent pixels, and the contents
802 // behind those translucent pixels wouldn't have the filter applied.
803 if (frame->current_render_pass->has_transparent_background)
804 return false;
806 // TODO(ajuma): Add support for reference filters once
807 // FilterOperations::GetOutsets supports reference filters.
808 if (quad->background_filters.HasReferenceFilter())
809 return false;
810 return true;
813 gfx::Rect GLRenderer::GetBackdropBoundingBoxForRenderPassQuad(
814 DrawingFrame* frame,
815 const RenderPassDrawQuad* quad,
816 const gfx::Transform& contents_device_transform,
817 bool use_aa) {
818 gfx::Rect backdrop_rect = gfx::ToEnclosingRect(MathUtil::MapClippedRect(
819 contents_device_transform, SharedGeometryQuad().BoundingBox()));
821 if (ShouldApplyBackgroundFilters(frame, quad)) {
822 int top, right, bottom, left;
823 quad->background_filters.GetOutsets(&top, &right, &bottom, &left);
824 backdrop_rect.Inset(-left, -top, -right, -bottom);
827 if (!backdrop_rect.IsEmpty() && use_aa) {
828 const int kOutsetForAntialiasing = 1;
829 backdrop_rect.Inset(-kOutsetForAntialiasing, -kOutsetForAntialiasing);
832 backdrop_rect.Intersect(MoveFromDrawToWindowSpace(
833 frame, frame->current_render_pass->output_rect));
834 return backdrop_rect;
837 scoped_ptr<ScopedResource> GLRenderer::GetBackdropTexture(
838 const gfx::Rect& bounding_rect) {
839 scoped_ptr<ScopedResource> device_background_texture =
840 ScopedResource::Create(resource_provider_);
841 // CopyTexImage2D fails when called on a texture having immutable storage.
842 device_background_texture->Allocate(
843 bounding_rect.size(), ResourceProvider::TextureHintDefault, RGBA_8888);
845 ResourceProvider::ScopedWriteLockGL lock(resource_provider_,
846 device_background_texture->id());
847 GetFramebufferTexture(
848 lock.texture_id(), device_background_texture->format(), bounding_rect);
850 return device_background_texture.Pass();
853 skia::RefPtr<SkImage> GLRenderer::ApplyBackgroundFilters(
854 DrawingFrame* frame,
855 const RenderPassDrawQuad* quad,
856 ScopedResource* background_texture) {
857 DCHECK(ShouldApplyBackgroundFilters(frame, quad));
858 skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
859 quad->background_filters, background_texture->size());
861 skia::RefPtr<SkImage> background_with_filters =
862 ApplyImageFilter(ScopedUseGrContext::Create(this, frame),
863 resource_provider_,
864 quad->rect.origin(),
865 quad->filters_scale,
866 filter.get(),
867 background_texture);
868 return background_with_filters;
871 void GLRenderer::DrawRenderPassQuad(DrawingFrame* frame,
872 const RenderPassDrawQuad* quad) {
873 ScopedResource* contents_texture =
874 render_pass_textures_.get(quad->render_pass_id);
875 if (!contents_texture || !contents_texture->id())
876 return;
878 gfx::Transform quad_rect_matrix;
879 QuadRectTransform(&quad_rect_matrix, quad->quadTransform(), quad->rect);
880 gfx::Transform contents_device_transform =
881 frame->window_matrix * frame->projection_matrix * quad_rect_matrix;
882 contents_device_transform.FlattenTo2d();
884 // Can only draw surface if device matrix is invertible.
885 if (!contents_device_transform.IsInvertible())
886 return;
888 gfx::QuadF surface_quad = SharedGeometryQuad();
889 float edge[24];
890 bool use_aa = settings_->allow_antialiasing &&
891 ShouldAntialiasQuad(contents_device_transform, quad,
892 settings_->force_antialiasing);
894 if (use_aa)
895 SetupQuadForAntialiasing(contents_device_transform, quad,
896 &surface_quad, edge);
898 SkXfermode::Mode blend_mode = quad->shared_quad_state->blend_mode;
899 bool use_shaders_for_blending =
900 !CanApplyBlendModeUsingBlendFunc(blend_mode) ||
901 ShouldApplyBackgroundFilters(frame, quad) ||
902 settings_->force_blending_with_shaders;
904 scoped_ptr<ScopedResource> background_texture;
905 skia::RefPtr<SkImage> background_image;
906 gfx::Rect background_rect;
907 if (use_shaders_for_blending) {
908 // Compute a bounding box around the pixels that will be visible through
909 // the quad.
910 background_rect = GetBackdropBoundingBoxForRenderPassQuad(
911 frame, quad, contents_device_transform, use_aa);
913 if (!background_rect.IsEmpty()) {
914 // The pixels from the filtered background should completely replace the
915 // current pixel values.
916 if (blend_enabled())
917 SetBlendEnabled(false);
919 // Read the pixels in the bounding box into a buffer R.
920 // This function allocates a texture, which should contribute to the
921 // amount of memory used by render surfaces:
922 // LayerTreeHost::CalculateMemoryForRenderSurfaces.
923 background_texture = GetBackdropTexture(background_rect);
925 if (ShouldApplyBackgroundFilters(frame, quad) && background_texture) {
926 // Apply the background filters to R, so that it is applied in the
927 // pixels' coordinate space.
928 background_image =
929 ApplyBackgroundFilters(frame, quad, background_texture.get());
933 if (!background_texture) {
934 // Something went wrong with reading the backdrop.
935 DCHECK(!background_image);
936 use_shaders_for_blending = false;
937 } else if (background_image) {
938 background_texture.reset();
939 } else if (CanApplyBlendModeUsingBlendFunc(blend_mode) &&
940 ShouldApplyBackgroundFilters(frame, quad)) {
941 // Something went wrong with applying background filters to the backdrop.
942 use_shaders_for_blending = false;
943 background_texture.reset();
947 SetBlendEnabled(
948 !use_shaders_for_blending &&
949 (quad->ShouldDrawWithBlending() || !IsDefaultBlendMode(blend_mode)));
951 // TODO(senorblanco): Cache this value so that we don't have to do it for both
952 // the surface and its replica. Apply filters to the contents texture.
953 skia::RefPtr<SkImage> filter_image;
954 SkScalar color_matrix[20];
955 bool use_color_matrix = false;
956 if (!quad->filters.IsEmpty()) {
957 skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
958 quad->filters, contents_texture->size());
959 if (filter) {
960 skia::RefPtr<SkColorFilter> cf;
963 SkColorFilter* colorfilter_rawptr = NULL;
964 filter->asColorFilter(&colorfilter_rawptr);
965 cf = skia::AdoptRef(colorfilter_rawptr);
968 if (cf && cf->asColorMatrix(color_matrix) && !filter->getInput(0)) {
969 // We have a single color matrix as a filter; apply it locally
970 // in the compositor.
971 use_color_matrix = true;
972 } else {
973 filter_image = ApplyImageFilter(ScopedUseGrContext::Create(this, frame),
974 resource_provider_,
975 quad->rect.origin(),
976 quad->filters_scale,
977 filter.get(),
978 contents_texture);
983 scoped_ptr<ResourceProvider::ScopedSamplerGL> mask_resource_lock;
984 unsigned mask_texture_id = 0;
985 SamplerType mask_sampler = SamplerTypeNA;
986 if (quad->mask_resource_id) {
987 mask_resource_lock.reset(new ResourceProvider::ScopedSamplerGL(
988 resource_provider_, quad->mask_resource_id, GL_TEXTURE1, GL_LINEAR));
989 mask_texture_id = mask_resource_lock->texture_id();
990 mask_sampler = SamplerTypeFromTextureTarget(mask_resource_lock->target());
993 scoped_ptr<ResourceProvider::ScopedSamplerGL> contents_resource_lock;
994 if (filter_image) {
995 GrTexture* texture = filter_image->getTexture();
996 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
997 gl_->BindTexture(GL_TEXTURE_2D, texture->getTextureHandle());
998 } else {
999 contents_resource_lock =
1000 make_scoped_ptr(new ResourceProvider::ScopedSamplerGL(
1001 resource_provider_, contents_texture->id(), GL_LINEAR));
1002 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
1003 contents_resource_lock->target());
1006 if (!use_shaders_for_blending) {
1007 if (!use_blend_equation_advanced_coherent_ && use_blend_equation_advanced_)
1008 GLC(gl_, gl_->BlendBarrierKHR());
1010 ApplyBlendModeUsingBlendFunc(blend_mode);
1013 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1014 gl_,
1015 &highp_threshold_cache_,
1016 highp_threshold_min_,
1017 quad->shared_quad_state->visible_content_rect.bottom_right());
1019 int shader_quad_location = -1;
1020 int shader_edge_location = -1;
1021 int shader_viewport_location = -1;
1022 int shader_mask_sampler_location = -1;
1023 int shader_mask_tex_coord_scale_location = -1;
1024 int shader_mask_tex_coord_offset_location = -1;
1025 int shader_matrix_location = -1;
1026 int shader_alpha_location = -1;
1027 int shader_color_matrix_location = -1;
1028 int shader_color_offset_location = -1;
1029 int shader_tex_transform_location = -1;
1030 int shader_backdrop_location = -1;
1031 int shader_backdrop_rect_location = -1;
1033 DCHECK_EQ(background_texture || background_image, use_shaders_for_blending);
1034 BlendMode shader_blend_mode = use_shaders_for_blending
1035 ? BlendModeFromSkXfermode(blend_mode)
1036 : BlendModeNone;
1038 if (use_aa && mask_texture_id && !use_color_matrix) {
1039 const RenderPassMaskProgramAA* program = GetRenderPassMaskProgramAA(
1040 tex_coord_precision, mask_sampler, shader_blend_mode);
1041 SetUseProgram(program->program());
1042 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1044 shader_quad_location = program->vertex_shader().quad_location();
1045 shader_edge_location = program->vertex_shader().edge_location();
1046 shader_viewport_location = program->vertex_shader().viewport_location();
1047 shader_mask_sampler_location =
1048 program->fragment_shader().mask_sampler_location();
1049 shader_mask_tex_coord_scale_location =
1050 program->fragment_shader().mask_tex_coord_scale_location();
1051 shader_mask_tex_coord_offset_location =
1052 program->fragment_shader().mask_tex_coord_offset_location();
1053 shader_matrix_location = program->vertex_shader().matrix_location();
1054 shader_alpha_location = program->fragment_shader().alpha_location();
1055 shader_tex_transform_location =
1056 program->vertex_shader().tex_transform_location();
1057 shader_backdrop_location = program->fragment_shader().backdrop_location();
1058 shader_backdrop_rect_location =
1059 program->fragment_shader().backdrop_rect_location();
1060 } else if (!use_aa && mask_texture_id && !use_color_matrix) {
1061 const RenderPassMaskProgram* program = GetRenderPassMaskProgram(
1062 tex_coord_precision, mask_sampler, shader_blend_mode);
1063 SetUseProgram(program->program());
1064 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1066 shader_mask_sampler_location =
1067 program->fragment_shader().mask_sampler_location();
1068 shader_mask_tex_coord_scale_location =
1069 program->fragment_shader().mask_tex_coord_scale_location();
1070 shader_mask_tex_coord_offset_location =
1071 program->fragment_shader().mask_tex_coord_offset_location();
1072 shader_matrix_location = program->vertex_shader().matrix_location();
1073 shader_alpha_location = program->fragment_shader().alpha_location();
1074 shader_tex_transform_location =
1075 program->vertex_shader().tex_transform_location();
1076 shader_backdrop_location = program->fragment_shader().backdrop_location();
1077 shader_backdrop_rect_location =
1078 program->fragment_shader().backdrop_rect_location();
1079 } else if (use_aa && !mask_texture_id && !use_color_matrix) {
1080 const RenderPassProgramAA* program =
1081 GetRenderPassProgramAA(tex_coord_precision, shader_blend_mode);
1082 SetUseProgram(program->program());
1083 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1085 shader_quad_location = program->vertex_shader().quad_location();
1086 shader_edge_location = program->vertex_shader().edge_location();
1087 shader_viewport_location = program->vertex_shader().viewport_location();
1088 shader_matrix_location = program->vertex_shader().matrix_location();
1089 shader_alpha_location = program->fragment_shader().alpha_location();
1090 shader_tex_transform_location =
1091 program->vertex_shader().tex_transform_location();
1092 shader_backdrop_location = program->fragment_shader().backdrop_location();
1093 shader_backdrop_rect_location =
1094 program->fragment_shader().backdrop_rect_location();
1095 } else if (use_aa && mask_texture_id && use_color_matrix) {
1096 const RenderPassMaskColorMatrixProgramAA* program =
1097 GetRenderPassMaskColorMatrixProgramAA(
1098 tex_coord_precision, mask_sampler, shader_blend_mode);
1099 SetUseProgram(program->program());
1100 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1102 shader_matrix_location = program->vertex_shader().matrix_location();
1103 shader_quad_location = program->vertex_shader().quad_location();
1104 shader_tex_transform_location =
1105 program->vertex_shader().tex_transform_location();
1106 shader_edge_location = program->vertex_shader().edge_location();
1107 shader_viewport_location = program->vertex_shader().viewport_location();
1108 shader_alpha_location = program->fragment_shader().alpha_location();
1109 shader_mask_sampler_location =
1110 program->fragment_shader().mask_sampler_location();
1111 shader_mask_tex_coord_scale_location =
1112 program->fragment_shader().mask_tex_coord_scale_location();
1113 shader_mask_tex_coord_offset_location =
1114 program->fragment_shader().mask_tex_coord_offset_location();
1115 shader_color_matrix_location =
1116 program->fragment_shader().color_matrix_location();
1117 shader_color_offset_location =
1118 program->fragment_shader().color_offset_location();
1119 shader_backdrop_location = program->fragment_shader().backdrop_location();
1120 shader_backdrop_rect_location =
1121 program->fragment_shader().backdrop_rect_location();
1122 } else if (use_aa && !mask_texture_id && use_color_matrix) {
1123 const RenderPassColorMatrixProgramAA* program =
1124 GetRenderPassColorMatrixProgramAA(tex_coord_precision,
1125 shader_blend_mode);
1126 SetUseProgram(program->program());
1127 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1129 shader_matrix_location = program->vertex_shader().matrix_location();
1130 shader_quad_location = program->vertex_shader().quad_location();
1131 shader_tex_transform_location =
1132 program->vertex_shader().tex_transform_location();
1133 shader_edge_location = program->vertex_shader().edge_location();
1134 shader_viewport_location = program->vertex_shader().viewport_location();
1135 shader_alpha_location = program->fragment_shader().alpha_location();
1136 shader_color_matrix_location =
1137 program->fragment_shader().color_matrix_location();
1138 shader_color_offset_location =
1139 program->fragment_shader().color_offset_location();
1140 shader_backdrop_location = program->fragment_shader().backdrop_location();
1141 shader_backdrop_rect_location =
1142 program->fragment_shader().backdrop_rect_location();
1143 } else if (!use_aa && mask_texture_id && use_color_matrix) {
1144 const RenderPassMaskColorMatrixProgram* program =
1145 GetRenderPassMaskColorMatrixProgram(
1146 tex_coord_precision, mask_sampler, shader_blend_mode);
1147 SetUseProgram(program->program());
1148 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1150 shader_matrix_location = program->vertex_shader().matrix_location();
1151 shader_tex_transform_location =
1152 program->vertex_shader().tex_transform_location();
1153 shader_mask_sampler_location =
1154 program->fragment_shader().mask_sampler_location();
1155 shader_mask_tex_coord_scale_location =
1156 program->fragment_shader().mask_tex_coord_scale_location();
1157 shader_mask_tex_coord_offset_location =
1158 program->fragment_shader().mask_tex_coord_offset_location();
1159 shader_alpha_location = program->fragment_shader().alpha_location();
1160 shader_color_matrix_location =
1161 program->fragment_shader().color_matrix_location();
1162 shader_color_offset_location =
1163 program->fragment_shader().color_offset_location();
1164 shader_backdrop_location = program->fragment_shader().backdrop_location();
1165 shader_backdrop_rect_location =
1166 program->fragment_shader().backdrop_rect_location();
1167 } else if (!use_aa && !mask_texture_id && use_color_matrix) {
1168 const RenderPassColorMatrixProgram* program =
1169 GetRenderPassColorMatrixProgram(tex_coord_precision, shader_blend_mode);
1170 SetUseProgram(program->program());
1171 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1173 shader_matrix_location = program->vertex_shader().matrix_location();
1174 shader_tex_transform_location =
1175 program->vertex_shader().tex_transform_location();
1176 shader_alpha_location = program->fragment_shader().alpha_location();
1177 shader_color_matrix_location =
1178 program->fragment_shader().color_matrix_location();
1179 shader_color_offset_location =
1180 program->fragment_shader().color_offset_location();
1181 shader_backdrop_location = program->fragment_shader().backdrop_location();
1182 shader_backdrop_rect_location =
1183 program->fragment_shader().backdrop_rect_location();
1184 } else {
1185 const RenderPassProgram* program =
1186 GetRenderPassProgram(tex_coord_precision, shader_blend_mode);
1187 SetUseProgram(program->program());
1188 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1190 shader_matrix_location = program->vertex_shader().matrix_location();
1191 shader_alpha_location = program->fragment_shader().alpha_location();
1192 shader_tex_transform_location =
1193 program->vertex_shader().tex_transform_location();
1194 shader_backdrop_location = program->fragment_shader().backdrop_location();
1195 shader_backdrop_rect_location =
1196 program->fragment_shader().backdrop_rect_location();
1198 float tex_scale_x =
1199 quad->rect.width() / static_cast<float>(contents_texture->size().width());
1200 float tex_scale_y = quad->rect.height() /
1201 static_cast<float>(contents_texture->size().height());
1202 DCHECK_LE(tex_scale_x, 1.0f);
1203 DCHECK_LE(tex_scale_y, 1.0f);
1205 DCHECK(shader_tex_transform_location != -1 || IsContextLost());
1206 // Flip the content vertically in the shader, as the RenderPass input
1207 // texture is already oriented the same way as the framebuffer, but the
1208 // projection transform does a flip.
1209 GLC(gl_,
1210 gl_->Uniform4f(shader_tex_transform_location,
1211 0.0f,
1212 tex_scale_y,
1213 tex_scale_x,
1214 -tex_scale_y));
1216 GLint last_texture_unit = 0;
1217 if (shader_mask_sampler_location != -1) {
1218 DCHECK_NE(shader_mask_tex_coord_scale_location, 1);
1219 DCHECK_NE(shader_mask_tex_coord_offset_location, 1);
1220 GLC(gl_, gl_->Uniform1i(shader_mask_sampler_location, 1));
1222 gfx::RectF mask_uv_rect = quad->MaskUVRect();
1223 if (mask_sampler != SamplerType2D) {
1224 mask_uv_rect.Scale(quad->mask_texture_size.width(),
1225 quad->mask_texture_size.height());
1228 // Mask textures are oriented vertically flipped relative to the framebuffer
1229 // and the RenderPass contents texture, so we flip the tex coords from the
1230 // RenderPass texture to find the mask texture coords.
1231 GLC(gl_,
1232 gl_->Uniform2f(shader_mask_tex_coord_offset_location,
1233 mask_uv_rect.x(),
1234 mask_uv_rect.bottom()));
1235 GLC(gl_,
1236 gl_->Uniform2f(shader_mask_tex_coord_scale_location,
1237 mask_uv_rect.width() / tex_scale_x,
1238 -mask_uv_rect.height() / tex_scale_y));
1240 last_texture_unit = 1;
1243 if (shader_edge_location != -1)
1244 GLC(gl_, gl_->Uniform3fv(shader_edge_location, 8, edge));
1246 if (shader_viewport_location != -1) {
1247 float viewport[4] = {static_cast<float>(viewport_.x()),
1248 static_cast<float>(viewport_.y()),
1249 static_cast<float>(viewport_.width()),
1250 static_cast<float>(viewport_.height()), };
1251 GLC(gl_, gl_->Uniform4fv(shader_viewport_location, 1, viewport));
1254 if (shader_color_matrix_location != -1) {
1255 float matrix[16];
1256 for (int i = 0; i < 4; ++i) {
1257 for (int j = 0; j < 4; ++j)
1258 matrix[i * 4 + j] = SkScalarToFloat(color_matrix[j * 5 + i]);
1260 GLC(gl_,
1261 gl_->UniformMatrix4fv(shader_color_matrix_location, 1, false, matrix));
1263 static const float kScale = 1.0f / 255.0f;
1264 if (shader_color_offset_location != -1) {
1265 float offset[4];
1266 for (int i = 0; i < 4; ++i)
1267 offset[i] = SkScalarToFloat(color_matrix[i * 5 + 4]) * kScale;
1269 GLC(gl_, gl_->Uniform4fv(shader_color_offset_location, 1, offset));
1272 scoped_ptr<ResourceProvider::ScopedSamplerGL> shader_background_sampler_lock;
1273 if (shader_backdrop_location != -1) {
1274 DCHECK(background_texture || background_image);
1275 DCHECK_NE(shader_backdrop_location, 0);
1276 DCHECK_NE(shader_backdrop_rect_location, 0);
1278 GLC(gl_, gl_->Uniform1i(shader_backdrop_location, ++last_texture_unit));
1280 GLC(gl_,
1281 gl_->Uniform4f(shader_backdrop_rect_location,
1282 background_rect.x(),
1283 background_rect.y(),
1284 background_rect.width(),
1285 background_rect.height()));
1287 if (background_image) {
1288 GrTexture* texture = background_image->getTexture();
1289 GLC(gl_, gl_->ActiveTexture(GL_TEXTURE0 + last_texture_unit));
1290 gl_->BindTexture(GL_TEXTURE_2D, texture->getTextureHandle());
1291 GLC(gl_, gl_->ActiveTexture(GL_TEXTURE0));
1292 } else {
1293 shader_background_sampler_lock = make_scoped_ptr(
1294 new ResourceProvider::ScopedSamplerGL(resource_provider_,
1295 background_texture->id(),
1296 GL_TEXTURE0 + last_texture_unit,
1297 GL_LINEAR));
1298 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
1299 shader_background_sampler_lock->target());
1303 SetShaderOpacity(quad->opacity(), shader_alpha_location);
1304 SetShaderQuadF(surface_quad, shader_quad_location);
1305 DrawQuadGeometry(
1306 frame, quad->quadTransform(), quad->rect, shader_matrix_location);
1308 // Flush the compositor context before the filter bitmap goes out of
1309 // scope, so the draw gets processed before the filter texture gets deleted.
1310 if (filter_image)
1311 GLC(gl_, gl_->Flush());
1313 if (!use_shaders_for_blending)
1314 RestoreBlendFuncToDefault(blend_mode);
1317 struct SolidColorProgramUniforms {
1318 unsigned program;
1319 unsigned matrix_location;
1320 unsigned viewport_location;
1321 unsigned quad_location;
1322 unsigned edge_location;
1323 unsigned color_location;
1326 template <class T>
1327 static void SolidColorUniformLocation(T program,
1328 SolidColorProgramUniforms* uniforms) {
1329 uniforms->program = program->program();
1330 uniforms->matrix_location = program->vertex_shader().matrix_location();
1331 uniforms->viewport_location = program->vertex_shader().viewport_location();
1332 uniforms->quad_location = program->vertex_shader().quad_location();
1333 uniforms->edge_location = program->vertex_shader().edge_location();
1334 uniforms->color_location = program->fragment_shader().color_location();
1337 static gfx::QuadF GetDeviceQuadWithAntialiasingOnExteriorEdges(
1338 const LayerQuad& device_layer_edges,
1339 const gfx::Transform& device_transform,
1340 const DrawQuad* quad) {
1341 gfx::Rect tile_rect = quad->visible_rect;
1342 gfx::PointF bottom_right = tile_rect.bottom_right();
1343 gfx::PointF bottom_left = tile_rect.bottom_left();
1344 gfx::PointF top_left = tile_rect.origin();
1345 gfx::PointF top_right = tile_rect.top_right();
1346 bool clipped = false;
1348 // Map points to device space. We ignore |clipped|, since the result of
1349 // |MapPoint()| still produces a valid point to draw the quad with. When
1350 // clipped, the point will be outside of the viewport. See crbug.com/416367.
1351 bottom_right = MathUtil::MapPoint(device_transform, bottom_right, &clipped);
1352 bottom_left = MathUtil::MapPoint(device_transform, bottom_left, &clipped);
1353 top_left = MathUtil::MapPoint(device_transform, top_left, &clipped);
1354 top_right = MathUtil::MapPoint(device_transform, top_right, &clipped);
1356 LayerQuad::Edge bottom_edge(bottom_right, bottom_left);
1357 LayerQuad::Edge left_edge(bottom_left, top_left);
1358 LayerQuad::Edge top_edge(top_left, top_right);
1359 LayerQuad::Edge right_edge(top_right, bottom_right);
1361 // Only apply anti-aliasing to edges not clipped by culling or scissoring.
1362 if (quad->IsTopEdge() && tile_rect.y() == quad->rect.y())
1363 top_edge = device_layer_edges.top();
1364 if (quad->IsLeftEdge() && tile_rect.x() == quad->rect.x())
1365 left_edge = device_layer_edges.left();
1366 if (quad->IsRightEdge() && tile_rect.right() == quad->rect.right())
1367 right_edge = device_layer_edges.right();
1368 if (quad->IsBottomEdge() && tile_rect.bottom() == quad->rect.bottom())
1369 bottom_edge = device_layer_edges.bottom();
1371 float sign = gfx::QuadF(tile_rect).IsCounterClockwise() ? -1 : 1;
1372 bottom_edge.scale(sign);
1373 left_edge.scale(sign);
1374 top_edge.scale(sign);
1375 right_edge.scale(sign);
1377 // Create device space quad.
1378 return LayerQuad(left_edge, top_edge, right_edge, bottom_edge).ToQuadF();
1381 // static
1382 bool GLRenderer::ShouldAntialiasQuad(const gfx::Transform& device_transform,
1383 const DrawQuad* quad,
1384 bool force_antialiasing) {
1385 bool is_render_pass_quad = (quad->material == DrawQuad::RENDER_PASS);
1386 // For render pass quads, |device_transform| already contains quad's rect.
1387 // TODO(rosca@adobe.com): remove branching on is_render_pass_quad
1388 // crbug.com/429702
1389 if (!is_render_pass_quad && !quad->IsEdge())
1390 return false;
1391 gfx::RectF content_rect =
1392 is_render_pass_quad ? QuadVertexRect() : quad->visibleContentRect();
1394 bool clipped = false;
1395 gfx::QuadF device_layer_quad =
1396 MathUtil::MapQuad(device_transform, gfx::QuadF(content_rect), &clipped);
1398 if (device_layer_quad.BoundingBox().IsEmpty())
1399 return false;
1401 bool is_axis_aligned_in_target = device_layer_quad.IsRectilinear();
1402 bool is_nearest_rect_within_epsilon =
1403 is_axis_aligned_in_target &&
1404 gfx::IsNearestRectWithinDistance(device_layer_quad.BoundingBox(),
1405 kAntiAliasingEpsilon);
1406 // AAing clipped quads is not supported by the code yet.
1407 bool use_aa = !clipped && !is_nearest_rect_within_epsilon;
1408 return use_aa || force_antialiasing;
1411 // static
1412 void GLRenderer::SetupQuadForAntialiasing(
1413 const gfx::Transform& device_transform,
1414 const DrawQuad* quad,
1415 gfx::QuadF* local_quad,
1416 float edge[24]) {
1417 bool is_render_pass_quad = (quad->material == DrawQuad::RENDER_PASS);
1418 gfx::RectF content_rect =
1419 is_render_pass_quad ? QuadVertexRect() : quad->visibleContentRect();
1421 bool clipped = false;
1422 gfx::QuadF device_layer_quad =
1423 MathUtil::MapQuad(device_transform, gfx::QuadF(content_rect), &clipped);
1425 LayerQuad device_layer_bounds(gfx::QuadF(device_layer_quad.BoundingBox()));
1426 device_layer_bounds.InflateAntiAliasingDistance();
1428 LayerQuad device_layer_edges(device_layer_quad);
1429 device_layer_edges.InflateAntiAliasingDistance();
1431 device_layer_edges.ToFloatArray(edge);
1432 device_layer_bounds.ToFloatArray(&edge[12]);
1434 bool use_aa_on_all_four_edges =
1435 is_render_pass_quad ||
1436 (quad->IsTopEdge() && quad->IsLeftEdge() && quad->IsBottomEdge() &&
1437 quad->IsRightEdge() && quad->visible_rect == quad->rect);
1439 gfx::QuadF device_quad =
1440 use_aa_on_all_four_edges
1441 ? device_layer_edges.ToQuadF()
1442 : GetDeviceQuadWithAntialiasingOnExteriorEdges(
1443 device_layer_edges, device_transform, quad);
1445 // Map device space quad to local space. device_transform has no 3d
1446 // component since it was flattened, so we don't need to project. We should
1447 // have already checked that the transform was uninvertible above.
1448 gfx::Transform inverse_device_transform(gfx::Transform::kSkipInitialization);
1449 bool did_invert = device_transform.GetInverse(&inverse_device_transform);
1450 DCHECK(did_invert);
1451 *local_quad =
1452 MathUtil::MapQuad(inverse_device_transform, device_quad, &clipped);
1453 // We should not DCHECK(!clipped) here, because anti-aliasing inflation may
1454 // cause device_quad to become clipped. To our knowledge this scenario does
1455 // not need to be handled differently than the unclipped case.
1458 void GLRenderer::DrawSolidColorQuad(const DrawingFrame* frame,
1459 const SolidColorDrawQuad* quad) {
1460 gfx::Rect tile_rect = quad->visible_rect;
1462 SkColor color = quad->color;
1463 float opacity = quad->opacity();
1464 float alpha = (SkColorGetA(color) * (1.0f / 255.0f)) * opacity;
1466 // Early out if alpha is small enough that quad doesn't contribute to output.
1467 if (alpha < std::numeric_limits<float>::epsilon() &&
1468 quad->ShouldDrawWithBlending())
1469 return;
1471 gfx::Transform device_transform =
1472 frame->window_matrix * frame->projection_matrix * quad->quadTransform();
1473 device_transform.FlattenTo2d();
1474 if (!device_transform.IsInvertible())
1475 return;
1477 bool force_aa = false;
1478 gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1479 float edge[24];
1480 bool use_aa = settings_->allow_antialiasing &&
1481 !quad->force_anti_aliasing_off &&
1482 ShouldAntialiasQuad(device_transform, quad, force_aa);
1484 SolidColorProgramUniforms uniforms;
1485 if (use_aa) {
1486 SetupQuadForAntialiasing(device_transform, quad, &local_quad, edge);
1487 SolidColorUniformLocation(GetSolidColorProgramAA(), &uniforms);
1488 } else {
1489 SolidColorUniformLocation(GetSolidColorProgram(), &uniforms);
1491 SetUseProgram(uniforms.program);
1493 GLC(gl_,
1494 gl_->Uniform4f(uniforms.color_location,
1495 (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
1496 (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
1497 (SkColorGetB(color) * (1.0f / 255.0f)) * alpha,
1498 alpha));
1499 if (use_aa) {
1500 float viewport[4] = {static_cast<float>(viewport_.x()),
1501 static_cast<float>(viewport_.y()),
1502 static_cast<float>(viewport_.width()),
1503 static_cast<float>(viewport_.height()), };
1504 GLC(gl_, gl_->Uniform4fv(uniforms.viewport_location, 1, viewport));
1505 GLC(gl_, gl_->Uniform3fv(uniforms.edge_location, 8, edge));
1508 // Enable blending when the quad properties require it or if we decided
1509 // to use antialiasing.
1510 SetBlendEnabled(quad->ShouldDrawWithBlending() || use_aa);
1512 // Normalize to tile_rect.
1513 local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1515 SetShaderQuadF(local_quad, uniforms.quad_location);
1517 // The transform and vertex data are used to figure out the extents that the
1518 // un-antialiased quad should have and which vertex this is and the float
1519 // quad passed in via uniform is the actual geometry that gets used to draw
1520 // it. This is why this centered rect is used and not the original quad_rect.
1521 gfx::RectF centered_rect(
1522 gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1523 tile_rect.size());
1524 DrawQuadGeometry(
1525 frame, quad->quadTransform(), centered_rect, uniforms.matrix_location);
1528 struct TileProgramUniforms {
1529 unsigned program;
1530 unsigned matrix_location;
1531 unsigned viewport_location;
1532 unsigned quad_location;
1533 unsigned edge_location;
1534 unsigned vertex_tex_transform_location;
1535 unsigned sampler_location;
1536 unsigned fragment_tex_transform_location;
1537 unsigned alpha_location;
1540 template <class T>
1541 static void TileUniformLocation(T program, TileProgramUniforms* uniforms) {
1542 uniforms->program = program->program();
1543 uniforms->matrix_location = program->vertex_shader().matrix_location();
1544 uniforms->viewport_location = program->vertex_shader().viewport_location();
1545 uniforms->quad_location = program->vertex_shader().quad_location();
1546 uniforms->edge_location = program->vertex_shader().edge_location();
1547 uniforms->vertex_tex_transform_location =
1548 program->vertex_shader().vertex_tex_transform_location();
1550 uniforms->sampler_location = program->fragment_shader().sampler_location();
1551 uniforms->alpha_location = program->fragment_shader().alpha_location();
1552 uniforms->fragment_tex_transform_location =
1553 program->fragment_shader().fragment_tex_transform_location();
1556 void GLRenderer::DrawTileQuad(const DrawingFrame* frame,
1557 const TileDrawQuad* quad) {
1558 DrawContentQuad(frame, quad, quad->resource_id);
1561 void GLRenderer::DrawContentQuad(const DrawingFrame* frame,
1562 const ContentDrawQuadBase* quad,
1563 ResourceProvider::ResourceId resource_id) {
1564 gfx::Transform device_transform =
1565 frame->window_matrix * frame->projection_matrix * quad->quadTransform();
1566 device_transform.FlattenTo2d();
1568 bool use_aa = settings_->allow_antialiasing &&
1569 ShouldAntialiasQuad(device_transform, quad, false);
1571 // TODO(timav): simplify coordinate transformations in DrawContentQuadAA
1572 // similar to the way DrawContentQuadNoAA works and then consider
1573 // combining DrawContentQuadAA and DrawContentQuadNoAA into one method.
1574 if (use_aa)
1575 DrawContentQuadAA(frame, quad, resource_id, device_transform);
1576 else
1577 DrawContentQuadNoAA(frame, quad, resource_id);
1580 void GLRenderer::DrawContentQuadAA(const DrawingFrame* frame,
1581 const ContentDrawQuadBase* quad,
1582 ResourceProvider::ResourceId resource_id,
1583 const gfx::Transform& device_transform) {
1584 if (!device_transform.IsInvertible())
1585 return;
1587 gfx::Rect tile_rect = quad->visible_rect;
1589 gfx::RectF tex_coord_rect = MathUtil::ScaleRectProportional(
1590 quad->tex_coord_rect, quad->rect, tile_rect);
1591 float tex_to_geom_scale_x = quad->rect.width() / quad->tex_coord_rect.width();
1592 float tex_to_geom_scale_y =
1593 quad->rect.height() / quad->tex_coord_rect.height();
1595 gfx::RectF clamp_geom_rect(tile_rect);
1596 gfx::RectF clamp_tex_rect(tex_coord_rect);
1597 // Clamp texture coordinates to avoid sampling outside the layer
1598 // by deflating the tile region half a texel or half a texel
1599 // minus epsilon for one pixel layers. The resulting clamp region
1600 // is mapped to the unit square by the vertex shader and mapped
1601 // back to normalized texture coordinates by the fragment shader
1602 // after being clamped to 0-1 range.
1603 float tex_clamp_x =
1604 std::min(0.5f, 0.5f * clamp_tex_rect.width() - kAntiAliasingEpsilon);
1605 float tex_clamp_y =
1606 std::min(0.5f, 0.5f * clamp_tex_rect.height() - kAntiAliasingEpsilon);
1607 float geom_clamp_x =
1608 std::min(tex_clamp_x * tex_to_geom_scale_x,
1609 0.5f * clamp_geom_rect.width() - kAntiAliasingEpsilon);
1610 float geom_clamp_y =
1611 std::min(tex_clamp_y * tex_to_geom_scale_y,
1612 0.5f * clamp_geom_rect.height() - kAntiAliasingEpsilon);
1613 clamp_geom_rect.Inset(geom_clamp_x, geom_clamp_y, geom_clamp_x, geom_clamp_y);
1614 clamp_tex_rect.Inset(tex_clamp_x, tex_clamp_y, tex_clamp_x, tex_clamp_y);
1616 // Map clamping rectangle to unit square.
1617 float vertex_tex_translate_x = -clamp_geom_rect.x() / clamp_geom_rect.width();
1618 float vertex_tex_translate_y =
1619 -clamp_geom_rect.y() / clamp_geom_rect.height();
1620 float vertex_tex_scale_x = tile_rect.width() / clamp_geom_rect.width();
1621 float vertex_tex_scale_y = tile_rect.height() / clamp_geom_rect.height();
1623 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1624 gl_, &highp_threshold_cache_, highp_threshold_min_, quad->texture_size);
1626 gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1627 float edge[24];
1628 SetupQuadForAntialiasing(device_transform, quad, &local_quad, edge);
1630 ResourceProvider::ScopedSamplerGL quad_resource_lock(
1631 resource_provider_, resource_id, GL_LINEAR);
1632 SamplerType sampler =
1633 SamplerTypeFromTextureTarget(quad_resource_lock.target());
1635 float fragment_tex_translate_x = clamp_tex_rect.x();
1636 float fragment_tex_translate_y = clamp_tex_rect.y();
1637 float fragment_tex_scale_x = clamp_tex_rect.width();
1638 float fragment_tex_scale_y = clamp_tex_rect.height();
1640 // Map to normalized texture coordinates.
1641 if (sampler != SamplerType2DRect) {
1642 gfx::Size texture_size = quad->texture_size;
1643 DCHECK(!texture_size.IsEmpty());
1644 fragment_tex_translate_x /= texture_size.width();
1645 fragment_tex_translate_y /= texture_size.height();
1646 fragment_tex_scale_x /= texture_size.width();
1647 fragment_tex_scale_y /= texture_size.height();
1650 TileProgramUniforms uniforms;
1651 if (quad->swizzle_contents) {
1652 TileUniformLocation(GetTileProgramSwizzleAA(tex_coord_precision, sampler),
1653 &uniforms);
1654 } else {
1655 TileUniformLocation(GetTileProgramAA(tex_coord_precision, sampler),
1656 &uniforms);
1659 SetUseProgram(uniforms.program);
1660 GLC(gl_, gl_->Uniform1i(uniforms.sampler_location, 0));
1662 float viewport[4] = {
1663 static_cast<float>(viewport_.x()),
1664 static_cast<float>(viewport_.y()),
1665 static_cast<float>(viewport_.width()),
1666 static_cast<float>(viewport_.height()),
1668 GLC(gl_, gl_->Uniform4fv(uniforms.viewport_location, 1, viewport));
1669 GLC(gl_, gl_->Uniform3fv(uniforms.edge_location, 8, edge));
1671 GLC(gl_,
1672 gl_->Uniform4f(uniforms.vertex_tex_transform_location,
1673 vertex_tex_translate_x,
1674 vertex_tex_translate_y,
1675 vertex_tex_scale_x,
1676 vertex_tex_scale_y));
1677 GLC(gl_,
1678 gl_->Uniform4f(uniforms.fragment_tex_transform_location,
1679 fragment_tex_translate_x,
1680 fragment_tex_translate_y,
1681 fragment_tex_scale_x,
1682 fragment_tex_scale_y));
1684 // Blending is required for antialiasing.
1685 SetBlendEnabled(true);
1687 // Normalize to tile_rect.
1688 local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1690 SetShaderOpacity(quad->opacity(), uniforms.alpha_location);
1691 SetShaderQuadF(local_quad, uniforms.quad_location);
1693 // The transform and vertex data are used to figure out the extents that the
1694 // un-antialiased quad should have and which vertex this is and the float
1695 // quad passed in via uniform is the actual geometry that gets used to draw
1696 // it. This is why this centered rect is used and not the original quad_rect.
1697 gfx::RectF centered_rect(
1698 gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1699 tile_rect.size());
1700 DrawQuadGeometry(
1701 frame, quad->quadTransform(), centered_rect, uniforms.matrix_location);
1704 void GLRenderer::DrawContentQuadNoAA(const DrawingFrame* frame,
1705 const ContentDrawQuadBase* quad,
1706 ResourceProvider::ResourceId resource_id) {
1707 gfx::RectF tex_coord_rect = MathUtil::ScaleRectProportional(
1708 quad->tex_coord_rect, quad->rect, quad->visible_rect);
1709 float tex_to_geom_scale_x = quad->rect.width() / quad->tex_coord_rect.width();
1710 float tex_to_geom_scale_y =
1711 quad->rect.height() / quad->tex_coord_rect.height();
1713 bool scaled = (tex_to_geom_scale_x != 1.f || tex_to_geom_scale_y != 1.f);
1714 GLenum filter =
1715 (scaled || !quad->quadTransform().IsIdentityOrIntegerTranslation())
1716 ? GL_LINEAR
1717 : GL_NEAREST;
1719 ResourceProvider::ScopedSamplerGL quad_resource_lock(
1720 resource_provider_, resource_id, filter);
1721 SamplerType sampler =
1722 SamplerTypeFromTextureTarget(quad_resource_lock.target());
1724 float vertex_tex_translate_x = tex_coord_rect.x();
1725 float vertex_tex_translate_y = tex_coord_rect.y();
1726 float vertex_tex_scale_x = tex_coord_rect.width();
1727 float vertex_tex_scale_y = tex_coord_rect.height();
1729 // Map to normalized texture coordinates.
1730 if (sampler != SamplerType2DRect) {
1731 gfx::Size texture_size = quad->texture_size;
1732 DCHECK(!texture_size.IsEmpty());
1733 vertex_tex_translate_x /= texture_size.width();
1734 vertex_tex_translate_y /= texture_size.height();
1735 vertex_tex_scale_x /= texture_size.width();
1736 vertex_tex_scale_y /= texture_size.height();
1739 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1740 gl_, &highp_threshold_cache_, highp_threshold_min_, quad->texture_size);
1742 TileProgramUniforms uniforms;
1743 if (quad->ShouldDrawWithBlending()) {
1744 if (quad->swizzle_contents) {
1745 TileUniformLocation(GetTileProgramSwizzle(tex_coord_precision, sampler),
1746 &uniforms);
1747 } else {
1748 TileUniformLocation(GetTileProgram(tex_coord_precision, sampler),
1749 &uniforms);
1751 } else {
1752 if (quad->swizzle_contents) {
1753 TileUniformLocation(
1754 GetTileProgramSwizzleOpaque(tex_coord_precision, sampler), &uniforms);
1755 } else {
1756 TileUniformLocation(GetTileProgramOpaque(tex_coord_precision, sampler),
1757 &uniforms);
1761 SetUseProgram(uniforms.program);
1762 GLC(gl_, gl_->Uniform1i(uniforms.sampler_location, 0));
1764 GLC(gl_,
1765 gl_->Uniform4f(uniforms.vertex_tex_transform_location,
1766 vertex_tex_translate_x,
1767 vertex_tex_translate_y,
1768 vertex_tex_scale_x,
1769 vertex_tex_scale_y));
1771 SetBlendEnabled(quad->ShouldDrawWithBlending());
1773 SetShaderOpacity(quad->opacity(), uniforms.alpha_location);
1775 // Pass quad coordinates to the uniform in the same order as GeometryBinding
1776 // does, then vertices will match the texture mapping in the vertex buffer.
1777 // The method SetShaderQuadF() changes the order of vertices and so it's
1778 // not used here.
1780 gfx::RectF tile_rect = quad->visible_rect;
1781 float gl_quad[8] = {
1782 tile_rect.x(),
1783 tile_rect.bottom(),
1784 tile_rect.x(),
1785 tile_rect.y(),
1786 tile_rect.right(),
1787 tile_rect.y(),
1788 tile_rect.right(),
1789 tile_rect.bottom(),
1791 GLC(gl_, gl_->Uniform2fv(uniforms.quad_location, 4, gl_quad));
1793 static float gl_matrix[16];
1794 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad->quadTransform());
1795 GLC(gl_,
1796 gl_->UniformMatrix4fv(uniforms.matrix_location, 1, false, &gl_matrix[0]));
1798 GLC(gl_, gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0));
1801 void GLRenderer::DrawYUVVideoQuad(const DrawingFrame* frame,
1802 const YUVVideoDrawQuad* quad) {
1803 SetBlendEnabled(quad->ShouldDrawWithBlending());
1805 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1806 gl_,
1807 &highp_threshold_cache_,
1808 highp_threshold_min_,
1809 quad->shared_quad_state->visible_content_rect.bottom_right());
1811 bool use_alpha_plane = quad->a_plane_resource_id != 0;
1813 ResourceProvider::ScopedSamplerGL y_plane_lock(
1814 resource_provider_, quad->y_plane_resource_id, GL_TEXTURE1, GL_LINEAR);
1815 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), y_plane_lock.target());
1816 ResourceProvider::ScopedSamplerGL u_plane_lock(
1817 resource_provider_, quad->u_plane_resource_id, GL_TEXTURE2, GL_LINEAR);
1818 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), u_plane_lock.target());
1819 ResourceProvider::ScopedSamplerGL v_plane_lock(
1820 resource_provider_, quad->v_plane_resource_id, GL_TEXTURE3, GL_LINEAR);
1821 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), v_plane_lock.target());
1822 scoped_ptr<ResourceProvider::ScopedSamplerGL> a_plane_lock;
1823 if (use_alpha_plane) {
1824 a_plane_lock.reset(new ResourceProvider::ScopedSamplerGL(
1825 resource_provider_, quad->a_plane_resource_id, GL_TEXTURE4, GL_LINEAR));
1826 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), a_plane_lock->target());
1829 int matrix_location = -1;
1830 int tex_scale_location = -1;
1831 int tex_offset_location = -1;
1832 int y_texture_location = -1;
1833 int u_texture_location = -1;
1834 int v_texture_location = -1;
1835 int a_texture_location = -1;
1836 int yuv_matrix_location = -1;
1837 int yuv_adj_location = -1;
1838 int alpha_location = -1;
1839 if (use_alpha_plane) {
1840 const VideoYUVAProgram* program = GetVideoYUVAProgram(tex_coord_precision);
1841 DCHECK(program && (program->initialized() || IsContextLost()));
1842 SetUseProgram(program->program());
1843 matrix_location = program->vertex_shader().matrix_location();
1844 tex_scale_location = program->vertex_shader().tex_scale_location();
1845 tex_offset_location = program->vertex_shader().tex_offset_location();
1846 y_texture_location = program->fragment_shader().y_texture_location();
1847 u_texture_location = program->fragment_shader().u_texture_location();
1848 v_texture_location = program->fragment_shader().v_texture_location();
1849 a_texture_location = program->fragment_shader().a_texture_location();
1850 yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
1851 yuv_adj_location = program->fragment_shader().yuv_adj_location();
1852 alpha_location = program->fragment_shader().alpha_location();
1853 } else {
1854 const VideoYUVProgram* program = GetVideoYUVProgram(tex_coord_precision);
1855 DCHECK(program && (program->initialized() || IsContextLost()));
1856 SetUseProgram(program->program());
1857 matrix_location = program->vertex_shader().matrix_location();
1858 tex_scale_location = program->vertex_shader().tex_scale_location();
1859 tex_offset_location = program->vertex_shader().tex_offset_location();
1860 y_texture_location = program->fragment_shader().y_texture_location();
1861 u_texture_location = program->fragment_shader().u_texture_location();
1862 v_texture_location = program->fragment_shader().v_texture_location();
1863 yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
1864 yuv_adj_location = program->fragment_shader().yuv_adj_location();
1865 alpha_location = program->fragment_shader().alpha_location();
1868 GLC(gl_,
1869 gl_->Uniform2f(tex_scale_location,
1870 quad->tex_coord_rect.width(),
1871 quad->tex_coord_rect.height()));
1872 GLC(gl_,
1873 gl_->Uniform2f(tex_offset_location,
1874 quad->tex_coord_rect.x(),
1875 quad->tex_coord_rect.y()));
1876 GLC(gl_, gl_->Uniform1i(y_texture_location, 1));
1877 GLC(gl_, gl_->Uniform1i(u_texture_location, 2));
1878 GLC(gl_, gl_->Uniform1i(v_texture_location, 3));
1879 if (use_alpha_plane)
1880 GLC(gl_, gl_->Uniform1i(a_texture_location, 4));
1882 // These values are magic numbers that are used in the transformation from YUV
1883 // to RGB color values. They are taken from the following webpage:
1884 // http://www.fourcc.org/fccyvrgb.php
1885 float yuv_to_rgb_rec601[9] = {
1886 1.164f, 1.164f, 1.164f, 0.0f, -.391f, 2.018f, 1.596f, -.813f, 0.0f,
1888 float yuv_to_rgb_rec601_jpeg[9] = {
1889 1.f, 1.f, 1.f, 0.0f, -.34414f, 1.772f, 1.402f, -.71414f, 0.0f,
1892 // These values map to 16, 128, and 128 respectively, and are computed
1893 // as a fraction over 256 (e.g. 16 / 256 = 0.0625).
1894 // They are used in the YUV to RGBA conversion formula:
1895 // Y - 16 : Gives 16 values of head and footroom for overshooting
1896 // U - 128 : Turns unsigned U into signed U [-128,127]
1897 // V - 128 : Turns unsigned V into signed V [-128,127]
1898 float yuv_adjust_rec601[3] = {
1899 -0.0625f, -0.5f, -0.5f,
1902 // Same as above, but without the head and footroom.
1903 float yuv_adjust_rec601_jpeg[3] = {
1904 0.0f, -0.5f, -0.5f,
1907 float* yuv_to_rgb = NULL;
1908 float* yuv_adjust = NULL;
1910 switch (quad->color_space) {
1911 case YUVVideoDrawQuad::REC_601:
1912 yuv_to_rgb = yuv_to_rgb_rec601;
1913 yuv_adjust = yuv_adjust_rec601;
1914 break;
1915 case YUVVideoDrawQuad::REC_601_JPEG:
1916 yuv_to_rgb = yuv_to_rgb_rec601_jpeg;
1917 yuv_adjust = yuv_adjust_rec601_jpeg;
1918 break;
1921 GLC(gl_, gl_->UniformMatrix3fv(yuv_matrix_location, 1, 0, yuv_to_rgb));
1922 GLC(gl_, gl_->Uniform3fv(yuv_adj_location, 1, yuv_adjust));
1924 SetShaderOpacity(quad->opacity(), alpha_location);
1925 DrawQuadGeometry(frame, quad->quadTransform(), quad->rect, matrix_location);
1928 void GLRenderer::DrawStreamVideoQuad(const DrawingFrame* frame,
1929 const StreamVideoDrawQuad* quad) {
1930 SetBlendEnabled(quad->ShouldDrawWithBlending());
1932 static float gl_matrix[16];
1934 DCHECK(capabilities_.using_egl_image);
1936 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1937 gl_,
1938 &highp_threshold_cache_,
1939 highp_threshold_min_,
1940 quad->shared_quad_state->visible_content_rect.bottom_right());
1942 const VideoStreamTextureProgram* program =
1943 GetVideoStreamTextureProgram(tex_coord_precision);
1944 SetUseProgram(program->program());
1946 ToGLMatrix(&gl_matrix[0], quad->matrix);
1947 GLC(gl_,
1948 gl_->UniformMatrix4fv(
1949 program->vertex_shader().tex_matrix_location(), 1, false, gl_matrix));
1951 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
1952 quad->resource_id);
1953 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
1954 GLC(gl_, gl_->BindTexture(GL_TEXTURE_EXTERNAL_OES, lock.texture_id()));
1956 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1958 SetShaderOpacity(quad->opacity(),
1959 program->fragment_shader().alpha_location());
1960 DrawQuadGeometry(frame,
1961 quad->quadTransform(),
1962 quad->rect,
1963 program->vertex_shader().matrix_location());
1966 void GLRenderer::DrawPictureQuad(const DrawingFrame* frame,
1967 const PictureDrawQuad* quad) {
1968 if (on_demand_tile_raster_bitmap_.width() != quad->texture_size.width() ||
1969 on_demand_tile_raster_bitmap_.height() != quad->texture_size.height()) {
1970 on_demand_tile_raster_bitmap_.allocN32Pixels(quad->texture_size.width(),
1971 quad->texture_size.height());
1973 if (on_demand_tile_raster_resource_id_)
1974 resource_provider_->DeleteResource(on_demand_tile_raster_resource_id_);
1976 on_demand_tile_raster_resource_id_ = resource_provider_->CreateGLTexture(
1977 quad->texture_size,
1978 GL_TEXTURE_2D,
1979 GL_TEXTURE_POOL_UNMANAGED_CHROMIUM,
1980 GL_CLAMP_TO_EDGE,
1981 ResourceProvider::TextureHintImmutable,
1982 quad->texture_format);
1985 SkCanvas canvas(on_demand_tile_raster_bitmap_);
1986 quad->raster_source->PlaybackToCanvas(&canvas, quad->content_rect,
1987 quad->contents_scale);
1989 uint8_t* bitmap_pixels = NULL;
1990 SkBitmap on_demand_tile_raster_bitmap_dest;
1991 SkColorType colorType = ResourceFormatToSkColorType(quad->texture_format);
1992 if (on_demand_tile_raster_bitmap_.colorType() != colorType) {
1993 on_demand_tile_raster_bitmap_.copyTo(&on_demand_tile_raster_bitmap_dest,
1994 colorType);
1995 // TODO(kaanb): The GL pipeline assumes a 4-byte alignment for the
1996 // bitmap data. This check will be removed once crbug.com/293728 is fixed.
1997 CHECK_EQ(0u, on_demand_tile_raster_bitmap_dest.rowBytes() % 4);
1998 bitmap_pixels = reinterpret_cast<uint8_t*>(
1999 on_demand_tile_raster_bitmap_dest.getPixels());
2000 } else {
2001 bitmap_pixels =
2002 reinterpret_cast<uint8_t*>(on_demand_tile_raster_bitmap_.getPixels());
2005 resource_provider_->SetPixels(on_demand_tile_raster_resource_id_,
2006 bitmap_pixels,
2007 gfx::Rect(quad->texture_size),
2008 gfx::Rect(quad->texture_size),
2009 gfx::Vector2d());
2011 DrawContentQuad(frame, quad, on_demand_tile_raster_resource_id_);
2014 struct TextureProgramBinding {
2015 template <class Program>
2016 void Set(Program* program) {
2017 DCHECK(program);
2018 program_id = program->program();
2019 sampler_location = program->fragment_shader().sampler_location();
2020 matrix_location = program->vertex_shader().matrix_location();
2021 background_color_location =
2022 program->fragment_shader().background_color_location();
2024 int program_id;
2025 int sampler_location;
2026 int matrix_location;
2027 int background_color_location;
2030 struct TexTransformTextureProgramBinding : TextureProgramBinding {
2031 template <class Program>
2032 void Set(Program* program) {
2033 TextureProgramBinding::Set(program);
2034 tex_transform_location = program->vertex_shader().tex_transform_location();
2035 vertex_opacity_location =
2036 program->vertex_shader().vertex_opacity_location();
2038 int tex_transform_location;
2039 int vertex_opacity_location;
2042 void GLRenderer::FlushTextureQuadCache() {
2043 // Check to see if we have anything to draw.
2044 if (draw_cache_.program_id == -1)
2045 return;
2047 // Set the correct blending mode.
2048 SetBlendEnabled(draw_cache_.needs_blending);
2050 // Bind the program to the GL state.
2051 SetUseProgram(draw_cache_.program_id);
2053 // Bind the correct texture sampler location.
2054 GLC(gl_, gl_->Uniform1i(draw_cache_.sampler_location, 0));
2056 // Assume the current active textures is 0.
2057 ResourceProvider::ScopedReadLockGL locked_quad(resource_provider_,
2058 draw_cache_.resource_id);
2059 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2060 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, locked_quad.texture_id()));
2062 COMPILE_ASSERT(sizeof(Float4) == 4 * sizeof(float), struct_is_densely_packed);
2063 COMPILE_ASSERT(sizeof(Float16) == 16 * sizeof(float),
2064 struct_is_densely_packed);
2066 // Upload the tranforms for both points and uvs.
2067 GLC(gl_,
2068 gl_->UniformMatrix4fv(
2069 static_cast<int>(draw_cache_.matrix_location),
2070 static_cast<int>(draw_cache_.matrix_data.size()),
2071 false,
2072 reinterpret_cast<float*>(&draw_cache_.matrix_data.front())));
2073 GLC(gl_,
2074 gl_->Uniform4fv(
2075 static_cast<int>(draw_cache_.uv_xform_location),
2076 static_cast<int>(draw_cache_.uv_xform_data.size()),
2077 reinterpret_cast<float*>(&draw_cache_.uv_xform_data.front())));
2079 if (draw_cache_.background_color != SK_ColorTRANSPARENT) {
2080 Float4 background_color = PremultipliedColor(draw_cache_.background_color);
2081 GLC(gl_,
2082 gl_->Uniform4fv(
2083 draw_cache_.background_color_location, 1, background_color.data));
2086 GLC(gl_,
2087 gl_->Uniform1fv(
2088 static_cast<int>(draw_cache_.vertex_opacity_location),
2089 static_cast<int>(draw_cache_.vertex_opacity_data.size()),
2090 static_cast<float*>(&draw_cache_.vertex_opacity_data.front())));
2092 // Draw the quads!
2093 GLC(gl_,
2094 gl_->DrawElements(GL_TRIANGLES,
2095 6 * draw_cache_.matrix_data.size(),
2096 GL_UNSIGNED_SHORT,
2097 0));
2099 // Clear the cache.
2100 draw_cache_.program_id = -1;
2101 draw_cache_.uv_xform_data.resize(0);
2102 draw_cache_.vertex_opacity_data.resize(0);
2103 draw_cache_.matrix_data.resize(0);
2106 void GLRenderer::EnqueueTextureQuad(const DrawingFrame* frame,
2107 const TextureDrawQuad* quad) {
2108 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2109 gl_,
2110 &highp_threshold_cache_,
2111 highp_threshold_min_,
2112 quad->shared_quad_state->visible_content_rect.bottom_right());
2114 // Choose the correct texture program binding
2115 TexTransformTextureProgramBinding binding;
2116 if (quad->premultiplied_alpha) {
2117 if (quad->background_color == SK_ColorTRANSPARENT) {
2118 binding.Set(GetTextureProgram(tex_coord_precision));
2119 } else {
2120 binding.Set(GetTextureBackgroundProgram(tex_coord_precision));
2122 } else {
2123 if (quad->background_color == SK_ColorTRANSPARENT) {
2124 binding.Set(GetNonPremultipliedTextureProgram(tex_coord_precision));
2125 } else {
2126 binding.Set(
2127 GetNonPremultipliedTextureBackgroundProgram(tex_coord_precision));
2131 int resource_id = quad->resource_id;
2133 if (draw_cache_.program_id != binding.program_id ||
2134 draw_cache_.resource_id != resource_id ||
2135 draw_cache_.needs_blending != quad->ShouldDrawWithBlending() ||
2136 draw_cache_.background_color != quad->background_color ||
2137 draw_cache_.matrix_data.size() >= 8) {
2138 FlushTextureQuadCache();
2139 draw_cache_.program_id = binding.program_id;
2140 draw_cache_.resource_id = resource_id;
2141 draw_cache_.needs_blending = quad->ShouldDrawWithBlending();
2142 draw_cache_.background_color = quad->background_color;
2144 draw_cache_.uv_xform_location = binding.tex_transform_location;
2145 draw_cache_.background_color_location = binding.background_color_location;
2146 draw_cache_.vertex_opacity_location = binding.vertex_opacity_location;
2147 draw_cache_.matrix_location = binding.matrix_location;
2148 draw_cache_.sampler_location = binding.sampler_location;
2151 // Generate the uv-transform
2152 draw_cache_.uv_xform_data.push_back(UVTransform(quad));
2154 // Generate the vertex opacity
2155 const float opacity = quad->opacity();
2156 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[0] * opacity);
2157 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[1] * opacity);
2158 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[2] * opacity);
2159 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[3] * opacity);
2161 // Generate the transform matrix
2162 gfx::Transform quad_rect_matrix;
2163 QuadRectTransform(&quad_rect_matrix, quad->quadTransform(), quad->rect);
2164 quad_rect_matrix = frame->projection_matrix * quad_rect_matrix;
2166 Float16 m;
2167 quad_rect_matrix.matrix().asColMajorf(m.data);
2168 draw_cache_.matrix_data.push_back(m);
2171 void GLRenderer::DrawIOSurfaceQuad(const DrawingFrame* frame,
2172 const IOSurfaceDrawQuad* quad) {
2173 SetBlendEnabled(quad->ShouldDrawWithBlending());
2175 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2176 gl_,
2177 &highp_threshold_cache_,
2178 highp_threshold_min_,
2179 quad->shared_quad_state->visible_content_rect.bottom_right());
2181 TexTransformTextureProgramBinding binding;
2182 binding.Set(GetTextureIOSurfaceProgram(tex_coord_precision));
2184 SetUseProgram(binding.program_id);
2185 GLC(gl_, gl_->Uniform1i(binding.sampler_location, 0));
2186 if (quad->orientation == IOSurfaceDrawQuad::FLIPPED) {
2187 GLC(gl_,
2188 gl_->Uniform4f(binding.tex_transform_location,
2190 quad->io_surface_size.height(),
2191 quad->io_surface_size.width(),
2192 quad->io_surface_size.height() * -1.0f));
2193 } else {
2194 GLC(gl_,
2195 gl_->Uniform4f(binding.tex_transform_location,
2198 quad->io_surface_size.width(),
2199 quad->io_surface_size.height()));
2202 const float vertex_opacity[] = {quad->opacity(), quad->opacity(),
2203 quad->opacity(), quad->opacity()};
2204 GLC(gl_, gl_->Uniform1fv(binding.vertex_opacity_location, 4, vertex_opacity));
2206 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
2207 quad->io_surface_resource_id);
2208 DCHECK_EQ(GL_TEXTURE0, GetActiveTextureUnit(gl_));
2209 GLC(gl_, gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, lock.texture_id()));
2211 DrawQuadGeometry(
2212 frame, quad->quadTransform(), quad->rect, binding.matrix_location);
2214 GLC(gl_, gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, 0));
2217 void GLRenderer::FinishDrawingFrame(DrawingFrame* frame) {
2218 if (use_sync_query_) {
2219 DCHECK(current_sync_query_);
2220 current_sync_query_->End();
2221 pending_sync_queries_.push_back(current_sync_query_.Pass());
2224 current_framebuffer_lock_ = nullptr;
2225 swap_buffer_rect_.Union(gfx::ToEnclosingRect(frame->root_damage_rect));
2227 GLC(gl_, gl_->Disable(GL_BLEND));
2228 blend_shadow_ = false;
2230 ScheduleOverlays(frame);
2233 void GLRenderer::FinishDrawingQuadList() { FlushTextureQuadCache(); }
2235 bool GLRenderer::FlippedFramebuffer(const DrawingFrame* frame) const {
2236 if (frame->current_render_pass != frame->root_render_pass)
2237 return true;
2238 return FlippedRootFramebuffer();
2241 bool GLRenderer::FlippedRootFramebuffer() const {
2242 // GL is normally flipped, so a flipped output results in an unflipping.
2243 return !output_surface_->capabilities().flipped_output_surface;
2246 void GLRenderer::EnsureScissorTestEnabled() {
2247 if (is_scissor_enabled_)
2248 return;
2250 FlushTextureQuadCache();
2251 GLC(gl_, gl_->Enable(GL_SCISSOR_TEST));
2252 is_scissor_enabled_ = true;
2255 void GLRenderer::EnsureScissorTestDisabled() {
2256 if (!is_scissor_enabled_)
2257 return;
2259 FlushTextureQuadCache();
2260 GLC(gl_, gl_->Disable(GL_SCISSOR_TEST));
2261 is_scissor_enabled_ = false;
2264 void GLRenderer::CopyCurrentRenderPassToBitmap(
2265 DrawingFrame* frame,
2266 scoped_ptr<CopyOutputRequest> request) {
2267 TRACE_EVENT0("cc", "GLRenderer::CopyCurrentRenderPassToBitmap");
2268 gfx::Rect copy_rect = frame->current_render_pass->output_rect;
2269 if (request->has_area())
2270 copy_rect.Intersect(request->area());
2271 GetFramebufferPixelsAsync(frame, copy_rect, request.Pass());
2274 void GLRenderer::ToGLMatrix(float* gl_matrix, const gfx::Transform& transform) {
2275 transform.matrix().asColMajorf(gl_matrix);
2278 void GLRenderer::SetShaderQuadF(const gfx::QuadF& quad, int quad_location) {
2279 if (quad_location == -1)
2280 return;
2282 float gl_quad[8];
2283 gl_quad[0] = quad.p1().x();
2284 gl_quad[1] = quad.p1().y();
2285 gl_quad[2] = quad.p2().x();
2286 gl_quad[3] = quad.p2().y();
2287 gl_quad[4] = quad.p3().x();
2288 gl_quad[5] = quad.p3().y();
2289 gl_quad[6] = quad.p4().x();
2290 gl_quad[7] = quad.p4().y();
2291 GLC(gl_, gl_->Uniform2fv(quad_location, 4, gl_quad));
2294 void GLRenderer::SetShaderOpacity(float opacity, int alpha_location) {
2295 if (alpha_location != -1)
2296 GLC(gl_, gl_->Uniform1f(alpha_location, opacity));
2299 void GLRenderer::SetStencilEnabled(bool enabled) {
2300 if (enabled == stencil_shadow_)
2301 return;
2303 if (enabled)
2304 GLC(gl_, gl_->Enable(GL_STENCIL_TEST));
2305 else
2306 GLC(gl_, gl_->Disable(GL_STENCIL_TEST));
2307 stencil_shadow_ = enabled;
2310 void GLRenderer::SetBlendEnabled(bool enabled) {
2311 if (enabled == blend_shadow_)
2312 return;
2314 if (enabled)
2315 GLC(gl_, gl_->Enable(GL_BLEND));
2316 else
2317 GLC(gl_, gl_->Disable(GL_BLEND));
2318 blend_shadow_ = enabled;
2321 void GLRenderer::SetUseProgram(unsigned program) {
2322 if (program == program_shadow_)
2323 return;
2324 gl_->UseProgram(program);
2325 program_shadow_ = program;
2328 void GLRenderer::DrawQuadGeometry(const DrawingFrame* frame,
2329 const gfx::Transform& draw_transform,
2330 const gfx::RectF& quad_rect,
2331 int matrix_location) {
2332 gfx::Transform quad_rect_matrix;
2333 QuadRectTransform(&quad_rect_matrix, draw_transform, quad_rect);
2334 static float gl_matrix[16];
2335 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad_rect_matrix);
2336 GLC(gl_, gl_->UniformMatrix4fv(matrix_location, 1, false, &gl_matrix[0]));
2338 GLC(gl_, gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0));
2341 void GLRenderer::Finish() {
2342 TRACE_EVENT0("cc", "GLRenderer::Finish");
2343 GLC(gl_, gl_->Finish());
2346 void GLRenderer::SwapBuffers(const CompositorFrameMetadata& metadata) {
2347 DCHECK(!is_backbuffer_discarded_);
2349 TRACE_EVENT0("cc,benchmark", "GLRenderer::SwapBuffers");
2350 // We're done! Time to swapbuffers!
2352 gfx::Size surface_size = output_surface_->SurfaceSize();
2354 CompositorFrame compositor_frame;
2355 compositor_frame.metadata = metadata;
2356 compositor_frame.gl_frame_data = make_scoped_ptr(new GLFrameData);
2357 compositor_frame.gl_frame_data->size = surface_size;
2358 if (capabilities_.using_partial_swap) {
2359 // If supported, we can save significant bandwidth by only swapping the
2360 // damaged/scissored region (clamped to the viewport).
2361 swap_buffer_rect_.Intersect(gfx::Rect(surface_size));
2362 int flipped_y_pos_of_rect_bottom = surface_size.height() -
2363 swap_buffer_rect_.y() -
2364 swap_buffer_rect_.height();
2365 compositor_frame.gl_frame_data->sub_buffer_rect =
2366 gfx::Rect(swap_buffer_rect_.x(),
2367 FlippedRootFramebuffer() ? flipped_y_pos_of_rect_bottom
2368 : swap_buffer_rect_.y(),
2369 swap_buffer_rect_.width(),
2370 swap_buffer_rect_.height());
2371 } else {
2372 compositor_frame.gl_frame_data->sub_buffer_rect =
2373 gfx::Rect(output_surface_->SurfaceSize());
2375 output_surface_->SwapBuffers(&compositor_frame);
2377 // Release previously used overlay resources and hold onto the pending ones
2378 // until the next swap buffers.
2379 in_use_overlay_resources_.clear();
2380 in_use_overlay_resources_.swap(pending_overlay_resources_);
2382 swap_buffer_rect_ = gfx::Rect();
2385 void GLRenderer::EnforceMemoryPolicy() {
2386 if (!visible()) {
2387 TRACE_EVENT0("cc", "GLRenderer::EnforceMemoryPolicy dropping resources");
2388 ReleaseRenderPassTextures();
2389 DiscardBackbuffer();
2390 resource_provider_->ReleaseCachedData();
2391 output_surface_->context_provider()->DeleteCachedResources();
2392 GLC(gl_, gl_->Flush());
2396 void GLRenderer::DiscardBackbuffer() {
2397 if (is_backbuffer_discarded_)
2398 return;
2400 output_surface_->DiscardBackbuffer();
2402 is_backbuffer_discarded_ = true;
2404 // Damage tracker needs a full reset every time framebuffer is discarded.
2405 client_->SetFullRootLayerDamage();
2408 void GLRenderer::EnsureBackbuffer() {
2409 if (!is_backbuffer_discarded_)
2410 return;
2412 output_surface_->EnsureBackbuffer();
2413 is_backbuffer_discarded_ = false;
2416 void GLRenderer::GetFramebufferPixelsAsync(
2417 const DrawingFrame* frame,
2418 const gfx::Rect& rect,
2419 scoped_ptr<CopyOutputRequest> request) {
2420 DCHECK(!request->IsEmpty());
2421 if (request->IsEmpty())
2422 return;
2423 if (rect.IsEmpty())
2424 return;
2426 gfx::Rect window_rect = MoveFromDrawToWindowSpace(frame, rect);
2427 DCHECK_GE(window_rect.x(), 0);
2428 DCHECK_GE(window_rect.y(), 0);
2429 DCHECK_LE(window_rect.right(), current_surface_size_.width());
2430 DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2432 if (!request->force_bitmap_result()) {
2433 bool own_mailbox = !request->has_texture_mailbox();
2435 GLuint texture_id = 0;
2436 gpu::Mailbox mailbox;
2437 if (own_mailbox) {
2438 GLC(gl_, gl_->GenMailboxCHROMIUM(mailbox.name));
2439 gl_->GenTextures(1, &texture_id);
2440 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, texture_id));
2442 GLC(gl_,
2443 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
2444 GLC(gl_,
2445 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
2446 GLC(gl_,
2447 gl_->TexParameteri(
2448 GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
2449 GLC(gl_,
2450 gl_->TexParameteri(
2451 GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
2452 GLC(gl_, gl_->ProduceTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name));
2453 } else {
2454 mailbox = request->texture_mailbox().mailbox();
2455 DCHECK_EQ(static_cast<unsigned>(GL_TEXTURE_2D),
2456 request->texture_mailbox().target());
2457 DCHECK(!mailbox.IsZero());
2458 unsigned incoming_sync_point = request->texture_mailbox().sync_point();
2459 if (incoming_sync_point)
2460 GLC(gl_, gl_->WaitSyncPointCHROMIUM(incoming_sync_point));
2462 texture_id = GLC(
2463 gl_,
2464 gl_->CreateAndConsumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name));
2466 GetFramebufferTexture(texture_id, RGBA_8888, window_rect);
2468 unsigned sync_point = gl_->InsertSyncPointCHROMIUM();
2469 TextureMailbox texture_mailbox(mailbox, GL_TEXTURE_2D, sync_point);
2471 scoped_ptr<SingleReleaseCallback> release_callback;
2472 if (own_mailbox) {
2473 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, 0));
2474 release_callback = texture_mailbox_deleter_->GetReleaseCallback(
2475 output_surface_->context_provider(), texture_id);
2476 } else {
2477 gl_->DeleteTextures(1, &texture_id);
2480 request->SendTextureResult(
2481 window_rect.size(), texture_mailbox, release_callback.Pass());
2482 return;
2485 DCHECK(request->force_bitmap_result());
2487 scoped_ptr<PendingAsyncReadPixels> pending_read(new PendingAsyncReadPixels);
2488 pending_read->copy_request = request.Pass();
2489 pending_async_read_pixels_.insert(pending_async_read_pixels_.begin(),
2490 pending_read.Pass());
2492 bool do_workaround = NeedsIOSurfaceReadbackWorkaround();
2494 unsigned temporary_texture = 0;
2495 unsigned temporary_fbo = 0;
2497 if (do_workaround) {
2498 // On Mac OS X, calling glReadPixels() against an FBO whose color attachment
2499 // is an IOSurface-backed texture causes corruption of future glReadPixels()
2500 // calls, even those on different OpenGL contexts. It is believed that this
2501 // is the root cause of top crasher
2502 // http://crbug.com/99393. <rdar://problem/10949687>
2504 gl_->GenTextures(1, &temporary_texture);
2505 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, temporary_texture));
2506 GLC(gl_,
2507 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
2508 GLC(gl_,
2509 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
2510 GLC(gl_,
2511 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
2512 GLC(gl_,
2513 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
2514 // Copy the contents of the current (IOSurface-backed) framebuffer into a
2515 // temporary texture.
2516 GetFramebufferTexture(
2517 temporary_texture, RGBA_8888, gfx::Rect(current_surface_size_));
2518 gl_->GenFramebuffers(1, &temporary_fbo);
2519 // Attach this texture to an FBO, and perform the readback from that FBO.
2520 GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, temporary_fbo));
2521 GLC(gl_,
2522 gl_->FramebufferTexture2D(GL_FRAMEBUFFER,
2523 GL_COLOR_ATTACHMENT0,
2524 GL_TEXTURE_2D,
2525 temporary_texture,
2526 0));
2528 DCHECK_EQ(static_cast<unsigned>(GL_FRAMEBUFFER_COMPLETE),
2529 gl_->CheckFramebufferStatus(GL_FRAMEBUFFER));
2532 GLuint buffer = 0;
2533 gl_->GenBuffers(1, &buffer);
2534 GLC(gl_, gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, buffer));
2535 GLC(gl_,
2536 gl_->BufferData(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM,
2537 4 * window_rect.size().GetArea(),
2538 NULL,
2539 GL_STREAM_READ));
2541 GLuint query = 0;
2542 gl_->GenQueriesEXT(1, &query);
2543 GLC(gl_, gl_->BeginQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM, query));
2545 GLC(gl_,
2546 gl_->ReadPixels(window_rect.x(),
2547 window_rect.y(),
2548 window_rect.width(),
2549 window_rect.height(),
2550 GL_RGBA,
2551 GL_UNSIGNED_BYTE,
2552 NULL));
2554 GLC(gl_, gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0));
2556 if (do_workaround) {
2557 // Clean up.
2558 GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, 0));
2559 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, 0));
2560 GLC(gl_, gl_->DeleteFramebuffers(1, &temporary_fbo));
2561 GLC(gl_, gl_->DeleteTextures(1, &temporary_texture));
2564 base::Closure finished_callback = base::Bind(&GLRenderer::FinishedReadback,
2565 base::Unretained(this),
2566 buffer,
2567 query,
2568 window_rect.size());
2569 // Save the finished_callback so it can be cancelled.
2570 pending_async_read_pixels_.front()->finished_read_pixels_callback.Reset(
2571 finished_callback);
2572 base::Closure cancelable_callback =
2573 pending_async_read_pixels_.front()->
2574 finished_read_pixels_callback.callback();
2576 // Save the buffer to verify the callbacks happen in the expected order.
2577 pending_async_read_pixels_.front()->buffer = buffer;
2579 GLC(gl_, gl_->EndQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM));
2580 context_support_->SignalQuery(query, cancelable_callback);
2582 EnforceMemoryPolicy();
2585 void GLRenderer::FinishedReadback(unsigned source_buffer,
2586 unsigned query,
2587 const gfx::Size& size) {
2588 DCHECK(!pending_async_read_pixels_.empty());
2590 if (query != 0) {
2591 GLC(gl_, gl_->DeleteQueriesEXT(1, &query));
2594 PendingAsyncReadPixels* current_read = pending_async_read_pixels_.back();
2595 // Make sure we service the readbacks in order.
2596 DCHECK_EQ(source_buffer, current_read->buffer);
2598 uint8* src_pixels = NULL;
2599 scoped_ptr<SkBitmap> bitmap;
2601 if (source_buffer != 0) {
2602 GLC(gl_,
2603 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, source_buffer));
2604 src_pixels = static_cast<uint8*>(gl_->MapBufferCHROMIUM(
2605 GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, GL_READ_ONLY));
2607 if (src_pixels) {
2608 bitmap.reset(new SkBitmap);
2609 bitmap->allocN32Pixels(size.width(), size.height());
2610 scoped_ptr<SkAutoLockPixels> lock(new SkAutoLockPixels(*bitmap));
2611 uint8* dest_pixels = static_cast<uint8*>(bitmap->getPixels());
2613 size_t row_bytes = size.width() * 4;
2614 int num_rows = size.height();
2615 size_t total_bytes = num_rows * row_bytes;
2616 for (size_t dest_y = 0; dest_y < total_bytes; dest_y += row_bytes) {
2617 // Flip Y axis.
2618 size_t src_y = total_bytes - dest_y - row_bytes;
2619 // Swizzle OpenGL -> Skia byte order.
2620 for (size_t x = 0; x < row_bytes; x += 4) {
2621 dest_pixels[dest_y + x + SK_R32_SHIFT / 8] =
2622 src_pixels[src_y + x + 0];
2623 dest_pixels[dest_y + x + SK_G32_SHIFT / 8] =
2624 src_pixels[src_y + x + 1];
2625 dest_pixels[dest_y + x + SK_B32_SHIFT / 8] =
2626 src_pixels[src_y + x + 2];
2627 dest_pixels[dest_y + x + SK_A32_SHIFT / 8] =
2628 src_pixels[src_y + x + 3];
2632 GLC(gl_,
2633 gl_->UnmapBufferCHROMIUM(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM));
2635 GLC(gl_, gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0));
2636 GLC(gl_, gl_->DeleteBuffers(1, &source_buffer));
2639 if (bitmap)
2640 current_read->copy_request->SendBitmapResult(bitmap.Pass());
2641 pending_async_read_pixels_.pop_back();
2644 void GLRenderer::GetFramebufferTexture(unsigned texture_id,
2645 ResourceFormat texture_format,
2646 const gfx::Rect& window_rect) {
2647 DCHECK(texture_id);
2648 DCHECK_GE(window_rect.x(), 0);
2649 DCHECK_GE(window_rect.y(), 0);
2650 DCHECK_LE(window_rect.right(), current_surface_size_.width());
2651 DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2653 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, texture_id));
2654 GLC(gl_,
2655 gl_->CopyTexImage2D(GL_TEXTURE_2D,
2657 GLDataFormat(texture_format),
2658 window_rect.x(),
2659 window_rect.y(),
2660 window_rect.width(),
2661 window_rect.height(),
2662 0));
2663 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, 0));
2666 bool GLRenderer::UseScopedTexture(DrawingFrame* frame,
2667 const ScopedResource* texture,
2668 const gfx::Rect& viewport_rect) {
2669 DCHECK(texture->id());
2670 frame->current_render_pass = NULL;
2671 frame->current_texture = texture;
2673 return BindFramebufferToTexture(frame, texture, viewport_rect);
2676 void GLRenderer::BindFramebufferToOutputSurface(DrawingFrame* frame) {
2677 current_framebuffer_lock_ = nullptr;
2678 output_surface_->BindFramebuffer();
2680 if (output_surface_->HasExternalStencilTest()) {
2681 SetStencilEnabled(true);
2682 GLC(gl_, gl_->StencilFunc(GL_EQUAL, 1, 1));
2683 } else {
2684 SetStencilEnabled(false);
2688 bool GLRenderer::BindFramebufferToTexture(DrawingFrame* frame,
2689 const ScopedResource* texture,
2690 const gfx::Rect& target_rect) {
2691 DCHECK(texture->id());
2693 current_framebuffer_lock_ = nullptr;
2695 SetStencilEnabled(false);
2696 GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, offscreen_framebuffer_id_));
2697 current_framebuffer_lock_ =
2698 make_scoped_ptr(new ResourceProvider::ScopedWriteLockGL(
2699 resource_provider_, texture->id()));
2700 unsigned texture_id = current_framebuffer_lock_->texture_id();
2701 GLC(gl_,
2702 gl_->FramebufferTexture2D(
2703 GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_id, 0));
2705 DCHECK(gl_->CheckFramebufferStatus(GL_FRAMEBUFFER) ==
2706 GL_FRAMEBUFFER_COMPLETE ||
2707 IsContextLost());
2709 InitializeViewport(
2710 frame, target_rect, gfx::Rect(target_rect.size()), target_rect.size());
2711 return true;
2714 void GLRenderer::SetScissorTestRect(const gfx::Rect& scissor_rect) {
2715 EnsureScissorTestEnabled();
2717 // Don't unnecessarily ask the context to change the scissor, because it
2718 // may cause undesired GPU pipeline flushes.
2719 if (scissor_rect == scissor_rect_ && !scissor_rect_needs_reset_)
2720 return;
2722 scissor_rect_ = scissor_rect;
2723 FlushTextureQuadCache();
2724 GLC(gl_,
2725 gl_->Scissor(scissor_rect.x(),
2726 scissor_rect.y(),
2727 scissor_rect.width(),
2728 scissor_rect.height()));
2730 scissor_rect_needs_reset_ = false;
2733 void GLRenderer::SetDrawViewport(const gfx::Rect& window_space_viewport) {
2734 viewport_ = window_space_viewport;
2735 GLC(gl_,
2736 gl_->Viewport(window_space_viewport.x(),
2737 window_space_viewport.y(),
2738 window_space_viewport.width(),
2739 window_space_viewport.height()));
2742 void GLRenderer::InitializeSharedObjects() {
2743 TRACE_EVENT0("cc", "GLRenderer::InitializeSharedObjects");
2745 // Create an FBO for doing offscreen rendering.
2746 GLC(gl_, gl_->GenFramebuffers(1, &offscreen_framebuffer_id_));
2748 shared_geometry_ = make_scoped_ptr(
2749 new GeometryBinding(gl_, QuadVertexRect()));
2752 const GLRenderer::TileCheckerboardProgram*
2753 GLRenderer::GetTileCheckerboardProgram() {
2754 if (!tile_checkerboard_program_.initialized()) {
2755 TRACE_EVENT0("cc", "GLRenderer::checkerboardProgram::initalize");
2756 tile_checkerboard_program_.Initialize(output_surface_->context_provider(),
2757 TexCoordPrecisionNA,
2758 SamplerTypeNA);
2760 return &tile_checkerboard_program_;
2763 const GLRenderer::DebugBorderProgram* GLRenderer::GetDebugBorderProgram() {
2764 if (!debug_border_program_.initialized()) {
2765 TRACE_EVENT0("cc", "GLRenderer::debugBorderProgram::initialize");
2766 debug_border_program_.Initialize(output_surface_->context_provider(),
2767 TexCoordPrecisionNA,
2768 SamplerTypeNA);
2770 return &debug_border_program_;
2773 const GLRenderer::SolidColorProgram* GLRenderer::GetSolidColorProgram() {
2774 if (!solid_color_program_.initialized()) {
2775 TRACE_EVENT0("cc", "GLRenderer::solidColorProgram::initialize");
2776 solid_color_program_.Initialize(output_surface_->context_provider(),
2777 TexCoordPrecisionNA,
2778 SamplerTypeNA);
2780 return &solid_color_program_;
2783 const GLRenderer::SolidColorProgramAA* GLRenderer::GetSolidColorProgramAA() {
2784 if (!solid_color_program_aa_.initialized()) {
2785 TRACE_EVENT0("cc", "GLRenderer::solidColorProgramAA::initialize");
2786 solid_color_program_aa_.Initialize(output_surface_->context_provider(),
2787 TexCoordPrecisionNA,
2788 SamplerTypeNA);
2790 return &solid_color_program_aa_;
2793 const GLRenderer::RenderPassProgram* GLRenderer::GetRenderPassProgram(
2794 TexCoordPrecision precision,
2795 BlendMode blend_mode) {
2796 DCHECK_GE(precision, 0);
2797 DCHECK_LT(precision, NumTexCoordPrecisions);
2798 DCHECK_GE(blend_mode, 0);
2799 DCHECK_LT(blend_mode, NumBlendModes);
2800 RenderPassProgram* program = &render_pass_program_[precision][blend_mode];
2801 if (!program->initialized()) {
2802 TRACE_EVENT0("cc", "GLRenderer::renderPassProgram::initialize");
2803 program->Initialize(output_surface_->context_provider(),
2804 precision,
2805 SamplerType2D,
2806 blend_mode);
2808 return program;
2811 const GLRenderer::RenderPassProgramAA* GLRenderer::GetRenderPassProgramAA(
2812 TexCoordPrecision precision,
2813 BlendMode blend_mode) {
2814 DCHECK_GE(precision, 0);
2815 DCHECK_LT(precision, NumTexCoordPrecisions);
2816 DCHECK_GE(blend_mode, 0);
2817 DCHECK_LT(blend_mode, NumBlendModes);
2818 RenderPassProgramAA* program =
2819 &render_pass_program_aa_[precision][blend_mode];
2820 if (!program->initialized()) {
2821 TRACE_EVENT0("cc", "GLRenderer::renderPassProgramAA::initialize");
2822 program->Initialize(output_surface_->context_provider(),
2823 precision,
2824 SamplerType2D,
2825 blend_mode);
2827 return program;
2830 const GLRenderer::RenderPassMaskProgram* GLRenderer::GetRenderPassMaskProgram(
2831 TexCoordPrecision precision,
2832 SamplerType sampler,
2833 BlendMode blend_mode) {
2834 DCHECK_GE(precision, 0);
2835 DCHECK_LT(precision, NumTexCoordPrecisions);
2836 DCHECK_GE(sampler, 0);
2837 DCHECK_LT(sampler, NumSamplerTypes);
2838 DCHECK_GE(blend_mode, 0);
2839 DCHECK_LT(blend_mode, NumBlendModes);
2840 RenderPassMaskProgram* program =
2841 &render_pass_mask_program_[precision][sampler][blend_mode];
2842 if (!program->initialized()) {
2843 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgram::initialize");
2844 program->Initialize(
2845 output_surface_->context_provider(), precision, sampler, blend_mode);
2847 return program;
2850 const GLRenderer::RenderPassMaskProgramAA*
2851 GLRenderer::GetRenderPassMaskProgramAA(TexCoordPrecision precision,
2852 SamplerType sampler,
2853 BlendMode blend_mode) {
2854 DCHECK_GE(precision, 0);
2855 DCHECK_LT(precision, NumTexCoordPrecisions);
2856 DCHECK_GE(sampler, 0);
2857 DCHECK_LT(sampler, NumSamplerTypes);
2858 DCHECK_GE(blend_mode, 0);
2859 DCHECK_LT(blend_mode, NumBlendModes);
2860 RenderPassMaskProgramAA* program =
2861 &render_pass_mask_program_aa_[precision][sampler][blend_mode];
2862 if (!program->initialized()) {
2863 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgramAA::initialize");
2864 program->Initialize(
2865 output_surface_->context_provider(), precision, sampler, blend_mode);
2867 return program;
2870 const GLRenderer::RenderPassColorMatrixProgram*
2871 GLRenderer::GetRenderPassColorMatrixProgram(TexCoordPrecision precision,
2872 BlendMode blend_mode) {
2873 DCHECK_GE(precision, 0);
2874 DCHECK_LT(precision, NumTexCoordPrecisions);
2875 DCHECK_GE(blend_mode, 0);
2876 DCHECK_LT(blend_mode, NumBlendModes);
2877 RenderPassColorMatrixProgram* program =
2878 &render_pass_color_matrix_program_[precision][blend_mode];
2879 if (!program->initialized()) {
2880 TRACE_EVENT0("cc", "GLRenderer::renderPassColorMatrixProgram::initialize");
2881 program->Initialize(output_surface_->context_provider(),
2882 precision,
2883 SamplerType2D,
2884 blend_mode);
2886 return program;
2889 const GLRenderer::RenderPassColorMatrixProgramAA*
2890 GLRenderer::GetRenderPassColorMatrixProgramAA(TexCoordPrecision precision,
2891 BlendMode blend_mode) {
2892 DCHECK_GE(precision, 0);
2893 DCHECK_LT(precision, NumTexCoordPrecisions);
2894 DCHECK_GE(blend_mode, 0);
2895 DCHECK_LT(blend_mode, NumBlendModes);
2896 RenderPassColorMatrixProgramAA* program =
2897 &render_pass_color_matrix_program_aa_[precision][blend_mode];
2898 if (!program->initialized()) {
2899 TRACE_EVENT0("cc",
2900 "GLRenderer::renderPassColorMatrixProgramAA::initialize");
2901 program->Initialize(output_surface_->context_provider(),
2902 precision,
2903 SamplerType2D,
2904 blend_mode);
2906 return program;
2909 const GLRenderer::RenderPassMaskColorMatrixProgram*
2910 GLRenderer::GetRenderPassMaskColorMatrixProgram(TexCoordPrecision precision,
2911 SamplerType sampler,
2912 BlendMode blend_mode) {
2913 DCHECK_GE(precision, 0);
2914 DCHECK_LT(precision, NumTexCoordPrecisions);
2915 DCHECK_GE(sampler, 0);
2916 DCHECK_LT(sampler, NumSamplerTypes);
2917 DCHECK_GE(blend_mode, 0);
2918 DCHECK_LT(blend_mode, NumBlendModes);
2919 RenderPassMaskColorMatrixProgram* program =
2920 &render_pass_mask_color_matrix_program_[precision][sampler][blend_mode];
2921 if (!program->initialized()) {
2922 TRACE_EVENT0("cc",
2923 "GLRenderer::renderPassMaskColorMatrixProgram::initialize");
2924 program->Initialize(
2925 output_surface_->context_provider(), precision, sampler, blend_mode);
2927 return program;
2930 const GLRenderer::RenderPassMaskColorMatrixProgramAA*
2931 GLRenderer::GetRenderPassMaskColorMatrixProgramAA(TexCoordPrecision precision,
2932 SamplerType sampler,
2933 BlendMode blend_mode) {
2934 DCHECK_GE(precision, 0);
2935 DCHECK_LT(precision, NumTexCoordPrecisions);
2936 DCHECK_GE(sampler, 0);
2937 DCHECK_LT(sampler, NumSamplerTypes);
2938 DCHECK_GE(blend_mode, 0);
2939 DCHECK_LT(blend_mode, NumBlendModes);
2940 RenderPassMaskColorMatrixProgramAA* program =
2941 &render_pass_mask_color_matrix_program_aa_[precision][sampler]
2942 [blend_mode];
2943 if (!program->initialized()) {
2944 TRACE_EVENT0("cc",
2945 "GLRenderer::renderPassMaskColorMatrixProgramAA::initialize");
2946 program->Initialize(
2947 output_surface_->context_provider(), precision, sampler, blend_mode);
2949 return program;
2952 const GLRenderer::TileProgram* GLRenderer::GetTileProgram(
2953 TexCoordPrecision precision,
2954 SamplerType sampler) {
2955 DCHECK_GE(precision, 0);
2956 DCHECK_LT(precision, NumTexCoordPrecisions);
2957 DCHECK_GE(sampler, 0);
2958 DCHECK_LT(sampler, NumSamplerTypes);
2959 TileProgram* program = &tile_program_[precision][sampler];
2960 if (!program->initialized()) {
2961 TRACE_EVENT0("cc", "GLRenderer::tileProgram::initialize");
2962 program->Initialize(
2963 output_surface_->context_provider(), precision, sampler);
2965 return program;
2968 const GLRenderer::TileProgramOpaque* GLRenderer::GetTileProgramOpaque(
2969 TexCoordPrecision precision,
2970 SamplerType sampler) {
2971 DCHECK_GE(precision, 0);
2972 DCHECK_LT(precision, NumTexCoordPrecisions);
2973 DCHECK_GE(sampler, 0);
2974 DCHECK_LT(sampler, NumSamplerTypes);
2975 TileProgramOpaque* program = &tile_program_opaque_[precision][sampler];
2976 if (!program->initialized()) {
2977 TRACE_EVENT0("cc", "GLRenderer::tileProgramOpaque::initialize");
2978 program->Initialize(
2979 output_surface_->context_provider(), precision, sampler);
2981 return program;
2984 const GLRenderer::TileProgramAA* GLRenderer::GetTileProgramAA(
2985 TexCoordPrecision precision,
2986 SamplerType sampler) {
2987 DCHECK_GE(precision, 0);
2988 DCHECK_LT(precision, NumTexCoordPrecisions);
2989 DCHECK_GE(sampler, 0);
2990 DCHECK_LT(sampler, NumSamplerTypes);
2991 TileProgramAA* program = &tile_program_aa_[precision][sampler];
2992 if (!program->initialized()) {
2993 TRACE_EVENT0("cc", "GLRenderer::tileProgramAA::initialize");
2994 program->Initialize(
2995 output_surface_->context_provider(), precision, sampler);
2997 return program;
3000 const GLRenderer::TileProgramSwizzle* GLRenderer::GetTileProgramSwizzle(
3001 TexCoordPrecision precision,
3002 SamplerType sampler) {
3003 DCHECK_GE(precision, 0);
3004 DCHECK_LT(precision, NumTexCoordPrecisions);
3005 DCHECK_GE(sampler, 0);
3006 DCHECK_LT(sampler, NumSamplerTypes);
3007 TileProgramSwizzle* program = &tile_program_swizzle_[precision][sampler];
3008 if (!program->initialized()) {
3009 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzle::initialize");
3010 program->Initialize(
3011 output_surface_->context_provider(), precision, sampler);
3013 return program;
3016 const GLRenderer::TileProgramSwizzleOpaque*
3017 GLRenderer::GetTileProgramSwizzleOpaque(TexCoordPrecision precision,
3018 SamplerType sampler) {
3019 DCHECK_GE(precision, 0);
3020 DCHECK_LT(precision, NumTexCoordPrecisions);
3021 DCHECK_GE(sampler, 0);
3022 DCHECK_LT(sampler, NumSamplerTypes);
3023 TileProgramSwizzleOpaque* program =
3024 &tile_program_swizzle_opaque_[precision][sampler];
3025 if (!program->initialized()) {
3026 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleOpaque::initialize");
3027 program->Initialize(
3028 output_surface_->context_provider(), precision, sampler);
3030 return program;
3033 const GLRenderer::TileProgramSwizzleAA* GLRenderer::GetTileProgramSwizzleAA(
3034 TexCoordPrecision precision,
3035 SamplerType sampler) {
3036 DCHECK_GE(precision, 0);
3037 DCHECK_LT(precision, NumTexCoordPrecisions);
3038 DCHECK_GE(sampler, 0);
3039 DCHECK_LT(sampler, NumSamplerTypes);
3040 TileProgramSwizzleAA* program = &tile_program_swizzle_aa_[precision][sampler];
3041 if (!program->initialized()) {
3042 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleAA::initialize");
3043 program->Initialize(
3044 output_surface_->context_provider(), precision, sampler);
3046 return program;
3049 const GLRenderer::TextureProgram* GLRenderer::GetTextureProgram(
3050 TexCoordPrecision precision) {
3051 DCHECK_GE(precision, 0);
3052 DCHECK_LT(precision, NumTexCoordPrecisions);
3053 TextureProgram* program = &texture_program_[precision];
3054 if (!program->initialized()) {
3055 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3056 program->Initialize(
3057 output_surface_->context_provider(), precision, SamplerType2D);
3059 return program;
3062 const GLRenderer::NonPremultipliedTextureProgram*
3063 GLRenderer::GetNonPremultipliedTextureProgram(TexCoordPrecision precision) {
3064 DCHECK_GE(precision, 0);
3065 DCHECK_LT(precision, NumTexCoordPrecisions);
3066 NonPremultipliedTextureProgram* program =
3067 &nonpremultiplied_texture_program_[precision];
3068 if (!program->initialized()) {
3069 TRACE_EVENT0("cc",
3070 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3071 program->Initialize(
3072 output_surface_->context_provider(), precision, SamplerType2D);
3074 return program;
3077 const GLRenderer::TextureBackgroundProgram*
3078 GLRenderer::GetTextureBackgroundProgram(TexCoordPrecision precision) {
3079 DCHECK_GE(precision, 0);
3080 DCHECK_LT(precision, NumTexCoordPrecisions);
3081 TextureBackgroundProgram* program = &texture_background_program_[precision];
3082 if (!program->initialized()) {
3083 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3084 program->Initialize(
3085 output_surface_->context_provider(), precision, SamplerType2D);
3087 return program;
3090 const GLRenderer::NonPremultipliedTextureBackgroundProgram*
3091 GLRenderer::GetNonPremultipliedTextureBackgroundProgram(
3092 TexCoordPrecision precision) {
3093 DCHECK_GE(precision, 0);
3094 DCHECK_LT(precision, NumTexCoordPrecisions);
3095 NonPremultipliedTextureBackgroundProgram* program =
3096 &nonpremultiplied_texture_background_program_[precision];
3097 if (!program->initialized()) {
3098 TRACE_EVENT0("cc",
3099 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3100 program->Initialize(
3101 output_surface_->context_provider(), precision, SamplerType2D);
3103 return program;
3106 const GLRenderer::TextureProgram* GLRenderer::GetTextureIOSurfaceProgram(
3107 TexCoordPrecision precision) {
3108 DCHECK_GE(precision, 0);
3109 DCHECK_LT(precision, NumTexCoordPrecisions);
3110 TextureProgram* program = &texture_io_surface_program_[precision];
3111 if (!program->initialized()) {
3112 TRACE_EVENT0("cc", "GLRenderer::textureIOSurfaceProgram::initialize");
3113 program->Initialize(
3114 output_surface_->context_provider(), precision, SamplerType2DRect);
3116 return program;
3119 const GLRenderer::VideoYUVProgram* GLRenderer::GetVideoYUVProgram(
3120 TexCoordPrecision precision) {
3121 DCHECK_GE(precision, 0);
3122 DCHECK_LT(precision, NumTexCoordPrecisions);
3123 VideoYUVProgram* program = &video_yuv_program_[precision];
3124 if (!program->initialized()) {
3125 TRACE_EVENT0("cc", "GLRenderer::videoYUVProgram::initialize");
3126 program->Initialize(
3127 output_surface_->context_provider(), precision, SamplerType2D);
3129 return program;
3132 const GLRenderer::VideoYUVAProgram* GLRenderer::GetVideoYUVAProgram(
3133 TexCoordPrecision precision) {
3134 DCHECK_GE(precision, 0);
3135 DCHECK_LT(precision, NumTexCoordPrecisions);
3136 VideoYUVAProgram* program = &video_yuva_program_[precision];
3137 if (!program->initialized()) {
3138 TRACE_EVENT0("cc", "GLRenderer::videoYUVAProgram::initialize");
3139 program->Initialize(
3140 output_surface_->context_provider(), precision, SamplerType2D);
3142 return program;
3145 const GLRenderer::VideoStreamTextureProgram*
3146 GLRenderer::GetVideoStreamTextureProgram(TexCoordPrecision precision) {
3147 if (!Capabilities().using_egl_image)
3148 return NULL;
3149 DCHECK_GE(precision, 0);
3150 DCHECK_LT(precision, NumTexCoordPrecisions);
3151 VideoStreamTextureProgram* program =
3152 &video_stream_texture_program_[precision];
3153 if (!program->initialized()) {
3154 TRACE_EVENT0("cc", "GLRenderer::streamTextureProgram::initialize");
3155 program->Initialize(
3156 output_surface_->context_provider(), precision, SamplerTypeExternalOES);
3158 return program;
3161 void GLRenderer::CleanupSharedObjects() {
3162 shared_geometry_ = nullptr;
3164 for (int i = 0; i < NumTexCoordPrecisions; ++i) {
3165 for (int j = 0; j < NumSamplerTypes; ++j) {
3166 tile_program_[i][j].Cleanup(gl_);
3167 tile_program_opaque_[i][j].Cleanup(gl_);
3168 tile_program_swizzle_[i][j].Cleanup(gl_);
3169 tile_program_swizzle_opaque_[i][j].Cleanup(gl_);
3170 tile_program_aa_[i][j].Cleanup(gl_);
3171 tile_program_swizzle_aa_[i][j].Cleanup(gl_);
3173 for (int k = 0; k < NumBlendModes; k++) {
3174 render_pass_mask_program_[i][j][k].Cleanup(gl_);
3175 render_pass_mask_program_aa_[i][j][k].Cleanup(gl_);
3176 render_pass_mask_color_matrix_program_aa_[i][j][k].Cleanup(gl_);
3177 render_pass_mask_color_matrix_program_[i][j][k].Cleanup(gl_);
3180 for (int j = 0; j < NumBlendModes; j++) {
3181 render_pass_program_[i][j].Cleanup(gl_);
3182 render_pass_program_aa_[i][j].Cleanup(gl_);
3183 render_pass_color_matrix_program_[i][j].Cleanup(gl_);
3184 render_pass_color_matrix_program_aa_[i][j].Cleanup(gl_);
3187 texture_program_[i].Cleanup(gl_);
3188 nonpremultiplied_texture_program_[i].Cleanup(gl_);
3189 texture_background_program_[i].Cleanup(gl_);
3190 nonpremultiplied_texture_background_program_[i].Cleanup(gl_);
3191 texture_io_surface_program_[i].Cleanup(gl_);
3193 video_yuv_program_[i].Cleanup(gl_);
3194 video_yuva_program_[i].Cleanup(gl_);
3195 video_stream_texture_program_[i].Cleanup(gl_);
3198 tile_checkerboard_program_.Cleanup(gl_);
3200 debug_border_program_.Cleanup(gl_);
3201 solid_color_program_.Cleanup(gl_);
3202 solid_color_program_aa_.Cleanup(gl_);
3204 if (offscreen_framebuffer_id_)
3205 GLC(gl_, gl_->DeleteFramebuffers(1, &offscreen_framebuffer_id_));
3207 if (on_demand_tile_raster_resource_id_)
3208 resource_provider_->DeleteResource(on_demand_tile_raster_resource_id_);
3210 ReleaseRenderPassTextures();
3213 void GLRenderer::ReinitializeGLState() {
3214 is_scissor_enabled_ = false;
3215 scissor_rect_needs_reset_ = true;
3216 stencil_shadow_ = false;
3217 blend_shadow_ = true;
3218 program_shadow_ = 0;
3220 RestoreGLState();
3223 void GLRenderer::RestoreGLState() {
3224 // This restores the current GLRenderer state to the GL context.
3226 shared_geometry_->PrepareForDraw();
3228 GLC(gl_, gl_->Disable(GL_DEPTH_TEST));
3229 GLC(gl_, gl_->Disable(GL_CULL_FACE));
3230 GLC(gl_, gl_->ColorMask(true, true, true, true));
3231 GLC(gl_, gl_->BlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA));
3232 GLC(gl_, gl_->ActiveTexture(GL_TEXTURE0));
3234 if (program_shadow_)
3235 gl_->UseProgram(program_shadow_);
3237 if (stencil_shadow_)
3238 GLC(gl_, gl_->Enable(GL_STENCIL_TEST));
3239 else
3240 GLC(gl_, gl_->Disable(GL_STENCIL_TEST));
3242 if (blend_shadow_)
3243 GLC(gl_, gl_->Enable(GL_BLEND));
3244 else
3245 GLC(gl_, gl_->Disable(GL_BLEND));
3247 if (is_scissor_enabled_) {
3248 GLC(gl_, gl_->Enable(GL_SCISSOR_TEST));
3249 GLC(gl_,
3250 gl_->Scissor(scissor_rect_.x(),
3251 scissor_rect_.y(),
3252 scissor_rect_.width(),
3253 scissor_rect_.height()));
3254 } else {
3255 GLC(gl_, gl_->Disable(GL_SCISSOR_TEST));
3259 void GLRenderer::RestoreFramebuffer(DrawingFrame* frame) {
3260 UseRenderPass(frame, frame->current_render_pass);
3263 bool GLRenderer::IsContextLost() {
3264 return output_surface_->context_provider()->IsContextLost();
3267 void GLRenderer::ScheduleOverlays(DrawingFrame* frame) {
3268 if (!frame->overlay_list.size())
3269 return;
3271 ResourceProvider::ResourceIdArray resources;
3272 OverlayCandidateList& overlays = frame->overlay_list;
3273 OverlayCandidateList::iterator it;
3274 for (it = overlays.begin(); it != overlays.end(); ++it) {
3275 const OverlayCandidate& overlay = *it;
3276 // Skip primary plane.
3277 if (overlay.plane_z_order == 0)
3278 continue;
3280 pending_overlay_resources_.push_back(
3281 make_scoped_ptr(new ResourceProvider::ScopedReadLockGL(
3282 resource_provider_, overlay.resource_id)));
3284 context_support_->ScheduleOverlayPlane(
3285 overlay.plane_z_order,
3286 overlay.transform,
3287 pending_overlay_resources_.back()->texture_id(),
3288 overlay.display_rect,
3289 overlay.uv_rect);
3293 } // namespace cc