[chromium] Make CCThreadProxy draw
[WebKit-https.git] / Source / WebCore / platform / graphics / chromium / LayerRendererChromium.cpp
1 /*
2  * Copyright (C) 2010 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31
32 #include "config.h"
33
34 #if USE(ACCELERATED_COMPOSITING)
35 #include "LayerRendererChromium.h"
36
37 #include "Canvas2DLayerChromium.h"
38 #include "Extensions3DChromium.h"
39 #include "FloatQuad.h"
40 #include "GeometryBinding.h"
41 #include "GraphicsContext3D.h"
42 #include "LayerChromium.h"
43 #include "LayerPainterChromium.h"
44 #include "ManagedTexture.h"
45 #include "LayerTextureUpdaterCanvas.h"
46 #include "NonCompositedContentHost.h"
47 #include "NotImplemented.h"
48 #include "PlatformColor.h"
49 #include "RenderSurfaceChromium.h"
50 #include "TextStream.h"
51 #include "TextureManager.h"
52 #include "TreeSynchronizer.h"
53 #include "TraceEvent.h"
54 #include "WebGLLayerChromium.h"
55 #include "cc/CCLayerImpl.h"
56 #include "cc/CCLayerTreeHostCommon.h"
57 #include "cc/CCMainThreadTask.h"
58 #if USE(SKIA)
59 #include "Extensions3D.h"
60 #include "GrContext.h"
61 #include "NativeImageSkia.h"
62 #include "PlatformContextSkia.h"
63 #elif USE(CG)
64 #include <CoreGraphics/CGBitmapContext.h>
65 #endif
66 #include <wtf/CurrentTime.h>
67 #include <wtf/MainThread.h>
68
69 using namespace std;
70
71 namespace WebCore {
72
73 namespace {
74
75 static TransformationMatrix orthoMatrix(float left, float right, float bottom, float top)
76 {
77     float deltaX = right - left;
78     float deltaY = top - bottom;
79     TransformationMatrix ortho;
80     if (!deltaX || !deltaY)
81         return ortho;
82     ortho.setM11(2.0f / deltaX);
83     ortho.setM41(-(right + left) / deltaX);
84     ortho.setM22(2.0f / deltaY);
85     ortho.setM42(-(top + bottom) / deltaY);
86
87     // Z component of vertices is always set to zero as we don't use the depth buffer
88     // while drawing.
89     ortho.setM33(0);
90
91     return ortho;
92 }
93
94 static TransformationMatrix screenMatrix(int x, int y, int width, int height)
95 {
96     TransformationMatrix screen;
97
98     // Map to viewport.
99     screen.translate3d(x, y, 0);
100     screen.scale3d(width, height, 0);
101
102     // Map x, y and z to unit square.
103     screen.translate3d(0.5, 0.5, 0.5);
104     screen.scale3d(0.5, 0.5, 0.5);
105
106     return screen;
107 }
108
109 #if USE(SKIA)
110 bool contextSupportsAcceleratedPainting(GraphicsContext3D* context)
111 {
112     WebCore::Extensions3D* extensions = context->getExtensions();
113     if (extensions->supports("GL_EXT_texture_format_BGRA8888"))
114         extensions->ensureEnabled("GL_EXT_texture_format_BGRA8888");
115     else
116         return false;
117
118     if (extensions->supports("GL_EXT_read_format_bgra"))
119         extensions->ensureEnabled("GL_EXT_read_format_bgra");
120     else
121         return false;
122
123     if (!context->grContext())
124         return false;
125
126     return true;
127 }
128 #endif
129
130 } // anonymous namespace
131
132 PassOwnPtr<LayerRendererChromium> LayerRendererChromium::create(CCLayerTreeHostImpl* owner, PassRefPtr<GraphicsContext3D> context)
133 {
134 #if USE(SKIA)
135     if (owner->settings().acceleratePainting && !contextSupportsAcceleratedPainting(context.get()))
136         return nullptr;
137 #endif
138     OwnPtr<LayerRendererChromium> layerRenderer(adoptPtr(new LayerRendererChromium(owner, context)));
139     if (!layerRenderer->initialize())
140         return nullptr;
141
142     return layerRenderer.release();
143 }
144
145 LayerRendererChromium::LayerRendererChromium(CCLayerTreeHostImpl* owner,
146                                              PassRefPtr<GraphicsContext3D> context)
147     : m_owner(owner)
148     , m_currentRenderSurface(0)
149     , m_offscreenFramebufferId(0)
150     , m_zoomAnimatorScale(1)
151     , m_contentsTextureMemoryUseBytes(0)
152     , m_context(context)
153     , m_defaultRenderSurface(0)
154     , m_sharedGeometryQuad(FloatRect(-0.5f, -0.5f, 1.0f, 1.0f))
155 {
156 }
157
158 bool LayerRendererChromium::initialize()
159 {
160     m_context->makeContextCurrent();
161     if (settings().acceleratePainting) {
162         m_capabilities.usingAcceleratedPainting = true;
163     }
164
165     WebCore::Extensions3D* extensions = m_context->getExtensions();
166     m_capabilities.usingMapSub = extensions->supports("GL_CHROMIUM_map_sub");
167     if (m_capabilities.usingMapSub)
168         extensions->ensureEnabled("GL_CHROMIUM_map_sub");
169
170     GLC(m_context.get(), m_context->getIntegerv(GraphicsContext3D::MAX_TEXTURE_SIZE, &m_capabilities.maxTextureSize));
171     m_capabilities.bestTextureFormat = PlatformColor::bestTextureFormat(m_context.get());
172
173     if (!initializeSharedObjects())
174         return false;
175
176     m_headsUpDisplay = CCHeadsUpDisplay::create(this);
177
178     // Make sure the viewport and context gets initialized, even if it is to zero.
179     viewportChanged();
180     return true;
181 }
182
183 LayerRendererChromium::~LayerRendererChromium()
184 {
185     ASSERT(CCProxy::isMainThread());
186     m_headsUpDisplay.clear(); // Explicitly destroy the HUD before the TextureManager dies.
187     cleanupSharedObjects();
188 }
189
190 void LayerRendererChromium::clearRenderSurfacesOnCCLayerImplRecursive(CCLayerImpl* layer)
191 {
192     for (size_t i = 0; i < layer->children().size(); ++i)
193         clearRenderSurfacesOnCCLayerImplRecursive(layer->children()[i].get());
194     layer->clearRenderSurface();
195 }
196
197 void LayerRendererChromium::close()
198 {
199     if (rootLayer())
200         clearRenderSurfacesOnCCLayerImplRecursive(rootLayer());
201 }
202
203 GraphicsContext3D* LayerRendererChromium::context()
204 {
205     return m_context.get();
206 }
207
208 void LayerRendererChromium::debugGLCall(GraphicsContext3D* context, const char* command, const char* file, int line)
209 {
210     unsigned long error = context->getError();
211     if (error != GraphicsContext3D::NO_ERROR)
212         LOG_ERROR("GL command failed: File: %s\n\tLine %d\n\tcommand: %s, error %x\n", file, line, command, static_cast<int>(error));
213 }
214
215 void LayerRendererChromium::releaseRenderSurfaceTextures()
216 {
217     m_renderSurfaceTextureManager->evictAndDeleteAllTextures(m_context.get());
218 }
219
220 void LayerRendererChromium::viewportChanged()
221 {
222     if (m_context)
223         m_context->reshape(std::max(1, viewportWidth()), std::max(1, viewportHeight()));
224
225     // Reset the current render surface to force an update of the viewport and
226     // projection matrix next time useRenderSurface is called.
227     m_currentRenderSurface = 0;
228 }
229
230 void LayerRendererChromium::drawLayers()
231 {
232     // FIXME: use the frame begin time from the overall compositor scheduler.
233     // This value is currently inaccessible because it is up in Chromium's
234     // RenderWidget.
235     m_headsUpDisplay->onFrameBegin(currentTime());
236
237     if (!rootLayer())
238         return;
239
240     m_renderSurfaceTextureManager->setMemoryLimitBytes(TextureManager::highLimitBytes() - m_contentsTextureMemoryUseBytes);
241     drawLayersInternal();
242
243     if (TextureManager::reclaimLimitBytes() > m_contentsTextureMemoryUseBytes)
244         m_renderSurfaceTextureManager->reduceMemoryToLimit(TextureManager::reclaimLimitBytes() - m_contentsTextureMemoryUseBytes);
245     else
246         m_renderSurfaceTextureManager->reduceMemoryToLimit(0);
247     m_renderSurfaceTextureManager->deleteEvictedTextures(m_context.get());
248
249     if (settings().compositeOffscreen)
250         copyOffscreenTextureToDisplay();
251 }
252
253 void LayerRendererChromium::drawLayersInternal()
254 {
255     if (viewportSize().isEmpty() || !rootLayer())
256         return;
257
258     TRACE_EVENT("LayerRendererChromium::drawLayers", this, 0);
259     CCLayerImpl* rootDrawLayer = rootLayer();
260     makeContextCurrent();
261
262     if (!rootDrawLayer->renderSurface())
263         rootDrawLayer->createRenderSurface();
264     rootDrawLayer->renderSurface()->setContentRect(IntRect(IntPoint(), viewportSize()));
265
266     rootDrawLayer->setScissorRect(IntRect(IntPoint(), viewportSize()));
267
268     CCLayerList renderSurfaceLayerList;
269     renderSurfaceLayerList.append(rootDrawLayer);
270
271     TransformationMatrix zoomMatrix;
272     zoomMatrix.scale3d(m_zoomAnimatorScale, m_zoomAnimatorScale, 1);
273     m_defaultRenderSurface = rootDrawLayer->renderSurface();
274     m_defaultRenderSurface->clearLayerList();
275
276     {
277         TRACE_EVENT("LayerRendererChromium::drawLayersInternal::calcDrawEtc", this, 0);
278         CCLayerTreeHostCommon::calculateDrawTransformsAndVisibility(rootDrawLayer, rootDrawLayer, zoomMatrix, zoomMatrix, renderSurfaceLayerList, m_defaultRenderSurface->layerList(), &m_layerSorter, m_capabilities.maxTextureSize);
279     }
280
281     // The GL viewport covers the entire visible area, including the scrollbars.
282     GLC(m_context.get(), m_context->viewport(0, 0, viewportWidth(), viewportHeight()));
283     m_windowMatrix = screenMatrix(0, 0, viewportWidth(), viewportHeight());
284
285     // Bind the common vertex attributes used for drawing all the layers.
286     m_sharedGeometry->prepareForDraw();
287
288     GLC(m_context.get(), m_context->disable(GraphicsContext3D::SCISSOR_TEST));
289     GLC(m_context.get(), m_context->disable(GraphicsContext3D::DEPTH_TEST));
290     GLC(m_context.get(), m_context->disable(GraphicsContext3D::CULL_FACE));
291
292     useRenderSurface(m_defaultRenderSurface);
293
294     // Clear to blue to make it easier to spot unrendered regions.
295     m_context->clearColor(0, 0, 1, 1);
296     m_context->colorMask(true, true, true, true);
297     m_context->clear(GraphicsContext3D::COLOR_BUFFER_BIT);
298
299     GLC(m_context.get(), m_context->enable(GraphicsContext3D::BLEND));
300     GLC(m_context.get(), m_context->blendFunc(GraphicsContext3D::ONE, GraphicsContext3D::ONE_MINUS_SRC_ALPHA));
301     GLC(m_context.get(), m_context->enable(GraphicsContext3D::SCISSOR_TEST));
302
303     // Update the contents of the render surfaces. We traverse the array from
304     // back to front to guarantee that nested render surfaces get rendered in the
305     // correct order.
306     for (int surfaceIndex = renderSurfaceLayerList.size() - 1; surfaceIndex >= 0 ; --surfaceIndex) {
307         CCLayerImpl* renderSurfaceLayer = renderSurfaceLayerList[surfaceIndex].get();
308         CCRenderSurface* renderSurface = renderSurfaceLayer->renderSurface();
309         ASSERT(renderSurface);
310
311         renderSurface->setSkipsDraw(true);
312
313         // Render surfaces whose drawable area has zero width or height
314         // will have no layers associated with them and should be skipped.
315         if (!renderSurface->layerList().size())
316             continue;
317
318         // Skip completely transparent render surfaces.
319         if (!renderSurface->drawOpacity())
320             continue;
321
322         if (useRenderSurface(renderSurface)) {
323             renderSurface->setSkipsDraw(false);
324
325             if (renderSurfaceLayer != rootDrawLayer) {
326                 GLC(m_context.get(), m_context->disable(GraphicsContext3D::SCISSOR_TEST));
327                 GLC(m_context.get(), m_context->clearColor(0, 0, 0, 0));
328                 GLC(m_context.get(), m_context->clear(GraphicsContext3D::COLOR_BUFFER_BIT));
329                 GLC(m_context.get(), m_context->enable(GraphicsContext3D::SCISSOR_TEST));
330             }
331
332             const CCLayerList& layerList = renderSurface->layerList();
333             for (unsigned layerIndex = 0; layerIndex < layerList.size(); ++layerIndex)
334                 drawLayer(layerList[layerIndex].get(), renderSurface);
335         }
336     }
337
338     if (m_headsUpDisplay->enabled()) {
339         GLC(m_context.get(), m_context->enable(GraphicsContext3D::BLEND));
340         GLC(m_context.get(), m_context->blendFunc(GraphicsContext3D::ONE, GraphicsContext3D::ONE_MINUS_SRC_ALPHA));
341         GLC(m_context.get(), m_context->disable(GraphicsContext3D::SCISSOR_TEST));
342         useRenderSurface(m_defaultRenderSurface);
343         m_headsUpDisplay->draw();
344     }
345
346     GLC(m_context.get(), m_context->disable(GraphicsContext3D::SCISSOR_TEST));
347     GLC(m_context.get(), m_context->disable(GraphicsContext3D::BLEND));
348 }
349
350 void LayerRendererChromium::toGLMatrix(float* flattened, const TransformationMatrix& m)
351 {
352     flattened[0] = m.m11();
353     flattened[1] = m.m12();
354     flattened[2] = m.m13();
355     flattened[3] = m.m14();
356     flattened[4] = m.m21();
357     flattened[5] = m.m22();
358     flattened[6] = m.m23();
359     flattened[7] = m.m24();
360     flattened[8] = m.m31();
361     flattened[9] = m.m32();
362     flattened[10] = m.m33();
363     flattened[11] = m.m34();
364     flattened[12] = m.m41();
365     flattened[13] = m.m42();
366     flattened[14] = m.m43();
367     flattened[15] = m.m44();
368 }
369
370 void LayerRendererChromium::drawTexturedQuad(const TransformationMatrix& drawMatrix,
371                                              float width, float height, float opacity, const FloatQuad& quad,
372                                              int matrixLocation, int alphaLocation, int quadLocation)
373 {
374     static float glMatrix[16];
375
376     TransformationMatrix renderMatrix = drawMatrix;
377
378     // Apply a scaling factor to size the quad from 1x1 to its intended size.
379     renderMatrix.scale3d(width, height, 1);
380
381     // Apply the projection matrix before sending the transform over to the shader.
382     toGLMatrix(&glMatrix[0], m_projectionMatrix * renderMatrix);
383
384     GLC(m_context, m_context->uniformMatrix4fv(matrixLocation, false, &glMatrix[0], 1));
385
386     if (quadLocation != -1) {
387         float point[8];
388         point[0] = quad.p1().x();
389         point[1] = quad.p1().y();
390         point[2] = quad.p2().x();
391         point[3] = quad.p2().y();
392         point[4] = quad.p3().x();
393         point[5] = quad.p3().y();
394         point[6] = quad.p4().x();
395         point[7] = quad.p4().y();
396         GLC(m_context, m_context->uniform2fv(quadLocation, point, 4));
397     }
398
399     if (alphaLocation != -1)
400         GLC(m_context, m_context->uniform1f(alphaLocation, opacity));
401
402     GLC(m_context, m_context->drawElements(GraphicsContext3D::TRIANGLES, 6, GraphicsContext3D::UNSIGNED_SHORT, 0));
403 }
404
405 void LayerRendererChromium::finish()
406 {
407     TRACE_EVENT("LayerRendererChromium::finish", this, 0);
408     m_context->finish();
409 }
410
411 void LayerRendererChromium::present()
412 {
413     TRACE_EVENT("LayerRendererChromium::present", this, 0);
414     // We're done! Time to swapbuffers!
415
416     // Note that currently this has the same effect as swapBuffers; we should
417     // consider exposing a different entry point on GraphicsContext3D.
418     m_context->prepareTexture();
419
420     m_headsUpDisplay->onPresent();
421 }
422
423 void LayerRendererChromium::getFramebufferPixels(void *pixels, const IntRect& rect)
424 {
425     ASSERT(rect.maxX() <= viewportWidth() && rect.maxY() <= viewportHeight());
426
427     if (!pixels)
428         return;
429
430     makeContextCurrent();
431
432     GLC(m_context.get(), m_context->readPixels(rect.x(), rect.y(), rect.width(), rect.height(),
433                                          GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, pixels));
434 }
435
436 // FIXME: This method should eventually be replaced by a proper texture manager.
437 unsigned LayerRendererChromium::createLayerTexture()
438 {
439     unsigned textureId = 0;
440     GLC(m_context.get(), textureId = m_context->createTexture());
441     GLC(m_context.get(), m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, textureId));
442     // Do basic linear filtering on resize.
443     GLC(m_context.get(), m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::LINEAR));
444     GLC(m_context.get(), m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MAG_FILTER, GraphicsContext3D::LINEAR));
445     // NPOT textures in GL ES only work when the wrap mode is set to GraphicsContext3D::CLAMP_TO_EDGE.
446     GLC(m_context.get(), m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_S, GraphicsContext3D::CLAMP_TO_EDGE));
447     GLC(m_context.get(), m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_T, GraphicsContext3D::CLAMP_TO_EDGE));
448     return textureId;
449 }
450
451 void LayerRendererChromium::deleteLayerTexture(unsigned textureId)
452 {
453     if (!textureId)
454         return;
455
456     GLC(m_context.get(), m_context->deleteTexture(textureId));
457 }
458
459 // Returns true if any part of the layer falls within the visibleRect
460 bool LayerRendererChromium::isLayerVisible(LayerChromium* layer, const TransformationMatrix& matrix, const IntRect& visibleRect)
461 {
462     // Form the matrix used by the shader to map the corners of the layer's
463     // bounds into clip space.
464     TransformationMatrix renderMatrix = matrix;
465     renderMatrix.scale3d(layer->bounds().width(), layer->bounds().height(), 1);
466     renderMatrix = m_projectionMatrix * renderMatrix;
467
468     FloatRect layerRect(-0.5, -0.5, 1, 1);
469     FloatRect mappedRect = renderMatrix.mapRect(layerRect);
470
471     // The layer is visible if it intersects any part of a rectangle whose origin
472     // is at (-1, -1) and size is 2x2.
473     return mappedRect.intersects(FloatRect(-1, -1, 2, 2));
474 }
475
476 ManagedTexture* LayerRendererChromium::getOffscreenLayerTexture()
477 {
478     return settings().compositeOffscreen && rootLayer() ? rootLayer()->renderSurface()->contentsTexture() : 0;
479 }
480
481 void LayerRendererChromium::copyOffscreenTextureToDisplay()
482 {
483     if (settings().compositeOffscreen) {
484         makeContextCurrent();
485
486         useRenderSurface(0);
487         TransformationMatrix drawTransform;
488         drawTransform.translate3d(0.5 * m_defaultRenderSurface->contentRect().width(), 0.5 * m_defaultRenderSurface->contentRect().height(), 0);
489         m_defaultRenderSurface->setDrawTransform(drawTransform);
490         m_defaultRenderSurface->setDrawOpacity(1);
491         m_defaultRenderSurface->draw(this, m_defaultRenderSurface->contentRect());
492     }
493 }
494
495 bool LayerRendererChromium::useRenderSurface(CCRenderSurface* renderSurface)
496 {
497     if (m_currentRenderSurface == renderSurface)
498         return true;
499
500     m_currentRenderSurface = renderSurface;
501
502     if ((renderSurface == m_defaultRenderSurface && !settings().compositeOffscreen) || (!renderSurface && settings().compositeOffscreen)) {
503         GLC(m_context.get(), m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, 0));
504         if (renderSurface)
505             setDrawViewportRect(renderSurface->contentRect(), true);
506         else
507             setDrawViewportRect(m_defaultRenderSurface->contentRect(), true);
508         return true;
509     }
510
511     GLC(m_context.get(), m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_offscreenFramebufferId));
512
513     if (!renderSurface->prepareContentsTexture(this))
514         return false;
515
516     renderSurface->contentsTexture()->framebufferTexture2D(m_context.get());
517
518 #if !defined ( NDEBUG )
519     if (m_context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {
520         ASSERT_NOT_REACHED();
521         return false;
522     }
523 #endif
524
525     setDrawViewportRect(renderSurface->contentRect(), false);
526     return true;
527 }
528
529 void LayerRendererChromium::drawLayer(CCLayerImpl* layer, CCRenderSurface* targetSurface)
530 {
531     if (layer->renderSurface() && layer->renderSurface() != targetSurface) {
532         layer->renderSurface()->draw(this, layer->getDrawRect());
533         layer->renderSurface()->releaseContentsTexture();
534         return;
535     }
536
537     if (!layer->drawsContent())
538         return;
539
540     if (!layer->opacity())
541         return;
542
543     if (layer->bounds().isEmpty())
544         return;
545
546     IntRect targetSurfaceRect = layer->targetRenderSurface() ? layer->targetRenderSurface()->contentRect() : m_defaultRenderSurface->contentRect();
547     if (layer->usesLayerScissor()) {
548         IntRect scissorRect = layer->scissorRect();
549         targetSurfaceRect.intersect(scissorRect);
550         if (targetSurfaceRect.isEmpty())
551             return;
552         setScissorToRect(scissorRect);
553     } else
554         GLC(m_context.get(), m_context->disable(GraphicsContext3D::SCISSOR_TEST));
555
556     // The layer should not be drawn if (1) it is not double-sided and (2) the back of the layer is facing the screen.
557     // This second condition is checked by computing the transformed normal of the layer.
558     if (!layer->doubleSided()) {
559         FloatRect layerRect(FloatPoint(0, 0), FloatSize(layer->bounds()));
560         FloatQuad mappedLayer = layer->screenSpaceTransform().mapQuad(FloatQuad(layerRect));
561         FloatSize horizontalDir = mappedLayer.p2() - mappedLayer.p1();
562         FloatSize verticalDir = mappedLayer.p4() - mappedLayer.p1();
563         FloatPoint3D xAxis(horizontalDir.width(), horizontalDir.height(), 0);
564         FloatPoint3D yAxis(verticalDir.width(), verticalDir.height(), 0);
565         FloatPoint3D zAxis = xAxis.cross(yAxis);
566         if (zAxis.z() < 0)
567             return;
568     }
569
570     layer->draw(this);
571
572     // Draw the debug border if there is one.
573     layer->drawDebugBorder(this);
574 }
575
576 // Sets the scissor region to the given rectangle. The coordinate system for the
577 // scissorRect has its origin at the top left corner of the current visible rect.
578 void LayerRendererChromium::setScissorToRect(const IntRect& scissorRect)
579 {
580     IntRect contentRect = (m_currentRenderSurface ? m_currentRenderSurface->contentRect() : m_defaultRenderSurface->contentRect());
581
582     GLC(m_context.get(), m_context->enable(GraphicsContext3D::SCISSOR_TEST));
583
584     // The scissor coordinates must be supplied in viewport space so we need to offset
585     // by the relative position of the top left corner of the current render surface.
586     int scissorX = scissorRect.x() - contentRect.x();
587     // When rendering to the default render surface we're rendering upside down so the top
588     // of the GL scissor is the bottom of our layer.
589     // But, if rendering to offscreen texture, we reverse our sense of 'upside down'.
590     int scissorY;
591     if (m_currentRenderSurface == m_defaultRenderSurface && !settings().compositeOffscreen)
592         scissorY = m_currentRenderSurface->contentRect().height() - (scissorRect.maxY() - m_currentRenderSurface->contentRect().y());
593     else
594         scissorY = scissorRect.y() - contentRect.y();
595     GLC(m_context.get(), m_context->scissor(scissorX, scissorY, scissorRect.width(), scissorRect.height()));
596 }
597
598 bool LayerRendererChromium::makeContextCurrent()
599 {
600     m_context->makeContextCurrent();
601     return true;
602 }
603
604 // Sets the coordinate range of content that ends being drawn onto the target render surface.
605 // The target render surface is assumed to have an origin at 0, 0 and the width and height of
606 // of the drawRect.
607 void LayerRendererChromium::setDrawViewportRect(const IntRect& drawRect, bool flipY)
608 {
609     if (flipY)
610         m_projectionMatrix = orthoMatrix(drawRect.x(), drawRect.maxX(), drawRect.maxY(), drawRect.y());
611     else
612         m_projectionMatrix = orthoMatrix(drawRect.x(), drawRect.maxX(), drawRect.y(), drawRect.maxY());
613     GLC(m_context.get(), m_context->viewport(0, 0, drawRect.width(), drawRect.height()));
614     m_windowMatrix = screenMatrix(0, 0, drawRect.width(), drawRect.height());
615 }
616
617
618 bool LayerRendererChromium::initializeSharedObjects()
619 {
620     TRACE_EVENT("LayerRendererChromium::initializeSharedObjects", this, 0);
621     makeContextCurrent();
622
623     // Create an FBO for doing offscreen rendering.
624     GLC(m_context.get(), m_offscreenFramebufferId = m_context->createFramebuffer());
625
626     // We will always need these programs to render, so create the programs eagerly so that the shader compilation can
627     // start while we do other work. Other programs are created lazily on first access.
628     m_sharedGeometry = adoptPtr(new GeometryBinding(m_context.get()));
629     m_renderSurfaceProgram = adoptPtr(new CCRenderSurface::Program(m_context.get()));
630     m_tilerProgram = adoptPtr(new CCTiledLayerImpl::Program(m_context.get()));
631
632     GLC(m_context.get(), m_context->flush());
633
634     m_renderSurfaceTextureManager = TextureManager::create(TextureManager::highLimitBytes(), m_capabilities.maxTextureSize);
635     return true;
636 }
637
638 const LayerChromium::BorderProgram* LayerRendererChromium::borderProgram()
639 {
640     if (!m_borderProgram)
641         m_borderProgram = adoptPtr(new LayerChromium::BorderProgram(m_context.get()));
642     if (!m_borderProgram->initialized()) {
643         TRACE_EVENT("LayerRendererChromium::borderProgram::initialize", this, 0);
644         m_borderProgram->initialize(m_context.get());
645     }
646     return m_borderProgram.get();
647 }
648
649 const CCHeadsUpDisplay::Program* LayerRendererChromium::headsUpDisplayProgram()
650 {
651     if (!m_headsUpDisplayProgram)
652         m_headsUpDisplayProgram = adoptPtr(new CCHeadsUpDisplay::Program(m_context.get()));
653     if (!m_headsUpDisplayProgram->initialized()) {
654         TRACE_EVENT("LayerRendererChromium::headsUpDisplayProgram::initialize", this, 0);
655         m_headsUpDisplayProgram->initialize(m_context.get());
656     }
657     return m_headsUpDisplayProgram.get();
658 }
659
660 const CCRenderSurface::Program* LayerRendererChromium::renderSurfaceProgram()
661 {
662     ASSERT(m_renderSurfaceProgram);
663     if (!m_renderSurfaceProgram->initialized()) {
664         TRACE_EVENT("LayerRendererChromium::renderSurfaceProgram::initialize", this, 0);
665         m_renderSurfaceProgram->initialize(m_context.get());
666     }
667     return m_renderSurfaceProgram.get();
668 }
669
670 const CCRenderSurface::ProgramAA* LayerRendererChromium::renderSurfaceProgramAA()
671 {
672     if (!m_renderSurfaceProgramAA)
673         m_renderSurfaceProgramAA = adoptPtr(new CCRenderSurface::ProgramAA(m_context.get()));
674     if (!m_renderSurfaceProgramAA->initialized()) {
675         TRACE_EVENT("LayerRendererChromium::renderSurfaceProgramAA::initialize", this, 0);
676         m_renderSurfaceProgramAA->initialize(m_context.get());
677     }
678     return m_renderSurfaceProgramAA.get();
679 }
680
681 const CCRenderSurface::MaskProgram* LayerRendererChromium::renderSurfaceMaskProgram()
682 {
683     if (!m_renderSurfaceMaskProgram)
684         m_renderSurfaceMaskProgram = adoptPtr(new CCRenderSurface::MaskProgram(m_context.get()));
685     if (!m_renderSurfaceMaskProgram->initialized()) {
686         TRACE_EVENT("LayerRendererChromium::renderSurfaceMaskProgram::initialize", this, 0);
687         m_renderSurfaceMaskProgram->initialize(m_context.get());
688     }
689     return m_renderSurfaceMaskProgram.get();
690 }
691
692 const CCRenderSurface::MaskProgramAA* LayerRendererChromium::renderSurfaceMaskProgramAA()
693 {
694     if (!m_renderSurfaceMaskProgramAA)
695         m_renderSurfaceMaskProgramAA = adoptPtr(new CCRenderSurface::MaskProgramAA(m_context.get()));
696     if (!m_renderSurfaceMaskProgramAA->initialized()) {
697         TRACE_EVENT("LayerRendererChromium::renderSurfaceMaskProgramAA::initialize", this, 0);
698         m_renderSurfaceMaskProgramAA->initialize(m_context.get());
699     }
700     return m_renderSurfaceMaskProgramAA.get();
701 }
702
703 const CCTiledLayerImpl::Program* LayerRendererChromium::tilerProgram()
704 {
705     ASSERT(m_tilerProgram);
706     if (!m_tilerProgram->initialized()) {
707         TRACE_EVENT("LayerRendererChromium::tilerProgram::initialize", this, 0);
708         m_tilerProgram->initialize(m_context.get());
709     }
710     return m_tilerProgram.get();
711 }
712
713 const CCTiledLayerImpl::ProgramAA* LayerRendererChromium::tilerProgramAA()
714 {
715     if (!m_tilerProgramAA)
716         m_tilerProgramAA = adoptPtr(new CCTiledLayerImpl::ProgramAA(m_context.get()));
717     if (!m_tilerProgramAA->initialized()) {
718         TRACE_EVENT("LayerRendererChromium::tilerProgramAA::initialize", this, 0);
719         m_tilerProgramAA->initialize(m_context.get());
720     }
721     return m_tilerProgramAA.get();
722 }
723
724 const CCTiledLayerImpl::ProgramSwizzle* LayerRendererChromium::tilerProgramSwizzle()
725 {
726     if (!m_tilerProgramSwizzle)
727         m_tilerProgramSwizzle = adoptPtr(new CCTiledLayerImpl::ProgramSwizzle(m_context.get()));
728     if (!m_tilerProgramSwizzle->initialized()) {
729         TRACE_EVENT("LayerRendererChromium::tilerProgramSwizzle::initialize", this, 0);
730         m_tilerProgramSwizzle->initialize(m_context.get());
731     }
732     return m_tilerProgramSwizzle.get();
733 }
734
735 const CCTiledLayerImpl::ProgramSwizzleAA* LayerRendererChromium::tilerProgramSwizzleAA()
736 {
737     if (!m_tilerProgramSwizzleAA)
738         m_tilerProgramSwizzleAA = adoptPtr(new CCTiledLayerImpl::ProgramSwizzleAA(m_context.get()));
739     if (!m_tilerProgramSwizzleAA->initialized()) {
740         TRACE_EVENT("LayerRendererChromium::tilerProgramSwizzleAA::initialize", this, 0);
741         m_tilerProgramSwizzleAA->initialize(m_context.get());
742     }
743     return m_tilerProgramSwizzleAA.get();
744 }
745
746 const CCCanvasLayerImpl::Program* LayerRendererChromium::canvasLayerProgram()
747 {
748     if (!m_canvasLayerProgram)
749         m_canvasLayerProgram = adoptPtr(new CCCanvasLayerImpl::Program(m_context.get()));
750     if (!m_canvasLayerProgram->initialized()) {
751         TRACE_EVENT("LayerRendererChromium::canvasLayerProgram::initialize", this, 0);
752         m_canvasLayerProgram->initialize(m_context.get());
753     }
754     return m_canvasLayerProgram.get();
755 }
756
757 const CCPluginLayerImpl::Program* LayerRendererChromium::pluginLayerProgram()
758 {
759     if (!m_pluginLayerProgram)
760         m_pluginLayerProgram = adoptPtr(new CCPluginLayerImpl::Program(m_context.get()));
761     if (!m_pluginLayerProgram->initialized()) {
762         TRACE_EVENT("LayerRendererChromium::pluginLayerProgram::initialize", this, 0);
763         m_pluginLayerProgram->initialize(m_context.get());
764     }
765     return m_pluginLayerProgram.get();
766 }
767
768 const CCVideoLayerImpl::RGBAProgram* LayerRendererChromium::videoLayerRGBAProgram()
769 {
770     if (!m_videoLayerRGBAProgram)
771         m_videoLayerRGBAProgram = adoptPtr(new CCVideoLayerImpl::RGBAProgram(m_context.get()));
772     if (!m_videoLayerRGBAProgram->initialized()) {
773         TRACE_EVENT("LayerRendererChromium::videoLayerRGBAProgram::initialize", this, 0);
774         m_videoLayerRGBAProgram->initialize(m_context.get());
775     }
776     return m_videoLayerRGBAProgram.get();
777 }
778
779 const CCVideoLayerImpl::YUVProgram* LayerRendererChromium::videoLayerYUVProgram()
780 {
781     if (!m_videoLayerYUVProgram)
782         m_videoLayerYUVProgram = adoptPtr(new CCVideoLayerImpl::YUVProgram(m_context.get()));
783     if (!m_videoLayerYUVProgram->initialized()) {
784         TRACE_EVENT("LayerRendererChromium::videoLayerYUVProgram::initialize", this, 0);
785         m_videoLayerYUVProgram->initialize(m_context.get());
786     }
787     return m_videoLayerYUVProgram.get();
788 }
789
790
791 void LayerRendererChromium::cleanupSharedObjects()
792 {
793     makeContextCurrent();
794
795     m_sharedGeometry.clear();
796
797     if (m_borderProgram)
798         m_borderProgram->cleanup(m_context.get());
799     if (m_headsUpDisplayProgram)
800         m_headsUpDisplayProgram->cleanup(m_context.get());
801     if (m_tilerProgram)
802         m_tilerProgram->cleanup(m_context.get());
803     if (m_tilerProgramAA)
804         m_tilerProgramAA->cleanup(m_context.get());
805     if (m_tilerProgramSwizzle)
806         m_tilerProgramSwizzle->cleanup(m_context.get());
807     if (m_tilerProgramSwizzleAA)
808         m_tilerProgramSwizzleAA->cleanup(m_context.get());
809     if (m_canvasLayerProgram)
810         m_canvasLayerProgram->cleanup(m_context.get());
811     if (m_pluginLayerProgram)
812         m_pluginLayerProgram->cleanup(m_context.get());
813     if (m_renderSurfaceMaskProgram)
814         m_renderSurfaceMaskProgram->cleanup(m_context.get());
815     if (m_renderSurfaceMaskProgramAA)
816         m_renderSurfaceMaskProgramAA->cleanup(m_context.get());
817     if (m_renderSurfaceProgram)
818         m_renderSurfaceProgram->cleanup(m_context.get());
819     if (m_renderSurfaceProgramAA)
820         m_renderSurfaceProgramAA->cleanup(m_context.get());
821     if (m_videoLayerRGBAProgram)
822         m_videoLayerRGBAProgram->cleanup(m_context.get());
823     if (m_videoLayerYUVProgram)
824         m_videoLayerYUVProgram->cleanup(m_context.get());
825
826     m_borderProgram.clear();
827     m_headsUpDisplayProgram.clear();
828     m_tilerProgram.clear();
829     m_tilerProgramAA.clear();
830     m_tilerProgramSwizzle.clear();
831     m_tilerProgramSwizzleAA.clear();
832     m_canvasLayerProgram.clear();
833     m_pluginLayerProgram.clear();
834     m_renderSurfaceMaskProgram.clear();
835     m_renderSurfaceMaskProgramAA.clear();
836     m_renderSurfaceProgram.clear();
837     m_renderSurfaceProgramAA.clear();
838     m_videoLayerRGBAProgram.clear();
839     m_videoLayerYUVProgram.clear();
840     if (m_offscreenFramebufferId)
841         GLC(m_context.get(), m_context->deleteFramebuffer(m_offscreenFramebufferId));
842
843     ASSERT(!m_contentsTextureMemoryUseBytes);
844     releaseRenderSurfaceTextures();
845 }
846
847 String LayerRendererChromium::layerTreeAsText() const
848 {
849     TextStream ts;
850     if (rootLayer()) {
851         ts << rootLayer()->layerTreeAsText();
852         ts << "RenderSurfaces:\n";
853         dumpRenderSurfaces(ts, 1, rootLayer());
854     }
855     return ts.release();
856 }
857
858 void LayerRendererChromium::dumpRenderSurfaces(TextStream& ts, int indent, const CCLayerImpl* layer) const
859 {
860     if (layer->renderSurface())
861         layer->renderSurface()->dumpSurface(ts, indent);
862
863     for (size_t i = 0; i < layer->children().size(); ++i)
864         dumpRenderSurfaces(ts, indent, layer->children()[i].get());
865 }
866
867 bool LayerRendererChromium::isContextLost()
868 {
869     return (m_context.get()->getExtensions()->getGraphicsResetStatusARB() != GraphicsContext3D::NO_ERROR);
870 }
871
872 } // namespace WebCore
873
874 #endif // USE(ACCELERATED_COMPOSITING)