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/debug/trace_event.h"
14 #include "base/logging.h"
15 #include "cc/base/math_util.h"
16 #include "cc/layers/video_layer_impl.h"
17 #include "cc/output/compositor_frame.h"
18 #include "cc/output/compositor_frame_metadata.h"
19 #include "cc/output/context_provider.h"
20 #include "cc/output/copy_output_request.h"
21 #include "cc/output/geometry_binding.h"
22 #include "cc/output/gl_frame_data.h"
23 #include "cc/output/output_surface.h"
24 #include "cc/output/render_surface_filters.h"
25 #include "cc/quads/picture_draw_quad.h"
26 #include "cc/quads/render_pass.h"
27 #include "cc/quads/stream_video_draw_quad.h"
28 #include "cc/quads/texture_draw_quad.h"
29 #include "cc/resources/layer_quad.h"
30 #include "cc/resources/scoped_resource.h"
31 #include "cc/resources/texture_mailbox_deleter.h"
32 #include "gpu/GLES2/gl2extchromium.h"
33 #include "gpu/command_buffer/client/context_support.h"
34 #include "gpu/command_buffer/client/gles2_interface.h"
35 #include "gpu/command_buffer/common/gpu_memory_allocation.h"
36 #include "third_party/skia/include/core/SkBitmap.h"
37 #include "third_party/skia/include/core/SkColor.h"
38 #include "third_party/skia/include/core/SkColorFilter.h"
39 #include "third_party/skia/include/core/SkImage.h"
40 #include "third_party/skia/include/core/SkSurface.h"
41 #include "third_party/skia/include/gpu/GrContext.h"
42 #include "third_party/skia/include/gpu/GrTexture.h"
43 #include "third_party/skia/include/gpu/SkGrTexturePixelRef.h"
44 #include "third_party/skia/include/gpu/gl/GrGLInterface.h"
45 #include "ui/gfx/geometry/quad_f.h"
46 #include "ui/gfx/geometry/rect_conversions.h"
48 using gpu::gles2::GLES2Interface
;
53 class FallbackFence
: public ResourceProvider::Fence
{
55 explicit FallbackFence(gpu::gles2::GLES2Interface
* gl
)
56 : gl_(gl
), has_passed_(true) {}
58 // Overridden from ResourceProvider::Fence:
59 virtual void Set() OVERRIDE
{ has_passed_
= false; }
60 virtual bool HasPassed() OVERRIDE
{
69 virtual ~FallbackFence() {}
72 TRACE_EVENT0("cc", "FallbackFence::Synchronize");
76 gpu::gles2::GLES2Interface
* gl_
;
79 DISALLOW_COPY_AND_ASSIGN(FallbackFence
);
82 bool NeedsIOSurfaceReadbackWorkaround() {
83 #if defined(OS_MACOSX)
84 // This isn't strictly required in DumpRenderTree-mode when Mesa is used,
85 // but it doesn't seem to hurt.
92 Float4
UVTransform(const TextureDrawQuad
* quad
) {
93 gfx::PointF uv0
= quad
->uv_top_left
;
94 gfx::PointF uv1
= quad
->uv_bottom_right
;
95 Float4 xform
= {{uv0
.x(), uv0
.y(), uv1
.x() - uv0
.x(), uv1
.y() - uv0
.y()}};
97 xform
.data
[1] = 1.0f
- xform
.data
[1];
98 xform
.data
[3] = -xform
.data
[3];
103 Float4
PremultipliedColor(SkColor color
) {
104 const float factor
= 1.0f
/ 255.0f
;
105 const float alpha
= SkColorGetA(color
) * factor
;
108 {SkColorGetR(color
) * factor
* alpha
, SkColorGetG(color
) * factor
* alpha
,
109 SkColorGetB(color
) * factor
* alpha
, alpha
}};
113 SamplerType
SamplerTypeFromTextureTarget(GLenum target
) {
116 return SamplerType2D
;
117 case GL_TEXTURE_RECTANGLE_ARB
:
118 return SamplerType2DRect
;
119 case GL_TEXTURE_EXTERNAL_OES
:
120 return SamplerTypeExternalOES
;
123 return SamplerType2D
;
127 // Smallest unit that impact anti-aliasing output. We use this to
128 // determine when anti-aliasing is unnecessary.
129 const float kAntiAliasingEpsilon
= 1.0f
/ 1024.0f
;
131 // Block or crash if the number of pending sync queries reach this high as
132 // something is seriously wrong on the service side if this happens.
133 const size_t kMaxPendingSyncQueries
= 16;
135 } // anonymous namespace
137 static GLint
GetActiveTextureUnit(GLES2Interface
* gl
) {
138 GLint active_unit
= 0;
139 gl
->GetIntegerv(GL_ACTIVE_TEXTURE
, &active_unit
);
143 class GLRenderer::ScopedUseGrContext
{
145 static scoped_ptr
<ScopedUseGrContext
> Create(GLRenderer
* renderer
,
146 DrawingFrame
* frame
) {
147 if (!renderer
->output_surface_
->context_provider()->GrContext())
148 return scoped_ptr
<ScopedUseGrContext
>();
149 return make_scoped_ptr(new ScopedUseGrContext(renderer
, frame
));
152 ~ScopedUseGrContext() { PassControlToGLRenderer(); }
154 GrContext
* context() const {
155 return renderer_
->output_surface_
->context_provider()->GrContext();
159 ScopedUseGrContext(GLRenderer
* renderer
, DrawingFrame
* frame
)
160 : renderer_(renderer
), frame_(frame
) {
164 void PassControlToSkia() { context()->resetContext(); }
166 void PassControlToGLRenderer() {
167 renderer_
->RestoreGLState();
168 renderer_
->RestoreFramebuffer(frame_
);
171 GLRenderer
* renderer_
;
172 DrawingFrame
* frame_
;
174 DISALLOW_COPY_AND_ASSIGN(ScopedUseGrContext
);
177 struct GLRenderer::PendingAsyncReadPixels
{
178 PendingAsyncReadPixels() : buffer(0) {}
180 scoped_ptr
<CopyOutputRequest
> copy_request
;
181 base::CancelableClosure finished_read_pixels_callback
;
185 DISALLOW_COPY_AND_ASSIGN(PendingAsyncReadPixels
);
188 class GLRenderer::SyncQuery
{
190 explicit SyncQuery(gpu::gles2::GLES2Interface
* gl
)
191 : gl_(gl
), query_id_(0u), is_pending_(false), weak_ptr_factory_(this) {
192 gl_
->GenQueriesEXT(1, &query_id_
);
194 virtual ~SyncQuery() { gl_
->DeleteQueriesEXT(1, &query_id_
); }
196 scoped_refptr
<ResourceProvider::Fence
> Begin() {
197 DCHECK(!IsPending());
198 // Invalidate weak pointer held by old fence.
199 weak_ptr_factory_
.InvalidateWeakPtrs();
200 // Note: In case the set of drawing commands issued before End() do not
201 // depend on the query, defer BeginQueryEXT call until Set() is called and
202 // query is required.
203 return make_scoped_refptr
<ResourceProvider::Fence
>(
204 new Fence(weak_ptr_factory_
.GetWeakPtr()));
211 // Note: BeginQueryEXT on GL_COMMANDS_COMPLETED_CHROMIUM is effectively a
212 // noop relative to GL, so it doesn't matter where it happens but we still
213 // make sure to issue this command when Set() is called (prior to issuing
214 // any drawing commands that depend on query), in case some future extension
215 // can take advantage of this.
216 gl_
->BeginQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM
, query_id_
);
224 gl_
->EndQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM
);
231 unsigned result_available
= 1;
232 gl_
->GetQueryObjectuivEXT(
233 query_id_
, GL_QUERY_RESULT_AVAILABLE_EXT
, &result_available
);
234 is_pending_
= !result_available
;
243 gl_
->GetQueryObjectuivEXT(query_id_
, GL_QUERY_RESULT_EXT
, &result
);
248 class Fence
: public ResourceProvider::Fence
{
250 explicit Fence(base::WeakPtr
<GLRenderer::SyncQuery
> query
)
253 // Overridden from ResourceProvider::Fence:
254 virtual void Set() OVERRIDE
{
258 virtual bool HasPassed() OVERRIDE
{
259 return !query_
|| !query_
->IsPending();
265 base::WeakPtr
<SyncQuery
> query_
;
267 DISALLOW_COPY_AND_ASSIGN(Fence
);
270 gpu::gles2::GLES2Interface
* gl_
;
273 base::WeakPtrFactory
<SyncQuery
> weak_ptr_factory_
;
275 DISALLOW_COPY_AND_ASSIGN(SyncQuery
);
278 scoped_ptr
<GLRenderer
> GLRenderer::Create(
279 RendererClient
* client
,
280 const LayerTreeSettings
* settings
,
281 OutputSurface
* output_surface
,
282 ResourceProvider
* resource_provider
,
283 TextureMailboxDeleter
* texture_mailbox_deleter
,
284 int highp_threshold_min
) {
285 return make_scoped_ptr(new GLRenderer(client
,
289 texture_mailbox_deleter
,
290 highp_threshold_min
));
293 GLRenderer::GLRenderer(RendererClient
* client
,
294 const LayerTreeSettings
* settings
,
295 OutputSurface
* output_surface
,
296 ResourceProvider
* resource_provider
,
297 TextureMailboxDeleter
* texture_mailbox_deleter
,
298 int highp_threshold_min
)
299 : DirectRenderer(client
, settings
, output_surface
, resource_provider
),
300 offscreen_framebuffer_id_(0),
301 shared_geometry_quad_(QuadVertexRect()),
302 gl_(output_surface
->context_provider()->ContextGL()),
303 context_support_(output_surface
->context_provider()->ContextSupport()),
304 texture_mailbox_deleter_(texture_mailbox_deleter
),
305 is_backbuffer_discarded_(false),
306 is_scissor_enabled_(false),
307 scissor_rect_needs_reset_(true),
308 stencil_shadow_(false),
309 blend_shadow_(false),
310 highp_threshold_min_(highp_threshold_min
),
311 highp_threshold_cache_(0),
312 use_sync_query_(false),
313 on_demand_tile_raster_resource_id_(0) {
315 DCHECK(context_support_
);
317 ContextProvider::Capabilities context_caps
=
318 output_surface_
->context_provider()->ContextCapabilities();
320 capabilities_
.using_partial_swap
=
321 settings_
->partial_swap_enabled
&& context_caps
.gpu
.post_sub_buffer
;
323 DCHECK(!context_caps
.gpu
.iosurface
|| context_caps
.gpu
.texture_rectangle
);
325 capabilities_
.using_egl_image
= context_caps
.gpu
.egl_image_external
;
327 capabilities_
.max_texture_size
= resource_provider_
->max_texture_size();
328 capabilities_
.best_texture_format
= resource_provider_
->best_texture_format();
330 // The updater can access textures while the GLRenderer is using them.
331 capabilities_
.allow_partial_texture_updates
= true;
333 capabilities_
.using_map_image
= context_caps
.gpu
.map_image
;
335 capabilities_
.using_discard_framebuffer
=
336 context_caps
.gpu
.discard_framebuffer
;
338 capabilities_
.allow_rasterize_on_demand
= true;
340 use_sync_query_
= context_caps
.gpu
.sync_query
;
342 InitializeSharedObjects();
345 GLRenderer::~GLRenderer() {
346 while (!pending_async_read_pixels_
.empty()) {
347 PendingAsyncReadPixels
* pending_read
= pending_async_read_pixels_
.back();
348 pending_read
->finished_read_pixels_callback
.Cancel();
349 pending_async_read_pixels_
.pop_back();
352 in_use_overlay_resources_
.clear();
354 CleanupSharedObjects();
357 const RendererCapabilitiesImpl
& GLRenderer::Capabilities() const {
358 return capabilities_
;
361 void GLRenderer::DebugGLCall(GLES2Interface
* gl
,
365 GLuint error
= gl
->GetError();
366 if (error
!= GL_NO_ERROR
)
367 LOG(ERROR
) << "GL command failed: File: " << file
<< "\n\tLine " << line
368 << "\n\tcommand: " << command
<< ", error "
369 << static_cast<int>(error
) << "\n";
372 void GLRenderer::DidChangeVisibility() {
373 EnforceMemoryPolicy();
375 context_support_
->SetSurfaceVisible(visible());
378 void GLRenderer::ReleaseRenderPassTextures() { render_pass_textures_
.clear(); }
380 void GLRenderer::DiscardPixels(bool has_external_stencil_test
,
381 bool draw_rect_covers_full_surface
) {
382 if (has_external_stencil_test
|| !draw_rect_covers_full_surface
||
383 !capabilities_
.using_discard_framebuffer
)
385 bool using_default_framebuffer
=
386 !current_framebuffer_lock_
&&
387 output_surface_
->capabilities().uses_default_gl_framebuffer
;
388 GLenum attachments
[] = {static_cast<GLenum
>(
389 using_default_framebuffer
? GL_COLOR_EXT
: GL_COLOR_ATTACHMENT0_EXT
)};
390 gl_
->DiscardFramebufferEXT(
391 GL_FRAMEBUFFER
, arraysize(attachments
), attachments
);
394 void GLRenderer::ClearFramebuffer(DrawingFrame
* frame
,
395 bool has_external_stencil_test
) {
396 // It's unsafe to clear when we have a stencil test because glClear ignores
398 if (has_external_stencil_test
) {
399 DCHECK(!frame
->current_render_pass
->has_transparent_background
);
403 // On DEBUG builds, opaque render passes are cleared to blue to easily see
404 // regions that were not drawn on the screen.
405 if (frame
->current_render_pass
->has_transparent_background
)
406 GLC(gl_
, gl_
->ClearColor(0, 0, 0, 0));
408 GLC(gl_
, gl_
->ClearColor(0, 0, 1, 1));
410 bool always_clear
= false;
414 if (always_clear
|| frame
->current_render_pass
->has_transparent_background
) {
415 GLbitfield clear_bits
= GL_COLOR_BUFFER_BIT
;
417 clear_bits
|= GL_STENCIL_BUFFER_BIT
;
418 gl_
->Clear(clear_bits
);
422 static ResourceProvider::ResourceId
WaitOnResourceSyncPoints(
423 ResourceProvider
* resource_provider
,
424 ResourceProvider::ResourceId resource_id
) {
425 resource_provider
->WaitSyncPointIfNeeded(resource_id
);
429 void GLRenderer::BeginDrawingFrame(DrawingFrame
* frame
) {
430 if (frame
->device_viewport_rect
.IsEmpty())
433 TRACE_EVENT0("cc", "GLRenderer::BeginDrawingFrame");
435 scoped_refptr
<ResourceProvider::Fence
> read_lock_fence
;
436 if (use_sync_query_
) {
437 // Block until oldest sync query has passed if the number of pending queries
438 // ever reach kMaxPendingSyncQueries.
439 if (pending_sync_queries_
.size() >= kMaxPendingSyncQueries
) {
440 LOG(ERROR
) << "Reached limit of pending sync queries.";
442 pending_sync_queries_
.front()->Wait();
443 DCHECK(!pending_sync_queries_
.front()->IsPending());
446 while (!pending_sync_queries_
.empty()) {
447 if (pending_sync_queries_
.front()->IsPending())
450 available_sync_queries_
.push_back(pending_sync_queries_
.take_front());
453 current_sync_query_
= available_sync_queries_
.empty()
454 ? make_scoped_ptr(new SyncQuery(gl_
))
455 : available_sync_queries_
.take_front();
457 read_lock_fence
= current_sync_query_
->Begin();
459 read_lock_fence
= make_scoped_refptr(new FallbackFence(gl_
));
461 resource_provider_
->SetReadLockFence(read_lock_fence
.get());
463 // Insert WaitSyncPointCHROMIUM on quad resources prior to drawing the frame,
464 // so that drawing can proceed without GL context switching interruptions.
465 DrawQuad::ResourceIteratorCallback wait_on_resource_syncpoints_callback
=
466 base::Bind(&WaitOnResourceSyncPoints
, resource_provider_
);
468 for (size_t i
= 0; i
< frame
->render_passes_in_draw_order
->size(); ++i
) {
469 RenderPass
* pass
= frame
->render_passes_in_draw_order
->at(i
);
470 for (size_t j
= 0; j
< pass
->quad_list
.size(); ++j
) {
471 DrawQuad
* quad
= pass
->quad_list
[j
];
472 quad
->IterateResources(wait_on_resource_syncpoints_callback
);
476 // TODO(enne): Do we need to reinitialize all of this state per frame?
477 ReinitializeGLState();
480 void GLRenderer::DoNoOp() {
481 GLC(gl_
, gl_
->BindFramebuffer(GL_FRAMEBUFFER
, 0));
482 GLC(gl_
, gl_
->Flush());
485 void GLRenderer::DoDrawQuad(DrawingFrame
* frame
, const DrawQuad
* quad
) {
486 DCHECK(quad
->rect
.Contains(quad
->visible_rect
));
487 if (quad
->material
!= DrawQuad::TEXTURE_CONTENT
) {
488 FlushTextureQuadCache();
491 switch (quad
->material
) {
492 case DrawQuad::INVALID
:
495 case DrawQuad::CHECKERBOARD
:
496 DrawCheckerboardQuad(frame
, CheckerboardDrawQuad::MaterialCast(quad
));
498 case DrawQuad::DEBUG_BORDER
:
499 DrawDebugBorderQuad(frame
, DebugBorderDrawQuad::MaterialCast(quad
));
501 case DrawQuad::IO_SURFACE_CONTENT
:
502 DrawIOSurfaceQuad(frame
, IOSurfaceDrawQuad::MaterialCast(quad
));
504 case DrawQuad::PICTURE_CONTENT
:
505 DrawPictureQuad(frame
, PictureDrawQuad::MaterialCast(quad
));
507 case DrawQuad::RENDER_PASS
:
508 DrawRenderPassQuad(frame
, RenderPassDrawQuad::MaterialCast(quad
));
510 case DrawQuad::SOLID_COLOR
:
511 DrawSolidColorQuad(frame
, SolidColorDrawQuad::MaterialCast(quad
));
513 case DrawQuad::STREAM_VIDEO_CONTENT
:
514 DrawStreamVideoQuad(frame
, StreamVideoDrawQuad::MaterialCast(quad
));
516 case DrawQuad::SURFACE_CONTENT
:
517 // Surface content should be fully resolved to other quad types before
518 // reaching a direct renderer.
521 case DrawQuad::TEXTURE_CONTENT
:
522 EnqueueTextureQuad(frame
, TextureDrawQuad::MaterialCast(quad
));
524 case DrawQuad::TILED_CONTENT
:
525 DrawTileQuad(frame
, TileDrawQuad::MaterialCast(quad
));
527 case DrawQuad::YUV_VIDEO_CONTENT
:
528 DrawYUVVideoQuad(frame
, YUVVideoDrawQuad::MaterialCast(quad
));
533 void GLRenderer::DrawCheckerboardQuad(const DrawingFrame
* frame
,
534 const CheckerboardDrawQuad
* quad
) {
535 SetBlendEnabled(quad
->ShouldDrawWithBlending());
537 const TileCheckerboardProgram
* program
= GetTileCheckerboardProgram();
538 DCHECK(program
&& (program
->initialized() || IsContextLost()));
539 SetUseProgram(program
->program());
541 SkColor color
= quad
->color
;
543 gl_
->Uniform4f(program
->fragment_shader().color_location(),
544 SkColorGetR(color
) * (1.0f
/ 255.0f
),
545 SkColorGetG(color
) * (1.0f
/ 255.0f
),
546 SkColorGetB(color
) * (1.0f
/ 255.0f
),
549 const int checkerboard_width
= 16;
550 float frequency
= 1.0f
/ checkerboard_width
;
552 gfx::Rect tile_rect
= quad
->rect
;
553 float tex_offset_x
= tile_rect
.x() % checkerboard_width
;
554 float tex_offset_y
= tile_rect
.y() % checkerboard_width
;
555 float tex_scale_x
= tile_rect
.width();
556 float tex_scale_y
= tile_rect
.height();
558 gl_
->Uniform4f(program
->fragment_shader().tex_transform_location(),
565 gl_
->Uniform1f(program
->fragment_shader().frequency_location(),
568 SetShaderOpacity(quad
->opacity(),
569 program
->fragment_shader().alpha_location());
570 DrawQuadGeometry(frame
,
571 quad
->quadTransform(),
573 program
->vertex_shader().matrix_location());
576 void GLRenderer::DrawDebugBorderQuad(const DrawingFrame
* frame
,
577 const DebugBorderDrawQuad
* quad
) {
578 SetBlendEnabled(quad
->ShouldDrawWithBlending());
580 static float gl_matrix
[16];
581 const DebugBorderProgram
* program
= GetDebugBorderProgram();
582 DCHECK(program
&& (program
->initialized() || IsContextLost()));
583 SetUseProgram(program
->program());
585 // Use the full quad_rect for debug quads to not move the edges based on
587 gfx::Rect layer_rect
= quad
->rect
;
588 gfx::Transform render_matrix
;
589 QuadRectTransform(&render_matrix
, quad
->quadTransform(), layer_rect
);
590 GLRenderer::ToGLMatrix(&gl_matrix
[0],
591 frame
->projection_matrix
* render_matrix
);
593 gl_
->UniformMatrix4fv(
594 program
->vertex_shader().matrix_location(), 1, false, &gl_matrix
[0]));
596 SkColor color
= quad
->color
;
597 float alpha
= SkColorGetA(color
) * (1.0f
/ 255.0f
);
600 gl_
->Uniform4f(program
->fragment_shader().color_location(),
601 (SkColorGetR(color
) * (1.0f
/ 255.0f
)) * alpha
,
602 (SkColorGetG(color
) * (1.0f
/ 255.0f
)) * alpha
,
603 (SkColorGetB(color
) * (1.0f
/ 255.0f
)) * alpha
,
606 GLC(gl_
, gl_
->LineWidth(quad
->width
));
608 // The indices for the line are stored in the same array as the triangle
610 GLC(gl_
, gl_
->DrawElements(GL_LINE_LOOP
, 4, GL_UNSIGNED_SHORT
, 0));
613 static skia::RefPtr
<SkImage
> ApplyImageFilter(
614 scoped_ptr
<GLRenderer::ScopedUseGrContext
> use_gr_context
,
615 ResourceProvider
* resource_provider
,
616 const gfx::Point
& origin
,
617 const gfx::Vector2dF
& scale
,
618 SkImageFilter
* filter
,
619 ScopedResource
* source_texture_resource
) {
621 return skia::RefPtr
<SkImage
>();
624 return skia::RefPtr
<SkImage
>();
626 ResourceProvider::ScopedReadLockGL
lock(resource_provider
,
627 source_texture_resource
->id());
629 // Wrap the source texture in a Ganesh platform texture.
630 GrBackendTextureDesc backend_texture_description
;
631 backend_texture_description
.fWidth
= source_texture_resource
->size().width();
632 backend_texture_description
.fHeight
=
633 source_texture_resource
->size().height();
634 backend_texture_description
.fConfig
= kSkia8888_GrPixelConfig
;
635 backend_texture_description
.fTextureHandle
= lock
.texture_id();
636 backend_texture_description
.fOrigin
= kBottomLeft_GrSurfaceOrigin
;
637 skia::RefPtr
<GrTexture
> texture
=
638 skia::AdoptRef(use_gr_context
->context()->wrapBackendTexture(
639 backend_texture_description
));
642 SkImageInfo::MakeN32Premul(source_texture_resource
->size().width(),
643 source_texture_resource
->size().height());
644 // Place the platform texture inside an SkBitmap.
646 source
.setInfo(info
);
647 skia::RefPtr
<SkGrPixelRef
> pixel_ref
=
648 skia::AdoptRef(new SkGrPixelRef(info
, texture
.get()));
649 source
.setPixelRef(pixel_ref
.get());
651 // Create a scratch texture for backing store.
653 desc
.fFlags
= kRenderTarget_GrTextureFlagBit
| kNoStencil_GrTextureFlagBit
;
655 desc
.fWidth
= source
.width();
656 desc
.fHeight
= source
.height();
657 desc
.fConfig
= kSkia8888_GrPixelConfig
;
658 desc
.fOrigin
= kBottomLeft_GrSurfaceOrigin
;
659 GrAutoScratchTexture
scratch_texture(
660 use_gr_context
->context(), desc
, GrContext::kExact_ScratchTexMatch
);
661 skia::RefPtr
<GrTexture
> backing_store
=
662 skia::AdoptRef(scratch_texture
.detach());
663 if (backing_store
.get() == NULL
) {
664 TRACE_EVENT_INSTANT0("cc",
665 "ApplyImageFilter scratch texture allocation failed",
666 TRACE_EVENT_SCOPE_THREAD
);
667 return skia::RefPtr
<SkImage
>();
670 // Create surface to draw into.
671 skia::RefPtr
<SkSurface
> surface
= skia::AdoptRef(
672 SkSurface::NewRenderTargetDirect(backing_store
->asRenderTarget()));
673 skia::RefPtr
<SkCanvas
> canvas
= skia::SharePtr(surface
->getCanvas());
675 // Draw the source bitmap through the filter to the canvas.
677 paint
.setImageFilter(filter
);
678 canvas
->clear(SK_ColorTRANSPARENT
);
680 canvas
->translate(SkIntToScalar(-origin
.x()), SkIntToScalar(-origin
.y()));
681 canvas
->scale(scale
.x(), scale
.y());
682 canvas
->drawSprite(source
, 0, 0, &paint
);
684 skia::RefPtr
<SkImage
> image
= skia::AdoptRef(surface
->newImageSnapshot());
685 if (!image
|| !image
->getTexture()) {
686 return skia::RefPtr
<SkImage
>();
689 // Flush the GrContext to ensure all buffered GL calls are drawn to the
690 // backing store before we access and return it, and have cc begin using the
697 static skia::RefPtr
<SkImage
> ApplyBlendModeWithBackdrop(
698 scoped_ptr
<GLRenderer::ScopedUseGrContext
> use_gr_context
,
699 ResourceProvider
* resource_provider
,
700 skia::RefPtr
<SkImage
> source_bitmap_with_filters
,
701 ScopedResource
* source_texture_resource
,
702 ScopedResource
* background_texture_resource
,
703 SkXfermode::Mode blend_mode
) {
705 return source_bitmap_with_filters
;
707 DCHECK(background_texture_resource
);
708 DCHECK(source_texture_resource
);
710 gfx::Size source_size
= source_texture_resource
->size();
711 gfx::Size background_size
= background_texture_resource
->size();
713 DCHECK_LE(background_size
.width(), source_size
.width());
714 DCHECK_LE(background_size
.height(), source_size
.height());
716 int source_texture_with_filters_id
;
717 scoped_ptr
<ResourceProvider::ScopedReadLockGL
> lock
;
718 if (source_bitmap_with_filters
) {
719 DCHECK_EQ(source_size
.width(), source_bitmap_with_filters
->width());
720 DCHECK_EQ(source_size
.height(), source_bitmap_with_filters
->height());
722 reinterpret_cast<GrTexture
*>(source_bitmap_with_filters
->getTexture());
723 source_texture_with_filters_id
= texture
->getTextureHandle();
725 lock
.reset(new ResourceProvider::ScopedReadLockGL(
726 resource_provider
, source_texture_resource
->id()));
727 source_texture_with_filters_id
= lock
->texture_id();
730 ResourceProvider::ScopedReadLockGL
lock_background(
731 resource_provider
, background_texture_resource
->id());
733 // Wrap the source texture in a Ganesh platform texture.
734 GrBackendTextureDesc backend_texture_description
;
735 backend_texture_description
.fConfig
= kSkia8888_GrPixelConfig
;
736 backend_texture_description
.fOrigin
= kBottomLeft_GrSurfaceOrigin
;
738 backend_texture_description
.fWidth
= source_size
.width();
739 backend_texture_description
.fHeight
= source_size
.height();
740 backend_texture_description
.fTextureHandle
= source_texture_with_filters_id
;
741 skia::RefPtr
<GrTexture
> source_texture
=
742 skia::AdoptRef(use_gr_context
->context()->wrapBackendTexture(
743 backend_texture_description
));
745 backend_texture_description
.fWidth
= background_size
.width();
746 backend_texture_description
.fHeight
= background_size
.height();
747 backend_texture_description
.fTextureHandle
= lock_background
.texture_id();
748 skia::RefPtr
<GrTexture
> background_texture
=
749 skia::AdoptRef(use_gr_context
->context()->wrapBackendTexture(
750 backend_texture_description
));
752 SkImageInfo source_info
=
753 SkImageInfo::MakeN32Premul(source_size
.width(), source_size
.height());
754 // Place the platform texture inside an SkBitmap.
756 source
.setInfo(source_info
);
757 skia::RefPtr
<SkGrPixelRef
> source_pixel_ref
=
758 skia::AdoptRef(new SkGrPixelRef(source_info
, source_texture
.get()));
759 source
.setPixelRef(source_pixel_ref
.get());
761 SkImageInfo background_info
= SkImageInfo::MakeN32Premul(
762 background_size
.width(), background_size
.height());
765 background
.setInfo(background_info
);
766 skia::RefPtr
<SkGrPixelRef
> background_pixel_ref
=
767 skia::AdoptRef(new SkGrPixelRef(
768 background_info
, background_texture
.get()));
769 background
.setPixelRef(background_pixel_ref
.get());
771 // Create a scratch texture for backing store.
773 desc
.fFlags
= kRenderTarget_GrTextureFlagBit
| kNoStencil_GrTextureFlagBit
;
775 desc
.fWidth
= source
.width();
776 desc
.fHeight
= source
.height();
777 desc
.fConfig
= kSkia8888_GrPixelConfig
;
778 desc
.fOrigin
= kBottomLeft_GrSurfaceOrigin
;
779 GrAutoScratchTexture
scratch_texture(
780 use_gr_context
->context(), desc
, GrContext::kExact_ScratchTexMatch
);
781 skia::RefPtr
<GrTexture
> backing_store
=
782 skia::AdoptRef(scratch_texture
.detach());
783 if (backing_store
.get() == NULL
) {
784 TRACE_EVENT_INSTANT0(
786 "ApplyBlendModeWithBackdrop scratch texture allocation failed",
787 TRACE_EVENT_SCOPE_THREAD
);
788 return source_bitmap_with_filters
;
791 // Create a device and canvas using that backing store.
792 skia::RefPtr
<SkSurface
> surface
= skia::AdoptRef(
793 SkSurface::NewRenderTargetDirect(backing_store
->asRenderTarget()));
795 return skia::RefPtr
<SkImage
>();
796 skia::RefPtr
<SkCanvas
> canvas
= skia::SharePtr(surface
->getCanvas());
798 // Draw the source bitmap through the filter to the canvas.
799 canvas
->clear(SK_ColorTRANSPARENT
);
800 canvas
->drawSprite(background
, 0, 0);
802 paint
.setXfermodeMode(blend_mode
);
803 canvas
->drawSprite(source
, 0, 0, &paint
);
805 skia::RefPtr
<SkImage
> image
= skia::AdoptRef(surface
->newImageSnapshot());
806 if (!image
|| !image
->getTexture()) {
807 return skia::RefPtr
<SkImage
>();
810 // Flush the GrContext to ensure all buffered GL calls are drawn to the
811 // backing store before we access and return it, and have cc begin using the
818 scoped_ptr
<ScopedResource
> GLRenderer::GetBackgroundWithFilters(
820 const RenderPassDrawQuad
* quad
,
821 const gfx::Transform
& contents_device_transform
,
822 const gfx::Transform
& contents_device_transform_inverse
,
823 bool* background_changed
) {
824 // This method draws a background filter, which applies a filter to any pixels
825 // behind the quad and seen through its background. The algorithm works as
827 // 1. Compute a bounding box around the pixels that will be visible through
829 // 2. Read the pixels in the bounding box into a buffer R.
830 // 3. Apply the background filter to R, so that it is applied in the pixels'
832 // 4. Apply the quad's inverse transform to map the pixels in R into the
833 // quad's content space. This implicitly clips R by the content bounds of the
834 // quad since the destination texture has bounds matching the quad's content.
835 // 5. Draw the background texture for the contents using the same transform as
836 // used to draw the contents itself. This is done without blending to replace
837 // the current background pixels with the new filtered background.
838 // 6. Draw the contents of the quad over drop of the new background with
839 // blending, as per usual. The filtered background pixels will show through
840 // any non-opaque pixels in this draws.
842 // Pixel copies in this algorithm occur at steps 2, 3, 4, and 5.
844 // TODO(danakj): When this algorithm changes, update
845 // LayerTreeHost::PrioritizeTextures() accordingly.
847 // TODO(danakj): We only allow background filters on an opaque render surface
848 // because other surfaces may contain translucent pixels, and the contents
849 // behind those translucent pixels wouldn't have the filter applied.
850 bool apply_background_filters
=
851 !frame
->current_render_pass
->has_transparent_background
;
852 DCHECK(!frame
->current_texture
);
854 // TODO(ajuma): Add support for reference filters once
855 // FilterOperations::GetOutsets supports reference filters.
856 if (apply_background_filters
&& quad
->background_filters
.HasReferenceFilter())
857 apply_background_filters
= false;
859 // TODO(danakj): Do a single readback for both the surface and replica and
860 // cache the filtered results (once filter textures are not reused).
861 gfx::Rect window_rect
= gfx::ToEnclosingRect(MathUtil::MapClippedRect(
862 contents_device_transform
, SharedGeometryQuad().BoundingBox()));
864 int top
, right
, bottom
, left
;
865 quad
->background_filters
.GetOutsets(&top
, &right
, &bottom
, &left
);
866 window_rect
.Inset(-left
, -top
, -right
, -bottom
);
868 window_rect
.Intersect(
869 MoveFromDrawToWindowSpace(frame
->current_render_pass
->output_rect
));
871 scoped_ptr
<ScopedResource
> device_background_texture
=
872 ScopedResource::Create(resource_provider_
);
873 // CopyTexImage2D fails when called on a texture having immutable storage.
874 device_background_texture
->Allocate(
875 window_rect
.size(), ResourceProvider::TextureHintDefault
, RGBA_8888
);
877 ResourceProvider::ScopedWriteLockGL
lock(resource_provider_
,
878 device_background_texture
->id());
879 GetFramebufferTexture(
880 lock
.texture_id(), device_background_texture
->format(), window_rect
);
883 skia::RefPtr
<SkImageFilter
> filter
= RenderSurfaceFilters::BuildImageFilter(
884 quad
->background_filters
, device_background_texture
->size());
886 skia::RefPtr
<SkImage
> filtered_device_background
;
887 if (apply_background_filters
) {
888 filtered_device_background
=
889 ApplyImageFilter(ScopedUseGrContext::Create(this, frame
),
894 device_background_texture
.get());
896 *background_changed
= (filtered_device_background
!= NULL
);
898 int filtered_device_background_texture_id
= 0;
899 scoped_ptr
<ResourceProvider::ScopedReadLockGL
> lock
;
900 if (filtered_device_background
) {
901 GrTexture
* texture
= filtered_device_background
->getTexture();
902 filtered_device_background_texture_id
= texture
->getTextureHandle();
904 lock
.reset(new ResourceProvider::ScopedReadLockGL(
905 resource_provider_
, device_background_texture
->id()));
906 filtered_device_background_texture_id
= lock
->texture_id();
909 scoped_ptr
<ScopedResource
> background_texture
=
910 ScopedResource::Create(resource_provider_
);
911 background_texture
->Allocate(
913 ResourceProvider::TextureHintImmutableFramebuffer
,
916 const RenderPass
* target_render_pass
= frame
->current_render_pass
;
917 bool using_background_texture
=
918 UseScopedTexture(frame
, background_texture
.get(), quad
->rect
);
920 if (using_background_texture
) {
921 // Copy the readback pixels from device to the background texture for the
923 gfx::Transform device_to_framebuffer_transform
;
925 &device_to_framebuffer_transform
, gfx::Transform(), quad
->rect
);
926 device_to_framebuffer_transform
.PreconcatTransform(
927 contents_device_transform_inverse
);
930 GLC(gl_
, gl_
->ClearColor(0, 0, 1, 1));
931 gl_
->Clear(GL_COLOR_BUFFER_BIT
);
934 // The filtered_deveice_background_texture is oriented the same as the frame
935 // buffer. The transform we are copying with has a vertical flip, as well as
936 // the |device_to_framebuffer_transform|, which cancel each other out. So do
937 // not flip the contents in the shader to maintain orientation.
938 bool flip_vertically
= false;
940 CopyTextureToFramebuffer(frame
,
941 filtered_device_background_texture_id
,
943 device_to_framebuffer_transform
,
947 UseRenderPass(frame
, target_render_pass
);
949 if (!using_background_texture
)
950 return scoped_ptr
<ScopedResource
>();
951 return background_texture
.Pass();
954 void GLRenderer::DrawRenderPassQuad(DrawingFrame
* frame
,
955 const RenderPassDrawQuad
* quad
) {
956 SetBlendEnabled(quad
->ShouldDrawWithBlending());
958 ScopedResource
* contents_texture
=
959 render_pass_textures_
.get(quad
->render_pass_id
);
960 if (!contents_texture
|| !contents_texture
->id())
963 gfx::Transform quad_rect_matrix
;
964 QuadRectTransform(&quad_rect_matrix
, quad
->quadTransform(), quad
->rect
);
965 gfx::Transform contents_device_transform
=
966 frame
->window_matrix
* frame
->projection_matrix
* quad_rect_matrix
;
967 contents_device_transform
.FlattenTo2d();
969 // Can only draw surface if device matrix is invertible.
970 gfx::Transform
contents_device_transform_inverse(
971 gfx::Transform::kSkipInitialization
);
972 if (!contents_device_transform
.GetInverse(&contents_device_transform_inverse
))
975 bool need_background_texture
=
976 quad
->shared_quad_state
->blend_mode
!= SkXfermode::kSrcOver_Mode
||
977 !quad
->background_filters
.IsEmpty();
978 bool background_changed
= false;
979 scoped_ptr
<ScopedResource
> background_texture
;
980 if (need_background_texture
) {
981 // The pixels from the filtered background should completely replace the
982 // current pixel values.
983 bool disable_blending
= blend_enabled();
984 if (disable_blending
)
985 SetBlendEnabled(false);
988 GetBackgroundWithFilters(frame
,
990 contents_device_transform
,
991 contents_device_transform_inverse
,
992 &background_changed
);
994 if (disable_blending
)
995 SetBlendEnabled(true);
998 // TODO(senorblanco): Cache this value so that we don't have to do it for both
999 // the surface and its replica. Apply filters to the contents texture.
1000 skia::RefPtr
<SkImage
> filter_bitmap
;
1001 SkScalar color_matrix
[20];
1002 bool use_color_matrix
= false;
1003 if (!quad
->filters
.IsEmpty()) {
1004 skia::RefPtr
<SkImageFilter
> filter
= RenderSurfaceFilters::BuildImageFilter(
1005 quad
->filters
, contents_texture
->size());
1007 skia::RefPtr
<SkColorFilter
> cf
;
1010 SkColorFilter
* colorfilter_rawptr
= NULL
;
1011 filter
->asColorFilter(&colorfilter_rawptr
);
1012 cf
= skia::AdoptRef(colorfilter_rawptr
);
1015 if (cf
&& cf
->asColorMatrix(color_matrix
) && !filter
->getInput(0)) {
1016 // We have a single color matrix as a filter; apply it locally
1017 // in the compositor.
1018 use_color_matrix
= true;
1021 ApplyImageFilter(ScopedUseGrContext::Create(this, frame
),
1023 quad
->rect
.origin(),
1024 quad
->filters_scale
,
1031 if (quad
->shared_quad_state
->blend_mode
!= SkXfermode::kSrcOver_Mode
&&
1032 background_texture
) {
1034 ApplyBlendModeWithBackdrop(ScopedUseGrContext::Create(this, frame
),
1038 background_texture
.get(),
1039 quad
->shared_quad_state
->blend_mode
);
1042 // Draw the background texture if it has some filters applied.
1043 if (background_texture
&& background_changed
) {
1044 DCHECK(background_texture
->size() == quad
->rect
.size());
1045 ResourceProvider::ScopedReadLockGL
lock(resource_provider_
,
1046 background_texture
->id());
1048 // The background_texture is oriented the same as the frame buffer. The
1049 // transform we are copying with has a vertical flip, so flip the contents
1050 // in the shader to maintain orientation
1051 bool flip_vertically
= true;
1053 CopyTextureToFramebuffer(frame
,
1056 quad
->quadTransform(),
1060 bool clipped
= false;
1061 gfx::QuadF device_quad
= MathUtil::MapQuad(
1062 contents_device_transform
, SharedGeometryQuad(), &clipped
);
1063 LayerQuad
device_layer_bounds(gfx::QuadF(device_quad
.BoundingBox()));
1064 LayerQuad
device_layer_edges(device_quad
);
1066 // Use anti-aliasing programs only when necessary.
1068 !clipped
&& (!device_quad
.IsRectilinear() ||
1069 !gfx::IsNearestRectWithinDistance(device_quad
.BoundingBox(),
1070 kAntiAliasingEpsilon
));
1072 device_layer_bounds
.InflateAntiAliasingDistance();
1073 device_layer_edges
.InflateAntiAliasingDistance();
1076 scoped_ptr
<ResourceProvider::ScopedReadLockGL
> mask_resource_lock
;
1077 unsigned mask_texture_id
= 0;
1078 if (quad
->mask_resource_id
) {
1079 mask_resource_lock
.reset(new ResourceProvider::ScopedReadLockGL(
1080 resource_provider_
, quad
->mask_resource_id
));
1081 mask_texture_id
= mask_resource_lock
->texture_id();
1084 // TODO(danakj): use the background_texture and blend the background in with
1085 // this draw instead of having a separate copy of the background texture.
1087 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> contents_resource_lock
;
1088 if (filter_bitmap
) {
1089 GrTexture
* texture
= filter_bitmap
->getTexture();
1090 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
1091 gl_
->BindTexture(GL_TEXTURE_2D
, texture
->getTextureHandle());
1093 contents_resource_lock
=
1094 make_scoped_ptr(new ResourceProvider::ScopedSamplerGL(
1095 resource_provider_
, contents_texture
->id(), GL_LINEAR
));
1096 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
),
1097 contents_resource_lock
->target());
1100 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1102 &highp_threshold_cache_
,
1103 highp_threshold_min_
,
1104 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
1106 int shader_quad_location
= -1;
1107 int shader_edge_location
= -1;
1108 int shader_viewport_location
= -1;
1109 int shader_mask_sampler_location
= -1;
1110 int shader_mask_tex_coord_scale_location
= -1;
1111 int shader_mask_tex_coord_offset_location
= -1;
1112 int shader_matrix_location
= -1;
1113 int shader_alpha_location
= -1;
1114 int shader_color_matrix_location
= -1;
1115 int shader_color_offset_location
= -1;
1116 int shader_tex_transform_location
= -1;
1118 if (use_aa
&& mask_texture_id
&& !use_color_matrix
) {
1119 const RenderPassMaskProgramAA
* program
=
1120 GetRenderPassMaskProgramAA(tex_coord_precision
);
1121 SetUseProgram(program
->program());
1122 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1124 shader_quad_location
= program
->vertex_shader().quad_location();
1125 shader_edge_location
= program
->vertex_shader().edge_location();
1126 shader_viewport_location
= program
->vertex_shader().viewport_location();
1127 shader_mask_sampler_location
=
1128 program
->fragment_shader().mask_sampler_location();
1129 shader_mask_tex_coord_scale_location
=
1130 program
->fragment_shader().mask_tex_coord_scale_location();
1131 shader_mask_tex_coord_offset_location
=
1132 program
->fragment_shader().mask_tex_coord_offset_location();
1133 shader_matrix_location
= program
->vertex_shader().matrix_location();
1134 shader_alpha_location
= program
->fragment_shader().alpha_location();
1135 shader_tex_transform_location
=
1136 program
->vertex_shader().tex_transform_location();
1137 } else if (!use_aa
&& mask_texture_id
&& !use_color_matrix
) {
1138 const RenderPassMaskProgram
* program
=
1139 GetRenderPassMaskProgram(tex_coord_precision
);
1140 SetUseProgram(program
->program());
1141 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1143 shader_mask_sampler_location
=
1144 program
->fragment_shader().mask_sampler_location();
1145 shader_mask_tex_coord_scale_location
=
1146 program
->fragment_shader().mask_tex_coord_scale_location();
1147 shader_mask_tex_coord_offset_location
=
1148 program
->fragment_shader().mask_tex_coord_offset_location();
1149 shader_matrix_location
= program
->vertex_shader().matrix_location();
1150 shader_alpha_location
= program
->fragment_shader().alpha_location();
1151 shader_tex_transform_location
=
1152 program
->vertex_shader().tex_transform_location();
1153 } else if (use_aa
&& !mask_texture_id
&& !use_color_matrix
) {
1154 const RenderPassProgramAA
* program
=
1155 GetRenderPassProgramAA(tex_coord_precision
);
1156 SetUseProgram(program
->program());
1157 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1159 shader_quad_location
= program
->vertex_shader().quad_location();
1160 shader_edge_location
= program
->vertex_shader().edge_location();
1161 shader_viewport_location
= program
->vertex_shader().viewport_location();
1162 shader_matrix_location
= program
->vertex_shader().matrix_location();
1163 shader_alpha_location
= program
->fragment_shader().alpha_location();
1164 shader_tex_transform_location
=
1165 program
->vertex_shader().tex_transform_location();
1166 } else if (use_aa
&& mask_texture_id
&& use_color_matrix
) {
1167 const RenderPassMaskColorMatrixProgramAA
* program
=
1168 GetRenderPassMaskColorMatrixProgramAA(tex_coord_precision
);
1169 SetUseProgram(program
->program());
1170 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1172 shader_matrix_location
= program
->vertex_shader().matrix_location();
1173 shader_quad_location
= program
->vertex_shader().quad_location();
1174 shader_tex_transform_location
=
1175 program
->vertex_shader().tex_transform_location();
1176 shader_edge_location
= program
->vertex_shader().edge_location();
1177 shader_viewport_location
= program
->vertex_shader().viewport_location();
1178 shader_alpha_location
= program
->fragment_shader().alpha_location();
1179 shader_mask_sampler_location
=
1180 program
->fragment_shader().mask_sampler_location();
1181 shader_mask_tex_coord_scale_location
=
1182 program
->fragment_shader().mask_tex_coord_scale_location();
1183 shader_mask_tex_coord_offset_location
=
1184 program
->fragment_shader().mask_tex_coord_offset_location();
1185 shader_color_matrix_location
=
1186 program
->fragment_shader().color_matrix_location();
1187 shader_color_offset_location
=
1188 program
->fragment_shader().color_offset_location();
1189 } else if (use_aa
&& !mask_texture_id
&& use_color_matrix
) {
1190 const RenderPassColorMatrixProgramAA
* program
=
1191 GetRenderPassColorMatrixProgramAA(tex_coord_precision
);
1192 SetUseProgram(program
->program());
1193 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1195 shader_matrix_location
= program
->vertex_shader().matrix_location();
1196 shader_quad_location
= program
->vertex_shader().quad_location();
1197 shader_tex_transform_location
=
1198 program
->vertex_shader().tex_transform_location();
1199 shader_edge_location
= program
->vertex_shader().edge_location();
1200 shader_viewport_location
= program
->vertex_shader().viewport_location();
1201 shader_alpha_location
= program
->fragment_shader().alpha_location();
1202 shader_color_matrix_location
=
1203 program
->fragment_shader().color_matrix_location();
1204 shader_color_offset_location
=
1205 program
->fragment_shader().color_offset_location();
1206 } else if (!use_aa
&& mask_texture_id
&& use_color_matrix
) {
1207 const RenderPassMaskColorMatrixProgram
* program
=
1208 GetRenderPassMaskColorMatrixProgram(tex_coord_precision
);
1209 SetUseProgram(program
->program());
1210 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1212 shader_matrix_location
= program
->vertex_shader().matrix_location();
1213 shader_tex_transform_location
=
1214 program
->vertex_shader().tex_transform_location();
1215 shader_mask_sampler_location
=
1216 program
->fragment_shader().mask_sampler_location();
1217 shader_mask_tex_coord_scale_location
=
1218 program
->fragment_shader().mask_tex_coord_scale_location();
1219 shader_mask_tex_coord_offset_location
=
1220 program
->fragment_shader().mask_tex_coord_offset_location();
1221 shader_alpha_location
= program
->fragment_shader().alpha_location();
1222 shader_color_matrix_location
=
1223 program
->fragment_shader().color_matrix_location();
1224 shader_color_offset_location
=
1225 program
->fragment_shader().color_offset_location();
1226 } else if (!use_aa
&& !mask_texture_id
&& use_color_matrix
) {
1227 const RenderPassColorMatrixProgram
* program
=
1228 GetRenderPassColorMatrixProgram(tex_coord_precision
);
1229 SetUseProgram(program
->program());
1230 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1232 shader_matrix_location
= program
->vertex_shader().matrix_location();
1233 shader_tex_transform_location
=
1234 program
->vertex_shader().tex_transform_location();
1235 shader_alpha_location
= program
->fragment_shader().alpha_location();
1236 shader_color_matrix_location
=
1237 program
->fragment_shader().color_matrix_location();
1238 shader_color_offset_location
=
1239 program
->fragment_shader().color_offset_location();
1241 const RenderPassProgram
* program
=
1242 GetRenderPassProgram(tex_coord_precision
);
1243 SetUseProgram(program
->program());
1244 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1246 shader_matrix_location
= program
->vertex_shader().matrix_location();
1247 shader_alpha_location
= program
->fragment_shader().alpha_location();
1248 shader_tex_transform_location
=
1249 program
->vertex_shader().tex_transform_location();
1252 quad
->rect
.width() / static_cast<float>(contents_texture
->size().width());
1253 float tex_scale_y
= quad
->rect
.height() /
1254 static_cast<float>(contents_texture
->size().height());
1255 DCHECK_LE(tex_scale_x
, 1.0f
);
1256 DCHECK_LE(tex_scale_y
, 1.0f
);
1258 DCHECK(shader_tex_transform_location
!= -1 || IsContextLost());
1259 // Flip the content vertically in the shader, as the RenderPass input
1260 // texture is already oriented the same way as the framebuffer, but the
1261 // projection transform does a flip.
1263 gl_
->Uniform4f(shader_tex_transform_location
,
1269 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> shader_mask_sampler_lock
;
1270 if (shader_mask_sampler_location
!= -1) {
1271 DCHECK_NE(shader_mask_tex_coord_scale_location
, 1);
1272 DCHECK_NE(shader_mask_tex_coord_offset_location
, 1);
1273 GLC(gl_
, gl_
->Uniform1i(shader_mask_sampler_location
, 1));
1275 float mask_tex_scale_x
= quad
->mask_uv_rect
.width() / tex_scale_x
;
1276 float mask_tex_scale_y
= quad
->mask_uv_rect
.height() / tex_scale_y
;
1278 // Mask textures are oriented vertically flipped relative to the framebuffer
1279 // and the RenderPass contents texture, so we flip the tex coords from the
1280 // RenderPass texture to find the mask texture coords.
1282 gl_
->Uniform2f(shader_mask_tex_coord_offset_location
,
1283 quad
->mask_uv_rect
.x(),
1284 quad
->mask_uv_rect
.y() + quad
->mask_uv_rect
.height()));
1286 gl_
->Uniform2f(shader_mask_tex_coord_scale_location
,
1288 -mask_tex_scale_y
));
1289 shader_mask_sampler_lock
= make_scoped_ptr(
1290 new ResourceProvider::ScopedSamplerGL(resource_provider_
,
1291 quad
->mask_resource_id
,
1294 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
),
1295 shader_mask_sampler_lock
->target());
1298 if (shader_edge_location
!= -1) {
1300 device_layer_edges
.ToFloatArray(edge
);
1301 device_layer_bounds
.ToFloatArray(&edge
[12]);
1302 GLC(gl_
, gl_
->Uniform3fv(shader_edge_location
, 8, edge
));
1305 if (shader_viewport_location
!= -1) {
1306 float viewport
[4] = {static_cast<float>(viewport_
.x()),
1307 static_cast<float>(viewport_
.y()),
1308 static_cast<float>(viewport_
.width()),
1309 static_cast<float>(viewport_
.height()), };
1310 GLC(gl_
, gl_
->Uniform4fv(shader_viewport_location
, 1, viewport
));
1313 if (shader_color_matrix_location
!= -1) {
1315 for (int i
= 0; i
< 4; ++i
) {
1316 for (int j
= 0; j
< 4; ++j
)
1317 matrix
[i
* 4 + j
] = SkScalarToFloat(color_matrix
[j
* 5 + i
]);
1320 gl_
->UniformMatrix4fv(shader_color_matrix_location
, 1, false, matrix
));
1322 static const float kScale
= 1.0f
/ 255.0f
;
1323 if (shader_color_offset_location
!= -1) {
1325 for (int i
= 0; i
< 4; ++i
)
1326 offset
[i
] = SkScalarToFloat(color_matrix
[i
* 5 + 4]) * kScale
;
1328 GLC(gl_
, gl_
->Uniform4fv(shader_color_offset_location
, 1, offset
));
1331 // Map device space quad to surface space. contents_device_transform has no 3d
1332 // component since it was flattened, so we don't need to project.
1333 gfx::QuadF surface_quad
= MathUtil::MapQuad(contents_device_transform_inverse
,
1334 device_layer_edges
.ToQuadF(),
1337 SetShaderOpacity(quad
->opacity(), shader_alpha_location
);
1338 SetShaderQuadF(surface_quad
, shader_quad_location
);
1340 frame
, quad
->quadTransform(), quad
->rect
, shader_matrix_location
);
1342 // Flush the compositor context before the filter bitmap goes out of
1343 // scope, so the draw gets processed before the filter texture gets deleted.
1345 GLC(gl_
, gl_
->Flush());
1348 struct SolidColorProgramUniforms
{
1350 unsigned matrix_location
;
1351 unsigned viewport_location
;
1352 unsigned quad_location
;
1353 unsigned edge_location
;
1354 unsigned color_location
;
1358 static void SolidColorUniformLocation(T program
,
1359 SolidColorProgramUniforms
* uniforms
) {
1360 uniforms
->program
= program
->program();
1361 uniforms
->matrix_location
= program
->vertex_shader().matrix_location();
1362 uniforms
->viewport_location
= program
->vertex_shader().viewport_location();
1363 uniforms
->quad_location
= program
->vertex_shader().quad_location();
1364 uniforms
->edge_location
= program
->vertex_shader().edge_location();
1365 uniforms
->color_location
= program
->fragment_shader().color_location();
1369 bool GLRenderer::SetupQuadForAntialiasing(
1370 const gfx::Transform
& device_transform
,
1371 const DrawQuad
* quad
,
1372 gfx::QuadF
* local_quad
,
1374 gfx::Rect tile_rect
= quad
->visible_rect
;
1376 bool clipped
= false;
1377 gfx::QuadF device_layer_quad
= MathUtil::MapQuad(
1378 device_transform
, gfx::QuadF(quad
->visibleContentRect()), &clipped
);
1380 bool is_axis_aligned_in_target
= device_layer_quad
.IsRectilinear();
1381 bool is_nearest_rect_within_epsilon
=
1382 is_axis_aligned_in_target
&&
1383 gfx::IsNearestRectWithinDistance(device_layer_quad
.BoundingBox(),
1384 kAntiAliasingEpsilon
);
1385 // AAing clipped quads is not supported by the code yet.
1386 bool use_aa
= !clipped
&& !is_nearest_rect_within_epsilon
&& quad
->IsEdge();
1390 LayerQuad
device_layer_bounds(gfx::QuadF(device_layer_quad
.BoundingBox()));
1391 device_layer_bounds
.InflateAntiAliasingDistance();
1393 LayerQuad
device_layer_edges(device_layer_quad
);
1394 device_layer_edges
.InflateAntiAliasingDistance();
1396 device_layer_edges
.ToFloatArray(edge
);
1397 device_layer_bounds
.ToFloatArray(&edge
[12]);
1399 gfx::PointF bottom_right
= tile_rect
.bottom_right();
1400 gfx::PointF bottom_left
= tile_rect
.bottom_left();
1401 gfx::PointF top_left
= tile_rect
.origin();
1402 gfx::PointF top_right
= tile_rect
.top_right();
1404 // Map points to device space.
1405 bottom_right
= MathUtil::MapPoint(device_transform
, bottom_right
, &clipped
);
1407 bottom_left
= MathUtil::MapPoint(device_transform
, bottom_left
, &clipped
);
1409 top_left
= MathUtil::MapPoint(device_transform
, top_left
, &clipped
);
1411 top_right
= MathUtil::MapPoint(device_transform
, top_right
, &clipped
);
1414 LayerQuad::Edge
bottom_edge(bottom_right
, bottom_left
);
1415 LayerQuad::Edge
left_edge(bottom_left
, top_left
);
1416 LayerQuad::Edge
top_edge(top_left
, top_right
);
1417 LayerQuad::Edge
right_edge(top_right
, bottom_right
);
1419 // Only apply anti-aliasing to edges not clipped by culling or scissoring.
1420 if (quad
->IsTopEdge() && tile_rect
.y() == quad
->rect
.y())
1421 top_edge
= device_layer_edges
.top();
1422 if (quad
->IsLeftEdge() && tile_rect
.x() == quad
->rect
.x())
1423 left_edge
= device_layer_edges
.left();
1424 if (quad
->IsRightEdge() && tile_rect
.right() == quad
->rect
.right())
1425 right_edge
= device_layer_edges
.right();
1426 if (quad
->IsBottomEdge() && tile_rect
.bottom() == quad
->rect
.bottom())
1427 bottom_edge
= device_layer_edges
.bottom();
1429 float sign
= gfx::QuadF(tile_rect
).IsCounterClockwise() ? -1 : 1;
1430 bottom_edge
.scale(sign
);
1431 left_edge
.scale(sign
);
1432 top_edge
.scale(sign
);
1433 right_edge
.scale(sign
);
1435 // Create device space quad.
1436 LayerQuad
device_quad(left_edge
, top_edge
, right_edge
, bottom_edge
);
1438 // Map device space quad to local space. device_transform has no 3d
1439 // component since it was flattened, so we don't need to project. We should
1440 // have already checked that the transform was uninvertible above.
1441 gfx::Transform
inverse_device_transform(gfx::Transform::kSkipInitialization
);
1442 bool did_invert
= device_transform
.GetInverse(&inverse_device_transform
);
1444 *local_quad
= MathUtil::MapQuad(
1445 inverse_device_transform
, device_quad
.ToQuadF(), &clipped
);
1446 // We should not DCHECK(!clipped) here, because anti-aliasing inflation may
1447 // cause device_quad to become clipped. To our knowledge this scenario does
1448 // not need to be handled differently than the unclipped case.
1453 void GLRenderer::DrawSolidColorQuad(const DrawingFrame
* frame
,
1454 const SolidColorDrawQuad
* quad
) {
1455 gfx::Rect tile_rect
= quad
->visible_rect
;
1457 SkColor color
= quad
->color
;
1458 float opacity
= quad
->opacity();
1459 float alpha
= (SkColorGetA(color
) * (1.0f
/ 255.0f
)) * opacity
;
1461 // Early out if alpha is small enough that quad doesn't contribute to output.
1462 if (alpha
< std::numeric_limits
<float>::epsilon() &&
1463 quad
->ShouldDrawWithBlending())
1466 gfx::Transform device_transform
=
1467 frame
->window_matrix
* frame
->projection_matrix
* quad
->quadTransform();
1468 device_transform
.FlattenTo2d();
1469 if (!device_transform
.IsInvertible())
1472 gfx::QuadF local_quad
= gfx::QuadF(gfx::RectF(tile_rect
));
1475 settings_
->allow_antialiasing
&& !quad
->force_anti_aliasing_off
&&
1476 SetupQuadForAntialiasing(device_transform
, quad
, &local_quad
, edge
);
1478 SolidColorProgramUniforms uniforms
;
1480 SolidColorUniformLocation(GetSolidColorProgramAA(), &uniforms
);
1482 SolidColorUniformLocation(GetSolidColorProgram(), &uniforms
);
1483 SetUseProgram(uniforms
.program
);
1486 gl_
->Uniform4f(uniforms
.color_location
,
1487 (SkColorGetR(color
) * (1.0f
/ 255.0f
)) * alpha
,
1488 (SkColorGetG(color
) * (1.0f
/ 255.0f
)) * alpha
,
1489 (SkColorGetB(color
) * (1.0f
/ 255.0f
)) * alpha
,
1492 float viewport
[4] = {static_cast<float>(viewport_
.x()),
1493 static_cast<float>(viewport_
.y()),
1494 static_cast<float>(viewport_
.width()),
1495 static_cast<float>(viewport_
.height()), };
1496 GLC(gl_
, gl_
->Uniform4fv(uniforms
.viewport_location
, 1, viewport
));
1497 GLC(gl_
, gl_
->Uniform3fv(uniforms
.edge_location
, 8, edge
));
1500 // Enable blending when the quad properties require it or if we decided
1501 // to use antialiasing.
1502 SetBlendEnabled(quad
->ShouldDrawWithBlending() || use_aa
);
1504 // Normalize to tile_rect.
1505 local_quad
.Scale(1.0f
/ tile_rect
.width(), 1.0f
/ tile_rect
.height());
1507 SetShaderQuadF(local_quad
, uniforms
.quad_location
);
1509 // The transform and vertex data are used to figure out the extents that the
1510 // un-antialiased quad should have and which vertex this is and the float
1511 // quad passed in via uniform is the actual geometry that gets used to draw
1512 // it. This is why this centered rect is used and not the original quad_rect.
1513 gfx::RectF
centered_rect(
1514 gfx::PointF(-0.5f
* tile_rect
.width(), -0.5f
* tile_rect
.height()),
1517 frame
, quad
->quadTransform(), centered_rect
, uniforms
.matrix_location
);
1520 struct TileProgramUniforms
{
1522 unsigned matrix_location
;
1523 unsigned viewport_location
;
1524 unsigned quad_location
;
1525 unsigned edge_location
;
1526 unsigned vertex_tex_transform_location
;
1527 unsigned sampler_location
;
1528 unsigned fragment_tex_transform_location
;
1529 unsigned alpha_location
;
1533 static void TileUniformLocation(T program
, TileProgramUniforms
* uniforms
) {
1534 uniforms
->program
= program
->program();
1535 uniforms
->matrix_location
= program
->vertex_shader().matrix_location();
1536 uniforms
->viewport_location
= program
->vertex_shader().viewport_location();
1537 uniforms
->quad_location
= program
->vertex_shader().quad_location();
1538 uniforms
->edge_location
= program
->vertex_shader().edge_location();
1539 uniforms
->vertex_tex_transform_location
=
1540 program
->vertex_shader().vertex_tex_transform_location();
1542 uniforms
->sampler_location
= program
->fragment_shader().sampler_location();
1543 uniforms
->alpha_location
= program
->fragment_shader().alpha_location();
1544 uniforms
->fragment_tex_transform_location
=
1545 program
->fragment_shader().fragment_tex_transform_location();
1548 void GLRenderer::DrawTileQuad(const DrawingFrame
* frame
,
1549 const TileDrawQuad
* quad
) {
1550 DrawContentQuad(frame
, quad
, quad
->resource_id
);
1553 void GLRenderer::DrawContentQuad(const DrawingFrame
* frame
,
1554 const ContentDrawQuadBase
* quad
,
1555 ResourceProvider::ResourceId resource_id
) {
1556 gfx::Rect tile_rect
= quad
->visible_rect
;
1558 gfx::RectF tex_coord_rect
= MathUtil::ScaleRectProportional(
1559 quad
->tex_coord_rect
, quad
->rect
, tile_rect
);
1560 float tex_to_geom_scale_x
= quad
->rect
.width() / quad
->tex_coord_rect
.width();
1561 float tex_to_geom_scale_y
=
1562 quad
->rect
.height() / quad
->tex_coord_rect
.height();
1564 gfx::RectF
clamp_geom_rect(tile_rect
);
1565 gfx::RectF
clamp_tex_rect(tex_coord_rect
);
1566 // Clamp texture coordinates to avoid sampling outside the layer
1567 // by deflating the tile region half a texel or half a texel
1568 // minus epsilon for one pixel layers. The resulting clamp region
1569 // is mapped to the unit square by the vertex shader and mapped
1570 // back to normalized texture coordinates by the fragment shader
1571 // after being clamped to 0-1 range.
1573 std::min(0.5f
, 0.5f
* clamp_tex_rect
.width() - kAntiAliasingEpsilon
);
1575 std::min(0.5f
, 0.5f
* clamp_tex_rect
.height() - kAntiAliasingEpsilon
);
1576 float geom_clamp_x
=
1577 std::min(tex_clamp_x
* tex_to_geom_scale_x
,
1578 0.5f
* clamp_geom_rect
.width() - kAntiAliasingEpsilon
);
1579 float geom_clamp_y
=
1580 std::min(tex_clamp_y
* tex_to_geom_scale_y
,
1581 0.5f
* clamp_geom_rect
.height() - kAntiAliasingEpsilon
);
1582 clamp_geom_rect
.Inset(geom_clamp_x
, geom_clamp_y
, geom_clamp_x
, geom_clamp_y
);
1583 clamp_tex_rect
.Inset(tex_clamp_x
, tex_clamp_y
, tex_clamp_x
, tex_clamp_y
);
1585 // Map clamping rectangle to unit square.
1586 float vertex_tex_translate_x
= -clamp_geom_rect
.x() / clamp_geom_rect
.width();
1587 float vertex_tex_translate_y
=
1588 -clamp_geom_rect
.y() / clamp_geom_rect
.height();
1589 float vertex_tex_scale_x
= tile_rect
.width() / clamp_geom_rect
.width();
1590 float vertex_tex_scale_y
= tile_rect
.height() / clamp_geom_rect
.height();
1592 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1593 gl_
, &highp_threshold_cache_
, highp_threshold_min_
, quad
->texture_size
);
1595 gfx::Transform device_transform
=
1596 frame
->window_matrix
* frame
->projection_matrix
* quad
->quadTransform();
1597 device_transform
.FlattenTo2d();
1598 if (!device_transform
.IsInvertible())
1601 gfx::QuadF local_quad
= gfx::QuadF(gfx::RectF(tile_rect
));
1604 settings_
->allow_antialiasing
&&
1605 SetupQuadForAntialiasing(device_transform
, quad
, &local_quad
, edge
);
1607 bool scaled
= (tex_to_geom_scale_x
!= 1.f
|| tex_to_geom_scale_y
!= 1.f
);
1608 GLenum filter
= (use_aa
|| scaled
||
1609 !quad
->quadTransform().IsIdentityOrIntegerTranslation())
1612 ResourceProvider::ScopedSamplerGL
quad_resource_lock(
1613 resource_provider_
, resource_id
, filter
);
1614 SamplerType sampler
=
1615 SamplerTypeFromTextureTarget(quad_resource_lock
.target());
1617 float fragment_tex_translate_x
= clamp_tex_rect
.x();
1618 float fragment_tex_translate_y
= clamp_tex_rect
.y();
1619 float fragment_tex_scale_x
= clamp_tex_rect
.width();
1620 float fragment_tex_scale_y
= clamp_tex_rect
.height();
1622 // Map to normalized texture coordinates.
1623 if (sampler
!= SamplerType2DRect
) {
1624 gfx::Size texture_size
= quad
->texture_size
;
1625 DCHECK(!texture_size
.IsEmpty());
1626 fragment_tex_translate_x
/= texture_size
.width();
1627 fragment_tex_translate_y
/= texture_size
.height();
1628 fragment_tex_scale_x
/= texture_size
.width();
1629 fragment_tex_scale_y
/= texture_size
.height();
1632 TileProgramUniforms uniforms
;
1634 if (quad
->swizzle_contents
) {
1635 TileUniformLocation(GetTileProgramSwizzleAA(tex_coord_precision
, sampler
),
1638 TileUniformLocation(GetTileProgramAA(tex_coord_precision
, sampler
),
1642 if (quad
->ShouldDrawWithBlending()) {
1643 if (quad
->swizzle_contents
) {
1644 TileUniformLocation(GetTileProgramSwizzle(tex_coord_precision
, sampler
),
1647 TileUniformLocation(GetTileProgram(tex_coord_precision
, sampler
),
1651 if (quad
->swizzle_contents
) {
1652 TileUniformLocation(
1653 GetTileProgramSwizzleOpaque(tex_coord_precision
, sampler
),
1656 TileUniformLocation(GetTileProgramOpaque(tex_coord_precision
, sampler
),
1662 SetUseProgram(uniforms
.program
);
1663 GLC(gl_
, gl_
->Uniform1i(uniforms
.sampler_location
, 0));
1666 float viewport
[4] = {static_cast<float>(viewport_
.x()),
1667 static_cast<float>(viewport_
.y()),
1668 static_cast<float>(viewport_
.width()),
1669 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 // Move fragment shader transform to vertex shader. We can do this while
1687 // still producing correct results as fragment_tex_transform_location
1688 // should always be non-negative when tiles are transformed in a way
1689 // that could result in sampling outside the layer.
1690 vertex_tex_scale_x
*= fragment_tex_scale_x
;
1691 vertex_tex_scale_y
*= fragment_tex_scale_y
;
1692 vertex_tex_translate_x
*= fragment_tex_scale_x
;
1693 vertex_tex_translate_y
*= fragment_tex_scale_y
;
1694 vertex_tex_translate_x
+= fragment_tex_translate_x
;
1695 vertex_tex_translate_y
+= fragment_tex_translate_y
;
1698 gl_
->Uniform4f(uniforms
.vertex_tex_transform_location
,
1699 vertex_tex_translate_x
,
1700 vertex_tex_translate_y
,
1702 vertex_tex_scale_y
));
1705 // Enable blending when the quad properties require it or if we decided
1706 // to use antialiasing.
1707 SetBlendEnabled(quad
->ShouldDrawWithBlending() || use_aa
);
1709 // Normalize to tile_rect.
1710 local_quad
.Scale(1.0f
/ tile_rect
.width(), 1.0f
/ tile_rect
.height());
1712 SetShaderOpacity(quad
->opacity(), uniforms
.alpha_location
);
1713 SetShaderQuadF(local_quad
, uniforms
.quad_location
);
1715 // The transform and vertex data are used to figure out the extents that the
1716 // un-antialiased quad should have and which vertex this is and the float
1717 // quad passed in via uniform is the actual geometry that gets used to draw
1718 // it. This is why this centered rect is used and not the original quad_rect.
1719 gfx::RectF
centered_rect(
1720 gfx::PointF(-0.5f
* tile_rect
.width(), -0.5f
* tile_rect
.height()),
1723 frame
, quad
->quadTransform(), centered_rect
, uniforms
.matrix_location
);
1726 void GLRenderer::DrawYUVVideoQuad(const DrawingFrame
* frame
,
1727 const YUVVideoDrawQuad
* quad
) {
1728 SetBlendEnabled(quad
->ShouldDrawWithBlending());
1730 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1732 &highp_threshold_cache_
,
1733 highp_threshold_min_
,
1734 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
1736 bool use_alpha_plane
= quad
->a_plane_resource_id
!= 0;
1738 ResourceProvider::ScopedSamplerGL
y_plane_lock(
1739 resource_provider_
, quad
->y_plane_resource_id
, GL_TEXTURE1
, GL_LINEAR
);
1740 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
), y_plane_lock
.target());
1741 ResourceProvider::ScopedSamplerGL
u_plane_lock(
1742 resource_provider_
, quad
->u_plane_resource_id
, GL_TEXTURE2
, GL_LINEAR
);
1743 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
), u_plane_lock
.target());
1744 ResourceProvider::ScopedSamplerGL
v_plane_lock(
1745 resource_provider_
, quad
->v_plane_resource_id
, GL_TEXTURE3
, GL_LINEAR
);
1746 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
), v_plane_lock
.target());
1747 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> a_plane_lock
;
1748 if (use_alpha_plane
) {
1749 a_plane_lock
.reset(new ResourceProvider::ScopedSamplerGL(
1750 resource_provider_
, quad
->a_plane_resource_id
, GL_TEXTURE4
, GL_LINEAR
));
1751 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
), a_plane_lock
->target());
1754 int matrix_location
= -1;
1755 int tex_scale_location
= -1;
1756 int tex_offset_location
= -1;
1757 int y_texture_location
= -1;
1758 int u_texture_location
= -1;
1759 int v_texture_location
= -1;
1760 int a_texture_location
= -1;
1761 int yuv_matrix_location
= -1;
1762 int yuv_adj_location
= -1;
1763 int alpha_location
= -1;
1764 if (use_alpha_plane
) {
1765 const VideoYUVAProgram
* program
= GetVideoYUVAProgram(tex_coord_precision
);
1766 DCHECK(program
&& (program
->initialized() || IsContextLost()));
1767 SetUseProgram(program
->program());
1768 matrix_location
= program
->vertex_shader().matrix_location();
1769 tex_scale_location
= program
->vertex_shader().tex_scale_location();
1770 tex_offset_location
= program
->vertex_shader().tex_offset_location();
1771 y_texture_location
= program
->fragment_shader().y_texture_location();
1772 u_texture_location
= program
->fragment_shader().u_texture_location();
1773 v_texture_location
= program
->fragment_shader().v_texture_location();
1774 a_texture_location
= program
->fragment_shader().a_texture_location();
1775 yuv_matrix_location
= program
->fragment_shader().yuv_matrix_location();
1776 yuv_adj_location
= program
->fragment_shader().yuv_adj_location();
1777 alpha_location
= program
->fragment_shader().alpha_location();
1779 const VideoYUVProgram
* program
= GetVideoYUVProgram(tex_coord_precision
);
1780 DCHECK(program
&& (program
->initialized() || IsContextLost()));
1781 SetUseProgram(program
->program());
1782 matrix_location
= program
->vertex_shader().matrix_location();
1783 tex_scale_location
= program
->vertex_shader().tex_scale_location();
1784 tex_offset_location
= program
->vertex_shader().tex_offset_location();
1785 y_texture_location
= program
->fragment_shader().y_texture_location();
1786 u_texture_location
= program
->fragment_shader().u_texture_location();
1787 v_texture_location
= program
->fragment_shader().v_texture_location();
1788 yuv_matrix_location
= program
->fragment_shader().yuv_matrix_location();
1789 yuv_adj_location
= program
->fragment_shader().yuv_adj_location();
1790 alpha_location
= program
->fragment_shader().alpha_location();
1794 gl_
->Uniform2f(tex_scale_location
,
1795 quad
->tex_coord_rect
.width(),
1796 quad
->tex_coord_rect
.height()));
1798 gl_
->Uniform2f(tex_offset_location
,
1799 quad
->tex_coord_rect
.x(),
1800 quad
->tex_coord_rect
.y()));
1801 GLC(gl_
, gl_
->Uniform1i(y_texture_location
, 1));
1802 GLC(gl_
, gl_
->Uniform1i(u_texture_location
, 2));
1803 GLC(gl_
, gl_
->Uniform1i(v_texture_location
, 3));
1804 if (use_alpha_plane
)
1805 GLC(gl_
, gl_
->Uniform1i(a_texture_location
, 4));
1807 // These values are magic numbers that are used in the transformation from YUV
1808 // to RGB color values. They are taken from the following webpage:
1809 // http://www.fourcc.org/fccyvrgb.php
1810 float yuv_to_rgb_rec601
[9] = {
1811 1.164f
, 1.164f
, 1.164f
, 0.0f
, -.391f
, 2.018f
, 1.596f
, -.813f
, 0.0f
,
1813 float yuv_to_rgb_rec601_jpeg
[9] = {
1814 1.f
, 1.f
, 1.f
, 0.0f
, -.34414f
, 1.772f
, 1.402f
, -.71414f
, 0.0f
,
1817 // These values map to 16, 128, and 128 respectively, and are computed
1818 // as a fraction over 256 (e.g. 16 / 256 = 0.0625).
1819 // They are used in the YUV to RGBA conversion formula:
1820 // Y - 16 : Gives 16 values of head and footroom for overshooting
1821 // U - 128 : Turns unsigned U into signed U [-128,127]
1822 // V - 128 : Turns unsigned V into signed V [-128,127]
1823 float yuv_adjust_rec601
[3] = {
1824 -0.0625f
, -0.5f
, -0.5f
,
1827 // Same as above, but without the head and footroom.
1828 float yuv_adjust_rec601_jpeg
[3] = {
1832 float* yuv_to_rgb
= NULL
;
1833 float* yuv_adjust
= NULL
;
1835 switch (quad
->color_space
) {
1836 case YUVVideoDrawQuad::REC_601
:
1837 yuv_to_rgb
= yuv_to_rgb_rec601
;
1838 yuv_adjust
= yuv_adjust_rec601
;
1840 case YUVVideoDrawQuad::REC_601_JPEG
:
1841 yuv_to_rgb
= yuv_to_rgb_rec601_jpeg
;
1842 yuv_adjust
= yuv_adjust_rec601_jpeg
;
1846 GLC(gl_
, gl_
->UniformMatrix3fv(yuv_matrix_location
, 1, 0, yuv_to_rgb
));
1847 GLC(gl_
, gl_
->Uniform3fv(yuv_adj_location
, 1, yuv_adjust
));
1849 SetShaderOpacity(quad
->opacity(), alpha_location
);
1850 DrawQuadGeometry(frame
, quad
->quadTransform(), quad
->rect
, matrix_location
);
1853 void GLRenderer::DrawStreamVideoQuad(const DrawingFrame
* frame
,
1854 const StreamVideoDrawQuad
* quad
) {
1855 SetBlendEnabled(quad
->ShouldDrawWithBlending());
1857 static float gl_matrix
[16];
1859 DCHECK(capabilities_
.using_egl_image
);
1861 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1863 &highp_threshold_cache_
,
1864 highp_threshold_min_
,
1865 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
1867 const VideoStreamTextureProgram
* program
=
1868 GetVideoStreamTextureProgram(tex_coord_precision
);
1869 SetUseProgram(program
->program());
1871 ToGLMatrix(&gl_matrix
[0], quad
->matrix
);
1873 gl_
->UniformMatrix4fv(
1874 program
->vertex_shader().tex_matrix_location(), 1, false, gl_matrix
));
1876 ResourceProvider::ScopedReadLockGL
lock(resource_provider_
,
1878 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
1879 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_EXTERNAL_OES
, lock
.texture_id()));
1881 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
1883 SetShaderOpacity(quad
->opacity(),
1884 program
->fragment_shader().alpha_location());
1885 DrawQuadGeometry(frame
,
1886 quad
->quadTransform(),
1888 program
->vertex_shader().matrix_location());
1891 void GLRenderer::DrawPictureQuad(const DrawingFrame
* frame
,
1892 const PictureDrawQuad
* quad
) {
1893 if (on_demand_tile_raster_bitmap_
.width() != quad
->texture_size
.width() ||
1894 on_demand_tile_raster_bitmap_
.height() != quad
->texture_size
.height()) {
1895 on_demand_tile_raster_bitmap_
.allocN32Pixels(quad
->texture_size
.width(),
1896 quad
->texture_size
.height());
1898 if (on_demand_tile_raster_resource_id_
)
1899 resource_provider_
->DeleteResource(on_demand_tile_raster_resource_id_
);
1901 on_demand_tile_raster_resource_id_
= resource_provider_
->CreateGLTexture(
1904 GL_TEXTURE_POOL_UNMANAGED_CHROMIUM
,
1906 ResourceProvider::TextureHintImmutable
,
1907 quad
->texture_format
);
1910 SkCanvas
canvas(on_demand_tile_raster_bitmap_
);
1911 quad
->picture_pile
->RasterToBitmap(
1912 &canvas
, quad
->content_rect
, quad
->contents_scale
, NULL
);
1914 uint8_t* bitmap_pixels
= NULL
;
1915 SkBitmap on_demand_tile_raster_bitmap_dest
;
1916 SkColorType colorType
= ResourceFormatToSkColorType(quad
->texture_format
);
1917 if (on_demand_tile_raster_bitmap_
.colorType() != colorType
) {
1918 on_demand_tile_raster_bitmap_
.copyTo(&on_demand_tile_raster_bitmap_dest
,
1920 // TODO(kaanb): The GL pipeline assumes a 4-byte alignment for the
1921 // bitmap data. This check will be removed once crbug.com/293728 is fixed.
1922 CHECK_EQ(0u, on_demand_tile_raster_bitmap_dest
.rowBytes() % 4);
1923 bitmap_pixels
= reinterpret_cast<uint8_t*>(
1924 on_demand_tile_raster_bitmap_dest
.getPixels());
1927 reinterpret_cast<uint8_t*>(on_demand_tile_raster_bitmap_
.getPixels());
1930 resource_provider_
->SetPixels(on_demand_tile_raster_resource_id_
,
1932 gfx::Rect(quad
->texture_size
),
1933 gfx::Rect(quad
->texture_size
),
1936 DrawContentQuad(frame
, quad
, on_demand_tile_raster_resource_id_
);
1939 struct TextureProgramBinding
{
1940 template <class Program
>
1941 void Set(Program
* program
) {
1943 program_id
= program
->program();
1944 sampler_location
= program
->fragment_shader().sampler_location();
1945 matrix_location
= program
->vertex_shader().matrix_location();
1946 background_color_location
=
1947 program
->fragment_shader().background_color_location();
1950 int sampler_location
;
1951 int matrix_location
;
1952 int background_color_location
;
1955 struct TexTransformTextureProgramBinding
: TextureProgramBinding
{
1956 template <class Program
>
1957 void Set(Program
* program
) {
1958 TextureProgramBinding::Set(program
);
1959 tex_transform_location
= program
->vertex_shader().tex_transform_location();
1960 vertex_opacity_location
=
1961 program
->vertex_shader().vertex_opacity_location();
1963 int tex_transform_location
;
1964 int vertex_opacity_location
;
1967 void GLRenderer::FlushTextureQuadCache() {
1968 // Check to see if we have anything to draw.
1969 if (draw_cache_
.program_id
== 0)
1972 // Set the correct blending mode.
1973 SetBlendEnabled(draw_cache_
.needs_blending
);
1975 // Bind the program to the GL state.
1976 SetUseProgram(draw_cache_
.program_id
);
1978 // Bind the correct texture sampler location.
1979 GLC(gl_
, gl_
->Uniform1i(draw_cache_
.sampler_location
, 0));
1981 // Assume the current active textures is 0.
1982 ResourceProvider::ScopedReadLockGL
locked_quad(resource_provider_
,
1983 draw_cache_
.resource_id
);
1984 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
1985 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_2D
, locked_quad
.texture_id()));
1987 COMPILE_ASSERT(sizeof(Float4
) == 4 * sizeof(float), struct_is_densely_packed
);
1988 COMPILE_ASSERT(sizeof(Float16
) == 16 * sizeof(float),
1989 struct_is_densely_packed
);
1991 // Upload the tranforms for both points and uvs.
1993 gl_
->UniformMatrix4fv(
1994 static_cast<int>(draw_cache_
.matrix_location
),
1995 static_cast<int>(draw_cache_
.matrix_data
.size()),
1997 reinterpret_cast<float*>(&draw_cache_
.matrix_data
.front())));
2000 static_cast<int>(draw_cache_
.uv_xform_location
),
2001 static_cast<int>(draw_cache_
.uv_xform_data
.size()),
2002 reinterpret_cast<float*>(&draw_cache_
.uv_xform_data
.front())));
2004 if (draw_cache_
.background_color
!= SK_ColorTRANSPARENT
) {
2005 Float4 background_color
= PremultipliedColor(draw_cache_
.background_color
);
2008 draw_cache_
.background_color_location
, 1, background_color
.data
));
2013 static_cast<int>(draw_cache_
.vertex_opacity_location
),
2014 static_cast<int>(draw_cache_
.vertex_opacity_data
.size()),
2015 static_cast<float*>(&draw_cache_
.vertex_opacity_data
.front())));
2019 gl_
->DrawElements(GL_TRIANGLES
,
2020 6 * draw_cache_
.matrix_data
.size(),
2025 draw_cache_
.program_id
= 0;
2026 draw_cache_
.uv_xform_data
.resize(0);
2027 draw_cache_
.vertex_opacity_data
.resize(0);
2028 draw_cache_
.matrix_data
.resize(0);
2031 void GLRenderer::EnqueueTextureQuad(const DrawingFrame
* frame
,
2032 const TextureDrawQuad
* quad
) {
2033 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
2035 &highp_threshold_cache_
,
2036 highp_threshold_min_
,
2037 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
2039 // Choose the correct texture program binding
2040 TexTransformTextureProgramBinding binding
;
2041 if (quad
->premultiplied_alpha
) {
2042 if (quad
->background_color
== SK_ColorTRANSPARENT
) {
2043 binding
.Set(GetTextureProgram(tex_coord_precision
));
2045 binding
.Set(GetTextureBackgroundProgram(tex_coord_precision
));
2048 if (quad
->background_color
== SK_ColorTRANSPARENT
) {
2049 binding
.Set(GetNonPremultipliedTextureProgram(tex_coord_precision
));
2052 GetNonPremultipliedTextureBackgroundProgram(tex_coord_precision
));
2056 int resource_id
= quad
->resource_id
;
2058 if (draw_cache_
.program_id
!= binding
.program_id
||
2059 draw_cache_
.resource_id
!= resource_id
||
2060 draw_cache_
.needs_blending
!= quad
->ShouldDrawWithBlending() ||
2061 draw_cache_
.background_color
!= quad
->background_color
||
2062 draw_cache_
.matrix_data
.size() >= 8) {
2063 FlushTextureQuadCache();
2064 draw_cache_
.program_id
= binding
.program_id
;
2065 draw_cache_
.resource_id
= resource_id
;
2066 draw_cache_
.needs_blending
= quad
->ShouldDrawWithBlending();
2067 draw_cache_
.background_color
= quad
->background_color
;
2069 draw_cache_
.uv_xform_location
= binding
.tex_transform_location
;
2070 draw_cache_
.background_color_location
= binding
.background_color_location
;
2071 draw_cache_
.vertex_opacity_location
= binding
.vertex_opacity_location
;
2072 draw_cache_
.matrix_location
= binding
.matrix_location
;
2073 draw_cache_
.sampler_location
= binding
.sampler_location
;
2076 // Generate the uv-transform
2077 draw_cache_
.uv_xform_data
.push_back(UVTransform(quad
));
2079 // Generate the vertex opacity
2080 const float opacity
= quad
->opacity();
2081 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[0] * opacity
);
2082 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[1] * opacity
);
2083 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[2] * opacity
);
2084 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[3] * opacity
);
2086 // Generate the transform matrix
2087 gfx::Transform quad_rect_matrix
;
2088 QuadRectTransform(&quad_rect_matrix
, quad
->quadTransform(), quad
->rect
);
2089 quad_rect_matrix
= frame
->projection_matrix
* quad_rect_matrix
;
2092 quad_rect_matrix
.matrix().asColMajorf(m
.data
);
2093 draw_cache_
.matrix_data
.push_back(m
);
2096 void GLRenderer::DrawIOSurfaceQuad(const DrawingFrame
* frame
,
2097 const IOSurfaceDrawQuad
* quad
) {
2098 SetBlendEnabled(quad
->ShouldDrawWithBlending());
2100 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
2102 &highp_threshold_cache_
,
2103 highp_threshold_min_
,
2104 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
2106 TexTransformTextureProgramBinding binding
;
2107 binding
.Set(GetTextureIOSurfaceProgram(tex_coord_precision
));
2109 SetUseProgram(binding
.program_id
);
2110 GLC(gl_
, gl_
->Uniform1i(binding
.sampler_location
, 0));
2111 if (quad
->orientation
== IOSurfaceDrawQuad::FLIPPED
) {
2113 gl_
->Uniform4f(binding
.tex_transform_location
,
2115 quad
->io_surface_size
.height(),
2116 quad
->io_surface_size
.width(),
2117 quad
->io_surface_size
.height() * -1.0f
));
2120 gl_
->Uniform4f(binding
.tex_transform_location
,
2123 quad
->io_surface_size
.width(),
2124 quad
->io_surface_size
.height()));
2127 const float vertex_opacity
[] = {quad
->opacity(), quad
->opacity(),
2128 quad
->opacity(), quad
->opacity()};
2129 GLC(gl_
, gl_
->Uniform1fv(binding
.vertex_opacity_location
, 4, vertex_opacity
));
2131 ResourceProvider::ScopedReadLockGL
lock(resource_provider_
,
2132 quad
->io_surface_resource_id
);
2133 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
2134 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_RECTANGLE_ARB
, lock
.texture_id()));
2137 frame
, quad
->quadTransform(), quad
->rect
, binding
.matrix_location
);
2139 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_RECTANGLE_ARB
, 0));
2142 void GLRenderer::FinishDrawingFrame(DrawingFrame
* frame
) {
2143 if (use_sync_query_
) {
2144 DCHECK(current_sync_query_
);
2145 current_sync_query_
->End();
2146 pending_sync_queries_
.push_back(current_sync_query_
.Pass());
2149 current_framebuffer_lock_
.reset();
2150 swap_buffer_rect_
.Union(gfx::ToEnclosingRect(frame
->root_damage_rect
));
2152 GLC(gl_
, gl_
->Disable(GL_BLEND
));
2153 blend_shadow_
= false;
2155 ScheduleOverlays(frame
);
2158 void GLRenderer::FinishDrawingQuadList() { FlushTextureQuadCache(); }
2160 bool GLRenderer::FlippedFramebuffer() const { return true; }
2162 void GLRenderer::EnsureScissorTestEnabled() {
2163 if (is_scissor_enabled_
)
2166 FlushTextureQuadCache();
2167 GLC(gl_
, gl_
->Enable(GL_SCISSOR_TEST
));
2168 is_scissor_enabled_
= true;
2171 void GLRenderer::EnsureScissorTestDisabled() {
2172 if (!is_scissor_enabled_
)
2175 FlushTextureQuadCache();
2176 GLC(gl_
, gl_
->Disable(GL_SCISSOR_TEST
));
2177 is_scissor_enabled_
= false;
2180 void GLRenderer::CopyCurrentRenderPassToBitmap(
2181 DrawingFrame
* frame
,
2182 scoped_ptr
<CopyOutputRequest
> request
) {
2183 TRACE_EVENT0("cc", "GLRenderer::CopyCurrentRenderPassToBitmap");
2184 gfx::Rect copy_rect
= frame
->current_render_pass
->output_rect
;
2185 if (request
->has_area())
2186 copy_rect
.Intersect(request
->area());
2187 GetFramebufferPixelsAsync(copy_rect
, request
.Pass());
2190 void GLRenderer::ToGLMatrix(float* gl_matrix
, const gfx::Transform
& transform
) {
2191 transform
.matrix().asColMajorf(gl_matrix
);
2194 void GLRenderer::SetShaderQuadF(const gfx::QuadF
& quad
, int quad_location
) {
2195 if (quad_location
== -1)
2199 gl_quad
[0] = quad
.p1().x();
2200 gl_quad
[1] = quad
.p1().y();
2201 gl_quad
[2] = quad
.p2().x();
2202 gl_quad
[3] = quad
.p2().y();
2203 gl_quad
[4] = quad
.p3().x();
2204 gl_quad
[5] = quad
.p3().y();
2205 gl_quad
[6] = quad
.p4().x();
2206 gl_quad
[7] = quad
.p4().y();
2207 GLC(gl_
, gl_
->Uniform2fv(quad_location
, 4, gl_quad
));
2210 void GLRenderer::SetShaderOpacity(float opacity
, int alpha_location
) {
2211 if (alpha_location
!= -1)
2212 GLC(gl_
, gl_
->Uniform1f(alpha_location
, opacity
));
2215 void GLRenderer::SetStencilEnabled(bool enabled
) {
2216 if (enabled
== stencil_shadow_
)
2220 GLC(gl_
, gl_
->Enable(GL_STENCIL_TEST
));
2222 GLC(gl_
, gl_
->Disable(GL_STENCIL_TEST
));
2223 stencil_shadow_
= enabled
;
2226 void GLRenderer::SetBlendEnabled(bool enabled
) {
2227 if (enabled
== blend_shadow_
)
2231 GLC(gl_
, gl_
->Enable(GL_BLEND
));
2233 GLC(gl_
, gl_
->Disable(GL_BLEND
));
2234 blend_shadow_
= enabled
;
2237 void GLRenderer::SetUseProgram(unsigned program
) {
2238 if (program
== program_shadow_
)
2240 gl_
->UseProgram(program
);
2241 program_shadow_
= program
;
2244 void GLRenderer::DrawQuadGeometry(const DrawingFrame
* frame
,
2245 const gfx::Transform
& draw_transform
,
2246 const gfx::RectF
& quad_rect
,
2247 int matrix_location
) {
2248 gfx::Transform quad_rect_matrix
;
2249 QuadRectTransform(&quad_rect_matrix
, draw_transform
, quad_rect
);
2250 static float gl_matrix
[16];
2251 ToGLMatrix(&gl_matrix
[0], frame
->projection_matrix
* quad_rect_matrix
);
2252 GLC(gl_
, gl_
->UniformMatrix4fv(matrix_location
, 1, false, &gl_matrix
[0]));
2254 GLC(gl_
, gl_
->DrawElements(GL_TRIANGLES
, 6, GL_UNSIGNED_SHORT
, 0));
2257 void GLRenderer::CopyTextureToFramebuffer(const DrawingFrame
* frame
,
2259 const gfx::Rect
& rect
,
2260 const gfx::Transform
& draw_matrix
,
2261 bool flip_vertically
) {
2262 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
2263 gl_
, &highp_threshold_cache_
, highp_threshold_min_
, rect
.bottom_right());
2265 const RenderPassProgram
* program
= GetRenderPassProgram(tex_coord_precision
);
2266 SetUseProgram(program
->program());
2268 GLC(gl_
, gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0));
2270 if (flip_vertically
) {
2272 gl_
->Uniform4f(program
->vertex_shader().tex_transform_location(),
2279 gl_
->Uniform4f(program
->vertex_shader().tex_transform_location(),
2286 SetShaderOpacity(1.f
, program
->fragment_shader().alpha_location());
2287 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
2288 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_2D
, texture_id
));
2290 frame
, draw_matrix
, rect
, program
->vertex_shader().matrix_location());
2293 void GLRenderer::Finish() {
2294 TRACE_EVENT0("cc", "GLRenderer::Finish");
2295 GLC(gl_
, gl_
->Finish());
2298 void GLRenderer::SwapBuffers(const CompositorFrameMetadata
& metadata
) {
2299 DCHECK(!is_backbuffer_discarded_
);
2301 TRACE_EVENT0("cc,benchmark", "GLRenderer::SwapBuffers");
2302 // We're done! Time to swapbuffers!
2304 gfx::Size surface_size
= output_surface_
->SurfaceSize();
2306 CompositorFrame compositor_frame
;
2307 compositor_frame
.metadata
= metadata
;
2308 compositor_frame
.gl_frame_data
= make_scoped_ptr(new GLFrameData
);
2309 compositor_frame
.gl_frame_data
->size
= surface_size
;
2310 if (capabilities_
.using_partial_swap
) {
2311 // If supported, we can save significant bandwidth by only swapping the
2312 // damaged/scissored region (clamped to the viewport).
2313 swap_buffer_rect_
.Intersect(gfx::Rect(surface_size
));
2314 int flipped_y_pos_of_rect_bottom
= surface_size
.height() -
2315 swap_buffer_rect_
.y() -
2316 swap_buffer_rect_
.height();
2317 compositor_frame
.gl_frame_data
->sub_buffer_rect
=
2318 gfx::Rect(swap_buffer_rect_
.x(),
2319 flipped_y_pos_of_rect_bottom
,
2320 swap_buffer_rect_
.width(),
2321 swap_buffer_rect_
.height());
2323 compositor_frame
.gl_frame_data
->sub_buffer_rect
=
2324 gfx::Rect(output_surface_
->SurfaceSize());
2326 output_surface_
->SwapBuffers(&compositor_frame
);
2328 // Release previously used overlay resources and hold onto the pending ones
2329 // until the next swap buffers.
2330 in_use_overlay_resources_
.clear();
2331 in_use_overlay_resources_
.swap(pending_overlay_resources_
);
2333 swap_buffer_rect_
= gfx::Rect();
2336 void GLRenderer::EnforceMemoryPolicy() {
2338 TRACE_EVENT0("cc", "GLRenderer::EnforceMemoryPolicy dropping resources");
2339 ReleaseRenderPassTextures();
2340 DiscardBackbuffer();
2341 resource_provider_
->ReleaseCachedData();
2342 output_surface_
->context_provider()->DeleteCachedResources();
2343 GLC(gl_
, gl_
->Flush());
2347 void GLRenderer::DiscardBackbuffer() {
2348 if (is_backbuffer_discarded_
)
2351 output_surface_
->DiscardBackbuffer();
2353 is_backbuffer_discarded_
= true;
2355 // Damage tracker needs a full reset every time framebuffer is discarded.
2356 client_
->SetFullRootLayerDamage();
2359 void GLRenderer::EnsureBackbuffer() {
2360 if (!is_backbuffer_discarded_
)
2363 output_surface_
->EnsureBackbuffer();
2364 is_backbuffer_discarded_
= false;
2367 void GLRenderer::GetFramebufferPixelsAsync(
2368 const gfx::Rect
& rect
,
2369 scoped_ptr
<CopyOutputRequest
> request
) {
2370 DCHECK(!request
->IsEmpty());
2371 if (request
->IsEmpty())
2376 gfx::Rect window_rect
= MoveFromDrawToWindowSpace(rect
);
2377 DCHECK_GE(window_rect
.x(), 0);
2378 DCHECK_GE(window_rect
.y(), 0);
2379 DCHECK_LE(window_rect
.right(), current_surface_size_
.width());
2380 DCHECK_LE(window_rect
.bottom(), current_surface_size_
.height());
2382 if (!request
->force_bitmap_result()) {
2383 bool own_mailbox
= !request
->has_texture_mailbox();
2385 GLuint texture_id
= 0;
2386 gpu::Mailbox mailbox
;
2388 GLC(gl_
, gl_
->GenMailboxCHROMIUM(mailbox
.name
));
2389 gl_
->GenTextures(1, &texture_id
);
2390 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_2D
, texture_id
));
2393 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_LINEAR
));
2395 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAG_FILTER
, GL_LINEAR
));
2398 GL_TEXTURE_2D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
));
2401 GL_TEXTURE_2D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
));
2402 GLC(gl_
, gl_
->ProduceTextureCHROMIUM(GL_TEXTURE_2D
, mailbox
.name
));
2404 mailbox
= request
->texture_mailbox().mailbox();
2405 DCHECK_EQ(static_cast<unsigned>(GL_TEXTURE_2D
),
2406 request
->texture_mailbox().target());
2407 DCHECK(!mailbox
.IsZero());
2408 unsigned incoming_sync_point
= request
->texture_mailbox().sync_point();
2409 if (incoming_sync_point
)
2410 GLC(gl_
, gl_
->WaitSyncPointCHROMIUM(incoming_sync_point
));
2414 gl_
->CreateAndConsumeTextureCHROMIUM(GL_TEXTURE_2D
, mailbox
.name
));
2416 GetFramebufferTexture(texture_id
, RGBA_8888
, window_rect
);
2418 unsigned sync_point
= gl_
->InsertSyncPointCHROMIUM();
2419 TextureMailbox
texture_mailbox(mailbox
, GL_TEXTURE_2D
, sync_point
);
2421 scoped_ptr
<SingleReleaseCallback
> release_callback
;
2423 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_2D
, 0));
2424 release_callback
= texture_mailbox_deleter_
->GetReleaseCallback(
2425 output_surface_
->context_provider(), texture_id
);
2427 gl_
->DeleteTextures(1, &texture_id
);
2430 request
->SendTextureResult(
2431 window_rect
.size(), texture_mailbox
, release_callback
.Pass());
2435 DCHECK(request
->force_bitmap_result());
2437 scoped_ptr
<PendingAsyncReadPixels
> pending_read(new PendingAsyncReadPixels
);
2438 pending_read
->copy_request
= request
.Pass();
2439 pending_async_read_pixels_
.insert(pending_async_read_pixels_
.begin(),
2440 pending_read
.Pass());
2442 bool do_workaround
= NeedsIOSurfaceReadbackWorkaround();
2444 unsigned temporary_texture
= 0;
2445 unsigned temporary_fbo
= 0;
2447 if (do_workaround
) {
2448 // On Mac OS X, calling glReadPixels() against an FBO whose color attachment
2449 // is an IOSurface-backed texture causes corruption of future glReadPixels()
2450 // calls, even those on different OpenGL contexts. It is believed that this
2451 // is the root cause of top crasher
2452 // http://crbug.com/99393. <rdar://problem/10949687>
2454 gl_
->GenTextures(1, &temporary_texture
);
2455 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_2D
, temporary_texture
));
2457 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_LINEAR
));
2459 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAG_FILTER
, GL_LINEAR
));
2461 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
));
2463 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
));
2464 // Copy the contents of the current (IOSurface-backed) framebuffer into a
2465 // temporary texture.
2466 GetFramebufferTexture(
2467 temporary_texture
, RGBA_8888
, gfx::Rect(current_surface_size_
));
2468 gl_
->GenFramebuffers(1, &temporary_fbo
);
2469 // Attach this texture to an FBO, and perform the readback from that FBO.
2470 GLC(gl_
, gl_
->BindFramebuffer(GL_FRAMEBUFFER
, temporary_fbo
));
2472 gl_
->FramebufferTexture2D(GL_FRAMEBUFFER
,
2473 GL_COLOR_ATTACHMENT0
,
2478 DCHECK_EQ(static_cast<unsigned>(GL_FRAMEBUFFER_COMPLETE
),
2479 gl_
->CheckFramebufferStatus(GL_FRAMEBUFFER
));
2483 gl_
->GenBuffers(1, &buffer
);
2484 GLC(gl_
, gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, buffer
));
2486 gl_
->BufferData(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
,
2487 4 * window_rect
.size().GetArea(),
2492 gl_
->GenQueriesEXT(1, &query
);
2493 GLC(gl_
, gl_
->BeginQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM
, query
));
2496 gl_
->ReadPixels(window_rect
.x(),
2498 window_rect
.width(),
2499 window_rect
.height(),
2504 GLC(gl_
, gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, 0));
2506 if (do_workaround
) {
2508 GLC(gl_
, gl_
->BindFramebuffer(GL_FRAMEBUFFER
, 0));
2509 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_2D
, 0));
2510 GLC(gl_
, gl_
->DeleteFramebuffers(1, &temporary_fbo
));
2511 GLC(gl_
, gl_
->DeleteTextures(1, &temporary_texture
));
2514 base::Closure finished_callback
= base::Bind(&GLRenderer::FinishedReadback
,
2515 base::Unretained(this),
2518 window_rect
.size());
2519 // Save the finished_callback so it can be cancelled.
2520 pending_async_read_pixels_
.front()->finished_read_pixels_callback
.Reset(
2522 base::Closure cancelable_callback
=
2523 pending_async_read_pixels_
.front()->
2524 finished_read_pixels_callback
.callback();
2526 // Save the buffer to verify the callbacks happen in the expected order.
2527 pending_async_read_pixels_
.front()->buffer
= buffer
;
2529 GLC(gl_
, gl_
->EndQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM
));
2530 context_support_
->SignalQuery(query
, cancelable_callback
);
2532 EnforceMemoryPolicy();
2535 void GLRenderer::FinishedReadback(unsigned source_buffer
,
2537 const gfx::Size
& size
) {
2538 DCHECK(!pending_async_read_pixels_
.empty());
2541 GLC(gl_
, gl_
->DeleteQueriesEXT(1, &query
));
2544 PendingAsyncReadPixels
* current_read
= pending_async_read_pixels_
.back();
2545 // Make sure we service the readbacks in order.
2546 DCHECK_EQ(source_buffer
, current_read
->buffer
);
2548 uint8
* src_pixels
= NULL
;
2549 scoped_ptr
<SkBitmap
> bitmap
;
2551 if (source_buffer
!= 0) {
2553 gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, source_buffer
));
2554 src_pixels
= static_cast<uint8
*>(gl_
->MapBufferCHROMIUM(
2555 GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, GL_READ_ONLY
));
2558 bitmap
.reset(new SkBitmap
);
2559 bitmap
->allocN32Pixels(size
.width(), size
.height());
2560 scoped_ptr
<SkAutoLockPixels
> lock(new SkAutoLockPixels(*bitmap
));
2561 uint8
* dest_pixels
= static_cast<uint8
*>(bitmap
->getPixels());
2563 size_t row_bytes
= size
.width() * 4;
2564 int num_rows
= size
.height();
2565 size_t total_bytes
= num_rows
* row_bytes
;
2566 for (size_t dest_y
= 0; dest_y
< total_bytes
; dest_y
+= row_bytes
) {
2568 size_t src_y
= total_bytes
- dest_y
- row_bytes
;
2569 // Swizzle OpenGL -> Skia byte order.
2570 for (size_t x
= 0; x
< row_bytes
; x
+= 4) {
2571 dest_pixels
[dest_y
+ x
+ SK_R32_SHIFT
/ 8] =
2572 src_pixels
[src_y
+ x
+ 0];
2573 dest_pixels
[dest_y
+ x
+ SK_G32_SHIFT
/ 8] =
2574 src_pixels
[src_y
+ x
+ 1];
2575 dest_pixels
[dest_y
+ x
+ SK_B32_SHIFT
/ 8] =
2576 src_pixels
[src_y
+ x
+ 2];
2577 dest_pixels
[dest_y
+ x
+ SK_A32_SHIFT
/ 8] =
2578 src_pixels
[src_y
+ x
+ 3];
2583 gl_
->UnmapBufferCHROMIUM(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
));
2585 GLC(gl_
, gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, 0));
2586 GLC(gl_
, gl_
->DeleteBuffers(1, &source_buffer
));
2590 current_read
->copy_request
->SendBitmapResult(bitmap
.Pass());
2591 pending_async_read_pixels_
.pop_back();
2594 void GLRenderer::GetFramebufferTexture(unsigned texture_id
,
2595 ResourceFormat texture_format
,
2596 const gfx::Rect
& window_rect
) {
2598 DCHECK_GE(window_rect
.x(), 0);
2599 DCHECK_GE(window_rect
.y(), 0);
2600 DCHECK_LE(window_rect
.right(), current_surface_size_
.width());
2601 DCHECK_LE(window_rect
.bottom(), current_surface_size_
.height());
2603 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_2D
, texture_id
));
2605 gl_
->CopyTexImage2D(GL_TEXTURE_2D
,
2607 GLDataFormat(texture_format
),
2610 window_rect
.width(),
2611 window_rect
.height(),
2613 GLC(gl_
, gl_
->BindTexture(GL_TEXTURE_2D
, 0));
2616 bool GLRenderer::UseScopedTexture(DrawingFrame
* frame
,
2617 const ScopedResource
* texture
,
2618 const gfx::Rect
& viewport_rect
) {
2619 DCHECK(texture
->id());
2620 frame
->current_render_pass
= NULL
;
2621 frame
->current_texture
= texture
;
2623 return BindFramebufferToTexture(frame
, texture
, viewport_rect
);
2626 void GLRenderer::BindFramebufferToOutputSurface(DrawingFrame
* frame
) {
2627 current_framebuffer_lock_
.reset();
2628 output_surface_
->BindFramebuffer();
2630 if (output_surface_
->HasExternalStencilTest()) {
2631 SetStencilEnabled(true);
2632 GLC(gl_
, gl_
->StencilFunc(GL_EQUAL
, 1, 1));
2634 SetStencilEnabled(false);
2638 bool GLRenderer::BindFramebufferToTexture(DrawingFrame
* frame
,
2639 const ScopedResource
* texture
,
2640 const gfx::Rect
& target_rect
) {
2641 DCHECK(texture
->id());
2643 current_framebuffer_lock_
.reset();
2645 SetStencilEnabled(false);
2646 GLC(gl_
, gl_
->BindFramebuffer(GL_FRAMEBUFFER
, offscreen_framebuffer_id_
));
2647 current_framebuffer_lock_
=
2648 make_scoped_ptr(new ResourceProvider::ScopedWriteLockGL(
2649 resource_provider_
, texture
->id()));
2650 unsigned texture_id
= current_framebuffer_lock_
->texture_id();
2652 gl_
->FramebufferTexture2D(
2653 GL_FRAMEBUFFER
, GL_COLOR_ATTACHMENT0
, GL_TEXTURE_2D
, texture_id
, 0));
2655 DCHECK(gl_
->CheckFramebufferStatus(GL_FRAMEBUFFER
) ==
2656 GL_FRAMEBUFFER_COMPLETE
||
2660 frame
, target_rect
, gfx::Rect(target_rect
.size()), target_rect
.size());
2664 void GLRenderer::SetScissorTestRect(const gfx::Rect
& scissor_rect
) {
2665 EnsureScissorTestEnabled();
2667 // Don't unnecessarily ask the context to change the scissor, because it
2668 // may cause undesired GPU pipeline flushes.
2669 if (scissor_rect
== scissor_rect_
&& !scissor_rect_needs_reset_
)
2672 scissor_rect_
= scissor_rect
;
2673 FlushTextureQuadCache();
2675 gl_
->Scissor(scissor_rect
.x(),
2677 scissor_rect
.width(),
2678 scissor_rect
.height()));
2680 scissor_rect_needs_reset_
= false;
2683 void GLRenderer::SetDrawViewport(const gfx::Rect
& window_space_viewport
) {
2684 viewport_
= window_space_viewport
;
2686 gl_
->Viewport(window_space_viewport
.x(),
2687 window_space_viewport
.y(),
2688 window_space_viewport
.width(),
2689 window_space_viewport
.height()));
2692 void GLRenderer::InitializeSharedObjects() {
2693 TRACE_EVENT0("cc", "GLRenderer::InitializeSharedObjects");
2695 // Create an FBO for doing offscreen rendering.
2696 GLC(gl_
, gl_
->GenFramebuffers(1, &offscreen_framebuffer_id_
));
2698 shared_geometry_
= make_scoped_ptr(
2699 new GeometryBinding(gl_
, QuadVertexRect()));
2702 const GLRenderer::TileCheckerboardProgram
*
2703 GLRenderer::GetTileCheckerboardProgram() {
2704 if (!tile_checkerboard_program_
.initialized()) {
2705 TRACE_EVENT0("cc", "GLRenderer::checkerboardProgram::initalize");
2706 tile_checkerboard_program_
.Initialize(output_surface_
->context_provider(),
2707 TexCoordPrecisionNA
,
2710 return &tile_checkerboard_program_
;
2713 const GLRenderer::DebugBorderProgram
* GLRenderer::GetDebugBorderProgram() {
2714 if (!debug_border_program_
.initialized()) {
2715 TRACE_EVENT0("cc", "GLRenderer::debugBorderProgram::initialize");
2716 debug_border_program_
.Initialize(output_surface_
->context_provider(),
2717 TexCoordPrecisionNA
,
2720 return &debug_border_program_
;
2723 const GLRenderer::SolidColorProgram
* GLRenderer::GetSolidColorProgram() {
2724 if (!solid_color_program_
.initialized()) {
2725 TRACE_EVENT0("cc", "GLRenderer::solidColorProgram::initialize");
2726 solid_color_program_
.Initialize(output_surface_
->context_provider(),
2727 TexCoordPrecisionNA
,
2730 return &solid_color_program_
;
2733 const GLRenderer::SolidColorProgramAA
* GLRenderer::GetSolidColorProgramAA() {
2734 if (!solid_color_program_aa_
.initialized()) {
2735 TRACE_EVENT0("cc", "GLRenderer::solidColorProgramAA::initialize");
2736 solid_color_program_aa_
.Initialize(output_surface_
->context_provider(),
2737 TexCoordPrecisionNA
,
2740 return &solid_color_program_aa_
;
2743 const GLRenderer::RenderPassProgram
* GLRenderer::GetRenderPassProgram(
2744 TexCoordPrecision precision
) {
2745 DCHECK_GE(precision
, 0);
2746 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2747 RenderPassProgram
* program
= &render_pass_program_
[precision
];
2748 if (!program
->initialized()) {
2749 TRACE_EVENT0("cc", "GLRenderer::renderPassProgram::initialize");
2750 program
->Initialize(
2751 output_surface_
->context_provider(), precision
, SamplerType2D
);
2756 const GLRenderer::RenderPassProgramAA
* GLRenderer::GetRenderPassProgramAA(
2757 TexCoordPrecision precision
) {
2758 DCHECK_GE(precision
, 0);
2759 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2760 RenderPassProgramAA
* program
= &render_pass_program_aa_
[precision
];
2761 if (!program
->initialized()) {
2762 TRACE_EVENT0("cc", "GLRenderer::renderPassProgramAA::initialize");
2763 program
->Initialize(
2764 output_surface_
->context_provider(), precision
, SamplerType2D
);
2769 const GLRenderer::RenderPassMaskProgram
* GLRenderer::GetRenderPassMaskProgram(
2770 TexCoordPrecision precision
) {
2771 DCHECK_GE(precision
, 0);
2772 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2773 RenderPassMaskProgram
* program
= &render_pass_mask_program_
[precision
];
2774 if (!program
->initialized()) {
2775 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgram::initialize");
2776 program
->Initialize(
2777 output_surface_
->context_provider(), precision
, SamplerType2D
);
2782 const GLRenderer::RenderPassMaskProgramAA
*
2783 GLRenderer::GetRenderPassMaskProgramAA(TexCoordPrecision precision
) {
2784 DCHECK_GE(precision
, 0);
2785 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2786 RenderPassMaskProgramAA
* program
= &render_pass_mask_program_aa_
[precision
];
2787 if (!program
->initialized()) {
2788 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgramAA::initialize");
2789 program
->Initialize(
2790 output_surface_
->context_provider(), precision
, SamplerType2D
);
2795 const GLRenderer::RenderPassColorMatrixProgram
*
2796 GLRenderer::GetRenderPassColorMatrixProgram(TexCoordPrecision precision
) {
2797 DCHECK_GE(precision
, 0);
2798 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2799 RenderPassColorMatrixProgram
* program
=
2800 &render_pass_color_matrix_program_
[precision
];
2801 if (!program
->initialized()) {
2802 TRACE_EVENT0("cc", "GLRenderer::renderPassColorMatrixProgram::initialize");
2803 program
->Initialize(
2804 output_surface_
->context_provider(), precision
, SamplerType2D
);
2809 const GLRenderer::RenderPassColorMatrixProgramAA
*
2810 GLRenderer::GetRenderPassColorMatrixProgramAA(TexCoordPrecision precision
) {
2811 DCHECK_GE(precision
, 0);
2812 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2813 RenderPassColorMatrixProgramAA
* program
=
2814 &render_pass_color_matrix_program_aa_
[precision
];
2815 if (!program
->initialized()) {
2817 "GLRenderer::renderPassColorMatrixProgramAA::initialize");
2818 program
->Initialize(
2819 output_surface_
->context_provider(), precision
, SamplerType2D
);
2824 const GLRenderer::RenderPassMaskColorMatrixProgram
*
2825 GLRenderer::GetRenderPassMaskColorMatrixProgram(TexCoordPrecision precision
) {
2826 DCHECK_GE(precision
, 0);
2827 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2828 RenderPassMaskColorMatrixProgram
* program
=
2829 &render_pass_mask_color_matrix_program_
[precision
];
2830 if (!program
->initialized()) {
2832 "GLRenderer::renderPassMaskColorMatrixProgram::initialize");
2833 program
->Initialize(
2834 output_surface_
->context_provider(), precision
, SamplerType2D
);
2839 const GLRenderer::RenderPassMaskColorMatrixProgramAA
*
2840 GLRenderer::GetRenderPassMaskColorMatrixProgramAA(TexCoordPrecision precision
) {
2841 DCHECK_GE(precision
, 0);
2842 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2843 RenderPassMaskColorMatrixProgramAA
* program
=
2844 &render_pass_mask_color_matrix_program_aa_
[precision
];
2845 if (!program
->initialized()) {
2847 "GLRenderer::renderPassMaskColorMatrixProgramAA::initialize");
2848 program
->Initialize(
2849 output_surface_
->context_provider(), precision
, SamplerType2D
);
2854 const GLRenderer::TileProgram
* GLRenderer::GetTileProgram(
2855 TexCoordPrecision precision
,
2856 SamplerType sampler
) {
2857 DCHECK_GE(precision
, 0);
2858 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2859 DCHECK_GE(sampler
, 0);
2860 DCHECK_LT(sampler
, NumSamplerTypes
);
2861 TileProgram
* program
= &tile_program_
[precision
][sampler
];
2862 if (!program
->initialized()) {
2863 TRACE_EVENT0("cc", "GLRenderer::tileProgram::initialize");
2864 program
->Initialize(
2865 output_surface_
->context_provider(), precision
, sampler
);
2870 const GLRenderer::TileProgramOpaque
* GLRenderer::GetTileProgramOpaque(
2871 TexCoordPrecision precision
,
2872 SamplerType sampler
) {
2873 DCHECK_GE(precision
, 0);
2874 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2875 DCHECK_GE(sampler
, 0);
2876 DCHECK_LT(sampler
, NumSamplerTypes
);
2877 TileProgramOpaque
* program
= &tile_program_opaque_
[precision
][sampler
];
2878 if (!program
->initialized()) {
2879 TRACE_EVENT0("cc", "GLRenderer::tileProgramOpaque::initialize");
2880 program
->Initialize(
2881 output_surface_
->context_provider(), precision
, sampler
);
2886 const GLRenderer::TileProgramAA
* GLRenderer::GetTileProgramAA(
2887 TexCoordPrecision precision
,
2888 SamplerType sampler
) {
2889 DCHECK_GE(precision
, 0);
2890 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2891 DCHECK_GE(sampler
, 0);
2892 DCHECK_LT(sampler
, NumSamplerTypes
);
2893 TileProgramAA
* program
= &tile_program_aa_
[precision
][sampler
];
2894 if (!program
->initialized()) {
2895 TRACE_EVENT0("cc", "GLRenderer::tileProgramAA::initialize");
2896 program
->Initialize(
2897 output_surface_
->context_provider(), precision
, sampler
);
2902 const GLRenderer::TileProgramSwizzle
* GLRenderer::GetTileProgramSwizzle(
2903 TexCoordPrecision precision
,
2904 SamplerType sampler
) {
2905 DCHECK_GE(precision
, 0);
2906 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2907 DCHECK_GE(sampler
, 0);
2908 DCHECK_LT(sampler
, NumSamplerTypes
);
2909 TileProgramSwizzle
* program
= &tile_program_swizzle_
[precision
][sampler
];
2910 if (!program
->initialized()) {
2911 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzle::initialize");
2912 program
->Initialize(
2913 output_surface_
->context_provider(), precision
, sampler
);
2918 const GLRenderer::TileProgramSwizzleOpaque
*
2919 GLRenderer::GetTileProgramSwizzleOpaque(TexCoordPrecision precision
,
2920 SamplerType sampler
) {
2921 DCHECK_GE(precision
, 0);
2922 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2923 DCHECK_GE(sampler
, 0);
2924 DCHECK_LT(sampler
, NumSamplerTypes
);
2925 TileProgramSwizzleOpaque
* program
=
2926 &tile_program_swizzle_opaque_
[precision
][sampler
];
2927 if (!program
->initialized()) {
2928 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleOpaque::initialize");
2929 program
->Initialize(
2930 output_surface_
->context_provider(), precision
, sampler
);
2935 const GLRenderer::TileProgramSwizzleAA
* GLRenderer::GetTileProgramSwizzleAA(
2936 TexCoordPrecision precision
,
2937 SamplerType sampler
) {
2938 DCHECK_GE(precision
, 0);
2939 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2940 DCHECK_GE(sampler
, 0);
2941 DCHECK_LT(sampler
, NumSamplerTypes
);
2942 TileProgramSwizzleAA
* program
= &tile_program_swizzle_aa_
[precision
][sampler
];
2943 if (!program
->initialized()) {
2944 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleAA::initialize");
2945 program
->Initialize(
2946 output_surface_
->context_provider(), precision
, sampler
);
2951 const GLRenderer::TextureProgram
* GLRenderer::GetTextureProgram(
2952 TexCoordPrecision precision
) {
2953 DCHECK_GE(precision
, 0);
2954 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2955 TextureProgram
* program
= &texture_program_
[precision
];
2956 if (!program
->initialized()) {
2957 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
2958 program
->Initialize(
2959 output_surface_
->context_provider(), precision
, SamplerType2D
);
2964 const GLRenderer::NonPremultipliedTextureProgram
*
2965 GLRenderer::GetNonPremultipliedTextureProgram(TexCoordPrecision precision
) {
2966 DCHECK_GE(precision
, 0);
2967 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2968 NonPremultipliedTextureProgram
* program
=
2969 &nonpremultiplied_texture_program_
[precision
];
2970 if (!program
->initialized()) {
2972 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
2973 program
->Initialize(
2974 output_surface_
->context_provider(), precision
, SamplerType2D
);
2979 const GLRenderer::TextureBackgroundProgram
*
2980 GLRenderer::GetTextureBackgroundProgram(TexCoordPrecision precision
) {
2981 DCHECK_GE(precision
, 0);
2982 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2983 TextureBackgroundProgram
* program
= &texture_background_program_
[precision
];
2984 if (!program
->initialized()) {
2985 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
2986 program
->Initialize(
2987 output_surface_
->context_provider(), precision
, SamplerType2D
);
2992 const GLRenderer::NonPremultipliedTextureBackgroundProgram
*
2993 GLRenderer::GetNonPremultipliedTextureBackgroundProgram(
2994 TexCoordPrecision precision
) {
2995 DCHECK_GE(precision
, 0);
2996 DCHECK_LT(precision
, NumTexCoordPrecisions
);
2997 NonPremultipliedTextureBackgroundProgram
* program
=
2998 &nonpremultiplied_texture_background_program_
[precision
];
2999 if (!program
->initialized()) {
3001 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3002 program
->Initialize(
3003 output_surface_
->context_provider(), precision
, SamplerType2D
);
3008 const GLRenderer::TextureProgram
* GLRenderer::GetTextureIOSurfaceProgram(
3009 TexCoordPrecision precision
) {
3010 DCHECK_GE(precision
, 0);
3011 DCHECK_LT(precision
, NumTexCoordPrecisions
);
3012 TextureProgram
* program
= &texture_io_surface_program_
[precision
];
3013 if (!program
->initialized()) {
3014 TRACE_EVENT0("cc", "GLRenderer::textureIOSurfaceProgram::initialize");
3015 program
->Initialize(
3016 output_surface_
->context_provider(), precision
, SamplerType2DRect
);
3021 const GLRenderer::VideoYUVProgram
* GLRenderer::GetVideoYUVProgram(
3022 TexCoordPrecision precision
) {
3023 DCHECK_GE(precision
, 0);
3024 DCHECK_LT(precision
, NumTexCoordPrecisions
);
3025 VideoYUVProgram
* program
= &video_yuv_program_
[precision
];
3026 if (!program
->initialized()) {
3027 TRACE_EVENT0("cc", "GLRenderer::videoYUVProgram::initialize");
3028 program
->Initialize(
3029 output_surface_
->context_provider(), precision
, SamplerType2D
);
3034 const GLRenderer::VideoYUVAProgram
* GLRenderer::GetVideoYUVAProgram(
3035 TexCoordPrecision precision
) {
3036 DCHECK_GE(precision
, 0);
3037 DCHECK_LT(precision
, NumTexCoordPrecisions
);
3038 VideoYUVAProgram
* program
= &video_yuva_program_
[precision
];
3039 if (!program
->initialized()) {
3040 TRACE_EVENT0("cc", "GLRenderer::videoYUVAProgram::initialize");
3041 program
->Initialize(
3042 output_surface_
->context_provider(), precision
, SamplerType2D
);
3047 const GLRenderer::VideoStreamTextureProgram
*
3048 GLRenderer::GetVideoStreamTextureProgram(TexCoordPrecision precision
) {
3049 if (!Capabilities().using_egl_image
)
3051 DCHECK_GE(precision
, 0);
3052 DCHECK_LT(precision
, NumTexCoordPrecisions
);
3053 VideoStreamTextureProgram
* program
=
3054 &video_stream_texture_program_
[precision
];
3055 if (!program
->initialized()) {
3056 TRACE_EVENT0("cc", "GLRenderer::streamTextureProgram::initialize");
3057 program
->Initialize(
3058 output_surface_
->context_provider(), precision
, SamplerTypeExternalOES
);
3063 void GLRenderer::CleanupSharedObjects() {
3064 shared_geometry_
.reset();
3066 for (int i
= 0; i
< NumTexCoordPrecisions
; ++i
) {
3067 for (int j
= 0; j
< NumSamplerTypes
; ++j
) {
3068 tile_program_
[i
][j
].Cleanup(gl_
);
3069 tile_program_opaque_
[i
][j
].Cleanup(gl_
);
3070 tile_program_swizzle_
[i
][j
].Cleanup(gl_
);
3071 tile_program_swizzle_opaque_
[i
][j
].Cleanup(gl_
);
3072 tile_program_aa_
[i
][j
].Cleanup(gl_
);
3073 tile_program_swizzle_aa_
[i
][j
].Cleanup(gl_
);
3076 render_pass_mask_program_
[i
].Cleanup(gl_
);
3077 render_pass_program_
[i
].Cleanup(gl_
);
3078 render_pass_mask_program_aa_
[i
].Cleanup(gl_
);
3079 render_pass_program_aa_
[i
].Cleanup(gl_
);
3080 render_pass_color_matrix_program_
[i
].Cleanup(gl_
);
3081 render_pass_mask_color_matrix_program_aa_
[i
].Cleanup(gl_
);
3082 render_pass_color_matrix_program_aa_
[i
].Cleanup(gl_
);
3083 render_pass_mask_color_matrix_program_
[i
].Cleanup(gl_
);
3085 texture_program_
[i
].Cleanup(gl_
);
3086 nonpremultiplied_texture_program_
[i
].Cleanup(gl_
);
3087 texture_background_program_
[i
].Cleanup(gl_
);
3088 nonpremultiplied_texture_background_program_
[i
].Cleanup(gl_
);
3089 texture_io_surface_program_
[i
].Cleanup(gl_
);
3091 video_yuv_program_
[i
].Cleanup(gl_
);
3092 video_yuva_program_
[i
].Cleanup(gl_
);
3093 video_stream_texture_program_
[i
].Cleanup(gl_
);
3096 tile_checkerboard_program_
.Cleanup(gl_
);
3098 debug_border_program_
.Cleanup(gl_
);
3099 solid_color_program_
.Cleanup(gl_
);
3100 solid_color_program_aa_
.Cleanup(gl_
);
3102 if (offscreen_framebuffer_id_
)
3103 GLC(gl_
, gl_
->DeleteFramebuffers(1, &offscreen_framebuffer_id_
));
3105 if (on_demand_tile_raster_resource_id_
)
3106 resource_provider_
->DeleteResource(on_demand_tile_raster_resource_id_
);
3108 ReleaseRenderPassTextures();
3111 void GLRenderer::ReinitializeGLState() {
3112 is_scissor_enabled_
= false;
3113 scissor_rect_needs_reset_
= true;
3114 stencil_shadow_
= false;
3115 blend_shadow_
= true;
3116 program_shadow_
= 0;
3121 void GLRenderer::RestoreGLState() {
3122 // This restores the current GLRenderer state to the GL context.
3124 shared_geometry_
->PrepareForDraw();
3126 GLC(gl_
, gl_
->Disable(GL_DEPTH_TEST
));
3127 GLC(gl_
, gl_
->Disable(GL_CULL_FACE
));
3128 GLC(gl_
, gl_
->ColorMask(true, true, true, true));
3129 GLC(gl_
, gl_
->BlendFunc(GL_ONE
, GL_ONE_MINUS_SRC_ALPHA
));
3130 GLC(gl_
, gl_
->ActiveTexture(GL_TEXTURE0
));
3132 if (program_shadow_
)
3133 gl_
->UseProgram(program_shadow_
);
3135 if (stencil_shadow_
)
3136 GLC(gl_
, gl_
->Enable(GL_STENCIL_TEST
));
3138 GLC(gl_
, gl_
->Disable(GL_STENCIL_TEST
));
3141 GLC(gl_
, gl_
->Enable(GL_BLEND
));
3143 GLC(gl_
, gl_
->Disable(GL_BLEND
));
3145 if (is_scissor_enabled_
) {
3146 GLC(gl_
, gl_
->Enable(GL_SCISSOR_TEST
));
3148 gl_
->Scissor(scissor_rect_
.x(),
3150 scissor_rect_
.width(),
3151 scissor_rect_
.height()));
3153 GLC(gl_
, gl_
->Disable(GL_SCISSOR_TEST
));
3157 void GLRenderer::RestoreFramebuffer(DrawingFrame
* frame
) {
3158 UseRenderPass(frame
, frame
->current_render_pass
);
3161 bool GLRenderer::IsContextLost() {
3162 return output_surface_
->context_provider()->IsContextLost();
3165 void GLRenderer::ScheduleOverlays(DrawingFrame
* frame
) {
3166 if (!frame
->overlay_list
.size())
3169 ResourceProvider::ResourceIdArray resources
;
3170 OverlayCandidateList
& overlays
= frame
->overlay_list
;
3171 OverlayCandidateList::iterator it
;
3172 for (it
= overlays
.begin(); it
!= overlays
.end(); ++it
) {
3173 const OverlayCandidate
& overlay
= *it
;
3174 // Skip primary plane.
3175 if (overlay
.plane_z_order
== 0)
3178 pending_overlay_resources_
.push_back(
3179 make_scoped_ptr(new ResourceProvider::ScopedReadLockGL(
3180 resource_provider_
, overlay
.resource_id
)));
3182 context_support_
->ScheduleOverlayPlane(
3183 overlay
.plane_z_order
,
3185 pending_overlay_resources_
.back()->texture_id(),
3186 overlay
.display_rect
,