Fix import error in mac_platform_backend.py
[chromium-blink-merge.git] / cc / output / gl_renderer.cc
blob353ea6a9cef61da895eb9a6e0d86cf4d574b3f28
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 "base/strings/string_split.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "build/build_config.h"
19 #include "cc/base/math_util.h"
20 #include "cc/layers/video_layer_impl.h"
21 #include "cc/output/compositor_frame.h"
22 #include "cc/output/compositor_frame_metadata.h"
23 #include "cc/output/context_provider.h"
24 #include "cc/output/copy_output_request.h"
25 #include "cc/output/geometry_binding.h"
26 #include "cc/output/gl_frame_data.h"
27 #include "cc/output/output_surface.h"
28 #include "cc/output/render_surface_filters.h"
29 #include "cc/quads/picture_draw_quad.h"
30 #include "cc/quads/render_pass.h"
31 #include "cc/quads/stream_video_draw_quad.h"
32 #include "cc/quads/texture_draw_quad.h"
33 #include "cc/resources/layer_quad.h"
34 #include "cc/resources/scoped_resource.h"
35 #include "cc/resources/texture_mailbox_deleter.h"
36 #include "cc/trees/damage_tracker.h"
37 #include "cc/trees/proxy.h"
38 #include "cc/trees/single_thread_proxy.h"
39 #include "gpu/GLES2/gl2extchromium.h"
40 #include "gpu/command_buffer/client/context_support.h"
41 #include "gpu/command_buffer/client/gles2_interface.h"
42 #include "gpu/command_buffer/common/gpu_memory_allocation.h"
43 #include "third_party/khronos/GLES2/gl2.h"
44 #include "third_party/khronos/GLES2/gl2ext.h"
45 #include "third_party/skia/include/core/SkBitmap.h"
46 #include "third_party/skia/include/core/SkColor.h"
47 #include "third_party/skia/include/core/SkColorFilter.h"
48 #include "third_party/skia/include/core/SkSurface.h"
49 #include "third_party/skia/include/gpu/GrContext.h"
50 #include "third_party/skia/include/gpu/GrTexture.h"
51 #include "third_party/skia/include/gpu/SkGpuDevice.h"
52 #include "third_party/skia/include/gpu/SkGrTexturePixelRef.h"
53 #include "third_party/skia/include/gpu/gl/GrGLInterface.h"
54 #include "ui/gfx/quad_f.h"
55 #include "ui/gfx/rect_conversions.h"
57 using gpu::gles2::GLES2Interface;
59 namespace cc {
61 namespace {
63 // TODO(epenner): This should probably be moved to output surface.
65 // This implements a simple fence based on client side swaps.
66 // This is to isolate the ResourceProvider from 'frames' which
67 // it shouldn't need to care about, while still allowing us to
68 // enforce good texture recycling behavior strictly throughout
69 // the compositor (don't recycle a texture while it's in use).
70 class SimpleSwapFence : public ResourceProvider::Fence {
71 public:
72 SimpleSwapFence() : has_passed_(false) {}
73 virtual bool HasPassed() OVERRIDE { return has_passed_; }
74 void SetHasPassed() { has_passed_ = true; }
76 private:
77 virtual ~SimpleSwapFence() {}
78 bool has_passed_;
81 bool NeedsIOSurfaceReadbackWorkaround() {
82 #if defined(OS_MACOSX)
83 // This isn't strictly required in DumpRenderTree-mode when Mesa is used,
84 // but it doesn't seem to hurt.
85 return true;
86 #else
87 return false;
88 #endif
91 Float4 UVTransform(const TextureDrawQuad* quad) {
92 gfx::PointF uv0 = quad->uv_top_left;
93 gfx::PointF uv1 = quad->uv_bottom_right;
94 Float4 xform = {{uv0.x(), uv0.y(), uv1.x() - uv0.x(), uv1.y() - uv0.y()}};
95 if (quad->flipped) {
96 xform.data[1] = 1.0f - xform.data[1];
97 xform.data[3] = -xform.data[3];
99 return xform;
102 Float4 PremultipliedColor(SkColor color) {
103 const float factor = 1.0f / 255.0f;
104 const float alpha = SkColorGetA(color) * factor;
106 Float4 result = {
107 {SkColorGetR(color) * factor * alpha, SkColorGetG(color) * factor * alpha,
108 SkColorGetB(color) * factor * alpha, alpha}};
109 return result;
112 SamplerType SamplerTypeFromTextureTarget(GLenum target) {
113 switch (target) {
114 case GL_TEXTURE_2D:
115 return SamplerType2D;
116 case GL_TEXTURE_RECTANGLE_ARB:
117 return SamplerType2DRect;
118 case GL_TEXTURE_EXTERNAL_OES:
119 return SamplerTypeExternalOES;
120 default:
121 NOTREACHED();
122 return SamplerType2D;
126 // Smallest unit that impact anti-aliasing output. We use this to
127 // determine when anti-aliasing is unnecessary.
128 const float kAntiAliasingEpsilon = 1.0f / 1024.0f;
130 } // anonymous namespace
132 struct GLRenderer::PendingAsyncReadPixels {
133 PendingAsyncReadPixels() : buffer(0) {}
135 scoped_ptr<CopyOutputRequest> copy_request;
136 base::CancelableClosure finished_read_pixels_callback;
137 unsigned buffer;
139 private:
140 DISALLOW_COPY_AND_ASSIGN(PendingAsyncReadPixels);
143 scoped_ptr<GLRenderer> GLRenderer::Create(
144 RendererClient* client,
145 const LayerTreeSettings* settings,
146 OutputSurface* output_surface,
147 ResourceProvider* resource_provider,
148 TextureMailboxDeleter* texture_mailbox_deleter,
149 int highp_threshold_min) {
150 return make_scoped_ptr(new GLRenderer(client,
151 settings,
152 output_surface,
153 resource_provider,
154 texture_mailbox_deleter,
155 highp_threshold_min));
158 GLRenderer::GLRenderer(RendererClient* client,
159 const LayerTreeSettings* settings,
160 OutputSurface* output_surface,
161 ResourceProvider* resource_provider,
162 TextureMailboxDeleter* texture_mailbox_deleter,
163 int highp_threshold_min)
164 : DirectRenderer(client, settings, output_surface, resource_provider),
165 offscreen_framebuffer_id_(0),
166 shared_geometry_quad_(gfx::RectF(-0.5f, -0.5f, 1.0f, 1.0f)),
167 gl_(output_surface->context_provider()->ContextGL()),
168 context_support_(output_surface->context_provider()->ContextSupport()),
169 texture_mailbox_deleter_(texture_mailbox_deleter),
170 is_backbuffer_discarded_(false),
171 visible_(true),
172 is_scissor_enabled_(false),
173 scissor_rect_needs_reset_(true),
174 stencil_shadow_(false),
175 blend_shadow_(false),
176 highp_threshold_min_(highp_threshold_min),
177 highp_threshold_cache_(0),
178 on_demand_tile_raster_resource_id_(0) {
179 DCHECK(gl_);
180 DCHECK(context_support_);
182 ContextProvider::Capabilities context_caps =
183 output_surface_->context_provider()->ContextCapabilities();
185 capabilities_.using_partial_swap =
186 settings_->partial_swap_enabled && context_caps.gpu.post_sub_buffer;
188 DCHECK(!context_caps.gpu.iosurface || context_caps.gpu.texture_rectangle);
190 capabilities_.using_egl_image = context_caps.gpu.egl_image_external;
192 capabilities_.max_texture_size = resource_provider_->max_texture_size();
193 capabilities_.best_texture_format = resource_provider_->best_texture_format();
195 // The updater can access textures while the GLRenderer is using them.
196 capabilities_.allow_partial_texture_updates = true;
198 // Check for texture fast paths. Currently we always use MO8 textures,
199 // so we only need to avoid POT textures if we have an NPOT fast-path.
200 capabilities_.avoid_pow2_textures = context_caps.gpu.fast_npot_mo8_textures;
202 capabilities_.using_offscreen_context3d = true;
204 capabilities_.using_map_image =
205 settings_->use_map_image && context_caps.gpu.map_image;
207 capabilities_.using_discard_framebuffer =
208 context_caps.gpu.discard_framebuffer;
210 InitializeSharedObjects();
213 GLRenderer::~GLRenderer() {
214 while (!pending_async_read_pixels_.empty()) {
215 PendingAsyncReadPixels* pending_read = pending_async_read_pixels_.back();
216 pending_read->finished_read_pixels_callback.Cancel();
217 pending_async_read_pixels_.pop_back();
220 CleanupSharedObjects();
223 const RendererCapabilitiesImpl& GLRenderer::Capabilities() const {
224 return capabilities_;
227 void GLRenderer::DebugGLCall(GLES2Interface* gl,
228 const char* command,
229 const char* file,
230 int line) {
231 GLuint error = gl->GetError();
232 if (error != GL_NO_ERROR)
233 LOG(ERROR) << "GL command failed: File: " << file << "\n\tLine " << line
234 << "\n\tcommand: " << command << ", error "
235 << static_cast<int>(error) << "\n";
238 void GLRenderer::SetVisible(bool visible) {
239 if (visible_ == visible)
240 return;
241 visible_ = visible;
243 EnforceMemoryPolicy();
245 context_support_->SetSurfaceVisible(visible);
248 void GLRenderer::SendManagedMemoryStats(size_t bytes_visible,
249 size_t bytes_visible_and_nearby,
250 size_t bytes_allocated) {
251 gpu::ManagedMemoryStats stats;
252 stats.bytes_required = bytes_visible;
253 stats.bytes_nice_to_have = bytes_visible_and_nearby;
254 stats.bytes_allocated = bytes_allocated;
255 stats.backbuffer_requested = !is_backbuffer_discarded_;
256 context_support_->SendManagedMemoryStats(stats);
259 void GLRenderer::ReleaseRenderPassTextures() { render_pass_textures_.clear(); }
261 void GLRenderer::DiscardPixels(bool has_external_stencil_test,
262 bool draw_rect_covers_full_surface) {
263 if (has_external_stencil_test || !draw_rect_covers_full_surface ||
264 !capabilities_.using_discard_framebuffer)
265 return;
266 bool using_default_framebuffer =
267 !current_framebuffer_lock_ &&
268 output_surface_->capabilities().uses_default_gl_framebuffer;
269 GLenum attachments[] = {static_cast<GLenum>(
270 using_default_framebuffer ? GL_COLOR_EXT : GL_COLOR_ATTACHMENT0_EXT)};
271 gl_->DiscardFramebufferEXT(
272 GL_FRAMEBUFFER, arraysize(attachments), attachments);
275 void GLRenderer::ClearFramebuffer(DrawingFrame* frame,
276 bool has_external_stencil_test) {
277 // It's unsafe to clear when we have a stencil test because glClear ignores
278 // stencil.
279 if (has_external_stencil_test) {
280 DCHECK(!frame->current_render_pass->has_transparent_background);
281 return;
284 // On DEBUG builds, opaque render passes are cleared to blue to easily see
285 // regions that were not drawn on the screen.
286 if (frame->current_render_pass->has_transparent_background)
287 GLC(gl_, gl_->ClearColor(0, 0, 0, 0));
288 else
289 GLC(gl_, gl_->ClearColor(0, 0, 1, 1));
291 bool always_clear = false;
292 #ifndef NDEBUG
293 always_clear = true;
294 #endif
295 if (always_clear || frame->current_render_pass->has_transparent_background) {
296 GLbitfield clear_bits = GL_COLOR_BUFFER_BIT;
297 if (always_clear)
298 clear_bits |= GL_STENCIL_BUFFER_BIT;
299 gl_->Clear(clear_bits);
303 void GLRenderer::BeginDrawingFrame(DrawingFrame* frame) {
304 if (frame->device_viewport_rect.IsEmpty())
305 return;
307 TRACE_EVENT0("cc", "GLRenderer::BeginDrawingFrame");
309 // TODO(enne): Do we need to reinitialize all of this state per frame?
310 ReinitializeGLState();
313 void GLRenderer::DoNoOp() {
314 GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, 0));
315 GLC(gl_, gl_->Flush());
318 void GLRenderer::DoDrawQuad(DrawingFrame* frame, const DrawQuad* quad) {
319 DCHECK(quad->rect.Contains(quad->visible_rect));
320 if (quad->material != DrawQuad::TEXTURE_CONTENT) {
321 FlushTextureQuadCache();
324 switch (quad->material) {
325 case DrawQuad::INVALID:
326 NOTREACHED();
327 break;
328 case DrawQuad::CHECKERBOARD:
329 DrawCheckerboardQuad(frame, CheckerboardDrawQuad::MaterialCast(quad));
330 break;
331 case DrawQuad::DEBUG_BORDER:
332 DrawDebugBorderQuad(frame, DebugBorderDrawQuad::MaterialCast(quad));
333 break;
334 case DrawQuad::IO_SURFACE_CONTENT:
335 DrawIOSurfaceQuad(frame, IOSurfaceDrawQuad::MaterialCast(quad));
336 break;
337 case DrawQuad::PICTURE_CONTENT:
338 DrawPictureQuad(frame, PictureDrawQuad::MaterialCast(quad));
339 break;
340 case DrawQuad::RENDER_PASS:
341 DrawRenderPassQuad(frame, RenderPassDrawQuad::MaterialCast(quad));
342 break;
343 case DrawQuad::SOLID_COLOR:
344 DrawSolidColorQuad(frame, SolidColorDrawQuad::MaterialCast(quad));
345 break;
346 case DrawQuad::STREAM_VIDEO_CONTENT:
347 DrawStreamVideoQuad(frame, StreamVideoDrawQuad::MaterialCast(quad));
348 break;
349 case DrawQuad::SURFACE_CONTENT:
350 // Surface content should be fully resolved to other quad types before
351 // reaching a direct renderer.
352 NOTREACHED();
353 break;
354 case DrawQuad::TEXTURE_CONTENT:
355 EnqueueTextureQuad(frame, TextureDrawQuad::MaterialCast(quad));
356 break;
357 case DrawQuad::TILED_CONTENT:
358 DrawTileQuad(frame, TileDrawQuad::MaterialCast(quad));
359 break;
360 case DrawQuad::YUV_VIDEO_CONTENT:
361 DrawYUVVideoQuad(frame, YUVVideoDrawQuad::MaterialCast(quad));
362 break;
366 void GLRenderer::DrawCheckerboardQuad(const DrawingFrame* frame,
367 const CheckerboardDrawQuad* quad) {
368 SetBlendEnabled(quad->ShouldDrawWithBlending());
370 const TileCheckerboardProgram* program = GetTileCheckerboardProgram();
371 DCHECK(program && (program->initialized() || IsContextLost()));
372 SetUseProgram(program->program());
374 SkColor color = quad->color;
375 GLC(gl_,
376 gl_->Uniform4f(program->fragment_shader().color_location(),
377 SkColorGetR(color) * (1.0f / 255.0f),
378 SkColorGetG(color) * (1.0f / 255.0f),
379 SkColorGetB(color) * (1.0f / 255.0f),
380 1));
382 const int checkerboard_width = 16;
383 float frequency = 1.0f / checkerboard_width;
385 gfx::Rect tile_rect = quad->rect;
386 float tex_offset_x = tile_rect.x() % checkerboard_width;
387 float tex_offset_y = tile_rect.y() % checkerboard_width;
388 float tex_scale_x = tile_rect.width();
389 float tex_scale_y = tile_rect.height();
390 GLC(gl_,
391 gl_->Uniform4f(program->fragment_shader().tex_transform_location(),
392 tex_offset_x,
393 tex_offset_y,
394 tex_scale_x,
395 tex_scale_y));
397 GLC(gl_,
398 gl_->Uniform1f(program->fragment_shader().frequency_location(),
399 frequency));
401 SetShaderOpacity(quad->opacity(),
402 program->fragment_shader().alpha_location());
403 DrawQuadGeometry(frame,
404 quad->quadTransform(),
405 quad->rect,
406 program->vertex_shader().matrix_location());
409 void GLRenderer::DrawDebugBorderQuad(const DrawingFrame* frame,
410 const DebugBorderDrawQuad* quad) {
411 SetBlendEnabled(quad->ShouldDrawWithBlending());
413 static float gl_matrix[16];
414 const DebugBorderProgram* program = GetDebugBorderProgram();
415 DCHECK(program && (program->initialized() || IsContextLost()));
416 SetUseProgram(program->program());
418 // Use the full quad_rect for debug quads to not move the edges based on
419 // partial swaps.
420 gfx::Rect layer_rect = quad->rect;
421 gfx::Transform render_matrix = quad->quadTransform();
422 render_matrix.Translate(0.5f * layer_rect.width() + layer_rect.x(),
423 0.5f * layer_rect.height() + layer_rect.y());
424 render_matrix.Scale(layer_rect.width(), layer_rect.height());
425 GLRenderer::ToGLMatrix(&gl_matrix[0],
426 frame->projection_matrix * render_matrix);
427 GLC(gl_,
428 gl_->UniformMatrix4fv(
429 program->vertex_shader().matrix_location(), 1, false, &gl_matrix[0]));
431 SkColor color = quad->color;
432 float alpha = SkColorGetA(color) * (1.0f / 255.0f);
434 GLC(gl_,
435 gl_->Uniform4f(program->fragment_shader().color_location(),
436 (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
437 (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
438 (SkColorGetB(color) * (1.0f / 255.0f)) * alpha,
439 alpha));
441 GLC(gl_, gl_->LineWidth(quad->width));
443 // The indices for the line are stored in the same array as the triangle
444 // indices.
445 GLC(gl_, gl_->DrawElements(GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, 0));
448 static SkBitmap ApplyImageFilter(GLRenderer* renderer,
449 ContextProvider* offscreen_contexts,
450 gfx::Point origin,
451 SkImageFilter* filter,
452 ScopedResource* source_texture_resource) {
453 if (!filter)
454 return SkBitmap();
456 if (!offscreen_contexts || !offscreen_contexts->GrContext())
457 return SkBitmap();
459 ResourceProvider::ScopedWriteLockGL lock(renderer->resource_provider(),
460 source_texture_resource->id());
462 // Flush the compositor context to ensure that textures there are available
463 // in the shared context. Do this after locking/creating the compositor
464 // texture.
465 renderer->resource_provider()->Flush();
467 // Wrap the source texture in a Ganesh platform texture.
468 GrBackendTextureDesc backend_texture_description;
469 backend_texture_description.fWidth = source_texture_resource->size().width();
470 backend_texture_description.fHeight =
471 source_texture_resource->size().height();
472 backend_texture_description.fConfig = kSkia8888_GrPixelConfig;
473 backend_texture_description.fTextureHandle = lock.texture_id();
474 backend_texture_description.fOrigin = kBottomLeft_GrSurfaceOrigin;
475 skia::RefPtr<GrTexture> texture =
476 skia::AdoptRef(offscreen_contexts->GrContext()->wrapBackendTexture(
477 backend_texture_description));
479 SkImageInfo info = {
480 source_texture_resource->size().width(),
481 source_texture_resource->size().height(),
482 kPMColor_SkColorType,
483 kPremul_SkAlphaType
485 // Place the platform texture inside an SkBitmap.
486 SkBitmap source;
487 source.setConfig(info);
488 skia::RefPtr<SkGrPixelRef> pixel_ref =
489 skia::AdoptRef(new SkGrPixelRef(info, texture.get()));
490 source.setPixelRef(pixel_ref.get());
492 // Create a scratch texture for backing store.
493 GrTextureDesc desc;
494 desc.fFlags = kRenderTarget_GrTextureFlagBit | kNoStencil_GrTextureFlagBit;
495 desc.fSampleCnt = 0;
496 desc.fWidth = source.width();
497 desc.fHeight = source.height();
498 desc.fConfig = kSkia8888_GrPixelConfig;
499 desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
500 GrAutoScratchTexture scratch_texture(
501 offscreen_contexts->GrContext(), desc, GrContext::kExact_ScratchTexMatch);
502 skia::RefPtr<GrTexture> backing_store =
503 skia::AdoptRef(scratch_texture.detach());
505 // Create a device and canvas using that backing store.
506 SkGpuDevice device(offscreen_contexts->GrContext(), backing_store.get());
507 SkCanvas canvas(&device);
509 // Draw the source bitmap through the filter to the canvas.
510 SkPaint paint;
511 paint.setImageFilter(filter);
512 canvas.clear(SK_ColorTRANSPARENT);
514 // TODO(senorblanco): in addition to the origin translation here, the canvas
515 // should also be scaled to accomodate device pixel ratio and pinch zoom. See
516 // crbug.com/281516 and crbug.com/281518.
517 canvas.translate(SkIntToScalar(-origin.x()), SkIntToScalar(-origin.y()));
518 canvas.drawSprite(source, 0, 0, &paint);
520 // Flush skia context so that all the rendered stuff appears on the
521 // texture.
522 offscreen_contexts->GrContext()->flush();
524 // Flush the GL context so rendering results from this context are
525 // visible in the compositor's context.
526 offscreen_contexts->ContextGL()->Flush();
528 return device.accessBitmap(false);
531 static SkBitmap ApplyBlendModeWithBackdrop(
532 GLRenderer* renderer,
533 ContextProvider* offscreen_contexts,
534 SkBitmap source_bitmap_with_filters,
535 ScopedResource* source_texture_resource,
536 ScopedResource* background_texture_resource,
537 SkXfermode::Mode blend_mode) {
538 if (!offscreen_contexts || !offscreen_contexts->GrContext())
539 return source_bitmap_with_filters;
541 DCHECK(background_texture_resource);
542 DCHECK(source_texture_resource);
544 gfx::Size source_size = source_texture_resource->size();
545 gfx::Size background_size = background_texture_resource->size();
547 DCHECK_LE(background_size.width(), source_size.width());
548 DCHECK_LE(background_size.height(), source_size.height());
550 int source_texture_with_filters_id;
551 scoped_ptr<ResourceProvider::ScopedReadLockGL> lock;
552 if (source_bitmap_with_filters.getTexture()) {
553 DCHECK_EQ(source_size.width(), source_bitmap_with_filters.width());
554 DCHECK_EQ(source_size.height(), source_bitmap_with_filters.height());
555 GrTexture* texture =
556 reinterpret_cast<GrTexture*>(source_bitmap_with_filters.getTexture());
557 source_texture_with_filters_id = texture->getTextureHandle();
558 } else {
559 lock.reset(new ResourceProvider::ScopedReadLockGL(
560 renderer->resource_provider(), source_texture_resource->id()));
561 source_texture_with_filters_id = lock->texture_id();
564 ResourceProvider::ScopedReadLockGL lock_background(
565 renderer->resource_provider(), background_texture_resource->id());
567 // Flush the compositor context to ensure that textures there are available
568 // in the shared context. Do this after locking/creating the compositor
569 // texture.
570 renderer->resource_provider()->Flush();
572 // Wrap the source texture in a Ganesh platform texture.
573 GrBackendTextureDesc backend_texture_description;
574 backend_texture_description.fConfig = kSkia8888_GrPixelConfig;
575 backend_texture_description.fOrigin = kBottomLeft_GrSurfaceOrigin;
577 backend_texture_description.fWidth = source_size.width();
578 backend_texture_description.fHeight = source_size.height();
579 backend_texture_description.fTextureHandle = source_texture_with_filters_id;
580 skia::RefPtr<GrTexture> source_texture =
581 skia::AdoptRef(offscreen_contexts->GrContext()->wrapBackendTexture(
582 backend_texture_description));
584 backend_texture_description.fWidth = background_size.width();
585 backend_texture_description.fHeight = background_size.height();
586 backend_texture_description.fTextureHandle = lock_background.texture_id();
587 skia::RefPtr<GrTexture> background_texture =
588 skia::AdoptRef(offscreen_contexts->GrContext()->wrapBackendTexture(
589 backend_texture_description));
591 SkImageInfo source_info = {
592 source_size.width(),
593 source_size.height(),
594 kPMColor_SkColorType,
595 kPremul_SkAlphaType
597 // Place the platform texture inside an SkBitmap.
598 SkBitmap source;
599 source.setConfig(source_info);
600 skia::RefPtr<SkGrPixelRef> source_pixel_ref =
601 skia::AdoptRef(new SkGrPixelRef(source_info, source_texture.get()));
602 source.setPixelRef(source_pixel_ref.get());
604 SkImageInfo background_info = {
605 background_size.width(),
606 background_size.height(),
607 kPMColor_SkColorType,
608 kPremul_SkAlphaType
611 SkBitmap background;
612 background.setConfig(background_info);
613 skia::RefPtr<SkGrPixelRef> background_pixel_ref =
614 skia::AdoptRef(new SkGrPixelRef(
615 background_info, background_texture.get()));
616 background.setPixelRef(background_pixel_ref.get());
618 // Create a scratch texture for backing store.
619 GrTextureDesc desc;
620 desc.fFlags = kRenderTarget_GrTextureFlagBit | kNoStencil_GrTextureFlagBit;
621 desc.fSampleCnt = 0;
622 desc.fWidth = source.width();
623 desc.fHeight = source.height();
624 desc.fConfig = kSkia8888_GrPixelConfig;
625 desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
626 GrAutoScratchTexture scratch_texture(
627 offscreen_contexts->GrContext(), desc, GrContext::kExact_ScratchTexMatch);
628 skia::RefPtr<GrTexture> backing_store =
629 skia::AdoptRef(scratch_texture.detach());
631 // Create a device and canvas using that backing store.
632 SkGpuDevice device(offscreen_contexts->GrContext(), backing_store.get());
633 SkCanvas canvas(&device);
635 // Draw the source bitmap through the filter to the canvas.
636 canvas.clear(SK_ColorTRANSPARENT);
637 canvas.drawSprite(background, 0, 0);
638 SkPaint paint;
639 paint.setXfermodeMode(blend_mode);
640 canvas.drawSprite(source, 0, 0, &paint);
642 // Flush skia context so that all the rendered stuff appears on the
643 // texture.
644 offscreen_contexts->GrContext()->flush();
646 // Flush the GL context so rendering results from this context are
647 // visible in the compositor's context.
648 offscreen_contexts->ContextGL()->Flush();
650 return device.accessBitmap(false);
653 scoped_ptr<ScopedResource> GLRenderer::GetBackgroundWithFilters(
654 DrawingFrame* frame,
655 const RenderPassDrawQuad* quad,
656 const gfx::Transform& contents_device_transform,
657 const gfx::Transform& contents_device_transform_inverse,
658 bool* background_changed) {
659 // This method draws a background filter, which applies a filter to any pixels
660 // behind the quad and seen through its background. The algorithm works as
661 // follows:
662 // 1. Compute a bounding box around the pixels that will be visible through
663 // the quad.
664 // 2. Read the pixels in the bounding box into a buffer R.
665 // 3. Apply the background filter to R, so that it is applied in the pixels'
666 // coordinate space.
667 // 4. Apply the quad's inverse transform to map the pixels in R into the
668 // quad's content space. This implicitly clips R by the content bounds of the
669 // quad since the destination texture has bounds matching the quad's content.
670 // 5. Draw the background texture for the contents using the same transform as
671 // used to draw the contents itself. This is done without blending to replace
672 // the current background pixels with the new filtered background.
673 // 6. Draw the contents of the quad over drop of the new background with
674 // blending, as per usual. The filtered background pixels will show through
675 // any non-opaque pixels in this draws.
677 // Pixel copies in this algorithm occur at steps 2, 3, 4, and 5.
679 // TODO(danakj): When this algorithm changes, update
680 // LayerTreeHost::PrioritizeTextures() accordingly.
682 // TODO(danakj): We only allow background filters on an opaque render surface
683 // because other surfaces may contain translucent pixels, and the contents
684 // behind those translucent pixels wouldn't have the filter applied.
685 bool apply_background_filters =
686 !frame->current_render_pass->has_transparent_background;
687 DCHECK(!frame->current_texture);
689 // TODO(ajuma): Add support for reference filters once
690 // FilterOperations::GetOutsets supports reference filters.
691 if (apply_background_filters && quad->background_filters.HasReferenceFilter())
692 apply_background_filters = false;
694 // TODO(danakj): Do a single readback for both the surface and replica and
695 // cache the filtered results (once filter textures are not reused).
696 gfx::Rect window_rect = gfx::ToEnclosingRect(MathUtil::MapClippedRect(
697 contents_device_transform, SharedGeometryQuad().BoundingBox()));
699 int top, right, bottom, left;
700 quad->background_filters.GetOutsets(&top, &right, &bottom, &left);
701 window_rect.Inset(-left, -top, -right, -bottom);
703 window_rect.Intersect(
704 MoveFromDrawToWindowSpace(frame->current_render_pass->output_rect));
706 scoped_ptr<ScopedResource> device_background_texture =
707 ScopedResource::Create(resource_provider_);
708 // The TextureUsageFramebuffer hint makes ResourceProvider avoid immutable
709 // storage allocation (texStorage2DEXT) for this texture. copyTexImage2D fails
710 // when called on a texture having immutable storage.
711 device_background_texture->Allocate(
712 window_rect.size(), ResourceProvider::TextureUsageFramebuffer, RGBA_8888);
714 ResourceProvider::ScopedWriteLockGL lock(resource_provider_,
715 device_background_texture->id());
716 GetFramebufferTexture(
717 lock.texture_id(), device_background_texture->format(), window_rect);
720 skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
721 quad->background_filters, device_background_texture->size());
723 SkBitmap filtered_device_background;
724 if (apply_background_filters) {
725 filtered_device_background =
726 ApplyImageFilter(this,
727 frame->offscreen_context_provider,
728 quad->rect.origin(),
729 filter.get(),
730 device_background_texture.get());
732 *background_changed = (filtered_device_background.getTexture() != NULL);
734 int filtered_device_background_texture_id = 0;
735 scoped_ptr<ResourceProvider::ScopedReadLockGL> lock;
736 if (filtered_device_background.getTexture()) {
737 GrTexture* texture =
738 reinterpret_cast<GrTexture*>(filtered_device_background.getTexture());
739 filtered_device_background_texture_id = texture->getTextureHandle();
740 } else {
741 lock.reset(new ResourceProvider::ScopedReadLockGL(
742 resource_provider_, device_background_texture->id()));
743 filtered_device_background_texture_id = lock->texture_id();
746 scoped_ptr<ScopedResource> background_texture =
747 ScopedResource::Create(resource_provider_);
748 background_texture->Allocate(
749 quad->rect.size(), ResourceProvider::TextureUsageFramebuffer, RGBA_8888);
751 const RenderPass* target_render_pass = frame->current_render_pass;
752 bool using_background_texture =
753 UseScopedTexture(frame, background_texture.get(), quad->rect);
755 if (using_background_texture) {
756 // Copy the readback pixels from device to the background texture for the
757 // surface.
758 gfx::Transform device_to_framebuffer_transform;
759 device_to_framebuffer_transform.Translate(
760 quad->rect.width() * 0.5f + quad->rect.x(),
761 quad->rect.height() * 0.5f + quad->rect.y());
762 device_to_framebuffer_transform.Scale(quad->rect.width(),
763 quad->rect.height());
764 device_to_framebuffer_transform.PreconcatTransform(
765 contents_device_transform_inverse);
767 #ifndef NDEBUG
768 GLC(gl_, gl_->ClearColor(0, 0, 1, 1));
769 gl_->Clear(GL_COLOR_BUFFER_BIT);
770 #endif
772 // The filtered_deveice_background_texture is oriented the same as the frame
773 // buffer. The transform we are copying with has a vertical flip, as well as
774 // the |device_to_framebuffer_transform|, which cancel each other out. So do
775 // not flip the contents in the shader to maintain orientation.
776 bool flip_vertically = false;
778 CopyTextureToFramebuffer(frame,
779 filtered_device_background_texture_id,
780 window_rect,
781 device_to_framebuffer_transform,
782 flip_vertically);
785 UseRenderPass(frame, target_render_pass);
787 if (!using_background_texture)
788 return scoped_ptr<ScopedResource>();
789 return background_texture.Pass();
792 void GLRenderer::DrawRenderPassQuad(DrawingFrame* frame,
793 const RenderPassDrawQuad* quad) {
794 SetBlendEnabled(quad->ShouldDrawWithBlending());
796 ScopedResource* contents_texture =
797 render_pass_textures_.get(quad->render_pass_id);
798 if (!contents_texture || !contents_texture->id())
799 return;
801 gfx::Transform quad_rect_matrix;
802 QuadRectTransform(&quad_rect_matrix, quad->quadTransform(), quad->rect);
803 gfx::Transform contents_device_transform =
804 frame->window_matrix * frame->projection_matrix * quad_rect_matrix;
805 contents_device_transform.FlattenTo2d();
807 // Can only draw surface if device matrix is invertible.
808 gfx::Transform contents_device_transform_inverse(
809 gfx::Transform::kSkipInitialization);
810 if (!contents_device_transform.GetInverse(&contents_device_transform_inverse))
811 return;
813 bool need_background_texture =
814 quad->shared_quad_state->blend_mode != SkXfermode::kSrcOver_Mode ||
815 !quad->background_filters.IsEmpty();
816 bool background_changed = false;
817 scoped_ptr<ScopedResource> background_texture;
818 if (need_background_texture) {
819 // The pixels from the filtered background should completely replace the
820 // current pixel values.
821 bool disable_blending = blend_enabled();
822 if (disable_blending)
823 SetBlendEnabled(false);
825 background_texture =
826 GetBackgroundWithFilters(frame,
827 quad,
828 contents_device_transform,
829 contents_device_transform_inverse,
830 &background_changed);
832 if (disable_blending)
833 SetBlendEnabled(true);
836 // TODO(senorblanco): Cache this value so that we don't have to do it for both
837 // the surface and its replica. Apply filters to the contents texture.
838 SkBitmap filter_bitmap;
839 SkScalar color_matrix[20];
840 bool use_color_matrix = false;
841 // TODO(ajuma): Always use RenderSurfaceFilters::BuildImageFilter, not just
842 // when we have a reference filter.
843 if (!quad->filters.IsEmpty()) {
844 skia::RefPtr<SkImageFilter> filter = RenderSurfaceFilters::BuildImageFilter(
845 quad->filters, contents_texture->size());
846 if (filter) {
847 skia::RefPtr<SkColorFilter> cf;
850 SkColorFilter* colorfilter_rawptr = NULL;
851 filter->asColorFilter(&colorfilter_rawptr);
852 cf = skia::AdoptRef(colorfilter_rawptr);
855 if (cf && cf->asColorMatrix(color_matrix) && !filter->getInput(0)) {
856 // We have a single color matrix as a filter; apply it locally
857 // in the compositor.
858 use_color_matrix = true;
859 } else {
860 filter_bitmap = ApplyImageFilter(this,
861 frame->offscreen_context_provider,
862 quad->rect.origin(),
863 filter.get(),
864 contents_texture);
869 if (quad->shared_quad_state->blend_mode != SkXfermode::kSrcOver_Mode &&
870 background_texture) {
871 filter_bitmap =
872 ApplyBlendModeWithBackdrop(this,
873 frame->offscreen_context_provider,
874 filter_bitmap,
875 contents_texture,
876 background_texture.get(),
877 quad->shared_quad_state->blend_mode);
880 // Draw the background texture if it has some filters applied.
881 if (background_texture && background_changed) {
882 DCHECK(background_texture->size() == quad->rect.size());
883 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
884 background_texture->id());
886 // The background_texture is oriented the same as the frame buffer. The
887 // transform we are copying with has a vertical flip, so flip the contents
888 // in the shader to maintain orientation
889 bool flip_vertically = true;
891 CopyTextureToFramebuffer(frame,
892 lock.texture_id(),
893 quad->rect,
894 quad->quadTransform(),
895 flip_vertically);
898 bool clipped = false;
899 gfx::QuadF device_quad = MathUtil::MapQuad(
900 contents_device_transform, SharedGeometryQuad(), &clipped);
901 LayerQuad device_layer_bounds(gfx::QuadF(device_quad.BoundingBox()));
902 LayerQuad device_layer_edges(device_quad);
904 // Use anti-aliasing programs only when necessary.
905 bool use_aa =
906 !clipped && (!device_quad.IsRectilinear() ||
907 !gfx::IsNearestRectWithinDistance(device_quad.BoundingBox(),
908 kAntiAliasingEpsilon));
909 if (use_aa) {
910 device_layer_bounds.InflateAntiAliasingDistance();
911 device_layer_edges.InflateAntiAliasingDistance();
914 scoped_ptr<ResourceProvider::ScopedReadLockGL> mask_resource_lock;
915 unsigned mask_texture_id = 0;
916 if (quad->mask_resource_id) {
917 mask_resource_lock.reset(new ResourceProvider::ScopedReadLockGL(
918 resource_provider_, quad->mask_resource_id));
919 mask_texture_id = mask_resource_lock->texture_id();
922 // TODO(danakj): use the background_texture and blend the background in with
923 // this draw instead of having a separate copy of the background texture.
925 scoped_ptr<ResourceProvider::ScopedSamplerGL> contents_resource_lock;
926 if (filter_bitmap.getTexture()) {
927 GrTexture* texture =
928 reinterpret_cast<GrTexture*>(filter_bitmap.getTexture());
929 DCHECK_EQ(GL_TEXTURE0, ResourceProvider::GetActiveTextureUnit(gl_));
930 gl_->BindTexture(GL_TEXTURE_2D, texture->getTextureHandle());
931 } else {
932 contents_resource_lock =
933 make_scoped_ptr(new ResourceProvider::ScopedSamplerGL(
934 resource_provider_, contents_texture->id(), GL_LINEAR));
935 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
936 contents_resource_lock->target());
939 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
940 gl_,
941 &highp_threshold_cache_,
942 highp_threshold_min_,
943 quad->shared_quad_state->visible_content_rect.bottom_right());
945 int shader_quad_location = -1;
946 int shader_edge_location = -1;
947 int shader_viewport_location = -1;
948 int shader_mask_sampler_location = -1;
949 int shader_mask_tex_coord_scale_location = -1;
950 int shader_mask_tex_coord_offset_location = -1;
951 int shader_matrix_location = -1;
952 int shader_alpha_location = -1;
953 int shader_color_matrix_location = -1;
954 int shader_color_offset_location = -1;
955 int shader_tex_transform_location = -1;
957 if (use_aa && mask_texture_id && !use_color_matrix) {
958 const RenderPassMaskProgramAA* program =
959 GetRenderPassMaskProgramAA(tex_coord_precision);
960 SetUseProgram(program->program());
961 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
963 shader_quad_location = program->vertex_shader().quad_location();
964 shader_edge_location = program->vertex_shader().edge_location();
965 shader_viewport_location = program->vertex_shader().viewport_location();
966 shader_mask_sampler_location =
967 program->fragment_shader().mask_sampler_location();
968 shader_mask_tex_coord_scale_location =
969 program->fragment_shader().mask_tex_coord_scale_location();
970 shader_mask_tex_coord_offset_location =
971 program->fragment_shader().mask_tex_coord_offset_location();
972 shader_matrix_location = program->vertex_shader().matrix_location();
973 shader_alpha_location = program->fragment_shader().alpha_location();
974 shader_tex_transform_location =
975 program->vertex_shader().tex_transform_location();
976 } else if (!use_aa && mask_texture_id && !use_color_matrix) {
977 const RenderPassMaskProgram* program =
978 GetRenderPassMaskProgram(tex_coord_precision);
979 SetUseProgram(program->program());
980 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
982 shader_mask_sampler_location =
983 program->fragment_shader().mask_sampler_location();
984 shader_mask_tex_coord_scale_location =
985 program->fragment_shader().mask_tex_coord_scale_location();
986 shader_mask_tex_coord_offset_location =
987 program->fragment_shader().mask_tex_coord_offset_location();
988 shader_matrix_location = program->vertex_shader().matrix_location();
989 shader_alpha_location = program->fragment_shader().alpha_location();
990 shader_tex_transform_location =
991 program->vertex_shader().tex_transform_location();
992 } else if (use_aa && !mask_texture_id && !use_color_matrix) {
993 const RenderPassProgramAA* program =
994 GetRenderPassProgramAA(tex_coord_precision);
995 SetUseProgram(program->program());
996 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
998 shader_quad_location = program->vertex_shader().quad_location();
999 shader_edge_location = program->vertex_shader().edge_location();
1000 shader_viewport_location = program->vertex_shader().viewport_location();
1001 shader_matrix_location = program->vertex_shader().matrix_location();
1002 shader_alpha_location = program->fragment_shader().alpha_location();
1003 shader_tex_transform_location =
1004 program->vertex_shader().tex_transform_location();
1005 } else if (use_aa && mask_texture_id && use_color_matrix) {
1006 const RenderPassMaskColorMatrixProgramAA* program =
1007 GetRenderPassMaskColorMatrixProgramAA(tex_coord_precision);
1008 SetUseProgram(program->program());
1009 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1011 shader_matrix_location = program->vertex_shader().matrix_location();
1012 shader_quad_location = program->vertex_shader().quad_location();
1013 shader_tex_transform_location =
1014 program->vertex_shader().tex_transform_location();
1015 shader_edge_location = program->vertex_shader().edge_location();
1016 shader_viewport_location = program->vertex_shader().viewport_location();
1017 shader_alpha_location = program->fragment_shader().alpha_location();
1018 shader_mask_sampler_location =
1019 program->fragment_shader().mask_sampler_location();
1020 shader_mask_tex_coord_scale_location =
1021 program->fragment_shader().mask_tex_coord_scale_location();
1022 shader_mask_tex_coord_offset_location =
1023 program->fragment_shader().mask_tex_coord_offset_location();
1024 shader_color_matrix_location =
1025 program->fragment_shader().color_matrix_location();
1026 shader_color_offset_location =
1027 program->fragment_shader().color_offset_location();
1028 } else if (use_aa && !mask_texture_id && use_color_matrix) {
1029 const RenderPassColorMatrixProgramAA* program =
1030 GetRenderPassColorMatrixProgramAA(tex_coord_precision);
1031 SetUseProgram(program->program());
1032 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1034 shader_matrix_location = program->vertex_shader().matrix_location();
1035 shader_quad_location = program->vertex_shader().quad_location();
1036 shader_tex_transform_location =
1037 program->vertex_shader().tex_transform_location();
1038 shader_edge_location = program->vertex_shader().edge_location();
1039 shader_viewport_location = program->vertex_shader().viewport_location();
1040 shader_alpha_location = program->fragment_shader().alpha_location();
1041 shader_color_matrix_location =
1042 program->fragment_shader().color_matrix_location();
1043 shader_color_offset_location =
1044 program->fragment_shader().color_offset_location();
1045 } else if (!use_aa && mask_texture_id && use_color_matrix) {
1046 const RenderPassMaskColorMatrixProgram* program =
1047 GetRenderPassMaskColorMatrixProgram(tex_coord_precision);
1048 SetUseProgram(program->program());
1049 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1051 shader_matrix_location = program->vertex_shader().matrix_location();
1052 shader_tex_transform_location =
1053 program->vertex_shader().tex_transform_location();
1054 shader_mask_sampler_location =
1055 program->fragment_shader().mask_sampler_location();
1056 shader_mask_tex_coord_scale_location =
1057 program->fragment_shader().mask_tex_coord_scale_location();
1058 shader_mask_tex_coord_offset_location =
1059 program->fragment_shader().mask_tex_coord_offset_location();
1060 shader_alpha_location = program->fragment_shader().alpha_location();
1061 shader_color_matrix_location =
1062 program->fragment_shader().color_matrix_location();
1063 shader_color_offset_location =
1064 program->fragment_shader().color_offset_location();
1065 } else if (!use_aa && !mask_texture_id && use_color_matrix) {
1066 const RenderPassColorMatrixProgram* program =
1067 GetRenderPassColorMatrixProgram(tex_coord_precision);
1068 SetUseProgram(program->program());
1069 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1071 shader_matrix_location = program->vertex_shader().matrix_location();
1072 shader_tex_transform_location =
1073 program->vertex_shader().tex_transform_location();
1074 shader_alpha_location = program->fragment_shader().alpha_location();
1075 shader_color_matrix_location =
1076 program->fragment_shader().color_matrix_location();
1077 shader_color_offset_location =
1078 program->fragment_shader().color_offset_location();
1079 } else {
1080 const RenderPassProgram* program =
1081 GetRenderPassProgram(tex_coord_precision);
1082 SetUseProgram(program->program());
1083 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1085 shader_matrix_location = program->vertex_shader().matrix_location();
1086 shader_alpha_location = program->fragment_shader().alpha_location();
1087 shader_tex_transform_location =
1088 program->vertex_shader().tex_transform_location();
1090 float tex_scale_x =
1091 quad->rect.width() / static_cast<float>(contents_texture->size().width());
1092 float tex_scale_y = quad->rect.height() /
1093 static_cast<float>(contents_texture->size().height());
1094 DCHECK_LE(tex_scale_x, 1.0f);
1095 DCHECK_LE(tex_scale_y, 1.0f);
1097 DCHECK(shader_tex_transform_location != -1 || IsContextLost());
1098 // Flip the content vertically in the shader, as the RenderPass input
1099 // texture is already oriented the same way as the framebuffer, but the
1100 // projection transform does a flip.
1101 GLC(gl_,
1102 gl_->Uniform4f(shader_tex_transform_location,
1103 0.0f,
1104 tex_scale_y,
1105 tex_scale_x,
1106 -tex_scale_y));
1108 scoped_ptr<ResourceProvider::ScopedSamplerGL> shader_mask_sampler_lock;
1109 if (shader_mask_sampler_location != -1) {
1110 DCHECK_NE(shader_mask_tex_coord_scale_location, 1);
1111 DCHECK_NE(shader_mask_tex_coord_offset_location, 1);
1112 GLC(gl_, gl_->Uniform1i(shader_mask_sampler_location, 1));
1114 float mask_tex_scale_x = quad->mask_uv_rect.width() / tex_scale_x;
1115 float mask_tex_scale_y = quad->mask_uv_rect.height() / tex_scale_y;
1117 // Mask textures are oriented vertically flipped relative to the framebuffer
1118 // and the RenderPass contents texture, so we flip the tex coords from the
1119 // RenderPass texture to find the mask texture coords.
1120 GLC(gl_,
1121 gl_->Uniform2f(shader_mask_tex_coord_offset_location,
1122 quad->mask_uv_rect.x(),
1123 quad->mask_uv_rect.y() + quad->mask_uv_rect.height()));
1124 GLC(gl_,
1125 gl_->Uniform2f(shader_mask_tex_coord_scale_location,
1126 mask_tex_scale_x,
1127 -mask_tex_scale_y));
1128 shader_mask_sampler_lock = make_scoped_ptr(
1129 new ResourceProvider::ScopedSamplerGL(resource_provider_,
1130 quad->mask_resource_id,
1131 GL_TEXTURE1,
1132 GL_LINEAR));
1133 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D),
1134 shader_mask_sampler_lock->target());
1137 if (shader_edge_location != -1) {
1138 float edge[24];
1139 device_layer_edges.ToFloatArray(edge);
1140 device_layer_bounds.ToFloatArray(&edge[12]);
1141 GLC(gl_, gl_->Uniform3fv(shader_edge_location, 8, edge));
1144 if (shader_viewport_location != -1) {
1145 float viewport[4] = {static_cast<float>(viewport_.x()),
1146 static_cast<float>(viewport_.y()),
1147 static_cast<float>(viewport_.width()),
1148 static_cast<float>(viewport_.height()), };
1149 GLC(gl_, gl_->Uniform4fv(shader_viewport_location, 1, viewport));
1152 if (shader_color_matrix_location != -1) {
1153 float matrix[16];
1154 for (int i = 0; i < 4; ++i) {
1155 for (int j = 0; j < 4; ++j)
1156 matrix[i * 4 + j] = SkScalarToFloat(color_matrix[j * 5 + i]);
1158 GLC(gl_,
1159 gl_->UniformMatrix4fv(shader_color_matrix_location, 1, false, matrix));
1161 static const float kScale = 1.0f / 255.0f;
1162 if (shader_color_offset_location != -1) {
1163 float offset[4];
1164 for (int i = 0; i < 4; ++i)
1165 offset[i] = SkScalarToFloat(color_matrix[i * 5 + 4]) * kScale;
1167 GLC(gl_, gl_->Uniform4fv(shader_color_offset_location, 1, offset));
1170 // Map device space quad to surface space. contents_device_transform has no 3d
1171 // component since it was flattened, so we don't need to project.
1172 gfx::QuadF surface_quad = MathUtil::MapQuad(contents_device_transform_inverse,
1173 device_layer_edges.ToQuadF(),
1174 &clipped);
1176 SetShaderOpacity(quad->opacity(), shader_alpha_location);
1177 SetShaderQuadF(surface_quad, shader_quad_location);
1178 DrawQuadGeometry(
1179 frame, quad->quadTransform(), quad->rect, shader_matrix_location);
1181 // Flush the compositor context before the filter bitmap goes out of
1182 // scope, so the draw gets processed before the filter texture gets deleted.
1183 if (filter_bitmap.getTexture())
1184 GLC(gl_, gl_->Flush());
1187 struct SolidColorProgramUniforms {
1188 unsigned program;
1189 unsigned matrix_location;
1190 unsigned viewport_location;
1191 unsigned quad_location;
1192 unsigned edge_location;
1193 unsigned color_location;
1196 template <class T>
1197 static void SolidColorUniformLocation(T program,
1198 SolidColorProgramUniforms* uniforms) {
1199 uniforms->program = program->program();
1200 uniforms->matrix_location = program->vertex_shader().matrix_location();
1201 uniforms->viewport_location = program->vertex_shader().viewport_location();
1202 uniforms->quad_location = program->vertex_shader().quad_location();
1203 uniforms->edge_location = program->vertex_shader().edge_location();
1204 uniforms->color_location = program->fragment_shader().color_location();
1207 // static
1208 bool GLRenderer::SetupQuadForAntialiasing(
1209 const gfx::Transform& device_transform,
1210 const DrawQuad* quad,
1211 gfx::QuadF* local_quad,
1212 float edge[24]) {
1213 gfx::Rect tile_rect = quad->visible_rect;
1215 bool clipped = false;
1216 gfx::QuadF device_layer_quad = MathUtil::MapQuad(
1217 device_transform, gfx::QuadF(quad->visibleContentRect()), &clipped);
1219 bool is_axis_aligned_in_target = device_layer_quad.IsRectilinear();
1220 bool is_nearest_rect_within_epsilon =
1221 is_axis_aligned_in_target &&
1222 gfx::IsNearestRectWithinDistance(device_layer_quad.BoundingBox(),
1223 kAntiAliasingEpsilon);
1224 // AAing clipped quads is not supported by the code yet.
1225 bool use_aa = !clipped && !is_nearest_rect_within_epsilon && quad->IsEdge();
1226 if (!use_aa)
1227 return false;
1229 LayerQuad device_layer_bounds(gfx::QuadF(device_layer_quad.BoundingBox()));
1230 device_layer_bounds.InflateAntiAliasingDistance();
1232 LayerQuad device_layer_edges(device_layer_quad);
1233 device_layer_edges.InflateAntiAliasingDistance();
1235 device_layer_edges.ToFloatArray(edge);
1236 device_layer_bounds.ToFloatArray(&edge[12]);
1238 gfx::PointF bottom_right = tile_rect.bottom_right();
1239 gfx::PointF bottom_left = tile_rect.bottom_left();
1240 gfx::PointF top_left = tile_rect.origin();
1241 gfx::PointF top_right = tile_rect.top_right();
1243 // Map points to device space.
1244 bottom_right = MathUtil::MapPoint(device_transform, bottom_right, &clipped);
1245 DCHECK(!clipped);
1246 bottom_left = MathUtil::MapPoint(device_transform, bottom_left, &clipped);
1247 DCHECK(!clipped);
1248 top_left = MathUtil::MapPoint(device_transform, top_left, &clipped);
1249 DCHECK(!clipped);
1250 top_right = MathUtil::MapPoint(device_transform, top_right, &clipped);
1251 DCHECK(!clipped);
1253 LayerQuad::Edge bottom_edge(bottom_right, bottom_left);
1254 LayerQuad::Edge left_edge(bottom_left, top_left);
1255 LayerQuad::Edge top_edge(top_left, top_right);
1256 LayerQuad::Edge right_edge(top_right, bottom_right);
1258 // Only apply anti-aliasing to edges not clipped by culling or scissoring.
1259 if (quad->IsTopEdge() && tile_rect.y() == quad->rect.y())
1260 top_edge = device_layer_edges.top();
1261 if (quad->IsLeftEdge() && tile_rect.x() == quad->rect.x())
1262 left_edge = device_layer_edges.left();
1263 if (quad->IsRightEdge() && tile_rect.right() == quad->rect.right())
1264 right_edge = device_layer_edges.right();
1265 if (quad->IsBottomEdge() && tile_rect.bottom() == quad->rect.bottom())
1266 bottom_edge = device_layer_edges.bottom();
1268 float sign = gfx::QuadF(tile_rect).IsCounterClockwise() ? -1 : 1;
1269 bottom_edge.scale(sign);
1270 left_edge.scale(sign);
1271 top_edge.scale(sign);
1272 right_edge.scale(sign);
1274 // Create device space quad.
1275 LayerQuad device_quad(left_edge, top_edge, right_edge, bottom_edge);
1277 // Map device space quad to local space. device_transform has no 3d
1278 // component since it was flattened, so we don't need to project. We should
1279 // have already checked that the transform was uninvertible above.
1280 gfx::Transform inverse_device_transform(gfx::Transform::kSkipInitialization);
1281 bool did_invert = device_transform.GetInverse(&inverse_device_transform);
1282 DCHECK(did_invert);
1283 *local_quad = MathUtil::MapQuad(
1284 inverse_device_transform, device_quad.ToQuadF(), &clipped);
1285 // We should not DCHECK(!clipped) here, because anti-aliasing inflation may
1286 // cause device_quad to become clipped. To our knowledge this scenario does
1287 // not need to be handled differently than the unclipped case.
1289 return true;
1292 void GLRenderer::DrawSolidColorQuad(const DrawingFrame* frame,
1293 const SolidColorDrawQuad* quad) {
1294 gfx::Rect tile_rect = quad->visible_rect;
1296 SkColor color = quad->color;
1297 float opacity = quad->opacity();
1298 float alpha = (SkColorGetA(color) * (1.0f / 255.0f)) * opacity;
1300 // Early out if alpha is small enough that quad doesn't contribute to output.
1301 if (alpha < std::numeric_limits<float>::epsilon() &&
1302 quad->ShouldDrawWithBlending())
1303 return;
1305 gfx::Transform device_transform =
1306 frame->window_matrix * frame->projection_matrix * quad->quadTransform();
1307 device_transform.FlattenTo2d();
1308 if (!device_transform.IsInvertible())
1309 return;
1311 gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1312 float edge[24];
1313 bool use_aa =
1314 settings_->allow_antialiasing && !quad->force_anti_aliasing_off &&
1315 SetupQuadForAntialiasing(device_transform, quad, &local_quad, edge);
1317 SolidColorProgramUniforms uniforms;
1318 if (use_aa)
1319 SolidColorUniformLocation(GetSolidColorProgramAA(), &uniforms);
1320 else
1321 SolidColorUniformLocation(GetSolidColorProgram(), &uniforms);
1322 SetUseProgram(uniforms.program);
1324 GLC(gl_,
1325 gl_->Uniform4f(uniforms.color_location,
1326 (SkColorGetR(color) * (1.0f / 255.0f)) * alpha,
1327 (SkColorGetG(color) * (1.0f / 255.0f)) * alpha,
1328 (SkColorGetB(color) * (1.0f / 255.0f)) * alpha,
1329 alpha));
1330 if (use_aa) {
1331 float viewport[4] = {static_cast<float>(viewport_.x()),
1332 static_cast<float>(viewport_.y()),
1333 static_cast<float>(viewport_.width()),
1334 static_cast<float>(viewport_.height()), };
1335 GLC(gl_, gl_->Uniform4fv(uniforms.viewport_location, 1, viewport));
1336 GLC(gl_, gl_->Uniform3fv(uniforms.edge_location, 8, edge));
1339 // Enable blending when the quad properties require it or if we decided
1340 // to use antialiasing.
1341 SetBlendEnabled(quad->ShouldDrawWithBlending() || use_aa);
1343 // Normalize to tile_rect.
1344 local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1346 SetShaderQuadF(local_quad, uniforms.quad_location);
1348 // The transform and vertex data are used to figure out the extents that the
1349 // un-antialiased quad should have and which vertex this is and the float
1350 // quad passed in via uniform is the actual geometry that gets used to draw
1351 // it. This is why this centered rect is used and not the original quad_rect.
1352 gfx::RectF centered_rect(
1353 gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1354 tile_rect.size());
1355 DrawQuadGeometry(
1356 frame, quad->quadTransform(), centered_rect, uniforms.matrix_location);
1359 struct TileProgramUniforms {
1360 unsigned program;
1361 unsigned matrix_location;
1362 unsigned viewport_location;
1363 unsigned quad_location;
1364 unsigned edge_location;
1365 unsigned vertex_tex_transform_location;
1366 unsigned sampler_location;
1367 unsigned fragment_tex_transform_location;
1368 unsigned alpha_location;
1371 template <class T>
1372 static void TileUniformLocation(T program, TileProgramUniforms* uniforms) {
1373 uniforms->program = program->program();
1374 uniforms->matrix_location = program->vertex_shader().matrix_location();
1375 uniforms->viewport_location = program->vertex_shader().viewport_location();
1376 uniforms->quad_location = program->vertex_shader().quad_location();
1377 uniforms->edge_location = program->vertex_shader().edge_location();
1378 uniforms->vertex_tex_transform_location =
1379 program->vertex_shader().vertex_tex_transform_location();
1381 uniforms->sampler_location = program->fragment_shader().sampler_location();
1382 uniforms->alpha_location = program->fragment_shader().alpha_location();
1383 uniforms->fragment_tex_transform_location =
1384 program->fragment_shader().fragment_tex_transform_location();
1387 void GLRenderer::DrawTileQuad(const DrawingFrame* frame,
1388 const TileDrawQuad* quad) {
1389 DrawContentQuad(frame, quad, quad->resource_id);
1392 void GLRenderer::DrawContentQuad(const DrawingFrame* frame,
1393 const ContentDrawQuadBase* quad,
1394 ResourceProvider::ResourceId resource_id) {
1395 gfx::Rect tile_rect = quad->visible_rect;
1397 gfx::RectF tex_coord_rect = MathUtil::ScaleRectProportional(
1398 quad->tex_coord_rect, quad->rect, tile_rect);
1399 float tex_to_geom_scale_x = quad->rect.width() / quad->tex_coord_rect.width();
1400 float tex_to_geom_scale_y =
1401 quad->rect.height() / quad->tex_coord_rect.height();
1403 gfx::RectF clamp_geom_rect(tile_rect);
1404 gfx::RectF clamp_tex_rect(tex_coord_rect);
1405 // Clamp texture coordinates to avoid sampling outside the layer
1406 // by deflating the tile region half a texel or half a texel
1407 // minus epsilon for one pixel layers. The resulting clamp region
1408 // is mapped to the unit square by the vertex shader and mapped
1409 // back to normalized texture coordinates by the fragment shader
1410 // after being clamped to 0-1 range.
1411 float tex_clamp_x =
1412 std::min(0.5f, 0.5f * clamp_tex_rect.width() - kAntiAliasingEpsilon);
1413 float tex_clamp_y =
1414 std::min(0.5f, 0.5f * clamp_tex_rect.height() - kAntiAliasingEpsilon);
1415 float geom_clamp_x =
1416 std::min(tex_clamp_x * tex_to_geom_scale_x,
1417 0.5f * clamp_geom_rect.width() - kAntiAliasingEpsilon);
1418 float geom_clamp_y =
1419 std::min(tex_clamp_y * tex_to_geom_scale_y,
1420 0.5f * clamp_geom_rect.height() - kAntiAliasingEpsilon);
1421 clamp_geom_rect.Inset(geom_clamp_x, geom_clamp_y, geom_clamp_x, geom_clamp_y);
1422 clamp_tex_rect.Inset(tex_clamp_x, tex_clamp_y, tex_clamp_x, tex_clamp_y);
1424 // Map clamping rectangle to unit square.
1425 float vertex_tex_translate_x = -clamp_geom_rect.x() / clamp_geom_rect.width();
1426 float vertex_tex_translate_y =
1427 -clamp_geom_rect.y() / clamp_geom_rect.height();
1428 float vertex_tex_scale_x = tile_rect.width() / clamp_geom_rect.width();
1429 float vertex_tex_scale_y = tile_rect.height() / clamp_geom_rect.height();
1431 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1432 gl_, &highp_threshold_cache_, highp_threshold_min_, quad->texture_size);
1434 gfx::Transform device_transform =
1435 frame->window_matrix * frame->projection_matrix * quad->quadTransform();
1436 device_transform.FlattenTo2d();
1437 if (!device_transform.IsInvertible())
1438 return;
1440 gfx::QuadF local_quad = gfx::QuadF(gfx::RectF(tile_rect));
1441 float edge[24];
1442 bool use_aa =
1443 settings_->allow_antialiasing &&
1444 SetupQuadForAntialiasing(device_transform, quad, &local_quad, edge);
1446 bool scaled = (tex_to_geom_scale_x != 1.f || tex_to_geom_scale_y != 1.f);
1447 GLenum filter = (use_aa || scaled ||
1448 !quad->quadTransform().IsIdentityOrIntegerTranslation())
1449 ? GL_LINEAR
1450 : GL_NEAREST;
1451 ResourceProvider::ScopedSamplerGL quad_resource_lock(
1452 resource_provider_, resource_id, filter);
1453 SamplerType sampler =
1454 SamplerTypeFromTextureTarget(quad_resource_lock.target());
1456 float fragment_tex_translate_x = clamp_tex_rect.x();
1457 float fragment_tex_translate_y = clamp_tex_rect.y();
1458 float fragment_tex_scale_x = clamp_tex_rect.width();
1459 float fragment_tex_scale_y = clamp_tex_rect.height();
1461 // Map to normalized texture coordinates.
1462 if (sampler != SamplerType2DRect) {
1463 gfx::Size texture_size = quad->texture_size;
1464 DCHECK(!texture_size.IsEmpty());
1465 fragment_tex_translate_x /= texture_size.width();
1466 fragment_tex_translate_y /= texture_size.height();
1467 fragment_tex_scale_x /= texture_size.width();
1468 fragment_tex_scale_y /= texture_size.height();
1471 TileProgramUniforms uniforms;
1472 if (use_aa) {
1473 if (quad->swizzle_contents) {
1474 TileUniformLocation(GetTileProgramSwizzleAA(tex_coord_precision, sampler),
1475 &uniforms);
1476 } else {
1477 TileUniformLocation(GetTileProgramAA(tex_coord_precision, sampler),
1478 &uniforms);
1480 } else {
1481 if (quad->ShouldDrawWithBlending()) {
1482 if (quad->swizzle_contents) {
1483 TileUniformLocation(GetTileProgramSwizzle(tex_coord_precision, sampler),
1484 &uniforms);
1485 } else {
1486 TileUniformLocation(GetTileProgram(tex_coord_precision, sampler),
1487 &uniforms);
1489 } else {
1490 if (quad->swizzle_contents) {
1491 TileUniformLocation(
1492 GetTileProgramSwizzleOpaque(tex_coord_precision, sampler),
1493 &uniforms);
1494 } else {
1495 TileUniformLocation(GetTileProgramOpaque(tex_coord_precision, sampler),
1496 &uniforms);
1501 SetUseProgram(uniforms.program);
1502 GLC(gl_, gl_->Uniform1i(uniforms.sampler_location, 0));
1504 if (use_aa) {
1505 float viewport[4] = {static_cast<float>(viewport_.x()),
1506 static_cast<float>(viewport_.y()),
1507 static_cast<float>(viewport_.width()),
1508 static_cast<float>(viewport_.height()), };
1509 GLC(gl_, gl_->Uniform4fv(uniforms.viewport_location, 1, viewport));
1510 GLC(gl_, gl_->Uniform3fv(uniforms.edge_location, 8, edge));
1512 GLC(gl_,
1513 gl_->Uniform4f(uniforms.vertex_tex_transform_location,
1514 vertex_tex_translate_x,
1515 vertex_tex_translate_y,
1516 vertex_tex_scale_x,
1517 vertex_tex_scale_y));
1518 GLC(gl_,
1519 gl_->Uniform4f(uniforms.fragment_tex_transform_location,
1520 fragment_tex_translate_x,
1521 fragment_tex_translate_y,
1522 fragment_tex_scale_x,
1523 fragment_tex_scale_y));
1524 } else {
1525 // Move fragment shader transform to vertex shader. We can do this while
1526 // still producing correct results as fragment_tex_transform_location
1527 // should always be non-negative when tiles are transformed in a way
1528 // that could result in sampling outside the layer.
1529 vertex_tex_scale_x *= fragment_tex_scale_x;
1530 vertex_tex_scale_y *= fragment_tex_scale_y;
1531 vertex_tex_translate_x *= fragment_tex_scale_x;
1532 vertex_tex_translate_y *= fragment_tex_scale_y;
1533 vertex_tex_translate_x += fragment_tex_translate_x;
1534 vertex_tex_translate_y += fragment_tex_translate_y;
1536 GLC(gl_,
1537 gl_->Uniform4f(uniforms.vertex_tex_transform_location,
1538 vertex_tex_translate_x,
1539 vertex_tex_translate_y,
1540 vertex_tex_scale_x,
1541 vertex_tex_scale_y));
1544 // Enable blending when the quad properties require it or if we decided
1545 // to use antialiasing.
1546 SetBlendEnabled(quad->ShouldDrawWithBlending() || use_aa);
1548 // Normalize to tile_rect.
1549 local_quad.Scale(1.0f / tile_rect.width(), 1.0f / tile_rect.height());
1551 SetShaderOpacity(quad->opacity(), uniforms.alpha_location);
1552 SetShaderQuadF(local_quad, uniforms.quad_location);
1554 // The transform and vertex data are used to figure out the extents that the
1555 // un-antialiased quad should have and which vertex this is and the float
1556 // quad passed in via uniform is the actual geometry that gets used to draw
1557 // it. This is why this centered rect is used and not the original quad_rect.
1558 gfx::RectF centered_rect(
1559 gfx::PointF(-0.5f * tile_rect.width(), -0.5f * tile_rect.height()),
1560 tile_rect.size());
1561 DrawQuadGeometry(
1562 frame, quad->quadTransform(), centered_rect, uniforms.matrix_location);
1565 void GLRenderer::DrawYUVVideoQuad(const DrawingFrame* frame,
1566 const YUVVideoDrawQuad* quad) {
1567 SetBlendEnabled(quad->ShouldDrawWithBlending());
1569 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1570 gl_,
1571 &highp_threshold_cache_,
1572 highp_threshold_min_,
1573 quad->shared_quad_state->visible_content_rect.bottom_right());
1575 bool use_alpha_plane = quad->a_plane_resource_id != 0;
1577 ResourceProvider::ScopedSamplerGL y_plane_lock(
1578 resource_provider_, quad->y_plane_resource_id, GL_TEXTURE1, GL_LINEAR);
1579 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), y_plane_lock.target());
1580 ResourceProvider::ScopedSamplerGL u_plane_lock(
1581 resource_provider_, quad->u_plane_resource_id, GL_TEXTURE2, GL_LINEAR);
1582 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), u_plane_lock.target());
1583 ResourceProvider::ScopedSamplerGL v_plane_lock(
1584 resource_provider_, quad->v_plane_resource_id, GL_TEXTURE3, GL_LINEAR);
1585 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), v_plane_lock.target());
1586 scoped_ptr<ResourceProvider::ScopedSamplerGL> a_plane_lock;
1587 if (use_alpha_plane) {
1588 a_plane_lock.reset(new ResourceProvider::ScopedSamplerGL(
1589 resource_provider_, quad->a_plane_resource_id, GL_TEXTURE4, GL_LINEAR));
1590 DCHECK_EQ(static_cast<GLenum>(GL_TEXTURE_2D), a_plane_lock->target());
1593 int tex_scale_location = -1;
1594 int matrix_location = -1;
1595 int y_texture_location = -1;
1596 int u_texture_location = -1;
1597 int v_texture_location = -1;
1598 int a_texture_location = -1;
1599 int yuv_matrix_location = -1;
1600 int yuv_adj_location = -1;
1601 int alpha_location = -1;
1602 if (use_alpha_plane) {
1603 const VideoYUVAProgram* program = GetVideoYUVAProgram(tex_coord_precision);
1604 DCHECK(program && (program->initialized() || IsContextLost()));
1605 SetUseProgram(program->program());
1606 tex_scale_location = program->vertex_shader().tex_scale_location();
1607 matrix_location = program->vertex_shader().matrix_location();
1608 y_texture_location = program->fragment_shader().y_texture_location();
1609 u_texture_location = program->fragment_shader().u_texture_location();
1610 v_texture_location = program->fragment_shader().v_texture_location();
1611 a_texture_location = program->fragment_shader().a_texture_location();
1612 yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
1613 yuv_adj_location = program->fragment_shader().yuv_adj_location();
1614 alpha_location = program->fragment_shader().alpha_location();
1615 } else {
1616 const VideoYUVProgram* program = GetVideoYUVProgram(tex_coord_precision);
1617 DCHECK(program && (program->initialized() || IsContextLost()));
1618 SetUseProgram(program->program());
1619 tex_scale_location = program->vertex_shader().tex_scale_location();
1620 matrix_location = program->vertex_shader().matrix_location();
1621 y_texture_location = program->fragment_shader().y_texture_location();
1622 u_texture_location = program->fragment_shader().u_texture_location();
1623 v_texture_location = program->fragment_shader().v_texture_location();
1624 yuv_matrix_location = program->fragment_shader().yuv_matrix_location();
1625 yuv_adj_location = program->fragment_shader().yuv_adj_location();
1626 alpha_location = program->fragment_shader().alpha_location();
1629 GLC(gl_,
1630 gl_->Uniform2f(tex_scale_location,
1631 quad->tex_scale.width(),
1632 quad->tex_scale.height()));
1633 GLC(gl_, gl_->Uniform1i(y_texture_location, 1));
1634 GLC(gl_, gl_->Uniform1i(u_texture_location, 2));
1635 GLC(gl_, gl_->Uniform1i(v_texture_location, 3));
1636 if (use_alpha_plane)
1637 GLC(gl_, gl_->Uniform1i(a_texture_location, 4));
1639 // These values are magic numbers that are used in the transformation from YUV
1640 // to RGB color values. They are taken from the following webpage:
1641 // http://www.fourcc.org/fccyvrgb.php
1642 float yuv_to_rgb[9] = {1.164f, 1.164f, 1.164f, 0.0f, -.391f,
1643 2.018f, 1.596f, -.813f, 0.0f, };
1644 GLC(gl_, gl_->UniformMatrix3fv(yuv_matrix_location, 1, 0, yuv_to_rgb));
1646 // These values map to 16, 128, and 128 respectively, and are computed
1647 // as a fraction over 256 (e.g. 16 / 256 = 0.0625).
1648 // They are used in the YUV to RGBA conversion formula:
1649 // Y - 16 : Gives 16 values of head and footroom for overshooting
1650 // U - 128 : Turns unsigned U into signed U [-128,127]
1651 // V - 128 : Turns unsigned V into signed V [-128,127]
1652 float yuv_adjust[3] = {-0.0625f, -0.5f, -0.5f, };
1653 GLC(gl_, gl_->Uniform3fv(yuv_adj_location, 1, yuv_adjust));
1655 SetShaderOpacity(quad->opacity(), alpha_location);
1656 DrawQuadGeometry(frame, quad->quadTransform(), quad->rect, matrix_location);
1659 void GLRenderer::DrawStreamVideoQuad(const DrawingFrame* frame,
1660 const StreamVideoDrawQuad* quad) {
1661 SetBlendEnabled(quad->ShouldDrawWithBlending());
1663 static float gl_matrix[16];
1665 DCHECK(capabilities_.using_egl_image);
1667 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1668 gl_,
1669 &highp_threshold_cache_,
1670 highp_threshold_min_,
1671 quad->shared_quad_state->visible_content_rect.bottom_right());
1673 const VideoStreamTextureProgram* program =
1674 GetVideoStreamTextureProgram(tex_coord_precision);
1675 SetUseProgram(program->program());
1677 ToGLMatrix(&gl_matrix[0], quad->matrix);
1678 GLC(gl_,
1679 gl_->UniformMatrix4fv(
1680 program->vertex_shader().tex_matrix_location(), 1, false, gl_matrix));
1682 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
1683 quad->resource_id);
1684 DCHECK_EQ(GL_TEXTURE0, ResourceProvider::GetActiveTextureUnit(gl_));
1685 GLC(gl_, gl_->BindTexture(GL_TEXTURE_EXTERNAL_OES, lock.texture_id()));
1687 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
1689 SetShaderOpacity(quad->opacity(),
1690 program->fragment_shader().alpha_location());
1691 DrawQuadGeometry(frame,
1692 quad->quadTransform(),
1693 quad->rect,
1694 program->vertex_shader().matrix_location());
1697 void GLRenderer::DrawPictureQuad(const DrawingFrame* frame,
1698 const PictureDrawQuad* quad) {
1699 if (on_demand_tile_raster_bitmap_.width() != quad->texture_size.width() ||
1700 on_demand_tile_raster_bitmap_.height() != quad->texture_size.height()) {
1701 on_demand_tile_raster_bitmap_.setConfig(SkBitmap::kARGB_8888_Config,
1702 quad->texture_size.width(),
1703 quad->texture_size.height());
1704 on_demand_tile_raster_bitmap_.allocPixels();
1706 if (on_demand_tile_raster_resource_id_)
1707 resource_provider_->DeleteResource(on_demand_tile_raster_resource_id_);
1709 on_demand_tile_raster_resource_id_ =
1710 resource_provider_->CreateGLTexture(quad->texture_size,
1711 GL_TEXTURE_2D,
1712 GL_TEXTURE_POOL_UNMANAGED_CHROMIUM,
1713 GL_CLAMP_TO_EDGE,
1714 ResourceProvider::TextureUsageAny,
1715 quad->texture_format);
1718 SkBitmapDevice device(on_demand_tile_raster_bitmap_);
1719 SkCanvas canvas(&device);
1721 quad->picture_pile->RasterToBitmap(
1722 &canvas, quad->content_rect, quad->contents_scale, NULL);
1724 uint8_t* bitmap_pixels = NULL;
1725 SkBitmap on_demand_tile_raster_bitmap_dest;
1726 SkBitmap::Config config = SkBitmapConfig(quad->texture_format);
1727 if (on_demand_tile_raster_bitmap_.getConfig() != config) {
1728 on_demand_tile_raster_bitmap_.copyTo(&on_demand_tile_raster_bitmap_dest,
1729 config);
1730 // TODO(kaanb): The GL pipeline assumes a 4-byte alignment for the
1731 // bitmap data. This check will be removed once crbug.com/293728 is fixed.
1732 CHECK_EQ(0u, on_demand_tile_raster_bitmap_dest.rowBytes() % 4);
1733 bitmap_pixels = reinterpret_cast<uint8_t*>(
1734 on_demand_tile_raster_bitmap_dest.getPixels());
1735 } else {
1736 bitmap_pixels =
1737 reinterpret_cast<uint8_t*>(on_demand_tile_raster_bitmap_.getPixels());
1740 resource_provider_->SetPixels(on_demand_tile_raster_resource_id_,
1741 bitmap_pixels,
1742 gfx::Rect(quad->texture_size),
1743 gfx::Rect(quad->texture_size),
1744 gfx::Vector2d());
1746 DrawContentQuad(frame, quad, on_demand_tile_raster_resource_id_);
1749 struct TextureProgramBinding {
1750 template <class Program>
1751 void Set(Program* program) {
1752 DCHECK(program);
1753 program_id = program->program();
1754 sampler_location = program->fragment_shader().sampler_location();
1755 matrix_location = program->vertex_shader().matrix_location();
1756 background_color_location =
1757 program->fragment_shader().background_color_location();
1759 int program_id;
1760 int sampler_location;
1761 int matrix_location;
1762 int background_color_location;
1765 struct TexTransformTextureProgramBinding : TextureProgramBinding {
1766 template <class Program>
1767 void Set(Program* program) {
1768 TextureProgramBinding::Set(program);
1769 tex_transform_location = program->vertex_shader().tex_transform_location();
1770 vertex_opacity_location =
1771 program->vertex_shader().vertex_opacity_location();
1773 int tex_transform_location;
1774 int vertex_opacity_location;
1777 void GLRenderer::FlushTextureQuadCache() {
1778 // Check to see if we have anything to draw.
1779 if (draw_cache_.program_id == 0)
1780 return;
1782 // Set the correct blending mode.
1783 SetBlendEnabled(draw_cache_.needs_blending);
1785 // Bind the program to the GL state.
1786 SetUseProgram(draw_cache_.program_id);
1788 // Bind the correct texture sampler location.
1789 GLC(gl_, gl_->Uniform1i(draw_cache_.sampler_location, 0));
1791 // Assume the current active textures is 0.
1792 ResourceProvider::ScopedReadLockGL locked_quad(resource_provider_,
1793 draw_cache_.resource_id);
1794 DCHECK_EQ(GL_TEXTURE0, ResourceProvider::GetActiveTextureUnit(gl_));
1795 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, locked_quad.texture_id()));
1797 COMPILE_ASSERT(sizeof(Float4) == 4 * sizeof(float), // NOLINT(runtime/sizeof)
1798 struct_is_densely_packed);
1799 COMPILE_ASSERT(
1800 sizeof(Float16) == 16 * sizeof(float), // NOLINT(runtime/sizeof)
1801 struct_is_densely_packed);
1803 // Upload the tranforms for both points and uvs.
1804 GLC(gl_,
1805 gl_->UniformMatrix4fv(
1806 static_cast<int>(draw_cache_.matrix_location),
1807 static_cast<int>(draw_cache_.matrix_data.size()),
1808 false,
1809 reinterpret_cast<float*>(&draw_cache_.matrix_data.front())));
1810 GLC(gl_,
1811 gl_->Uniform4fv(
1812 static_cast<int>(draw_cache_.uv_xform_location),
1813 static_cast<int>(draw_cache_.uv_xform_data.size()),
1814 reinterpret_cast<float*>(&draw_cache_.uv_xform_data.front())));
1816 if (draw_cache_.background_color != SK_ColorTRANSPARENT) {
1817 Float4 background_color = PremultipliedColor(draw_cache_.background_color);
1818 GLC(gl_,
1819 gl_->Uniform4fv(
1820 draw_cache_.background_color_location, 1, background_color.data));
1823 GLC(gl_,
1824 gl_->Uniform1fv(
1825 static_cast<int>(draw_cache_.vertex_opacity_location),
1826 static_cast<int>(draw_cache_.vertex_opacity_data.size()),
1827 static_cast<float*>(&draw_cache_.vertex_opacity_data.front())));
1829 // Draw the quads!
1830 GLC(gl_,
1831 gl_->DrawElements(GL_TRIANGLES,
1832 6 * draw_cache_.matrix_data.size(),
1833 GL_UNSIGNED_SHORT,
1834 0));
1836 // Clear the cache.
1837 draw_cache_.program_id = 0;
1838 draw_cache_.uv_xform_data.resize(0);
1839 draw_cache_.vertex_opacity_data.resize(0);
1840 draw_cache_.matrix_data.resize(0);
1843 void GLRenderer::EnqueueTextureQuad(const DrawingFrame* frame,
1844 const TextureDrawQuad* quad) {
1845 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1846 gl_,
1847 &highp_threshold_cache_,
1848 highp_threshold_min_,
1849 quad->shared_quad_state->visible_content_rect.bottom_right());
1851 // Choose the correct texture program binding
1852 TexTransformTextureProgramBinding binding;
1853 if (quad->premultiplied_alpha) {
1854 if (quad->background_color == SK_ColorTRANSPARENT) {
1855 binding.Set(GetTextureProgram(tex_coord_precision));
1856 } else {
1857 binding.Set(GetTextureBackgroundProgram(tex_coord_precision));
1859 } else {
1860 if (quad->background_color == SK_ColorTRANSPARENT) {
1861 binding.Set(GetNonPremultipliedTextureProgram(tex_coord_precision));
1862 } else {
1863 binding.Set(
1864 GetNonPremultipliedTextureBackgroundProgram(tex_coord_precision));
1868 int resource_id = quad->resource_id;
1870 if (draw_cache_.program_id != binding.program_id ||
1871 draw_cache_.resource_id != resource_id ||
1872 draw_cache_.needs_blending != quad->ShouldDrawWithBlending() ||
1873 draw_cache_.background_color != quad->background_color ||
1874 draw_cache_.matrix_data.size() >= 8) {
1875 FlushTextureQuadCache();
1876 draw_cache_.program_id = binding.program_id;
1877 draw_cache_.resource_id = resource_id;
1878 draw_cache_.needs_blending = quad->ShouldDrawWithBlending();
1879 draw_cache_.background_color = quad->background_color;
1881 draw_cache_.uv_xform_location = binding.tex_transform_location;
1882 draw_cache_.background_color_location = binding.background_color_location;
1883 draw_cache_.vertex_opacity_location = binding.vertex_opacity_location;
1884 draw_cache_.matrix_location = binding.matrix_location;
1885 draw_cache_.sampler_location = binding.sampler_location;
1888 // Generate the uv-transform
1889 draw_cache_.uv_xform_data.push_back(UVTransform(quad));
1891 // Generate the vertex opacity
1892 const float opacity = quad->opacity();
1893 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[0] * opacity);
1894 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[1] * opacity);
1895 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[2] * opacity);
1896 draw_cache_.vertex_opacity_data.push_back(quad->vertex_opacity[3] * opacity);
1898 // Generate the transform matrix
1899 gfx::Transform quad_rect_matrix;
1900 QuadRectTransform(&quad_rect_matrix, quad->quadTransform(), quad->rect);
1901 quad_rect_matrix = frame->projection_matrix * quad_rect_matrix;
1903 Float16 m;
1904 quad_rect_matrix.matrix().asColMajorf(m.data);
1905 draw_cache_.matrix_data.push_back(m);
1908 void GLRenderer::DrawIOSurfaceQuad(const DrawingFrame* frame,
1909 const IOSurfaceDrawQuad* quad) {
1910 SetBlendEnabled(quad->ShouldDrawWithBlending());
1912 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
1913 gl_,
1914 &highp_threshold_cache_,
1915 highp_threshold_min_,
1916 quad->shared_quad_state->visible_content_rect.bottom_right());
1918 TexTransformTextureProgramBinding binding;
1919 binding.Set(GetTextureIOSurfaceProgram(tex_coord_precision));
1921 SetUseProgram(binding.program_id);
1922 GLC(gl_, gl_->Uniform1i(binding.sampler_location, 0));
1923 if (quad->orientation == IOSurfaceDrawQuad::FLIPPED) {
1924 GLC(gl_,
1925 gl_->Uniform4f(binding.tex_transform_location,
1927 quad->io_surface_size.height(),
1928 quad->io_surface_size.width(),
1929 quad->io_surface_size.height() * -1.0f));
1930 } else {
1931 GLC(gl_,
1932 gl_->Uniform4f(binding.tex_transform_location,
1935 quad->io_surface_size.width(),
1936 quad->io_surface_size.height()));
1939 const float vertex_opacity[] = {quad->opacity(), quad->opacity(),
1940 quad->opacity(), quad->opacity()};
1941 GLC(gl_, gl_->Uniform1fv(binding.vertex_opacity_location, 4, vertex_opacity));
1943 ResourceProvider::ScopedReadLockGL lock(resource_provider_,
1944 quad->io_surface_resource_id);
1945 DCHECK_EQ(GL_TEXTURE0, ResourceProvider::GetActiveTextureUnit(gl_));
1946 GLC(gl_, gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, lock.texture_id()));
1948 DrawQuadGeometry(
1949 frame, quad->quadTransform(), quad->rect, binding.matrix_location);
1951 GLC(gl_, gl_->BindTexture(GL_TEXTURE_RECTANGLE_ARB, 0));
1954 void GLRenderer::FinishDrawingFrame(DrawingFrame* frame) {
1955 current_framebuffer_lock_.reset();
1956 swap_buffer_rect_.Union(gfx::ToEnclosingRect(frame->root_damage_rect));
1958 GLC(gl_, gl_->Disable(GL_BLEND));
1959 blend_shadow_ = false;
1962 void GLRenderer::FinishDrawingQuadList() { FlushTextureQuadCache(); }
1964 bool GLRenderer::FlippedFramebuffer() const { return true; }
1966 void GLRenderer::EnsureScissorTestEnabled() {
1967 if (is_scissor_enabled_)
1968 return;
1970 FlushTextureQuadCache();
1971 GLC(gl_, gl_->Enable(GL_SCISSOR_TEST));
1972 is_scissor_enabled_ = true;
1975 void GLRenderer::EnsureScissorTestDisabled() {
1976 if (!is_scissor_enabled_)
1977 return;
1979 FlushTextureQuadCache();
1980 GLC(gl_, gl_->Disable(GL_SCISSOR_TEST));
1981 is_scissor_enabled_ = false;
1984 void GLRenderer::CopyCurrentRenderPassToBitmap(
1985 DrawingFrame* frame,
1986 scoped_ptr<CopyOutputRequest> request) {
1987 gfx::Rect copy_rect = frame->current_render_pass->output_rect;
1988 if (request->has_area())
1989 copy_rect.Intersect(request->area());
1990 GetFramebufferPixelsAsync(copy_rect, request.Pass());
1993 void GLRenderer::ToGLMatrix(float* gl_matrix, const gfx::Transform& transform) {
1994 transform.matrix().asColMajorf(gl_matrix);
1997 void GLRenderer::SetShaderQuadF(const gfx::QuadF& quad, int quad_location) {
1998 if (quad_location == -1)
1999 return;
2001 float gl_quad[8];
2002 gl_quad[0] = quad.p1().x();
2003 gl_quad[1] = quad.p1().y();
2004 gl_quad[2] = quad.p2().x();
2005 gl_quad[3] = quad.p2().y();
2006 gl_quad[4] = quad.p3().x();
2007 gl_quad[5] = quad.p3().y();
2008 gl_quad[6] = quad.p4().x();
2009 gl_quad[7] = quad.p4().y();
2010 GLC(gl_, gl_->Uniform2fv(quad_location, 4, gl_quad));
2013 void GLRenderer::SetShaderOpacity(float opacity, int alpha_location) {
2014 if (alpha_location != -1)
2015 GLC(gl_, gl_->Uniform1f(alpha_location, opacity));
2018 void GLRenderer::SetStencilEnabled(bool enabled) {
2019 if (enabled == stencil_shadow_)
2020 return;
2022 if (enabled)
2023 GLC(gl_, gl_->Enable(GL_STENCIL_TEST));
2024 else
2025 GLC(gl_, gl_->Disable(GL_STENCIL_TEST));
2026 stencil_shadow_ = enabled;
2029 void GLRenderer::SetBlendEnabled(bool enabled) {
2030 if (enabled == blend_shadow_)
2031 return;
2033 if (enabled)
2034 GLC(gl_, gl_->Enable(GL_BLEND));
2035 else
2036 GLC(gl_, gl_->Disable(GL_BLEND));
2037 blend_shadow_ = enabled;
2040 void GLRenderer::SetUseProgram(unsigned program) {
2041 if (program == program_shadow_)
2042 return;
2043 gl_->UseProgram(program);
2044 program_shadow_ = program;
2047 void GLRenderer::DrawQuadGeometry(const DrawingFrame* frame,
2048 const gfx::Transform& draw_transform,
2049 const gfx::RectF& quad_rect,
2050 int matrix_location) {
2051 gfx::Transform quad_rect_matrix;
2052 QuadRectTransform(&quad_rect_matrix, draw_transform, quad_rect);
2053 static float gl_matrix[16];
2054 ToGLMatrix(&gl_matrix[0], frame->projection_matrix * quad_rect_matrix);
2055 GLC(gl_, gl_->UniformMatrix4fv(matrix_location, 1, false, &gl_matrix[0]));
2057 GLC(gl_, gl_->DrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0));
2060 void GLRenderer::CopyTextureToFramebuffer(const DrawingFrame* frame,
2061 int texture_id,
2062 const gfx::Rect& rect,
2063 const gfx::Transform& draw_matrix,
2064 bool flip_vertically) {
2065 TexCoordPrecision tex_coord_precision = TexCoordPrecisionRequired(
2066 gl_, &highp_threshold_cache_, highp_threshold_min_, rect.bottom_right());
2068 const RenderPassProgram* program = GetRenderPassProgram(tex_coord_precision);
2069 SetUseProgram(program->program());
2071 GLC(gl_, gl_->Uniform1i(program->fragment_shader().sampler_location(), 0));
2073 if (flip_vertically) {
2074 GLC(gl_,
2075 gl_->Uniform4f(program->vertex_shader().tex_transform_location(),
2076 0.f,
2077 1.f,
2078 1.f,
2079 -1.f));
2080 } else {
2081 GLC(gl_,
2082 gl_->Uniform4f(program->vertex_shader().tex_transform_location(),
2083 0.f,
2084 0.f,
2085 1.f,
2086 1.f));
2089 SetShaderOpacity(1.f, program->fragment_shader().alpha_location());
2090 DCHECK_EQ(GL_TEXTURE0, ResourceProvider::GetActiveTextureUnit(gl_));
2091 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, texture_id));
2092 DrawQuadGeometry(
2093 frame, draw_matrix, rect, program->vertex_shader().matrix_location());
2096 void GLRenderer::Finish() {
2097 TRACE_EVENT0("cc", "GLRenderer::Finish");
2098 GLC(gl_, gl_->Finish());
2101 void GLRenderer::SwapBuffers(const CompositorFrameMetadata& metadata) {
2102 DCHECK(!is_backbuffer_discarded_);
2104 TRACE_EVENT0("cc", "GLRenderer::SwapBuffers");
2105 // We're done! Time to swapbuffers!
2107 gfx::Size surface_size = output_surface_->SurfaceSize();
2109 CompositorFrame compositor_frame;
2110 compositor_frame.metadata = metadata;
2111 compositor_frame.gl_frame_data = make_scoped_ptr(new GLFrameData);
2112 compositor_frame.gl_frame_data->size = surface_size;
2113 if (capabilities_.using_partial_swap) {
2114 // If supported, we can save significant bandwidth by only swapping the
2115 // damaged/scissored region (clamped to the viewport).
2116 swap_buffer_rect_.Intersect(gfx::Rect(surface_size));
2117 int flipped_y_pos_of_rect_bottom = surface_size.height() -
2118 swap_buffer_rect_.y() -
2119 swap_buffer_rect_.height();
2120 compositor_frame.gl_frame_data->sub_buffer_rect =
2121 gfx::Rect(swap_buffer_rect_.x(),
2122 flipped_y_pos_of_rect_bottom,
2123 swap_buffer_rect_.width(),
2124 swap_buffer_rect_.height());
2125 } else {
2126 compositor_frame.gl_frame_data->sub_buffer_rect =
2127 gfx::Rect(output_surface_->SurfaceSize());
2129 output_surface_->SwapBuffers(&compositor_frame);
2131 swap_buffer_rect_ = gfx::Rect();
2133 // We don't have real fences, so we mark read fences as passed
2134 // assuming a double-buffered GPU pipeline. A texture can be
2135 // written to after one full frame has past since it was last read.
2136 if (last_swap_fence_.get())
2137 static_cast<SimpleSwapFence*>(last_swap_fence_.get())->SetHasPassed();
2138 last_swap_fence_ = resource_provider_->GetReadLockFence();
2139 resource_provider_->SetReadLockFence(new SimpleSwapFence());
2142 void GLRenderer::EnforceMemoryPolicy() {
2143 if (!visible_) {
2144 TRACE_EVENT0("cc", "GLRenderer::EnforceMemoryPolicy dropping resources");
2145 ReleaseRenderPassTextures();
2146 DiscardBackbuffer();
2147 resource_provider_->ReleaseCachedData();
2148 GLC(gl_, gl_->Flush());
2152 void GLRenderer::DiscardBackbuffer() {
2153 if (is_backbuffer_discarded_)
2154 return;
2156 output_surface_->DiscardBackbuffer();
2158 is_backbuffer_discarded_ = true;
2160 // Damage tracker needs a full reset every time framebuffer is discarded.
2161 client_->SetFullRootLayerDamage();
2164 void GLRenderer::EnsureBackbuffer() {
2165 if (!is_backbuffer_discarded_)
2166 return;
2168 output_surface_->EnsureBackbuffer();
2169 is_backbuffer_discarded_ = false;
2172 void GLRenderer::GetFramebufferPixels(void* pixels, const gfx::Rect& rect) {
2173 if (!pixels || rect.IsEmpty())
2174 return;
2176 // This function assumes that it is reading the root frame buffer.
2177 DCHECK(!current_framebuffer_lock_);
2179 scoped_ptr<PendingAsyncReadPixels> pending_read(new PendingAsyncReadPixels);
2180 pending_async_read_pixels_.insert(pending_async_read_pixels_.begin(),
2181 pending_read.Pass());
2183 // This is a syncronous call since the callback is null.
2184 gfx::Rect window_rect = MoveFromDrawToWindowSpace(rect);
2185 DoGetFramebufferPixels(static_cast<uint8*>(pixels),
2186 window_rect,
2187 AsyncGetFramebufferPixelsCleanupCallback());
2190 void GLRenderer::GetFramebufferPixelsAsync(
2191 const gfx::Rect& rect,
2192 scoped_ptr<CopyOutputRequest> request) {
2193 DCHECK(!request->IsEmpty());
2194 if (request->IsEmpty())
2195 return;
2196 if (rect.IsEmpty())
2197 return;
2199 gfx::Rect window_rect = MoveFromDrawToWindowSpace(rect);
2201 if (!request->force_bitmap_result()) {
2202 bool own_mailbox = !request->has_texture_mailbox();
2204 GLuint texture_id = 0;
2205 gl_->GenTextures(1, &texture_id);
2207 gpu::Mailbox mailbox;
2208 if (own_mailbox) {
2209 GLC(gl_, gl_->GenMailboxCHROMIUM(mailbox.name));
2210 if (mailbox.IsZero()) {
2211 gl_->DeleteTextures(1, &texture_id);
2212 request->SendEmptyResult();
2213 return;
2215 } else {
2216 mailbox = request->texture_mailbox().mailbox();
2217 DCHECK_EQ(static_cast<unsigned>(GL_TEXTURE_2D),
2218 request->texture_mailbox().target());
2219 DCHECK(!mailbox.IsZero());
2220 unsigned incoming_sync_point = request->texture_mailbox().sync_point();
2221 if (incoming_sync_point)
2222 GLC(gl_, gl_->WaitSyncPointCHROMIUM(incoming_sync_point));
2225 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, texture_id));
2226 if (own_mailbox) {
2227 GLC(gl_,
2228 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
2229 GLC(gl_,
2230 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
2231 GLC(gl_,
2232 gl_->TexParameteri(
2233 GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
2234 GLC(gl_,
2235 gl_->TexParameteri(
2236 GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
2237 GLC(gl_, gl_->ProduceTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name));
2238 } else {
2239 GLC(gl_, gl_->ConsumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name));
2241 GetFramebufferTexture(texture_id, RGBA_8888, window_rect);
2242 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, 0));
2244 unsigned sync_point = gl_->InsertSyncPointCHROMIUM();
2245 TextureMailbox texture_mailbox(mailbox, GL_TEXTURE_2D, sync_point);
2247 scoped_ptr<SingleReleaseCallback> release_callback;
2248 if (own_mailbox) {
2249 release_callback = texture_mailbox_deleter_->GetReleaseCallback(
2250 output_surface_->context_provider(), texture_id);
2251 } else {
2252 gl_->DeleteTextures(1, &texture_id);
2255 request->SendTextureResult(
2256 window_rect.size(), texture_mailbox, release_callback.Pass());
2257 return;
2260 DCHECK(request->force_bitmap_result());
2262 scoped_ptr<SkBitmap> bitmap(new SkBitmap);
2263 bitmap->setConfig(
2264 SkBitmap::kARGB_8888_Config, window_rect.width(), window_rect.height());
2265 bitmap->allocPixels();
2267 scoped_ptr<SkAutoLockPixels> lock(new SkAutoLockPixels(*bitmap));
2269 // Save a pointer to the pixels, the bitmap is owned by the cleanup_callback.
2270 uint8* pixels = static_cast<uint8*>(bitmap->getPixels());
2272 AsyncGetFramebufferPixelsCleanupCallback cleanup_callback =
2273 base::Bind(&GLRenderer::PassOnSkBitmap,
2274 base::Unretained(this),
2275 base::Passed(&bitmap),
2276 base::Passed(&lock));
2278 scoped_ptr<PendingAsyncReadPixels> pending_read(new PendingAsyncReadPixels);
2279 pending_read->copy_request = request.Pass();
2280 pending_async_read_pixels_.insert(pending_async_read_pixels_.begin(),
2281 pending_read.Pass());
2283 // This is an asyncronous call since the callback is not null.
2284 DoGetFramebufferPixels(pixels, window_rect, cleanup_callback);
2287 void GLRenderer::DoGetFramebufferPixels(
2288 uint8* dest_pixels,
2289 const gfx::Rect& window_rect,
2290 const AsyncGetFramebufferPixelsCleanupCallback& cleanup_callback) {
2291 DCHECK_GE(window_rect.x(), 0);
2292 DCHECK_GE(window_rect.y(), 0);
2293 DCHECK_LE(window_rect.right(), current_surface_size_.width());
2294 DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2296 bool is_async = !cleanup_callback.is_null();
2298 bool do_workaround = NeedsIOSurfaceReadbackWorkaround();
2300 unsigned temporary_texture = 0;
2301 unsigned temporary_fbo = 0;
2303 if (do_workaround) {
2304 // On Mac OS X, calling glReadPixels() against an FBO whose color attachment
2305 // is an IOSurface-backed texture causes corruption of future glReadPixels()
2306 // calls, even those on different OpenGL contexts. It is believed that this
2307 // is the root cause of top crasher
2308 // http://crbug.com/99393. <rdar://problem/10949687>
2310 gl_->GenTextures(1, &temporary_texture);
2311 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, temporary_texture));
2312 GLC(gl_,
2313 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
2314 GLC(gl_,
2315 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
2316 GLC(gl_,
2317 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
2318 GLC(gl_,
2319 gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
2320 // Copy the contents of the current (IOSurface-backed) framebuffer into a
2321 // temporary texture.
2322 GetFramebufferTexture(
2323 temporary_texture, RGBA_8888, gfx::Rect(current_surface_size_));
2324 gl_->GenFramebuffers(1, &temporary_fbo);
2325 // Attach this texture to an FBO, and perform the readback from that FBO.
2326 GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, temporary_fbo));
2327 GLC(gl_,
2328 gl_->FramebufferTexture2D(GL_FRAMEBUFFER,
2329 GL_COLOR_ATTACHMENT0,
2330 GL_TEXTURE_2D,
2331 temporary_texture,
2332 0));
2334 DCHECK_EQ(static_cast<unsigned>(GL_FRAMEBUFFER_COMPLETE),
2335 gl_->CheckFramebufferStatus(GL_FRAMEBUFFER));
2338 GLuint buffer = 0;
2339 gl_->GenBuffers(1, &buffer);
2340 GLC(gl_, gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, buffer));
2341 GLC(gl_,
2342 gl_->BufferData(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM,
2343 4 * window_rect.size().GetArea(),
2344 NULL,
2345 GL_STREAM_READ));
2347 GLuint query = 0;
2348 if (is_async) {
2349 gl_->GenQueriesEXT(1, &query);
2350 GLC(gl_, gl_->BeginQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM, query));
2353 GLC(gl_,
2354 gl_->ReadPixels(window_rect.x(),
2355 window_rect.y(),
2356 window_rect.width(),
2357 window_rect.height(),
2358 GL_RGBA,
2359 GL_UNSIGNED_BYTE,
2360 NULL));
2362 GLC(gl_, gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0));
2364 if (do_workaround) {
2365 // Clean up.
2366 GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, 0));
2367 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, 0));
2368 GLC(gl_, gl_->DeleteFramebuffers(1, &temporary_fbo));
2369 GLC(gl_, gl_->DeleteTextures(1, &temporary_texture));
2372 base::Closure finished_callback = base::Bind(&GLRenderer::FinishedReadback,
2373 base::Unretained(this),
2374 cleanup_callback,
2375 buffer,
2376 query,
2377 dest_pixels,
2378 window_rect.size());
2379 // Save the finished_callback so it can be cancelled.
2380 pending_async_read_pixels_.front()->finished_read_pixels_callback.Reset(
2381 finished_callback);
2382 base::Closure cancelable_callback =
2383 pending_async_read_pixels_.front()->
2384 finished_read_pixels_callback.callback();
2386 // Save the buffer to verify the callbacks happen in the expected order.
2387 pending_async_read_pixels_.front()->buffer = buffer;
2389 if (is_async) {
2390 GLC(gl_, gl_->EndQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM));
2391 context_support_->SignalQuery(query, cancelable_callback);
2392 } else {
2393 resource_provider_->Finish();
2394 finished_callback.Run();
2397 EnforceMemoryPolicy();
2400 void GLRenderer::FinishedReadback(
2401 const AsyncGetFramebufferPixelsCleanupCallback& cleanup_callback,
2402 unsigned source_buffer,
2403 unsigned query,
2404 uint8* dest_pixels,
2405 const gfx::Size& size) {
2406 DCHECK(!pending_async_read_pixels_.empty());
2408 if (query != 0) {
2409 GLC(gl_, gl_->DeleteQueriesEXT(1, &query));
2412 PendingAsyncReadPixels* current_read = pending_async_read_pixels_.back();
2413 // Make sure we service the readbacks in order.
2414 DCHECK_EQ(source_buffer, current_read->buffer);
2416 uint8* src_pixels = NULL;
2418 if (source_buffer != 0) {
2419 GLC(gl_,
2420 gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, source_buffer));
2421 src_pixels = static_cast<uint8*>(gl_->MapBufferCHROMIUM(
2422 GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, GL_READ_ONLY));
2424 if (src_pixels) {
2425 size_t row_bytes = size.width() * 4;
2426 int num_rows = size.height();
2427 size_t total_bytes = num_rows * row_bytes;
2428 for (size_t dest_y = 0; dest_y < total_bytes; dest_y += row_bytes) {
2429 // Flip Y axis.
2430 size_t src_y = total_bytes - dest_y - row_bytes;
2431 // Swizzle OpenGL -> Skia byte order.
2432 for (size_t x = 0; x < row_bytes; x += 4) {
2433 dest_pixels[dest_y + x + SK_R32_SHIFT / 8] =
2434 src_pixels[src_y + x + 0];
2435 dest_pixels[dest_y + x + SK_G32_SHIFT / 8] =
2436 src_pixels[src_y + x + 1];
2437 dest_pixels[dest_y + x + SK_B32_SHIFT / 8] =
2438 src_pixels[src_y + x + 2];
2439 dest_pixels[dest_y + x + SK_A32_SHIFT / 8] =
2440 src_pixels[src_y + x + 3];
2444 GLC(gl_,
2445 gl_->UnmapBufferCHROMIUM(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM));
2447 GLC(gl_, gl_->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM, 0));
2448 GLC(gl_, gl_->DeleteBuffers(1, &source_buffer));
2451 // TODO(danakj): This can go away when synchronous readback is no more and its
2452 // contents can just move here.
2453 if (!cleanup_callback.is_null())
2454 cleanup_callback.Run(current_read->copy_request.Pass(), src_pixels != NULL);
2456 pending_async_read_pixels_.pop_back();
2459 void GLRenderer::PassOnSkBitmap(scoped_ptr<SkBitmap> bitmap,
2460 scoped_ptr<SkAutoLockPixels> lock,
2461 scoped_ptr<CopyOutputRequest> request,
2462 bool success) {
2463 DCHECK(request->force_bitmap_result());
2465 lock.reset();
2466 if (success)
2467 request->SendBitmapResult(bitmap.Pass());
2470 void GLRenderer::GetFramebufferTexture(unsigned texture_id,
2471 ResourceFormat texture_format,
2472 const gfx::Rect& window_rect) {
2473 DCHECK(texture_id);
2474 DCHECK_GE(window_rect.x(), 0);
2475 DCHECK_GE(window_rect.y(), 0);
2476 DCHECK_LE(window_rect.right(), current_surface_size_.width());
2477 DCHECK_LE(window_rect.bottom(), current_surface_size_.height());
2479 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, texture_id));
2480 GLC(gl_,
2481 gl_->CopyTexImage2D(GL_TEXTURE_2D,
2483 GLDataFormat(texture_format),
2484 window_rect.x(),
2485 window_rect.y(),
2486 window_rect.width(),
2487 window_rect.height(),
2488 0));
2489 GLC(gl_, gl_->BindTexture(GL_TEXTURE_2D, 0));
2492 bool GLRenderer::UseScopedTexture(DrawingFrame* frame,
2493 const ScopedResource* texture,
2494 const gfx::Rect& viewport_rect) {
2495 DCHECK(texture->id());
2496 frame->current_render_pass = NULL;
2497 frame->current_texture = texture;
2499 return BindFramebufferToTexture(frame, texture, viewport_rect);
2502 void GLRenderer::BindFramebufferToOutputSurface(DrawingFrame* frame) {
2503 current_framebuffer_lock_.reset();
2504 output_surface_->BindFramebuffer();
2506 if (output_surface_->HasExternalStencilTest()) {
2507 SetStencilEnabled(true);
2508 GLC(gl_, gl_->StencilFunc(GL_EQUAL, 1, 1));
2509 } else {
2510 SetStencilEnabled(false);
2514 bool GLRenderer::BindFramebufferToTexture(DrawingFrame* frame,
2515 const ScopedResource* texture,
2516 const gfx::Rect& target_rect) {
2517 DCHECK(texture->id());
2519 current_framebuffer_lock_.reset();
2521 SetStencilEnabled(false);
2522 GLC(gl_, gl_->BindFramebuffer(GL_FRAMEBUFFER, offscreen_framebuffer_id_));
2523 current_framebuffer_lock_ =
2524 make_scoped_ptr(new ResourceProvider::ScopedWriteLockGL(
2525 resource_provider_, texture->id()));
2526 unsigned texture_id = current_framebuffer_lock_->texture_id();
2527 GLC(gl_,
2528 gl_->FramebufferTexture2D(
2529 GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_id, 0));
2531 DCHECK(gl_->CheckFramebufferStatus(GL_FRAMEBUFFER) ==
2532 GL_FRAMEBUFFER_COMPLETE ||
2533 IsContextLost());
2535 InitializeViewport(
2536 frame, target_rect, gfx::Rect(target_rect.size()), target_rect.size());
2537 return true;
2540 void GLRenderer::SetScissorTestRect(const gfx::Rect& scissor_rect) {
2541 EnsureScissorTestEnabled();
2543 // Don't unnecessarily ask the context to change the scissor, because it
2544 // may cause undesired GPU pipeline flushes.
2545 if (scissor_rect == scissor_rect_ && !scissor_rect_needs_reset_)
2546 return;
2548 scissor_rect_ = scissor_rect;
2549 FlushTextureQuadCache();
2550 GLC(gl_,
2551 gl_->Scissor(scissor_rect.x(),
2552 scissor_rect.y(),
2553 scissor_rect.width(),
2554 scissor_rect.height()));
2556 scissor_rect_needs_reset_ = false;
2559 void GLRenderer::SetDrawViewport(const gfx::Rect& window_space_viewport) {
2560 viewport_ = window_space_viewport;
2561 GLC(gl_,
2562 gl_->Viewport(window_space_viewport.x(),
2563 window_space_viewport.y(),
2564 window_space_viewport.width(),
2565 window_space_viewport.height()));
2568 void GLRenderer::InitializeSharedObjects() {
2569 TRACE_EVENT0("cc", "GLRenderer::InitializeSharedObjects");
2571 // Create an FBO for doing offscreen rendering.
2572 GLC(gl_, gl_->GenFramebuffers(1, &offscreen_framebuffer_id_));
2574 shared_geometry_ = make_scoped_ptr(
2575 new GeometryBinding(gl_, QuadVertexRect()));
2578 const GLRenderer::TileCheckerboardProgram*
2579 GLRenderer::GetTileCheckerboardProgram() {
2580 if (!tile_checkerboard_program_.initialized()) {
2581 TRACE_EVENT0("cc", "GLRenderer::checkerboardProgram::initalize");
2582 tile_checkerboard_program_.Initialize(output_surface_->context_provider(),
2583 TexCoordPrecisionNA,
2584 SamplerTypeNA);
2586 return &tile_checkerboard_program_;
2589 const GLRenderer::DebugBorderProgram* GLRenderer::GetDebugBorderProgram() {
2590 if (!debug_border_program_.initialized()) {
2591 TRACE_EVENT0("cc", "GLRenderer::debugBorderProgram::initialize");
2592 debug_border_program_.Initialize(output_surface_->context_provider(),
2593 TexCoordPrecisionNA,
2594 SamplerTypeNA);
2596 return &debug_border_program_;
2599 const GLRenderer::SolidColorProgram* GLRenderer::GetSolidColorProgram() {
2600 if (!solid_color_program_.initialized()) {
2601 TRACE_EVENT0("cc", "GLRenderer::solidColorProgram::initialize");
2602 solid_color_program_.Initialize(output_surface_->context_provider(),
2603 TexCoordPrecisionNA,
2604 SamplerTypeNA);
2606 return &solid_color_program_;
2609 const GLRenderer::SolidColorProgramAA* GLRenderer::GetSolidColorProgramAA() {
2610 if (!solid_color_program_aa_.initialized()) {
2611 TRACE_EVENT0("cc", "GLRenderer::solidColorProgramAA::initialize");
2612 solid_color_program_aa_.Initialize(output_surface_->context_provider(),
2613 TexCoordPrecisionNA,
2614 SamplerTypeNA);
2616 return &solid_color_program_aa_;
2619 const GLRenderer::RenderPassProgram* GLRenderer::GetRenderPassProgram(
2620 TexCoordPrecision precision) {
2621 DCHECK_GE(precision, 0);
2622 DCHECK_LT(precision, NumTexCoordPrecisions);
2623 RenderPassProgram* program = &render_pass_program_[precision];
2624 if (!program->initialized()) {
2625 TRACE_EVENT0("cc", "GLRenderer::renderPassProgram::initialize");
2626 program->Initialize(
2627 output_surface_->context_provider(), precision, SamplerType2D);
2629 return program;
2632 const GLRenderer::RenderPassProgramAA* GLRenderer::GetRenderPassProgramAA(
2633 TexCoordPrecision precision) {
2634 DCHECK_GE(precision, 0);
2635 DCHECK_LT(precision, NumTexCoordPrecisions);
2636 RenderPassProgramAA* program = &render_pass_program_aa_[precision];
2637 if (!program->initialized()) {
2638 TRACE_EVENT0("cc", "GLRenderer::renderPassProgramAA::initialize");
2639 program->Initialize(
2640 output_surface_->context_provider(), precision, SamplerType2D);
2642 return program;
2645 const GLRenderer::RenderPassMaskProgram* GLRenderer::GetRenderPassMaskProgram(
2646 TexCoordPrecision precision) {
2647 DCHECK_GE(precision, 0);
2648 DCHECK_LT(precision, NumTexCoordPrecisions);
2649 RenderPassMaskProgram* program = &render_pass_mask_program_[precision];
2650 if (!program->initialized()) {
2651 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgram::initialize");
2652 program->Initialize(
2653 output_surface_->context_provider(), precision, SamplerType2D);
2655 return program;
2658 const GLRenderer::RenderPassMaskProgramAA*
2659 GLRenderer::GetRenderPassMaskProgramAA(TexCoordPrecision precision) {
2660 DCHECK_GE(precision, 0);
2661 DCHECK_LT(precision, NumTexCoordPrecisions);
2662 RenderPassMaskProgramAA* program = &render_pass_mask_program_aa_[precision];
2663 if (!program->initialized()) {
2664 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgramAA::initialize");
2665 program->Initialize(
2666 output_surface_->context_provider(), precision, SamplerType2D);
2668 return program;
2671 const GLRenderer::RenderPassColorMatrixProgram*
2672 GLRenderer::GetRenderPassColorMatrixProgram(TexCoordPrecision precision) {
2673 DCHECK_GE(precision, 0);
2674 DCHECK_LT(precision, NumTexCoordPrecisions);
2675 RenderPassColorMatrixProgram* program =
2676 &render_pass_color_matrix_program_[precision];
2677 if (!program->initialized()) {
2678 TRACE_EVENT0("cc", "GLRenderer::renderPassColorMatrixProgram::initialize");
2679 program->Initialize(
2680 output_surface_->context_provider(), precision, SamplerType2D);
2682 return program;
2685 const GLRenderer::RenderPassColorMatrixProgramAA*
2686 GLRenderer::GetRenderPassColorMatrixProgramAA(TexCoordPrecision precision) {
2687 DCHECK_GE(precision, 0);
2688 DCHECK_LT(precision, NumTexCoordPrecisions);
2689 RenderPassColorMatrixProgramAA* program =
2690 &render_pass_color_matrix_program_aa_[precision];
2691 if (!program->initialized()) {
2692 TRACE_EVENT0("cc",
2693 "GLRenderer::renderPassColorMatrixProgramAA::initialize");
2694 program->Initialize(
2695 output_surface_->context_provider(), precision, SamplerType2D);
2697 return program;
2700 const GLRenderer::RenderPassMaskColorMatrixProgram*
2701 GLRenderer::GetRenderPassMaskColorMatrixProgram(TexCoordPrecision precision) {
2702 DCHECK_GE(precision, 0);
2703 DCHECK_LT(precision, NumTexCoordPrecisions);
2704 RenderPassMaskColorMatrixProgram* program =
2705 &render_pass_mask_color_matrix_program_[precision];
2706 if (!program->initialized()) {
2707 TRACE_EVENT0("cc",
2708 "GLRenderer::renderPassMaskColorMatrixProgram::initialize");
2709 program->Initialize(
2710 output_surface_->context_provider(), precision, SamplerType2D);
2712 return program;
2715 const GLRenderer::RenderPassMaskColorMatrixProgramAA*
2716 GLRenderer::GetRenderPassMaskColorMatrixProgramAA(TexCoordPrecision precision) {
2717 DCHECK_GE(precision, 0);
2718 DCHECK_LT(precision, NumTexCoordPrecisions);
2719 RenderPassMaskColorMatrixProgramAA* program =
2720 &render_pass_mask_color_matrix_program_aa_[precision];
2721 if (!program->initialized()) {
2722 TRACE_EVENT0("cc",
2723 "GLRenderer::renderPassMaskColorMatrixProgramAA::initialize");
2724 program->Initialize(
2725 output_surface_->context_provider(), precision, SamplerType2D);
2727 return program;
2730 const GLRenderer::TileProgram* GLRenderer::GetTileProgram(
2731 TexCoordPrecision precision,
2732 SamplerType sampler) {
2733 DCHECK_GE(precision, 0);
2734 DCHECK_LT(precision, NumTexCoordPrecisions);
2735 DCHECK_GE(sampler, 0);
2736 DCHECK_LT(sampler, NumSamplerTypes);
2737 TileProgram* program = &tile_program_[precision][sampler];
2738 if (!program->initialized()) {
2739 TRACE_EVENT0("cc", "GLRenderer::tileProgram::initialize");
2740 program->Initialize(
2741 output_surface_->context_provider(), precision, sampler);
2743 return program;
2746 const GLRenderer::TileProgramOpaque* GLRenderer::GetTileProgramOpaque(
2747 TexCoordPrecision precision,
2748 SamplerType sampler) {
2749 DCHECK_GE(precision, 0);
2750 DCHECK_LT(precision, NumTexCoordPrecisions);
2751 DCHECK_GE(sampler, 0);
2752 DCHECK_LT(sampler, NumSamplerTypes);
2753 TileProgramOpaque* program = &tile_program_opaque_[precision][sampler];
2754 if (!program->initialized()) {
2755 TRACE_EVENT0("cc", "GLRenderer::tileProgramOpaque::initialize");
2756 program->Initialize(
2757 output_surface_->context_provider(), precision, sampler);
2759 return program;
2762 const GLRenderer::TileProgramAA* GLRenderer::GetTileProgramAA(
2763 TexCoordPrecision precision,
2764 SamplerType sampler) {
2765 DCHECK_GE(precision, 0);
2766 DCHECK_LT(precision, NumTexCoordPrecisions);
2767 DCHECK_GE(sampler, 0);
2768 DCHECK_LT(sampler, NumSamplerTypes);
2769 TileProgramAA* program = &tile_program_aa_[precision][sampler];
2770 if (!program->initialized()) {
2771 TRACE_EVENT0("cc", "GLRenderer::tileProgramAA::initialize");
2772 program->Initialize(
2773 output_surface_->context_provider(), precision, sampler);
2775 return program;
2778 const GLRenderer::TileProgramSwizzle* GLRenderer::GetTileProgramSwizzle(
2779 TexCoordPrecision precision,
2780 SamplerType sampler) {
2781 DCHECK_GE(precision, 0);
2782 DCHECK_LT(precision, NumTexCoordPrecisions);
2783 DCHECK_GE(sampler, 0);
2784 DCHECK_LT(sampler, NumSamplerTypes);
2785 TileProgramSwizzle* program = &tile_program_swizzle_[precision][sampler];
2786 if (!program->initialized()) {
2787 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzle::initialize");
2788 program->Initialize(
2789 output_surface_->context_provider(), precision, sampler);
2791 return program;
2794 const GLRenderer::TileProgramSwizzleOpaque*
2795 GLRenderer::GetTileProgramSwizzleOpaque(TexCoordPrecision precision,
2796 SamplerType sampler) {
2797 DCHECK_GE(precision, 0);
2798 DCHECK_LT(precision, NumTexCoordPrecisions);
2799 DCHECK_GE(sampler, 0);
2800 DCHECK_LT(sampler, NumSamplerTypes);
2801 TileProgramSwizzleOpaque* program =
2802 &tile_program_swizzle_opaque_[precision][sampler];
2803 if (!program->initialized()) {
2804 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleOpaque::initialize");
2805 program->Initialize(
2806 output_surface_->context_provider(), precision, sampler);
2808 return program;
2811 const GLRenderer::TileProgramSwizzleAA* GLRenderer::GetTileProgramSwizzleAA(
2812 TexCoordPrecision precision,
2813 SamplerType sampler) {
2814 DCHECK_GE(precision, 0);
2815 DCHECK_LT(precision, NumTexCoordPrecisions);
2816 DCHECK_GE(sampler, 0);
2817 DCHECK_LT(sampler, NumSamplerTypes);
2818 TileProgramSwizzleAA* program = &tile_program_swizzle_aa_[precision][sampler];
2819 if (!program->initialized()) {
2820 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleAA::initialize");
2821 program->Initialize(
2822 output_surface_->context_provider(), precision, sampler);
2824 return program;
2827 const GLRenderer::TextureProgram* GLRenderer::GetTextureProgram(
2828 TexCoordPrecision precision) {
2829 DCHECK_GE(precision, 0);
2830 DCHECK_LT(precision, NumTexCoordPrecisions);
2831 TextureProgram* program = &texture_program_[precision];
2832 if (!program->initialized()) {
2833 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
2834 program->Initialize(
2835 output_surface_->context_provider(), precision, SamplerType2D);
2837 return program;
2840 const GLRenderer::NonPremultipliedTextureProgram*
2841 GLRenderer::GetNonPremultipliedTextureProgram(TexCoordPrecision precision) {
2842 DCHECK_GE(precision, 0);
2843 DCHECK_LT(precision, NumTexCoordPrecisions);
2844 NonPremultipliedTextureProgram* program =
2845 &nonpremultiplied_texture_program_[precision];
2846 if (!program->initialized()) {
2847 TRACE_EVENT0("cc",
2848 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
2849 program->Initialize(
2850 output_surface_->context_provider(), precision, SamplerType2D);
2852 return program;
2855 const GLRenderer::TextureBackgroundProgram*
2856 GLRenderer::GetTextureBackgroundProgram(TexCoordPrecision precision) {
2857 DCHECK_GE(precision, 0);
2858 DCHECK_LT(precision, NumTexCoordPrecisions);
2859 TextureBackgroundProgram* program = &texture_background_program_[precision];
2860 if (!program->initialized()) {
2861 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
2862 program->Initialize(
2863 output_surface_->context_provider(), precision, SamplerType2D);
2865 return program;
2868 const GLRenderer::NonPremultipliedTextureBackgroundProgram*
2869 GLRenderer::GetNonPremultipliedTextureBackgroundProgram(
2870 TexCoordPrecision precision) {
2871 DCHECK_GE(precision, 0);
2872 DCHECK_LT(precision, NumTexCoordPrecisions);
2873 NonPremultipliedTextureBackgroundProgram* program =
2874 &nonpremultiplied_texture_background_program_[precision];
2875 if (!program->initialized()) {
2876 TRACE_EVENT0("cc",
2877 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
2878 program->Initialize(
2879 output_surface_->context_provider(), precision, SamplerType2D);
2881 return program;
2884 const GLRenderer::TextureProgram* GLRenderer::GetTextureIOSurfaceProgram(
2885 TexCoordPrecision precision) {
2886 DCHECK_GE(precision, 0);
2887 DCHECK_LT(precision, NumTexCoordPrecisions);
2888 TextureProgram* program = &texture_io_surface_program_[precision];
2889 if (!program->initialized()) {
2890 TRACE_EVENT0("cc", "GLRenderer::textureIOSurfaceProgram::initialize");
2891 program->Initialize(
2892 output_surface_->context_provider(), precision, SamplerType2DRect);
2894 return program;
2897 const GLRenderer::VideoYUVProgram* GLRenderer::GetVideoYUVProgram(
2898 TexCoordPrecision precision) {
2899 DCHECK_GE(precision, 0);
2900 DCHECK_LT(precision, NumTexCoordPrecisions);
2901 VideoYUVProgram* program = &video_yuv_program_[precision];
2902 if (!program->initialized()) {
2903 TRACE_EVENT0("cc", "GLRenderer::videoYUVProgram::initialize");
2904 program->Initialize(
2905 output_surface_->context_provider(), precision, SamplerType2D);
2907 return program;
2910 const GLRenderer::VideoYUVAProgram* GLRenderer::GetVideoYUVAProgram(
2911 TexCoordPrecision precision) {
2912 DCHECK_GE(precision, 0);
2913 DCHECK_LT(precision, NumTexCoordPrecisions);
2914 VideoYUVAProgram* program = &video_yuva_program_[precision];
2915 if (!program->initialized()) {
2916 TRACE_EVENT0("cc", "GLRenderer::videoYUVAProgram::initialize");
2917 program->Initialize(
2918 output_surface_->context_provider(), precision, SamplerType2D);
2920 return program;
2923 const GLRenderer::VideoStreamTextureProgram*
2924 GLRenderer::GetVideoStreamTextureProgram(TexCoordPrecision precision) {
2925 if (!Capabilities().using_egl_image)
2926 return NULL;
2927 DCHECK_GE(precision, 0);
2928 DCHECK_LT(precision, NumTexCoordPrecisions);
2929 VideoStreamTextureProgram* program =
2930 &video_stream_texture_program_[precision];
2931 if (!program->initialized()) {
2932 TRACE_EVENT0("cc", "GLRenderer::streamTextureProgram::initialize");
2933 program->Initialize(
2934 output_surface_->context_provider(), precision, SamplerTypeExternalOES);
2936 return program;
2939 void GLRenderer::CleanupSharedObjects() {
2940 shared_geometry_.reset();
2942 for (int i = 0; i < NumTexCoordPrecisions; ++i) {
2943 for (int j = 0; j < NumSamplerTypes; ++j) {
2944 tile_program_[i][j].Cleanup(gl_);
2945 tile_program_opaque_[i][j].Cleanup(gl_);
2946 tile_program_swizzle_[i][j].Cleanup(gl_);
2947 tile_program_swizzle_opaque_[i][j].Cleanup(gl_);
2948 tile_program_aa_[i][j].Cleanup(gl_);
2949 tile_program_swizzle_aa_[i][j].Cleanup(gl_);
2952 render_pass_mask_program_[i].Cleanup(gl_);
2953 render_pass_program_[i].Cleanup(gl_);
2954 render_pass_mask_program_aa_[i].Cleanup(gl_);
2955 render_pass_program_aa_[i].Cleanup(gl_);
2956 render_pass_color_matrix_program_[i].Cleanup(gl_);
2957 render_pass_mask_color_matrix_program_aa_[i].Cleanup(gl_);
2958 render_pass_color_matrix_program_aa_[i].Cleanup(gl_);
2959 render_pass_mask_color_matrix_program_[i].Cleanup(gl_);
2961 texture_program_[i].Cleanup(gl_);
2962 nonpremultiplied_texture_program_[i].Cleanup(gl_);
2963 texture_background_program_[i].Cleanup(gl_);
2964 nonpremultiplied_texture_background_program_[i].Cleanup(gl_);
2965 texture_io_surface_program_[i].Cleanup(gl_);
2967 video_yuv_program_[i].Cleanup(gl_);
2968 video_yuva_program_[i].Cleanup(gl_);
2969 video_stream_texture_program_[i].Cleanup(gl_);
2972 tile_checkerboard_program_.Cleanup(gl_);
2974 debug_border_program_.Cleanup(gl_);
2975 solid_color_program_.Cleanup(gl_);
2976 solid_color_program_aa_.Cleanup(gl_);
2978 if (offscreen_framebuffer_id_)
2979 GLC(gl_, gl_->DeleteFramebuffers(1, &offscreen_framebuffer_id_));
2981 if (on_demand_tile_raster_resource_id_)
2982 resource_provider_->DeleteResource(on_demand_tile_raster_resource_id_);
2984 ReleaseRenderPassTextures();
2987 void GLRenderer::ReinitializeGLState() {
2988 // Bind the common vertex attributes used for drawing all the layers.
2989 shared_geometry_->PrepareForDraw();
2991 GLC(gl_, gl_->Disable(GL_DEPTH_TEST));
2992 GLC(gl_, gl_->Disable(GL_CULL_FACE));
2993 GLC(gl_, gl_->ColorMask(true, true, true, true));
2994 GLC(gl_, gl_->Disable(GL_STENCIL_TEST));
2995 stencil_shadow_ = false;
2996 GLC(gl_, gl_->Enable(GL_BLEND));
2997 blend_shadow_ = true;
2998 GLC(gl_, gl_->BlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA));
2999 GLC(gl_, gl_->ActiveTexture(GL_TEXTURE0));
3000 program_shadow_ = 0;
3002 // Make sure scissoring starts as disabled.
3003 is_scissor_enabled_ = false;
3004 GLC(gl_, gl_->Disable(GL_SCISSOR_TEST));
3005 scissor_rect_needs_reset_ = true;
3008 bool GLRenderer::IsContextLost() {
3009 return output_surface_->context_provider()->IsContextLost();
3012 } // namespace cc