/
LayerRendererChromium.cpp
1350 lines (1116 loc) · 55.3 KB
/
LayerRendererChromium.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if USE(ACCELERATED_COMPOSITING)
#include "LayerRendererChromium.h"
#include "Canvas2DLayerChromium.h"
#include "Extensions3DChromium.h"
#include "FloatQuad.h"
#include "GeometryBinding.h"
#include "GraphicsContext3D.h"
#include "LayerChromium.h"
#include "LayerPainterChromium.h"
#include "ManagedTexture.h"
#include "LayerTextureUpdaterCanvas.h"
#include "NonCompositedContentHost.h"
#include "NotImplemented.h"
#include "PlatformColor.h"
#include "RenderSurfaceChromium.h"
#include "TextStream.h"
#include "TextureManager.h"
#include "TreeSynchronizer.h"
#include "TraceEvent.h"
#include "WebGLLayerChromium.h"
#include "cc/CCLayerImpl.h"
#include "cc/CCMainThreadTask.h"
#if USE(SKIA)
#include "Extensions3D.h"
#include "GrContext.h"
#include "NativeImageSkia.h"
#include "PlatformContextSkia.h"
#elif USE(CG)
#include <CoreGraphics/CGBitmapContext.h>
#endif
#include <wtf/CurrentTime.h>
#include <wtf/MainThread.h>
using namespace std;
namespace WebCore {
// FIXME: Make this limit adjustable and give it a useful value.
// Absolute maximum limit for texture allocations for this instance.
static size_t textureMemoryHighLimitBytes = 128 * 1024 * 1024;
// Preferred texture size limit. Can be exceeded if needed.
static size_t textureMemoryReclaimLimitBytes = 64 * 1024 * 1024;
// The maximum texture memory usage when asked to release textures.
static size_t textureMemoryLowLimitBytes = 3 * 1024 * 1024;
namespace {
IntRect calculateVisibleRect(const IntRect& targetSurfaceRect, const IntRect& layerBoundRect, const TransformationMatrix& transform)
{
// Is this layer fully contained within the target surface?
IntRect layerInSurfaceSpace = transform.mapRect(layerBoundRect);
if (targetSurfaceRect.contains(layerInSurfaceSpace))
return layerBoundRect;
// If the layer doesn't fill up the entire surface, then find the part of
// the surface rect where the layer could be visible. This avoids trying to
// project surface rect points that are behind the projection point.
IntRect minimalSurfaceRect = targetSurfaceRect;
minimalSurfaceRect.intersect(layerInSurfaceSpace);
// Project the corners of the target surface rect into the layer space.
// This bounding rectangle may be larger than it needs to be (being
// axis-aligned), but is a reasonable filter on the space to consider.
// Non-invertible transforms will create an empty rect here.
const TransformationMatrix surfaceToLayer = transform.inverse();
IntRect layerRect = surfaceToLayer.projectQuad(FloatQuad(FloatRect(minimalSurfaceRect))).enclosingBoundingBox();
layerRect.intersect(layerBoundRect);
return layerRect;
}
// Returns true if the matrix has no rotation, skew or perspective components to it.
bool isScaleOrTranslation(const TransformationMatrix& m)
{
return !m.m12() && !m.m13() && !m.m14()
&& !m.m21() && !m.m23() && !m.m24()
&& !m.m31() && !m.m32() && !m.m43()
&& m.m44();
}
void sortLayers(Vector<RefPtr<LayerChromium> >::iterator, Vector<RefPtr<LayerChromium> >::iterator, void*)
{
// Currently we don't use z-order to decide what to paint, so there's no need to actually sort LayerChromiums.
}
void sortLayers(Vector<RefPtr<CCLayerImpl> >::iterator first, Vector<RefPtr<CCLayerImpl> >::iterator end, CCLayerSorter* layerSorter)
{
TRACE_EVENT("LayerRendererChromium::sortLayers", 0, 0);
layerSorter->sort(first, end);
}
// Recursively walks the layer tree starting at the given node and computes all the
// necessary transformations, scissor rectangles, render surfaces, etc.
template<typename LayerType, typename RenderSurfaceType, typename LayerSorter>
void calculateDrawTransformsAndVisibility(LayerType* layer, LayerType* rootLayer, const TransformationMatrix& parentMatrix, const TransformationMatrix& fullHierarchyMatrix, Vector<RefPtr<LayerType> >& renderSurfaceLayerList, Vector<RefPtr<LayerType> >& layerList, LayerSorter* layerSorter, int maxTextureSize)
{
typedef Vector<RefPtr<LayerType> > LayerList;
// Compute the new matrix transformation that will be applied to this layer and
// all its children. It's important to remember that the layer's position
// is the position of the layer's anchor point. Also, the coordinate system used
// assumes that the origin is at the lower left even though the coordinates the browser
// gives us for the layers are for the upper left corner. The Y flip happens via
// the orthographic projection applied at render time.
// The transformation chain for the layer is (using the Matrix x Vector order):
// M = M[p] * Tr[l] * M[l] * Tr[c]
// Where M[p] is the parent matrix passed down to the function
// Tr[l] is the translation matrix locating the layer's anchor point
// Tr[c] is the translation offset between the anchor point and the center of the layer
// M[l] is the layer's matrix (applied at the anchor point)
// This transform creates a coordinate system whose origin is the center of the layer.
// Note that the final matrix used by the shader for the layer is P * M * S . This final product
// is computed in drawTexturedQuad().
// Where: P is the projection matrix
// M is the layer's matrix computed above
// S is the scale adjustment (to scale up to the layer size)
IntSize bounds = layer->bounds();
FloatPoint anchorPoint = layer->anchorPoint();
FloatPoint position = layer->position();
// Offset between anchor point and the center of the quad.
float centerOffsetX = (0.5 - anchorPoint.x()) * bounds.width();
float centerOffsetY = (0.5 - anchorPoint.y()) * bounds.height();
TransformationMatrix layerLocalTransform;
// LT = Tr[l]
layerLocalTransform.translate3d(position.x(), position.y(), layer->anchorPointZ());
// LT = Tr[l] * M[l]
layerLocalTransform.multiply(layer->transform());
// LT = Tr[l] * M[l] * Tr[c]
layerLocalTransform.translate3d(centerOffsetX, centerOffsetY, -layer->anchorPointZ());
TransformationMatrix combinedTransform = parentMatrix;
combinedTransform = combinedTransform.multiply(layerLocalTransform);
FloatRect layerRect(-0.5 * layer->bounds().width(), -0.5 * layer->bounds().height(), layer->bounds().width(), layer->bounds().height());
IntRect transformedLayerRect;
// fullHierarchyMatrix is the matrix that transforms objects between screen space (except projection matrix) and the most recent RenderSurface's space.
// nextHierarchyMatrix will only change if this layer uses a new RenderSurface, otherwise remains the same.
TransformationMatrix nextHierarchyMatrix = fullHierarchyMatrix;
// FIXME: This seems like the wrong place to set this
layer->setUsesLayerScissor(false);
// The layer and its descendants render on a new RenderSurface if any of
// these conditions hold:
// 1. The layer clips its descendants and its transform is not a simple translation.
// 2. If the layer has opacity != 1 and does not have a preserves-3d transform style.
// 3. The layer uses a mask
// 4. The layer has a replica (used for reflections)
// 5. The layer doesn't preserve-3d but is the child of a layer which does.
// If a layer preserves-3d then we don't create a RenderSurface for it to avoid flattening
// out its children. The opacity value of the children layers is multiplied by the opacity
// of their parent.
bool useSurfaceForClipping = layer->masksToBounds() && !isScaleOrTranslation(combinedTransform);
bool useSurfaceForOpacity = layer->opacity() != 1 && !layer->preserves3D();
bool useSurfaceForMasking = layer->maskLayer();
bool useSurfaceForReflection = layer->replicaLayer();
bool useSurfaceForFlatDescendants = layer->parent() && layer->parent()->preserves3D() && !layer->preserves3D() && layer->descendantDrawsContent();
if (useSurfaceForMasking || useSurfaceForReflection || useSurfaceForFlatDescendants || ((useSurfaceForClipping || useSurfaceForOpacity) && layer->descendantDrawsContent())) {
if (!layer->renderSurface())
layer->createRenderSurface();
RenderSurfaceType* renderSurface = layer->renderSurface();
// The origin of the new surface is the upper left corner of the layer.
TransformationMatrix drawTransform;
drawTransform.translate3d(0.5 * bounds.width(), 0.5 * bounds.height(), 0);
layer->setDrawTransform(drawTransform);
transformedLayerRect = IntRect(0, 0, bounds.width(), bounds.height());
// Layer's opacity will be applied when drawing the render surface.
float drawOpacity = layer->opacity();
if (layer->parent() && layer->parent()->preserves3D())
drawOpacity *= layer->parent()->drawOpacity();
renderSurface->setDrawOpacity(drawOpacity);
layer->setDrawOpacity(1);
TransformationMatrix layerOriginTransform = combinedTransform;
layerOriginTransform.translate3d(-0.5 * bounds.width(), -0.5 * bounds.height(), 0);
renderSurface->setOriginTransform(layerOriginTransform);
// Update the aggregate hierarchy matrix to include the transform of the newly created RenderSurface.
nextHierarchyMatrix.multiply(layerOriginTransform);
// The render surface scissor rect is the scissor rect that needs to
// be applied before drawing the render surface onto its containing
// surface and is therefore expressed in the parent's coordinate system.
renderSurface->setScissorRect(layer->parent() ? layer->parent()->scissorRect() : layer->scissorRect());
renderSurface->clearLayerList();
if (layer->maskLayer()) {
renderSurface->setMaskLayer(layer->maskLayer());
layer->maskLayer()->setTargetRenderSurface(renderSurface);
} else
renderSurface->setMaskLayer(0);
if (layer->replicaLayer() && layer->replicaLayer()->maskLayer())
layer->replicaLayer()->maskLayer()->setTargetRenderSurface(renderSurface);
renderSurfaceLayerList.append(layer);
} else {
// DT = M[p] * LT
layer->setDrawTransform(combinedTransform);
transformedLayerRect = enclosingIntRect(layer->drawTransform().mapRect(layerRect));
layer->setDrawOpacity(layer->opacity());
if (layer->parent()) {
if (layer->parent()->preserves3D())
layer->setDrawOpacity(layer->drawOpacity() * layer->parent()->drawOpacity());
// Layers inherit the scissor rect from their parent.
layer->setScissorRect(layer->parent()->scissorRect());
if (layer->parent()->usesLayerScissor())
layer->setUsesLayerScissor(true);
layer->setTargetRenderSurface(layer->parent()->targetRenderSurface());
}
if (layer != rootLayer)
layer->clearRenderSurface();
if (layer->masksToBounds()) {
IntRect scissor = transformedLayerRect;
if (!layer->scissorRect().isEmpty())
scissor.intersect(layer->scissorRect());
layer->setScissorRect(scissor);
layer->setUsesLayerScissor(true);
}
}
// Note that at this point, layer->drawTransform() is not necessarily the same as local variable drawTransform.
// layerScreenSpaceTransform represents the transform between layer space (in pixels) and screen space.
// So we do not include projection P or scaling transform S (see comments above that describe P*M*S).
TransformationMatrix layerScreenSpaceTransform = nextHierarchyMatrix;
layerScreenSpaceTransform.multiply(layer->drawTransform());
layerScreenSpaceTransform.translate3d(-0.5 * bounds.width(), -0.5 * bounds.height(), 0);
layer->setScreenSpaceTransform(layerScreenSpaceTransform);
if (layer->renderSurface())
layer->setTargetRenderSurface(layer->renderSurface());
else {
ASSERT(layer->parent());
layer->setTargetRenderSurface(layer->parent()->targetRenderSurface());
}
// drawableContentRect() is always stored in the coordinate system of the
// RenderSurface the layer draws into.
if (layer->drawsContent()) {
IntRect drawableContentRect = transformedLayerRect;
if (layer->usesLayerScissor())
drawableContentRect.intersect(layer->scissorRect());
layer->setDrawableContentRect(drawableContentRect);
} else
layer->setDrawableContentRect(IntRect());
TransformationMatrix sublayerMatrix = layer->drawTransform();
// Flatten to 2D if the layer doesn't preserve 3D.
if (!layer->preserves3D()) {
sublayerMatrix.setM13(0);
sublayerMatrix.setM23(0);
sublayerMatrix.setM31(0);
sublayerMatrix.setM32(0);
sublayerMatrix.setM33(1);
sublayerMatrix.setM34(0);
sublayerMatrix.setM43(0);
}
// Apply the sublayer transform at the center of the layer.
sublayerMatrix.multiply(layer->sublayerTransform());
// The origin of the children is the top left corner of the layer, not the
// center. The matrix passed down to the children is therefore:
// M[s] = M * Tr[-center]
sublayerMatrix.translate3d(-bounds.width() * 0.5, -bounds.height() * 0.5, 0);
LayerList& descendants = (layer->renderSurface() ? layer->renderSurface()->layerList() : layerList);
descendants.append(layer);
unsigned thisLayerIndex = descendants.size() - 1;
for (size_t i = 0; i < layer->children().size(); ++i) {
LayerType* child = layer->children()[i].get();
calculateDrawTransformsAndVisibility<LayerType, RenderSurfaceType, LayerSorter>(child, rootLayer, sublayerMatrix, nextHierarchyMatrix, renderSurfaceLayerList, descendants, layerSorter, maxTextureSize);
if (child->renderSurface()) {
RenderSurfaceType* childRenderSurface = child->renderSurface();
IntRect drawableContentRect = layer->drawableContentRect();
drawableContentRect.unite(enclosingIntRect(childRenderSurface->drawableContentRect()));
layer->setDrawableContentRect(drawableContentRect);
descendants.append(child);
} else {
IntRect drawableContentRect = layer->drawableContentRect();
drawableContentRect.unite(child->drawableContentRect());
layer->setDrawableContentRect(drawableContentRect);
}
}
if (layer->masksToBounds() || useSurfaceForMasking) {
IntRect drawableContentRect = layer->drawableContentRect();
drawableContentRect.intersect(transformedLayerRect);
layer->setDrawableContentRect(drawableContentRect);
}
if (layer->renderSurface() && layer != rootLayer) {
RenderSurfaceType* renderSurface = layer->renderSurface();
IntRect clippedContentRect = layer->drawableContentRect();
FloatPoint surfaceCenter = FloatRect(clippedContentRect).center();
// Restrict the RenderSurface size to the portion that's visible.
FloatSize centerOffsetDueToClipping;
// Don't clip if the layer is reflected as the reflection shouldn't be
// clipped.
if (!layer->replicaLayer()) {
if (!renderSurface->scissorRect().isEmpty() && !clippedContentRect.isEmpty()) {
IntRect surfaceScissorRect = calculateVisibleRect(renderSurface->scissorRect(), clippedContentRect, renderSurface->originTransform());
clippedContentRect.intersect(surfaceScissorRect);
}
FloatPoint clippedSurfaceCenter = FloatRect(clippedContentRect).center();
centerOffsetDueToClipping = clippedSurfaceCenter - surfaceCenter;
}
// The RenderSurface backing texture cannot exceed the maximum supported
// texture size.
clippedContentRect.setWidth(min(clippedContentRect.width(), maxTextureSize));
clippedContentRect.setHeight(min(clippedContentRect.height(), maxTextureSize));
if (clippedContentRect.isEmpty())
renderSurface->clearLayerList();
renderSurface->setContentRect(clippedContentRect);
// Since the layer starts a new render surface we need to adjust its
// scissor rect to be expressed in the new surface's coordinate system.
layer->setScissorRect(layer->drawableContentRect());
// Adjust the origin of the transform to be the center of the render surface.
TransformationMatrix drawTransform = renderSurface->originTransform();
drawTransform.translate3d(surfaceCenter.x() + centerOffsetDueToClipping.width(), surfaceCenter.y() + centerOffsetDueToClipping.height(), 0);
renderSurface->setDrawTransform(drawTransform);
// Compute the transformation matrix used to draw the replica of the render
// surface.
if (layer->replicaLayer()) {
TransformationMatrix replicaDrawTransform = renderSurface->originTransform();
replicaDrawTransform.translate3d(layer->replicaLayer()->position().x(), layer->replicaLayer()->position().y(), 0);
replicaDrawTransform.multiply(layer->replicaLayer()->transform());
replicaDrawTransform.translate3d(surfaceCenter.x() - anchorPoint.x() * bounds.width(), surfaceCenter.y() - anchorPoint.y() * bounds.height(), 0);
renderSurface->setReplicaDrawTransform(replicaDrawTransform);
}
}
// If preserves-3d then sort all the descendants in 3D so that they can be
// drawn from back to front. If the preserves-3d property is also set on the parent then
// skip the sorting as the parent will sort all the descendants anyway.
if (layer->preserves3D() && (!layer->parent() || !layer->parent()->preserves3D()))
sortLayers(&descendants.at(thisLayerIndex), descendants.end(), layerSorter);
}
}
static TransformationMatrix orthoMatrix(float left, float right, float bottom, float top)
{
float deltaX = right - left;
float deltaY = top - bottom;
TransformationMatrix ortho;
if (!deltaX || !deltaY)
return ortho;
ortho.setM11(2.0f / deltaX);
ortho.setM41(-(right + left) / deltaX);
ortho.setM22(2.0f / deltaY);
ortho.setM42(-(top + bottom) / deltaY);
// Z component of vertices is always set to zero as we don't use the depth buffer
// while drawing.
ortho.setM33(0);
return ortho;
}
static TransformationMatrix screenMatrix(int x, int y, int width, int height)
{
TransformationMatrix screen;
// Map to viewport.
screen.translate3d(x, y, 0);
screen.scale3d(width, height, 0);
// Map x, y and z to unit square.
screen.translate3d(0.5, 0.5, 0.5);
screen.scale3d(0.5, 0.5, 0.5);
return screen;
}
#if USE(SKIA)
bool contextSupportsAcceleratedPainting(GraphicsContext3D* context)
{
WebCore::Extensions3D* extensions = context->getExtensions();
if (extensions->supports("GL_EXT_texture_format_BGRA8888"))
extensions->ensureEnabled("GL_EXT_texture_format_BGRA8888");
else
return false;
if (extensions->supports("GL_EXT_read_format_bgra"))
extensions->ensureEnabled("GL_EXT_read_format_bgra");
else
return false;
return true;
}
#endif
PassRefPtr<LayerRendererChromium> LayerRendererChromium::create(CCLayerTreeHost* owner, PassRefPtr<GraphicsContext3D> context)
{
#if USE(SKIA)
if (owner->settings().acceleratePainting && !contextSupportsAcceleratedPainting(context.get()))
return 0;
#endif
RefPtr<LayerRendererChromium> layerRenderer(adoptRef(new LayerRendererChromium(owner, context)));
if (!layerRenderer->initialize())
return 0;
return layerRenderer.release();
}
LayerRendererChromium::LayerRendererChromium(CCLayerTreeHost* owner,
PassRefPtr<GraphicsContext3D> context)
: m_owner(owner)
, m_currentRenderSurface(0)
, m_offscreenFramebufferId(0)
, m_context(context)
, m_defaultRenderSurface(0)
{
}
bool LayerRendererChromium::initialize()
{
m_context->makeContextCurrent();
#if USE(SKIA)
if (settings().acceleratePainting) {
m_skiaContext = adoptPtr(GrContext::CreateGLShaderContext());
// Limit the number of textures we hold in the bitmap->texture cache.
static const int maxTextureCacheCount = 512;
// Limit the bytes allocated toward textures in the bitmap->texture cache.
static const size_t maxTextureCacheBytes = 50 * 1024 * 1024;
m_skiaContext->setTextureCacheLimits(maxTextureCacheCount, maxTextureCacheBytes);
}
#endif
WebCore::Extensions3D* extensions = m_context->getExtensions();
m_contextSupportsMapSub = extensions->supports("GL_CHROMIUM_map_sub");
if (m_contextSupportsMapSub)
extensions->ensureEnabled("GL_CHROMIUM_map_sub");
if (!initializeSharedObjects())
return false;
m_headsUpDisplay = CCHeadsUpDisplay::create(this);
// Make sure the viewport and context gets initialized, even if it is to zero.
viewportChanged();
return true;
}
LayerRendererChromium::~LayerRendererChromium()
{
m_headsUpDisplay.clear(); // Explicitly destroy the HUD before the TextureManager dies.
cleanupSharedObjects();
}
GraphicsContext3D* LayerRendererChromium::context()
{
return m_context.get();
}
void LayerRendererChromium::debugGLCall(GraphicsContext3D* context, const char* command, const char* file, int line)
{
unsigned long error = context->getError();
if (error != GraphicsContext3D::NO_ERROR)
LOG_ERROR("GL command failed: File: %s\n\tLine %d\n\tcommand: %s, error %x\n", file, line, command, static_cast<int>(error));
}
void LayerRendererChromium::releaseTextures()
{
// Reduces texture memory usage to textureMemoryLowLimitBytes by deleting non root layer
// textures.
m_owner->nonCompositedContentHost()->protectVisibleTileTextures();
m_contentsTextureManager->reduceMemoryToLimit(textureMemoryLowLimitBytes);
m_contentsTextureManager->unprotectAllTextures();
m_contentsTextureManager->deleteEvictedTextures(m_context.get());
// Evict all RenderSurface textures.
m_renderSurfaceTextureManager->unprotectAllTextures();
m_renderSurfaceTextureManager->reduceMemoryToLimit(0);
m_renderSurfaceTextureManager->deleteEvictedTextures(m_context.get());
}
GC3Denum LayerRendererChromium::bestTextureFormat()
{
return PlatformColor::bestTextureFormat(context());
}
void LayerRendererChromium::viewportChanged()
{
if (m_context)
m_context->reshape(std::max(1, viewportWidth()), std::max(1, viewportHeight()));
// Reset the current render surface to force an update of the viewport and
// projection matrix next time useRenderSurface is called.
m_currentRenderSurface = 0;
}
void LayerRendererChromium::updateLayers()
{
if (m_owner->viewportSize().isEmpty())
return;
// FIXME: use the frame begin time from the overall compositor scheduler.
// This value is currently inaccessible because it is up in Chromium's
// RenderWidget.
m_headsUpDisplay->onFrameBegin(currentTime());
// Recheck that we still have a root layer. This may become null if
// compositing gets turned off during a paint operation.
if (!rootLayer()) {
m_rootCCLayerImpl.clear();
return;
}
updateLayers(rootLayer()->platformLayer());
}
void LayerRendererChromium::drawLayers()
{
if (!rootLayer())
return;
// Before drawLayers:
ChildContextMap::iterator i = m_childContexts.begin();
for (; i != m_childContexts.end(); ++i) {
i->first->flush();
}
{
TRACE_EVENT("LayerRendererChromium::synchronizeTrees", this, 0);
m_rootCCLayerImpl = TreeSynchronizer::synchronizeTrees(rootLayer()->platformLayer(), m_rootCCLayerImpl.get());
}
m_renderSurfaceTextureManager->setMemoryLimitBytes(textureMemoryHighLimitBytes - m_contentsTextureManager->currentMemoryUseBytes());
drawLayersInternal();
m_contentsTextureManager->unprotectAllTextures();
if (textureMemoryReclaimLimitBytes > m_contentsTextureManager->currentMemoryUseBytes())
m_renderSurfaceTextureManager->reduceMemoryToLimit(textureMemoryReclaimLimitBytes - m_contentsTextureManager->currentMemoryUseBytes());
else
m_renderSurfaceTextureManager->reduceMemoryToLimit(0);
m_renderSurfaceTextureManager->deleteEvictedTextures(m_context.get());
if (settings().compositeOffscreen)
copyOffscreenTextureToDisplay();
}
void LayerRendererChromium::updateLayers(LayerChromium* rootLayer)
{
TRACE_EVENT("LayerRendererChromium::updateLayers", this, 0);
if (!rootLayer->renderSurface())
rootLayer->createRenderSurface();
rootLayer->renderSurface()->setContentRect(IntRect(IntPoint(0, 0), viewportSize()));
IntRect rootScissorRect(IntPoint(), viewportSize());
rootLayer->setScissorRect(rootScissorRect);
LayerList renderSurfaceLayerList;
renderSurfaceLayerList.append(rootLayer);
RenderSurfaceChromium* rootRenderSurface = rootLayer->renderSurface();
rootRenderSurface->clearLayerList();
TransformationMatrix identityMatrix;
{
TRACE_EVENT("LayerRendererChromium::updateLayers::calcDrawEtc", this, 0);
calculateDrawTransformsAndVisibility<LayerChromium, RenderSurfaceChromium, void*>(rootLayer, rootLayer, identityMatrix, identityMatrix, renderSurfaceLayerList, rootRenderSurface->layerList(), 0, m_maxTextureSize);
}
paintLayerContents(renderSurfaceLayerList);
m_contentsTextureManager->reduceMemoryToLimit(textureMemoryReclaimLimitBytes);
m_contentsTextureManager->deleteEvictedTextures(m_context.get());
updateCompositorResources(renderSurfaceLayerList);
}
static IntRect calculateVisibleLayerRect(const IntRect& targetSurfaceRect, const IntSize& bounds, const IntSize& contentBounds, const TransformationMatrix& tilingTransform)
{
if (targetSurfaceRect.isEmpty() || contentBounds.isEmpty())
return targetSurfaceRect;
const IntRect layerBoundRect = IntRect(IntPoint(), contentBounds);
TransformationMatrix transform = tilingTransform;
transform.scaleNonUniform(bounds.width() / static_cast<double>(contentBounds.width()),
bounds.height() / static_cast<double>(contentBounds.height()));
transform.translate(-contentBounds.width() / 2.0, -contentBounds.height() / 2.0);
return calculateVisibleRect(targetSurfaceRect, layerBoundRect, transform);
}
static void paintContentsIfDirty(LayerChromium* layer, const IntRect& visibleLayerRect)
{
if (layer->drawsContent()) {
layer->setVisibleLayerRect(visibleLayerRect);
layer->paintContentsIfDirty();
}
}
void LayerRendererChromium::paintLayerContents(const LayerList& renderSurfaceLayerList)
{
for (int surfaceIndex = renderSurfaceLayerList.size() - 1; surfaceIndex >= 0 ; --surfaceIndex) {
LayerChromium* renderSurfaceLayer = renderSurfaceLayerList[surfaceIndex].get();
RenderSurfaceChromium* renderSurface = renderSurfaceLayer->renderSurface();
ASSERT(renderSurface);
// Make sure any renderSurfaceLayer is associated with this layerRenderer.
// This is a defensive assignment in case the owner of this layer hasn't
// set the layerRenderer on this layer already.
renderSurfaceLayer->setLayerRenderer(this);
// Render surfaces whose drawable area has zero width or height
// will have no layers associated with them and should be skipped.
if (!renderSurface->layerList().size())
continue;
if (!renderSurface->drawOpacity())
continue;
const LayerList& layerList = renderSurface->layerList();
ASSERT(layerList.size());
for (unsigned layerIndex = 0; layerIndex < layerList.size(); ++layerIndex) {
LayerChromium* layer = layerList[layerIndex].get();
// Layers that start a new render surface will be painted when the render
// surface's list is processed.
if (layer->renderSurface() && layer->renderSurface() != renderSurface)
continue;
layer->setLayerRenderer(this);
if (!layer->opacity())
continue;
if (layer->maskLayer())
layer->maskLayer()->setLayerRenderer(this);
if (layer->replicaLayer()) {
layer->replicaLayer()->setLayerRenderer(this);
if (layer->replicaLayer()->maskLayer())
layer->replicaLayer()->maskLayer()->setLayerRenderer(this);
}
if (layer->bounds().isEmpty())
continue;
IntRect targetSurfaceRect = layer->targetRenderSurface() ? layer->targetRenderSurface()->contentRect() : m_defaultRenderSurface->contentRect();
if (layer->usesLayerScissor())
targetSurfaceRect.intersect(layer->scissorRect());
IntRect visibleLayerRect = calculateVisibleLayerRect(targetSurfaceRect, layer->bounds(), layer->contentBounds(), layer->drawTransform());
visibleLayerRect.move(toSize(layer->scrollPosition()));
paintContentsIfDirty(layer, visibleLayerRect);
if (LayerChromium* maskLayer = layer->maskLayer()) {
paintContentsIfDirty(maskLayer, IntRect(IntPoint(), maskLayer->contentBounds()));
}
if (LayerChromium* replicaLayer = layer->replicaLayer()) {
paintContentsIfDirty(replicaLayer, visibleLayerRect);
if (LayerChromium* replicaMaskLayer = replicaLayer->maskLayer()) {
paintContentsIfDirty(replicaMaskLayer, IntRect(IntPoint(), replicaMaskLayer->contentBounds()));
}
}
}
}
}
void LayerRendererChromium::drawLayersInternal()
{
if (viewportSize().isEmpty() || !rootLayer())
return;
TRACE_EVENT("LayerRendererChromium::drawLayers", this, 0);
CCLayerImpl* rootDrawLayer = m_rootCCLayerImpl.get();
makeContextCurrent();
if (!rootDrawLayer->renderSurface())
rootDrawLayer->createRenderSurface();
rootDrawLayer->renderSurface()->setContentRect(IntRect(IntPoint(), viewportSize()));
rootDrawLayer->setScissorRect(IntRect(IntPoint(), viewportSize()));
CCLayerList renderSurfaceLayerList;
renderSurfaceLayerList.append(rootDrawLayer);
TransformationMatrix identityMatrix;
m_defaultRenderSurface = rootDrawLayer->renderSurface();
m_defaultRenderSurface->clearLayerList();
{
TRACE_EVENT("LayerRendererChromium::drawLayersInternal::calcDrawEtc", this, 0);
calculateDrawTransformsAndVisibility<CCLayerImpl, CCRenderSurface, CCLayerSorter>(rootDrawLayer, rootDrawLayer, identityMatrix, identityMatrix, renderSurfaceLayerList, m_defaultRenderSurface->layerList(), &m_layerSorter, m_maxTextureSize);
}
// The GL viewport covers the entire visible area, including the scrollbars.
GLC(m_context.get(), m_context->viewport(0, 0, viewportWidth(), viewportHeight()));
m_windowMatrix = screenMatrix(0, 0, viewportWidth(), viewportHeight());
// Bind the common vertex attributes used for drawing all the layers.
m_sharedGeometry->prepareForDraw();
// FIXME: These calls can be made once, when the compositor context is initialized.
GLC(m_context.get(), m_context->disable(GraphicsContext3D::DEPTH_TEST));
GLC(m_context.get(), m_context->disable(GraphicsContext3D::CULL_FACE));
useRenderSurface(m_defaultRenderSurface);
// Clear to blue to make it easier to spot unrendered regions.
m_context->clearColor(0, 0, 1, 1);
m_context->colorMask(true, true, true, true);
m_context->clear(GraphicsContext3D::COLOR_BUFFER_BIT);
GLC(m_context.get(), m_context->enable(GraphicsContext3D::BLEND));
GLC(m_context.get(), m_context->blendFunc(GraphicsContext3D::ONE, GraphicsContext3D::ONE_MINUS_SRC_ALPHA));
GLC(m_context.get(), m_context->enable(GraphicsContext3D::SCISSOR_TEST));
// Update the contents of the render surfaces. We traverse the array from
// back to front to guarantee that nested render surfaces get rendered in the
// correct order.
for (int surfaceIndex = renderSurfaceLayerList.size() - 1; surfaceIndex >= 0 ; --surfaceIndex) {
CCLayerImpl* renderSurfaceLayer = renderSurfaceLayerList[surfaceIndex].get();
CCRenderSurface* renderSurface = renderSurfaceLayer->renderSurface();
ASSERT(renderSurface);
renderSurface->setSkipsDraw(true);
// Render surfaces whose drawable area has zero width or height
// will have no layers associated with them and should be skipped.
if (!renderSurface->layerList().size())
continue;
// Skip completely transparent render surfaces.
if (!renderSurface->drawOpacity())
continue;
if (useRenderSurface(renderSurface)) {
renderSurface->setSkipsDraw(false);
if (renderSurfaceLayer != rootDrawLayer) {
GLC(m_context.get(), m_context->disable(GraphicsContext3D::SCISSOR_TEST));
GLC(m_context.get(), m_context->clearColor(0, 0, 0, 0));
GLC(m_context.get(), m_context->clear(GraphicsContext3D::COLOR_BUFFER_BIT));
GLC(m_context.get(), m_context->enable(GraphicsContext3D::SCISSOR_TEST));
}
const CCLayerList& layerList = renderSurface->layerList();
for (unsigned layerIndex = 0; layerIndex < layerList.size(); ++layerIndex)
drawLayer(layerList[layerIndex].get(), renderSurface);
}
}
if (m_headsUpDisplay->enabled()) {
GLC(m_context.get(), m_context->enable(GraphicsContext3D::BLEND));
GLC(m_context.get(), m_context->blendFunc(GraphicsContext3D::ONE, GraphicsContext3D::ONE_MINUS_SRC_ALPHA));
GLC(m_context.get(), m_context->disable(GraphicsContext3D::SCISSOR_TEST));
useRenderSurface(m_defaultRenderSurface);
m_headsUpDisplay->draw();
}
GLC(m_context.get(), m_context->disable(GraphicsContext3D::SCISSOR_TEST));
GLC(m_context.get(), m_context->disable(GraphicsContext3D::BLEND));
}
void LayerRendererChromium::finish()
{
TRACE_EVENT("LayerRendererChromium::finish", this, 0);
m_context->finish();
}
void LayerRendererChromium::present()
{
TRACE_EVENT("LayerRendererChromium::present", this, 0);
// We're done! Time to swapbuffers!
// Note that currently this has the same effect as swapBuffers; we should
// consider exposing a different entry point on GraphicsContext3D.
m_context->prepareTexture();
m_headsUpDisplay->onPresent();
}
void LayerRendererChromium::setLayerRendererRecursive(LayerChromium* layer)
{
const Vector<RefPtr<LayerChromium> >& children = layer->children();
for (size_t i = 0; i < children.size(); ++i)
setLayerRendererRecursive(children[i].get());
if (layer->maskLayer())
setLayerRendererRecursive(layer->maskLayer());
if (layer->replicaLayer())
setLayerRendererRecursive(layer->replicaLayer());
layer->setLayerRenderer(this);
}
void LayerRendererChromium::getFramebufferPixels(void *pixels, const IntRect& rect)
{
ASSERT(rect.maxX() <= viewportWidth() && rect.maxY() <= viewportHeight());
if (!pixels)
return;
makeContextCurrent();
GLC(m_context.get(), m_context->readPixels(rect.x(), rect.y(), rect.width(), rect.height(),
GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, pixels));
}
// FIXME: This method should eventually be replaced by a proper texture manager.
unsigned LayerRendererChromium::createLayerTexture()
{
unsigned textureId = 0;
GLC(m_context.get(), textureId = m_context->createTexture());
GLC(m_context.get(), m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, textureId));
// Do basic linear filtering on resize.
GLC(m_context.get(), m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::LINEAR));
GLC(m_context.get(), m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MAG_FILTER, GraphicsContext3D::LINEAR));
// NPOT textures in GL ES only work when the wrap mode is set to GraphicsContext3D::CLAMP_TO_EDGE.
GLC(m_context.get(), m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_S, GraphicsContext3D::CLAMP_TO_EDGE));
GLC(m_context.get(), m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_T, GraphicsContext3D::CLAMP_TO_EDGE));
return textureId;
}
void LayerRendererChromium::deleteLayerTexture(unsigned textureId)
{
if (!textureId)
return;
GLC(m_context.get(), m_context->deleteTexture(textureId));
}
// Returns true if any part of the layer falls within the visibleRect
bool LayerRendererChromium::isLayerVisible(LayerChromium* layer, const TransformationMatrix& matrix, const IntRect& visibleRect)
{
// Form the matrix used by the shader to map the corners of the layer's
// bounds into clip space.
TransformationMatrix renderMatrix = matrix;
renderMatrix.scale3d(layer->bounds().width(), layer->bounds().height(), 1);
renderMatrix = m_projectionMatrix * renderMatrix;
FloatRect layerRect(-0.5, -0.5, 1, 1);
FloatRect mappedRect = renderMatrix.mapRect(layerRect);
// The layer is visible if it intersects any part of a rectangle whose origin
// is at (-1, -1) and size is 2x2.
return mappedRect.intersects(FloatRect(-1, -1, 2, 2));
}
void LayerRendererChromium::updateCompositorResources(const LayerList& renderSurfaceLayerList)
{
for (int surfaceIndex = renderSurfaceLayerList.size() - 1; surfaceIndex >= 0 ; --surfaceIndex) {
LayerChromium* renderSurfaceLayer = renderSurfaceLayerList[surfaceIndex].get();
RenderSurfaceChromium* renderSurface = renderSurfaceLayer->renderSurface();
ASSERT(renderSurface);
if (!renderSurface->layerList().size() || !renderSurface->drawOpacity())
continue;
const LayerList& layerList = renderSurface->layerList();
ASSERT(layerList.size());
for (unsigned layerIndex = 0; layerIndex < layerList.size(); ++layerIndex) {
LayerChromium* layer = layerList[layerIndex].get();
if (layer->renderSurface() && layer->renderSurface() != renderSurface)
continue;
updateCompositorResources(layer);
}
}
}
void LayerRendererChromium::updateCompositorResources(LayerChromium* layer)
{
if (layer->bounds().isEmpty())
return;
if (!layer->opacity())
return;
if (layer->maskLayer())
updateCompositorResources(layer->maskLayer());
if (layer->replicaLayer())
updateCompositorResources(layer->replicaLayer());
if (layer->drawsContent())
layer->updateCompositorResources(context());
}
ManagedTexture* LayerRendererChromium::getOffscreenLayerTexture()
{
return settings().compositeOffscreen && m_rootCCLayerImpl ? m_rootCCLayerImpl->renderSurface()->contentsTexture() : 0;
}
void LayerRendererChromium::copyOffscreenTextureToDisplay()
{
if (settings().compositeOffscreen) {
makeContextCurrent();
useRenderSurface(0);
TransformationMatrix drawTransform;
drawTransform.translate3d(0.5 * m_defaultRenderSurface->contentRect().width(), 0.5 * m_defaultRenderSurface->contentRect().height(), 0);
m_defaultRenderSurface->setDrawTransform(drawTransform);
m_defaultRenderSurface->setDrawOpacity(1);
m_defaultRenderSurface->draw(m_defaultRenderSurface->contentRect());
}
}
bool LayerRendererChromium::useRenderSurface(CCRenderSurface* renderSurface)
{
if (m_currentRenderSurface == renderSurface)
return true;
m_currentRenderSurface = renderSurface;
if ((renderSurface == m_defaultRenderSurface && !settings().compositeOffscreen) || (!renderSurface && settings().compositeOffscreen)) {
GLC(m_context.get(), m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, 0));
if (renderSurface)
setDrawViewportRect(renderSurface->contentRect(), true);
else
setDrawViewportRect(m_defaultRenderSurface->contentRect(), true);
return true;
}
GLC(m_context.get(), m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_offscreenFramebufferId));
if (!renderSurface->prepareContentsTexture())
return false;
renderSurface->contentsTexture()->framebufferTexture2D(m_context.get());
#if !defined ( NDEBUG )
if (m_context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {
ASSERT_NOT_REACHED();
return false;
}
#endif
setDrawViewportRect(renderSurface->contentRect(), false);
return true;
}
void LayerRendererChromium::drawLayer(CCLayerImpl* layer, CCRenderSurface* targetSurface)