1 // Copyright 2010 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "cc/output/gl_renderer.h"
13 #include "base/logging.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "build/build_config.h"
19 #include "base/trace_event/trace_event.h"
20 #include "cc/base/math_util.h"
21 #include "cc/output/compositor_frame.h"
22 #include "cc/output/compositor_frame_metadata.h"
23 #include "cc/output/context_provider.h"
24 #include "cc/output/copy_output_request.h"
25 #include "cc/output/dynamic_geometry_binding.h"
26 #include "cc/output/gl_frame_data.h"
27 #include "cc/output/layer_quad.h"
28 #include "cc/output/output_surface.h"
29 #include "cc/output/render_surface_filters.h"
30 #include "cc/output/static_geometry_binding.h"
31 #include "cc/output/texture_mailbox_deleter.h"
32 #include "cc/quads/draw_polygon.h"
33 #include "cc/quads/picture_draw_quad.h"
34 #include "cc/quads/render_pass.h"
35 #include "cc/quads/stream_video_draw_quad.h"
36 #include "cc/quads/texture_draw_quad.h"
37 #include "cc/raster/scoped_gpu_raster.h"
38 #include "cc/resources/scoped_resource.h"
39 #include "gpu/GLES2/gl2extchromium.h"
40 #include "gpu/command_buffer/client/context_support.h"
41 #include "gpu/command_buffer/client/gles2_interface.h"
42 #include "gpu/command_buffer/common/gpu_memory_allocation.h"
43 #include "third_party/skia/include/core/SkBitmap.h"
44 #include "third_party/skia/include/core/SkColor.h"
45 #include "third_party/skia/include/core/SkColorFilter.h"
46 #include "third_party/skia/include/core/SkImage.h"
47 #include "third_party/skia/include/core/SkSurface.h"
48 #include "third_party/skia/include/gpu/GrContext.h"
49 #include "third_party/skia/include/gpu/GrTexture.h"
50 #include "third_party/skia/include/gpu/GrTextureProvider.h"
51 #include "third_party/skia/include/gpu/SkGrTexturePixelRef.h"
52 #include "third_party/skia/include/gpu/gl/GrGLInterface.h"
53 #include "ui/gfx/geometry/quad_f.h"
54 #include "ui/gfx/geometry/rect_conversions.h"
56 using gpu::gles2::GLES2Interface
;
61 bool NeedsIOSurfaceReadbackWorkaround() {
62 #if defined(OS_MACOSX)
63 // This isn't strictly required in DumpRenderTree-mode when Mesa is used,
64 // but it doesn't seem to hurt.
71 Float4
UVTransform(const TextureDrawQuad
* quad
) {
72 gfx::PointF uv0
= quad
->uv_top_left
;
73 gfx::PointF uv1
= quad
->uv_bottom_right
;
74 Float4 xform
= {{uv0
.x(), uv0
.y(), uv1
.x() - uv0
.x(), uv1
.y() - uv0
.y()}};
75 if (quad
->y_flipped
) {
76 xform
.data
[1] = 1.0f
- xform
.data
[1];
77 xform
.data
[3] = -xform
.data
[3];
82 Float4
PremultipliedColor(SkColor color
) {
83 const float factor
= 1.0f
/ 255.0f
;
84 const float alpha
= SkColorGetA(color
) * factor
;
87 {SkColorGetR(color
) * factor
* alpha
, SkColorGetG(color
) * factor
* alpha
,
88 SkColorGetB(color
) * factor
* alpha
, alpha
}};
92 SamplerType
SamplerTypeFromTextureTarget(GLenum target
) {
95 return SAMPLER_TYPE_2D
;
96 case GL_TEXTURE_RECTANGLE_ARB
:
97 return SAMPLER_TYPE_2D_RECT
;
98 case GL_TEXTURE_EXTERNAL_OES
:
99 return SAMPLER_TYPE_EXTERNAL_OES
;
102 return SAMPLER_TYPE_2D
;
106 BlendMode
BlendModeFromSkXfermode(SkXfermode::Mode mode
) {
108 case SkXfermode::kSrcOver_Mode
:
109 return BLEND_MODE_NORMAL
;
110 case SkXfermode::kScreen_Mode
:
111 return BLEND_MODE_SCREEN
;
112 case SkXfermode::kOverlay_Mode
:
113 return BLEND_MODE_OVERLAY
;
114 case SkXfermode::kDarken_Mode
:
115 return BLEND_MODE_DARKEN
;
116 case SkXfermode::kLighten_Mode
:
117 return BLEND_MODE_LIGHTEN
;
118 case SkXfermode::kColorDodge_Mode
:
119 return BLEND_MODE_COLOR_DODGE
;
120 case SkXfermode::kColorBurn_Mode
:
121 return BLEND_MODE_COLOR_BURN
;
122 case SkXfermode::kHardLight_Mode
:
123 return BLEND_MODE_HARD_LIGHT
;
124 case SkXfermode::kSoftLight_Mode
:
125 return BLEND_MODE_SOFT_LIGHT
;
126 case SkXfermode::kDifference_Mode
:
127 return BLEND_MODE_DIFFERENCE
;
128 case SkXfermode::kExclusion_Mode
:
129 return BLEND_MODE_EXCLUSION
;
130 case SkXfermode::kMultiply_Mode
:
131 return BLEND_MODE_MULTIPLY
;
132 case SkXfermode::kHue_Mode
:
133 return BLEND_MODE_HUE
;
134 case SkXfermode::kSaturation_Mode
:
135 return BLEND_MODE_SATURATION
;
136 case SkXfermode::kColor_Mode
:
137 return BLEND_MODE_COLOR
;
138 case SkXfermode::kLuminosity_Mode
:
139 return BLEND_MODE_LUMINOSITY
;
142 return BLEND_MODE_NONE
;
146 // Smallest unit that impact anti-aliasing output. We use this to
147 // determine when anti-aliasing is unnecessary.
148 const float kAntiAliasingEpsilon
= 1.0f
/ 1024.0f
;
150 // Block or crash if the number of pending sync queries reach this high as
151 // something is seriously wrong on the service side if this happens.
152 const size_t kMaxPendingSyncQueries
= 16;
154 } // anonymous namespace
156 static GLint
GetActiveTextureUnit(GLES2Interface
* gl
) {
157 GLint active_unit
= 0;
158 gl
->GetIntegerv(GL_ACTIVE_TEXTURE
, &active_unit
);
162 class GLRenderer::ScopedUseGrContext
{
164 static scoped_ptr
<ScopedUseGrContext
> Create(GLRenderer
* renderer
,
165 DrawingFrame
* frame
) {
166 // GrContext for filters is created lazily, and may fail if the context
168 // TODO(vmiura,bsalomon): crbug.com/487850 Ensure that
169 // ContextProvider::GrContext() does not return NULL.
170 if (renderer
->output_surface_
->context_provider()->GrContext())
171 return make_scoped_ptr(new ScopedUseGrContext(renderer
, frame
));
175 ~ScopedUseGrContext() {
176 // Pass context control back to GLrenderer.
177 scoped_gpu_raster_
= nullptr;
178 renderer_
->RestoreGLState();
179 renderer_
->RestoreFramebuffer(frame_
);
182 GrContext
* context() const {
183 return renderer_
->output_surface_
->context_provider()->GrContext();
187 ScopedUseGrContext(GLRenderer
* renderer
, DrawingFrame
* frame
)
188 : scoped_gpu_raster_(
189 new ScopedGpuRaster(renderer
->output_surface_
->context_provider())),
192 // scoped_gpu_raster_ passes context control to Skia.
195 scoped_ptr
<ScopedGpuRaster
> scoped_gpu_raster_
;
196 GLRenderer
* renderer_
;
197 DrawingFrame
* frame_
;
199 DISALLOW_COPY_AND_ASSIGN(ScopedUseGrContext
);
202 struct GLRenderer::PendingAsyncReadPixels
{
203 PendingAsyncReadPixels() : buffer(0) {}
205 scoped_ptr
<CopyOutputRequest
> copy_request
;
206 base::CancelableClosure finished_read_pixels_callback
;
210 DISALLOW_COPY_AND_ASSIGN(PendingAsyncReadPixels
);
213 class GLRenderer::SyncQuery
{
215 explicit SyncQuery(gpu::gles2::GLES2Interface
* gl
)
216 : gl_(gl
), query_id_(0u), is_pending_(false), weak_ptr_factory_(this) {
217 gl_
->GenQueriesEXT(1, &query_id_
);
219 virtual ~SyncQuery() { gl_
->DeleteQueriesEXT(1, &query_id_
); }
221 scoped_refptr
<ResourceProvider::Fence
> Begin() {
222 DCHECK(!IsPending());
223 // Invalidate weak pointer held by old fence.
224 weak_ptr_factory_
.InvalidateWeakPtrs();
225 // Note: In case the set of drawing commands issued before End() do not
226 // depend on the query, defer BeginQueryEXT call until Set() is called and
227 // query is required.
228 return make_scoped_refptr
<ResourceProvider::Fence
>(
229 new Fence(weak_ptr_factory_
.GetWeakPtr()));
236 // Note: BeginQueryEXT on GL_COMMANDS_COMPLETED_CHROMIUM is effectively a
237 // noop relative to GL, so it doesn't matter where it happens but we still
238 // make sure to issue this command when Set() is called (prior to issuing
239 // any drawing commands that depend on query), in case some future extension
240 // can take advantage of this.
241 gl_
->BeginQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM
, query_id_
);
249 gl_
->EndQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM
);
256 unsigned result_available
= 1;
257 gl_
->GetQueryObjectuivEXT(
258 query_id_
, GL_QUERY_RESULT_AVAILABLE_EXT
, &result_available
);
259 is_pending_
= !result_available
;
268 gl_
->GetQueryObjectuivEXT(query_id_
, GL_QUERY_RESULT_EXT
, &result
);
273 class Fence
: public ResourceProvider::Fence
{
275 explicit Fence(base::WeakPtr
<GLRenderer::SyncQuery
> query
)
278 // Overridden from ResourceProvider::Fence:
279 void Set() override
{
283 bool HasPassed() override
{ return !query_
|| !query_
->IsPending(); }
284 void Wait() override
{
292 base::WeakPtr
<SyncQuery
> query_
;
294 DISALLOW_COPY_AND_ASSIGN(Fence
);
297 gpu::gles2::GLES2Interface
* gl_
;
300 base::WeakPtrFactory
<SyncQuery
> weak_ptr_factory_
;
302 DISALLOW_COPY_AND_ASSIGN(SyncQuery
);
305 scoped_ptr
<GLRenderer
> GLRenderer::Create(
306 RendererClient
* client
,
307 const RendererSettings
* settings
,
308 OutputSurface
* output_surface
,
309 ResourceProvider
* resource_provider
,
310 TextureMailboxDeleter
* texture_mailbox_deleter
,
311 int highp_threshold_min
) {
312 return make_scoped_ptr(new GLRenderer(client
,
316 texture_mailbox_deleter
,
317 highp_threshold_min
));
320 GLRenderer::GLRenderer(RendererClient
* client
,
321 const RendererSettings
* settings
,
322 OutputSurface
* output_surface
,
323 ResourceProvider
* resource_provider
,
324 TextureMailboxDeleter
* texture_mailbox_deleter
,
325 int highp_threshold_min
)
326 : DirectRenderer(client
, settings
, output_surface
, resource_provider
),
327 offscreen_framebuffer_id_(0),
328 shared_geometry_quad_(QuadVertexRect()),
329 gl_(output_surface
->context_provider()->ContextGL()),
330 context_support_(output_surface
->context_provider()->ContextSupport()),
331 texture_mailbox_deleter_(texture_mailbox_deleter
),
332 is_backbuffer_discarded_(false),
333 is_scissor_enabled_(false),
334 scissor_rect_needs_reset_(true),
335 stencil_shadow_(false),
336 blend_shadow_(false),
337 highp_threshold_min_(highp_threshold_min
),
338 highp_threshold_cache_(0),
339 use_sync_query_(false),
340 on_demand_tile_raster_resource_id_(0),
341 bound_geometry_(NO_BINDING
) {
343 DCHECK(context_support_
);
345 ContextProvider::Capabilities context_caps
=
346 output_surface_
->context_provider()->ContextCapabilities();
348 capabilities_
.using_partial_swap
=
349 settings_
->partial_swap_enabled
&& context_caps
.gpu
.post_sub_buffer
;
351 DCHECK(!context_caps
.gpu
.iosurface
|| context_caps
.gpu
.texture_rectangle
);
353 capabilities_
.using_egl_image
= context_caps
.gpu
.egl_image_external
;
355 capabilities_
.max_texture_size
= resource_provider_
->max_texture_size();
356 capabilities_
.best_texture_format
= resource_provider_
->best_texture_format();
358 // The updater can access textures while the GLRenderer is using them.
359 capabilities_
.allow_partial_texture_updates
= true;
361 capabilities_
.using_image
= context_caps
.gpu
.image
;
363 capabilities_
.using_discard_framebuffer
=
364 context_caps
.gpu
.discard_framebuffer
;
366 capabilities_
.allow_rasterize_on_demand
= true;
367 capabilities_
.max_msaa_samples
= context_caps
.gpu
.max_samples
;
369 use_sync_query_
= context_caps
.gpu
.sync_query
;
370 use_blend_equation_advanced_
= context_caps
.gpu
.blend_equation_advanced
;
371 use_blend_equation_advanced_coherent_
=
372 context_caps
.gpu
.blend_equation_advanced_coherent
;
374 InitializeSharedObjects();
377 GLRenderer::~GLRenderer() {
378 while (!pending_async_read_pixels_
.empty()) {
379 PendingAsyncReadPixels
* pending_read
= pending_async_read_pixels_
.back();
380 pending_read
->finished_read_pixels_callback
.Cancel();
381 pending_async_read_pixels_
.pop_back();
384 in_use_overlay_resources_
.clear();
386 CleanupSharedObjects();
389 const RendererCapabilitiesImpl
& GLRenderer::Capabilities() const {
390 return capabilities_
;
393 void GLRenderer::DidChangeVisibility() {
394 EnforceMemoryPolicy();
396 context_support_
->SetSurfaceVisible(visible());
399 void GLRenderer::ReleaseRenderPassTextures() { render_pass_textures_
.clear(); }
401 void GLRenderer::DiscardPixels() {
402 if (!capabilities_
.using_discard_framebuffer
)
404 bool using_default_framebuffer
=
405 !current_framebuffer_lock_
&&
406 output_surface_
->capabilities().uses_default_gl_framebuffer
;
407 GLenum attachments
[] = {static_cast<GLenum
>(
408 using_default_framebuffer
? GL_COLOR_EXT
: GL_COLOR_ATTACHMENT0_EXT
)};
409 gl_
->DiscardFramebufferEXT(
410 GL_FRAMEBUFFER
, arraysize(attachments
), attachments
);
413 void GLRenderer::PrepareSurfaceForPass(
415 SurfaceInitializationMode initialization_mode
,
416 const gfx::Rect
& render_pass_scissor
) {
419 switch (initialization_mode
) {
420 case SURFACE_INITIALIZATION_MODE_PRESERVE
:
421 EnsureScissorTestDisabled();
423 case SURFACE_INITIALIZATION_MODE_FULL_SURFACE_CLEAR
:
424 EnsureScissorTestDisabled();
426 ClearFramebuffer(frame
);
428 case SURFACE_INITIALIZATION_MODE_SCISSORED_CLEAR
:
429 SetScissorTestRect(render_pass_scissor
);
430 ClearFramebuffer(frame
);
435 void GLRenderer::ClearFramebuffer(DrawingFrame
* frame
) {
436 // On DEBUG builds, opaque render passes are cleared to blue to easily see
437 // regions that were not drawn on the screen.
438 if (frame
->current_render_pass
->has_transparent_background
)
439 gl_
->ClearColor(0, 0, 0, 0);
441 gl_
->ClearColor(0, 0, 1, 1);
443 bool always_clear
= false;
447 if (always_clear
|| frame
->current_render_pass
->has_transparent_background
) {
448 GLbitfield clear_bits
= GL_COLOR_BUFFER_BIT
;
450 clear_bits
|= GL_STENCIL_BUFFER_BIT
;
451 gl_
->Clear(clear_bits
);
455 void GLRenderer::BeginDrawingFrame(DrawingFrame
* frame
) {
456 TRACE_EVENT0("cc", "GLRenderer::BeginDrawingFrame");
458 scoped_refptr
<ResourceProvider::Fence
> read_lock_fence
;
459 if (use_sync_query_
) {
460 // Block until oldest sync query has passed if the number of pending queries
461 // ever reach kMaxPendingSyncQueries.
462 if (pending_sync_queries_
.size() >= kMaxPendingSyncQueries
) {
463 LOG(ERROR
) << "Reached limit of pending sync queries.";
465 pending_sync_queries_
.front()->Wait();
466 DCHECK(!pending_sync_queries_
.front()->IsPending());
469 while (!pending_sync_queries_
.empty()) {
470 if (pending_sync_queries_
.front()->IsPending())
473 available_sync_queries_
.push_back(pending_sync_queries_
.take_front());
476 current_sync_query_
= available_sync_queries_
.empty()
477 ? make_scoped_ptr(new SyncQuery(gl_
))
478 : available_sync_queries_
.take_front();
480 read_lock_fence
= current_sync_query_
->Begin();
483 make_scoped_refptr(new ResourceProvider::SynchronousFence(gl_
));
485 resource_provider_
->SetReadLockFence(read_lock_fence
.get());
487 // Insert WaitSyncPointCHROMIUM on quad resources prior to drawing the frame,
488 // so that drawing can proceed without GL context switching interruptions.
489 ResourceProvider
* resource_provider
= resource_provider_
;
490 for (const auto& pass
: *frame
->render_passes_in_draw_order
) {
491 for (const auto& quad
: pass
->quad_list
) {
492 for (ResourceId resource_id
: quad
->resources
)
493 resource_provider
->WaitSyncPointIfNeeded(resource_id
);
497 // TODO(enne): Do we need to reinitialize all of this state per frame?
498 ReinitializeGLState();
501 void GLRenderer::DoNoOp() {
502 gl_
->BindFramebuffer(GL_FRAMEBUFFER
, 0);
506 void GLRenderer::DoDrawQuad(DrawingFrame
* frame
,
507 const DrawQuad
* quad
,
508 const gfx::QuadF
* clip_region
) {
509 DCHECK(quad
->rect
.Contains(quad
->visible_rect
));
510 if (quad
->material
!= DrawQuad::TEXTURE_CONTENT
) {
511 FlushTextureQuadCache(SHARED_BINDING
);
514 switch (quad
->material
) {
515 case DrawQuad::INVALID
:
518 case DrawQuad::CHECKERBOARD
:
519 DrawCheckerboardQuad(frame
, CheckerboardDrawQuad::MaterialCast(quad
),
522 case DrawQuad::DEBUG_BORDER
:
523 DrawDebugBorderQuad(frame
, DebugBorderDrawQuad::MaterialCast(quad
));
525 case DrawQuad::IO_SURFACE_CONTENT
:
526 DrawIOSurfaceQuad(frame
, IOSurfaceDrawQuad::MaterialCast(quad
),
529 case DrawQuad::PICTURE_CONTENT
:
530 // PictureDrawQuad should only be used for resourceless software draws.
533 case DrawQuad::RENDER_PASS
:
534 DrawRenderPassQuad(frame
, RenderPassDrawQuad::MaterialCast(quad
),
537 case DrawQuad::SOLID_COLOR
:
538 DrawSolidColorQuad(frame
, SolidColorDrawQuad::MaterialCast(quad
),
541 case DrawQuad::STREAM_VIDEO_CONTENT
:
542 DrawStreamVideoQuad(frame
, StreamVideoDrawQuad::MaterialCast(quad
),
545 case DrawQuad::SURFACE_CONTENT
:
546 // Surface content should be fully resolved to other quad types before
547 // reaching a direct renderer.
550 case DrawQuad::TEXTURE_CONTENT
:
551 EnqueueTextureQuad(frame
, TextureDrawQuad::MaterialCast(quad
),
554 case DrawQuad::TILED_CONTENT
:
555 DrawTileQuad(frame
, TileDrawQuad::MaterialCast(quad
), clip_region
);
557 case DrawQuad::YUV_VIDEO_CONTENT
:
558 DrawYUVVideoQuad(frame
, YUVVideoDrawQuad::MaterialCast(quad
),
564 void GLRenderer::DrawCheckerboardQuad(const DrawingFrame
* frame
,
565 const CheckerboardDrawQuad
* quad
,
566 const gfx::QuadF
* clip_region
) {
567 // TODO(enne) For now since checkerboards shouldn't be part of a 3D
568 // context, clipping regions aren't supported so we skip drawing them
569 // if this becomes the case.
573 SetBlendEnabled(quad
->ShouldDrawWithBlending());
575 const TileCheckerboardProgram
* program
= GetTileCheckerboardProgram();
576 DCHECK(program
&& (program
->initialized() || IsContextLost()));
577 SetUseProgram(program
->program());
579 SkColor color
= quad
->color
;
580 gl_
->Uniform4f(program
->fragment_shader().color_location(),
581 SkColorGetR(color
) * (1.0f
/ 255.0f
),
582 SkColorGetG(color
) * (1.0f
/ 255.0f
),
583 SkColorGetB(color
) * (1.0f
/ 255.0f
), 1);
585 const int kCheckerboardWidth
= 16;
586 float frequency
= 1.0f
/ kCheckerboardWidth
;
588 gfx::Rect tile_rect
= quad
->rect
;
590 static_cast<int>(tile_rect
.x() / quad
->scale
) % kCheckerboardWidth
;
592 static_cast<int>(tile_rect
.y() / quad
->scale
) % kCheckerboardWidth
;
593 float tex_scale_x
= tile_rect
.width() / quad
->scale
;
594 float tex_scale_y
= tile_rect
.height() / quad
->scale
;
595 gl_
->Uniform4f(program
->fragment_shader().tex_transform_location(),
596 tex_offset_x
, tex_offset_y
, tex_scale_x
, tex_scale_y
);
598 gl_
->Uniform1f(program
->fragment_shader().frequency_location(), frequency
);
600 SetShaderOpacity(quad
->opacity(),
601 program
->fragment_shader().alpha_location());
602 DrawQuadGeometry(frame
,
603 quad
->quadTransform(),
605 program
->vertex_shader().matrix_location());
608 // This function does not handle 3D sorting right now, since the debug border
609 // quads are just drawn as their original quads and not in split pieces. This
610 // results in some debug border quads drawing over foreground quads.
611 void GLRenderer::DrawDebugBorderQuad(const DrawingFrame
* frame
,
612 const DebugBorderDrawQuad
* quad
) {
613 SetBlendEnabled(quad
->ShouldDrawWithBlending());
615 static float gl_matrix
[16];
616 const DebugBorderProgram
* program
= GetDebugBorderProgram();
617 DCHECK(program
&& (program
->initialized() || IsContextLost()));
618 SetUseProgram(program
->program());
620 // Use the full quad_rect for debug quads to not move the edges based on
622 gfx::Rect layer_rect
= quad
->rect
;
623 gfx::Transform render_matrix
;
624 QuadRectTransform(&render_matrix
, quad
->quadTransform(), layer_rect
);
625 GLRenderer::ToGLMatrix(&gl_matrix
[0],
626 frame
->projection_matrix
* render_matrix
);
627 gl_
->UniformMatrix4fv(program
->vertex_shader().matrix_location(), 1, false,
630 SkColor color
= quad
->color
;
631 float alpha
= SkColorGetA(color
) * (1.0f
/ 255.0f
);
633 gl_
->Uniform4f(program
->fragment_shader().color_location(),
634 (SkColorGetR(color
) * (1.0f
/ 255.0f
)) * alpha
,
635 (SkColorGetG(color
) * (1.0f
/ 255.0f
)) * alpha
,
636 (SkColorGetB(color
) * (1.0f
/ 255.0f
)) * alpha
, alpha
);
638 gl_
->LineWidth(quad
->width
);
640 // The indices for the line are stored in the same array as the triangle
642 gl_
->DrawElements(GL_LINE_LOOP
, 4, GL_UNSIGNED_SHORT
, 0);
645 static skia::RefPtr
<SkImage
> ApplyImageFilter(
646 scoped_ptr
<GLRenderer::ScopedUseGrContext
> use_gr_context
,
647 ResourceProvider
* resource_provider
,
648 const gfx::Rect
& rect
,
649 const gfx::Vector2dF
& scale
,
650 SkImageFilter
* filter
,
651 ScopedResource
* source_texture_resource
) {
653 return skia::RefPtr
<SkImage
>();
656 return skia::RefPtr
<SkImage
>();
658 ResourceProvider::ScopedReadLockGL
lock(resource_provider
,
659 source_texture_resource
->id());
661 // Wrap the source texture in a Ganesh platform texture.
662 GrBackendTextureDesc backend_texture_description
;
663 backend_texture_description
.fWidth
= source_texture_resource
->size().width();
664 backend_texture_description
.fHeight
=
665 source_texture_resource
->size().height();
666 backend_texture_description
.fConfig
= kSkia8888_GrPixelConfig
;
667 backend_texture_description
.fTextureHandle
= lock
.texture_id();
668 backend_texture_description
.fOrigin
= kBottomLeft_GrSurfaceOrigin
;
669 skia::RefPtr
<GrTexture
> texture
= skia::AdoptRef(
670 use_gr_context
->context()->textureProvider()->wrapBackendTexture(
671 backend_texture_description
));
673 TRACE_EVENT_INSTANT0("cc",
674 "ApplyImageFilter wrap background texture failed",
675 TRACE_EVENT_SCOPE_THREAD
);
676 return skia::RefPtr
<SkImage
>();
679 SkImageInfo src_info
=
680 SkImageInfo::MakeN32Premul(source_texture_resource
->size().width(),
681 source_texture_resource
->size().height());
682 // Place the platform texture inside an SkBitmap.
684 source
.setInfo(src_info
);
685 skia::RefPtr
<SkGrPixelRef
> pixel_ref
=
686 skia::AdoptRef(new SkGrPixelRef(src_info
, texture
.get()));
687 source
.setPixelRef(pixel_ref
.get());
689 // Create surface to draw into.
690 SkImageInfo dst_info
=
691 SkImageInfo::MakeN32Premul(source
.width(), source
.height());
692 skia::RefPtr
<SkSurface
> surface
= skia::AdoptRef(SkSurface::NewRenderTarget(
693 use_gr_context
->context(), SkSurface::kYes_Budgeted
, dst_info
, 0));
695 TRACE_EVENT_INSTANT0("cc", "ApplyImageFilter surface allocation failed",
696 TRACE_EVENT_SCOPE_THREAD
);
697 return skia::RefPtr
<SkImage
>();
699 skia::RefPtr
<SkCanvas
> canvas
= skia::SharePtr(surface
->getCanvas());
701 // Draw the source bitmap through the filter to the canvas.
703 paint
.setImageFilter(filter
);
704 canvas
->clear(SK_ColorTRANSPARENT
);
706 // The origin of the filter is top-left and the origin of the source is
707 // bottom-left, but the orientation is the same, so we must translate the
708 // filter so that it renders at the bottom of the texture to avoid
710 int y_translate
= source
.height() - rect
.height() - rect
.origin().y();
711 canvas
->translate(-rect
.origin().x(), y_translate
);
712 canvas
->scale(scale
.x(), scale
.y());
713 canvas
->drawSprite(source
, 0, 0, &paint
);
715 skia::RefPtr
<SkImage
> image
= skia::AdoptRef(surface
->newImageSnapshot());
716 if (!image
|| !image
->getTexture()) {
717 return skia::RefPtr
<SkImage
>();
720 // Flush the GrContext to ensure all buffered GL calls are drawn to the
721 // backing store before we access and return it, and have cc begin using the
728 bool GLRenderer::CanApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode
) {
729 return use_blend_equation_advanced_
||
730 blend_mode
== SkXfermode::kScreen_Mode
||
731 blend_mode
== SkXfermode::kSrcOver_Mode
;
734 void GLRenderer::ApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode
) {
735 DCHECK(CanApplyBlendModeUsingBlendFunc(blend_mode
));
737 // Any modes set here must be reset in RestoreBlendFuncToDefault
738 if (use_blend_equation_advanced_
) {
739 GLenum equation
= GL_FUNC_ADD
;
741 switch (blend_mode
) {
742 case SkXfermode::kScreen_Mode
:
743 equation
= GL_SCREEN_KHR
;
745 case SkXfermode::kOverlay_Mode
:
746 equation
= GL_OVERLAY_KHR
;
748 case SkXfermode::kDarken_Mode
:
749 equation
= GL_DARKEN_KHR
;
751 case SkXfermode::kLighten_Mode
:
752 equation
= GL_LIGHTEN_KHR
;
754 case SkXfermode::kColorDodge_Mode
:
755 equation
= GL_COLORDODGE_KHR
;
757 case SkXfermode::kColorBurn_Mode
:
758 equation
= GL_COLORBURN_KHR
;
760 case SkXfermode::kHardLight_Mode
:
761 equation
= GL_HARDLIGHT_KHR
;
763 case SkXfermode::kSoftLight_Mode
:
764 equation
= GL_SOFTLIGHT_KHR
;
766 case SkXfermode::kDifference_Mode
:
767 equation
= GL_DIFFERENCE_KHR
;
769 case SkXfermode::kExclusion_Mode
:
770 equation
= GL_EXCLUSION_KHR
;
772 case SkXfermode::kMultiply_Mode
:
773 equation
= GL_MULTIPLY_KHR
;
775 case SkXfermode::kHue_Mode
:
776 equation
= GL_HSL_HUE_KHR
;
778 case SkXfermode::kSaturation_Mode
:
779 equation
= GL_HSL_SATURATION_KHR
;
781 case SkXfermode::kColor_Mode
:
782 equation
= GL_HSL_COLOR_KHR
;
784 case SkXfermode::kLuminosity_Mode
:
785 equation
= GL_HSL_LUMINOSITY_KHR
;
791 gl_
->BlendEquation(equation
);
793 if (blend_mode
== SkXfermode::kScreen_Mode
) {
794 gl_
->BlendFunc(GL_ONE_MINUS_DST_COLOR
, GL_ONE
);
799 void GLRenderer::RestoreBlendFuncToDefault(SkXfermode::Mode blend_mode
) {
800 if (blend_mode
== SkXfermode::kSrcOver_Mode
)
803 if (use_blend_equation_advanced_
) {
804 gl_
->BlendEquation(GL_FUNC_ADD
);
806 gl_
->BlendFunc(GL_ONE
, GL_ONE_MINUS_SRC_ALPHA
);
810 bool GLRenderer::ShouldApplyBackgroundFilters(DrawingFrame
* frame
,
811 const RenderPassDrawQuad
* quad
) {
812 if (quad
->background_filters
.IsEmpty())
815 // TODO(danakj): We only allow background filters on an opaque render surface
816 // because other surfaces may contain translucent pixels, and the contents
817 // behind those translucent pixels wouldn't have the filter applied.
818 if (frame
->current_render_pass
->has_transparent_background
)
821 // TODO(ajuma): Add support for reference filters once
822 // FilterOperations::GetOutsets supports reference filters.
823 if (quad
->background_filters
.HasReferenceFilter())
828 // This takes a gfx::Rect and a clip region quad in the same space,
829 // and returns a quad with the same proportions in the space -0.5->0.5.
830 bool GetScaledRegion(const gfx::Rect
& rect
,
831 const gfx::QuadF
* clip
,
832 gfx::QuadF
* scaled_region
) {
836 gfx::PointF
p1(((clip
->p1().x() - rect
.x()) / rect
.width()) - 0.5f
,
837 ((clip
->p1().y() - rect
.y()) / rect
.height()) - 0.5f
);
838 gfx::PointF
p2(((clip
->p2().x() - rect
.x()) / rect
.width()) - 0.5f
,
839 ((clip
->p2().y() - rect
.y()) / rect
.height()) - 0.5f
);
840 gfx::PointF
p3(((clip
->p3().x() - rect
.x()) / rect
.width()) - 0.5f
,
841 ((clip
->p3().y() - rect
.y()) / rect
.height()) - 0.5f
);
842 gfx::PointF
p4(((clip
->p4().x() - rect
.x()) / rect
.width()) - 0.5f
,
843 ((clip
->p4().y() - rect
.y()) / rect
.height()) - 0.5f
);
844 *scaled_region
= gfx::QuadF(p1
, p2
, p3
, p4
);
848 // This takes a gfx::Rect and a clip region quad in the same space,
849 // and returns the proportional uv's in the space 0->1.
850 bool GetScaledUVs(const gfx::Rect
& rect
, const gfx::QuadF
* clip
, float uvs
[8]) {
854 uvs
[0] = ((clip
->p1().x() - rect
.x()) / rect
.width());
855 uvs
[1] = ((clip
->p1().y() - rect
.y()) / rect
.height());
856 uvs
[2] = ((clip
->p2().x() - rect
.x()) / rect
.width());
857 uvs
[3] = ((clip
->p2().y() - rect
.y()) / rect
.height());
858 uvs
[4] = ((clip
->p3().x() - rect
.x()) / rect
.width());
859 uvs
[5] = ((clip
->p3().y() - rect
.y()) / rect
.height());
860 uvs
[6] = ((clip
->p4().x() - rect
.x()) / rect
.width());
861 uvs
[7] = ((clip
->p4().y() - rect
.y()) / rect
.height());
865 gfx::Rect
GLRenderer::GetBackdropBoundingBoxForRenderPassQuad(
867 const RenderPassDrawQuad
* quad
,
868 const gfx::Transform
& contents_device_transform
,
869 const gfx::QuadF
* clip_region
,
871 gfx::QuadF scaled_region
;
872 if (!GetScaledRegion(quad
->rect
, clip_region
, &scaled_region
)) {
873 scaled_region
= SharedGeometryQuad().BoundingBox();
876 gfx::Rect backdrop_rect
= gfx::ToEnclosingRect(MathUtil::MapClippedRect(
877 contents_device_transform
, scaled_region
.BoundingBox()));
879 if (ShouldApplyBackgroundFilters(frame
, quad
)) {
880 int top
, right
, bottom
, left
;
881 quad
->background_filters
.GetOutsets(&top
, &right
, &bottom
, &left
);
882 backdrop_rect
.Inset(-left
, -top
, -right
, -bottom
);
885 if (!backdrop_rect
.IsEmpty() && use_aa
) {
886 const int kOutsetForAntialiasing
= 1;
887 backdrop_rect
.Inset(-kOutsetForAntialiasing
, -kOutsetForAntialiasing
);
890 backdrop_rect
.Intersect(MoveFromDrawToWindowSpace(
891 frame
, frame
->current_render_pass
->output_rect
));
892 return backdrop_rect
;
895 scoped_ptr
<ScopedResource
> GLRenderer::GetBackdropTexture(
896 const gfx::Rect
& bounding_rect
) {
897 scoped_ptr
<ScopedResource
> device_background_texture
=
898 ScopedResource::Create(resource_provider_
);
899 // CopyTexImage2D fails when called on a texture having immutable storage.
900 device_background_texture
->Allocate(
901 bounding_rect
.size(), ResourceProvider::TEXTURE_HINT_DEFAULT
, RGBA_8888
);
903 ResourceProvider::ScopedWriteLockGL
lock(resource_provider_
,
904 device_background_texture
->id());
905 GetFramebufferTexture(
906 lock
.texture_id(), device_background_texture
->format(), bounding_rect
);
908 return device_background_texture
.Pass();
911 skia::RefPtr
<SkImage
> GLRenderer::ApplyBackgroundFilters(
913 const RenderPassDrawQuad
* quad
,
914 ScopedResource
* background_texture
) {
915 DCHECK(ShouldApplyBackgroundFilters(frame
, quad
));
916 skia::RefPtr
<SkImageFilter
> filter
= RenderSurfaceFilters::BuildImageFilter(
917 quad
->background_filters
, background_texture
->size());
919 skia::RefPtr
<SkImage
> background_with_filters
= ApplyImageFilter(
920 ScopedUseGrContext::Create(this, frame
), resource_provider_
, quad
->rect
,
921 quad
->filters_scale
, filter
.get(), background_texture
);
922 return background_with_filters
;
925 void GLRenderer::DrawRenderPassQuad(DrawingFrame
* frame
,
926 const RenderPassDrawQuad
* quad
,
927 const gfx::QuadF
* clip_region
) {
928 ScopedResource
* contents_texture
=
929 render_pass_textures_
.get(quad
->render_pass_id
);
930 DCHECK(contents_texture
);
931 DCHECK(contents_texture
->id());
933 gfx::Transform quad_rect_matrix
;
934 QuadRectTransform(&quad_rect_matrix
, quad
->quadTransform(), quad
->rect
);
935 gfx::Transform contents_device_transform
=
936 frame
->window_matrix
* frame
->projection_matrix
* quad_rect_matrix
;
937 contents_device_transform
.FlattenTo2d();
939 // Can only draw surface if device matrix is invertible.
940 if (!contents_device_transform
.IsInvertible())
943 gfx::QuadF surface_quad
= SharedGeometryQuad();
945 bool use_aa
= settings_
->allow_antialiasing
&&
946 ShouldAntialiasQuad(contents_device_transform
, quad
,
947 settings_
->force_antialiasing
);
949 SetupQuadForClippingAndAntialiasing(contents_device_transform
, quad
, use_aa
,
950 clip_region
, &surface_quad
, edge
);
951 SkXfermode::Mode blend_mode
= quad
->shared_quad_state
->blend_mode
;
952 bool use_shaders_for_blending
=
953 !CanApplyBlendModeUsingBlendFunc(blend_mode
) ||
954 ShouldApplyBackgroundFilters(frame
, quad
) ||
955 settings_
->force_blending_with_shaders
;
957 scoped_ptr
<ScopedResource
> background_texture
;
958 skia::RefPtr
<SkImage
> background_image
;
959 gfx::Rect background_rect
;
960 if (use_shaders_for_blending
) {
961 // Compute a bounding box around the pixels that will be visible through
963 background_rect
= GetBackdropBoundingBoxForRenderPassQuad(
964 frame
, quad
, contents_device_transform
, clip_region
, use_aa
);
966 if (!background_rect
.IsEmpty()) {
967 // The pixels from the filtered background should completely replace the
968 // current pixel values.
970 SetBlendEnabled(false);
972 // Read the pixels in the bounding box into a buffer R.
973 // This function allocates a texture, which should contribute to the
974 // amount of memory used by render surfaces:
975 // LayerTreeHost::CalculateMemoryForRenderSurfaces.
976 background_texture
= GetBackdropTexture(background_rect
);
978 if (ShouldApplyBackgroundFilters(frame
, quad
) && background_texture
) {
979 // Apply the background filters to R, so that it is applied in the
980 // pixels' coordinate space.
982 ApplyBackgroundFilters(frame
, quad
, background_texture
.get());
986 if (!background_texture
) {
987 // Something went wrong with reading the backdrop.
988 DCHECK(!background_image
);
989 use_shaders_for_blending
= false;
990 } else if (background_image
) {
991 // Reset original background texture if there is not any mask
992 if (!quad
->mask_resource_id())
993 background_texture
.reset();
994 } else if (CanApplyBlendModeUsingBlendFunc(blend_mode
) &&
995 ShouldApplyBackgroundFilters(frame
, quad
)) {
996 // Something went wrong with applying background filters to the backdrop.
997 use_shaders_for_blending
= false;
998 background_texture
.reset();
1001 // Need original background texture for mask?
1002 bool mask_for_background
=
1003 background_texture
&& // Have original background texture
1004 background_image
&& // Have filtered background texture
1005 quad
->mask_resource_id(); // Have mask texture
1007 !use_shaders_for_blending
&&
1008 (quad
->ShouldDrawWithBlending() || !IsDefaultBlendMode(blend_mode
)));
1010 // TODO(senorblanco): Cache this value so that we don't have to do it for both
1011 // the surface and its replica. Apply filters to the contents texture.
1012 skia::RefPtr
<SkImage
> filter_image
;
1013 SkScalar color_matrix
[20];
1014 bool use_color_matrix
= false;
1015 if (!quad
->filters
.IsEmpty()) {
1016 skia::RefPtr
<SkImageFilter
> filter
= RenderSurfaceFilters::BuildImageFilter(
1017 quad
->filters
, contents_texture
->size());
1019 skia::RefPtr
<SkColorFilter
> cf
;
1022 SkColorFilter
* colorfilter_rawptr
= NULL
;
1023 filter
->asColorFilter(&colorfilter_rawptr
);
1024 cf
= skia::AdoptRef(colorfilter_rawptr
);
1027 if (cf
&& cf
->asColorMatrix(color_matrix
) && !filter
->getInput(0)) {
1028 // We have a single color matrix as a filter; apply it locally
1029 // in the compositor.
1030 use_color_matrix
= true;
1032 filter_image
= ApplyImageFilter(
1033 ScopedUseGrContext::Create(this, frame
), resource_provider_
,
1034 quad
->rect
, quad
->filters_scale
, filter
.get(), contents_texture
);
1039 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> mask_resource_lock
;
1040 unsigned mask_texture_id
= 0;
1041 SamplerType mask_sampler
= SAMPLER_TYPE_NA
;
1042 if (quad
->mask_resource_id()) {
1043 mask_resource_lock
.reset(new ResourceProvider::ScopedSamplerGL(
1044 resource_provider_
, quad
->mask_resource_id(), GL_TEXTURE1
, GL_LINEAR
));
1045 mask_texture_id
= mask_resource_lock
->texture_id();
1046 mask_sampler
= SamplerTypeFromTextureTarget(mask_resource_lock
->target());
1049 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> contents_resource_lock
;
1051 GrTexture
* texture
= filter_image
->getTexture();
1052 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
1053 gl_
->BindTexture(GL_TEXTURE_2D
, texture
->getTextureHandle());
1055 contents_resource_lock
=
1056 make_scoped_ptr(new ResourceProvider::ScopedSamplerGL(
1057 resource_provider_
, contents_texture
->id(), GL_LINEAR
));
1058 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
),
1059 contents_resource_lock
->target());
1062 if (!use_shaders_for_blending
) {
1063 if (!use_blend_equation_advanced_coherent_
&& use_blend_equation_advanced_
)
1064 gl_
->BlendBarrierKHR();
1066 ApplyBlendModeUsingBlendFunc(blend_mode
);
1069 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1071 &highp_threshold_cache_
,
1072 highp_threshold_min_
,
1073 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
1075 ShaderLocations locations
;
1077 DCHECK_EQ(background_texture
|| background_image
, use_shaders_for_blending
);
1078 BlendMode shader_blend_mode
= use_shaders_for_blending
1079 ? BlendModeFromSkXfermode(blend_mode
)
1082 if (use_aa
&& mask_texture_id
&& !use_color_matrix
) {
1083 const RenderPassMaskProgramAA
* program
= GetRenderPassMaskProgramAA(
1084 tex_coord_precision
, mask_sampler
,
1085 shader_blend_mode
, mask_for_background
);
1086 SetUseProgram(program
->program());
1087 program
->vertex_shader().FillLocations(&locations
);
1088 program
->fragment_shader().FillLocations(&locations
);
1089 gl_
->Uniform1i(locations
.sampler
, 0);
1090 } else if (!use_aa
&& mask_texture_id
&& !use_color_matrix
) {
1091 const RenderPassMaskProgram
* program
= GetRenderPassMaskProgram(
1092 tex_coord_precision
, mask_sampler
,
1093 shader_blend_mode
, mask_for_background
);
1094 SetUseProgram(program
->program());
1095 program
->vertex_shader().FillLocations(&locations
);
1096 program
->fragment_shader().FillLocations(&locations
);
1097 gl_
->Uniform1i(locations
.sampler
, 0);
1098 } else if (use_aa
&& !mask_texture_id
&& !use_color_matrix
) {
1099 const RenderPassProgramAA
* program
=
1100 GetRenderPassProgramAA(tex_coord_precision
, shader_blend_mode
);
1101 SetUseProgram(program
->program());
1102 program
->vertex_shader().FillLocations(&locations
);
1103 program
->fragment_shader().FillLocations(&locations
);
1104 gl_
->Uniform1i(locations
.sampler
, 0);
1105 } else if (use_aa
&& mask_texture_id
&& use_color_matrix
) {
1106 const RenderPassMaskColorMatrixProgramAA
* program
=
1107 GetRenderPassMaskColorMatrixProgramAA(
1108 tex_coord_precision
, mask_sampler
,
1109 shader_blend_mode
, mask_for_background
);
1110 SetUseProgram(program
->program());
1111 program
->vertex_shader().FillLocations(&locations
);
1112 program
->fragment_shader().FillLocations(&locations
);
1113 gl_
->Uniform1i(locations
.sampler
, 0);
1114 } else if (use_aa
&& !mask_texture_id
&& use_color_matrix
) {
1115 const RenderPassColorMatrixProgramAA
* program
=
1116 GetRenderPassColorMatrixProgramAA(tex_coord_precision
,
1118 SetUseProgram(program
->program());
1119 program
->vertex_shader().FillLocations(&locations
);
1120 program
->fragment_shader().FillLocations(&locations
);
1121 gl_
->Uniform1i(locations
.sampler
, 0);
1122 } else if (!use_aa
&& mask_texture_id
&& use_color_matrix
) {
1123 const RenderPassMaskColorMatrixProgram
* program
=
1124 GetRenderPassMaskColorMatrixProgram(
1125 tex_coord_precision
, mask_sampler
,
1126 shader_blend_mode
, mask_for_background
);
1127 SetUseProgram(program
->program());
1128 program
->vertex_shader().FillLocations(&locations
);
1129 program
->fragment_shader().FillLocations(&locations
);
1130 gl_
->Uniform1i(locations
.sampler
, 0);
1131 } else if (!use_aa
&& !mask_texture_id
&& use_color_matrix
) {
1132 const RenderPassColorMatrixProgram
* program
=
1133 GetRenderPassColorMatrixProgram(tex_coord_precision
, shader_blend_mode
);
1134 SetUseProgram(program
->program());
1135 program
->vertex_shader().FillLocations(&locations
);
1136 program
->fragment_shader().FillLocations(&locations
);
1137 gl_
->Uniform1i(locations
.sampler
, 0);
1139 const RenderPassProgram
* program
=
1140 GetRenderPassProgram(tex_coord_precision
, shader_blend_mode
);
1141 SetUseProgram(program
->program());
1142 program
->vertex_shader().FillLocations(&locations
);
1143 program
->fragment_shader().FillLocations(&locations
);
1144 gl_
->Uniform1i(locations
.sampler
, 0);
1147 quad
->rect
.width() / static_cast<float>(contents_texture
->size().width());
1148 float tex_scale_y
= quad
->rect
.height() /
1149 static_cast<float>(contents_texture
->size().height());
1150 DCHECK_LE(tex_scale_x
, 1.0f
);
1151 DCHECK_LE(tex_scale_y
, 1.0f
);
1153 DCHECK(locations
.tex_transform
!= -1 || IsContextLost());
1154 // Flip the content vertically in the shader, as the RenderPass input
1155 // texture is already oriented the same way as the framebuffer, but the
1156 // projection transform does a flip.
1157 gl_
->Uniform4f(locations
.tex_transform
, 0.0f
, tex_scale_y
, tex_scale_x
,
1160 GLint last_texture_unit
= 0;
1161 if (locations
.mask_sampler
!= -1) {
1162 DCHECK_NE(locations
.mask_tex_coord_scale
, 1);
1163 DCHECK_NE(locations
.mask_tex_coord_offset
, 1);
1164 gl_
->Uniform1i(locations
.mask_sampler
, 1);
1166 gfx::RectF mask_uv_rect
= quad
->MaskUVRect();
1167 if (mask_sampler
!= SAMPLER_TYPE_2D
) {
1168 mask_uv_rect
.Scale(quad
->mask_texture_size
.width(),
1169 quad
->mask_texture_size
.height());
1172 // Mask textures are oriented vertically flipped relative to the framebuffer
1173 // and the RenderPass contents texture, so we flip the tex coords from the
1174 // RenderPass texture to find the mask texture coords.
1175 gl_
->Uniform2f(locations
.mask_tex_coord_offset
, mask_uv_rect
.x(),
1176 mask_uv_rect
.bottom());
1177 gl_
->Uniform2f(locations
.mask_tex_coord_scale
,
1178 mask_uv_rect
.width() / tex_scale_x
,
1179 -mask_uv_rect
.height() / tex_scale_y
);
1181 last_texture_unit
= 1;
1184 if (locations
.edge
!= -1)
1185 gl_
->Uniform3fv(locations
.edge
, 8, edge
);
1187 if (locations
.viewport
!= -1) {
1188 float viewport
[4] = {
1189 static_cast<float>(current_window_space_viewport_
.x()),
1190 static_cast<float>(current_window_space_viewport_
.y()),
1191 static_cast<float>(current_window_space_viewport_
.width()),
1192 static_cast<float>(current_window_space_viewport_
.height()),
1194 gl_
->Uniform4fv(locations
.viewport
, 1, viewport
);
1197 if (locations
.color_matrix
!= -1) {
1199 for (int i
= 0; i
< 4; ++i
) {
1200 for (int j
= 0; j
< 4; ++j
)
1201 matrix
[i
* 4 + j
] = SkScalarToFloat(color_matrix
[j
* 5 + i
]);
1203 gl_
->UniformMatrix4fv(locations
.color_matrix
, 1, false, matrix
);
1205 static const float kScale
= 1.0f
/ 255.0f
;
1206 if (locations
.color_offset
!= -1) {
1208 for (int i
= 0; i
< 4; ++i
)
1209 offset
[i
] = SkScalarToFloat(color_matrix
[i
* 5 + 4]) * kScale
;
1211 gl_
->Uniform4fv(locations
.color_offset
, 1, offset
);
1214 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> shader_background_sampler_lock
;
1215 if (locations
.backdrop
!= -1) {
1216 DCHECK(background_texture
|| background_image
);
1217 DCHECK_NE(locations
.backdrop
, 0);
1218 DCHECK_NE(locations
.backdrop_rect
, 0);
1220 gl_
->Uniform1i(locations
.backdrop
, ++last_texture_unit
);
1222 gl_
->Uniform4f(locations
.backdrop_rect
, background_rect
.x(),
1223 background_rect
.y(), background_rect
.width(),
1224 background_rect
.height());
1226 if (background_image
) {
1227 GrTexture
* texture
= background_image
->getTexture();
1228 gl_
->ActiveTexture(GL_TEXTURE0
+ last_texture_unit
);
1229 gl_
->BindTexture(GL_TEXTURE_2D
, texture
->getTextureHandle());
1230 gl_
->ActiveTexture(GL_TEXTURE0
);
1231 if (mask_for_background
)
1232 gl_
->Uniform1i(locations
.original_backdrop
, ++last_texture_unit
);
1234 if (background_texture
) {
1235 shader_background_sampler_lock
= make_scoped_ptr(
1236 new ResourceProvider::ScopedSamplerGL(resource_provider_
,
1237 background_texture
->id(),
1238 GL_TEXTURE0
+ last_texture_unit
,
1240 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
),
1241 shader_background_sampler_lock
->target());
1245 SetShaderOpacity(quad
->opacity(), locations
.alpha
);
1246 SetShaderQuadF(surface_quad
, locations
.quad
);
1248 frame
, quad
->quadTransform(), quad
->rect
, locations
.matrix
);
1250 // Flush the compositor context before the filter bitmap goes out of
1251 // scope, so the draw gets processed before the filter texture gets deleted.
1255 if (!use_shaders_for_blending
)
1256 RestoreBlendFuncToDefault(blend_mode
);
1259 struct SolidColorProgramUniforms
{
1261 unsigned matrix_location
;
1262 unsigned viewport_location
;
1263 unsigned quad_location
;
1264 unsigned edge_location
;
1265 unsigned color_location
;
1269 static void SolidColorUniformLocation(T program
,
1270 SolidColorProgramUniforms
* uniforms
) {
1271 uniforms
->program
= program
->program();
1272 uniforms
->matrix_location
= program
->vertex_shader().matrix_location();
1273 uniforms
->viewport_location
= program
->vertex_shader().viewport_location();
1274 uniforms
->quad_location
= program
->vertex_shader().quad_location();
1275 uniforms
->edge_location
= program
->vertex_shader().edge_location();
1276 uniforms
->color_location
= program
->fragment_shader().color_location();
1280 // These functions determine if a quad, clipped by a clip_region contains
1281 // the entire {top|bottom|left|right} edge.
1282 bool is_top(const gfx::QuadF
* clip_region
, const DrawQuad
* quad
) {
1283 if (!quad
->IsTopEdge())
1288 return std::abs(clip_region
->p1().y()) < kAntiAliasingEpsilon
&&
1289 std::abs(clip_region
->p2().y()) < kAntiAliasingEpsilon
;
1292 bool is_bottom(const gfx::QuadF
* clip_region
, const DrawQuad
* quad
) {
1293 if (!quad
->IsBottomEdge())
1298 return std::abs(clip_region
->p3().y() -
1299 quad
->shared_quad_state
->content_bounds
.height()) <
1300 kAntiAliasingEpsilon
&&
1301 std::abs(clip_region
->p4().y() -
1302 quad
->shared_quad_state
->content_bounds
.height()) <
1303 kAntiAliasingEpsilon
;
1306 bool is_left(const gfx::QuadF
* clip_region
, const DrawQuad
* quad
) {
1307 if (!quad
->IsLeftEdge())
1312 return std::abs(clip_region
->p1().x()) < kAntiAliasingEpsilon
&&
1313 std::abs(clip_region
->p4().x()) < kAntiAliasingEpsilon
;
1316 bool is_right(const gfx::QuadF
* clip_region
, const DrawQuad
* quad
) {
1317 if (!quad
->IsRightEdge())
1322 return std::abs(clip_region
->p2().x() -
1323 quad
->shared_quad_state
->content_bounds
.width()) <
1324 kAntiAliasingEpsilon
&&
1325 std::abs(clip_region
->p3().x() -
1326 quad
->shared_quad_state
->content_bounds
.width()) <
1327 kAntiAliasingEpsilon
;
1329 } // anonymous namespace
1331 static gfx::QuadF
GetDeviceQuadWithAntialiasingOnExteriorEdges(
1332 const LayerQuad
& device_layer_edges
,
1333 const gfx::Transform
& device_transform
,
1334 const gfx::QuadF
* clip_region
,
1335 const DrawQuad
* quad
) {
1336 gfx::RectF tile_rect
= quad
->visible_rect
;
1337 gfx::QuadF
tile_quad(tile_rect
);
1340 if (quad
->material
!= DrawQuad::RENDER_PASS
) {
1341 tile_quad
= *clip_region
;
1343 GetScaledRegion(quad
->rect
, clip_region
, &tile_quad
);
1347 gfx::PointF bottom_right
= tile_quad
.p3();
1348 gfx::PointF bottom_left
= tile_quad
.p4();
1349 gfx::PointF top_left
= tile_quad
.p1();
1350 gfx::PointF top_right
= tile_quad
.p2();
1351 bool clipped
= false;
1353 // Map points to device space. We ignore |clipped|, since the result of
1354 // |MapPoint()| still produces a valid point to draw the quad with. When
1355 // clipped, the point will be outside of the viewport. See crbug.com/416367.
1356 bottom_right
= MathUtil::MapPoint(device_transform
, bottom_right
, &clipped
);
1357 bottom_left
= MathUtil::MapPoint(device_transform
, bottom_left
, &clipped
);
1358 top_left
= MathUtil::MapPoint(device_transform
, top_left
, &clipped
);
1359 top_right
= MathUtil::MapPoint(device_transform
, top_right
, &clipped
);
1361 LayerQuad::Edge
bottom_edge(bottom_right
, bottom_left
);
1362 LayerQuad::Edge
left_edge(bottom_left
, top_left
);
1363 LayerQuad::Edge
top_edge(top_left
, top_right
);
1364 LayerQuad::Edge
right_edge(top_right
, bottom_right
);
1366 // Only apply anti-aliasing to edges not clipped by culling or scissoring.
1367 // If an edge is degenerate we do not want to replace it with a "proper" edge
1368 // as that will cause the quad to possibly expand is strange ways.
1369 if (!top_edge
.degenerate() && is_top(clip_region
, quad
) &&
1370 tile_rect
.y() == quad
->rect
.y()) {
1371 top_edge
= device_layer_edges
.top();
1373 if (!left_edge
.degenerate() && is_left(clip_region
, quad
) &&
1374 tile_rect
.x() == quad
->rect
.x()) {
1375 left_edge
= device_layer_edges
.left();
1377 if (!right_edge
.degenerate() && is_right(clip_region
, quad
) &&
1378 tile_rect
.right() == quad
->rect
.right()) {
1379 right_edge
= device_layer_edges
.right();
1381 if (!bottom_edge
.degenerate() && is_bottom(clip_region
, quad
) &&
1382 tile_rect
.bottom() == quad
->rect
.bottom()) {
1383 bottom_edge
= device_layer_edges
.bottom();
1386 float sign
= tile_quad
.IsCounterClockwise() ? -1 : 1;
1387 bottom_edge
.scale(sign
);
1388 left_edge
.scale(sign
);
1389 top_edge
.scale(sign
);
1390 right_edge
.scale(sign
);
1392 // Create device space quad.
1393 return LayerQuad(left_edge
, top_edge
, right_edge
, bottom_edge
).ToQuadF();
1396 float GetTotalQuadError(const gfx::QuadF
* clipped_quad
,
1397 const gfx::QuadF
* ideal_rect
) {
1398 return (clipped_quad
->p1() - ideal_rect
->p1()).LengthSquared() +
1399 (clipped_quad
->p2() - ideal_rect
->p2()).LengthSquared() +
1400 (clipped_quad
->p3() - ideal_rect
->p3()).LengthSquared() +
1401 (clipped_quad
->p4() - ideal_rect
->p4()).LengthSquared();
1404 // Attempt to rotate the clipped quad until it lines up the most
1405 // correctly. This is necessary because we check the edges of this
1406 // quad against the expected left/right/top/bottom for anti-aliasing.
1407 void AlignQuadToBoundingBox(gfx::QuadF
* clipped_quad
) {
1408 gfx::QuadF bounding_quad
= gfx::QuadF(clipped_quad
->BoundingBox());
1409 gfx::QuadF best_rotation
= *clipped_quad
;
1410 float least_error_amount
= GetTotalQuadError(clipped_quad
, &bounding_quad
);
1411 for (size_t i
= 1; i
< 4; ++i
) {
1412 clipped_quad
->Realign(1);
1413 float new_error
= GetTotalQuadError(clipped_quad
, &bounding_quad
);
1414 if (new_error
< least_error_amount
) {
1415 least_error_amount
= new_error
;
1416 best_rotation
= *clipped_quad
;
1419 *clipped_quad
= best_rotation
;
1423 bool GLRenderer::ShouldAntialiasQuad(const gfx::Transform
& device_transform
,
1424 const DrawQuad
* quad
,
1425 bool force_antialiasing
) {
1426 bool is_render_pass_quad
= (quad
->material
== DrawQuad::RENDER_PASS
);
1427 // For render pass quads, |device_transform| already contains quad's rect.
1428 // TODO(rosca@adobe.com): remove branching on is_render_pass_quad
1430 if (!is_render_pass_quad
&& !quad
->IsEdge())
1432 gfx::RectF content_rect
=
1433 is_render_pass_quad
? QuadVertexRect() : quad
->visibleContentRect();
1435 bool clipped
= false;
1436 gfx::QuadF device_layer_quad
=
1437 MathUtil::MapQuad(device_transform
, gfx::QuadF(content_rect
), &clipped
);
1439 if (device_layer_quad
.BoundingBox().IsEmpty())
1442 bool is_axis_aligned_in_target
= device_layer_quad
.IsRectilinear();
1443 bool is_nearest_rect_within_epsilon
=
1444 is_axis_aligned_in_target
&&
1445 gfx::IsNearestRectWithinDistance(device_layer_quad
.BoundingBox(),
1446 kAntiAliasingEpsilon
);
1447 // AAing clipped quads is not supported by the code yet.
1448 bool use_aa
= !clipped
&& !is_nearest_rect_within_epsilon
;
1449 return use_aa
|| force_antialiasing
;
1453 void GLRenderer::SetupQuadForClippingAndAntialiasing(
1454 const gfx::Transform
& device_transform
,
1455 const DrawQuad
* quad
,
1457 const gfx::QuadF
* clip_region
,
1458 gfx::QuadF
* local_quad
,
1460 bool is_render_pass_quad
= (quad
->material
== DrawQuad::RENDER_PASS
);
1461 gfx::QuadF rotated_clip
;
1462 const gfx::QuadF
* local_clip_region
= clip_region
;
1463 if (local_clip_region
) {
1464 rotated_clip
= *clip_region
;
1465 AlignQuadToBoundingBox(&rotated_clip
);
1466 local_clip_region
= &rotated_clip
;
1469 gfx::QuadF content_rect
= is_render_pass_quad
1470 ? gfx::QuadF(QuadVertexRect())
1471 : gfx::QuadF(quad
->visibleContentRect());
1473 if (local_clip_region
) {
1474 if (!is_render_pass_quad
) {
1475 content_rect
= *local_clip_region
;
1477 GetScaledRegion(quad
->rect
, local_clip_region
, &content_rect
);
1479 *local_quad
= content_rect
;
1483 bool clipped
= false;
1484 gfx::QuadF device_layer_quad
=
1485 MathUtil::MapQuad(device_transform
, content_rect
, &clipped
);
1487 LayerQuad
device_layer_bounds(gfx::QuadF(device_layer_quad
.BoundingBox()));
1488 device_layer_bounds
.InflateAntiAliasingDistance();
1490 LayerQuad
device_layer_edges(device_layer_quad
);
1491 device_layer_edges
.InflateAntiAliasingDistance();
1493 device_layer_edges
.ToFloatArray(edge
);
1494 device_layer_bounds
.ToFloatArray(&edge
[12]);
1496 // If we have a clip region then we are split, and therefore
1497 // by necessity, at least one of our edges is not an external
1499 bool is_full_rect
= quad
->visible_rect
== quad
->rect
;
1501 bool region_contains_all_outside_edges
=
1503 (is_top(local_clip_region
, quad
) && is_left(local_clip_region
, quad
) &&
1504 is_bottom(local_clip_region
, quad
) && is_right(local_clip_region
, quad
));
1506 bool use_aa_on_all_four_edges
=
1507 !local_clip_region
&&
1508 (is_render_pass_quad
|| region_contains_all_outside_edges
);
1510 gfx::QuadF device_quad
=
1511 use_aa_on_all_four_edges
1512 ? device_layer_edges
.ToQuadF()
1513 : GetDeviceQuadWithAntialiasingOnExteriorEdges(
1514 device_layer_edges
, device_transform
, local_clip_region
, quad
);
1516 // Map device space quad to local space. device_transform has no 3d
1517 // component since it was flattened, so we don't need to project. We should
1518 // have already checked that the transform was uninvertible above.
1519 gfx::Transform
inverse_device_transform(gfx::Transform::kSkipInitialization
);
1520 bool did_invert
= device_transform
.GetInverse(&inverse_device_transform
);
1523 MathUtil::MapQuad(inverse_device_transform
, device_quad
, &clipped
);
1524 // We should not DCHECK(!clipped) here, because anti-aliasing inflation may
1525 // cause device_quad to become clipped. To our knowledge this scenario does
1526 // not need to be handled differently than the unclipped case.
1529 void GLRenderer::DrawSolidColorQuad(const DrawingFrame
* frame
,
1530 const SolidColorDrawQuad
* quad
,
1531 const gfx::QuadF
* clip_region
) {
1532 gfx::Rect tile_rect
= quad
->visible_rect
;
1534 SkColor color
= quad
->color
;
1535 float opacity
= quad
->opacity();
1536 float alpha
= (SkColorGetA(color
) * (1.0f
/ 255.0f
)) * opacity
;
1538 // Early out if alpha is small enough that quad doesn't contribute to output.
1539 if (alpha
< std::numeric_limits
<float>::epsilon() &&
1540 quad
->ShouldDrawWithBlending())
1543 gfx::Transform device_transform
=
1544 frame
->window_matrix
* frame
->projection_matrix
* quad
->quadTransform();
1545 device_transform
.FlattenTo2d();
1546 if (!device_transform
.IsInvertible())
1549 bool force_aa
= false;
1550 gfx::QuadF local_quad
= gfx::QuadF(gfx::RectF(tile_rect
));
1552 bool use_aa
= settings_
->allow_antialiasing
&&
1553 !quad
->force_anti_aliasing_off
&&
1554 ShouldAntialiasQuad(device_transform
, quad
, force_aa
);
1555 SetupQuadForClippingAndAntialiasing(device_transform
, quad
, use_aa
,
1556 clip_region
, &local_quad
, edge
);
1558 SolidColorProgramUniforms uniforms
;
1560 SolidColorUniformLocation(GetSolidColorProgramAA(), &uniforms
);
1562 SolidColorUniformLocation(GetSolidColorProgram(), &uniforms
);
1564 SetUseProgram(uniforms
.program
);
1566 gl_
->Uniform4f(uniforms
.color_location
,
1567 (SkColorGetR(color
) * (1.0f
/ 255.0f
)) * alpha
,
1568 (SkColorGetG(color
) * (1.0f
/ 255.0f
)) * alpha
,
1569 (SkColorGetB(color
) * (1.0f
/ 255.0f
)) * alpha
, alpha
);
1571 float viewport
[4] = {
1572 static_cast<float>(current_window_space_viewport_
.x()),
1573 static_cast<float>(current_window_space_viewport_
.y()),
1574 static_cast<float>(current_window_space_viewport_
.width()),
1575 static_cast<float>(current_window_space_viewport_
.height()),
1577 gl_
->Uniform4fv(uniforms
.viewport_location
, 1, viewport
);
1578 gl_
->Uniform3fv(uniforms
.edge_location
, 8, edge
);
1581 // Enable blending when the quad properties require it or if we decided
1582 // to use antialiasing.
1583 SetBlendEnabled(quad
->ShouldDrawWithBlending() || use_aa
);
1585 // Normalize to tile_rect.
1586 local_quad
.Scale(1.0f
/ tile_rect
.width(), 1.0f
/ tile_rect
.height());
1588 SetShaderQuadF(local_quad
, uniforms
.quad_location
);
1590 // The transform and vertex data are used to figure out the extents that the
1591 // un-antialiased quad should have and which vertex this is and the float
1592 // quad passed in via uniform is the actual geometry that gets used to draw
1593 // it. This is why this centered rect is used and not the original quad_rect.
1594 gfx::RectF
centered_rect(
1595 gfx::PointF(-0.5f
* tile_rect
.width(), -0.5f
* tile_rect
.height()),
1598 frame
, quad
->quadTransform(), centered_rect
, uniforms
.matrix_location
);
1601 struct TileProgramUniforms
{
1603 unsigned matrix_location
;
1604 unsigned viewport_location
;
1605 unsigned quad_location
;
1606 unsigned edge_location
;
1607 unsigned vertex_tex_transform_location
;
1608 unsigned sampler_location
;
1609 unsigned fragment_tex_transform_location
;
1610 unsigned alpha_location
;
1614 static void TileUniformLocation(T program
, TileProgramUniforms
* uniforms
) {
1615 uniforms
->program
= program
->program();
1616 uniforms
->matrix_location
= program
->vertex_shader().matrix_location();
1617 uniforms
->viewport_location
= program
->vertex_shader().viewport_location();
1618 uniforms
->quad_location
= program
->vertex_shader().quad_location();
1619 uniforms
->edge_location
= program
->vertex_shader().edge_location();
1620 uniforms
->vertex_tex_transform_location
=
1621 program
->vertex_shader().vertex_tex_transform_location();
1623 uniforms
->sampler_location
= program
->fragment_shader().sampler_location();
1624 uniforms
->alpha_location
= program
->fragment_shader().alpha_location();
1625 uniforms
->fragment_tex_transform_location
=
1626 program
->fragment_shader().fragment_tex_transform_location();
1629 void GLRenderer::DrawTileQuad(const DrawingFrame
* frame
,
1630 const TileDrawQuad
* quad
,
1631 const gfx::QuadF
* clip_region
) {
1632 DrawContentQuad(frame
, quad
, quad
->resource_id(), clip_region
);
1635 void GLRenderer::DrawContentQuad(const DrawingFrame
* frame
,
1636 const ContentDrawQuadBase
* quad
,
1637 ResourceId resource_id
,
1638 const gfx::QuadF
* clip_region
) {
1639 gfx::Transform device_transform
=
1640 frame
->window_matrix
* frame
->projection_matrix
* quad
->quadTransform();
1641 device_transform
.FlattenTo2d();
1643 bool use_aa
= settings_
->allow_antialiasing
&&
1644 ShouldAntialiasQuad(device_transform
, quad
, false);
1646 // TODO(timav): simplify coordinate transformations in DrawContentQuadAA
1647 // similar to the way DrawContentQuadNoAA works and then consider
1648 // combining DrawContentQuadAA and DrawContentQuadNoAA into one method.
1650 DrawContentQuadAA(frame
, quad
, resource_id
, device_transform
, clip_region
);
1652 DrawContentQuadNoAA(frame
, quad
, resource_id
, clip_region
);
1655 void GLRenderer::DrawContentQuadAA(const DrawingFrame
* frame
,
1656 const ContentDrawQuadBase
* quad
,
1657 ResourceId resource_id
,
1658 const gfx::Transform
& device_transform
,
1659 const gfx::QuadF
* clip_region
) {
1660 if (!device_transform
.IsInvertible())
1663 gfx::Rect tile_rect
= quad
->visible_rect
;
1665 gfx::RectF tex_coord_rect
= MathUtil::ScaleRectProportional(
1666 quad
->tex_coord_rect
, quad
->rect
, tile_rect
);
1667 float tex_to_geom_scale_x
= quad
->rect
.width() / quad
->tex_coord_rect
.width();
1668 float tex_to_geom_scale_y
=
1669 quad
->rect
.height() / quad
->tex_coord_rect
.height();
1671 gfx::RectF
clamp_geom_rect(tile_rect
);
1672 gfx::RectF
clamp_tex_rect(tex_coord_rect
);
1673 // Clamp texture coordinates to avoid sampling outside the layer
1674 // by deflating the tile region half a texel or half a texel
1675 // minus epsilon for one pixel layers. The resulting clamp region
1676 // is mapped to the unit square by the vertex shader and mapped
1677 // back to normalized texture coordinates by the fragment shader
1678 // after being clamped to 0-1 range.
1680 std::min(0.5f
, 0.5f
* clamp_tex_rect
.width() - kAntiAliasingEpsilon
);
1682 std::min(0.5f
, 0.5f
* clamp_tex_rect
.height() - kAntiAliasingEpsilon
);
1683 float geom_clamp_x
=
1684 std::min(tex_clamp_x
* tex_to_geom_scale_x
,
1685 0.5f
* clamp_geom_rect
.width() - kAntiAliasingEpsilon
);
1686 float geom_clamp_y
=
1687 std::min(tex_clamp_y
* tex_to_geom_scale_y
,
1688 0.5f
* clamp_geom_rect
.height() - kAntiAliasingEpsilon
);
1689 clamp_geom_rect
.Inset(geom_clamp_x
, geom_clamp_y
, geom_clamp_x
, geom_clamp_y
);
1690 clamp_tex_rect
.Inset(tex_clamp_x
, tex_clamp_y
, tex_clamp_x
, tex_clamp_y
);
1692 // Map clamping rectangle to unit square.
1693 float vertex_tex_translate_x
= -clamp_geom_rect
.x() / clamp_geom_rect
.width();
1694 float vertex_tex_translate_y
=
1695 -clamp_geom_rect
.y() / clamp_geom_rect
.height();
1696 float vertex_tex_scale_x
= tile_rect
.width() / clamp_geom_rect
.width();
1697 float vertex_tex_scale_y
= tile_rect
.height() / clamp_geom_rect
.height();
1699 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1700 gl_
, &highp_threshold_cache_
, highp_threshold_min_
, quad
->texture_size
);
1702 gfx::QuadF local_quad
= gfx::QuadF(gfx::RectF(tile_rect
));
1704 SetupQuadForClippingAndAntialiasing(device_transform
, quad
, true, clip_region
,
1706 ResourceProvider::ScopedSamplerGL
quad_resource_lock(
1707 resource_provider_
, resource_id
,
1708 quad
->nearest_neighbor
? GL_NEAREST
: GL_LINEAR
);
1709 SamplerType sampler
=
1710 SamplerTypeFromTextureTarget(quad_resource_lock
.target());
1712 float fragment_tex_translate_x
= clamp_tex_rect
.x();
1713 float fragment_tex_translate_y
= clamp_tex_rect
.y();
1714 float fragment_tex_scale_x
= clamp_tex_rect
.width();
1715 float fragment_tex_scale_y
= clamp_tex_rect
.height();
1717 // Map to normalized texture coordinates.
1718 if (sampler
!= SAMPLER_TYPE_2D_RECT
) {
1719 gfx::Size texture_size
= quad
->texture_size
;
1720 DCHECK(!texture_size
.IsEmpty());
1721 fragment_tex_translate_x
/= texture_size
.width();
1722 fragment_tex_translate_y
/= texture_size
.height();
1723 fragment_tex_scale_x
/= texture_size
.width();
1724 fragment_tex_scale_y
/= texture_size
.height();
1727 TileProgramUniforms uniforms
;
1728 if (quad
->swizzle_contents
) {
1729 TileUniformLocation(GetTileProgramSwizzleAA(tex_coord_precision
, sampler
),
1732 TileUniformLocation(GetTileProgramAA(tex_coord_precision
, sampler
),
1736 SetUseProgram(uniforms
.program
);
1737 gl_
->Uniform1i(uniforms
.sampler_location
, 0);
1739 float viewport
[4] = {
1740 static_cast<float>(current_window_space_viewport_
.x()),
1741 static_cast<float>(current_window_space_viewport_
.y()),
1742 static_cast<float>(current_window_space_viewport_
.width()),
1743 static_cast<float>(current_window_space_viewport_
.height()),
1745 gl_
->Uniform4fv(uniforms
.viewport_location
, 1, viewport
);
1746 gl_
->Uniform3fv(uniforms
.edge_location
, 8, edge
);
1748 gl_
->Uniform4f(uniforms
.vertex_tex_transform_location
, vertex_tex_translate_x
,
1749 vertex_tex_translate_y
, vertex_tex_scale_x
,
1750 vertex_tex_scale_y
);
1751 gl_
->Uniform4f(uniforms
.fragment_tex_transform_location
,
1752 fragment_tex_translate_x
, fragment_tex_translate_y
,
1753 fragment_tex_scale_x
, fragment_tex_scale_y
);
1755 // Blending is required for antialiasing.
1756 SetBlendEnabled(true);
1758 // Normalize to tile_rect.
1759 local_quad
.Scale(1.0f
/ tile_rect
.width(), 1.0f
/ tile_rect
.height());
1761 SetShaderOpacity(quad
->opacity(), uniforms
.alpha_location
);
1762 SetShaderQuadF(local_quad
, uniforms
.quad_location
);
1764 // The transform and vertex data are used to figure out the extents that the
1765 // un-antialiased quad should have and which vertex this is and the float
1766 // quad passed in via uniform is the actual geometry that gets used to draw
1767 // it. This is why this centered rect is used and not the original quad_rect.
1768 gfx::RectF
centered_rect(
1769 gfx::PointF(-0.5f
* tile_rect
.width(), -0.5f
* tile_rect
.height()),
1772 frame
, quad
->quadTransform(), centered_rect
, uniforms
.matrix_location
);
1775 void GLRenderer::DrawContentQuadNoAA(const DrawingFrame
* frame
,
1776 const ContentDrawQuadBase
* quad
,
1777 ResourceId resource_id
,
1778 const gfx::QuadF
* clip_region
) {
1779 gfx::RectF tex_coord_rect
= MathUtil::ScaleRectProportional(
1780 quad
->tex_coord_rect
, quad
->rect
, quad
->visible_rect
);
1781 float tex_to_geom_scale_x
= quad
->rect
.width() / quad
->tex_coord_rect
.width();
1782 float tex_to_geom_scale_y
=
1783 quad
->rect
.height() / quad
->tex_coord_rect
.height();
1785 bool scaled
= (tex_to_geom_scale_x
!= 1.f
|| tex_to_geom_scale_y
!= 1.f
);
1787 (scaled
|| !quad
->quadTransform().IsIdentityOrIntegerTranslation()) &&
1788 !quad
->nearest_neighbor
1792 ResourceProvider::ScopedSamplerGL
quad_resource_lock(
1793 resource_provider_
, resource_id
, filter
);
1794 SamplerType sampler
=
1795 SamplerTypeFromTextureTarget(quad_resource_lock
.target());
1797 float vertex_tex_translate_x
= tex_coord_rect
.x();
1798 float vertex_tex_translate_y
= tex_coord_rect
.y();
1799 float vertex_tex_scale_x
= tex_coord_rect
.width();
1800 float vertex_tex_scale_y
= tex_coord_rect
.height();
1802 // Map to normalized texture coordinates.
1803 if (sampler
!= SAMPLER_TYPE_2D_RECT
) {
1804 gfx::Size texture_size
= quad
->texture_size
;
1805 DCHECK(!texture_size
.IsEmpty());
1806 vertex_tex_translate_x
/= texture_size
.width();
1807 vertex_tex_translate_y
/= texture_size
.height();
1808 vertex_tex_scale_x
/= texture_size
.width();
1809 vertex_tex_scale_y
/= texture_size
.height();
1812 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1813 gl_
, &highp_threshold_cache_
, highp_threshold_min_
, quad
->texture_size
);
1815 TileProgramUniforms uniforms
;
1816 if (quad
->ShouldDrawWithBlending()) {
1817 if (quad
->swizzle_contents
) {
1818 TileUniformLocation(GetTileProgramSwizzle(tex_coord_precision
, sampler
),
1821 TileUniformLocation(GetTileProgram(tex_coord_precision
, sampler
),
1825 if (quad
->swizzle_contents
) {
1826 TileUniformLocation(
1827 GetTileProgramSwizzleOpaque(tex_coord_precision
, sampler
), &uniforms
);
1829 TileUniformLocation(GetTileProgramOpaque(tex_coord_precision
, sampler
),
1834 SetUseProgram(uniforms
.program
);
1835 gl_
->Uniform1i(uniforms
.sampler_location
, 0);
1837 gl_
->Uniform4f(uniforms
.vertex_tex_transform_location
, vertex_tex_translate_x
,
1838 vertex_tex_translate_y
, vertex_tex_scale_x
,
1839 vertex_tex_scale_y
);
1841 SetBlendEnabled(quad
->ShouldDrawWithBlending());
1843 SetShaderOpacity(quad
->opacity(), uniforms
.alpha_location
);
1845 // Pass quad coordinates to the uniform in the same order as GeometryBinding
1846 // does, then vertices will match the texture mapping in the vertex buffer.
1847 // The method SetShaderQuadF() changes the order of vertices and so it's
1849 gfx::QuadF
tile_rect(quad
->visible_rect
);
1850 float width
= quad
->visible_rect
.width();
1851 float height
= quad
->visible_rect
.height();
1852 gfx::PointF top_left
= quad
->visible_rect
.origin();
1854 tile_rect
= *clip_region
;
1856 (tile_rect
.p4().x() - top_left
.x()) / width
,
1857 (tile_rect
.p4().y() - top_left
.y()) / height
,
1858 (tile_rect
.p1().x() - top_left
.x()) / width
,
1859 (tile_rect
.p1().y() - top_left
.y()) / height
,
1860 (tile_rect
.p2().x() - top_left
.x()) / width
,
1861 (tile_rect
.p2().y() - top_left
.y()) / height
,
1862 (tile_rect
.p3().x() - top_left
.x()) / width
,
1863 (tile_rect
.p3().y() - top_left
.y()) / height
,
1865 PrepareGeometry(CLIPPED_BINDING
);
1866 clipped_geometry_
->InitializeCustomQuadWithUVs(
1867 gfx::QuadF(quad
->visible_rect
), gl_uv
);
1869 PrepareGeometry(SHARED_BINDING
);
1871 float gl_quad
[8] = {
1881 gl_
->Uniform2fv(uniforms
.quad_location
, 4, gl_quad
);
1883 static float gl_matrix
[16];
1884 ToGLMatrix(&gl_matrix
[0], frame
->projection_matrix
* quad
->quadTransform());
1885 gl_
->UniformMatrix4fv(uniforms
.matrix_location
, 1, false, &gl_matrix
[0]);
1887 gl_
->DrawElements(GL_TRIANGLES
, 6, GL_UNSIGNED_SHORT
, 0);
1890 void GLRenderer::DrawYUVVideoQuad(const DrawingFrame
* frame
,
1891 const YUVVideoDrawQuad
* quad
,
1892 const gfx::QuadF
* clip_region
) {
1893 SetBlendEnabled(quad
->ShouldDrawWithBlending());
1895 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1897 &highp_threshold_cache_
,
1898 highp_threshold_min_
,
1899 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
1901 bool use_alpha_plane
= quad
->a_plane_resource_id() != 0;
1903 ResourceProvider::ScopedSamplerGL
y_plane_lock(
1904 resource_provider_
, quad
->y_plane_resource_id(), GL_TEXTURE1
, GL_LINEAR
);
1905 ResourceProvider::ScopedSamplerGL
u_plane_lock(
1906 resource_provider_
, quad
->u_plane_resource_id(), GL_TEXTURE2
, GL_LINEAR
);
1907 DCHECK_EQ(y_plane_lock
.target(), u_plane_lock
.target());
1908 ResourceProvider::ScopedSamplerGL
v_plane_lock(
1909 resource_provider_
, quad
->v_plane_resource_id(), GL_TEXTURE3
, GL_LINEAR
);
1910 DCHECK_EQ(y_plane_lock
.target(), v_plane_lock
.target());
1911 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> a_plane_lock
;
1912 if (use_alpha_plane
) {
1913 a_plane_lock
.reset(new ResourceProvider::ScopedSamplerGL(
1914 resource_provider_
, quad
->a_plane_resource_id(), GL_TEXTURE4
,
1916 DCHECK_EQ(y_plane_lock
.target(), a_plane_lock
->target());
1919 // All planes must have the same sampler type.
1920 SamplerType sampler
= SamplerTypeFromTextureTarget(y_plane_lock
.target());
1922 int matrix_location
= -1;
1923 int ya_tex_scale_location
= -1;
1924 int ya_tex_offset_location
= -1;
1925 int uv_tex_scale_location
= -1;
1926 int uv_tex_offset_location
= -1;
1927 int ya_clamp_rect_location
= -1;
1928 int uv_clamp_rect_location
= -1;
1929 int y_texture_location
= -1;
1930 int u_texture_location
= -1;
1931 int v_texture_location
= -1;
1932 int a_texture_location
= -1;
1933 int yuv_matrix_location
= -1;
1934 int yuv_adj_location
= -1;
1935 int alpha_location
= -1;
1936 if (use_alpha_plane
) {
1937 const VideoYUVAProgram
* program
=
1938 GetVideoYUVAProgram(tex_coord_precision
, sampler
);
1939 DCHECK(program
&& (program
->initialized() || IsContextLost()));
1940 SetUseProgram(program
->program());
1941 matrix_location
= program
->vertex_shader().matrix_location();
1942 ya_tex_scale_location
= program
->vertex_shader().ya_tex_scale_location();
1943 ya_tex_offset_location
= program
->vertex_shader().ya_tex_offset_location();
1944 uv_tex_scale_location
= program
->vertex_shader().uv_tex_scale_location();
1945 uv_tex_offset_location
= program
->vertex_shader().uv_tex_offset_location();
1946 y_texture_location
= program
->fragment_shader().y_texture_location();
1947 u_texture_location
= program
->fragment_shader().u_texture_location();
1948 v_texture_location
= program
->fragment_shader().v_texture_location();
1949 a_texture_location
= program
->fragment_shader().a_texture_location();
1950 yuv_matrix_location
= program
->fragment_shader().yuv_matrix_location();
1951 yuv_adj_location
= program
->fragment_shader().yuv_adj_location();
1952 ya_clamp_rect_location
=
1953 program
->fragment_shader().ya_clamp_rect_location();
1954 uv_clamp_rect_location
=
1955 program
->fragment_shader().uv_clamp_rect_location();
1956 alpha_location
= program
->fragment_shader().alpha_location();
1958 const VideoYUVProgram
* program
=
1959 GetVideoYUVProgram(tex_coord_precision
, sampler
);
1960 DCHECK(program
&& (program
->initialized() || IsContextLost()));
1961 SetUseProgram(program
->program());
1962 matrix_location
= program
->vertex_shader().matrix_location();
1963 ya_tex_scale_location
= program
->vertex_shader().ya_tex_scale_location();
1964 ya_tex_offset_location
= program
->vertex_shader().ya_tex_offset_location();
1965 uv_tex_scale_location
= program
->vertex_shader().uv_tex_scale_location();
1966 uv_tex_offset_location
= program
->vertex_shader().uv_tex_offset_location();
1967 y_texture_location
= program
->fragment_shader().y_texture_location();
1968 u_texture_location
= program
->fragment_shader().u_texture_location();
1969 v_texture_location
= program
->fragment_shader().v_texture_location();
1970 yuv_matrix_location
= program
->fragment_shader().yuv_matrix_location();
1971 yuv_adj_location
= program
->fragment_shader().yuv_adj_location();
1972 ya_clamp_rect_location
=
1973 program
->fragment_shader().ya_clamp_rect_location();
1974 uv_clamp_rect_location
=
1975 program
->fragment_shader().uv_clamp_rect_location();
1976 alpha_location
= program
->fragment_shader().alpha_location();
1979 gfx::SizeF
ya_tex_scale(1.0f
, 1.0f
);
1980 gfx::SizeF
uv_tex_scale(1.0f
, 1.0f
);
1981 if (sampler
!= SAMPLER_TYPE_2D_RECT
) {
1982 DCHECK(!quad
->ya_tex_size
.IsEmpty());
1983 DCHECK(!quad
->uv_tex_size
.IsEmpty());
1984 ya_tex_scale
= gfx::SizeF(1.0f
/ quad
->ya_tex_size
.width(),
1985 1.0f
/ quad
->ya_tex_size
.height());
1986 uv_tex_scale
= gfx::SizeF(1.0f
/ quad
->uv_tex_size
.width(),
1987 1.0f
/ quad
->uv_tex_size
.height());
1990 float ya_vertex_tex_translate_x
=
1991 quad
->ya_tex_coord_rect
.x() * ya_tex_scale
.width();
1992 float ya_vertex_tex_translate_y
=
1993 quad
->ya_tex_coord_rect
.y() * ya_tex_scale
.height();
1994 float ya_vertex_tex_scale_x
=
1995 quad
->ya_tex_coord_rect
.width() * ya_tex_scale
.width();
1996 float ya_vertex_tex_scale_y
=
1997 quad
->ya_tex_coord_rect
.height() * ya_tex_scale
.height();
1999 float uv_vertex_tex_translate_x
=
2000 quad
->uv_tex_coord_rect
.x() * uv_tex_scale
.width();
2001 float uv_vertex_tex_translate_y
=
2002 quad
->uv_tex_coord_rect
.y() * uv_tex_scale
.height();
2003 float uv_vertex_tex_scale_x
=
2004 quad
->uv_tex_coord_rect
.width() * uv_tex_scale
.width();
2005 float uv_vertex_tex_scale_y
=
2006 quad
->uv_tex_coord_rect
.height() * uv_tex_scale
.height();
2008 gl_
->Uniform2f(ya_tex_scale_location
, ya_vertex_tex_scale_x
,
2009 ya_vertex_tex_scale_y
);
2010 gl_
->Uniform2f(ya_tex_offset_location
, ya_vertex_tex_translate_x
,
2011 ya_vertex_tex_translate_y
);
2012 gl_
->Uniform2f(uv_tex_scale_location
, uv_vertex_tex_scale_x
,
2013 uv_vertex_tex_scale_y
);
2014 gl_
->Uniform2f(uv_tex_offset_location
, uv_vertex_tex_translate_x
,
2015 uv_vertex_tex_translate_y
);
2017 gfx::RectF
ya_clamp_rect(ya_vertex_tex_translate_x
, ya_vertex_tex_translate_y
,
2018 ya_vertex_tex_scale_x
, ya_vertex_tex_scale_y
);
2019 ya_clamp_rect
.Inset(0.5f
* ya_tex_scale
.width(),
2020 0.5f
* ya_tex_scale
.height());
2021 gfx::RectF
uv_clamp_rect(uv_vertex_tex_translate_x
, uv_vertex_tex_translate_y
,
2022 uv_vertex_tex_scale_x
, uv_vertex_tex_scale_y
);
2023 uv_clamp_rect
.Inset(0.5f
* uv_tex_scale
.width(),
2024 0.5f
* uv_tex_scale
.height());
2025 gl_
->Uniform4f(ya_clamp_rect_location
, ya_clamp_rect
.x(), ya_clamp_rect
.y(),
2026 ya_clamp_rect
.right(), ya_clamp_rect
.bottom());
2027 gl_
->Uniform4f(uv_clamp_rect_location
, uv_clamp_rect
.x(), uv_clamp_rect
.y(),
2028 uv_clamp_rect
.right(), uv_clamp_rect
.bottom());
2030 gl_
->Uniform1i(y_texture_location
, 1);
2031 gl_
->Uniform1i(u_texture_location
, 2);
2032 gl_
->Uniform1i(v_texture_location
, 3);
2033 if (use_alpha_plane
)
2034 gl_
->Uniform1i(a_texture_location
, 4);
2036 // These values are magic numbers that are used in the transformation from YUV
2037 // to RGB color values. They are taken from the following webpage:
2038 // http://www.fourcc.org/fccyvrgb.php
2039 float yuv_to_rgb_rec601
[9] = {
2040 1.164f
, 1.164f
, 1.164f
, 0.0f
, -.391f
, 2.018f
, 1.596f
, -.813f
, 0.0f
,
2042 float yuv_to_rgb_jpeg
[9] = {
2043 1.f
, 1.f
, 1.f
, 0.0f
, -.34414f
, 1.772f
, 1.402f
, -.71414f
, 0.0f
,
2045 float yuv_to_rgb_rec709
[9] = {
2046 1.164f
, 1.164f
, 1.164f
, 0.0f
, -0.213f
, 2.112f
, 1.793f
, -0.533f
, 0.0f
,
2049 // These values map to 16, 128, and 128 respectively, and are computed
2050 // as a fraction over 256 (e.g. 16 / 256 = 0.0625).
2051 // They are used in the YUV to RGBA conversion formula:
2052 // Y - 16 : Gives 16 values of head and footroom for overshooting
2053 // U - 128 : Turns unsigned U into signed U [-128,127]
2054 // V - 128 : Turns unsigned V into signed V [-128,127]
2055 float yuv_adjust_constrained
[3] = {
2056 -0.0625f
, -0.5f
, -0.5f
,
2059 // Same as above, but without the head and footroom.
2060 float yuv_adjust_full
[3] = {
2064 float* yuv_to_rgb
= NULL
;
2065 float* yuv_adjust
= NULL
;
2067 switch (quad
->color_space
) {
2068 case YUVVideoDrawQuad::REC_601
:
2069 yuv_to_rgb
= yuv_to_rgb_rec601
;
2070 yuv_adjust
= yuv_adjust_constrained
;
2072 case YUVVideoDrawQuad::REC_709
:
2073 yuv_to_rgb
= yuv_to_rgb_rec709
;
2074 yuv_adjust
= yuv_adjust_constrained
;
2076 case YUVVideoDrawQuad::JPEG
:
2077 yuv_to_rgb
= yuv_to_rgb_jpeg
;
2078 yuv_adjust
= yuv_adjust_full
;
2082 // The transform and vertex data are used to figure out the extents that the
2083 // un-antialiased quad should have and which vertex this is and the float
2084 // quad passed in via uniform is the actual geometry that gets used to draw
2085 // it. This is why this centered rect is used and not the original quad_rect.
2086 gfx::RectF tile_rect
= quad
->rect
;
2087 gl_
->UniformMatrix3fv(yuv_matrix_location
, 1, 0, yuv_to_rgb
);
2088 gl_
->Uniform3fv(yuv_adj_location
, 1, yuv_adjust
);
2090 SetShaderOpacity(quad
->opacity(), alpha_location
);
2092 DrawQuadGeometry(frame
, quad
->quadTransform(), tile_rect
, matrix_location
);
2095 GetScaledUVs(quad
->visible_rect
, clip_region
, uvs
);
2096 gfx::QuadF region_quad
= *clip_region
;
2097 region_quad
.Scale(1.0f
/ tile_rect
.width(), 1.0f
/ tile_rect
.height());
2098 region_quad
-= gfx::Vector2dF(0.5f
, 0.5f
);
2099 DrawQuadGeometryClippedByQuadF(frame
, quad
->quadTransform(), tile_rect
,
2100 region_quad
, matrix_location
, uvs
);
2104 void GLRenderer::DrawStreamVideoQuad(const DrawingFrame
* frame
,
2105 const StreamVideoDrawQuad
* quad
,
2106 const gfx::QuadF
* clip_region
) {
2107 SetBlendEnabled(quad
->ShouldDrawWithBlending());
2109 static float gl_matrix
[16];
2111 DCHECK(capabilities_
.using_egl_image
);
2113 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
2115 &highp_threshold_cache_
,
2116 highp_threshold_min_
,
2117 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
2119 const VideoStreamTextureProgram
* program
=
2120 GetVideoStreamTextureProgram(tex_coord_precision
);
2121 SetUseProgram(program
->program());
2123 ToGLMatrix(&gl_matrix
[0], quad
->matrix
);
2124 gl_
->UniformMatrix4fv(program
->vertex_shader().tex_matrix_location(), 1,
2127 ResourceProvider::ScopedReadLockGL
lock(resource_provider_
,
2128 quad
->resource_id());
2129 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
2130 gl_
->BindTexture(GL_TEXTURE_EXTERNAL_OES
, lock
.texture_id());
2132 gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0);
2134 SetShaderOpacity(quad
->opacity(),
2135 program
->fragment_shader().alpha_location());
2137 DrawQuadGeometry(frame
, quad
->quadTransform(), quad
->rect
,
2138 program
->vertex_shader().matrix_location());
2140 gfx::QuadF
region_quad(*clip_region
);
2141 region_quad
.Scale(1.0f
/ quad
->rect
.width(), 1.0f
/ quad
->rect
.height());
2142 region_quad
-= gfx::Vector2dF(0.5f
, 0.5f
);
2144 GetScaledUVs(quad
->visible_rect
, clip_region
, uvs
);
2145 DrawQuadGeometryClippedByQuadF(
2146 frame
, quad
->quadTransform(), quad
->rect
, region_quad
,
2147 program
->vertex_shader().matrix_location(), uvs
);
2151 struct TextureProgramBinding
{
2152 template <class Program
>
2153 void Set(Program
* program
) {
2155 program_id
= program
->program();
2156 sampler_location
= program
->fragment_shader().sampler_location();
2157 matrix_location
= program
->vertex_shader().matrix_location();
2158 background_color_location
=
2159 program
->fragment_shader().background_color_location();
2162 int sampler_location
;
2163 int matrix_location
;
2164 int transform_location
;
2165 int background_color_location
;
2168 struct TexTransformTextureProgramBinding
: TextureProgramBinding
{
2169 template <class Program
>
2170 void Set(Program
* program
) {
2171 TextureProgramBinding::Set(program
);
2172 tex_transform_location
= program
->vertex_shader().tex_transform_location();
2173 vertex_opacity_location
=
2174 program
->vertex_shader().vertex_opacity_location();
2176 int tex_transform_location
;
2177 int vertex_opacity_location
;
2180 void GLRenderer::FlushTextureQuadCache(BoundGeometry flush_binding
) {
2181 // Check to see if we have anything to draw.
2182 if (draw_cache_
.program_id
== -1)
2185 PrepareGeometry(flush_binding
);
2187 // Set the correct blending mode.
2188 SetBlendEnabled(draw_cache_
.needs_blending
);
2190 // Bind the program to the GL state.
2191 SetUseProgram(draw_cache_
.program_id
);
2193 // Bind the correct texture sampler location.
2194 gl_
->Uniform1i(draw_cache_
.sampler_location
, 0);
2196 // Assume the current active textures is 0.
2197 ResourceProvider::ScopedSamplerGL
locked_quad(
2199 draw_cache_
.resource_id
,
2200 draw_cache_
.nearest_neighbor
? GL_NEAREST
: GL_LINEAR
);
2201 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
2202 gl_
->BindTexture(locked_quad
.target(), locked_quad
.texture_id());
2204 static_assert(sizeof(Float4
) == 4 * sizeof(float),
2205 "Float4 struct should be densely packed");
2206 static_assert(sizeof(Float16
) == 16 * sizeof(float),
2207 "Float16 struct should be densely packed");
2209 // Upload the tranforms for both points and uvs.
2210 gl_
->UniformMatrix4fv(
2211 static_cast<int>(draw_cache_
.matrix_location
),
2212 static_cast<int>(draw_cache_
.matrix_data
.size()), false,
2213 reinterpret_cast<float*>(&draw_cache_
.matrix_data
.front()));
2214 gl_
->Uniform4fv(static_cast<int>(draw_cache_
.uv_xform_location
),
2215 static_cast<int>(draw_cache_
.uv_xform_data
.size()),
2216 reinterpret_cast<float*>(&draw_cache_
.uv_xform_data
.front()));
2218 if (draw_cache_
.background_color
!= SK_ColorTRANSPARENT
) {
2219 Float4 background_color
= PremultipliedColor(draw_cache_
.background_color
);
2220 gl_
->Uniform4fv(draw_cache_
.background_color_location
, 1,
2221 background_color
.data
);
2225 static_cast<int>(draw_cache_
.vertex_opacity_location
),
2226 static_cast<int>(draw_cache_
.vertex_opacity_data
.size()),
2227 static_cast<float*>(&draw_cache_
.vertex_opacity_data
.front()));
2230 gl_
->DrawElements(GL_TRIANGLES
, 6 * draw_cache_
.matrix_data
.size(),
2231 GL_UNSIGNED_SHORT
, 0);
2234 draw_cache_
.program_id
= -1;
2235 draw_cache_
.uv_xform_data
.resize(0);
2236 draw_cache_
.vertex_opacity_data
.resize(0);
2237 draw_cache_
.matrix_data
.resize(0);
2239 // If we had a clipped binding, prepare the shared binding for the
2241 if (flush_binding
== CLIPPED_BINDING
) {
2242 PrepareGeometry(SHARED_BINDING
);
2246 void GLRenderer::EnqueueTextureQuad(const DrawingFrame
* frame
,
2247 const TextureDrawQuad
* quad
,
2248 const gfx::QuadF
* clip_region
) {
2249 // If we have a clip_region then we have to render the next quad
2250 // with dynamic geometry, therefore we must flush all pending
2253 // We send in false here because we want to flush what's currently in the
2254 // queue using the shared_geometry and not clipped_geometry
2255 FlushTextureQuadCache(SHARED_BINDING
);
2258 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
2260 &highp_threshold_cache_
,
2261 highp_threshold_min_
,
2262 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
2264 ResourceProvider::ScopedReadLockGL
lock(resource_provider_
,
2265 quad
->resource_id());
2266 const SamplerType sampler
= SamplerTypeFromTextureTarget(lock
.target());
2267 // Choose the correct texture program binding
2268 TexTransformTextureProgramBinding binding
;
2269 if (quad
->premultiplied_alpha
) {
2270 if (quad
->background_color
== SK_ColorTRANSPARENT
) {
2271 binding
.Set(GetTextureProgram(tex_coord_precision
, sampler
));
2273 binding
.Set(GetTextureBackgroundProgram(tex_coord_precision
, sampler
));
2276 if (quad
->background_color
== SK_ColorTRANSPARENT
) {
2278 GetNonPremultipliedTextureProgram(tex_coord_precision
, sampler
));
2280 binding
.Set(GetNonPremultipliedTextureBackgroundProgram(
2281 tex_coord_precision
, sampler
));
2285 int resource_id
= quad
->resource_id();
2287 if (draw_cache_
.program_id
!= binding
.program_id
||
2288 draw_cache_
.resource_id
!= resource_id
||
2289 draw_cache_
.needs_blending
!= quad
->ShouldDrawWithBlending() ||
2290 draw_cache_
.nearest_neighbor
!= quad
->nearest_neighbor
||
2291 draw_cache_
.background_color
!= quad
->background_color
||
2292 draw_cache_
.matrix_data
.size() >= 8) {
2293 FlushTextureQuadCache(SHARED_BINDING
);
2294 draw_cache_
.program_id
= binding
.program_id
;
2295 draw_cache_
.resource_id
= resource_id
;
2296 draw_cache_
.needs_blending
= quad
->ShouldDrawWithBlending();
2297 draw_cache_
.nearest_neighbor
= quad
->nearest_neighbor
;
2298 draw_cache_
.background_color
= quad
->background_color
;
2300 draw_cache_
.uv_xform_location
= binding
.tex_transform_location
;
2301 draw_cache_
.background_color_location
= binding
.background_color_location
;
2302 draw_cache_
.vertex_opacity_location
= binding
.vertex_opacity_location
;
2303 draw_cache_
.matrix_location
= binding
.matrix_location
;
2304 draw_cache_
.sampler_location
= binding
.sampler_location
;
2307 // Generate the uv-transform
2309 draw_cache_
.uv_xform_data
.push_back(UVTransform(quad
));
2311 Float4 uv_transform
= {{0.0f
, 0.0f
, 1.0f
, 1.0f
}};
2312 draw_cache_
.uv_xform_data
.push_back(uv_transform
);
2315 // Generate the vertex opacity
2316 const float opacity
= quad
->opacity();
2317 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[0] * opacity
);
2318 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[1] * opacity
);
2319 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[2] * opacity
);
2320 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[3] * opacity
);
2322 // Generate the transform matrix
2323 gfx::Transform quad_rect_matrix
;
2324 QuadRectTransform(&quad_rect_matrix
, quad
->quadTransform(), quad
->rect
);
2325 quad_rect_matrix
= frame
->projection_matrix
* quad_rect_matrix
;
2328 quad_rect_matrix
.matrix().asColMajorf(m
.data
);
2329 draw_cache_
.matrix_data
.push_back(m
);
2332 gfx::QuadF scaled_region
;
2333 if (!GetScaledRegion(quad
->rect
, clip_region
, &scaled_region
)) {
2334 scaled_region
= SharedGeometryQuad().BoundingBox();
2336 // Both the scaled region and the SharedGeomtryQuad are in the space
2337 // -0.5->0.5. We need to move that to the space 0->1.
2339 uv
[0] = scaled_region
.p1().x() + 0.5f
;
2340 uv
[1] = scaled_region
.p1().y() + 0.5f
;
2341 uv
[2] = scaled_region
.p2().x() + 0.5f
;
2342 uv
[3] = scaled_region
.p2().y() + 0.5f
;
2343 uv
[4] = scaled_region
.p3().x() + 0.5f
;
2344 uv
[5] = scaled_region
.p3().y() + 0.5f
;
2345 uv
[6] = scaled_region
.p4().x() + 0.5f
;
2346 uv
[7] = scaled_region
.p4().y() + 0.5f
;
2347 PrepareGeometry(CLIPPED_BINDING
);
2348 clipped_geometry_
->InitializeCustomQuadWithUVs(scaled_region
, uv
);
2349 FlushTextureQuadCache(CLIPPED_BINDING
);
2353 void GLRenderer::DrawIOSurfaceQuad(const DrawingFrame
* frame
,
2354 const IOSurfaceDrawQuad
* quad
,
2355 const gfx::QuadF
* clip_region
) {
2356 SetBlendEnabled(quad
->ShouldDrawWithBlending());
2358 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
2360 &highp_threshold_cache_
,
2361 highp_threshold_min_
,
2362 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
2364 TexTransformTextureProgramBinding binding
;
2365 binding
.Set(GetTextureIOSurfaceProgram(tex_coord_precision
));
2367 SetUseProgram(binding
.program_id
);
2368 gl_
->Uniform1i(binding
.sampler_location
, 0);
2369 if (quad
->orientation
== IOSurfaceDrawQuad::FLIPPED
) {
2371 binding
.tex_transform_location
, 0, quad
->io_surface_size
.height(),
2372 quad
->io_surface_size
.width(), quad
->io_surface_size
.height() * -1.0f
);
2374 gl_
->Uniform4f(binding
.tex_transform_location
, 0, 0,
2375 quad
->io_surface_size
.width(),
2376 quad
->io_surface_size
.height());
2379 const float vertex_opacity
[] = {quad
->opacity(), quad
->opacity(),
2380 quad
->opacity(), quad
->opacity()};
2381 gl_
->Uniform1fv(binding
.vertex_opacity_location
, 4, vertex_opacity
);
2383 ResourceProvider::ScopedReadLockGL
lock(resource_provider_
,
2384 quad
->io_surface_resource_id());
2385 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
2386 gl_
->BindTexture(GL_TEXTURE_RECTANGLE_ARB
, lock
.texture_id());
2389 DrawQuadGeometry(frame
, quad
->quadTransform(), quad
->rect
,
2390 binding
.matrix_location
);
2393 GetScaledUVs(quad
->visible_rect
, clip_region
, uvs
);
2394 DrawQuadGeometryClippedByQuadF(frame
, quad
->quadTransform(), quad
->rect
,
2395 *clip_region
, binding
.matrix_location
, uvs
);
2398 gl_
->BindTexture(GL_TEXTURE_RECTANGLE_ARB
, 0);
2401 void GLRenderer::FinishDrawingFrame(DrawingFrame
* frame
) {
2402 if (use_sync_query_
) {
2403 DCHECK(current_sync_query_
);
2404 current_sync_query_
->End();
2405 pending_sync_queries_
.push_back(current_sync_query_
.Pass());
2408 current_framebuffer_lock_
= nullptr;
2409 swap_buffer_rect_
.Union(gfx::ToEnclosingRect(frame
->root_damage_rect
));
2411 gl_
->Disable(GL_BLEND
);
2412 blend_shadow_
= false;
2414 ScheduleOverlays(frame
);
2417 void GLRenderer::FinishDrawingQuadList() {
2418 FlushTextureQuadCache(SHARED_BINDING
);
2421 bool GLRenderer::FlippedFramebuffer(const DrawingFrame
* frame
) const {
2422 if (frame
->current_render_pass
!= frame
->root_render_pass
)
2424 return FlippedRootFramebuffer();
2427 bool GLRenderer::FlippedRootFramebuffer() const {
2428 // GL is normally flipped, so a flipped output results in an unflipping.
2429 return !output_surface_
->capabilities().flipped_output_surface
;
2432 void GLRenderer::EnsureScissorTestEnabled() {
2433 if (is_scissor_enabled_
)
2436 FlushTextureQuadCache(SHARED_BINDING
);
2437 gl_
->Enable(GL_SCISSOR_TEST
);
2438 is_scissor_enabled_
= true;
2441 void GLRenderer::EnsureScissorTestDisabled() {
2442 if (!is_scissor_enabled_
)
2445 FlushTextureQuadCache(SHARED_BINDING
);
2446 gl_
->Disable(GL_SCISSOR_TEST
);
2447 is_scissor_enabled_
= false;
2450 void GLRenderer::CopyCurrentRenderPassToBitmap(
2451 DrawingFrame
* frame
,
2452 scoped_ptr
<CopyOutputRequest
> request
) {
2453 TRACE_EVENT0("cc", "GLRenderer::CopyCurrentRenderPassToBitmap");
2454 gfx::Rect copy_rect
= frame
->current_render_pass
->output_rect
;
2455 if (request
->has_area())
2456 copy_rect
.Intersect(request
->area());
2457 GetFramebufferPixelsAsync(frame
, copy_rect
, request
.Pass());
2460 void GLRenderer::ToGLMatrix(float* gl_matrix
, const gfx::Transform
& transform
) {
2461 transform
.matrix().asColMajorf(gl_matrix
);
2464 void GLRenderer::SetShaderQuadF(const gfx::QuadF
& quad
, int quad_location
) {
2465 if (quad_location
== -1)
2469 gl_quad
[0] = quad
.p1().x();
2470 gl_quad
[1] = quad
.p1().y();
2471 gl_quad
[2] = quad
.p2().x();
2472 gl_quad
[3] = quad
.p2().y();
2473 gl_quad
[4] = quad
.p3().x();
2474 gl_quad
[5] = quad
.p3().y();
2475 gl_quad
[6] = quad
.p4().x();
2476 gl_quad
[7] = quad
.p4().y();
2477 gl_
->Uniform2fv(quad_location
, 4, gl_quad
);
2480 void GLRenderer::SetShaderOpacity(float opacity
, int alpha_location
) {
2481 if (alpha_location
!= -1)
2482 gl_
->Uniform1f(alpha_location
, opacity
);
2485 void GLRenderer::SetStencilEnabled(bool enabled
) {
2486 if (enabled
== stencil_shadow_
)
2490 gl_
->Enable(GL_STENCIL_TEST
);
2492 gl_
->Disable(GL_STENCIL_TEST
);
2493 stencil_shadow_
= enabled
;
2496 void GLRenderer::SetBlendEnabled(bool enabled
) {
2497 if (enabled
== blend_shadow_
)
2501 gl_
->Enable(GL_BLEND
);
2503 gl_
->Disable(GL_BLEND
);
2504 blend_shadow_
= enabled
;
2507 void GLRenderer::SetUseProgram(unsigned program
) {
2508 if (program
== program_shadow_
)
2510 gl_
->UseProgram(program
);
2511 program_shadow_
= program
;
2514 void GLRenderer::DrawQuadGeometryClippedByQuadF(
2515 const DrawingFrame
* frame
,
2516 const gfx::Transform
& draw_transform
,
2517 const gfx::RectF
& quad_rect
,
2518 const gfx::QuadF
& clipping_region_quad
,
2519 int matrix_location
,
2521 PrepareGeometry(CLIPPED_BINDING
);
2523 clipped_geometry_
->InitializeCustomQuadWithUVs(clipping_region_quad
, uvs
);
2525 clipped_geometry_
->InitializeCustomQuad(clipping_region_quad
);
2527 gfx::Transform quad_rect_matrix
;
2528 QuadRectTransform(&quad_rect_matrix
, draw_transform
, quad_rect
);
2529 static float gl_matrix
[16];
2530 ToGLMatrix(&gl_matrix
[0], frame
->projection_matrix
* quad_rect_matrix
);
2531 gl_
->UniformMatrix4fv(matrix_location
, 1, false, &gl_matrix
[0]);
2533 gl_
->DrawElements(GL_TRIANGLES
, 6, GL_UNSIGNED_SHORT
,
2534 reinterpret_cast<const void*>(0));
2537 void GLRenderer::DrawQuadGeometry(const DrawingFrame
* frame
,
2538 const gfx::Transform
& draw_transform
,
2539 const gfx::RectF
& quad_rect
,
2540 int matrix_location
) {
2541 PrepareGeometry(SHARED_BINDING
);
2542 gfx::Transform quad_rect_matrix
;
2543 QuadRectTransform(&quad_rect_matrix
, draw_transform
, quad_rect
);
2544 static float gl_matrix
[16];
2545 ToGLMatrix(&gl_matrix
[0], frame
->projection_matrix
* quad_rect_matrix
);
2546 gl_
->UniformMatrix4fv(matrix_location
, 1, false, &gl_matrix
[0]);
2548 gl_
->DrawElements(GL_TRIANGLES
, 6, GL_UNSIGNED_SHORT
, 0);
2551 void GLRenderer::Finish() {
2552 TRACE_EVENT0("cc", "GLRenderer::Finish");
2556 void GLRenderer::SwapBuffers(const CompositorFrameMetadata
& metadata
) {
2557 DCHECK(!is_backbuffer_discarded_
);
2559 TRACE_EVENT0("cc,benchmark", "GLRenderer::SwapBuffers");
2560 // We're done! Time to swapbuffers!
2562 gfx::Size surface_size
= output_surface_
->SurfaceSize();
2564 CompositorFrame compositor_frame
;
2565 compositor_frame
.metadata
= metadata
;
2566 compositor_frame
.gl_frame_data
= make_scoped_ptr(new GLFrameData
);
2567 compositor_frame
.gl_frame_data
->size
= surface_size
;
2568 if (capabilities_
.using_partial_swap
) {
2569 // If supported, we can save significant bandwidth by only swapping the
2570 // damaged/scissored region (clamped to the viewport).
2571 swap_buffer_rect_
.Intersect(gfx::Rect(surface_size
));
2572 int flipped_y_pos_of_rect_bottom
= surface_size
.height() -
2573 swap_buffer_rect_
.y() -
2574 swap_buffer_rect_
.height();
2575 compositor_frame
.gl_frame_data
->sub_buffer_rect
=
2576 gfx::Rect(swap_buffer_rect_
.x(),
2577 FlippedRootFramebuffer() ? flipped_y_pos_of_rect_bottom
2578 : swap_buffer_rect_
.y(),
2579 swap_buffer_rect_
.width(),
2580 swap_buffer_rect_
.height());
2582 compositor_frame
.gl_frame_data
->sub_buffer_rect
=
2583 gfx::Rect(output_surface_
->SurfaceSize());
2585 output_surface_
->SwapBuffers(&compositor_frame
);
2587 // Release previously used overlay resources and hold onto the pending ones
2588 // until the next swap buffers.
2589 in_use_overlay_resources_
.clear();
2590 in_use_overlay_resources_
.swap(pending_overlay_resources_
);
2592 swap_buffer_rect_
= gfx::Rect();
2595 void GLRenderer::EnforceMemoryPolicy() {
2597 TRACE_EVENT0("cc", "GLRenderer::EnforceMemoryPolicy dropping resources");
2598 ReleaseRenderPassTextures();
2599 DiscardBackbuffer();
2600 resource_provider_
->ReleaseCachedData();
2601 output_surface_
->context_provider()->DeleteCachedResources();
2604 PrepareGeometry(NO_BINDING
);
2607 void GLRenderer::DiscardBackbuffer() {
2608 if (is_backbuffer_discarded_
)
2611 output_surface_
->DiscardBackbuffer();
2613 is_backbuffer_discarded_
= true;
2615 // Damage tracker needs a full reset every time framebuffer is discarded.
2616 client_
->SetFullRootLayerDamage();
2619 void GLRenderer::EnsureBackbuffer() {
2620 if (!is_backbuffer_discarded_
)
2623 output_surface_
->EnsureBackbuffer();
2624 is_backbuffer_discarded_
= false;
2627 void GLRenderer::GetFramebufferPixelsAsync(
2628 const DrawingFrame
* frame
,
2629 const gfx::Rect
& rect
,
2630 scoped_ptr
<CopyOutputRequest
> request
) {
2631 DCHECK(!request
->IsEmpty());
2632 if (request
->IsEmpty())
2637 gfx::Rect window_rect
= MoveFromDrawToWindowSpace(frame
, rect
);
2638 DCHECK_GE(window_rect
.x(), 0);
2639 DCHECK_GE(window_rect
.y(), 0);
2640 DCHECK_LE(window_rect
.right(), current_surface_size_
.width());
2641 DCHECK_LE(window_rect
.bottom(), current_surface_size_
.height());
2643 if (!request
->force_bitmap_result()) {
2644 bool own_mailbox
= !request
->has_texture_mailbox();
2646 GLuint texture_id
= 0;
2647 gpu::Mailbox mailbox
;
2649 gl_
->GenMailboxCHROMIUM(mailbox
.name
);
2650 gl_
->GenTextures(1, &texture_id
);
2651 gl_
->BindTexture(GL_TEXTURE_2D
, texture_id
);
2653 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_LINEAR
);
2654 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAG_FILTER
, GL_LINEAR
);
2655 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
);
2656 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
);
2657 gl_
->ProduceTextureCHROMIUM(GL_TEXTURE_2D
, mailbox
.name
);
2659 mailbox
= request
->texture_mailbox().mailbox();
2660 DCHECK_EQ(static_cast<unsigned>(GL_TEXTURE_2D
),
2661 request
->texture_mailbox().target());
2662 DCHECK(!mailbox
.IsZero());
2663 unsigned incoming_sync_point
= request
->texture_mailbox().sync_point();
2664 if (incoming_sync_point
)
2665 gl_
->WaitSyncPointCHROMIUM(incoming_sync_point
);
2668 gl_
->CreateAndConsumeTextureCHROMIUM(GL_TEXTURE_2D
, mailbox
.name
);
2670 GetFramebufferTexture(texture_id
, RGBA_8888
, window_rect
);
2672 unsigned sync_point
= gl_
->InsertSyncPointCHROMIUM();
2673 TextureMailbox
texture_mailbox(mailbox
, GL_TEXTURE_2D
, sync_point
);
2675 scoped_ptr
<SingleReleaseCallback
> release_callback
;
2677 gl_
->BindTexture(GL_TEXTURE_2D
, 0);
2678 release_callback
= texture_mailbox_deleter_
->GetReleaseCallback(
2679 output_surface_
->context_provider(), texture_id
);
2681 gl_
->DeleteTextures(1, &texture_id
);
2684 request
->SendTextureResult(
2685 window_rect
.size(), texture_mailbox
, release_callback
.Pass());
2689 DCHECK(request
->force_bitmap_result());
2691 scoped_ptr
<PendingAsyncReadPixels
> pending_read(new PendingAsyncReadPixels
);
2692 pending_read
->copy_request
= request
.Pass();
2693 pending_async_read_pixels_
.insert(pending_async_read_pixels_
.begin(),
2694 pending_read
.Pass());
2696 bool do_workaround
= NeedsIOSurfaceReadbackWorkaround();
2698 unsigned temporary_texture
= 0;
2699 unsigned temporary_fbo
= 0;
2701 if (do_workaround
) {
2702 // On Mac OS X, calling glReadPixels() against an FBO whose color attachment
2703 // is an IOSurface-backed texture causes corruption of future glReadPixels()
2704 // calls, even those on different OpenGL contexts. It is believed that this
2705 // is the root cause of top crasher
2706 // http://crbug.com/99393. <rdar://problem/10949687>
2708 gl_
->GenTextures(1, &temporary_texture
);
2709 gl_
->BindTexture(GL_TEXTURE_2D
, temporary_texture
);
2710 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_LINEAR
);
2711 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAG_FILTER
, GL_LINEAR
);
2712 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
);
2713 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
);
2714 // Copy the contents of the current (IOSurface-backed) framebuffer into a
2715 // temporary texture.
2716 GetFramebufferTexture(
2717 temporary_texture
, RGBA_8888
, gfx::Rect(current_surface_size_
));
2718 gl_
->GenFramebuffers(1, &temporary_fbo
);
2719 // Attach this texture to an FBO, and perform the readback from that FBO.
2720 gl_
->BindFramebuffer(GL_FRAMEBUFFER
, temporary_fbo
);
2721 gl_
->FramebufferTexture2D(GL_FRAMEBUFFER
, GL_COLOR_ATTACHMENT0
,
2722 GL_TEXTURE_2D
, temporary_texture
, 0);
2724 DCHECK_EQ(static_cast<unsigned>(GL_FRAMEBUFFER_COMPLETE
),
2725 gl_
->CheckFramebufferStatus(GL_FRAMEBUFFER
));
2729 gl_
->GenBuffers(1, &buffer
);
2730 gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, buffer
);
2731 gl_
->BufferData(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
,
2732 4 * window_rect
.size().GetArea(), NULL
, GL_STREAM_READ
);
2735 gl_
->GenQueriesEXT(1, &query
);
2736 gl_
->BeginQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM
, query
);
2738 gl_
->ReadPixels(window_rect
.x(), window_rect
.y(), window_rect
.width(),
2739 window_rect
.height(), GL_RGBA
, GL_UNSIGNED_BYTE
, NULL
);
2741 gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, 0);
2743 if (do_workaround
) {
2745 gl_
->BindFramebuffer(GL_FRAMEBUFFER
, 0);
2746 gl_
->BindTexture(GL_TEXTURE_2D
, 0);
2747 gl_
->DeleteFramebuffers(1, &temporary_fbo
);
2748 gl_
->DeleteTextures(1, &temporary_texture
);
2751 base::Closure finished_callback
= base::Bind(&GLRenderer::FinishedReadback
,
2752 base::Unretained(this),
2755 window_rect
.size());
2756 // Save the finished_callback so it can be cancelled.
2757 pending_async_read_pixels_
.front()->finished_read_pixels_callback
.Reset(
2759 base::Closure cancelable_callback
=
2760 pending_async_read_pixels_
.front()->
2761 finished_read_pixels_callback
.callback();
2763 // Save the buffer to verify the callbacks happen in the expected order.
2764 pending_async_read_pixels_
.front()->buffer
= buffer
;
2766 gl_
->EndQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM
);
2767 context_support_
->SignalQuery(query
, cancelable_callback
);
2769 EnforceMemoryPolicy();
2772 void GLRenderer::FinishedReadback(unsigned source_buffer
,
2774 const gfx::Size
& size
) {
2775 DCHECK(!pending_async_read_pixels_
.empty());
2778 gl_
->DeleteQueriesEXT(1, &query
);
2781 PendingAsyncReadPixels
* current_read
= pending_async_read_pixels_
.back();
2782 // Make sure we service the readbacks in order.
2783 DCHECK_EQ(source_buffer
, current_read
->buffer
);
2785 uint8
* src_pixels
= NULL
;
2786 scoped_ptr
<SkBitmap
> bitmap
;
2788 if (source_buffer
!= 0) {
2789 gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, source_buffer
);
2790 src_pixels
= static_cast<uint8
*>(gl_
->MapBufferCHROMIUM(
2791 GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, GL_READ_ONLY
));
2794 bitmap
.reset(new SkBitmap
);
2795 bitmap
->allocN32Pixels(size
.width(), size
.height());
2796 scoped_ptr
<SkAutoLockPixels
> lock(new SkAutoLockPixels(*bitmap
));
2797 uint8
* dest_pixels
= static_cast<uint8
*>(bitmap
->getPixels());
2799 size_t row_bytes
= size
.width() * 4;
2800 int num_rows
= size
.height();
2801 size_t total_bytes
= num_rows
* row_bytes
;
2802 for (size_t dest_y
= 0; dest_y
< total_bytes
; dest_y
+= row_bytes
) {
2804 size_t src_y
= total_bytes
- dest_y
- row_bytes
;
2805 // Swizzle OpenGL -> Skia byte order.
2806 for (size_t x
= 0; x
< row_bytes
; x
+= 4) {
2807 dest_pixels
[dest_y
+ x
+ SK_R32_SHIFT
/ 8] =
2808 src_pixels
[src_y
+ x
+ 0];
2809 dest_pixels
[dest_y
+ x
+ SK_G32_SHIFT
/ 8] =
2810 src_pixels
[src_y
+ x
+ 1];
2811 dest_pixels
[dest_y
+ x
+ SK_B32_SHIFT
/ 8] =
2812 src_pixels
[src_y
+ x
+ 2];
2813 dest_pixels
[dest_y
+ x
+ SK_A32_SHIFT
/ 8] =
2814 src_pixels
[src_y
+ x
+ 3];
2818 gl_
->UnmapBufferCHROMIUM(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
);
2820 gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, 0);
2821 gl_
->DeleteBuffers(1, &source_buffer
);
2825 current_read
->copy_request
->SendBitmapResult(bitmap
.Pass());
2826 pending_async_read_pixels_
.pop_back();
2829 void GLRenderer::GetFramebufferTexture(unsigned texture_id
,
2830 ResourceFormat texture_format
,
2831 const gfx::Rect
& window_rect
) {
2833 DCHECK_GE(window_rect
.x(), 0);
2834 DCHECK_GE(window_rect
.y(), 0);
2835 DCHECK_LE(window_rect
.right(), current_surface_size_
.width());
2836 DCHECK_LE(window_rect
.bottom(), current_surface_size_
.height());
2838 gl_
->BindTexture(GL_TEXTURE_2D
, texture_id
);
2839 gl_
->CopyTexImage2D(GL_TEXTURE_2D
, 0, GLDataFormat(texture_format
),
2840 window_rect
.x(), window_rect
.y(), window_rect
.width(),
2841 window_rect
.height(), 0);
2842 gl_
->BindTexture(GL_TEXTURE_2D
, 0);
2845 bool GLRenderer::UseScopedTexture(DrawingFrame
* frame
,
2846 const ScopedResource
* texture
,
2847 const gfx::Rect
& viewport_rect
) {
2848 DCHECK(texture
->id());
2849 frame
->current_render_pass
= NULL
;
2850 frame
->current_texture
= texture
;
2852 return BindFramebufferToTexture(frame
, texture
, viewport_rect
);
2855 void GLRenderer::BindFramebufferToOutputSurface(DrawingFrame
* frame
) {
2856 current_framebuffer_lock_
= nullptr;
2857 output_surface_
->BindFramebuffer();
2859 if (output_surface_
->HasExternalStencilTest()) {
2860 SetStencilEnabled(true);
2861 gl_
->StencilFunc(GL_EQUAL
, 1, 1);
2863 SetStencilEnabled(false);
2867 bool GLRenderer::BindFramebufferToTexture(DrawingFrame
* frame
,
2868 const ScopedResource
* texture
,
2869 const gfx::Rect
& target_rect
) {
2870 DCHECK(texture
->id());
2872 // Explicitly release lock, otherwise we can crash when try to lock
2873 // same texture again.
2874 current_framebuffer_lock_
= nullptr;
2876 SetStencilEnabled(false);
2877 gl_
->BindFramebuffer(GL_FRAMEBUFFER
, offscreen_framebuffer_id_
);
2878 current_framebuffer_lock_
=
2879 make_scoped_ptr(new ResourceProvider::ScopedWriteLockGL(
2880 resource_provider_
, texture
->id()));
2881 unsigned texture_id
= current_framebuffer_lock_
->texture_id();
2882 gl_
->FramebufferTexture2D(GL_FRAMEBUFFER
, GL_COLOR_ATTACHMENT0
, GL_TEXTURE_2D
,
2885 DCHECK(gl_
->CheckFramebufferStatus(GL_FRAMEBUFFER
) ==
2886 GL_FRAMEBUFFER_COMPLETE
||
2891 void GLRenderer::SetScissorTestRect(const gfx::Rect
& scissor_rect
) {
2892 EnsureScissorTestEnabled();
2894 // Don't unnecessarily ask the context to change the scissor, because it
2895 // may cause undesired GPU pipeline flushes.
2896 if (scissor_rect
== scissor_rect_
&& !scissor_rect_needs_reset_
)
2899 scissor_rect_
= scissor_rect
;
2900 FlushTextureQuadCache(SHARED_BINDING
);
2901 gl_
->Scissor(scissor_rect
.x(), scissor_rect
.y(), scissor_rect
.width(),
2902 scissor_rect
.height());
2904 scissor_rect_needs_reset_
= false;
2907 void GLRenderer::SetViewport() {
2908 gl_
->Viewport(current_window_space_viewport_
.x(),
2909 current_window_space_viewport_
.y(),
2910 current_window_space_viewport_
.width(),
2911 current_window_space_viewport_
.height());
2914 void GLRenderer::InitializeSharedObjects() {
2915 TRACE_EVENT0("cc", "GLRenderer::InitializeSharedObjects");
2917 // Create an FBO for doing offscreen rendering.
2918 gl_
->GenFramebuffers(1, &offscreen_framebuffer_id_
);
2921 make_scoped_ptr(new StaticGeometryBinding(gl_
, QuadVertexRect()));
2922 clipped_geometry_
= make_scoped_ptr(new DynamicGeometryBinding(gl_
));
2925 void GLRenderer::PrepareGeometry(BoundGeometry binding
) {
2926 if (binding
== bound_geometry_
) {
2931 case SHARED_BINDING
:
2932 shared_geometry_
->PrepareForDraw();
2934 case CLIPPED_BINDING
:
2935 clipped_geometry_
->PrepareForDraw();
2940 bound_geometry_
= binding
;
2943 const GLRenderer::TileCheckerboardProgram
*
2944 GLRenderer::GetTileCheckerboardProgram() {
2945 if (!tile_checkerboard_program_
.initialized()) {
2946 TRACE_EVENT0("cc", "GLRenderer::checkerboardProgram::initalize");
2947 tile_checkerboard_program_
.Initialize(output_surface_
->context_provider(),
2948 TEX_COORD_PRECISION_NA
,
2951 return &tile_checkerboard_program_
;
2954 const GLRenderer::DebugBorderProgram
* GLRenderer::GetDebugBorderProgram() {
2955 if (!debug_border_program_
.initialized()) {
2956 TRACE_EVENT0("cc", "GLRenderer::debugBorderProgram::initialize");
2957 debug_border_program_
.Initialize(output_surface_
->context_provider(),
2958 TEX_COORD_PRECISION_NA
, SAMPLER_TYPE_NA
);
2960 return &debug_border_program_
;
2963 const GLRenderer::SolidColorProgram
* GLRenderer::GetSolidColorProgram() {
2964 if (!solid_color_program_
.initialized()) {
2965 TRACE_EVENT0("cc", "GLRenderer::solidColorProgram::initialize");
2966 solid_color_program_
.Initialize(output_surface_
->context_provider(),
2967 TEX_COORD_PRECISION_NA
, SAMPLER_TYPE_NA
);
2969 return &solid_color_program_
;
2972 const GLRenderer::SolidColorProgramAA
* GLRenderer::GetSolidColorProgramAA() {
2973 if (!solid_color_program_aa_
.initialized()) {
2974 TRACE_EVENT0("cc", "GLRenderer::solidColorProgramAA::initialize");
2975 solid_color_program_aa_
.Initialize(output_surface_
->context_provider(),
2976 TEX_COORD_PRECISION_NA
, SAMPLER_TYPE_NA
);
2978 return &solid_color_program_aa_
;
2981 const GLRenderer::RenderPassProgram
* GLRenderer::GetRenderPassProgram(
2982 TexCoordPrecision precision
,
2983 BlendMode blend_mode
) {
2984 DCHECK_GE(precision
, 0);
2985 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
2986 DCHECK_GE(blend_mode
, 0);
2987 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
2988 RenderPassProgram
* program
= &render_pass_program_
[precision
][blend_mode
];
2989 if (!program
->initialized()) {
2990 TRACE_EVENT0("cc", "GLRenderer::renderPassProgram::initialize");
2991 program
->Initialize(output_surface_
->context_provider(), precision
,
2992 SAMPLER_TYPE_2D
, blend_mode
);
2997 const GLRenderer::RenderPassProgramAA
* GLRenderer::GetRenderPassProgramAA(
2998 TexCoordPrecision precision
,
2999 BlendMode blend_mode
) {
3000 DCHECK_GE(precision
, 0);
3001 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3002 DCHECK_GE(blend_mode
, 0);
3003 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3004 RenderPassProgramAA
* program
=
3005 &render_pass_program_aa_
[precision
][blend_mode
];
3006 if (!program
->initialized()) {
3007 TRACE_EVENT0("cc", "GLRenderer::renderPassProgramAA::initialize");
3008 program
->Initialize(output_surface_
->context_provider(), precision
,
3009 SAMPLER_TYPE_2D
, blend_mode
);
3014 const GLRenderer::RenderPassMaskProgram
* GLRenderer::GetRenderPassMaskProgram(
3015 TexCoordPrecision precision
,
3016 SamplerType sampler
,
3017 BlendMode blend_mode
,
3018 bool mask_for_background
) {
3019 DCHECK_GE(precision
, 0);
3020 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3021 DCHECK_GE(sampler
, 0);
3022 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3023 DCHECK_GE(blend_mode
, 0);
3024 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3025 RenderPassMaskProgram
* program
=
3026 &render_pass_mask_program_
[precision
][sampler
][blend_mode
]
3027 [mask_for_background
? HAS_MASK
: NO_MASK
];
3028 if (!program
->initialized()) {
3029 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgram::initialize");
3030 program
->Initialize(
3031 output_surface_
->context_provider(), precision
,
3032 sampler
, blend_mode
, mask_for_background
);
3037 const GLRenderer::RenderPassMaskProgramAA
*
3038 GLRenderer::GetRenderPassMaskProgramAA(TexCoordPrecision precision
,
3039 SamplerType sampler
,
3040 BlendMode blend_mode
,
3041 bool mask_for_background
) {
3042 DCHECK_GE(precision
, 0);
3043 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3044 DCHECK_GE(sampler
, 0);
3045 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3046 DCHECK_GE(blend_mode
, 0);
3047 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3048 RenderPassMaskProgramAA
* program
=
3049 &render_pass_mask_program_aa_
[precision
][sampler
][blend_mode
]
3050 [mask_for_background
? HAS_MASK
: NO_MASK
];
3051 if (!program
->initialized()) {
3052 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgramAA::initialize");
3053 program
->Initialize(
3054 output_surface_
->context_provider(), precision
,
3055 sampler
, blend_mode
, mask_for_background
);
3060 const GLRenderer::RenderPassColorMatrixProgram
*
3061 GLRenderer::GetRenderPassColorMatrixProgram(TexCoordPrecision precision
,
3062 BlendMode blend_mode
) {
3063 DCHECK_GE(precision
, 0);
3064 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3065 DCHECK_GE(blend_mode
, 0);
3066 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3067 RenderPassColorMatrixProgram
* program
=
3068 &render_pass_color_matrix_program_
[precision
][blend_mode
];
3069 if (!program
->initialized()) {
3070 TRACE_EVENT0("cc", "GLRenderer::renderPassColorMatrixProgram::initialize");
3071 program
->Initialize(output_surface_
->context_provider(), precision
,
3072 SAMPLER_TYPE_2D
, blend_mode
);
3077 const GLRenderer::RenderPassColorMatrixProgramAA
*
3078 GLRenderer::GetRenderPassColorMatrixProgramAA(TexCoordPrecision precision
,
3079 BlendMode blend_mode
) {
3080 DCHECK_GE(precision
, 0);
3081 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3082 DCHECK_GE(blend_mode
, 0);
3083 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3084 RenderPassColorMatrixProgramAA
* program
=
3085 &render_pass_color_matrix_program_aa_
[precision
][blend_mode
];
3086 if (!program
->initialized()) {
3088 "GLRenderer::renderPassColorMatrixProgramAA::initialize");
3089 program
->Initialize(output_surface_
->context_provider(), precision
,
3090 SAMPLER_TYPE_2D
, blend_mode
);
3095 const GLRenderer::RenderPassMaskColorMatrixProgram
*
3096 GLRenderer::GetRenderPassMaskColorMatrixProgram(
3097 TexCoordPrecision precision
,
3098 SamplerType sampler
,
3099 BlendMode blend_mode
,
3100 bool mask_for_background
) {
3101 DCHECK_GE(precision
, 0);
3102 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3103 DCHECK_GE(sampler
, 0);
3104 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3105 DCHECK_GE(blend_mode
, 0);
3106 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3107 RenderPassMaskColorMatrixProgram
* program
=
3108 &render_pass_mask_color_matrix_program_
[precision
][sampler
][blend_mode
]
3109 [mask_for_background
? HAS_MASK
: NO_MASK
];
3110 if (!program
->initialized()) {
3112 "GLRenderer::renderPassMaskColorMatrixProgram::initialize");
3113 program
->Initialize(
3114 output_surface_
->context_provider(), precision
,
3115 sampler
, blend_mode
, mask_for_background
);
3120 const GLRenderer::RenderPassMaskColorMatrixProgramAA
*
3121 GLRenderer::GetRenderPassMaskColorMatrixProgramAA(
3122 TexCoordPrecision precision
,
3123 SamplerType sampler
,
3124 BlendMode blend_mode
,
3125 bool mask_for_background
) {
3126 DCHECK_GE(precision
, 0);
3127 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3128 DCHECK_GE(sampler
, 0);
3129 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3130 DCHECK_GE(blend_mode
, 0);
3131 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3132 RenderPassMaskColorMatrixProgramAA
* program
=
3133 &render_pass_mask_color_matrix_program_aa_
[precision
][sampler
][blend_mode
]
3134 [mask_for_background
? HAS_MASK
: NO_MASK
];
3135 if (!program
->initialized()) {
3137 "GLRenderer::renderPassMaskColorMatrixProgramAA::initialize");
3138 program
->Initialize(
3139 output_surface_
->context_provider(), precision
,
3140 sampler
, blend_mode
, mask_for_background
);
3145 const GLRenderer::TileProgram
* GLRenderer::GetTileProgram(
3146 TexCoordPrecision precision
,
3147 SamplerType sampler
) {
3148 DCHECK_GE(precision
, 0);
3149 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3150 DCHECK_GE(sampler
, 0);
3151 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3152 TileProgram
* program
= &tile_program_
[precision
][sampler
];
3153 if (!program
->initialized()) {
3154 TRACE_EVENT0("cc", "GLRenderer::tileProgram::initialize");
3155 program
->Initialize(
3156 output_surface_
->context_provider(), precision
, sampler
);
3161 const GLRenderer::TileProgramOpaque
* GLRenderer::GetTileProgramOpaque(
3162 TexCoordPrecision precision
,
3163 SamplerType sampler
) {
3164 DCHECK_GE(precision
, 0);
3165 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3166 DCHECK_GE(sampler
, 0);
3167 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3168 TileProgramOpaque
* program
= &tile_program_opaque_
[precision
][sampler
];
3169 if (!program
->initialized()) {
3170 TRACE_EVENT0("cc", "GLRenderer::tileProgramOpaque::initialize");
3171 program
->Initialize(
3172 output_surface_
->context_provider(), precision
, sampler
);
3177 const GLRenderer::TileProgramAA
* GLRenderer::GetTileProgramAA(
3178 TexCoordPrecision precision
,
3179 SamplerType sampler
) {
3180 DCHECK_GE(precision
, 0);
3181 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3182 DCHECK_GE(sampler
, 0);
3183 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3184 TileProgramAA
* program
= &tile_program_aa_
[precision
][sampler
];
3185 if (!program
->initialized()) {
3186 TRACE_EVENT0("cc", "GLRenderer::tileProgramAA::initialize");
3187 program
->Initialize(
3188 output_surface_
->context_provider(), precision
, sampler
);
3193 const GLRenderer::TileProgramSwizzle
* GLRenderer::GetTileProgramSwizzle(
3194 TexCoordPrecision precision
,
3195 SamplerType sampler
) {
3196 DCHECK_GE(precision
, 0);
3197 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3198 DCHECK_GE(sampler
, 0);
3199 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3200 TileProgramSwizzle
* program
= &tile_program_swizzle_
[precision
][sampler
];
3201 if (!program
->initialized()) {
3202 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzle::initialize");
3203 program
->Initialize(
3204 output_surface_
->context_provider(), precision
, sampler
);
3209 const GLRenderer::TileProgramSwizzleOpaque
*
3210 GLRenderer::GetTileProgramSwizzleOpaque(TexCoordPrecision precision
,
3211 SamplerType sampler
) {
3212 DCHECK_GE(precision
, 0);
3213 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3214 DCHECK_GE(sampler
, 0);
3215 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3216 TileProgramSwizzleOpaque
* program
=
3217 &tile_program_swizzle_opaque_
[precision
][sampler
];
3218 if (!program
->initialized()) {
3219 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleOpaque::initialize");
3220 program
->Initialize(
3221 output_surface_
->context_provider(), precision
, sampler
);
3226 const GLRenderer::TileProgramSwizzleAA
* GLRenderer::GetTileProgramSwizzleAA(
3227 TexCoordPrecision precision
,
3228 SamplerType sampler
) {
3229 DCHECK_GE(precision
, 0);
3230 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3231 DCHECK_GE(sampler
, 0);
3232 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3233 TileProgramSwizzleAA
* program
= &tile_program_swizzle_aa_
[precision
][sampler
];
3234 if (!program
->initialized()) {
3235 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleAA::initialize");
3236 program
->Initialize(
3237 output_surface_
->context_provider(), precision
, sampler
);
3242 const GLRenderer::TextureProgram
* GLRenderer::GetTextureProgram(
3243 TexCoordPrecision precision
,
3244 SamplerType sampler
) {
3245 DCHECK_GE(precision
, 0);
3246 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3247 DCHECK_GE(sampler
, 0);
3248 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3249 TextureProgram
* program
= &texture_program_
[precision
][sampler
];
3250 if (!program
->initialized()) {
3251 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3252 program
->Initialize(output_surface_
->context_provider(), precision
,
3258 const GLRenderer::NonPremultipliedTextureProgram
*
3259 GLRenderer::GetNonPremultipliedTextureProgram(TexCoordPrecision precision
,
3260 SamplerType sampler
) {
3261 DCHECK_GE(precision
, 0);
3262 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3263 DCHECK_GE(sampler
, 0);
3264 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3265 NonPremultipliedTextureProgram
* program
=
3266 &nonpremultiplied_texture_program_
[precision
][sampler
];
3267 if (!program
->initialized()) {
3269 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3270 program
->Initialize(output_surface_
->context_provider(), precision
,
3276 const GLRenderer::TextureBackgroundProgram
*
3277 GLRenderer::GetTextureBackgroundProgram(TexCoordPrecision precision
,
3278 SamplerType sampler
) {
3279 DCHECK_GE(precision
, 0);
3280 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3281 DCHECK_GE(sampler
, 0);
3282 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3283 TextureBackgroundProgram
* program
=
3284 &texture_background_program_
[precision
][sampler
];
3285 if (!program
->initialized()) {
3286 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3287 program
->Initialize(output_surface_
->context_provider(), precision
,
3293 const GLRenderer::NonPremultipliedTextureBackgroundProgram
*
3294 GLRenderer::GetNonPremultipliedTextureBackgroundProgram(
3295 TexCoordPrecision precision
,
3296 SamplerType sampler
) {
3297 DCHECK_GE(precision
, 0);
3298 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3299 DCHECK_GE(sampler
, 0);
3300 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3301 NonPremultipliedTextureBackgroundProgram
* program
=
3302 &nonpremultiplied_texture_background_program_
[precision
][sampler
];
3303 if (!program
->initialized()) {
3305 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3306 program
->Initialize(output_surface_
->context_provider(), precision
,
3312 const GLRenderer::TextureProgram
* GLRenderer::GetTextureIOSurfaceProgram(
3313 TexCoordPrecision precision
) {
3314 DCHECK_GE(precision
, 0);
3315 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3316 TextureProgram
* program
= &texture_io_surface_program_
[precision
];
3317 if (!program
->initialized()) {
3318 TRACE_EVENT0("cc", "GLRenderer::textureIOSurfaceProgram::initialize");
3319 program
->Initialize(output_surface_
->context_provider(), precision
,
3320 SAMPLER_TYPE_2D_RECT
);
3325 const GLRenderer::VideoYUVProgram
* GLRenderer::GetVideoYUVProgram(
3326 TexCoordPrecision precision
,
3327 SamplerType sampler
) {
3328 DCHECK_GE(precision
, 0);
3329 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3330 DCHECK_GE(sampler
, 0);
3331 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3332 VideoYUVProgram
* program
= &video_yuv_program_
[precision
][sampler
];
3333 if (!program
->initialized()) {
3334 TRACE_EVENT0("cc", "GLRenderer::videoYUVProgram::initialize");
3335 program
->Initialize(output_surface_
->context_provider(), precision
,
3341 const GLRenderer::VideoYUVAProgram
* GLRenderer::GetVideoYUVAProgram(
3342 TexCoordPrecision precision
,
3343 SamplerType sampler
) {
3344 DCHECK_GE(precision
, 0);
3345 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3346 DCHECK_GE(sampler
, 0);
3347 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3348 VideoYUVAProgram
* program
= &video_yuva_program_
[precision
][sampler
];
3349 if (!program
->initialized()) {
3350 TRACE_EVENT0("cc", "GLRenderer::videoYUVAProgram::initialize");
3351 program
->Initialize(output_surface_
->context_provider(), precision
,
3357 const GLRenderer::VideoStreamTextureProgram
*
3358 GLRenderer::GetVideoStreamTextureProgram(TexCoordPrecision precision
) {
3359 if (!Capabilities().using_egl_image
)
3361 DCHECK_GE(precision
, 0);
3362 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3363 VideoStreamTextureProgram
* program
=
3364 &video_stream_texture_program_
[precision
];
3365 if (!program
->initialized()) {
3366 TRACE_EVENT0("cc", "GLRenderer::streamTextureProgram::initialize");
3367 program
->Initialize(output_surface_
->context_provider(), precision
,
3368 SAMPLER_TYPE_EXTERNAL_OES
);
3373 void GLRenderer::CleanupSharedObjects() {
3374 shared_geometry_
= nullptr;
3376 for (int i
= 0; i
<= LAST_TEX_COORD_PRECISION
; ++i
) {
3377 for (int j
= 0; j
<= LAST_SAMPLER_TYPE
; ++j
) {
3378 tile_program_
[i
][j
].Cleanup(gl_
);
3379 tile_program_opaque_
[i
][j
].Cleanup(gl_
);
3380 tile_program_swizzle_
[i
][j
].Cleanup(gl_
);
3381 tile_program_swizzle_opaque_
[i
][j
].Cleanup(gl_
);
3382 tile_program_aa_
[i
][j
].Cleanup(gl_
);
3383 tile_program_swizzle_aa_
[i
][j
].Cleanup(gl_
);
3385 for (int k
= 0; k
<= LAST_BLEND_MODE
; k
++) {
3386 for (int l
= 0; l
<= LAST_MASK_VALUE
; ++l
) {
3387 render_pass_mask_program_
[i
][j
][k
][l
].Cleanup(gl_
);
3388 render_pass_mask_program_aa_
[i
][j
][k
][l
].Cleanup(gl_
);
3389 render_pass_mask_color_matrix_program_aa_
[i
][j
][k
][l
].Cleanup(gl_
);
3390 render_pass_mask_color_matrix_program_
[i
][j
][k
][l
].Cleanup(gl_
);
3394 video_yuv_program_
[i
][j
].Cleanup(gl_
);
3395 video_yuva_program_
[i
][j
].Cleanup(gl_
);
3397 for (int j
= 0; j
<= LAST_BLEND_MODE
; j
++) {
3398 render_pass_program_
[i
][j
].Cleanup(gl_
);
3399 render_pass_program_aa_
[i
][j
].Cleanup(gl_
);
3400 render_pass_color_matrix_program_
[i
][j
].Cleanup(gl_
);
3401 render_pass_color_matrix_program_aa_
[i
][j
].Cleanup(gl_
);
3404 for (int j
= 0; j
<= LAST_SAMPLER_TYPE
; ++j
) {
3405 texture_program_
[i
][j
].Cleanup(gl_
);
3406 nonpremultiplied_texture_program_
[i
][j
].Cleanup(gl_
);
3407 texture_background_program_
[i
][j
].Cleanup(gl_
);
3408 nonpremultiplied_texture_background_program_
[i
][j
].Cleanup(gl_
);
3410 texture_io_surface_program_
[i
].Cleanup(gl_
);
3412 video_stream_texture_program_
[i
].Cleanup(gl_
);
3415 tile_checkerboard_program_
.Cleanup(gl_
);
3417 debug_border_program_
.Cleanup(gl_
);
3418 solid_color_program_
.Cleanup(gl_
);
3419 solid_color_program_aa_
.Cleanup(gl_
);
3421 if (offscreen_framebuffer_id_
)
3422 gl_
->DeleteFramebuffers(1, &offscreen_framebuffer_id_
);
3424 if (on_demand_tile_raster_resource_id_
)
3425 resource_provider_
->DeleteResource(on_demand_tile_raster_resource_id_
);
3427 ReleaseRenderPassTextures();
3430 void GLRenderer::ReinitializeGLState() {
3431 is_scissor_enabled_
= false;
3432 scissor_rect_needs_reset_
= true;
3433 stencil_shadow_
= false;
3434 blend_shadow_
= true;
3435 program_shadow_
= 0;
3440 void GLRenderer::RestoreGLState() {
3441 // This restores the current GLRenderer state to the GL context.
3442 bound_geometry_
= NO_BINDING
;
3443 PrepareGeometry(SHARED_BINDING
);
3445 gl_
->Disable(GL_DEPTH_TEST
);
3446 gl_
->Disable(GL_CULL_FACE
);
3447 gl_
->ColorMask(true, true, true, true);
3448 gl_
->BlendFunc(GL_ONE
, GL_ONE_MINUS_SRC_ALPHA
);
3449 gl_
->ActiveTexture(GL_TEXTURE0
);
3451 if (program_shadow_
)
3452 gl_
->UseProgram(program_shadow_
);
3454 if (stencil_shadow_
)
3455 gl_
->Enable(GL_STENCIL_TEST
);
3457 gl_
->Disable(GL_STENCIL_TEST
);
3460 gl_
->Enable(GL_BLEND
);
3462 gl_
->Disable(GL_BLEND
);
3464 if (is_scissor_enabled_
) {
3465 gl_
->Enable(GL_SCISSOR_TEST
);
3466 gl_
->Scissor(scissor_rect_
.x(), scissor_rect_
.y(), scissor_rect_
.width(),
3467 scissor_rect_
.height());
3469 gl_
->Disable(GL_SCISSOR_TEST
);
3473 void GLRenderer::RestoreFramebuffer(DrawingFrame
* frame
) {
3474 UseRenderPass(frame
, frame
->current_render_pass
);
3476 // Call SetViewport directly, rather than through PrepareSurfaceForPass.
3477 // PrepareSurfaceForPass also clears the surface, which is not desired when
3482 bool GLRenderer::IsContextLost() {
3483 return output_surface_
->context_provider()->IsContextLost();
3486 void GLRenderer::ScheduleOverlays(DrawingFrame
* frame
) {
3487 if (!frame
->overlay_list
.size())
3490 ResourceProvider::ResourceIdArray resources
;
3491 OverlayCandidateList
& overlays
= frame
->overlay_list
;
3492 for (const OverlayCandidate
& overlay
: overlays
) {
3493 // Skip primary plane.
3494 if (overlay
.plane_z_order
== 0)
3497 pending_overlay_resources_
.push_back(
3498 make_scoped_ptr(new ResourceProvider::ScopedReadLockGL(
3499 resource_provider_
, overlay
.resource_id
)));
3501 context_support_
->ScheduleOverlayPlane(
3502 overlay
.plane_z_order
,
3504 pending_overlay_resources_
.back()->texture_id(),
3505 ToNearestRect(overlay
.display_rect
),