1/*
2 * Copyright (C) 2009, 2014 Apple 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
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#ifndef GraphicsContext3D_h
27#define GraphicsContext3D_h
28
29#include "ANGLEWebKitBridge.h"
30#include "GraphicsTypes3D.h"
31#include "Image.h"
32#include "IntRect.h"
33#include "PlatformLayer.h"
34#include <memory>
35#include <wtf/HashMap.h>
36#include <wtf/ListHashSet.h>
37#include <wtf/Noncopyable.h>
38#include <wtf/RefCounted.h>
39#include <wtf/text/WTFString.h>
40
41#if USE(CA)
42#include "PlatformCALayer.h"
43#endif
44
45// FIXME: Find a better way to avoid the name confliction for NO_ERROR.
46#if PLATFORM(WIN)
47#undef NO_ERROR
48#elif PLATFORM(GTK)
49// This define is from the X11 headers, but it's used below, so we must undefine it.
50#undef VERSION
51#endif
52
53#if PLATFORM(COCOA)
54#if PLATFORM(IOS)
55#include <OpenGLES/ES2/gl.h>
56#ifdef __OBJC__
57#import <OpenGLES/EAGL.h>
58#endif // __OBJC__
59#endif // PLATFORM(IOS)
60#include <wtf/RetainPtr.h>
61OBJC_CLASS CALayer;
62OBJC_CLASS WebGLLayer;
63#elif PLATFORM(GTK) || PLATFORM(EFL)
64typedef unsigned int GLuint;
65#endif
66
67#if PLATFORM(IOS)
68#ifdef __OBJC__
69typedef EAGLContext* PlatformGraphicsContext3D;
70#else
71typedef void* PlatformGraphicsContext3D;
72#endif // __OBJC__
73#elif PLATFORM(MAC)
74typedef struct _CGLContextObject *CGLContextObj;
75
76typedef CGLContextObj PlatformGraphicsContext3D;
77#else
78typedef void* PlatformGraphicsContext3D;
79typedef void* PlatformGraphicsSurface3D;
80#endif
81
82// These are currently the same among all implementations.
83const PlatformGraphicsContext3D NullPlatformGraphicsContext3D = 0;
84const Platform3DObject NullPlatform3DObject = 0;
85
86namespace WebCore {
87class DrawingBuffer;
88class Extensions3D;
89#if USE(OPENGL_ES_2)
90class Extensions3DOpenGLES;
91#else
92class Extensions3DOpenGL;
93#endif
94class HostWindow;
95class Image;
96class ImageBuffer;
97class ImageSource;
98class ImageData;
99class IntRect;
100class IntSize;
101#if USE(CAIRO)
102class PlatformContextCairo;
103#endif
104
105typedef WTF::HashMap<CString, uint64_t> ShaderNameHash;
106
107struct ActiveInfo {
108    String name;
109    GC3Denum type;
110    GC3Dint size;
111};
112
113class GraphicsContext3DPrivate;
114
115class GraphicsContext3D : public RefCounted<GraphicsContext3D> {
116public:
117    enum {
118        DEPTH_BUFFER_BIT = 0x00000100,
119        STENCIL_BUFFER_BIT = 0x00000400,
120        COLOR_BUFFER_BIT = 0x00004000,
121        POINTS = 0x0000,
122        LINES = 0x0001,
123        LINE_LOOP = 0x0002,
124        LINE_STRIP = 0x0003,
125        TRIANGLES = 0x0004,
126        TRIANGLE_STRIP = 0x0005,
127        TRIANGLE_FAN = 0x0006,
128        ZERO = 0,
129        ONE = 1,
130        SRC_COLOR = 0x0300,
131        ONE_MINUS_SRC_COLOR = 0x0301,
132        SRC_ALPHA = 0x0302,
133        ONE_MINUS_SRC_ALPHA = 0x0303,
134        DST_ALPHA = 0x0304,
135        ONE_MINUS_DST_ALPHA = 0x0305,
136        DST_COLOR = 0x0306,
137        ONE_MINUS_DST_COLOR = 0x0307,
138        SRC_ALPHA_SATURATE = 0x0308,
139        FUNC_ADD = 0x8006,
140        BLEND_EQUATION = 0x8009,
141        BLEND_EQUATION_RGB = 0x8009,
142        BLEND_EQUATION_ALPHA = 0x883D,
143        FUNC_SUBTRACT = 0x800A,
144        FUNC_REVERSE_SUBTRACT = 0x800B,
145        BLEND_DST_RGB = 0x80C8,
146        BLEND_SRC_RGB = 0x80C9,
147        BLEND_DST_ALPHA = 0x80CA,
148        BLEND_SRC_ALPHA = 0x80CB,
149        CONSTANT_COLOR = 0x8001,
150        ONE_MINUS_CONSTANT_COLOR = 0x8002,
151        CONSTANT_ALPHA = 0x8003,
152        ONE_MINUS_CONSTANT_ALPHA = 0x8004,
153        BLEND_COLOR = 0x8005,
154        ARRAY_BUFFER = 0x8892,
155        ELEMENT_ARRAY_BUFFER = 0x8893,
156        ARRAY_BUFFER_BINDING = 0x8894,
157        ELEMENT_ARRAY_BUFFER_BINDING = 0x8895,
158        STREAM_DRAW = 0x88E0,
159        STATIC_DRAW = 0x88E4,
160        DYNAMIC_DRAW = 0x88E8,
161        BUFFER_SIZE = 0x8764,
162        BUFFER_USAGE = 0x8765,
163        CURRENT_VERTEX_ATTRIB = 0x8626,
164        FRONT = 0x0404,
165        BACK = 0x0405,
166        FRONT_AND_BACK = 0x0408,
167        TEXTURE_2D = 0x0DE1,
168        CULL_FACE = 0x0B44,
169        BLEND = 0x0BE2,
170        DITHER = 0x0BD0,
171        STENCIL_TEST = 0x0B90,
172        DEPTH_TEST = 0x0B71,
173        SCISSOR_TEST = 0x0C11,
174        POLYGON_OFFSET_FILL = 0x8037,
175        SAMPLE_ALPHA_TO_COVERAGE = 0x809E,
176        SAMPLE_COVERAGE = 0x80A0,
177        NO_ERROR = 0,
178        INVALID_ENUM = 0x0500,
179        INVALID_VALUE = 0x0501,
180        INVALID_OPERATION = 0x0502,
181        OUT_OF_MEMORY = 0x0505,
182        CW = 0x0900,
183        CCW = 0x0901,
184        LINE_WIDTH = 0x0B21,
185        ALIASED_POINT_SIZE_RANGE = 0x846D,
186        ALIASED_LINE_WIDTH_RANGE = 0x846E,
187        CULL_FACE_MODE = 0x0B45,
188        FRONT_FACE = 0x0B46,
189        DEPTH_RANGE = 0x0B70,
190        DEPTH_WRITEMASK = 0x0B72,
191        DEPTH_CLEAR_VALUE = 0x0B73,
192        DEPTH_FUNC = 0x0B74,
193        STENCIL_CLEAR_VALUE = 0x0B91,
194        STENCIL_FUNC = 0x0B92,
195        STENCIL_FAIL = 0x0B94,
196        STENCIL_PASS_DEPTH_FAIL = 0x0B95,
197        STENCIL_PASS_DEPTH_PASS = 0x0B96,
198        STENCIL_REF = 0x0B97,
199        STENCIL_VALUE_MASK = 0x0B93,
200        STENCIL_WRITEMASK = 0x0B98,
201        STENCIL_BACK_FUNC = 0x8800,
202        STENCIL_BACK_FAIL = 0x8801,
203        STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802,
204        STENCIL_BACK_PASS_DEPTH_PASS = 0x8803,
205        STENCIL_BACK_REF = 0x8CA3,
206        STENCIL_BACK_VALUE_MASK = 0x8CA4,
207        STENCIL_BACK_WRITEMASK = 0x8CA5,
208        VIEWPORT = 0x0BA2,
209        SCISSOR_BOX = 0x0C10,
210        COLOR_CLEAR_VALUE = 0x0C22,
211        COLOR_WRITEMASK = 0x0C23,
212        UNPACK_ALIGNMENT = 0x0CF5,
213        PACK_ALIGNMENT = 0x0D05,
214        MAX_TEXTURE_SIZE = 0x0D33,
215        MAX_VIEWPORT_DIMS = 0x0D3A,
216        SUBPIXEL_BITS = 0x0D50,
217        RED_BITS = 0x0D52,
218        GREEN_BITS = 0x0D53,
219        BLUE_BITS = 0x0D54,
220        ALPHA_BITS = 0x0D55,
221        DEPTH_BITS = 0x0D56,
222        STENCIL_BITS = 0x0D57,
223        POLYGON_OFFSET_UNITS = 0x2A00,
224        POLYGON_OFFSET_FACTOR = 0x8038,
225        TEXTURE_BINDING_2D = 0x8069,
226        SAMPLE_BUFFERS = 0x80A8,
227        SAMPLES = 0x80A9,
228        SAMPLE_COVERAGE_VALUE = 0x80AA,
229        SAMPLE_COVERAGE_INVERT = 0x80AB,
230        NUM_COMPRESSED_TEXTURE_FORMATS = 0x86A2,
231        COMPRESSED_TEXTURE_FORMATS = 0x86A3,
232        DONT_CARE = 0x1100,
233        FASTEST = 0x1101,
234        NICEST = 0x1102,
235        GENERATE_MIPMAP_HINT = 0x8192,
236        BYTE = 0x1400,
237        UNSIGNED_BYTE = 0x1401,
238        SHORT = 0x1402,
239        UNSIGNED_SHORT = 0x1403,
240        INT = 0x1404,
241        UNSIGNED_INT = 0x1405,
242        FLOAT = 0x1406,
243        HALF_FLOAT_OES = 0x8D61,
244        FIXED = 0x140C,
245        DEPTH_COMPONENT = 0x1902,
246        ALPHA = 0x1906,
247        RGB = 0x1907,
248        RGBA = 0x1908,
249        BGRA = 0x80E1,
250        LUMINANCE = 0x1909,
251        LUMINANCE_ALPHA = 0x190A,
252        UNSIGNED_SHORT_4_4_4_4 = 0x8033,
253        UNSIGNED_SHORT_5_5_5_1 = 0x8034,
254        UNSIGNED_SHORT_5_6_5 = 0x8363,
255        FRAGMENT_SHADER = 0x8B30,
256        VERTEX_SHADER = 0x8B31,
257        MAX_VERTEX_ATTRIBS = 0x8869,
258        MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB,
259        MAX_VARYING_VECTORS = 0x8DFC,
260        MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D,
261        MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C,
262        MAX_TEXTURE_IMAGE_UNITS = 0x8872,
263        MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD,
264        SHADER_TYPE = 0x8B4F,
265        DELETE_STATUS = 0x8B80,
266        LINK_STATUS = 0x8B82,
267        VALIDATE_STATUS = 0x8B83,
268        ATTACHED_SHADERS = 0x8B85,
269        ACTIVE_UNIFORMS = 0x8B86,
270        ACTIVE_UNIFORM_MAX_LENGTH = 0x8B87,
271        ACTIVE_ATTRIBUTES = 0x8B89,
272        ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8B8A,
273        SHADING_LANGUAGE_VERSION = 0x8B8C,
274        CURRENT_PROGRAM = 0x8B8D,
275        NEVER = 0x0200,
276        LESS = 0x0201,
277        EQUAL = 0x0202,
278        LEQUAL = 0x0203,
279        GREATER = 0x0204,
280        NOTEQUAL = 0x0205,
281        GEQUAL = 0x0206,
282        ALWAYS = 0x0207,
283        KEEP = 0x1E00,
284        REPLACE = 0x1E01,
285        INCR = 0x1E02,
286        DECR = 0x1E03,
287        INVERT = 0x150A,
288        INCR_WRAP = 0x8507,
289        DECR_WRAP = 0x8508,
290        VENDOR = 0x1F00,
291        RENDERER = 0x1F01,
292        VERSION = 0x1F02,
293        EXTENSIONS = 0x1F03,
294        NEAREST = 0x2600,
295        LINEAR = 0x2601,
296        NEAREST_MIPMAP_NEAREST = 0x2700,
297        LINEAR_MIPMAP_NEAREST = 0x2701,
298        NEAREST_MIPMAP_LINEAR = 0x2702,
299        LINEAR_MIPMAP_LINEAR = 0x2703,
300        TEXTURE_MAG_FILTER = 0x2800,
301        TEXTURE_MIN_FILTER = 0x2801,
302        TEXTURE_WRAP_S = 0x2802,
303        TEXTURE_WRAP_T = 0x2803,
304        TEXTURE = 0x1702,
305        TEXTURE_CUBE_MAP = 0x8513,
306        TEXTURE_BINDING_CUBE_MAP = 0x8514,
307        TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515,
308        TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516,
309        TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517,
310        TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518,
311        TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519,
312        TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A,
313        MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C,
314        TEXTURE0 = 0x84C0,
315        TEXTURE1 = 0x84C1,
316        TEXTURE2 = 0x84C2,
317        TEXTURE3 = 0x84C3,
318        TEXTURE4 = 0x84C4,
319        TEXTURE5 = 0x84C5,
320        TEXTURE6 = 0x84C6,
321        TEXTURE7 = 0x84C7,
322        TEXTURE8 = 0x84C8,
323        TEXTURE9 = 0x84C9,
324        TEXTURE10 = 0x84CA,
325        TEXTURE11 = 0x84CB,
326        TEXTURE12 = 0x84CC,
327        TEXTURE13 = 0x84CD,
328        TEXTURE14 = 0x84CE,
329        TEXTURE15 = 0x84CF,
330        TEXTURE16 = 0x84D0,
331        TEXTURE17 = 0x84D1,
332        TEXTURE18 = 0x84D2,
333        TEXTURE19 = 0x84D3,
334        TEXTURE20 = 0x84D4,
335        TEXTURE21 = 0x84D5,
336        TEXTURE22 = 0x84D6,
337        TEXTURE23 = 0x84D7,
338        TEXTURE24 = 0x84D8,
339        TEXTURE25 = 0x84D9,
340        TEXTURE26 = 0x84DA,
341        TEXTURE27 = 0x84DB,
342        TEXTURE28 = 0x84DC,
343        TEXTURE29 = 0x84DD,
344        TEXTURE30 = 0x84DE,
345        TEXTURE31 = 0x84DF,
346        ACTIVE_TEXTURE = 0x84E0,
347        REPEAT = 0x2901,
348        CLAMP_TO_EDGE = 0x812F,
349        MIRRORED_REPEAT = 0x8370,
350        FLOAT_VEC2 = 0x8B50,
351        FLOAT_VEC3 = 0x8B51,
352        FLOAT_VEC4 = 0x8B52,
353        INT_VEC2 = 0x8B53,
354        INT_VEC3 = 0x8B54,
355        INT_VEC4 = 0x8B55,
356        BOOL = 0x8B56,
357        BOOL_VEC2 = 0x8B57,
358        BOOL_VEC3 = 0x8B58,
359        BOOL_VEC4 = 0x8B59,
360        FLOAT_MAT2 = 0x8B5A,
361        FLOAT_MAT3 = 0x8B5B,
362        FLOAT_MAT4 = 0x8B5C,
363        SAMPLER_2D = 0x8B5E,
364        SAMPLER_CUBE = 0x8B60,
365        VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622,
366        VERTEX_ATTRIB_ARRAY_SIZE = 0x8623,
367        VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624,
368        VERTEX_ATTRIB_ARRAY_TYPE = 0x8625,
369        VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A,
370        VERTEX_ATTRIB_ARRAY_POINTER = 0x8645,
371        VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F,
372        COMPILE_STATUS = 0x8B81,
373        INFO_LOG_LENGTH = 0x8B84,
374        SHADER_SOURCE_LENGTH = 0x8B88,
375        SHADER_COMPILER = 0x8DFA,
376        SHADER_BINARY_FORMATS = 0x8DF8,
377        NUM_SHADER_BINARY_FORMATS = 0x8DF9,
378        LOW_FLOAT = 0x8DF0,
379        MEDIUM_FLOAT = 0x8DF1,
380        HIGH_FLOAT = 0x8DF2,
381        LOW_INT = 0x8DF3,
382        MEDIUM_INT = 0x8DF4,
383        HIGH_INT = 0x8DF5,
384        FRAMEBUFFER = 0x8D40,
385        RENDERBUFFER = 0x8D41,
386        RGBA4 = 0x8056,
387        RGB5_A1 = 0x8057,
388        RGB565 = 0x8D62,
389        DEPTH_COMPONENT16 = 0x81A5,
390        STENCIL_INDEX = 0x1901,
391        STENCIL_INDEX8 = 0x8D48,
392        DEPTH_STENCIL = 0x84F9,
393        UNSIGNED_INT_24_8 = 0x84FA,
394        DEPTH24_STENCIL8 = 0x88F0,
395        RENDERBUFFER_WIDTH = 0x8D42,
396        RENDERBUFFER_HEIGHT = 0x8D43,
397        RENDERBUFFER_INTERNAL_FORMAT = 0x8D44,
398        RENDERBUFFER_RED_SIZE = 0x8D50,
399        RENDERBUFFER_GREEN_SIZE = 0x8D51,
400        RENDERBUFFER_BLUE_SIZE = 0x8D52,
401        RENDERBUFFER_ALPHA_SIZE = 0x8D53,
402        RENDERBUFFER_DEPTH_SIZE = 0x8D54,
403        RENDERBUFFER_STENCIL_SIZE = 0x8D55,
404        FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0,
405        FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1,
406        FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2,
407        FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3,
408        COLOR_ATTACHMENT0 = 0x8CE0,
409        DEPTH_ATTACHMENT = 0x8D00,
410        STENCIL_ATTACHMENT = 0x8D20,
411        DEPTH_STENCIL_ATTACHMENT = 0x821A,
412        NONE = 0,
413        FRAMEBUFFER_COMPLETE = 0x8CD5,
414        FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6,
415        FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7,
416        FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8CD9,
417        FRAMEBUFFER_UNSUPPORTED = 0x8CDD,
418        FRAMEBUFFER_BINDING = 0x8CA6,
419        RENDERBUFFER_BINDING = 0x8CA7,
420        MAX_RENDERBUFFER_SIZE = 0x84E8,
421        INVALID_FRAMEBUFFER_OPERATION = 0x0506,
422
423        // WebGL-specific enums
424        UNPACK_FLIP_Y_WEBGL = 0x9240,
425        UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241,
426        CONTEXT_LOST_WEBGL = 0x9242,
427        UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243,
428        BROWSER_DEFAULT_WEBGL = 0x9244,
429        VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE = 0x88FE
430    };
431
432    // Context creation attributes.
433    struct Attributes {
434        Attributes()
435            : alpha(true)
436            , depth(true)
437            , stencil(false)
438            , antialias(true)
439            , premultipliedAlpha(true)
440            , preserveDrawingBuffer(false)
441            , noExtensions(false)
442            , shareResources(true)
443            , preferDiscreteGPU(false)
444            , multithreaded(false)
445            , forceSoftwareRenderer(false)
446        {
447        }
448
449        bool alpha;
450        bool depth;
451        bool stencil;
452        bool antialias;
453        bool premultipliedAlpha;
454        bool preserveDrawingBuffer;
455        bool noExtensions;
456        bool shareResources;
457        bool preferDiscreteGPU;
458        bool multithreaded;
459        bool forceSoftwareRenderer;
460    };
461
462    enum RenderStyle {
463        RenderOffscreen,
464        RenderDirectlyToHostWindow,
465        RenderToCurrentGLContext
466    };
467
468    class ContextLostCallback {
469    public:
470        virtual void onContextLost() = 0;
471        virtual ~ContextLostCallback() {}
472    };
473
474    class ErrorMessageCallback {
475    public:
476        virtual void onErrorMessage(const String& message, GC3Dint id) = 0;
477        virtual ~ErrorMessageCallback() { }
478    };
479
480    void setContextLostCallback(std::unique_ptr<ContextLostCallback>);
481    void setErrorMessageCallback(std::unique_ptr<ErrorMessageCallback>);
482
483    static PassRefPtr<GraphicsContext3D> create(Attributes, HostWindow*, RenderStyle = RenderOffscreen);
484    static PassRefPtr<GraphicsContext3D> createForCurrentGLContext();
485    ~GraphicsContext3D();
486
487#if PLATFORM(COCOA)
488    PlatformGraphicsContext3D platformGraphicsContext3D() const { return m_contextObj; }
489    Platform3DObject platformTexture() const { return m_compositorTexture; }
490    CALayer* platformLayer() const { return reinterpret_cast<CALayer*>(m_webGLLayer.get()); }
491#else
492    PlatformGraphicsContext3D platformGraphicsContext3D();
493    Platform3DObject platformTexture() const;
494    PlatformLayer* platformLayer() const;
495#endif
496
497    bool makeContextCurrent();
498
499    // With multisampling on, blit from multisampleFBO to regular FBO.
500    void prepareTexture();
501
502    // Equivalent to ::glTexImage2D(). Allows pixels==0 with no allocation.
503    void texImage2DDirect(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, const void* pixels);
504
505    // Helper to texImage2D with pixel==0 case: pixels are initialized to 0.
506    // Return true if no GL error is synthesized.
507    // By default, alignment is 4, the OpenGL default setting.
508    bool texImage2DResourceSafe(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, GC3Dint alignment = 4);
509
510    bool isGLES2Compliant() const;
511
512    //----------------------------------------------------------------------
513    // Helpers for texture uploading and pixel readback.
514    //
515
516    // Computes the components per pixel and bytes per component
517    // for the given format and type combination. Returns false if
518    // either was an invalid enum.
519    static bool computeFormatAndTypeParameters(GC3Denum format,
520                                               GC3Denum type,
521                                               unsigned int* componentsPerPixel,
522                                               unsigned int* bytesPerComponent);
523
524    // Computes the image size in bytes. If paddingInBytes is not null, padding
525    // is also calculated in return. Returns NO_ERROR if succeed, otherwise
526    // return the suggested GL error indicating the cause of the failure:
527    //   INVALID_VALUE if width/height is negative or overflow happens.
528    //   INVALID_ENUM if format/type is illegal.
529    static GC3Denum computeImageSizeInBytes(GC3Denum format,
530                                     GC3Denum type,
531                                     GC3Dsizei width,
532                                     GC3Dsizei height,
533                                     GC3Dint alignment,
534                                     unsigned int* imageSizeInBytes,
535                                     unsigned int* paddingInBytes);
536
537    // Extracts the contents of the given ImageData into the passed Vector,
538    // packing the pixel data according to the given format and type,
539    // and obeying the flipY and premultiplyAlpha flags. Returns true
540    // upon success.
541    static bool extractImageData(ImageData*,
542                          GC3Denum format,
543                          GC3Denum type,
544                          bool flipY,
545                          bool premultiplyAlpha,
546                          Vector<uint8_t>& data);
547
548    // Helper function which extracts the user-supplied texture
549    // data, applying the flipY and premultiplyAlpha parameters.
550    // If the data is not tightly packed according to the passed
551    // unpackAlignment, the output data will be tightly packed.
552    // Returns true if successful, false if any error occurred.
553    static bool extractTextureData(unsigned int width, unsigned int height,
554                            GC3Denum format, GC3Denum type,
555                            unsigned int unpackAlignment,
556                            bool flipY, bool premultiplyAlpha,
557                            const void* pixels,
558                            Vector<uint8_t>& data);
559
560
561    // Attempt to enumerate all possible native image formats to
562    // reduce the amount of temporary allocations during texture
563    // uploading. This enum must be public because it is accessed
564    // by non-member functions.
565    enum DataFormat {
566        DataFormatRGBA8 = 0,
567        DataFormatRGBA16Little,
568        DataFormatRGBA16Big,
569        DataFormatRGBA16F,
570        DataFormatRGBA32F,
571        DataFormatRGB8,
572        DataFormatRGB16Little,
573        DataFormatRGB16Big,
574        DataFormatRGB16F,
575        DataFormatRGB32F,
576        DataFormatBGR8,
577        DataFormatBGRA8,
578        DataFormatBGRA16Little,
579        DataFormatBGRA16Big,
580        DataFormatARGB8,
581        DataFormatARGB16Little,
582        DataFormatARGB16Big,
583        DataFormatABGR8,
584        DataFormatRGBA5551,
585        DataFormatRGBA4444,
586        DataFormatRGB565,
587        DataFormatR8,
588        DataFormatR16Little,
589        DataFormatR16Big,
590        DataFormatR16F,
591        DataFormatR32F,
592        DataFormatRA8,
593        DataFormatRA16Little,
594        DataFormatRA16Big,
595        DataFormatRA16F,
596        DataFormatRA32F,
597        DataFormatAR8,
598        DataFormatAR16Little,
599        DataFormatAR16Big,
600        DataFormatA8,
601        DataFormatA16Little,
602        DataFormatA16Big,
603        DataFormatA16F,
604        DataFormatA32F,
605        DataFormatNumFormats
606    };
607
608    ALWAYS_INLINE static bool hasAlpha(DataFormat format)
609    {
610        return format == GraphicsContext3D::DataFormatA8
611            || format == GraphicsContext3D::DataFormatA16F
612            || format == GraphicsContext3D::DataFormatA32F
613            || format == GraphicsContext3D::DataFormatRA8
614            || format == GraphicsContext3D::DataFormatAR8
615            || format == GraphicsContext3D::DataFormatRA16F
616            || format == GraphicsContext3D::DataFormatRA32F
617            || format == GraphicsContext3D::DataFormatRGBA8
618            || format == GraphicsContext3D::DataFormatBGRA8
619            || format == GraphicsContext3D::DataFormatARGB8
620            || format == GraphicsContext3D::DataFormatABGR8
621            || format == GraphicsContext3D::DataFormatRGBA16F
622            || format == GraphicsContext3D::DataFormatRGBA32F
623            || format == GraphicsContext3D::DataFormatRGBA4444
624            || format == GraphicsContext3D::DataFormatRGBA5551;
625    }
626
627    ALWAYS_INLINE static bool hasColor(DataFormat format)
628    {
629        return format == GraphicsContext3D::DataFormatRGBA8
630            || format == GraphicsContext3D::DataFormatRGBA16F
631            || format == GraphicsContext3D::DataFormatRGBA32F
632            || format == GraphicsContext3D::DataFormatRGB8
633            || format == GraphicsContext3D::DataFormatRGB16F
634            || format == GraphicsContext3D::DataFormatRGB32F
635            || format == GraphicsContext3D::DataFormatBGR8
636            || format == GraphicsContext3D::DataFormatBGRA8
637            || format == GraphicsContext3D::DataFormatARGB8
638            || format == GraphicsContext3D::DataFormatABGR8
639            || format == GraphicsContext3D::DataFormatRGBA5551
640            || format == GraphicsContext3D::DataFormatRGBA4444
641            || format == GraphicsContext3D::DataFormatRGB565
642            || format == GraphicsContext3D::DataFormatR8
643            || format == GraphicsContext3D::DataFormatR16F
644            || format == GraphicsContext3D::DataFormatR32F
645            || format == GraphicsContext3D::DataFormatRA8
646            || format == GraphicsContext3D::DataFormatRA16F
647            || format == GraphicsContext3D::DataFormatRA32F
648            || format == GraphicsContext3D::DataFormatAR8;
649    }
650
651    // Check if the format is one of the formats from the ImageData or DOM elements.
652    // The formats from ImageData is always RGBA8.
653    // The formats from DOM elements vary with Graphics ports. It can only be RGBA8 or BGRA8 for non-CG port while a little more for CG port.
654    static ALWAYS_INLINE bool srcFormatComesFromDOMElementOrImageData(DataFormat SrcFormat)
655    {
656#if USE(CG)
657#if CPU(BIG_ENDIAN)
658    return SrcFormat == DataFormatRGBA8 || SrcFormat == DataFormatARGB8 || SrcFormat == DataFormatRGB8
659        || SrcFormat == DataFormatRA8 || SrcFormat == DataFormatAR8 || SrcFormat == DataFormatR8 || SrcFormat == DataFormatA8;
660#else
661    // That LITTLE_ENDIAN case has more possible formats than BIG_ENDIAN case is because some decoded image data is actually big endian
662    // even on little endian architectures.
663    return SrcFormat == DataFormatBGRA8 || SrcFormat == DataFormatABGR8 || SrcFormat == DataFormatBGR8
664        || SrcFormat == DataFormatRGBA8 || SrcFormat == DataFormatARGB8 || SrcFormat == DataFormatRGB8
665        || SrcFormat == DataFormatR8 || SrcFormat == DataFormatA8
666        || SrcFormat == DataFormatRA8 || SrcFormat == DataFormatAR8;
667#endif
668#else
669    return SrcFormat == DataFormatBGRA8 || SrcFormat == DataFormatRGBA8;
670#endif
671    }
672
673    //----------------------------------------------------------------------
674    // Entry points for WebGL.
675    //
676
677    void activeTexture(GC3Denum texture);
678    void attachShader(Platform3DObject program, Platform3DObject shader);
679    void bindAttribLocation(Platform3DObject, GC3Duint index, const String& name);
680    void bindBuffer(GC3Denum target, Platform3DObject);
681    void bindFramebuffer(GC3Denum target, Platform3DObject);
682    void bindRenderbuffer(GC3Denum target, Platform3DObject);
683    void bindTexture(GC3Denum target, Platform3DObject);
684    void blendColor(GC3Dclampf red, GC3Dclampf green, GC3Dclampf blue, GC3Dclampf alpha);
685    void blendEquation(GC3Denum mode);
686    void blendEquationSeparate(GC3Denum modeRGB, GC3Denum modeAlpha);
687    void blendFunc(GC3Denum sfactor, GC3Denum dfactor);
688    void blendFuncSeparate(GC3Denum srcRGB, GC3Denum dstRGB, GC3Denum srcAlpha, GC3Denum dstAlpha);
689
690    void bufferData(GC3Denum target, GC3Dsizeiptr size, GC3Denum usage);
691    void bufferData(GC3Denum target, GC3Dsizeiptr size, const void* data, GC3Denum usage);
692    void bufferSubData(GC3Denum target, GC3Dintptr offset, GC3Dsizeiptr size, const void* data);
693
694    GC3Denum checkFramebufferStatus(GC3Denum target);
695    void clear(GC3Dbitfield mask);
696    void clearColor(GC3Dclampf red, GC3Dclampf green, GC3Dclampf blue, GC3Dclampf alpha);
697    void clearDepth(GC3Dclampf depth);
698    void clearStencil(GC3Dint s);
699    void colorMask(GC3Dboolean red, GC3Dboolean green, GC3Dboolean blue, GC3Dboolean alpha);
700    void compileShader(Platform3DObject);
701
702    void compressedTexImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Dsizei imageSize, const void* data);
703    void compressedTexSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Dsizei imageSize, const void* data);
704    void copyTexImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height, GC3Dint border);
705    void copyTexSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height);
706    void cullFace(GC3Denum mode);
707    void depthFunc(GC3Denum func);
708    void depthMask(GC3Dboolean flag);
709    void depthRange(GC3Dclampf zNear, GC3Dclampf zFar);
710    void detachShader(Platform3DObject, Platform3DObject);
711    void disable(GC3Denum cap);
712    void disableVertexAttribArray(GC3Duint index);
713    void drawArrays(GC3Denum mode, GC3Dint first, GC3Dsizei count);
714    void drawElements(GC3Denum mode, GC3Dsizei count, GC3Denum type, GC3Dintptr offset);
715
716    void enable(GC3Denum cap);
717    void enableVertexAttribArray(GC3Duint index);
718    void finish();
719    void flush();
720    void framebufferRenderbuffer(GC3Denum target, GC3Denum attachment, GC3Denum renderbuffertarget, Platform3DObject);
721    void framebufferTexture2D(GC3Denum target, GC3Denum attachment, GC3Denum textarget, Platform3DObject, GC3Dint level);
722    void frontFace(GC3Denum mode);
723    void generateMipmap(GC3Denum target);
724
725    bool getActiveAttrib(Platform3DObject program, GC3Duint index, ActiveInfo&);
726    bool getActiveAttribImpl(Platform3DObject program, GC3Duint index, ActiveInfo&);
727    bool getActiveUniform(Platform3DObject program, GC3Duint index, ActiveInfo&);
728    bool getActiveUniformImpl(Platform3DObject program, GC3Duint index, ActiveInfo&);
729    void getAttachedShaders(Platform3DObject program, GC3Dsizei maxCount, GC3Dsizei* count, Platform3DObject* shaders);
730    GC3Dint getAttribLocation(Platform3DObject, const String& name);
731    void getBooleanv(GC3Denum pname, GC3Dboolean* value);
732    void getBufferParameteriv(GC3Denum target, GC3Denum pname, GC3Dint* value);
733    Attributes getContextAttributes();
734    GC3Denum getError();
735    void getFloatv(GC3Denum pname, GC3Dfloat* value);
736    void getFramebufferAttachmentParameteriv(GC3Denum target, GC3Denum attachment, GC3Denum pname, GC3Dint* value);
737    void getIntegerv(GC3Denum pname, GC3Dint* value);
738    void getProgramiv(Platform3DObject program, GC3Denum pname, GC3Dint* value);
739    void getNonBuiltInActiveSymbolCount(Platform3DObject program, GC3Denum pname, GC3Dint* value);
740    String getProgramInfoLog(Platform3DObject);
741    String getUnmangledInfoLog(Platform3DObject[2], GC3Dsizei, const String&);
742    void getRenderbufferParameteriv(GC3Denum target, GC3Denum pname, GC3Dint* value);
743    void getShaderiv(Platform3DObject, GC3Denum pname, GC3Dint* value);
744    String getShaderInfoLog(Platform3DObject);
745    void getShaderPrecisionFormat(GC3Denum shaderType, GC3Denum precisionType, GC3Dint* range, GC3Dint* precision);
746    String getShaderSource(Platform3DObject);
747    String getString(GC3Denum name);
748    void getTexParameterfv(GC3Denum target, GC3Denum pname, GC3Dfloat* value);
749    void getTexParameteriv(GC3Denum target, GC3Denum pname, GC3Dint* value);
750    void getUniformfv(Platform3DObject program, GC3Dint location, GC3Dfloat* value);
751    void getUniformiv(Platform3DObject program, GC3Dint location, GC3Dint* value);
752    GC3Dint getUniformLocation(Platform3DObject, const String& name);
753    void getVertexAttribfv(GC3Duint index, GC3Denum pname, GC3Dfloat* value);
754    void getVertexAttribiv(GC3Duint index, GC3Denum pname, GC3Dint* value);
755    GC3Dsizeiptr getVertexAttribOffset(GC3Duint index, GC3Denum pname);
756
757    void hint(GC3Denum target, GC3Denum mode);
758    GC3Dboolean isBuffer(Platform3DObject);
759    GC3Dboolean isEnabled(GC3Denum cap);
760    GC3Dboolean isFramebuffer(Platform3DObject);
761    GC3Dboolean isProgram(Platform3DObject);
762    GC3Dboolean isRenderbuffer(Platform3DObject);
763    GC3Dboolean isShader(Platform3DObject);
764    GC3Dboolean isTexture(Platform3DObject);
765    void lineWidth(GC3Dfloat);
766    void linkProgram(Platform3DObject);
767    void pixelStorei(GC3Denum pname, GC3Dint param);
768    void polygonOffset(GC3Dfloat factor, GC3Dfloat units);
769
770    void readPixels(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Denum type, void* data);
771
772    void releaseShaderCompiler();
773
774    void renderbufferStorage(GC3Denum target, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height);
775    void sampleCoverage(GC3Dclampf value, GC3Dboolean invert);
776    void scissor(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height);
777    void shaderSource(Platform3DObject, const String& string);
778    void stencilFunc(GC3Denum func, GC3Dint ref, GC3Duint mask);
779    void stencilFuncSeparate(GC3Denum face, GC3Denum func, GC3Dint ref, GC3Duint mask);
780    void stencilMask(GC3Duint mask);
781    void stencilMaskSeparate(GC3Denum face, GC3Duint mask);
782    void stencilOp(GC3Denum fail, GC3Denum zfail, GC3Denum zpass);
783    void stencilOpSeparate(GC3Denum face, GC3Denum fail, GC3Denum zfail, GC3Denum zpass);
784
785    bool texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, const void* pixels);
786    void texParameterf(GC3Denum target, GC3Denum pname, GC3Dfloat param);
787    void texParameteri(GC3Denum target, GC3Denum pname, GC3Dint param);
788    void texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Denum type, const void* pixels);
789
790    void uniform1f(GC3Dint location, GC3Dfloat x);
791    void uniform1fv(GC3Dint location, GC3Dsizei, GC3Dfloat* v);
792    void uniform1i(GC3Dint location, GC3Dint x);
793    void uniform1iv(GC3Dint location, GC3Dsizei, GC3Dint* v);
794    void uniform2f(GC3Dint location, GC3Dfloat x, GC3Dfloat y);
795    void uniform2fv(GC3Dint location, GC3Dsizei, GC3Dfloat* v);
796    void uniform2i(GC3Dint location, GC3Dint x, GC3Dint y);
797    void uniform2iv(GC3Dint location, GC3Dsizei, GC3Dint* v);
798    void uniform3f(GC3Dint location, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z);
799    void uniform3fv(GC3Dint location, GC3Dsizei, GC3Dfloat* v);
800    void uniform3i(GC3Dint location, GC3Dint x, GC3Dint y, GC3Dint z);
801    void uniform3iv(GC3Dint location, GC3Dsizei, GC3Dint* v);
802    void uniform4f(GC3Dint location, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z, GC3Dfloat w);
803    void uniform4fv(GC3Dint location, GC3Dsizei, GC3Dfloat* v);
804    void uniform4i(GC3Dint location, GC3Dint x, GC3Dint y, GC3Dint z, GC3Dint w);
805    void uniform4iv(GC3Dint location, GC3Dsizei, GC3Dint* v);
806    void uniformMatrix2fv(GC3Dint location, GC3Dsizei, GC3Dboolean transpose, GC3Dfloat* value);
807    void uniformMatrix3fv(GC3Dint location, GC3Dsizei, GC3Dboolean transpose, GC3Dfloat* value);
808    void uniformMatrix4fv(GC3Dint location, GC3Dsizei, GC3Dboolean transpose, GC3Dfloat* value);
809
810    void useProgram(Platform3DObject);
811    void validateProgram(Platform3DObject);
812    bool precisionsMatch(Platform3DObject vertexShader, Platform3DObject fragmentShader) const;
813
814    void vertexAttrib1f(GC3Duint index, GC3Dfloat x);
815    void vertexAttrib1fv(GC3Duint index, GC3Dfloat* values);
816    void vertexAttrib2f(GC3Duint index, GC3Dfloat x, GC3Dfloat y);
817    void vertexAttrib2fv(GC3Duint index, GC3Dfloat* values);
818    void vertexAttrib3f(GC3Duint index, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z);
819    void vertexAttrib3fv(GC3Duint index, GC3Dfloat* values);
820    void vertexAttrib4f(GC3Duint index, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z, GC3Dfloat w);
821    void vertexAttrib4fv(GC3Duint index, GC3Dfloat* values);
822    void vertexAttribPointer(GC3Duint index, GC3Dint size, GC3Denum type, GC3Dboolean normalized,
823                             GC3Dsizei stride, GC3Dintptr offset);
824
825    void viewport(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height);
826
827    void reshape(int width, int height);
828
829    void drawArraysInstanced(GC3Denum mode, GC3Dint first, GC3Dsizei count, GC3Dsizei primcount);
830    void drawElementsInstanced(GC3Denum mode, GC3Dsizei count, GC3Denum type, GC3Dintptr offset, GC3Dsizei primcount);
831    void vertexAttribDivisor(GC3Duint index, GC3Duint divisor);
832
833#if PLATFORM(GTK) || PLATFORM(EFL) || USE(CAIRO)
834    void paintToCanvas(const unsigned char* imagePixels, int imageWidth, int imageHeight,
835                       int canvasWidth, int canvasHeight, PlatformContextCairo* context);
836#elif USE(CG)
837    void paintToCanvas(const unsigned char* imagePixels, int imageWidth, int imageHeight,
838                       int canvasWidth, int canvasHeight, GraphicsContext*);
839#endif
840
841    void markContextChanged();
842    void markLayerComposited();
843    bool layerComposited() const;
844
845    void paintRenderingResultsToCanvas(ImageBuffer*, DrawingBuffer*);
846    PassRefPtr<ImageData> paintRenderingResultsToImageData(DrawingBuffer*);
847    bool paintCompositedResultsToCanvas(ImageBuffer*);
848
849#if PLATFORM(IOS)
850    void endPaint();
851#endif
852
853    // Support for buffer creation and deletion
854    Platform3DObject createBuffer();
855    Platform3DObject createFramebuffer();
856    Platform3DObject createProgram();
857    Platform3DObject createRenderbuffer();
858    Platform3DObject createShader(GC3Denum);
859    Platform3DObject createTexture();
860
861    void deleteBuffer(Platform3DObject);
862    void deleteFramebuffer(Platform3DObject);
863    void deleteProgram(Platform3DObject);
864    void deleteRenderbuffer(Platform3DObject);
865    void deleteShader(Platform3DObject);
866    void deleteTexture(Platform3DObject);
867
868    // Synthesizes an OpenGL error which will be returned from a
869    // later call to getError. This is used to emulate OpenGL ES
870    // 2.0 behavior on the desktop and to enforce additional error
871    // checking mandated by WebGL.
872    //
873    // Per the behavior of glGetError, this stores at most one
874    // instance of any given error, and returns them from calls to
875    // getError in the order they were added.
876    void synthesizeGLError(GC3Denum error);
877
878    // Read real OpenGL errors, and move them to the synthetic
879    // error list. Return true if at least one error is moved.
880    bool moveErrorsToSyntheticErrorList();
881
882    // Support for extensions. Returns a non-null object, though not
883    // all methods it contains may necessarily be supported on the
884    // current hardware. Must call Extensions3D::supports() to
885    // determine this.
886    Extensions3D* getExtensions();
887
888    IntSize getInternalFramebufferSize() const;
889
890    static unsigned getClearBitsByAttachmentType(GC3Denum);
891    static unsigned getClearBitsByFormat(GC3Denum);
892
893    enum ChannelBits {
894        ChannelRed = 1,
895        ChannelGreen = 2,
896        ChannelBlue = 4,
897        ChannelAlpha = 8,
898        ChannelDepth = 16,
899        ChannelStencil = 32,
900        ChannelRGB = ChannelRed | ChannelGreen | ChannelBlue,
901        ChannelRGBA = ChannelRGB | ChannelAlpha,
902    };
903
904    static unsigned getChannelBitsByFormat(GC3Denum);
905
906    // Possible alpha operations that may need to occur during
907    // pixel packing. FIXME: kAlphaDoUnmultiply is lossy and must
908    // be removed.
909    enum AlphaOp {
910        AlphaDoNothing = 0,
911        AlphaDoPremultiply = 1,
912        AlphaDoUnmultiply = 2
913    };
914
915    enum ImageHtmlDomSource {
916        HtmlDomImage = 0,
917        HtmlDomCanvas = 1,
918        HtmlDomVideo = 2,
919        HtmlDomNone = 3
920    };
921
922    // Packs the contents of the given Image which is passed in |pixels| into the passed Vector
923    // according to the given format and type, and obeying the flipY and AlphaOp flags.
924    // Returns true upon success.
925    static bool packImageData(Image*, const void* pixels, GC3Denum format, GC3Denum type, bool flipY, AlphaOp, DataFormat sourceFormat, unsigned width, unsigned height, unsigned sourceUnpackAlignment, Vector<uint8_t>& data);
926
927    class ImageExtractor {
928    public:
929        ImageExtractor(Image*, ImageHtmlDomSource, bool premultiplyAlpha, bool ignoreGammaAndColorProfile);
930
931        // Each platform must provide an implementation of this method to deallocate or release resources
932        // associated with the image if needed.
933        ~ImageExtractor();
934
935        bool extractSucceeded() { return m_extractSucceeded; }
936        const void* imagePixelData() { return m_imagePixelData; }
937        unsigned imageWidth() { return m_imageWidth; }
938        unsigned imageHeight() { return m_imageHeight; }
939        DataFormat imageSourceFormat() { return m_imageSourceFormat; }
940        AlphaOp imageAlphaOp() { return m_alphaOp; }
941        unsigned imageSourceUnpackAlignment() { return m_imageSourceUnpackAlignment; }
942        ImageHtmlDomSource imageHtmlDomSource() { return m_imageHtmlDomSource; }
943    private:
944        // Each platform must provide an implementation of this method.
945        // Extracts the image and keeps track of its status, such as width, height, Source Alignment, format and AlphaOp etc,
946        // needs to lock the resources or relevant data if needed and returns true upon success
947        bool extractImage(bool premultiplyAlpha, bool ignoreGammaAndColorProfile);
948
949#if USE(CAIRO)
950        ImageSource* m_decoder;
951        RefPtr<cairo_surface_t> m_imageSurface;
952#elif USE(CG)
953        CGImageRef m_cgImage;
954        RetainPtr<CGImageRef> m_decodedImage;
955        RetainPtr<CFDataRef> m_pixelData;
956        std::unique_ptr<uint8_t[]> m_formalizedRGBA8Data;
957#endif
958        Image* m_image;
959        ImageHtmlDomSource m_imageHtmlDomSource;
960        bool m_extractSucceeded;
961        const void* m_imagePixelData;
962        unsigned m_imageWidth;
963        unsigned m_imageHeight;
964        DataFormat m_imageSourceFormat;
965        AlphaOp m_alphaOp;
966        unsigned m_imageSourceUnpackAlignment;
967    };
968
969private:
970    GraphicsContext3D(Attributes, HostWindow*, RenderStyle = RenderOffscreen);
971    static int numActiveContexts;
972
973    // Helper for packImageData/extractImageData/extractTextureData which implement packing of pixel
974    // data into the specified OpenGL destination format and type.
975    // A sourceUnpackAlignment of zero indicates that the source
976    // data is tightly packed. Non-zero values may take a slow path.
977    // Destination data will have no gaps between rows.
978    static bool packPixels(const uint8_t* sourceData, DataFormat sourceDataFormat, unsigned width, unsigned height, unsigned sourceUnpackAlignment, unsigned destinationFormat, unsigned destinationType, AlphaOp, void* destinationData, bool flipY);
979
980    // Take into account the user's requested context creation attributes,
981    // in particular stencil and antialias, and determine which could or
982    // could not be honored based on the capabilities of the OpenGL
983    // implementation.
984    void validateDepthStencil(const char* packedDepthStencilExtension);
985    void validateAttributes();
986
987    // Read rendering results into a pixel array with the same format as the
988    // backbuffer.
989    void readRenderingResults(unsigned char* pixels, int pixelsSize);
990    void readPixelsAndConvertToBGRAIfNecessary(int x, int y, int width, int height, unsigned char* pixels);
991
992#if PLATFORM(IOS)
993    bool setRenderbufferStorageFromDrawable(GC3Dsizei width, GC3Dsizei height);
994#endif
995
996    bool reshapeFBOs(const IntSize&);
997    void resolveMultisamplingIfNecessary(const IntRect& = IntRect());
998#if PLATFORM(EFL) && USE(GRAPHICS_SURFACE)
999    void createGraphicsSurfaces(const IntSize&);
1000#endif
1001
1002    int m_currentWidth, m_currentHeight;
1003    bool isResourceSafe();
1004
1005#if PLATFORM(COCOA)
1006    RetainPtr<WebGLLayer> m_webGLLayer;
1007    PlatformGraphicsContext3D m_contextObj;
1008#endif
1009
1010#if PLATFORM(WIN) && USE(CA)
1011    RefPtr<PlatformCALayer> m_webGLLayer;
1012#endif
1013
1014    struct SymbolInfo {
1015        SymbolInfo()
1016            : type(0)
1017            , size(0)
1018            , precision(SH_PRECISION_UNDEFINED)
1019            , staticUse(0)
1020        {
1021        }
1022
1023        SymbolInfo(GC3Denum type, int size, const String& mappedName, ShPrecisionType precision, int staticUse)
1024            : type(type)
1025            , size(size)
1026            , mappedName(mappedName)
1027            , precision(precision)
1028            , staticUse(staticUse)
1029        {
1030        }
1031
1032        bool operator==(SymbolInfo& other) const
1033        {
1034            return type == other.type && size == other.size && mappedName == other.mappedName;
1035        }
1036
1037        GC3Denum type;
1038        int size;
1039        String mappedName;
1040        ShPrecisionType precision;
1041        int staticUse;
1042    };
1043
1044    typedef HashMap<String, SymbolInfo> ShaderSymbolMap;
1045
1046    struct ShaderSourceEntry {
1047        GC3Denum type;
1048        String source;
1049        String translatedSource;
1050        String log;
1051        bool isValid;
1052        ShaderSymbolMap attributeMap;
1053        ShaderSymbolMap uniformMap;
1054        ShaderSymbolMap varyingMap;
1055        ShaderSourceEntry()
1056            : type(VERTEX_SHADER)
1057            , isValid(false)
1058        {
1059        }
1060
1061        ShaderSymbolMap& symbolMap(enum ANGLEShaderSymbolType symbolType)
1062        {
1063            ASSERT(symbolType == SHADER_SYMBOL_TYPE_ATTRIBUTE || symbolType == SHADER_SYMBOL_TYPE_UNIFORM || symbolType == SHADER_SYMBOL_TYPE_VARYING);
1064            if (symbolType == SHADER_SYMBOL_TYPE_ATTRIBUTE)
1065                return attributeMap;
1066            if (symbolType == SHADER_SYMBOL_TYPE_VARYING)
1067                return varyingMap;
1068            return uniformMap;
1069        }
1070    };
1071
1072    typedef HashMap<Platform3DObject, ShaderSourceEntry> ShaderSourceMap;
1073    ShaderSourceMap m_shaderSourceMap;
1074
1075    struct ActiveShaderSymbolCounts {
1076        Vector<GC3Dint> filteredToActualAttributeIndexMap;
1077        Vector<GC3Dint> filteredToActualUniformIndexMap;
1078
1079        ActiveShaderSymbolCounts()
1080        {
1081        }
1082
1083        GC3Dint countForType(GC3Denum activeType)
1084        {
1085            ASSERT(activeType == ACTIVE_ATTRIBUTES || activeType == ACTIVE_UNIFORMS);
1086            if (activeType == ACTIVE_ATTRIBUTES)
1087                return filteredToActualAttributeIndexMap.size();
1088
1089            return filteredToActualUniformIndexMap.size();
1090        }
1091    };
1092    typedef HashMap<Platform3DObject, ActiveShaderSymbolCounts> ShaderProgramSymbolCountMap;
1093    ShaderProgramSymbolCountMap m_shaderProgramSymbolCountMap;
1094
1095    typedef HashMap<String, String> HashedSymbolMap;
1096    HashedSymbolMap m_possiblyUnusedAttributeMap;
1097
1098    String mappedSymbolName(Platform3DObject program, ANGLEShaderSymbolType, const String& name);
1099    String mappedSymbolName(Platform3DObject shaders[2], size_t count, const String& name);
1100    String originalSymbolName(Platform3DObject program, ANGLEShaderSymbolType, const String& name);
1101
1102    ANGLEWebKitBridge m_compiler;
1103
1104    OwnPtr<ShaderNameHash> nameHashMapForShaders;
1105
1106#if ((PLATFORM(GTK) || PLATFORM(EFL) || PLATFORM(WIN)) && USE(OPENGL_ES_2))
1107    friend class Extensions3DOpenGLES;
1108    OwnPtr<Extensions3DOpenGLES> m_extensions;
1109#else
1110    friend class Extensions3DOpenGL;
1111    OwnPtr<Extensions3DOpenGL> m_extensions;
1112#endif
1113    friend class Extensions3DOpenGLCommon;
1114
1115    Attributes m_attrs;
1116    RenderStyle m_renderStyle;
1117    Vector<Vector<float>> m_vertexArray;
1118
1119    GC3Duint m_texture;
1120    GC3Duint m_compositorTexture;
1121    GC3Duint m_fbo;
1122
1123    GC3Duint m_depthBuffer;
1124    GC3Duint m_stencilBuffer;
1125    GC3Duint m_depthStencilBuffer;
1126
1127    bool m_layerComposited;
1128    GC3Duint m_internalColorFormat;
1129
1130    struct GraphicsContext3DState {
1131        GraphicsContext3DState()
1132            : boundFBO(0)
1133            , activeTexture(GraphicsContext3D::TEXTURE0)
1134            , boundTexture0(0)
1135        { }
1136
1137        GC3Duint boundFBO;
1138        GC3Denum activeTexture;
1139        GC3Duint boundTexture0;
1140    };
1141
1142    GraphicsContext3DState m_state;
1143
1144    // For multisampling
1145    GC3Duint m_multisampleFBO;
1146    GC3Duint m_multisampleDepthStencilBuffer;
1147    GC3Duint m_multisampleColorBuffer;
1148
1149    // Errors raised by synthesizeGLError().
1150    ListHashSet<GC3Denum> m_syntheticErrors;
1151
1152    friend class GraphicsContext3DPrivate;
1153    std::unique_ptr<GraphicsContext3DPrivate> m_private;
1154};
1155
1156} // namespace WebCore
1157
1158#endif // GraphicsContext3D_h
1159