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"
13 #include "base/logging.h"
14 #include "base/trace_event/trace_event.h"
15 #include "cc/base/math_util.h"
16 #include "cc/layers/video_layer_impl.h"
17 #include "cc/output/compositor_frame.h"
18 #include "cc/output/compositor_frame_metadata.h"
19 #include "cc/output/context_provider.h"
20 #include "cc/output/copy_output_request.h"
21 #include "cc/output/geometry_binding.h"
22 #include "cc/output/gl_frame_data.h"
23 #include "cc/output/output_surface.h"
24 #include "cc/output/render_surface_filters.h"
25 #include "cc/quads/picture_draw_quad.h"
26 #include "cc/quads/render_pass.h"
27 #include "cc/quads/stream_video_draw_quad.h"
28 #include "cc/quads/texture_draw_quad.h"
29 #include "cc/resources/layer_quad.h"
30 #include "cc/resources/scoped_gpu_raster.h"
31 #include "cc/resources/scoped_resource.h"
32 #include "cc/resources/texture_mailbox_deleter.h"
33 #include "gpu/GLES2/gl2extchromium.h"
34 #include "gpu/command_buffer/client/context_support.h"
35 #include "gpu/command_buffer/client/gles2_interface.h"
36 #include "gpu/command_buffer/common/gpu_memory_allocation.h"
37 #include "third_party/skia/include/core/SkBitmap.h"
38 #include "third_party/skia/include/core/SkColor.h"
39 #include "third_party/skia/include/core/SkColorFilter.h"
40 #include "third_party/skia/include/core/SkImage.h"
41 #include "third_party/skia/include/core/SkSurface.h"
42 #include "third_party/skia/include/gpu/GrContext.h"
43 #include "third_party/skia/include/gpu/GrTexture.h"
44 #include "third_party/skia/include/gpu/SkGrTexturePixelRef.h"
45 #include "third_party/skia/include/gpu/gl/GrGLInterface.h"
46 #include "ui/gfx/geometry/quad_f.h"
47 #include "ui/gfx/geometry/rect_conversions.h"
49 using gpu::gles2::GLES2Interface
;
54 bool NeedsIOSurfaceReadbackWorkaround() {
55 #if defined(OS_MACOSX)
56 // This isn't strictly required in DumpRenderTree-mode when Mesa is used,
57 // but it doesn't seem to hurt.
64 Float4
UVTransform(const TextureDrawQuad
* quad
) {
65 gfx::PointF uv0
= quad
->uv_top_left
;
66 gfx::PointF uv1
= quad
->uv_bottom_right
;
67 Float4 xform
= {{uv0
.x(), uv0
.y(), uv1
.x() - uv0
.x(), uv1
.y() - uv0
.y()}};
69 xform
.data
[1] = 1.0f
- xform
.data
[1];
70 xform
.data
[3] = -xform
.data
[3];
75 Float4
PremultipliedColor(SkColor color
) {
76 const float factor
= 1.0f
/ 255.0f
;
77 const float alpha
= SkColorGetA(color
) * factor
;
80 {SkColorGetR(color
) * factor
* alpha
, SkColorGetG(color
) * factor
* alpha
,
81 SkColorGetB(color
) * factor
* alpha
, alpha
}};
85 SamplerType
SamplerTypeFromTextureTarget(GLenum target
) {
89 case GL_TEXTURE_RECTANGLE_ARB
:
90 return SamplerType2DRect
;
91 case GL_TEXTURE_EXTERNAL_OES
:
92 return SamplerTypeExternalOES
;
99 BlendMode
BlendModeFromSkXfermode(SkXfermode::Mode mode
) {
101 case SkXfermode::kSrcOver_Mode
:
102 return BlendModeNormal
;
103 case SkXfermode::kScreen_Mode
:
104 return BlendModeScreen
;
105 case SkXfermode::kOverlay_Mode
:
106 return BlendModeOverlay
;
107 case SkXfermode::kDarken_Mode
:
108 return BlendModeDarken
;
109 case SkXfermode::kLighten_Mode
:
110 return BlendModeLighten
;
111 case SkXfermode::kColorDodge_Mode
:
112 return BlendModeColorDodge
;
113 case SkXfermode::kColorBurn_Mode
:
114 return BlendModeColorBurn
;
115 case SkXfermode::kHardLight_Mode
:
116 return BlendModeHardLight
;
117 case SkXfermode::kSoftLight_Mode
:
118 return BlendModeSoftLight
;
119 case SkXfermode::kDifference_Mode
:
120 return BlendModeDifference
;
121 case SkXfermode::kExclusion_Mode
:
122 return BlendModeExclusion
;
123 case SkXfermode::kMultiply_Mode
:
124 return BlendModeMultiply
;
125 case SkXfermode::kHue_Mode
:
127 case SkXfermode::kSaturation_Mode
:
128 return BlendModeSaturation
;
129 case SkXfermode::kColor_Mode
:
130 return BlendModeColor
;
131 case SkXfermode::kLuminosity_Mode
:
132 return BlendModeLuminosity
;
135 return BlendModeNone
;
139 // Smallest unit that impact anti-aliasing output. We use this to
140 // determine when anti-aliasing is unnecessary.
141 const float kAntiAliasingEpsilon
= 1.0f
/ 1024.0f
;
143 // Block or crash if the number of pending sync queries reach this high as
144 // something is seriously wrong on the service side if this happens.
145 const size_t kMaxPendingSyncQueries
= 16;
147 } // anonymous namespace
149 static GLint
GetActiveTextureUnit(GLES2Interface
* gl
) {
150 GLint active_unit
= 0;
151 gl
->GetIntegerv(GL_ACTIVE_TEXTURE
, &active_unit
);
155 class GLRenderer::ScopedUseGrContext
{
157 static scoped_ptr
<ScopedUseGrContext
> Create(GLRenderer
* renderer
,
158 DrawingFrame
* frame
) {
159 return make_scoped_ptr(new ScopedUseGrContext(renderer
, frame
));
162 ~ScopedUseGrContext() {
163 // Pass context control back to GLrenderer.
164 scoped_gpu_raster_
= nullptr;
165 renderer_
->RestoreGLState();
166 renderer_
->RestoreFramebuffer(frame_
);
169 GrContext
* context() const {
170 return renderer_
->output_surface_
->context_provider()->GrContext();
174 ScopedUseGrContext(GLRenderer
* renderer
, DrawingFrame
* frame
)
175 : scoped_gpu_raster_(
176 new ScopedGpuRaster(renderer
->output_surface_
->context_provider())),
179 // scoped_gpu_raster_ passes context control to Skia.
182 scoped_ptr
<ScopedGpuRaster
> scoped_gpu_raster_
;
183 GLRenderer
* renderer_
;
184 DrawingFrame
* frame_
;
186 DISALLOW_COPY_AND_ASSIGN(ScopedUseGrContext
);
189 struct GLRenderer::PendingAsyncReadPixels
{
190 PendingAsyncReadPixels() : buffer(0) {}
192 scoped_ptr
<CopyOutputRequest
> copy_request
;
193 base::CancelableClosure finished_read_pixels_callback
;
197 DISALLOW_COPY_AND_ASSIGN(PendingAsyncReadPixels
);
200 class GLRenderer::SyncQuery
{
202 explicit SyncQuery(gpu::gles2::GLES2Interface
* gl
)
203 : gl_(gl
), query_id_(0u), is_pending_(false), weak_ptr_factory_(this) {
204 gl_
->GenQueriesEXT(1, &query_id_
);
206 virtual ~SyncQuery() { gl_
->DeleteQueriesEXT(1, &query_id_
); }
208 scoped_refptr
<ResourceProvider::Fence
> Begin() {
209 DCHECK(!IsPending());
210 // Invalidate weak pointer held by old fence.
211 weak_ptr_factory_
.InvalidateWeakPtrs();
212 // Note: In case the set of drawing commands issued before End() do not
213 // depend on the query, defer BeginQueryEXT call until Set() is called and
214 // query is required.
215 return make_scoped_refptr
<ResourceProvider::Fence
>(
216 new Fence(weak_ptr_factory_
.GetWeakPtr()));
223 // Note: BeginQueryEXT on GL_COMMANDS_COMPLETED_CHROMIUM is effectively a
224 // noop relative to GL, so it doesn't matter where it happens but we still
225 // make sure to issue this command when Set() is called (prior to issuing
226 // any drawing commands that depend on query), in case some future extension
227 // can take advantage of this.
228 gl_
->BeginQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM
, query_id_
);
236 gl_
->EndQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM
);
243 unsigned result_available
= 1;
244 gl_
->GetQueryObjectuivEXT(
245 query_id_
, GL_QUERY_RESULT_AVAILABLE_EXT
, &result_available
);
246 is_pending_
= !result_available
;
255 gl_
->GetQueryObjectuivEXT(query_id_
, GL_QUERY_RESULT_EXT
, &result
);
260 class Fence
: public ResourceProvider::Fence
{
262 explicit Fence(base::WeakPtr
<GLRenderer::SyncQuery
> query
)
265 // Overridden from ResourceProvider::Fence:
266 void Set() override
{
270 bool HasPassed() override
{ return !query_
|| !query_
->IsPending(); }
271 void Wait() override
{
279 base::WeakPtr
<SyncQuery
> query_
;
281 DISALLOW_COPY_AND_ASSIGN(Fence
);
284 gpu::gles2::GLES2Interface
* gl_
;
287 base::WeakPtrFactory
<SyncQuery
> weak_ptr_factory_
;
289 DISALLOW_COPY_AND_ASSIGN(SyncQuery
);
292 scoped_ptr
<GLRenderer
> GLRenderer::Create(
293 RendererClient
* client
,
294 const RendererSettings
* settings
,
295 OutputSurface
* output_surface
,
296 ResourceProvider
* resource_provider
,
297 TextureMailboxDeleter
* texture_mailbox_deleter
,
298 int highp_threshold_min
) {
299 return make_scoped_ptr(new GLRenderer(client
,
303 texture_mailbox_deleter
,
304 highp_threshold_min
));
307 GLRenderer::GLRenderer(RendererClient
* client
,
308 const RendererSettings
* settings
,
309 OutputSurface
* output_surface
,
310 ResourceProvider
* resource_provider
,
311 TextureMailboxDeleter
* texture_mailbox_deleter
,
312 int highp_threshold_min
)
313 : DirectRenderer(client
, settings
, output_surface
, resource_provider
),
314 offscreen_framebuffer_id_(0),
315 shared_geometry_quad_(QuadVertexRect()),
316 gl_(output_surface
->context_provider()->ContextGL()),
317 context_support_(output_surface
->context_provider()->ContextSupport()),
318 texture_mailbox_deleter_(texture_mailbox_deleter
),
319 is_backbuffer_discarded_(false),
320 is_scissor_enabled_(false),
321 scissor_rect_needs_reset_(true),
322 stencil_shadow_(false),
323 blend_shadow_(false),
324 highp_threshold_min_(highp_threshold_min
),
325 highp_threshold_cache_(0),
326 use_sync_query_(false),
327 on_demand_tile_raster_resource_id_(0) {
329 DCHECK(context_support_
);
331 ContextProvider::Capabilities context_caps
=
332 output_surface_
->context_provider()->ContextCapabilities();
334 capabilities_
.using_partial_swap
=
335 settings_
->partial_swap_enabled
&& context_caps
.gpu
.post_sub_buffer
;
337 DCHECK(!context_caps
.gpu
.iosurface
|| context_caps
.gpu
.texture_rectangle
);
339 capabilities_
.using_egl_image
= context_caps
.gpu
.egl_image_external
;
341 capabilities_
.max_texture_size
= resource_provider_
->max_texture_size();
342 capabilities_
.best_texture_format
= resource_provider_
->best_texture_format();
344 // The updater can access textures while the GLRenderer is using them.
345 capabilities_
.allow_partial_texture_updates
= true;
347 capabilities_
.using_image
= context_caps
.gpu
.image
;
349 capabilities_
.using_discard_framebuffer
=
350 context_caps
.gpu
.discard_framebuffer
;
352 capabilities_
.allow_rasterize_on_demand
= true;
354 use_sync_query_
= context_caps
.gpu
.sync_query
;
355 use_blend_equation_advanced_
= context_caps
.gpu
.blend_equation_advanced
;
356 use_blend_equation_advanced_coherent_
=
357 context_caps
.gpu
.blend_equation_advanced_coherent
;
359 InitializeSharedObjects();
362 GLRenderer::~GLRenderer() {
363 while (!pending_async_read_pixels_
.empty()) {
364 PendingAsyncReadPixels
* pending_read
= pending_async_read_pixels_
.back();
365 pending_read
->finished_read_pixels_callback
.Cancel();
366 pending_async_read_pixels_
.pop_back();
369 in_use_overlay_resources_
.clear();
371 CleanupSharedObjects();
374 const RendererCapabilitiesImpl
& GLRenderer::Capabilities() const {
375 return capabilities_
;
378 void GLRenderer::DebugGLCall(GLES2Interface
* gl
,
382 GLuint error
= gl
->GetError();
383 if (error
!= GL_NO_ERROR
)
384 LOG(ERROR
) << "GL command failed: File: " << file
<< "\n\tLine " << line
385 << "\n\tcommand: " << command
<< ", error "
386 << static_cast<int>(error
) << "\n";
389 void GLRenderer::DidChangeVisibility() {
390 EnforceMemoryPolicy();
392 context_support_
->SetSurfaceVisible(visible());
395 void GLRenderer::ReleaseRenderPassTextures() { render_pass_textures_
.clear(); }
397 void GLRenderer::DiscardPixels(bool has_external_stencil_test
,
398 bool draw_rect_covers_full_surface
) {
399 if (has_external_stencil_test
|| !draw_rect_covers_full_surface
||
400 !capabilities_
.using_discard_framebuffer
)
402 bool using_default_framebuffer
=
403 !current_framebuffer_lock_
&&
404 output_surface_
->capabilities().uses_default_gl_framebuffer
;
405 GLenum attachments
[] = {static_cast<GLenum
>(
406 using_default_framebuffer
? GL_COLOR_EXT
: GL_COLOR_ATTACHMENT0_EXT
)};
407 gl_
->DiscardFramebufferEXT(
408 GL_FRAMEBUFFER
, arraysize(attachments
), attachments
);
411 void GLRenderer::ClearFramebuffer(DrawingFrame
* frame
,
412 bool has_external_stencil_test
) {
413 // It's unsafe to clear when we have a stencil test because glClear ignores
415 if (has_external_stencil_test
) {
416 DCHECK(!frame
->current_render_pass
->has_transparent_background
);
420 // On DEBUG builds, opaque render passes are cleared to blue to easily see
421 // regions that were not drawn on the screen.
422 if (frame
->current_render_pass
->has_transparent_background
)
423 GLC(gl_
, gl_
->ClearColor(0, 0, 0, 0));
425 GLC(gl_
, gl_
->ClearColor(0, 0, 1, 1));
427 bool always_clear
= false;
431 if (always_clear
|| frame
->current_render_pass
->has_transparent_background
) {
432 GLbitfield clear_bits
= GL_COLOR_BUFFER_BIT
;
434 clear_bits
|= GL_STENCIL_BUFFER_BIT
;
435 gl_
->Clear(clear_bits
);
439 static ResourceProvider::ResourceId
WaitOnResourceSyncPoints(
440 ResourceProvider
* resource_provider
,
441 ResourceProvider::ResourceId resource_id
) {
442 resource_provider
->WaitSyncPointIfNeeded(resource_id
);
446 void GLRenderer::BeginDrawingFrame(DrawingFrame
* frame
) {
447 TRACE_EVENT0("cc", "GLRenderer::BeginDrawingFrame");
449 scoped_refptr
<ResourceProvider::Fence
> read_lock_fence
;
450 if (use_sync_query_
) {
451 // Block until oldest sync query has passed if the number of pending queries
452 // ever reach kMaxPendingSyncQueries.
453 if (pending_sync_queries_
.size() >= kMaxPendingSyncQueries
) {
454 LOG(ERROR
) << "Reached limit of pending sync queries.";
456 pending_sync_queries_
.front()->Wait();
457 DCHECK(!pending_sync_queries_
.front()->IsPending());
460 while (!pending_sync_queries_
.empty()) {
461 if (pending_sync_queries_
.front()->IsPending())
464 available_sync_queries_
.push_back(pending_sync_queries_
.take_front());
467 current_sync_query_
= available_sync_queries_
.empty()
468 ? make_scoped_ptr(new SyncQuery(gl_
))
469 : available_sync_queries_
.take_front();
471 read_lock_fence
= current_sync_query_
->Begin();
474 make_scoped_refptr(new ResourceProvider::SynchronousFence(gl_
));
476 resource_provider_
->SetReadLockFence(read_lock_fence
.get());
478 // Insert WaitSyncPointCHROMIUM on quad resources prior to drawing the frame,
479 // so that drawing can proceed without GL context switching interruptions.
480 DrawQuad::ResourceIteratorCallback wait_on_resource_syncpoints_callback
=
481 base::Bind(&WaitOnResourceSyncPoints
, resource_provider_
);
483 for (const auto& pass
: *frame
->render_passes_in_draw_order
) {
484 for (const auto& quad
: pass
->quad_list
)
485 quad
->IterateResources(wait_on_resource_syncpoints_callback
);
488 // TODO(enne): Do we need to reinitialize all of this state per frame?
489 ReinitializeGLState();
492 void GLRenderer::DoNoOp() {
493 GLC(gl_
, gl_
->BindFramebuffer(GL_FRAMEBUFFER
, 0));
494 GLC(gl_
, gl_
->Flush());
497 void GLRenderer::DoDrawQuad(DrawingFrame
* frame
, const DrawQuad
* quad
) {
498 DCHECK(quad
->rect
.Contains(quad
->visible_rect
));
499 if (quad
->material
!= DrawQuad::TEXTURE_CONTENT
) {
500 FlushTextureQuadCache();
503 switch (quad
->material
) {
504 case DrawQuad::INVALID
:
507 case DrawQuad::CHECKERBOARD
:
508 DrawCheckerboardQuad(frame
, CheckerboardDrawQuad::MaterialCast(quad
));
510 case DrawQuad::DEBUG_BORDER
:
511 DrawDebugBorderQuad(frame
, DebugBorderDrawQuad::MaterialCast(quad
));
513 case DrawQuad::IO_SURFACE_CONTENT
:
514 DrawIOSurfaceQuad(frame
, IOSurfaceDrawQuad::MaterialCast(quad
));
516 case DrawQuad::PICTURE_CONTENT
:
517 DrawPictureQuad(frame
, PictureDrawQuad::MaterialCast(quad
));
519 case DrawQuad::RENDER_PASS
:
520 DrawRenderPassQuad(frame
, RenderPassDrawQuad::MaterialCast(quad
));
522 case DrawQuad::SOLID_COLOR
:
523 DrawSolidColorQuad(frame
, SolidColorDrawQuad::MaterialCast(quad
));
525 case DrawQuad::STREAM_VIDEO_CONTENT
:
526 DrawStreamVideoQuad(frame
, StreamVideoDrawQuad::MaterialCast(quad
));
528 case DrawQuad::SURFACE_CONTENT
:
529 // Surface content should be fully resolved to other quad types before
530 // reaching a direct renderer.
533 case DrawQuad::TEXTURE_CONTENT
:
534 EnqueueTextureQuad(frame
, TextureDrawQuad::MaterialCast(quad
));
536 case DrawQuad::TILED_CONTENT
:
537 DrawTileQuad(frame
, TileDrawQuad::MaterialCast(quad
));
539 case DrawQuad::YUV_VIDEO_CONTENT
:
540 DrawYUVVideoQuad(frame
, YUVVideoDrawQuad::MaterialCast(quad
));
545 void GLRenderer::DrawCheckerboardQuad(const DrawingFrame
* frame
,
546 const CheckerboardDrawQuad
* quad
) {
547 SetBlendEnabled(quad
->ShouldDrawWithBlending());
549 const TileCheckerboardProgram
* program
= GetTileCheckerboardProgram();
550 DCHECK(program
&& (program
->initialized() || IsContextLost()));
551 SetUseProgram(program
->program());
553 SkColor color
= quad
->color
;
555 gl_
->Uniform4f(program
->fragment_shader().color_location(),
556 SkColorGetR(color
) * (1.0f
/ 255.0f
),
557 SkColorGetG(color
) * (1.0f
/ 255.0f
),
558 SkColorGetB(color
) * (1.0f
/ 255.0f
),
561 const int checkerboard_width
= 16;
562 float frequency
= 1.0f
/ checkerboard_width
;
564 gfx::Rect tile_rect
= quad
->rect
;
565 float tex_offset_x
= tile_rect
.x() % checkerboard_width
;
566 float tex_offset_y
= tile_rect
.y() % checkerboard_width
;
567 float tex_scale_x
= tile_rect
.width();
568 float tex_scale_y
= tile_rect
.height();
570 gl_
->Uniform4f(program
->fragment_shader().tex_transform_location(),
577 gl_
->Uniform1f(program
->fragment_shader().frequency_location(),
580 SetShaderOpacity(quad
->opacity(),
581 program
->fragment_shader().alpha_location());
582 DrawQuadGeometry(frame
,
583 quad
->quadTransform(),
585 program
->vertex_shader().matrix_location());
588 void GLRenderer::DrawDebugBorderQuad(const DrawingFrame
* frame
,
589 const DebugBorderDrawQuad
* quad
) {
590 SetBlendEnabled(quad
->ShouldDrawWithBlending());
592 static float gl_matrix
[16];
593 const DebugBorderProgram
* program
= GetDebugBorderProgram();
594 DCHECK(program
&& (program
->initialized() || IsContextLost()));
595 SetUseProgram(program
->program());
597 // Use the full quad_rect for debug quads to not move the edges based on
599 gfx::Rect layer_rect
= quad
->rect
;
600 gfx::Transform render_matrix
;
601 QuadRectTransform(&render_matrix
, quad
->quadTransform(), layer_rect
);
602 GLRenderer::ToGLMatrix(&gl_matrix
[0],
603 frame
->projection_matrix
* render_matrix
);
605 gl_
->UniformMatrix4fv(
606 program
->vertex_shader().matrix_location(), 1, false, &gl_matrix
[0]));
608 SkColor color
= quad
->color
;
609 float alpha
= SkColorGetA(color
) * (1.0f
/ 255.0f
);
612 gl_
->Uniform4f(program
->fragment_shader().color_location(),
613 (SkColorGetR(color
) * (1.0f
/ 255.0f
)) * alpha
,
614 (SkColorGetG(color
) * (1.0f
/ 255.0f
)) * alpha
,
615 (SkColorGetB(color
) * (1.0f
/ 255.0f
)) * alpha
,
618 GLC(gl_
, gl_
->LineWidth(quad
->width
));
620 // The indices for the line are stored in the same array as the triangle
622 GLC(gl_
, gl_
->DrawElements(GL_LINE_LOOP
, 4, GL_UNSIGNED_SHORT
, 0));
625 static skia::RefPtr
<SkImage
> ApplyImageFilter(
626 scoped_ptr
<GLRenderer::ScopedUseGrContext
> use_gr_context
,
627 ResourceProvider
* resource_provider
,
628 const gfx::Point
& origin
,
629 const gfx::Vector2dF
& scale
,
630 SkImageFilter
* filter
,
631 ScopedResource
* source_texture_resource
) {
633 return skia::RefPtr
<SkImage
>();
636 return skia::RefPtr
<SkImage
>();
638 ResourceProvider::ScopedReadLockGL
lock(resource_provider
,
639 source_texture_resource
->id());
641 // Wrap the source texture in a Ganesh platform texture.
642 GrBackendTextureDesc backend_texture_description
;
643 backend_texture_description
.fWidth
= source_texture_resource
->size().width();
644 backend_texture_description
.fHeight
=
645 source_texture_resource
->size().height();
646 backend_texture_description
.fConfig
= kSkia8888_GrPixelConfig
;
647 backend_texture_description
.fTextureHandle
= lock
.texture_id();
648 backend_texture_description
.fOrigin
= kBottomLeft_GrSurfaceOrigin
;
649 skia::RefPtr
<GrTexture
> texture
=
650 skia::AdoptRef(use_gr_context
->context()->wrapBackendTexture(
651 backend_texture_description
));
653 TRACE_EVENT_INSTANT0("cc",
654 "ApplyImageFilter wrap background texture failed",
655 TRACE_EVENT_SCOPE_THREAD
);
656 return skia::RefPtr
<SkImage
>();
660 SkImageInfo::MakeN32Premul(source_texture_resource
->size().width(),
661 source_texture_resource
->size().height());
662 // Place the platform texture inside an SkBitmap.
664 source
.setInfo(info
);
665 skia::RefPtr
<SkGrPixelRef
> pixel_ref
=
666 skia::AdoptRef(new SkGrPixelRef(info
, texture
.get()));
667 source
.setPixelRef(pixel_ref
.get());
669 // Create a scratch texture for backing store.
671 desc
.fFlags
= kRenderTarget_GrTextureFlagBit
| kNoStencil_GrTextureFlagBit
;
673 desc
.fWidth
= source
.width();
674 desc
.fHeight
= source
.height();
675 desc
.fConfig
= kSkia8888_GrPixelConfig
;
676 desc
.fOrigin
= kBottomLeft_GrSurfaceOrigin
;
677 skia::RefPtr
<GrTexture
> backing_store
=
678 skia::AdoptRef(use_gr_context
->context()->refScratchTexture(
679 desc
, GrContext::kExact_ScratchTexMatch
));
680 if (!backing_store
) {
681 TRACE_EVENT_INSTANT0("cc",
682 "ApplyImageFilter scratch texture allocation failed",
683 TRACE_EVENT_SCOPE_THREAD
);
684 return skia::RefPtr
<SkImage
>();
687 // Create surface to draw into.
688 skia::RefPtr
<SkSurface
> surface
= skia::AdoptRef(
689 SkSurface::NewRenderTargetDirect(backing_store
->asRenderTarget()));
690 skia::RefPtr
<SkCanvas
> canvas
= skia::SharePtr(surface
->getCanvas());
692 // Draw the source bitmap through the filter to the canvas.
694 paint
.setImageFilter(filter
);
695 canvas
->clear(SK_ColorTRANSPARENT
);
697 canvas
->translate(SkIntToScalar(-origin
.x()), SkIntToScalar(-origin
.y()));
698 canvas
->scale(scale
.x(), scale
.y());
699 canvas
->drawSprite(source
, 0, 0, &paint
);
701 skia::RefPtr
<SkImage
> image
= skia::AdoptRef(surface
->newImageSnapshot());
702 if (!image
|| !image
->getTexture()) {
703 return skia::RefPtr
<SkImage
>();
706 // Flush the GrContext to ensure all buffered GL calls are drawn to the
707 // backing store before we access and return it, and have cc begin using the
714 bool GLRenderer::CanApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode
) {
715 return use_blend_equation_advanced_
||
716 blend_mode
== SkXfermode::kScreen_Mode
||
717 blend_mode
== SkXfermode::kSrcOver_Mode
;
720 void GLRenderer::ApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode
) {
721 DCHECK(CanApplyBlendModeUsingBlendFunc(blend_mode
));
723 // Any modes set here must be reset in RestoreBlendFuncToDefault
724 if (use_blend_equation_advanced_
) {
725 GLenum equation
= GL_FUNC_ADD
;
727 switch (blend_mode
) {
728 case SkXfermode::kScreen_Mode
:
729 equation
= GL_SCREEN_KHR
;
731 case SkXfermode::kOverlay_Mode
:
732 equation
= GL_OVERLAY_KHR
;
734 case SkXfermode::kDarken_Mode
:
735 equation
= GL_DARKEN_KHR
;
737 case SkXfermode::kLighten_Mode
:
738 equation
= GL_LIGHTEN_KHR
;
740 case SkXfermode::kColorDodge_Mode
:
741 equation
= GL_COLORDODGE_KHR
;
743 case SkXfermode::kColorBurn_Mode
:
744 equation
= GL_COLORBURN_KHR
;
746 case SkXfermode::kHardLight_Mode
:
747 equation
= GL_HARDLIGHT_KHR
;
749 case SkXfermode::kSoftLight_Mode
:
750 equation
= GL_SOFTLIGHT_KHR
;
752 case SkXfermode::kDifference_Mode
:
753 equation
= GL_DIFFERENCE_KHR
;
755 case SkXfermode::kExclusion_Mode
:
756 equation
= GL_EXCLUSION_KHR
;
758 case SkXfermode::kMultiply_Mode
:
759 equation
= GL_MULTIPLY_KHR
;
761 case SkXfermode::kHue_Mode
:
762 equation
= GL_HSL_HUE_KHR
;
764 case SkXfermode::kSaturation_Mode
:
765 equation
= GL_HSL_SATURATION_KHR
;
767 case SkXfermode::kColor_Mode
:
768 equation
= GL_HSL_COLOR_KHR
;
770 case SkXfermode::kLuminosity_Mode
:
771 equation
= GL_HSL_LUMINOSITY_KHR
;
777 GLC(gl_
, gl_
->BlendEquation(equation
));
779 if (blend_mode
== SkXfermode::kScreen_Mode
) {
780 GLC(gl_
, gl_
->BlendFunc(GL_ONE_MINUS_DST_COLOR
, GL_ONE
));
785 void GLRenderer::RestoreBlendFuncToDefault(SkXfermode::Mode blend_mode
) {
786 if (blend_mode
== SkXfermode::kSrcOver_Mode
)
789 if (use_blend_equation_advanced_
) {
790 GLC(gl_
, gl_
->BlendEquation(GL_FUNC_ADD
));
792 GLC(gl_
, gl_
->BlendFunc(GL_ONE
, GL_ONE_MINUS_SRC_ALPHA
));
796 bool GLRenderer::ShouldApplyBackgroundFilters(DrawingFrame
* frame
,
797 const RenderPassDrawQuad
* quad
) {
798 if (quad
->background_filters
.IsEmpty())
801 // TODO(danakj): We only allow background filters on an opaque render surface
802 // because other surfaces may contain translucent pixels, and the contents
803 // behind those translucent pixels wouldn't have the filter applied.
804 if (frame
->current_render_pass
->has_transparent_background
)
807 // TODO(ajuma): Add support for reference filters once
808 // FilterOperations::GetOutsets supports reference filters.
809 if (quad
->background_filters
.HasReferenceFilter())
814 gfx::Rect
GLRenderer::GetBackdropBoundingBoxForRenderPassQuad(
816 const RenderPassDrawQuad
* quad
,
817 const gfx::Transform
& contents_device_transform
,
819 gfx::Rect backdrop_rect
= gfx::ToEnclosingRect(MathUtil::MapClippedRect(
820 contents_device_transform
, SharedGeometryQuad().BoundingBox()));
822 if (ShouldApplyBackgroundFilters(frame
, quad
)) {
823 int top
, right
, bottom
, left
;
824 quad
->background_filters
.GetOutsets(&top
, &right
, &bottom
, &left
);
825 backdrop_rect
.Inset(-left
, -top
, -right
, -bottom
);
828 if (!backdrop_rect
.IsEmpty() && use_aa
) {
829 const int kOutsetForAntialiasing
= 1;
830 backdrop_rect
.Inset(-kOutsetForAntialiasing
, -kOutsetForAntialiasing
);
833 backdrop_rect
.Intersect(MoveFromDrawToWindowSpace(
834 frame
, frame
->current_render_pass
->output_rect
));
835 return backdrop_rect
;
838 scoped_ptr
<ScopedResource
> GLRenderer::GetBackdropTexture(
839 const gfx::Rect
& bounding_rect
) {
840 scoped_ptr
<ScopedResource
> device_background_texture
=
841 ScopedResource::Create(resource_provider_
);
842 // CopyTexImage2D fails when called on a texture having immutable storage.
843 device_background_texture
->Allocate(
844 bounding_rect
.size(), ResourceProvider::TextureHintDefault
, RGBA_8888
);
846 ResourceProvider::ScopedWriteLockGL
lock(resource_provider_
,
847 device_background_texture
->id());
848 GetFramebufferTexture(
849 lock
.texture_id(), device_background_texture
->format(), bounding_rect
);
851 return device_background_texture
.Pass();
854 skia::RefPtr
<SkImage
> GLRenderer::ApplyBackgroundFilters(
856 const RenderPassDrawQuad
* quad
,
857 ScopedResource
* background_texture
) {
858 DCHECK(ShouldApplyBackgroundFilters(frame
, quad
));
859 skia::RefPtr
<SkImageFilter
> filter
= RenderSurfaceFilters::BuildImageFilter(
860 quad
->background_filters
, background_texture
->size());
862 skia::RefPtr
<SkImage
> background_with_filters
=
863 ApplyImageFilter(ScopedUseGrContext::Create(this, frame
),
869 return background_with_filters
;
872 void GLRenderer::DrawRenderPassQuad(DrawingFrame
* frame
,
873 const RenderPassDrawQuad
* quad
) {
874 ScopedResource
* contents_texture
=
875 render_pass_textures_
.get(quad
->render_pass_id
);
876 if (!contents_texture
|| !contents_texture
->id())
879 gfx::Transform quad_rect_matrix
;
880 QuadRectTransform(&quad_rect_matrix
, quad
->quadTransform(), quad
->rect
);
881 gfx::Transform contents_device_transform
=
882 frame
->window_matrix
* frame
->projection_matrix
* quad_rect_matrix
;
883 contents_device_transform
.FlattenTo2d();
885 // Can only draw surface if device matrix is invertible.
886 if (!contents_device_transform
.IsInvertible())
889 gfx::QuadF surface_quad
= SharedGeometryQuad();
891 bool use_aa
= settings_
->allow_antialiasing
&&
892 ShouldAntialiasQuad(contents_device_transform
, quad
,
893 settings_
->force_antialiasing
);
896 SetupQuadForAntialiasing(contents_device_transform
, quad
,
897 &surface_quad
, edge
);
899 SkXfermode::Mode blend_mode
= quad
->shared_quad_state
->blend_mode
;
900 bool use_shaders_for_blending
=
901 !CanApplyBlendModeUsingBlendFunc(blend_mode
) ||
902 ShouldApplyBackgroundFilters(frame
, quad
) ||
903 settings_
->force_blending_with_shaders
;
905 scoped_ptr
<ScopedResource
> background_texture
;
906 skia::RefPtr
<SkImage
> background_image
;
907 gfx::Rect background_rect
;
908 if (use_shaders_for_blending
) {
909 // Compute a bounding box around the pixels that will be visible through
911 background_rect
= GetBackdropBoundingBoxForRenderPassQuad(
912 frame
, quad
, contents_device_transform
, use_aa
);
914 if (!background_rect
.IsEmpty()) {
915 // The pixels from the filtered background should completely replace the
916 // current pixel values.
918 SetBlendEnabled(false);
920 // Read the pixels in the bounding box into a buffer R.
921 // This function allocates a texture, which should contribute to the
922 // amount of memory used by render surfaces:
923 // LayerTreeHost::CalculateMemoryForRenderSurfaces.
924 background_texture
= GetBackdropTexture(background_rect
);
926 if (ShouldApplyBackgroundFilters(frame
, quad
) && background_texture
) {
927 // Apply the background filters to R, so that it is applied in the
928 // pixels' coordinate space.
930 ApplyBackgroundFilters(frame
, quad
, background_texture
.get());
934 if (!background_texture
) {
935 // Something went wrong with reading the backdrop.
936 DCHECK(!background_image
);
937 use_shaders_for_blending
= false;
938 } else if (background_image
) {
939 background_texture
.reset();
940 } else if (CanApplyBlendModeUsingBlendFunc(blend_mode
) &&
941 ShouldApplyBackgroundFilters(frame
, quad
)) {
942 // Something went wrong with applying background filters to the backdrop.
943 use_shaders_for_blending
= false;
944 background_texture
.reset();
949 !use_shaders_for_blending
&&
950 (quad
->ShouldDrawWithBlending() || !IsDefaultBlendMode(blend_mode
)));
952 // TODO(senorblanco): Cache this value so that we don't have to do it for both
953 // the surface and its replica. Apply filters to the contents texture.
954 skia::RefPtr
<SkImage
> filter_image
;
955 SkScalar color_matrix
[20];
956 bool use_color_matrix
= false;
957 if (!quad
->filters
.IsEmpty()) {
958 skia::RefPtr
<SkImageFilter
> filter
= RenderSurfaceFilters::BuildImageFilter(
959 quad
->filters
, contents_texture
->size());
961 skia::RefPtr
<SkColorFilter
> cf
;
964 SkColorFilter
* colorfilter_rawptr
= NULL
;
965 filter
->asColorFilter(&colorfilter_rawptr
);
966 cf
= skia::AdoptRef(colorfilter_rawptr
);
969 if (cf
&& cf
->asColorMatrix(color_matrix
) && !filter
->getInput(0)) {
970 // We have a single color matrix as a filter; apply it locally
971 // in the compositor.
972 use_color_matrix
= true;
974 filter_image
= ApplyImageFilter(ScopedUseGrContext::Create(this, frame
),
984 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> mask_resource_lock
;
985 unsigned mask_texture_id
= 0;
986 SamplerType mask_sampler
= SamplerTypeNA
;
987 if (quad
->mask_resource_id
) {
988 mask_resource_lock
.reset(new ResourceProvider::ScopedSamplerGL(
989 resource_provider_
, quad
->mask_resource_id
, GL_TEXTURE1
, GL_LINEAR
));
990 mask_texture_id
= mask_resource_lock
->texture_id();
991 mask_sampler
= SamplerTypeFromTextureTarget(mask_resource_lock
->target());
994 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> contents_resource_lock
;
996 GrTexture
* texture
= filter_image
->getTexture();
997 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
998 gl_
->BindTexture(GL_TEXTURE_2D
, texture
->getTextureHandle());
1000 contents_resource_lock
=
1001 make_scoped_ptr(new ResourceProvider::ScopedSamplerGL(
1002 resource_provider_
, contents_texture
->id(), GL_LINEAR
));
1003 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
),
1004 contents_resource_lock
->target());
1007 if (!use_shaders_for_blending
) {
1008 if (!use_blend_equation_advanced_coherent_
&& use_blend_equation_advanced_
)
1009 GLC(gl_
, gl_
->BlendBarrierKHR());
1011 ApplyBlendModeUsingBlendFunc(blend_mode
);
1014 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1016 &highp_threshold_cache_
,
1017 highp_threshold_min_
,
1018 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
1020 int shader_quad_location
= -1;
1021 int shader_edge_location
= -1;
1022 int shader_viewport_location
= -1;
1023 int shader_mask_sampler_location
= -1;
1024 int shader_mask_tex_coord_scale_location
= -1;
1025 int shader_mask_tex_coord_offset_location
= -1;
1026 int shader_matrix_location
= -1;
1027 int shader_alpha_location
= -1;
1028 int shader_color_matrix_location
= -1;
1029 int shader_color_offset_location
= -1;
1030 int shader_tex_transform_location
= -1;
1031 int shader_backdrop_location
= -1;
1032 int shader_backdrop_rect_location
= -1;
1034 DCHECK_EQ(background_texture
|| background_image
, use_shaders_for_blending
);
1035 BlendMode shader_blend_mode
= use_shaders_for_blending
1036 ? BlendModeFromSkXfermode(blend_mode
)
1039 if (use_aa
&& mask_texture_id
&& !use_color_matrix
) {
1040 const RenderPassMaskProgramAA
* program
= GetRenderPassMaskProgramAA(
1041 tex_coord_precision
, mask_sampler
, shader_blend_mode
);
1042 SetUseProgram(program
->program());
1043 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1045 shader_quad_location
= program
->vertex_shader().quad_location();
1046 shader_edge_location
= program
->vertex_shader().edge_location();
1047 shader_viewport_location
= program
->vertex_shader().viewport_location();
1048 shader_mask_sampler_location
=
1049 program
->fragment_shader().mask_sampler_location();
1050 shader_mask_tex_coord_scale_location
=
1051 program
->fragment_shader().mask_tex_coord_scale_location();
1052 shader_mask_tex_coord_offset_location
=
1053 program
->fragment_shader().mask_tex_coord_offset_location();
1054 shader_matrix_location
= program
->vertex_shader().matrix_location();
1055 shader_alpha_location
= program
->fragment_shader().alpha_location();
1056 shader_tex_transform_location
=
1057 program
->vertex_shader().tex_transform_location();
1058 shader_backdrop_location
= program
->fragment_shader().backdrop_location();
1059 shader_backdrop_rect_location
=
1060 program
->fragment_shader().backdrop_rect_location();
1061 } else if (!use_aa
&& mask_texture_id
&& !use_color_matrix
) {
1062 const RenderPassMaskProgram
* program
= GetRenderPassMaskProgram(
1063 tex_coord_precision
, mask_sampler
, shader_blend_mode
);
1064 SetUseProgram(program
->program());
1065 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1067 shader_mask_sampler_location
=
1068 program
->fragment_shader().mask_sampler_location();
1069 shader_mask_tex_coord_scale_location
=
1070 program
->fragment_shader().mask_tex_coord_scale_location();
1071 shader_mask_tex_coord_offset_location
=
1072 program
->fragment_shader().mask_tex_coord_offset_location();
1073 shader_matrix_location
= program
->vertex_shader().matrix_location();
1074 shader_alpha_location
= program
->fragment_shader().alpha_location();
1075 shader_tex_transform_location
=
1076 program
->vertex_shader().tex_transform_location();
1077 shader_backdrop_location
= program
->fragment_shader().backdrop_location();
1078 shader_backdrop_rect_location
=
1079 program
->fragment_shader().backdrop_rect_location();
1080 } else if (use_aa
&& !mask_texture_id
&& !use_color_matrix
) {
1081 const RenderPassProgramAA
* program
=
1082 GetRenderPassProgramAA(tex_coord_precision
, shader_blend_mode
);
1083 SetUseProgram(program
->program());
1084 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1086 shader_quad_location
= program
->vertex_shader().quad_location();
1087 shader_edge_location
= program
->vertex_shader().edge_location();
1088 shader_viewport_location
= program
->vertex_shader().viewport_location();
1089 shader_matrix_location
= program
->vertex_shader().matrix_location();
1090 shader_alpha_location
= program
->fragment_shader().alpha_location();
1091 shader_tex_transform_location
=
1092 program
->vertex_shader().tex_transform_location();
1093 shader_backdrop_location
= program
->fragment_shader().backdrop_location();
1094 shader_backdrop_rect_location
=
1095 program
->fragment_shader().backdrop_rect_location();
1096 } else if (use_aa
&& mask_texture_id
&& use_color_matrix
) {
1097 const RenderPassMaskColorMatrixProgramAA
* program
=
1098 GetRenderPassMaskColorMatrixProgramAA(
1099 tex_coord_precision
, mask_sampler
, shader_blend_mode
);
1100 SetUseProgram(program
->program());
1101 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1103 shader_matrix_location
= program
->vertex_shader().matrix_location();
1104 shader_quad_location
= program
->vertex_shader().quad_location();
1105 shader_tex_transform_location
=
1106 program
->vertex_shader().tex_transform_location();
1107 shader_edge_location
= program
->vertex_shader().edge_location();
1108 shader_viewport_location
= program
->vertex_shader().viewport_location();
1109 shader_alpha_location
= program
->fragment_shader().alpha_location();
1110 shader_mask_sampler_location
=
1111 program
->fragment_shader().mask_sampler_location();
1112 shader_mask_tex_coord_scale_location
=
1113 program
->fragment_shader().mask_tex_coord_scale_location();
1114 shader_mask_tex_coord_offset_location
=
1115 program
->fragment_shader().mask_tex_coord_offset_location();
1116 shader_color_matrix_location
=
1117 program
->fragment_shader().color_matrix_location();
1118 shader_color_offset_location
=
1119 program
->fragment_shader().color_offset_location();
1120 shader_backdrop_location
= program
->fragment_shader().backdrop_location();
1121 shader_backdrop_rect_location
=
1122 program
->fragment_shader().backdrop_rect_location();
1123 } else if (use_aa
&& !mask_texture_id
&& use_color_matrix
) {
1124 const RenderPassColorMatrixProgramAA
* program
=
1125 GetRenderPassColorMatrixProgramAA(tex_coord_precision
,
1127 SetUseProgram(program
->program());
1128 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1130 shader_matrix_location
= program
->vertex_shader().matrix_location();
1131 shader_quad_location
= program
->vertex_shader().quad_location();
1132 shader_tex_transform_location
=
1133 program
->vertex_shader().tex_transform_location();
1134 shader_edge_location
= program
->vertex_shader().edge_location();
1135 shader_viewport_location
= program
->vertex_shader().viewport_location();
1136 shader_alpha_location
= program
->fragment_shader().alpha_location();
1137 shader_color_matrix_location
=
1138 program
->fragment_shader().color_matrix_location();
1139 shader_color_offset_location
=
1140 program
->fragment_shader().color_offset_location();
1141 shader_backdrop_location
= program
->fragment_shader().backdrop_location();
1142 shader_backdrop_rect_location
=
1143 program
->fragment_shader().backdrop_rect_location();
1144 } else if (!use_aa
&& mask_texture_id
&& use_color_matrix
) {
1145 const RenderPassMaskColorMatrixProgram
* program
=
1146 GetRenderPassMaskColorMatrixProgram(
1147 tex_coord_precision
, mask_sampler
, shader_blend_mode
);
1148 SetUseProgram(program
->program());
1149 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1151 shader_matrix_location
= program
->vertex_shader().matrix_location();
1152 shader_tex_transform_location
=
1153 program
->vertex_shader().tex_transform_location();
1154 shader_mask_sampler_location
=
1155 program
->fragment_shader().mask_sampler_location();
1156 shader_mask_tex_coord_scale_location
=
1157 program
->fragment_shader().mask_tex_coord_scale_location();
1158 shader_mask_tex_coord_offset_location
=
1159 program
->fragment_shader().mask_tex_coord_offset_location();
1160 shader_alpha_location
= program
->fragment_shader().alpha_location();
1161 shader_color_matrix_location
=
1162 program
->fragment_shader().color_matrix_location();
1163 shader_color_offset_location
=
1164 program
->fragment_shader().color_offset_location();
1165 shader_backdrop_location
= program
->fragment_shader().backdrop_location();
1166 shader_backdrop_rect_location
=
1167 program
->fragment_shader().backdrop_rect_location();
1168 } else if (!use_aa
&& !mask_texture_id
&& use_color_matrix
) {
1169 const RenderPassColorMatrixProgram
* program
=
1170 GetRenderPassColorMatrixProgram(tex_coord_precision
, shader_blend_mode
);
1171 SetUseProgram(program
->program());
1172 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1174 shader_matrix_location
= program
->vertex_shader().matrix_location();
1175 shader_tex_transform_location
=
1176 program
->vertex_shader().tex_transform_location();
1177 shader_alpha_location
= program
->fragment_shader().alpha_location();
1178 shader_color_matrix_location
=
1179 program
->fragment_shader().color_matrix_location();
1180 shader_color_offset_location
=
1181 program
->fragment_shader().color_offset_location();
1182 shader_backdrop_location
= program
->fragment_shader().backdrop_location();
1183 shader_backdrop_rect_location
=
1184 program
->fragment_shader().backdrop_rect_location();
1186 const RenderPassProgram
* program
=
1187 GetRenderPassProgram(tex_coord_precision
, shader_blend_mode
);
1188 SetUseProgram(program
->program());
1189 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1191 shader_matrix_location
= program
->vertex_shader().matrix_location();
1192 shader_alpha_location
= program
->fragment_shader().alpha_location();
1193 shader_tex_transform_location
=
1194 program
->vertex_shader().tex_transform_location();
1195 shader_backdrop_location
= program
->fragment_shader().backdrop_location();
1196 shader_backdrop_rect_location
=
1197 program
->fragment_shader().backdrop_rect_location();
1200 quad
->rect
.width() / static_cast<float>(contents_texture
->size().width());
1201 float tex_scale_y
= quad
->rect
.height() /
1202 static_cast<float>(contents_texture
->size().height());
1203 DCHECK_LE(tex_scale_x
, 1.0f
);
1204 DCHECK_LE(tex_scale_y
, 1.0f
);
1206 DCHECK(shader_tex_transform_location
!= -1 || IsContextLost());
1207 // Flip the content vertically in the shader, as the RenderPass input
1208 // texture is already oriented the same way as the framebuffer, but the
1209 // projection transform does a flip.
1211 gl_
->Uniform4f(shader_tex_transform_location
,
1217 GLint last_texture_unit
= 0;
1218 if (shader_mask_sampler_location
!= -1) {
1219 DCHECK_NE(shader_mask_tex_coord_scale_location
, 1);
1220 DCHECK_NE(shader_mask_tex_coord_offset_location
, 1);
1221 GLC(gl_
, gl_
->Uniform1i(shader_mask_sampler_location
, 1));
1223 gfx::RectF mask_uv_rect
= quad
->MaskUVRect();
1224 if (mask_sampler
!= SamplerType2D
) {
1225 mask_uv_rect
.Scale(quad
->mask_texture_size
.width(),
1226 quad
->mask_texture_size
.height());
1229 // Mask textures are oriented vertically flipped relative to the framebuffer
1230 // and the RenderPass contents texture, so we flip the tex coords from the
1231 // RenderPass texture to find the mask texture coords.
1233 gl_
->Uniform2f(shader_mask_tex_coord_offset_location
,
1235 mask_uv_rect
.bottom()));
1237 gl_
->Uniform2f(shader_mask_tex_coord_scale_location
,
1238 mask_uv_rect
.width() / tex_scale_x
,
1239 -mask_uv_rect
.height() / tex_scale_y
));
1241 last_texture_unit
= 1;
1244 if (shader_edge_location
!= -1)
1245 GLC(gl_
, gl_
->Uniform3fv(shader_edge_location
, 8, edge
));
1247 if (shader_viewport_location
!= -1) {
1248 float viewport
[4] = {static_cast<float>(viewport_
.x()),
1249 static_cast<float>(viewport_
.y()),
1250 static_cast<float>(viewport_
.width()),
1251 static_cast<float>(viewport_
.height()), };
1252 GLC(gl_
, gl_
->Uniform4fv(shader_viewport_location
, 1, viewport
));
1255 if (shader_color_matrix_location
!= -1) {
1257 for (int i
= 0; i
< 4; ++i
) {
1258 for (int j
= 0; j
< 4; ++j
)
1259 matrix
[i
* 4 + j
] = SkScalarToFloat(color_matrix
[j
* 5 + i
]);
1262 gl_
->UniformMatrix4fv(shader_color_matrix_location
, 1, false, matrix
));
1264 static const float kScale
= 1.0f
/ 255.0f
;
1265 if (shader_color_offset_location
!= -1) {
1267 for (int i
= 0; i
< 4; ++i
)
1268 offset
[i
] = SkScalarToFloat(color_matrix
[i
* 5 + 4]) * kScale
;
1270 GLC(gl_
, gl_
->Uniform4fv(shader_color_offset_location
, 1, offset
));
1273 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> shader_background_sampler_lock
;
1274 if (shader_backdrop_location
!= -1) {
1275 DCHECK(background_texture
|| background_image
);
1276 DCHECK_NE(shader_backdrop_location
, 0);
1277 DCHECK_NE(shader_backdrop_rect_location
, 0);
1279 GLC(gl_
, gl_
->Uniform1i(shader_backdrop_location
, ++last_texture_unit
));
1282 gl_
->Uniform4f(shader_backdrop_rect_location
,
1283 background_rect
.x(),
1284 background_rect
.y(),
1285 background_rect
.width(),
1286 background_rect
.height()));
1288 if (background_image
) {
1289 GrTexture
* texture
= background_image
->getTexture();
1290 GLC(gl_
, gl_
->ActiveTexture(GL_TEXTURE0
+ last_texture_unit
));
1291 gl_
->BindTexture(GL_TEXTURE_2D
, texture
->getTextureHandle());
1292 GLC(gl_
, gl_
->ActiveTexture(GL_TEXTURE0
));
1294 shader_background_sampler_lock
= make_scoped_ptr(
1295 new ResourceProvider::ScopedSamplerGL(resource_provider_
,
1296 background_texture
->id(),
1297 GL_TEXTURE0
+ last_texture_unit
,
1299 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
),
1300 shader_background_sampler_lock
->target());
1304 SetShaderOpacity(quad
->opacity(), shader_alpha_location
);
1305 SetShaderQuadF(surface_quad
, shader_quad_location
);
1307 frame
, quad
->quadTransform(), quad
->rect
, shader_matrix_location
);
1309 // Flush the compositor context before the filter bitmap goes out of
1310 // scope, so the draw gets processed before the filter texture gets deleted.
1312 GLC(gl_
, gl_
->Flush());
1314 if (!use_shaders_for_blending
)
1315 RestoreBlendFuncToDefault(blend_mode
);
1318 struct SolidColorProgramUniforms
{
1320 unsigned matrix_location
;
1321 unsigned viewport_location
;
1322 unsigned quad_location
;
1323 unsigned edge_location
;
1324 unsigned color_location
;
1328 static void SolidColorUniformLocation(T program
,
1329 SolidColorProgramUniforms
* uniforms
) {
1330 uniforms
->program
= program
->program();
1331 uniforms
->matrix_location
= program
->vertex_shader().matrix_location();
1332 uniforms
->viewport_location
= program
->vertex_shader().viewport_location();
1333 uniforms
->quad_location
= program
->vertex_shader().quad_location();
1334 uniforms
->edge_location
= program
->vertex_shader().edge_location();
1335 uniforms
->color_location
= program
->fragment_shader().color_location();
1338 static gfx::QuadF
GetDeviceQuadWithAntialiasingOnExteriorEdges(
1339 const LayerQuad
& device_layer_edges
,
1340 const gfx::Transform
& device_transform
,
1341 const DrawQuad
* quad
) {
1342 gfx::Rect tile_rect
= quad
->visible_rect
;
1343 gfx::PointF bottom_right
= tile_rect
.bottom_right();
1344 gfx::PointF bottom_left
= tile_rect
.bottom_left();
1345 gfx::PointF top_left
= tile_rect
.origin();
1346 gfx::PointF top_right
= tile_rect
.top_right();
1347 bool clipped
= false;
1349 // Map points to device space. We ignore |clipped|, since the result of
1350 // |MapPoint()| still produces a valid point to draw the quad with. When
1351 // clipped, the point will be outside of the viewport. See crbug.com/416367.
1352 bottom_right
= MathUtil::MapPoint(device_transform
, bottom_right
, &clipped
);
1353 bottom_left
= MathUtil::MapPoint(device_transform
, bottom_left
, &clipped
);
1354 top_left
= MathUtil::MapPoint(device_transform
, top_left
, &clipped
);
1355 top_right
= MathUtil::MapPoint(device_transform
, top_right
, &clipped
);
1357 LayerQuad::Edge
bottom_edge(bottom_right
, bottom_left
);
1358 LayerQuad::Edge
left_edge(bottom_left
, top_left
);
1359 LayerQuad::Edge
top_edge(top_left
, top_right
);
1360 LayerQuad::Edge
right_edge(top_right
, bottom_right
);
1362 // Only apply anti-aliasing to edges not clipped by culling or scissoring.
1363 if (quad
->IsTopEdge() && tile_rect
.y() == quad
->rect
.y())
1364 top_edge
= device_layer_edges
.top();
1365 if (quad
->IsLeftEdge() && tile_rect
.x() == quad
->rect
.x())
1366 left_edge
= device_layer_edges
.left();
1367 if (quad
->IsRightEdge() && tile_rect
.right() == quad
->rect
.right())
1368 right_edge
= device_layer_edges
.right();
1369 if (quad
->IsBottomEdge() && tile_rect
.bottom() == quad
->rect
.bottom())
1370 bottom_edge
= device_layer_edges
.bottom();
1372 float sign
= gfx::QuadF(tile_rect
).IsCounterClockwise() ? -1 : 1;
1373 bottom_edge
.scale(sign
);
1374 left_edge
.scale(sign
);
1375 top_edge
.scale(sign
);
1376 right_edge
.scale(sign
);
1378 // Create device space quad.
1379 return LayerQuad(left_edge
, top_edge
, right_edge
, bottom_edge
).ToQuadF();
1383 bool GLRenderer::ShouldAntialiasQuad(const gfx::Transform
& device_transform
,
1384 const DrawQuad
* quad
,
1385 bool force_antialiasing
) {
1386 bool is_render_pass_quad
= (quad
->material
== DrawQuad::RENDER_PASS
);
1387 // For render pass quads, |device_transform| already contains quad's rect.
1388 // TODO(rosca@adobe.com): remove branching on is_render_pass_quad
1390 if (!is_render_pass_quad
&& !quad
->IsEdge())
1392 gfx::RectF content_rect
=
1393 is_render_pass_quad
? QuadVertexRect() : quad
->visibleContentRect();
1395 bool clipped
= false;
1396 gfx::QuadF device_layer_quad
=
1397 MathUtil::MapQuad(device_transform
, gfx::QuadF(content_rect
), &clipped
);
1399 if (device_layer_quad
.BoundingBox().IsEmpty())
1402 bool is_axis_aligned_in_target
= device_layer_quad
.IsRectilinear();
1403 bool is_nearest_rect_within_epsilon
=
1404 is_axis_aligned_in_target
&&
1405 gfx::IsNearestRectWithinDistance(device_layer_quad
.BoundingBox(),
1406 kAntiAliasingEpsilon
);
1407 // AAing clipped quads is not supported by the code yet.
1408 bool use_aa
= !clipped
&& !is_nearest_rect_within_epsilon
;
1409 return use_aa
|| force_antialiasing
;
1413 void GLRenderer::SetupQuadForAntialiasing(
1414 const gfx::Transform
& device_transform
,
1415 const DrawQuad
* quad
,
1416 gfx::QuadF
* local_quad
,
1418 bool is_render_pass_quad
= (quad
->material
== DrawQuad::RENDER_PASS
);
1419 gfx::RectF content_rect
=
1420 is_render_pass_quad
? QuadVertexRect() : quad
->visibleContentRect();
1422 bool clipped
= false;
1423 gfx::QuadF device_layer_quad
=
1424 MathUtil::MapQuad(device_transform
, gfx::QuadF(content_rect
), &clipped
);
1426 LayerQuad
device_layer_bounds(gfx::QuadF(device_layer_quad
.BoundingBox()));
1427 device_layer_bounds
.InflateAntiAliasingDistance();
1429 LayerQuad
device_layer_edges(device_layer_quad
);
1430 device_layer_edges
.InflateAntiAliasingDistance();
1432 device_layer_edges
.ToFloatArray(edge
);
1433 device_layer_bounds
.ToFloatArray(&edge
[12]);
1435 bool use_aa_on_all_four_edges
=
1436 is_render_pass_quad
||
1437 (quad
->IsTopEdge() && quad
->IsLeftEdge() && quad
->IsBottomEdge() &&
1438 quad
->IsRightEdge() && quad
->visible_rect
== quad
->rect
);
1440 gfx::QuadF device_quad
=
1441 use_aa_on_all_four_edges
1442 ? device_layer_edges
.ToQuadF()
1443 : GetDeviceQuadWithAntialiasingOnExteriorEdges(
1444 device_layer_edges
, device_transform
, quad
);
1446 // Map device space quad to local space. device_transform has no 3d
1447 // component since it was flattened, so we don't need to project. We should
1448 // have already checked that the transform was uninvertible above.
1449 gfx::Transform
inverse_device_transform(gfx::Transform::kSkipInitialization
);
1450 bool did_invert
= device_transform
.GetInverse(&inverse_device_transform
);
1453 MathUtil::MapQuad(inverse_device_transform
, device_quad
, &clipped
);
1454 // We should not DCHECK(!clipped) here, because anti-aliasing inflation may
1455 // cause device_quad to become clipped. To our knowledge this scenario does
1456 // not need to be handled differently than the unclipped case.
1459 void GLRenderer::DrawSolidColorQuad(const DrawingFrame
* frame
,
1460 const SolidColorDrawQuad
* quad
) {
1461 gfx::Rect tile_rect
= quad
->visible_rect
;
1463 SkColor color
= quad
->color
;
1464 float opacity
= quad
->opacity();
1465 float alpha
= (SkColorGetA(color
) * (1.0f
/ 255.0f
)) * opacity
;
1467 // Early out if alpha is small enough that quad doesn't contribute to output.
1468 if (alpha
< std::numeric_limits
<float>::epsilon() &&
1469 quad
->ShouldDrawWithBlending())
1472 gfx::Transform device_transform
=
1473 frame
->window_matrix
* frame
->projection_matrix
* quad
->quadTransform();
1474 device_transform
.FlattenTo2d();
1475 if (!device_transform
.IsInvertible())
1478 bool force_aa
= false;
1479 gfx::QuadF local_quad
= gfx::QuadF(gfx::RectF(tile_rect
));
1481 bool use_aa
= settings_
->allow_antialiasing
&&
1482 !quad
->force_anti_aliasing_off
&&
1483 ShouldAntialiasQuad(device_transform
, quad
, force_aa
);
1485 SolidColorProgramUniforms uniforms
;
1487 SetupQuadForAntialiasing(device_transform
, quad
, &local_quad
, edge
);
1488 SolidColorUniformLocation(GetSolidColorProgramAA(), &uniforms
);
1490 SolidColorUniformLocation(GetSolidColorProgram(), &uniforms
);
1492 SetUseProgram(uniforms
.program
);
1495 gl_
->Uniform4f(uniforms
.color_location
,
1496 (SkColorGetR(color
) * (1.0f
/ 255.0f
)) * alpha
,
1497 (SkColorGetG(color
) * (1.0f
/ 255.0f
)) * alpha
,
1498 (SkColorGetB(color
) * (1.0f
/ 255.0f
)) * alpha
,
1501 float viewport
[4] = {static_cast<float>(viewport_
.x()),
1502 static_cast<float>(viewport_
.y()),
1503 static_cast<float>(viewport_
.width()),
1504 static_cast<float>(viewport_
.height()), };
1505 GLC(gl_
, gl_
->Uniform4fv(uniforms
.viewport_location
, 1, viewport
));
1506 GLC(gl_
, gl_
->Uniform3fv(uniforms
.edge_location
, 8, edge
));
1509 // Enable blending when the quad properties require it or if we decided
1510 // to use antialiasing.
1511 SetBlendEnabled(quad
->ShouldDrawWithBlending() || use_aa
);
1513 // Normalize to tile_rect.
1514 local_quad
.Scale(1.0f
/ tile_rect
.width(), 1.0f
/ tile_rect
.height());
1516 SetShaderQuadF(local_quad
, uniforms
.quad_location
);
1518 // The transform and vertex data are used to figure out the extents that the
1519 // un-antialiased quad should have and which vertex this is and the float
1520 // quad passed in via uniform is the actual geometry that gets used to draw
1521 // it. This is why this centered rect is used and not the original quad_rect.
1522 gfx::RectF
centered_rect(
1523 gfx::PointF(-0.5f
* tile_rect
.width(), -0.5f
* tile_rect
.height()),
1526 frame
, quad
->quadTransform(), centered_rect
, uniforms
.matrix_location
);
1529 struct TileProgramUniforms
{
1531 unsigned matrix_location
;
1532 unsigned viewport_location
;
1533 unsigned quad_location
;
1534 unsigned edge_location
;
1535 unsigned vertex_tex_transform_location
;
1536 unsigned sampler_location
;
1537 unsigned fragment_tex_transform_location
;
1538 unsigned alpha_location
;
1542 static void TileUniformLocation(T program
, TileProgramUniforms
* uniforms
) {
1543 uniforms
->program
= program
->program();
1544 uniforms
->matrix_location
= program
->vertex_shader().matrix_location();
1545 uniforms
->viewport_location
= program
->vertex_shader().viewport_location();
1546 uniforms
->quad_location
= program
->vertex_shader().quad_location();
1547 uniforms
->edge_location
= program
->vertex_shader().edge_location();
1548 uniforms
->vertex_tex_transform_location
=
1549 program
->vertex_shader().vertex_tex_transform_location();
1551 uniforms
->sampler_location
= program
->fragment_shader().sampler_location();
1552 uniforms
->alpha_location
= program
->fragment_shader().alpha_location();
1553 uniforms
->fragment_tex_transform_location
=
1554 program
->fragment_shader().fragment_tex_transform_location();
1557 void GLRenderer::DrawTileQuad(const DrawingFrame
* frame
,
1558 const TileDrawQuad
* quad
) {
1559 DrawContentQuad(frame
, quad
, quad
->resource_id
);
1562 void GLRenderer::DrawContentQuad(const DrawingFrame
* frame
,
1563 const ContentDrawQuadBase
* quad
,
1564 ResourceProvider::ResourceId resource_id
) {
1565 gfx::Transform device_transform
=
1566 frame
->window_matrix
* frame
->projection_matrix
* quad
->quadTransform();
1567 device_transform
.FlattenTo2d();
1569 bool use_aa
= settings_
->allow_antialiasing
&&
1570 ShouldAntialiasQuad(device_transform
, quad
, false);
1572 // TODO(timav): simplify coordinate transformations in DrawContentQuadAA
1573 // similar to the way DrawContentQuadNoAA works and then consider
1574 // combining DrawContentQuadAA and DrawContentQuadNoAA into one method.
1576 DrawContentQuadAA(frame
, quad
, resource_id
, device_transform
);
1578 DrawContentQuadNoAA(frame
, quad
, resource_id
);
1581 void GLRenderer::DrawContentQuadAA(const DrawingFrame
* frame
,
1582 const ContentDrawQuadBase
* quad
,
1583 ResourceProvider::ResourceId resource_id
,
1584 const gfx::Transform
& device_transform
) {
1585 if (!device_transform
.IsInvertible())
1588 gfx::Rect tile_rect
= quad
->visible_rect
;
1590 gfx::RectF tex_coord_rect
= MathUtil::ScaleRectProportional(
1591 quad
->tex_coord_rect
, quad
->rect
, tile_rect
);
1592 float tex_to_geom_scale_x
= quad
->rect
.width() / quad
->tex_coord_rect
.width();
1593 float tex_to_geom_scale_y
=
1594 quad
->rect
.height() / quad
->tex_coord_rect
.height();
1596 gfx::RectF
clamp_geom_rect(tile_rect
);
1597 gfx::RectF
clamp_tex_rect(tex_coord_rect
);
1598 // Clamp texture coordinates to avoid sampling outside the layer
1599 // by deflating the tile region half a texel or half a texel
1600 // minus epsilon for one pixel layers. The resulting clamp region
1601 // is mapped to the unit square by the vertex shader and mapped
1602 // back to normalized texture coordinates by the fragment shader
1603 // after being clamped to 0-1 range.
1605 std::min(0.5f
, 0.5f
* clamp_tex_rect
.width() - kAntiAliasingEpsilon
);
1607 std::min(0.5f
, 0.5f
* clamp_tex_rect
.height() - kAntiAliasingEpsilon
);
1608 float geom_clamp_x
=
1609 std::min(tex_clamp_x
* tex_to_geom_scale_x
,
1610 0.5f
* clamp_geom_rect
.width() - kAntiAliasingEpsilon
);
1611 float geom_clamp_y
=
1612 std::min(tex_clamp_y
* tex_to_geom_scale_y
,
1613 0.5f
* clamp_geom_rect
.height() - kAntiAliasingEpsilon
);
1614 clamp_geom_rect
.Inset(geom_clamp_x
, geom_clamp_y
, geom_clamp_x
, geom_clamp_y
);
1615 clamp_tex_rect
.Inset(tex_clamp_x
, tex_clamp_y
, tex_clamp_x
, tex_clamp_y
);
1617 // Map clamping rectangle to unit square.
1618 float vertex_tex_translate_x
= -clamp_geom_rect
.x() / clamp_geom_rect
.width();
1619 float vertex_tex_translate_y
=
1620 -clamp_geom_rect
.y() / clamp_geom_rect
.height();
1621 float vertex_tex_scale_x
= tile_rect
.width() / clamp_geom_rect
.width();
1622 float vertex_tex_scale_y
= tile_rect
.height() / clamp_geom_rect
.height();
1624 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1625 gl_
, &highp_threshold_cache_
, highp_threshold_min_
, quad
->texture_size
);
1627 gfx::QuadF local_quad
= gfx::QuadF(gfx::RectF(tile_rect
));
1629 SetupQuadForAntialiasing(device_transform
, quad
, &local_quad
, edge
);
1631 ResourceProvider::ScopedSamplerGL
quad_resource_lock(
1632 resource_provider_
, resource_id
,
1633 quad
->nearest_neighbor
? GL_NEAREST
: GL_LINEAR
);
1634 SamplerType sampler
=
1635 SamplerTypeFromTextureTarget(quad_resource_lock
.target());
1637 float fragment_tex_translate_x
= clamp_tex_rect
.x();
1638 float fragment_tex_translate_y
= clamp_tex_rect
.y();
1639 float fragment_tex_scale_x
= clamp_tex_rect
.width();
1640 float fragment_tex_scale_y
= clamp_tex_rect
.height();
1642 // Map to normalized texture coordinates.
1643 if (sampler
!= SamplerType2DRect
) {
1644 gfx::Size texture_size
= quad
->texture_size
;
1645 DCHECK(!texture_size
.IsEmpty());
1646 fragment_tex_translate_x
/= texture_size
.width();
1647 fragment_tex_translate_y
/= texture_size
.height();
1648 fragment_tex_scale_x
/= texture_size
.width();
1649 fragment_tex_scale_y
/= texture_size
.height();
1652 TileProgramUniforms uniforms
;
1653 if (quad
->swizzle_contents
) {
1654 TileUniformLocation(GetTileProgramSwizzleAA(tex_coord_precision
, sampler
),
1657 TileUniformLocation(GetTileProgramAA(tex_coord_precision
, sampler
),
1661 SetUseProgram(uniforms
.program
);
1662 GLC(gl_
, gl_
->Uniform1i(uniforms
.sampler_location
, 0));
1664 float viewport
[4] = {
1665 static_cast<float>(viewport_
.x()),
1666 static_cast<float>(viewport_
.y()),
1667 static_cast<float>(viewport_
.width()),
1668 static_cast<float>(viewport_
.height()),
1670 GLC(gl_
, gl_
->Uniform4fv(uniforms
.viewport_location
, 1, viewport
));
1671 GLC(gl_
, gl_
->Uniform3fv(uniforms
.edge_location
, 8, edge
));
1674 gl_
->Uniform4f(uniforms
.vertex_tex_transform_location
,
1675 vertex_tex_translate_x
,
1676 vertex_tex_translate_y
,
1678 vertex_tex_scale_y
));
1680 gl_
->Uniform4f(uniforms
.fragment_tex_transform_location
,
1681 fragment_tex_translate_x
,
1682 fragment_tex_translate_y
,
1683 fragment_tex_scale_x
,
1684 fragment_tex_scale_y
));
1686 // Blending is required for antialiasing.
1687 SetBlendEnabled(true);
1689 // Normalize to tile_rect.
1690 local_quad
.Scale(1.0f
/ tile_rect
.width(), 1.0f
/ tile_rect
.height());
1692 SetShaderOpacity(quad
->opacity(), uniforms
.alpha_location
);
1693 SetShaderQuadF(local_quad
, uniforms
.quad_location
);
1695 // The transform and vertex data are used to figure out the extents that the
1696 // un-antialiased quad should have and which vertex this is and the float
1697 // quad passed in via uniform is the actual geometry that gets used to draw
1698 // it. This is why this centered rect is used and not the original quad_rect.
1699 gfx::RectF
centered_rect(
1700 gfx::PointF(-0.5f
* tile_rect
.width(), -0.5f
* tile_rect
.height()),
1703 frame
, quad
->quadTransform(), centered_rect
, uniforms
.matrix_location
);
1706 void GLRenderer::DrawContentQuadNoAA(const DrawingFrame
* frame
,
1707 const ContentDrawQuadBase
* quad
,
1708 ResourceProvider::ResourceId resource_id
) {
1709 gfx::RectF tex_coord_rect
= MathUtil::ScaleRectProportional(
1710 quad
->tex_coord_rect
, quad
->rect
, quad
->visible_rect
);
1711 float tex_to_geom_scale_x
= quad
->rect
.width() / quad
->tex_coord_rect
.width();
1712 float tex_to_geom_scale_y
=
1713 quad
->rect
.height() / quad
->tex_coord_rect
.height();
1715 bool scaled
= (tex_to_geom_scale_x
!= 1.f
|| tex_to_geom_scale_y
!= 1.f
);
1717 (scaled
|| !quad
->quadTransform().IsIdentityOrIntegerTranslation()) &&
1718 !quad
->nearest_neighbor
1722 ResourceProvider::ScopedSamplerGL
quad_resource_lock(
1723 resource_provider_
, resource_id
, filter
);
1724 SamplerType sampler
=
1725 SamplerTypeFromTextureTarget(quad_resource_lock
.target());
1727 float vertex_tex_translate_x
= tex_coord_rect
.x();
1728 float vertex_tex_translate_y
= tex_coord_rect
.y();
1729 float vertex_tex_scale_x
= tex_coord_rect
.width();
1730 float vertex_tex_scale_y
= tex_coord_rect
.height();
1732 // Map to normalized texture coordinates.
1733 if (sampler
!= SamplerType2DRect
) {
1734 gfx::Size texture_size
= quad
->texture_size
;
1735 DCHECK(!texture_size
.IsEmpty());
1736 vertex_tex_translate_x
/= texture_size
.width();
1737 vertex_tex_translate_y
/= texture_size
.height();
1738 vertex_tex_scale_x
/= texture_size
.width();
1739 vertex_tex_scale_y
/= texture_size
.height();
1742 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1743 gl_
, &highp_threshold_cache_
, highp_threshold_min_
, quad
->texture_size
);
1745 TileProgramUniforms uniforms
;
1746 if (quad
->ShouldDrawWithBlending()) {
1747 if (quad
->swizzle_contents
) {
1748 TileUniformLocation(GetTileProgramSwizzle(tex_coord_precision
, sampler
),
1751 TileUniformLocation(GetTileProgram(tex_coord_precision
, sampler
),
1755 if (quad
->swizzle_contents
) {
1756 TileUniformLocation(
1757 GetTileProgramSwizzleOpaque(tex_coord_precision
, sampler
), &uniforms
);
1759 TileUniformLocation(GetTileProgramOpaque(tex_coord_precision
, sampler
),
1764 SetUseProgram(uniforms
.program
);
1765 GLC(gl_
, gl_
->Uniform1i(uniforms
.sampler_location
, 0));
1768 gl_
->Uniform4f(uniforms
.vertex_tex_transform_location
,
1769 vertex_tex_translate_x
,
1770 vertex_tex_translate_y
,
1772 vertex_tex_scale_y
));
1774 SetBlendEnabled(quad
->ShouldDrawWithBlending());
1776 SetShaderOpacity(quad
->opacity(), uniforms
.alpha_location
);
1778 // Pass quad coordinates to the uniform in the same order as GeometryBinding
1779 // does, then vertices will match the texture mapping in the vertex buffer.
1780 // The method SetShaderQuadF() changes the order of vertices and so it's
1783 gfx::RectF tile_rect
= quad
->visible_rect
;
1784 float gl_quad
[8] = {
1794 GLC(gl_
, gl_
->Uniform2fv(uniforms
.quad_location
, 4, gl_quad
));
1796 static float gl_matrix
[16];
1797 ToGLMatrix(&gl_matrix
[0], frame
->projection_matrix
* quad
->quadTransform());
1799 gl_
->UniformMatrix4fv(uniforms
.matrix_location
, 1, false, &gl_matrix
[0]));
1801 GLC(gl_
, gl_
->DrawElements(GL_TRIANGLES
, 6, GL_UNSIGNED_SHORT
, 0));
1804 void GLRenderer::DrawYUVVideoQuad(const DrawingFrame
* frame
,
1805 const YUVVideoDrawQuad
* quad
) {
1806 SetBlendEnabled(quad
->ShouldDrawWithBlending());
1808 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1810 &highp_threshold_cache_
,
1811 highp_threshold_min_
,
1812 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
1814 bool use_alpha_plane
= quad
->a_plane_resource_id
!= 0;
1816 ResourceProvider::ScopedSamplerGL
y_plane_lock(
1817 resource_provider_
, quad
->y_plane_resource_id
, GL_TEXTURE1
, GL_LINEAR
);
1818 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
), y_plane_lock
.target());
1819 ResourceProvider::ScopedSamplerGL
u_plane_lock(
1820 resource_provider_
, quad
->u_plane_resource_id
, GL_TEXTURE2
, GL_LINEAR
);
1821 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
), u_plane_lock
.target());
1822 ResourceProvider::ScopedSamplerGL
v_plane_lock(
1823 resource_provider_
, quad
->v_plane_resource_id
, GL_TEXTURE3
, GL_LINEAR
);
1824 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
), v_plane_lock
.target());
1825 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> a_plane_lock
;
1826 if (use_alpha_plane
) {
1827 a_plane_lock
.reset(new ResourceProvider::ScopedSamplerGL(
1828 resource_provider_
, quad
->a_plane_resource_id
, GL_TEXTURE4
, GL_LINEAR
));
1829 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
), a_plane_lock
->target());
1832 int matrix_location
= -1;
1833 int tex_scale_location
= -1;
1834 int tex_offset_location
= -1;
1835 int clamp_rect_location
= -1;
1836 int y_texture_location
= -1;
1837 int u_texture_location
= -1;
1838 int v_texture_location
= -1;
1839 int a_texture_location
= -1;
1840 int yuv_matrix_location
= -1;
1841 int yuv_adj_location
= -1;
1842 int alpha_location
= -1;
1843 if (use_alpha_plane
) {
1844 const VideoYUVAProgram
* program
= GetVideoYUVAProgram(tex_coord_precision
);
1845 DCHECK(program
&& (program
->initialized() || IsContextLost()));
1846 SetUseProgram(program
->program());
1847 matrix_location
= program
->vertex_shader().matrix_location();
1848 tex_scale_location
= program
->vertex_shader().tex_scale_location();
1849 tex_offset_location
= program
->vertex_shader().tex_offset_location();
1850 y_texture_location
= program
->fragment_shader().y_texture_location();
1851 u_texture_location
= program
->fragment_shader().u_texture_location();
1852 v_texture_location
= program
->fragment_shader().v_texture_location();
1853 a_texture_location
= program
->fragment_shader().a_texture_location();
1854 yuv_matrix_location
= program
->fragment_shader().yuv_matrix_location();
1855 yuv_adj_location
= program
->fragment_shader().yuv_adj_location();
1856 clamp_rect_location
= program
->fragment_shader().clamp_rect_location();
1857 alpha_location
= program
->fragment_shader().alpha_location();
1859 const VideoYUVProgram
* program
= GetVideoYUVProgram(tex_coord_precision
);
1860 DCHECK(program
&& (program
->initialized() || IsContextLost()));
1861 SetUseProgram(program
->program());
1862 matrix_location
= program
->vertex_shader().matrix_location();
1863 tex_scale_location
= program
->vertex_shader().tex_scale_location();
1864 tex_offset_location
= program
->vertex_shader().tex_offset_location();
1865 y_texture_location
= program
->fragment_shader().y_texture_location();
1866 u_texture_location
= program
->fragment_shader().u_texture_location();
1867 v_texture_location
= program
->fragment_shader().v_texture_location();
1868 yuv_matrix_location
= program
->fragment_shader().yuv_matrix_location();
1869 yuv_adj_location
= program
->fragment_shader().yuv_adj_location();
1870 clamp_rect_location
= program
->fragment_shader().clamp_rect_location();
1871 alpha_location
= program
->fragment_shader().alpha_location();
1875 gl_
->Uniform2f(tex_scale_location
,
1876 quad
->tex_coord_rect
.width(),
1877 quad
->tex_coord_rect
.height()));
1879 gl_
->Uniform2f(tex_offset_location
,
1880 quad
->tex_coord_rect
.x(),
1881 quad
->tex_coord_rect
.y()));
1882 // Clamping to half a texel inside the tex coord rect prevents bilinear
1883 // filtering from filtering outside the tex coord rect.
1884 gfx::RectF
clamp_rect(quad
->tex_coord_rect
);
1885 // Special case: empty texture size implies no clamping.
1886 if (!quad
->tex_size
.IsEmpty()) {
1887 clamp_rect
.Inset(0.5f
/ quad
->tex_size
.width(),
1888 0.5f
/ quad
->tex_size
.height());
1890 GLC(gl_
, gl_
->Uniform4f(clamp_rect_location
, clamp_rect
.x(), clamp_rect
.y(),
1891 clamp_rect
.right(), clamp_rect
.bottom()));
1893 GLC(gl_
, gl_
->Uniform1i(y_texture_location
, 1));
1894 GLC(gl_
, gl_
->Uniform1i(u_texture_location
, 2));
1895 GLC(gl_
, gl_
->Uniform1i(v_texture_location
, 3));
1896 if (use_alpha_plane
)
1897 GLC(gl_
, gl_
->Uniform1i(a_texture_location
, 4));
1899 // These values are magic numbers that are used in the transformation from YUV
1900 // to RGB color values. They are taken from the following webpage:
1901 // http://www.fourcc.org/fccyvrgb.php
1902 float yuv_to_rgb_rec601
[9] = {
1903 1.164f
, 1.164f
, 1.164f
, 0.0f
, -.391f
, 2.018f
, 1.596f
, -.813f
, 0.0f
,
1905 float yuv_to_rgb_rec601_jpeg
[9] = {
1906 1.f
, 1.f
, 1.f
, 0.0f
, -.34414f
, 1.772f
, 1.402f
, -.71414f
, 0.0f
,
1909 // These values map to 16, 128, and 128 respectively, and are computed
1910 // as a fraction over 256 (e.g. 16 / 256 = 0.0625).
1911 // They are used in the YUV to RGBA conversion formula:
1912 // Y - 16 : Gives 16 values of head and footroom for overshooting
1913 // U - 128 : Turns unsigned U into signed U [-128,127]
1914 // V - 128 : Turns unsigned V into signed V [-128,127]
1915 float yuv_adjust_rec601
[3] = {
1916 -0.0625f
, -0.5f
, -0.5f
,
1919 // Same as above, but without the head and footroom.
1920 float yuv_adjust_rec601_jpeg
[3] = {
1924 float* yuv_to_rgb
= NULL
;
1925 float* yuv_adjust
= NULL
;
1927 switch (quad
->color_space
) {
1928 case YUVVideoDrawQuad::REC_601
:
1929 yuv_to_rgb
= yuv_to_rgb_rec601
;
1930 yuv_adjust
= yuv_adjust_rec601
;
1932 case YUVVideoDrawQuad::REC_601_JPEG
:
1933 yuv_to_rgb
= yuv_to_rgb_rec601_jpeg
;
1934 yuv_adjust
= yuv_adjust_rec601_jpeg
;
1938 GLC(gl_
, gl_
->UniformMatrix3fv(yuv_matrix_location
, 1, 0, yuv_to_rgb
));
1939 GLC(gl_
, gl_
->Uniform3fv(yuv_adj_location
, 1, yuv_adjust
));
1941 SetShaderOpacity(quad
->opacity(), alpha_location
);
1942 DrawQuadGeometry(frame
, quad
->quadTransform(), quad
->rect
, matrix_location
);
1945 void GLRenderer::DrawStreamVideoQuad(const DrawingFrame
* frame
,
1946 const StreamVideoDrawQuad
* quad
) {
1947 SetBlendEnabled(quad
->ShouldDrawWithBlending());
1949 static float gl_matrix
[16];
1951 DCHECK(capabilities_
.using_egl_image
);
1953 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1955 &highp_threshold_cache_
,
1956 highp_threshold_min_
,
1957 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
1959 const VideoStreamTextureProgram
* program
=
1960 GetVideoStreamTextureProgram(tex_coord_precision
);
1961 SetUseProgram(program
->program());
1963 ToGLMatrix(&gl_matrix
[0], quad
->matrix
);
1965 gl_
->UniformMatrix4fv(
1966 program
->vertex_shader().tex_matrix_location(), 1, false, gl_matrix
));
1968 ResourceProvider::ScopedReadLockGL
lock(resource_provider_
,
1970 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
1971 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_EXTERNAL_OES
, lock
.texture_id()));
1973 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1975 SetShaderOpacity(quad
->opacity(),
1976 program
->fragment_shader().alpha_location());
1977 DrawQuadGeometry(frame
,
1978 quad
->quadTransform(),
1980 program
->vertex_shader().matrix_location());
1983 void GLRenderer::DrawPictureQuad(const DrawingFrame
* frame
,
1984 const PictureDrawQuad
* quad
) {
1985 if (on_demand_tile_raster_bitmap_
.width() != quad
->texture_size
.width() ||
1986 on_demand_tile_raster_bitmap_
.height() != quad
->texture_size
.height()) {
1987 on_demand_tile_raster_bitmap_
.allocN32Pixels(quad
->texture_size
.width(),
1988 quad
->texture_size
.height());
1990 if (on_demand_tile_raster_resource_id_
)
1991 resource_provider_
->DeleteResource(on_demand_tile_raster_resource_id_
);
1993 on_demand_tile_raster_resource_id_
= resource_provider_
->CreateGLTexture(
1996 GL_TEXTURE_POOL_UNMANAGED_CHROMIUM
,
1998 ResourceProvider::TextureHintImmutable
,
1999 quad
->texture_format
);
2002 SkCanvas
canvas(on_demand_tile_raster_bitmap_
);
2003 quad
->raster_source
->PlaybackToCanvas(&canvas
, quad
->content_rect
,
2004 quad
->contents_scale
);
2006 uint8_t* bitmap_pixels
= NULL
;
2007 SkBitmap on_demand_tile_raster_bitmap_dest
;
2008 SkColorType colorType
= ResourceFormatToSkColorType(quad
->texture_format
);
2009 if (on_demand_tile_raster_bitmap_
.colorType() != colorType
) {
2010 on_demand_tile_raster_bitmap_
.copyTo(&on_demand_tile_raster_bitmap_dest
,
2012 // TODO(kaanb): The GL pipeline assumes a 4-byte alignment for the
2013 // bitmap data. This check will be removed once crbug.com/293728 is fixed.
2014 CHECK_EQ(0u, on_demand_tile_raster_bitmap_dest
.rowBytes() % 4);
2015 bitmap_pixels
= reinterpret_cast<uint8_t*>(
2016 on_demand_tile_raster_bitmap_dest
.getPixels());
2019 reinterpret_cast<uint8_t*>(on_demand_tile_raster_bitmap_
.getPixels());
2022 resource_provider_
->SetPixels(on_demand_tile_raster_resource_id_
,
2024 gfx::Rect(quad
->texture_size
),
2025 gfx::Rect(quad
->texture_size
),
2028 DrawContentQuad(frame
, quad
, on_demand_tile_raster_resource_id_
);
2031 struct TextureProgramBinding
{
2032 template <class Program
>
2033 void Set(Program
* program
) {
2035 program_id
= program
->program();
2036 sampler_location
= program
->fragment_shader().sampler_location();
2037 matrix_location
= program
->vertex_shader().matrix_location();
2038 background_color_location
=
2039 program
->fragment_shader().background_color_location();
2042 int sampler_location
;
2043 int matrix_location
;
2044 int background_color_location
;
2047 struct TexTransformTextureProgramBinding
: TextureProgramBinding
{
2048 template <class Program
>
2049 void Set(Program
* program
) {
2050 TextureProgramBinding::Set(program
);
2051 tex_transform_location
= program
->vertex_shader().tex_transform_location();
2052 vertex_opacity_location
=
2053 program
->vertex_shader().vertex_opacity_location();
2055 int tex_transform_location
;
2056 int vertex_opacity_location
;
2059 void GLRenderer::FlushTextureQuadCache() {
2060 // Check to see if we have anything to draw.
2061 if (draw_cache_
.program_id
== -1)
2064 // Set the correct blending mode.
2065 SetBlendEnabled(draw_cache_
.needs_blending
);
2067 // Bind the program to the GL state.
2068 SetUseProgram(draw_cache_
.program_id
);
2070 // Bind the correct texture sampler location.
2071 GLC(gl_
, gl_
->Uniform1i(draw_cache_
.sampler_location
, 0));
2073 // Assume the current active textures is 0.
2074 ResourceProvider::ScopedSamplerGL
locked_quad(
2076 draw_cache_
.resource_id
,
2077 draw_cache_
.nearest_neighbor
? GL_NEAREST
: GL_LINEAR
);
2078 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
2079 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_2D
, locked_quad
.texture_id()));
2081 static_assert(sizeof(Float4
) == 4 * sizeof(float),
2082 "Float4 struct should be densely packed");
2083 static_assert(sizeof(Float16
) == 16 * sizeof(float),
2084 "Float16 struct should be densely packed");
2086 // Upload the tranforms for both points and uvs.
2088 gl_
->UniformMatrix4fv(
2089 static_cast<int>(draw_cache_
.matrix_location
),
2090 static_cast<int>(draw_cache_
.matrix_data
.size()),
2092 reinterpret_cast<float*>(&draw_cache_
.matrix_data
.front())));
2095 static_cast<int>(draw_cache_
.uv_xform_location
),
2096 static_cast<int>(draw_cache_
.uv_xform_data
.size()),
2097 reinterpret_cast<float*>(&draw_cache_
.uv_xform_data
.front())));
2099 if (draw_cache_
.background_color
!= SK_ColorTRANSPARENT
) {
2100 Float4 background_color
= PremultipliedColor(draw_cache_
.background_color
);
2103 draw_cache_
.background_color_location
, 1, background_color
.data
));
2108 static_cast<int>(draw_cache_
.vertex_opacity_location
),
2109 static_cast<int>(draw_cache_
.vertex_opacity_data
.size()),
2110 static_cast<float*>(&draw_cache_
.vertex_opacity_data
.front())));
2114 gl_
->DrawElements(GL_TRIANGLES
,
2115 6 * draw_cache_
.matrix_data
.size(),
2120 draw_cache_
.program_id
= -1;
2121 draw_cache_
.uv_xform_data
.resize(0);
2122 draw_cache_
.vertex_opacity_data
.resize(0);
2123 draw_cache_
.matrix_data
.resize(0);
2126 void GLRenderer::EnqueueTextureQuad(const DrawingFrame
* frame
,
2127 const TextureDrawQuad
* quad
) {
2128 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
2130 &highp_threshold_cache_
,
2131 highp_threshold_min_
,
2132 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
2134 // Choose the correct texture program binding
2135 TexTransformTextureProgramBinding binding
;
2136 if (quad
->premultiplied_alpha
) {
2137 if (quad
->background_color
== SK_ColorTRANSPARENT
) {
2138 binding
.Set(GetTextureProgram(tex_coord_precision
));
2140 binding
.Set(GetTextureBackgroundProgram(tex_coord_precision
));
2143 if (quad
->background_color
== SK_ColorTRANSPARENT
) {
2144 binding
.Set(GetNonPremultipliedTextureProgram(tex_coord_precision
));
2147 GetNonPremultipliedTextureBackgroundProgram(tex_coord_precision
));
2151 int resource_id
= quad
->resource_id
;
2153 if (draw_cache_
.program_id
!= binding
.program_id
||
2154 draw_cache_
.resource_id
!= resource_id
||
2155 draw_cache_
.needs_blending
!= quad
->ShouldDrawWithBlending() ||
2156 draw_cache_
.nearest_neighbor
!= quad
->nearest_neighbor
||
2157 draw_cache_
.background_color
!= quad
->background_color
||
2158 draw_cache_
.matrix_data
.size() >= 8) {
2159 FlushTextureQuadCache();
2160 draw_cache_
.program_id
= binding
.program_id
;
2161 draw_cache_
.resource_id
= resource_id
;
2162 draw_cache_
.needs_blending
= quad
->ShouldDrawWithBlending();
2163 draw_cache_
.nearest_neighbor
= quad
->nearest_neighbor
;
2164 draw_cache_
.background_color
= quad
->background_color
;
2166 draw_cache_
.uv_xform_location
= binding
.tex_transform_location
;
2167 draw_cache_
.background_color_location
= binding
.background_color_location
;
2168 draw_cache_
.vertex_opacity_location
= binding
.vertex_opacity_location
;
2169 draw_cache_
.matrix_location
= binding
.matrix_location
;
2170 draw_cache_
.sampler_location
= binding
.sampler_location
;
2173 // Generate the uv-transform
2174 draw_cache_
.uv_xform_data
.push_back(UVTransform(quad
));
2176 // Generate the vertex opacity
2177 const float opacity
= quad
->opacity();
2178 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[0] * opacity
);
2179 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[1] * opacity
);
2180 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[2] * opacity
);
2181 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[3] * opacity
);
2183 // Generate the transform matrix
2184 gfx::Transform quad_rect_matrix
;
2185 QuadRectTransform(&quad_rect_matrix
, quad
->quadTransform(), quad
->rect
);
2186 quad_rect_matrix
= frame
->projection_matrix
* quad_rect_matrix
;
2189 quad_rect_matrix
.matrix().asColMajorf(m
.data
);
2190 draw_cache_
.matrix_data
.push_back(m
);
2193 void GLRenderer::DrawIOSurfaceQuad(const DrawingFrame
* frame
,
2194 const IOSurfaceDrawQuad
* quad
) {
2195 SetBlendEnabled(quad
->ShouldDrawWithBlending());
2197 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
2199 &highp_threshold_cache_
,
2200 highp_threshold_min_
,
2201 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
2203 TexTransformTextureProgramBinding binding
;
2204 binding
.Set(GetTextureIOSurfaceProgram(tex_coord_precision
));
2206 SetUseProgram(binding
.program_id
);
2207 GLC(gl_
, gl_
->Uniform1i(binding
.sampler_location
, 0));
2208 if (quad
->orientation
== IOSurfaceDrawQuad::FLIPPED
) {
2210 gl_
->Uniform4f(binding
.tex_transform_location
,
2212 quad
->io_surface_size
.height(),
2213 quad
->io_surface_size
.width(),
2214 quad
->io_surface_size
.height() * -1.0f
));
2217 gl_
->Uniform4f(binding
.tex_transform_location
,
2220 quad
->io_surface_size
.width(),
2221 quad
->io_surface_size
.height()));
2224 const float vertex_opacity
[] = {quad
->opacity(), quad
->opacity(),
2225 quad
->opacity(), quad
->opacity()};
2226 GLC(gl_
, gl_
->Uniform1fv(binding
.vertex_opacity_location
, 4, vertex_opacity
));
2228 ResourceProvider::ScopedReadLockGL
lock(resource_provider_
,
2229 quad
->io_surface_resource_id
);
2230 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
2231 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_RECTANGLE_ARB
, lock
.texture_id()));
2234 frame
, quad
->quadTransform(), quad
->rect
, binding
.matrix_location
);
2236 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_RECTANGLE_ARB
, 0));
2239 void GLRenderer::FinishDrawingFrame(DrawingFrame
* frame
) {
2240 if (use_sync_query_
) {
2241 DCHECK(current_sync_query_
);
2242 current_sync_query_
->End();
2243 pending_sync_queries_
.push_back(current_sync_query_
.Pass());
2246 current_framebuffer_lock_
= nullptr;
2247 swap_buffer_rect_
.Union(gfx::ToEnclosingRect(frame
->root_damage_rect
));
2249 GLC(gl_
, gl_
->Disable(GL_BLEND
));
2250 blend_shadow_
= false;
2252 ScheduleOverlays(frame
);
2255 void GLRenderer::FinishDrawingQuadList() { FlushTextureQuadCache(); }
2257 bool GLRenderer::FlippedFramebuffer(const DrawingFrame
* frame
) const {
2258 if (frame
->current_render_pass
!= frame
->root_render_pass
)
2260 return FlippedRootFramebuffer();
2263 bool GLRenderer::FlippedRootFramebuffer() const {
2264 // GL is normally flipped, so a flipped output results in an unflipping.
2265 return !output_surface_
->capabilities().flipped_output_surface
;
2268 void GLRenderer::EnsureScissorTestEnabled() {
2269 if (is_scissor_enabled_
)
2272 FlushTextureQuadCache();
2273 GLC(gl_
, gl_
->Enable(GL_SCISSOR_TEST
));
2274 is_scissor_enabled_
= true;
2277 void GLRenderer::EnsureScissorTestDisabled() {
2278 if (!is_scissor_enabled_
)
2281 FlushTextureQuadCache();
2282 GLC(gl_
, gl_
->Disable(GL_SCISSOR_TEST
));
2283 is_scissor_enabled_
= false;
2286 void GLRenderer::CopyCurrentRenderPassToBitmap(
2287 DrawingFrame
* frame
,
2288 scoped_ptr
<CopyOutputRequest
> request
) {
2289 TRACE_EVENT0("cc", "GLRenderer::CopyCurrentRenderPassToBitmap");
2290 gfx::Rect copy_rect
= frame
->current_render_pass
->output_rect
;
2291 if (request
->has_area())
2292 copy_rect
.Intersect(request
->area());
2293 GetFramebufferPixelsAsync(frame
, copy_rect
, request
.Pass());
2296 void GLRenderer::ToGLMatrix(float* gl_matrix
, const gfx::Transform
& transform
) {
2297 transform
.matrix().asColMajorf(gl_matrix
);
2300 void GLRenderer::SetShaderQuadF(const gfx::QuadF
& quad
, int quad_location
) {
2301 if (quad_location
== -1)
2305 gl_quad
[0] = quad
.p1().x();
2306 gl_quad
[1] = quad
.p1().y();
2307 gl_quad
[2] = quad
.p2().x();
2308 gl_quad
[3] = quad
.p2().y();
2309 gl_quad
[4] = quad
.p3().x();
2310 gl_quad
[5] = quad
.p3().y();
2311 gl_quad
[6] = quad
.p4().x();
2312 gl_quad
[7] = quad
.p4().y();
2313 GLC(gl_
, gl_
->Uniform2fv(quad_location
, 4, gl_quad
));
2316 void GLRenderer::SetShaderOpacity(float opacity
, int alpha_location
) {
2317 if (alpha_location
!= -1)
2318 GLC(gl_
, gl_
->Uniform1f(alpha_location
, opacity
));
2321 void GLRenderer::SetStencilEnabled(bool enabled
) {
2322 if (enabled
== stencil_shadow_
)
2326 GLC(gl_
, gl_
->Enable(GL_STENCIL_TEST
));
2328 GLC(gl_
, gl_
->Disable(GL_STENCIL_TEST
));
2329 stencil_shadow_
= enabled
;
2332 void GLRenderer::SetBlendEnabled(bool enabled
) {
2333 if (enabled
== blend_shadow_
)
2337 GLC(gl_
, gl_
->Enable(GL_BLEND
));
2339 GLC(gl_
, gl_
->Disable(GL_BLEND
));
2340 blend_shadow_
= enabled
;
2343 void GLRenderer::SetUseProgram(unsigned program
) {
2344 if (program
== program_shadow_
)
2346 gl_
->UseProgram(program
);
2347 program_shadow_
= program
;
2350 void GLRenderer::DrawQuadGeometry(const DrawingFrame
* frame
,
2351 const gfx::Transform
& draw_transform
,
2352 const gfx::RectF
& quad_rect
,
2353 int matrix_location
) {
2354 gfx::Transform quad_rect_matrix
;
2355 QuadRectTransform(&quad_rect_matrix
, draw_transform
, quad_rect
);
2356 static float gl_matrix
[16];
2357 ToGLMatrix(&gl_matrix
[0], frame
->projection_matrix
* quad_rect_matrix
);
2358 GLC(gl_
, gl_
->UniformMatrix4fv(matrix_location
, 1, false, &gl_matrix
[0]));
2360 GLC(gl_
, gl_
->DrawElements(GL_TRIANGLES
, 6, GL_UNSIGNED_SHORT
, 0));
2363 void GLRenderer::Finish() {
2364 TRACE_EVENT0("cc", "GLRenderer::Finish");
2365 GLC(gl_
, gl_
->Finish());
2368 void GLRenderer::SwapBuffers(const CompositorFrameMetadata
& metadata
) {
2369 DCHECK(!is_backbuffer_discarded_
);
2371 TRACE_EVENT0("cc,benchmark", "GLRenderer::SwapBuffers");
2372 // We're done! Time to swapbuffers!
2374 gfx::Size surface_size
= output_surface_
->SurfaceSize();
2376 CompositorFrame compositor_frame
;
2377 compositor_frame
.metadata
= metadata
;
2378 compositor_frame
.gl_frame_data
= make_scoped_ptr(new GLFrameData
);
2379 compositor_frame
.gl_frame_data
->size
= surface_size
;
2380 if (capabilities_
.using_partial_swap
) {
2381 // If supported, we can save significant bandwidth by only swapping the
2382 // damaged/scissored region (clamped to the viewport).
2383 swap_buffer_rect_
.Intersect(gfx::Rect(surface_size
));
2384 int flipped_y_pos_of_rect_bottom
= surface_size
.height() -
2385 swap_buffer_rect_
.y() -
2386 swap_buffer_rect_
.height();
2387 compositor_frame
.gl_frame_data
->sub_buffer_rect
=
2388 gfx::Rect(swap_buffer_rect_
.x(),
2389 FlippedRootFramebuffer() ? flipped_y_pos_of_rect_bottom
2390 : swap_buffer_rect_
.y(),
2391 swap_buffer_rect_
.width(),
2392 swap_buffer_rect_
.height());
2394 compositor_frame
.gl_frame_data
->sub_buffer_rect
=
2395 gfx::Rect(output_surface_
->SurfaceSize());
2397 output_surface_
->SwapBuffers(&compositor_frame
);
2399 // Release previously used overlay resources and hold onto the pending ones
2400 // until the next swap buffers.
2401 in_use_overlay_resources_
.clear();
2402 in_use_overlay_resources_
.swap(pending_overlay_resources_
);
2404 swap_buffer_rect_
= gfx::Rect();
2407 void GLRenderer::EnforceMemoryPolicy() {
2409 TRACE_EVENT0("cc", "GLRenderer::EnforceMemoryPolicy dropping resources");
2410 ReleaseRenderPassTextures();
2411 DiscardBackbuffer();
2412 resource_provider_
->ReleaseCachedData();
2413 output_surface_
->context_provider()->DeleteCachedResources();
2414 GLC(gl_
, gl_
->Flush());
2418 void GLRenderer::DiscardBackbuffer() {
2419 if (is_backbuffer_discarded_
)
2422 output_surface_
->DiscardBackbuffer();
2424 is_backbuffer_discarded_
= true;
2426 // Damage tracker needs a full reset every time framebuffer is discarded.
2427 client_
->SetFullRootLayerDamage();
2430 void GLRenderer::EnsureBackbuffer() {
2431 if (!is_backbuffer_discarded_
)
2434 output_surface_
->EnsureBackbuffer();
2435 is_backbuffer_discarded_
= false;
2438 void GLRenderer::GetFramebufferPixelsAsync(
2439 const DrawingFrame
* frame
,
2440 const gfx::Rect
& rect
,
2441 scoped_ptr
<CopyOutputRequest
> request
) {
2442 DCHECK(!request
->IsEmpty());
2443 if (request
->IsEmpty())
2448 gfx::Rect window_rect
= MoveFromDrawToWindowSpace(frame
, rect
);
2449 DCHECK_GE(window_rect
.x(), 0);
2450 DCHECK_GE(window_rect
.y(), 0);
2451 DCHECK_LE(window_rect
.right(), current_surface_size_
.width());
2452 DCHECK_LE(window_rect
.bottom(), current_surface_size_
.height());
2454 if (!request
->force_bitmap_result()) {
2455 bool own_mailbox
= !request
->has_texture_mailbox();
2457 GLuint texture_id
= 0;
2458 gpu::Mailbox mailbox
;
2460 GLC(gl_
, gl_
->GenMailboxCHROMIUM(mailbox
.name
));
2461 gl_
->GenTextures(1, &texture_id
);
2462 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_2D
, texture_id
));
2465 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_LINEAR
));
2467 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAG_FILTER
, GL_LINEAR
));
2470 GL_TEXTURE_2D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
));
2473 GL_TEXTURE_2D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
));
2474 GLC(gl_
, gl_
->ProduceTextureCHROMIUM(GL_TEXTURE_2D
, mailbox
.name
));
2476 mailbox
= request
->texture_mailbox().mailbox();
2477 DCHECK_EQ(static_cast<unsigned>(GL_TEXTURE_2D
),
2478 request
->texture_mailbox().target());
2479 DCHECK(!mailbox
.IsZero());
2480 unsigned incoming_sync_point
= request
->texture_mailbox().sync_point();
2481 if (incoming_sync_point
)
2482 GLC(gl_
, gl_
->WaitSyncPointCHROMIUM(incoming_sync_point
));
2486 gl_
->CreateAndConsumeTextureCHROMIUM(GL_TEXTURE_2D
, mailbox
.name
));
2488 GetFramebufferTexture(texture_id
, RGBA_8888
, window_rect
);
2490 unsigned sync_point
= gl_
->InsertSyncPointCHROMIUM();
2491 TextureMailbox
texture_mailbox(mailbox
, GL_TEXTURE_2D
, sync_point
);
2493 scoped_ptr
<SingleReleaseCallback
> release_callback
;
2495 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_2D
, 0));
2496 release_callback
= texture_mailbox_deleter_
->GetReleaseCallback(
2497 output_surface_
->context_provider(), texture_id
);
2499 gl_
->DeleteTextures(1, &texture_id
);
2502 request
->SendTextureResult(
2503 window_rect
.size(), texture_mailbox
, release_callback
.Pass());
2507 DCHECK(request
->force_bitmap_result());
2509 scoped_ptr
<PendingAsyncReadPixels
> pending_read(new PendingAsyncReadPixels
);
2510 pending_read
->copy_request
= request
.Pass();
2511 pending_async_read_pixels_
.insert(pending_async_read_pixels_
.begin(),
2512 pending_read
.Pass());
2514 bool do_workaround
= NeedsIOSurfaceReadbackWorkaround();
2516 unsigned temporary_texture
= 0;
2517 unsigned temporary_fbo
= 0;
2519 if (do_workaround
) {
2520 // On Mac OS X, calling glReadPixels() against an FBO whose color attachment
2521 // is an IOSurface-backed texture causes corruption of future glReadPixels()
2522 // calls, even those on different OpenGL contexts. It is believed that this
2523 // is the root cause of top crasher
2524 // http://crbug.com/99393. <rdar://problem/10949687>
2526 gl_
->GenTextures(1, &temporary_texture
);
2527 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_2D
, temporary_texture
));
2529 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_LINEAR
));
2531 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAG_FILTER
, GL_LINEAR
));
2533 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
));
2535 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
));
2536 // Copy the contents of the current (IOSurface-backed) framebuffer into a
2537 // temporary texture.
2538 GetFramebufferTexture(
2539 temporary_texture
, RGBA_8888
, gfx::Rect(current_surface_size_
));
2540 gl_
->GenFramebuffers(1, &temporary_fbo
);
2541 // Attach this texture to an FBO, and perform the readback from that FBO.
2542 GLC(gl_
, gl_
->BindFramebuffer(GL_FRAMEBUFFER
, temporary_fbo
));
2544 gl_
->FramebufferTexture2D(GL_FRAMEBUFFER
,
2545 GL_COLOR_ATTACHMENT0
,
2550 DCHECK_EQ(static_cast<unsigned>(GL_FRAMEBUFFER_COMPLETE
),
2551 gl_
->CheckFramebufferStatus(GL_FRAMEBUFFER
));
2555 gl_
->GenBuffers(1, &buffer
);
2556 GLC(gl_
, gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, buffer
));
2558 gl_
->BufferData(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
,
2559 4 * window_rect
.size().GetArea(),
2564 gl_
->GenQueriesEXT(1, &query
);
2565 GLC(gl_
, gl_
->BeginQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM
, query
));
2568 gl_
->ReadPixels(window_rect
.x(),
2570 window_rect
.width(),
2571 window_rect
.height(),
2576 GLC(gl_
, gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, 0));
2578 if (do_workaround
) {
2580 GLC(gl_
, gl_
->BindFramebuffer(GL_FRAMEBUFFER
, 0));
2581 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_2D
, 0));
2582 GLC(gl_
, gl_
->DeleteFramebuffers(1, &temporary_fbo
));
2583 GLC(gl_
, gl_
->DeleteTextures(1, &temporary_texture
));
2586 base::Closure finished_callback
= base::Bind(&GLRenderer::FinishedReadback
,
2587 base::Unretained(this),
2590 window_rect
.size());
2591 // Save the finished_callback so it can be cancelled.
2592 pending_async_read_pixels_
.front()->finished_read_pixels_callback
.Reset(
2594 base::Closure cancelable_callback
=
2595 pending_async_read_pixels_
.front()->
2596 finished_read_pixels_callback
.callback();
2598 // Save the buffer to verify the callbacks happen in the expected order.
2599 pending_async_read_pixels_
.front()->buffer
= buffer
;
2601 GLC(gl_
, gl_
->EndQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM
));
2602 context_support_
->SignalQuery(query
, cancelable_callback
);
2604 EnforceMemoryPolicy();
2607 void GLRenderer::FinishedReadback(unsigned source_buffer
,
2609 const gfx::Size
& size
) {
2610 DCHECK(!pending_async_read_pixels_
.empty());
2613 GLC(gl_
, gl_
->DeleteQueriesEXT(1, &query
));
2616 PendingAsyncReadPixels
* current_read
= pending_async_read_pixels_
.back();
2617 // Make sure we service the readbacks in order.
2618 DCHECK_EQ(source_buffer
, current_read
->buffer
);
2620 uint8
* src_pixels
= NULL
;
2621 scoped_ptr
<SkBitmap
> bitmap
;
2623 if (source_buffer
!= 0) {
2625 gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, source_buffer
));
2626 src_pixels
= static_cast<uint8
*>(gl_
->MapBufferCHROMIUM(
2627 GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, GL_READ_ONLY
));
2630 bitmap
.reset(new SkBitmap
);
2631 bitmap
->allocN32Pixels(size
.width(), size
.height());
2632 scoped_ptr
<SkAutoLockPixels
> lock(new SkAutoLockPixels(*bitmap
));
2633 uint8
* dest_pixels
= static_cast<uint8
*>(bitmap
->getPixels());
2635 size_t row_bytes
= size
.width() * 4;
2636 int num_rows
= size
.height();
2637 size_t total_bytes
= num_rows
* row_bytes
;
2638 for (size_t dest_y
= 0; dest_y
< total_bytes
; dest_y
+= row_bytes
) {
2640 size_t src_y
= total_bytes
- dest_y
- row_bytes
;
2641 // Swizzle OpenGL -> Skia byte order.
2642 for (size_t x
= 0; x
< row_bytes
; x
+= 4) {
2643 dest_pixels
[dest_y
+ x
+ SK_R32_SHIFT
/ 8] =
2644 src_pixels
[src_y
+ x
+ 0];
2645 dest_pixels
[dest_y
+ x
+ SK_G32_SHIFT
/ 8] =
2646 src_pixels
[src_y
+ x
+ 1];
2647 dest_pixels
[dest_y
+ x
+ SK_B32_SHIFT
/ 8] =
2648 src_pixels
[src_y
+ x
+ 2];
2649 dest_pixels
[dest_y
+ x
+ SK_A32_SHIFT
/ 8] =
2650 src_pixels
[src_y
+ x
+ 3];
2655 gl_
->UnmapBufferCHROMIUM(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
));
2657 GLC(gl_
, gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, 0));
2658 GLC(gl_
, gl_
->DeleteBuffers(1, &source_buffer
));
2662 current_read
->copy_request
->SendBitmapResult(bitmap
.Pass());
2663 pending_async_read_pixels_
.pop_back();
2666 void GLRenderer::GetFramebufferTexture(unsigned texture_id
,
2667 ResourceFormat texture_format
,
2668 const gfx::Rect
& window_rect
) {
2670 DCHECK_GE(window_rect
.x(), 0);
2671 DCHECK_GE(window_rect
.y(), 0);
2672 DCHECK_LE(window_rect
.right(), current_surface_size_
.width());
2673 DCHECK_LE(window_rect
.bottom(), current_surface_size_
.height());
2675 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_2D
, texture_id
));
2677 gl_
->CopyTexImage2D(GL_TEXTURE_2D
,
2679 GLDataFormat(texture_format
),
2682 window_rect
.width(),
2683 window_rect
.height(),
2685 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_2D
, 0));
2688 bool GLRenderer::UseScopedTexture(DrawingFrame
* frame
,
2689 const ScopedResource
* texture
,
2690 const gfx::Rect
& viewport_rect
) {
2691 DCHECK(texture
->id());
2692 frame
->current_render_pass
= NULL
;
2693 frame
->current_texture
= texture
;
2695 return BindFramebufferToTexture(frame
, texture
, viewport_rect
);
2698 void GLRenderer::BindFramebufferToOutputSurface(DrawingFrame
* frame
) {
2699 current_framebuffer_lock_
= nullptr;
2700 output_surface_
->BindFramebuffer();
2702 if (output_surface_
->HasExternalStencilTest()) {
2703 SetStencilEnabled(true);
2704 GLC(gl_
, gl_
->StencilFunc(GL_EQUAL
, 1, 1));
2706 SetStencilEnabled(false);
2710 bool GLRenderer::BindFramebufferToTexture(DrawingFrame
* frame
,
2711 const ScopedResource
* texture
,
2712 const gfx::Rect
& target_rect
) {
2713 DCHECK(texture
->id());
2715 current_framebuffer_lock_
= nullptr;
2717 SetStencilEnabled(false);
2718 GLC(gl_
, gl_
->BindFramebuffer(GL_FRAMEBUFFER
, offscreen_framebuffer_id_
));
2719 current_framebuffer_lock_
=
2720 make_scoped_ptr(new ResourceProvider::ScopedWriteLockGL(
2721 resource_provider_
, texture
->id()));
2722 unsigned texture_id
= current_framebuffer_lock_
->texture_id();
2724 gl_
->FramebufferTexture2D(
2725 GL_FRAMEBUFFER
, GL_COLOR_ATTACHMENT0
, GL_TEXTURE_2D
, texture_id
, 0));
2727 DCHECK(gl_
->CheckFramebufferStatus(GL_FRAMEBUFFER
) ==
2728 GL_FRAMEBUFFER_COMPLETE
||
2732 frame
, target_rect
, gfx::Rect(target_rect
.size()), target_rect
.size());
2736 void GLRenderer::SetScissorTestRect(const gfx::Rect
& scissor_rect
) {
2737 EnsureScissorTestEnabled();
2739 // Don't unnecessarily ask the context to change the scissor, because it
2740 // may cause undesired GPU pipeline flushes.
2741 if (scissor_rect
== scissor_rect_
&& !scissor_rect_needs_reset_
)
2744 scissor_rect_
= scissor_rect
;
2745 FlushTextureQuadCache();
2747 gl_
->Scissor(scissor_rect
.x(),
2749 scissor_rect
.width(),
2750 scissor_rect
.height()));
2752 scissor_rect_needs_reset_
= false;
2755 void GLRenderer::SetDrawViewport(const gfx::Rect
& window_space_viewport
) {
2756 viewport_
= window_space_viewport
;
2758 gl_
->Viewport(window_space_viewport
.x(),
2759 window_space_viewport
.y(),
2760 window_space_viewport
.width(),
2761 window_space_viewport
.height()));
2764 void GLRenderer::InitializeSharedObjects() {
2765 TRACE_EVENT0("cc", "GLRenderer::InitializeSharedObjects");
2767 // Create an FBO for doing offscreen rendering.
2768 GLC(gl_
, gl_
->GenFramebuffers(1, &offscreen_framebuffer_id_
));
2770 shared_geometry_
= make_scoped_ptr(
2771 new GeometryBinding(gl_
, QuadVertexRect()));
2774 const GLRenderer::TileCheckerboardProgram
*
2775 GLRenderer::GetTileCheckerboardProgram() {
2776 if (!tile_checkerboard_program_
.initialized()) {
2777 TRACE_EVENT0("cc", "GLRenderer::checkerboardProgram::initalize");
2778 tile_checkerboard_program_
.Initialize(output_surface_
->context_provider(),
2779 TexCoordPrecisionNA
,
2782 return &tile_checkerboard_program_
;
2785 const GLRenderer::DebugBorderProgram
* GLRenderer::GetDebugBorderProgram() {
2786 if (!debug_border_program_
.initialized()) {
2787 TRACE_EVENT0("cc", "GLRenderer::debugBorderProgram::initialize");
2788 debug_border_program_
.Initialize(output_surface_
->context_provider(),
2789 TexCoordPrecisionNA
,
2792 return &debug_border_program_
;
2795 const GLRenderer::SolidColorProgram
* GLRenderer::GetSolidColorProgram() {
2796 if (!solid_color_program_
.initialized()) {
2797 TRACE_EVENT0("cc", "GLRenderer::solidColorProgram::initialize");
2798 solid_color_program_
.Initialize(output_surface_
->context_provider(),
2799 TexCoordPrecisionNA
,
2802 return &solid_color_program_
;
2805 const GLRenderer::SolidColorProgramAA
* GLRenderer::GetSolidColorProgramAA() {
2806 if (!solid_color_program_aa_
.initialized()) {
2807 TRACE_EVENT0("cc", "GLRenderer::solidColorProgramAA::initialize");
2808 solid_color_program_aa_
.Initialize(output_surface_
->context_provider(),
2809 TexCoordPrecisionNA
,
2812 return &solid_color_program_aa_
;
2815 const GLRenderer::RenderPassProgram
* GLRenderer::GetRenderPassProgram(
2816 TexCoordPrecision precision
,
2817 BlendMode blend_mode
) {
2818 DCHECK_GE(precision
, 0);
2819 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2820 DCHECK_GE(blend_mode
, 0);
2821 DCHECK_LT(blend_mode
, NumBlendModes
);
2822 RenderPassProgram
* program
= &render_pass_program_
[precision
][blend_mode
];
2823 if (!program
->initialized()) {
2824 TRACE_EVENT0("cc", "GLRenderer::renderPassProgram::initialize");
2825 program
->Initialize(output_surface_
->context_provider(),
2833 const GLRenderer::RenderPassProgramAA
* GLRenderer::GetRenderPassProgramAA(
2834 TexCoordPrecision precision
,
2835 BlendMode blend_mode
) {
2836 DCHECK_GE(precision
, 0);
2837 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2838 DCHECK_GE(blend_mode
, 0);
2839 DCHECK_LT(blend_mode
, NumBlendModes
);
2840 RenderPassProgramAA
* program
=
2841 &render_pass_program_aa_
[precision
][blend_mode
];
2842 if (!program
->initialized()) {
2843 TRACE_EVENT0("cc", "GLRenderer::renderPassProgramAA::initialize");
2844 program
->Initialize(output_surface_
->context_provider(),
2852 const GLRenderer::RenderPassMaskProgram
* GLRenderer::GetRenderPassMaskProgram(
2853 TexCoordPrecision precision
,
2854 SamplerType sampler
,
2855 BlendMode blend_mode
) {
2856 DCHECK_GE(precision
, 0);
2857 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2858 DCHECK_GE(sampler
, 0);
2859 DCHECK_LT(sampler
, NumSamplerTypes
);
2860 DCHECK_GE(blend_mode
, 0);
2861 DCHECK_LT(blend_mode
, NumBlendModes
);
2862 RenderPassMaskProgram
* program
=
2863 &render_pass_mask_program_
[precision
][sampler
][blend_mode
];
2864 if (!program
->initialized()) {
2865 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgram::initialize");
2866 program
->Initialize(
2867 output_surface_
->context_provider(), precision
, sampler
, blend_mode
);
2872 const GLRenderer::RenderPassMaskProgramAA
*
2873 GLRenderer::GetRenderPassMaskProgramAA(TexCoordPrecision precision
,
2874 SamplerType sampler
,
2875 BlendMode blend_mode
) {
2876 DCHECK_GE(precision
, 0);
2877 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2878 DCHECK_GE(sampler
, 0);
2879 DCHECK_LT(sampler
, NumSamplerTypes
);
2880 DCHECK_GE(blend_mode
, 0);
2881 DCHECK_LT(blend_mode
, NumBlendModes
);
2882 RenderPassMaskProgramAA
* program
=
2883 &render_pass_mask_program_aa_
[precision
][sampler
][blend_mode
];
2884 if (!program
->initialized()) {
2885 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgramAA::initialize");
2886 program
->Initialize(
2887 output_surface_
->context_provider(), precision
, sampler
, blend_mode
);
2892 const GLRenderer::RenderPassColorMatrixProgram
*
2893 GLRenderer::GetRenderPassColorMatrixProgram(TexCoordPrecision precision
,
2894 BlendMode blend_mode
) {
2895 DCHECK_GE(precision
, 0);
2896 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2897 DCHECK_GE(blend_mode
, 0);
2898 DCHECK_LT(blend_mode
, NumBlendModes
);
2899 RenderPassColorMatrixProgram
* program
=
2900 &render_pass_color_matrix_program_
[precision
][blend_mode
];
2901 if (!program
->initialized()) {
2902 TRACE_EVENT0("cc", "GLRenderer::renderPassColorMatrixProgram::initialize");
2903 program
->Initialize(output_surface_
->context_provider(),
2911 const GLRenderer::RenderPassColorMatrixProgramAA
*
2912 GLRenderer::GetRenderPassColorMatrixProgramAA(TexCoordPrecision precision
,
2913 BlendMode blend_mode
) {
2914 DCHECK_GE(precision
, 0);
2915 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2916 DCHECK_GE(blend_mode
, 0);
2917 DCHECK_LT(blend_mode
, NumBlendModes
);
2918 RenderPassColorMatrixProgramAA
* program
=
2919 &render_pass_color_matrix_program_aa_
[precision
][blend_mode
];
2920 if (!program
->initialized()) {
2922 "GLRenderer::renderPassColorMatrixProgramAA::initialize");
2923 program
->Initialize(output_surface_
->context_provider(),
2931 const GLRenderer::RenderPassMaskColorMatrixProgram
*
2932 GLRenderer::GetRenderPassMaskColorMatrixProgram(TexCoordPrecision precision
,
2933 SamplerType sampler
,
2934 BlendMode blend_mode
) {
2935 DCHECK_GE(precision
, 0);
2936 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2937 DCHECK_GE(sampler
, 0);
2938 DCHECK_LT(sampler
, NumSamplerTypes
);
2939 DCHECK_GE(blend_mode
, 0);
2940 DCHECK_LT(blend_mode
, NumBlendModes
);
2941 RenderPassMaskColorMatrixProgram
* program
=
2942 &render_pass_mask_color_matrix_program_
[precision
][sampler
][blend_mode
];
2943 if (!program
->initialized()) {
2945 "GLRenderer::renderPassMaskColorMatrixProgram::initialize");
2946 program
->Initialize(
2947 output_surface_
->context_provider(), precision
, sampler
, blend_mode
);
2952 const GLRenderer::RenderPassMaskColorMatrixProgramAA
*
2953 GLRenderer::GetRenderPassMaskColorMatrixProgramAA(TexCoordPrecision precision
,
2954 SamplerType sampler
,
2955 BlendMode blend_mode
) {
2956 DCHECK_GE(precision
, 0);
2957 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2958 DCHECK_GE(sampler
, 0);
2959 DCHECK_LT(sampler
, NumSamplerTypes
);
2960 DCHECK_GE(blend_mode
, 0);
2961 DCHECK_LT(blend_mode
, NumBlendModes
);
2962 RenderPassMaskColorMatrixProgramAA
* program
=
2963 &render_pass_mask_color_matrix_program_aa_
[precision
][sampler
]
2965 if (!program
->initialized()) {
2967 "GLRenderer::renderPassMaskColorMatrixProgramAA::initialize");
2968 program
->Initialize(
2969 output_surface_
->context_provider(), precision
, sampler
, blend_mode
);
2974 const GLRenderer::TileProgram
* GLRenderer::GetTileProgram(
2975 TexCoordPrecision precision
,
2976 SamplerType sampler
) {
2977 DCHECK_GE(precision
, 0);
2978 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2979 DCHECK_GE(sampler
, 0);
2980 DCHECK_LT(sampler
, NumSamplerTypes
);
2981 TileProgram
* program
= &tile_program_
[precision
][sampler
];
2982 if (!program
->initialized()) {
2983 TRACE_EVENT0("cc", "GLRenderer::tileProgram::initialize");
2984 program
->Initialize(
2985 output_surface_
->context_provider(), precision
, sampler
);
2990 const GLRenderer::TileProgramOpaque
* GLRenderer::GetTileProgramOpaque(
2991 TexCoordPrecision precision
,
2992 SamplerType sampler
) {
2993 DCHECK_GE(precision
, 0);
2994 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2995 DCHECK_GE(sampler
, 0);
2996 DCHECK_LT(sampler
, NumSamplerTypes
);
2997 TileProgramOpaque
* program
= &tile_program_opaque_
[precision
][sampler
];
2998 if (!program
->initialized()) {
2999 TRACE_EVENT0("cc", "GLRenderer::tileProgramOpaque::initialize");
3000 program
->Initialize(
3001 output_surface_
->context_provider(), precision
, sampler
);
3006 const GLRenderer::TileProgramAA
* GLRenderer::GetTileProgramAA(
3007 TexCoordPrecision precision
,
3008 SamplerType sampler
) {
3009 DCHECK_GE(precision
, 0);
3010 DCHECK_LT(precision
, NumTexCoordPrecisions
);
3011 DCHECK_GE(sampler
, 0);
3012 DCHECK_LT(sampler
, NumSamplerTypes
);
3013 TileProgramAA
* program
= &tile_program_aa_
[precision
][sampler
];
3014 if (!program
->initialized()) {
3015 TRACE_EVENT0("cc", "GLRenderer::tileProgramAA::initialize");
3016 program
->Initialize(
3017 output_surface_
->context_provider(), precision
, sampler
);
3022 const GLRenderer::TileProgramSwizzle
* GLRenderer::GetTileProgramSwizzle(
3023 TexCoordPrecision precision
,
3024 SamplerType sampler
) {
3025 DCHECK_GE(precision
, 0);
3026 DCHECK_LT(precision
, NumTexCoordPrecisions
);
3027 DCHECK_GE(sampler
, 0);
3028 DCHECK_LT(sampler
, NumSamplerTypes
);
3029 TileProgramSwizzle
* program
= &tile_program_swizzle_
[precision
][sampler
];
3030 if (!program
->initialized()) {
3031 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzle::initialize");
3032 program
->Initialize(
3033 output_surface_
->context_provider(), precision
, sampler
);
3038 const GLRenderer::TileProgramSwizzleOpaque
*
3039 GLRenderer::GetTileProgramSwizzleOpaque(TexCoordPrecision precision
,
3040 SamplerType sampler
) {
3041 DCHECK_GE(precision
, 0);
3042 DCHECK_LT(precision
, NumTexCoordPrecisions
);
3043 DCHECK_GE(sampler
, 0);
3044 DCHECK_LT(sampler
, NumSamplerTypes
);
3045 TileProgramSwizzleOpaque
* program
=
3046 &tile_program_swizzle_opaque_
[precision
][sampler
];
3047 if (!program
->initialized()) {
3048 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleOpaque::initialize");
3049 program
->Initialize(
3050 output_surface_
->context_provider(), precision
, sampler
);
3055 const GLRenderer::TileProgramSwizzleAA
* GLRenderer::GetTileProgramSwizzleAA(
3056 TexCoordPrecision precision
,
3057 SamplerType sampler
) {
3058 DCHECK_GE(precision
, 0);
3059 DCHECK_LT(precision
, NumTexCoordPrecisions
);
3060 DCHECK_GE(sampler
, 0);
3061 DCHECK_LT(sampler
, NumSamplerTypes
);
3062 TileProgramSwizzleAA
* program
= &tile_program_swizzle_aa_
[precision
][sampler
];
3063 if (!program
->initialized()) {
3064 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleAA::initialize");
3065 program
->Initialize(
3066 output_surface_
->context_provider(), precision
, sampler
);
3071 const GLRenderer::TextureProgram
* GLRenderer::GetTextureProgram(
3072 TexCoordPrecision precision
) {
3073 DCHECK_GE(precision
, 0);
3074 DCHECK_LT(precision
, NumTexCoordPrecisions
);
3075 TextureProgram
* program
= &texture_program_
[precision
];
3076 if (!program
->initialized()) {
3077 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3078 program
->Initialize(
3079 output_surface_
->context_provider(), precision
, SamplerType2D
);
3084 const GLRenderer::NonPremultipliedTextureProgram
*
3085 GLRenderer::GetNonPremultipliedTextureProgram(TexCoordPrecision precision
) {
3086 DCHECK_GE(precision
, 0);
3087 DCHECK_LT(precision
, NumTexCoordPrecisions
);
3088 NonPremultipliedTextureProgram
* program
=
3089 &nonpremultiplied_texture_program_
[precision
];
3090 if (!program
->initialized()) {
3092 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3093 program
->Initialize(
3094 output_surface_
->context_provider(), precision
, SamplerType2D
);
3099 const GLRenderer::TextureBackgroundProgram
*
3100 GLRenderer::GetTextureBackgroundProgram(TexCoordPrecision precision
) {
3101 DCHECK_GE(precision
, 0);
3102 DCHECK_LT(precision
, NumTexCoordPrecisions
);
3103 TextureBackgroundProgram
* program
= &texture_background_program_
[precision
];
3104 if (!program
->initialized()) {
3105 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3106 program
->Initialize(
3107 output_surface_
->context_provider(), precision
, SamplerType2D
);
3112 const GLRenderer::NonPremultipliedTextureBackgroundProgram
*
3113 GLRenderer::GetNonPremultipliedTextureBackgroundProgram(
3114 TexCoordPrecision precision
) {
3115 DCHECK_GE(precision
, 0);
3116 DCHECK_LT(precision
, NumTexCoordPrecisions
);
3117 NonPremultipliedTextureBackgroundProgram
* program
=
3118 &nonpremultiplied_texture_background_program_
[precision
];
3119 if (!program
->initialized()) {
3121 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3122 program
->Initialize(
3123 output_surface_
->context_provider(), precision
, SamplerType2D
);
3128 const GLRenderer::TextureProgram
* GLRenderer::GetTextureIOSurfaceProgram(
3129 TexCoordPrecision precision
) {
3130 DCHECK_GE(precision
, 0);
3131 DCHECK_LT(precision
, NumTexCoordPrecisions
);
3132 TextureProgram
* program
= &texture_io_surface_program_
[precision
];
3133 if (!program
->initialized()) {
3134 TRACE_EVENT0("cc", "GLRenderer::textureIOSurfaceProgram::initialize");
3135 program
->Initialize(
3136 output_surface_
->context_provider(), precision
, SamplerType2DRect
);
3141 const GLRenderer::VideoYUVProgram
* GLRenderer::GetVideoYUVProgram(
3142 TexCoordPrecision precision
) {
3143 DCHECK_GE(precision
, 0);
3144 DCHECK_LT(precision
, NumTexCoordPrecisions
);
3145 VideoYUVProgram
* program
= &video_yuv_program_
[precision
];
3146 if (!program
->initialized()) {
3147 TRACE_EVENT0("cc", "GLRenderer::videoYUVProgram::initialize");
3148 program
->Initialize(
3149 output_surface_
->context_provider(), precision
, SamplerType2D
);
3154 const GLRenderer::VideoYUVAProgram
* GLRenderer::GetVideoYUVAProgram(
3155 TexCoordPrecision precision
) {
3156 DCHECK_GE(precision
, 0);
3157 DCHECK_LT(precision
, NumTexCoordPrecisions
);
3158 VideoYUVAProgram
* program
= &video_yuva_program_
[precision
];
3159 if (!program
->initialized()) {
3160 TRACE_EVENT0("cc", "GLRenderer::videoYUVAProgram::initialize");
3161 program
->Initialize(
3162 output_surface_
->context_provider(), precision
, SamplerType2D
);
3167 const GLRenderer::VideoStreamTextureProgram
*
3168 GLRenderer::GetVideoStreamTextureProgram(TexCoordPrecision precision
) {
3169 if (!Capabilities().using_egl_image
)
3171 DCHECK_GE(precision
, 0);
3172 DCHECK_LT(precision
, NumTexCoordPrecisions
);
3173 VideoStreamTextureProgram
* program
=
3174 &video_stream_texture_program_
[precision
];
3175 if (!program
->initialized()) {
3176 TRACE_EVENT0("cc", "GLRenderer::streamTextureProgram::initialize");
3177 program
->Initialize(
3178 output_surface_
->context_provider(), precision
, SamplerTypeExternalOES
);
3183 void GLRenderer::CleanupSharedObjects() {
3184 shared_geometry_
= nullptr;
3186 for (int i
= 0; i
< NumTexCoordPrecisions
; ++i
) {
3187 for (int j
= 0; j
< NumSamplerTypes
; ++j
) {
3188 tile_program_
[i
][j
].Cleanup(gl_
);
3189 tile_program_opaque_
[i
][j
].Cleanup(gl_
);
3190 tile_program_swizzle_
[i
][j
].Cleanup(gl_
);
3191 tile_program_swizzle_opaque_
[i
][j
].Cleanup(gl_
);
3192 tile_program_aa_
[i
][j
].Cleanup(gl_
);
3193 tile_program_swizzle_aa_
[i
][j
].Cleanup(gl_
);
3195 for (int k
= 0; k
< NumBlendModes
; k
++) {
3196 render_pass_mask_program_
[i
][j
][k
].Cleanup(gl_
);
3197 render_pass_mask_program_aa_
[i
][j
][k
].Cleanup(gl_
);
3198 render_pass_mask_color_matrix_program_aa_
[i
][j
][k
].Cleanup(gl_
);
3199 render_pass_mask_color_matrix_program_
[i
][j
][k
].Cleanup(gl_
);
3202 for (int j
= 0; j
< NumBlendModes
; j
++) {
3203 render_pass_program_
[i
][j
].Cleanup(gl_
);
3204 render_pass_program_aa_
[i
][j
].Cleanup(gl_
);
3205 render_pass_color_matrix_program_
[i
][j
].Cleanup(gl_
);
3206 render_pass_color_matrix_program_aa_
[i
][j
].Cleanup(gl_
);
3209 texture_program_
[i
].Cleanup(gl_
);
3210 nonpremultiplied_texture_program_
[i
].Cleanup(gl_
);
3211 texture_background_program_
[i
].Cleanup(gl_
);
3212 nonpremultiplied_texture_background_program_
[i
].Cleanup(gl_
);
3213 texture_io_surface_program_
[i
].Cleanup(gl_
);
3215 video_yuv_program_
[i
].Cleanup(gl_
);
3216 video_yuva_program_
[i
].Cleanup(gl_
);
3217 video_stream_texture_program_
[i
].Cleanup(gl_
);
3220 tile_checkerboard_program_
.Cleanup(gl_
);
3222 debug_border_program_
.Cleanup(gl_
);
3223 solid_color_program_
.Cleanup(gl_
);
3224 solid_color_program_aa_
.Cleanup(gl_
);
3226 if (offscreen_framebuffer_id_
)
3227 GLC(gl_
, gl_
->DeleteFramebuffers(1, &offscreen_framebuffer_id_
));
3229 if (on_demand_tile_raster_resource_id_
)
3230 resource_provider_
->DeleteResource(on_demand_tile_raster_resource_id_
);
3232 ReleaseRenderPassTextures();
3235 void GLRenderer::ReinitializeGLState() {
3236 is_scissor_enabled_
= false;
3237 scissor_rect_needs_reset_
= true;
3238 stencil_shadow_
= false;
3239 blend_shadow_
= true;
3240 program_shadow_
= 0;
3245 void GLRenderer::RestoreGLState() {
3246 // This restores the current GLRenderer state to the GL context.
3248 shared_geometry_
->PrepareForDraw();
3250 GLC(gl_
, gl_
->Disable(GL_DEPTH_TEST
));
3251 GLC(gl_
, gl_
->Disable(GL_CULL_FACE
));
3252 GLC(gl_
, gl_
->ColorMask(true, true, true, true));
3253 GLC(gl_
, gl_
->BlendFunc(GL_ONE
, GL_ONE_MINUS_SRC_ALPHA
));
3254 GLC(gl_
, gl_
->ActiveTexture(GL_TEXTURE0
));
3256 if (program_shadow_
)
3257 gl_
->UseProgram(program_shadow_
);
3259 if (stencil_shadow_
)
3260 GLC(gl_
, gl_
->Enable(GL_STENCIL_TEST
));
3262 GLC(gl_
, gl_
->Disable(GL_STENCIL_TEST
));
3265 GLC(gl_
, gl_
->Enable(GL_BLEND
));
3267 GLC(gl_
, gl_
->Disable(GL_BLEND
));
3269 if (is_scissor_enabled_
) {
3270 GLC(gl_
, gl_
->Enable(GL_SCISSOR_TEST
));
3272 gl_
->Scissor(scissor_rect_
.x(),
3274 scissor_rect_
.width(),
3275 scissor_rect_
.height()));
3277 GLC(gl_
, gl_
->Disable(GL_SCISSOR_TEST
));
3281 void GLRenderer::RestoreFramebuffer(DrawingFrame
* frame
) {
3282 UseRenderPass(frame
, frame
->current_render_pass
);
3285 bool GLRenderer::IsContextLost() {
3286 return output_surface_
->context_provider()->IsContextLost();
3289 void GLRenderer::ScheduleOverlays(DrawingFrame
* frame
) {
3290 if (!frame
->overlay_list
.size())
3293 ResourceProvider::ResourceIdArray resources
;
3294 OverlayCandidateList
& overlays
= frame
->overlay_list
;
3295 OverlayCandidateList::iterator it
;
3296 for (it
= overlays
.begin(); it
!= overlays
.end(); ++it
) {
3297 const OverlayCandidate
& overlay
= *it
;
3298 // Skip primary plane.
3299 if (overlay
.plane_z_order
== 0)
3302 pending_overlay_resources_
.push_back(
3303 make_scoped_ptr(new ResourceProvider::ScopedReadLockGL(
3304 resource_provider_
, overlay
.resource_id
)));
3306 context_support_
->ScheduleOverlayPlane(
3307 overlay
.plane_z_order
,
3309 pending_overlay_resources_
.back()->texture_id(),
3310 overlay
.display_rect
,