Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / platform / graphics / gpu / DrawingBuffer.h
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 #ifndef DrawingBuffer_h
32 #define DrawingBuffer_h
33
34 #include "platform/PlatformExport.h"
35 #include "platform/geometry/IntSize.h"
36 #include "platform/graphics/GraphicsTypes3D.h"
37 #include "platform/graphics/gpu/WebGLImageConversion.h"
38 #include "public/platform/WebExternalTextureLayerClient.h"
39 #include "public/platform/WebExternalTextureMailbox.h"
40 #include "public/platform/WebGraphicsContext3D.h"
41 #include "third_party/khronos/GLES2/gl2.h"
42 #include "third_party/khronos/GLES2/gl2ext.h"
43 #include "third_party/skia/include/core/SkBitmap.h"
44 #include "wtf/Deque.h"
45 #include "wtf/Noncopyable.h"
46 #include "wtf/OwnPtr.h"
47 #include "wtf/PassOwnPtr.h"
48
49 namespace blink {
50
51 class Extensions3DUtil;
52 class ImageBuffer;
53 class ImageData;
54 class WebExternalBitmap;
55 class WebExternalTextureLayer;
56 class WebGraphicsContext3D;
57 class WebLayer;
58
59 // Abstract interface to allow basic context eviction management
60 class PLATFORM_EXPORT ContextEvictionManager : public RefCounted<ContextEvictionManager> {
61 public:
62     virtual ~ContextEvictionManager() {};
63
64     virtual void forciblyLoseOldestContext(const String& reason) = 0;
65     virtual IntSize oldestContextSize() = 0;
66 };
67
68 // Manages a rendering target (framebuffer + attachment) for a canvas.  Can publish its rendering
69 // results to a WebLayer for compositing.
70 class PLATFORM_EXPORT DrawingBuffer : public RefCounted<DrawingBuffer>, public WebExternalTextureLayerClient  {
71     // If we used CHROMIUM_image as the backing storage for our buffers,
72     // we need to know the mapping from texture id to image.
73     struct TextureInfo {
74         Platform3DObject textureId;
75         WGC3Duint imageId;
76
77         TextureInfo()
78             : textureId(0)
79             , imageId(0)
80         {
81         }
82     };
83
84     struct MailboxInfo : public RefCounted<MailboxInfo> {
85         WebExternalTextureMailbox mailbox;
86         TextureInfo textureInfo;
87         IntSize size;
88         // This keeps the parent drawing buffer alive as long as the compositor is
89         // referring to one of the mailboxes DrawingBuffer produced. The parent drawing buffer is
90         // cleared when the compositor returns the mailbox. See mailboxReleased().
91         RefPtr<DrawingBuffer> m_parentDrawingBuffer;
92     };
93 public:
94     enum PreserveDrawingBuffer {
95         Preserve,
96         Discard
97     };
98
99     static PassRefPtr<DrawingBuffer> create(PassOwnPtr<WebGraphicsContext3D>, const IntSize&, PreserveDrawingBuffer, WebGraphicsContext3D::Attributes requestedAttributes, PassRefPtr<ContextEvictionManager>);
100
101     virtual ~DrawingBuffer();
102
103     // Destruction will be completed after all mailboxes are released.
104     void beginDestruction();
105
106     // Issues a glClear() on all framebuffers associated with this DrawingBuffer. The caller is responsible for
107     // making the context current and setting the clear values and masks. Modifies the framebuffer binding.
108     void clearFramebuffers(GLbitfield clearMask);
109
110     // Given the desired buffer size, provides the largest dimensions that will fit in the pixel budget.
111     static IntSize adjustSize(const IntSize& desiredSize, const IntSize& curSize, int maxTextureSize);
112     bool reset(const IntSize&);
113     void bind();
114     IntSize size() const { return m_size; }
115
116     // Copies the multisample color buffer to the normal color buffer and leaves m_fbo bound.
117     void commit(long x = 0, long y = 0, long width = -1, long height = -1);
118
119     // commit should copy the full multisample buffer, and not respect the
120     // current scissor bounds. Track the state of the scissor test so that it
121     // can be disabled during calls to commit.
122     void setScissorEnabled(bool scissorEnabled) { m_scissorEnabled = scissorEnabled; }
123
124     // The DrawingBuffer needs to track the texture bound to texture unit 0.
125     // The bound texture is tracked to avoid costly queries during rendering.
126     void setTexture2DBinding(Platform3DObject texture) { m_texture2DBinding = texture; }
127
128     // The DrawingBuffer needs to track the currently bound framebuffer so it
129     // restore the binding when needed.
130     void setFramebufferBinding(Platform3DObject fbo) { m_framebufferBinding = fbo; }
131
132     // Track the currently active texture unit. Texture unit 0 is used as host for a scratch
133     // texture.
134     void setActiveTextureUnit(GLint textureUnit) { m_activeTextureUnit = textureUnit; }
135
136     bool multisample() const;
137
138     Platform3DObject framebuffer() const;
139
140     void markContentsChanged();
141     void markLayerComposited();
142     bool layerComposited() const;
143
144     WebLayer* platformLayer();
145     void paintCompositedResultsToCanvas(ImageBuffer*);
146
147     WebGraphicsContext3D* context();
148
149     // Returns the actual context attributes for this drawing buffer which may differ from the
150     // requested context attributes due to implementation limits.
151     WebGraphicsContext3D::Attributes getActualAttributes() const { return m_actualAttributes; }
152
153     // WebExternalTextureLayerClient implementation.
154     virtual bool prepareMailbox(WebExternalTextureMailbox*, WebExternalBitmap*) OVERRIDE;
155     virtual void mailboxReleased(const WebExternalTextureMailbox&, bool lostResource = false) OVERRIDE;
156
157     // Destroys the TEXTURE_2D binding for the owned context
158     bool copyToPlatformTexture(WebGraphicsContext3D*, Platform3DObject texture, GLenum internalFormat,
159         GLenum destType, GLint level, bool premultiplyAlpha, bool flipY, bool fromFrontBuffer = false);
160
161     void setPackAlignment(GLint param);
162
163     void paintRenderingResultsToCanvas(ImageBuffer*);
164     PassRefPtr<Uint8ClampedArray> paintRenderingResultsToImageData(int&, int&);
165
166 protected: // For unittests
167     DrawingBuffer(
168         PassOwnPtr<WebGraphicsContext3D>,
169         PassOwnPtr<Extensions3DUtil>,
170         bool multisampleExtensionSupported,
171         bool packedDepthStencilExtensionSupported,
172         PreserveDrawingBuffer,
173         WebGraphicsContext3D::Attributes requestedAttributes,
174         PassRefPtr<ContextEvictionManager>);
175
176     bool initialize(const IntSize&);
177
178 private:
179     void mailboxReleasedWhileDestructionInProgress(const WebExternalTextureMailbox&);
180
181     unsigned createColorTexture();
182     // Create the depth/stencil and multisample buffers, if needed.
183     void createSecondaryBuffers();
184     bool resizeFramebuffer(const IntSize&);
185     bool resizeMultisampleFramebuffer(const IntSize&);
186     void resizeDepthStencil(const IntSize&);
187
188     // Bind to the m_framebufferBinding if it's not 0.
189     void restoreFramebufferBinding();
190
191     void clearPlatformLayer();
192
193     PassRefPtr<MailboxInfo> recycledMailbox();
194     PassRefPtr<MailboxInfo> createNewMailbox(const TextureInfo&);
195     void deleteMailbox(const WebExternalTextureMailbox&);
196
197     // Updates the current size of the buffer, ensuring that s_currentResourceUsePixels is updated.
198     void setSize(const IntSize& size);
199
200     // Calculates the difference in pixels between the current buffer size and the proposed size.
201     static int pixelDelta(const IntSize& newSize, const IntSize& curSize);
202
203     // Given the desired buffer size, provides the largest dimensions that will fit in the pixel budget
204     // Returns true if the buffer will only fit if the oldest WebGL context is forcibly lost
205     IntSize adjustSizeWithContextEviction(const IntSize&, bool& evictContext);
206
207     void paintFramebufferToCanvas(int framebuffer, int width, int height, bool premultiplyAlpha, ImageBuffer*);
208
209     // This is the order of bytes to use when doing a readback.
210     enum ReadbackOrder {
211         ReadbackRGBA,
212         ReadbackSkia
213     };
214
215     // Helper function which does a readback from the currently-bound
216     // framebuffer into a buffer of a certain size with 4-byte pixels.
217     void readBackFramebuffer(unsigned char* pixels, int width, int height, ReadbackOrder, WebGLImageConversion::AlphaOp);
218
219     // Helper function to flip a bitmap vertically.
220     void flipVertically(uint8_t* data, int width, int height);
221
222     // Helper to texImage2D with pixel==0 case: pixels are initialized to 0.
223     // By default, alignment is 4, the OpenGL default setting.
224     void texImage2DResourceSafe(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, GLint alignment = 4);
225     // Allocate buffer storage to be sent to compositor using either texImage2D or CHROMIUM_image based on available support.
226     void allocateTextureMemory(TextureInfo*, const IntSize&);
227     void deleteChromiumImageForTexture(TextureInfo*);
228
229     PreserveDrawingBuffer m_preserveDrawingBuffer;
230     bool m_scissorEnabled;
231     Platform3DObject m_texture2DBinding;
232     Platform3DObject m_framebufferBinding;
233     GLenum m_activeTextureUnit;
234
235     OwnPtr<WebGraphicsContext3D> m_context;
236     OwnPtr<Extensions3DUtil> m_extensionsUtil;
237     IntSize m_size;
238     WebGraphicsContext3D::Attributes m_requestedAttributes;
239     bool m_multisampleExtensionSupported;
240     bool m_packedDepthStencilExtensionSupported;
241     Platform3DObject m_fbo;
242     // DrawingBuffer's output is double-buffered. m_colorBuffer is the back buffer.
243     TextureInfo m_colorBuffer;
244     TextureInfo m_frontColorBuffer;
245
246     // This is used when we have OES_packed_depth_stencil.
247     Platform3DObject m_depthStencilBuffer;
248
249     // These are used when we don't.
250     Platform3DObject m_depthBuffer;
251     Platform3DObject m_stencilBuffer;
252
253     // For multisampling.
254     Platform3DObject m_multisampleFBO;
255     Platform3DObject m_multisampleColorBuffer;
256
257     // True if our contents have been modified since the last presentation of this buffer.
258     bool m_contentsChanged;
259
260     // True if commit() has been called since the last time markContentsChanged() had been called.
261     bool m_contentsChangeCommitted;
262     bool m_layerComposited;
263
264     enum MultisampleMode {
265         None,
266         ImplicitResolve,
267         ExplicitResolve,
268     };
269
270     MultisampleMode m_multisampleMode;
271
272     WebGraphicsContext3D::Attributes m_actualAttributes;
273     unsigned m_internalColorFormat;
274     unsigned m_colorFormat;
275     unsigned m_internalRenderbufferFormat;
276     int m_maxTextureSize;
277     int m_sampleCount;
278     int m_packAlignment;
279     bool m_destructionInProgress;
280
281     OwnPtr<WebExternalTextureLayer> m_layer;
282
283     // All of the mailboxes that this DrawingBuffer has ever created.
284     Vector<RefPtr<MailboxInfo> > m_textureMailboxes;
285     // Mailboxes that were released by the compositor can be used again by this DrawingBuffer.
286     Deque<WebExternalTextureMailbox> m_recycledMailboxQueue;
287
288     RefPtr<ContextEvictionManager> m_contextEvictionManager;
289
290     // If the width and height of the Canvas's backing store don't
291     // match those that we were given in the most recent call to
292     // reshape(), then we need an intermediate bitmap to read back the
293     // frame buffer into. This seems to happen when CSS styles are
294     // used to resize the Canvas.
295     SkBitmap m_resizingBitmap;
296
297     // Used to flip a bitmap vertically.
298     Vector<uint8_t> m_scanline;
299 };
300
301 } // namespace blink
302
303 #endif // DrawingBuffer_h