Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / gpu / command_buffer / client / gles2_implementation.h
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef GPU_COMMAND_BUFFER_CLIENT_GLES2_IMPLEMENTATION_H_
6 #define GPU_COMMAND_BUFFER_CLIENT_GLES2_IMPLEMENTATION_H_
7
8 #include <GLES2/gl2.h>
9
10 #include <map>
11 #include <queue>
12 #include <set>
13 #include <string>
14 #include <vector>
15
16 #include "base/compiler_specific.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/weak_ptr.h"
19 #include "gles2_impl_export.h"
20 #include "gpu/command_buffer/client/buffer_tracker.h"
21 #include "gpu/command_buffer/client/client_context_state.h"
22 #include "gpu/command_buffer/client/context_support.h"
23 #include "gpu/command_buffer/client/gles2_cmd_helper.h"
24 #include "gpu/command_buffer/client/gles2_interface.h"
25 #include "gpu/command_buffer/client/gpu_memory_buffer_tracker.h"
26 #include "gpu/command_buffer/client/mapped_memory.h"
27 #include "gpu/command_buffer/client/query_tracker.h"
28 #include "gpu/command_buffer/client/ref_counted.h"
29 #include "gpu/command_buffer/client/ring_buffer.h"
30 #include "gpu/command_buffer/client/share_group.h"
31 #include "gpu/command_buffer/common/capabilities.h"
32 #include "gpu/command_buffer/common/debug_marker_manager.h"
33 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
34
35 #if !defined(NDEBUG) && !defined(__native_client__) && !defined(GLES2_CONFORMANCE_TESTS)  // NOLINT
36   #if defined(GLES2_INLINE_OPTIMIZATION)
37     // TODO(gman): Replace with macros that work with inline optmization.
38     #define GPU_CLIENT_SINGLE_THREAD_CHECK()
39     #define GPU_CLIENT_LOG(args)
40     #define GPU_CLIENT_LOG_CODE_BLOCK(code)
41     #define GPU_CLIENT_DCHECK_CODE_BLOCK(code)
42   #else
43     #include "base/logging.h"
44     #define GPU_CLIENT_SINGLE_THREAD_CHECK() SingleThreadChecker checker(this);
45     #define GPU_CLIENT_LOG(args)  DLOG_IF(INFO, debug_) << args;
46     #define GPU_CLIENT_LOG_CODE_BLOCK(code) code
47     #define GPU_CLIENT_DCHECK_CODE_BLOCK(code) code
48     #define GPU_CLIENT_DEBUG
49   #endif
50 #else
51   #define GPU_CLIENT_SINGLE_THREAD_CHECK()
52   #define GPU_CLIENT_LOG(args)
53   #define GPU_CLIENT_LOG_CODE_BLOCK(code)
54   #define GPU_CLIENT_DCHECK_CODE_BLOCK(code)
55 #endif
56
57 #if defined(GPU_CLIENT_DEBUG)
58   // Set to 1 to have the client fail when a GL error is generated.
59   // This helps find bugs in the renderer since the debugger stops on the error.
60 #  if 0
61 #    define GL_CLIENT_FAIL_GL_ERRORS
62 #  endif
63 #endif
64
65 // Check that destination pointers point to initialized memory.
66 // When the context is lost, calling GL function has no effect so if destination
67 // pointers point to initialized memory it can often lead to crash bugs. eg.
68 //
69 // GLsizei len;
70 // glGetShaderSource(shader, max_size, &len, buffer);
71 // std::string src(buffer, buffer + len);  // len can be uninitialized here!!!
72 //
73 // Because this check is not official GL this check happens only on Chrome code,
74 // not Pepper.
75 //
76 // If it was up to us we'd just always write to the destination but the OpenGL
77 // spec defines the behavior of OpenGL functions, not us. :-(
78 #if defined(__native_client__) || defined(GLES2_CONFORMANCE_TESTS)
79   #define GPU_CLIENT_VALIDATE_DESTINATION_INITALIZATION_ASSERT(v)
80   #define GPU_CLIENT_DCHECK(v)
81 #elif defined(GPU_DCHECK)
82   #define GPU_CLIENT_VALIDATE_DESTINATION_INITALIZATION_ASSERT(v) GPU_DCHECK(v)
83   #define GPU_CLIENT_DCHECK(v) GPU_DCHECK(v)
84 #elif defined(DCHECK)
85   #define GPU_CLIENT_VALIDATE_DESTINATION_INITALIZATION_ASSERT(v) DCHECK(v)
86   #define GPU_CLIENT_DCHECK(v) DCHECK(v)
87 #else
88   #define GPU_CLIENT_VALIDATE_DESTINATION_INITALIZATION_ASSERT(v) ASSERT(v)
89   #define GPU_CLIENT_DCHECK(v) ASSERT(v)
90 #endif
91
92 #define GPU_CLIENT_VALIDATE_DESTINATION_INITALIZATION(type, ptr) \
93     GPU_CLIENT_VALIDATE_DESTINATION_INITALIZATION_ASSERT(ptr && \
94         (ptr[0] == static_cast<type>(0) || ptr[0] == static_cast<type>(-1)));
95
96 #define GPU_CLIENT_VALIDATE_DESTINATION_OPTIONAL_INITALIZATION(type, ptr) \
97     GPU_CLIENT_VALIDATE_DESTINATION_INITALIZATION_ASSERT(!ptr || \
98         (ptr[0] == static_cast<type>(0) || ptr[0] == static_cast<type>(-1)));
99
100 struct GLUniformDefinitionCHROMIUM;
101
102 namespace gpu {
103
104 class GpuControl;
105 class ScopedTransferBufferPtr;
106 class TransferBufferInterface;
107
108 namespace gles2 {
109
110 class ImageFactory;
111 class VertexArrayObjectManager;
112
113 // This class emulates GLES2 over command buffers. It can be used by a client
114 // program so that the program does not need deal with shared memory and command
115 // buffer management. See gl2_lib.h.  Note that there is a performance gain to
116 // be had by changing your code to use command buffers directly by using the
117 // GLES2CmdHelper but that entails changing your code to use and deal with
118 // shared memory and synchronization issues.
119 class GLES2_IMPL_EXPORT GLES2Implementation
120     : NON_EXPORTED_BASE(public GLES2Interface),
121       NON_EXPORTED_BASE(public ContextSupport) {
122  public:
123   enum MappedMemoryLimit {
124     kNoLimit = MappedMemoryManager::kNoLimit,
125   };
126   class ErrorMessageCallback {
127    public:
128     virtual ~ErrorMessageCallback() { }
129     virtual void OnErrorMessage(const char* msg, int id) = 0;
130   };
131
132   // Stores GL state that never changes.
133   struct GLES2_IMPL_EXPORT GLStaticState {
134     GLStaticState();
135     ~GLStaticState();
136
137     struct GLES2_IMPL_EXPORT IntState {
138       IntState();
139       GLint max_combined_texture_image_units;
140       GLint max_cube_map_texture_size;
141       GLint max_fragment_uniform_vectors;
142       GLint max_renderbuffer_size;
143       GLint max_texture_image_units;
144       GLint max_texture_size;
145       GLint max_varying_vectors;
146       GLint max_vertex_attribs;
147       GLint max_vertex_texture_image_units;
148       GLint max_vertex_uniform_vectors;
149       GLint num_compressed_texture_formats;
150       GLint num_shader_binary_formats;
151       GLint bind_generates_resource_chromium;
152     };
153     IntState int_state;
154
155     typedef std::pair<GLenum,GLenum> ShaderPrecisionKey;
156     typedef std::map<ShaderPrecisionKey,
157                      cmds::GetShaderPrecisionFormat::Result>
158         ShaderPrecisionMap;
159     ShaderPrecisionMap shader_precisions;
160   };
161
162   // The maxiumum result size from simple GL get commands.
163   static const size_t kMaxSizeOfSimpleResult = 16 * sizeof(uint32);  // NOLINT.
164
165   // used for testing only. If more things are reseved add them here.
166   static const unsigned int kStartingOffset = kMaxSizeOfSimpleResult;
167
168   // Size in bytes to issue async flush for transfer buffer.
169   static const unsigned int kSizeToFlush = 256 * 1024;
170
171   // The bucket used for results. Public for testing only.
172   static const uint32 kResultBucketId = 1;
173
174   // Alignment of allocations.
175   static const unsigned int kAlignment = 4;
176
177   // GL names for the buffers used to emulate client side buffers.
178   static const GLuint kClientSideArrayId = 0xFEDCBA98u;
179   static const GLuint kClientSideElementArrayId = 0xFEDCBA99u;
180
181   // Number of swap buffers allowed before waiting.
182   static const size_t kMaxSwapBuffers = 2;
183
184   GLES2Implementation(GLES2CmdHelper* helper,
185                       ShareGroup* share_group,
186                       TransferBufferInterface* transfer_buffer,
187                       bool bind_generates_resource,
188                       bool lose_context_when_out_of_memory,
189                       GpuControl* gpu_control);
190
191   virtual ~GLES2Implementation();
192
193   bool Initialize(
194       unsigned int starting_transfer_buffer_size,
195       unsigned int min_transfer_buffer_size,
196       unsigned int max_transfer_buffer_size,
197       unsigned int mapped_memory_limit);
198
199   // The GLES2CmdHelper being used by this GLES2Implementation. You can use
200   // this to issue cmds at a lower level for certain kinds of optimization.
201   GLES2CmdHelper* helper() const;
202
203   // Gets client side generated errors.
204   GLenum GetClientSideGLError();
205
206   // Include the auto-generated part of this class. We split this because
207   // it means we can easily edit the non-auto generated parts right here in
208   // this file instead of having to edit some template or the code generator.
209   #include "gpu/command_buffer/client/gles2_implementation_autogen.h"
210
211   virtual void DisableVertexAttribArray(GLuint index) OVERRIDE;
212   virtual void EnableVertexAttribArray(GLuint index) OVERRIDE;
213   virtual void GetVertexAttribfv(
214       GLuint index, GLenum pname, GLfloat* params) OVERRIDE;
215   virtual void GetVertexAttribiv(
216       GLuint index, GLenum pname, GLint* params) OVERRIDE;
217
218   // ContextSupport implementation.
219   virtual void Swap() OVERRIDE;
220   virtual void PartialSwapBuffers(const gfx::Rect& sub_buffer) OVERRIDE;
221   virtual void SetSwapBuffersCompleteCallback(
222       const base::Closure& swap_buffers_complete_callback)
223           OVERRIDE;
224   virtual void ScheduleOverlayPlane(int plane_z_order,
225                                     gfx::OverlayTransform plane_transform,
226                                     unsigned overlay_texture_id,
227                                     const gfx::Rect& display_bounds,
228                                     const gfx::RectF& uv_rect) OVERRIDE;
229
230   void GetProgramInfoCHROMIUMHelper(GLuint program, std::vector<int8>* result);
231   GLint GetAttribLocationHelper(GLuint program, const char* name);
232   GLint GetUniformLocationHelper(GLuint program, const char* name);
233   bool GetActiveAttribHelper(
234       GLuint program, GLuint index, GLsizei bufsize, GLsizei* length,
235       GLint* size, GLenum* type, char* name);
236   bool GetActiveUniformHelper(
237       GLuint program, GLuint index, GLsizei bufsize, GLsizei* length,
238       GLint* size, GLenum* type, char* name);
239
240   void FreeUnusedSharedMemory();
241   void FreeEverything();
242
243   // ContextSupport implementation.
244   virtual void SignalSyncPoint(uint32 sync_point,
245                                const base::Closure& callback) OVERRIDE;
246   virtual void SignalQuery(uint32 query,
247                            const base::Closure& callback) OVERRIDE;
248   virtual void SetSurfaceVisible(bool visible) OVERRIDE;
249   virtual void SendManagedMemoryStats(const ManagedMemoryStats& stats)
250       OVERRIDE;
251
252   void SetErrorMessageCallback(ErrorMessageCallback* callback) {
253     error_message_callback_ = callback;
254   }
255
256   ShareGroup* share_group() const {
257     return share_group_.get();
258   }
259
260   const Capabilities& capabilities() const {
261     return capabilities_;
262   }
263
264   GpuControl* gpu_control() {
265     return gpu_control_;
266   }
267
268   ShareGroupContextData* share_group_context_data() {
269     return &share_group_context_data_;
270   }
271
272  private:
273   friend class GLES2ImplementationTest;
274   friend class VertexArrayObjectManager;
275
276   // Used to track whether an extension is available
277   enum ExtensionStatus {
278       kAvailableExtensionStatus,
279       kUnavailableExtensionStatus,
280       kUnknownExtensionStatus
281   };
282
283   // Base class for mapped resources.
284   struct MappedResource {
285     MappedResource(GLenum _access, int _shm_id, void* mem, unsigned int offset)
286         : access(_access),
287           shm_id(_shm_id),
288           shm_memory(mem),
289           shm_offset(offset) {
290     }
291
292     // access mode. Currently only GL_WRITE_ONLY is valid
293     GLenum access;
294
295     // Shared memory ID for buffer.
296     int shm_id;
297
298     // Address of shared memory
299     void* shm_memory;
300
301     // Offset of shared memory
302     unsigned int shm_offset;
303   };
304
305   // Used to track mapped textures.
306   struct MappedTexture : public MappedResource {
307     MappedTexture(
308         GLenum access,
309         int shm_id,
310         void* shm_mem,
311         unsigned int shm_offset,
312         GLenum _target,
313         GLint _level,
314         GLint _xoffset,
315         GLint _yoffset,
316         GLsizei _width,
317         GLsizei _height,
318         GLenum _format,
319         GLenum _type)
320         : MappedResource(access, shm_id, shm_mem, shm_offset),
321           target(_target),
322           level(_level),
323           xoffset(_xoffset),
324           yoffset(_yoffset),
325           width(_width),
326           height(_height),
327           format(_format),
328           type(_type) {
329     }
330
331     // These match the arguments to TexSubImage2D.
332     GLenum target;
333     GLint level;
334     GLint xoffset;
335     GLint yoffset;
336     GLsizei width;
337     GLsizei height;
338     GLenum format;
339     GLenum type;
340   };
341
342   // Used to track mapped buffers.
343   struct MappedBuffer : public MappedResource {
344     MappedBuffer(
345         GLenum access,
346         int shm_id,
347         void* shm_mem,
348         unsigned int shm_offset,
349         GLenum _target,
350         GLintptr _offset,
351         GLsizeiptr _size)
352         : MappedResource(access, shm_id, shm_mem, shm_offset),
353           target(_target),
354           offset(_offset),
355           size(_size) {
356     }
357
358     // These match the arguments to BufferSubData.
359     GLenum target;
360     GLintptr offset;
361     GLsizeiptr size;
362   };
363
364   struct TextureUnit {
365     TextureUnit()
366         : bound_texture_2d(0),
367           bound_texture_cube_map(0),
368           bound_texture_external_oes(0) {}
369
370     // texture currently bound to this unit's GL_TEXTURE_2D with glBindTexture
371     GLuint bound_texture_2d;
372
373     // texture currently bound to this unit's GL_TEXTURE_CUBE_MAP with
374     // glBindTexture
375     GLuint bound_texture_cube_map;
376
377     // texture currently bound to this unit's GL_TEXTURE_EXTERNAL_OES with
378     // glBindTexture
379     GLuint bound_texture_external_oes;
380   };
381
382   // Checks for single threaded access.
383   class SingleThreadChecker {
384    public:
385     SingleThreadChecker(GLES2Implementation* gles2_implementation);
386     ~SingleThreadChecker();
387
388    private:
389     GLES2Implementation* gles2_implementation_;
390   };
391
392   // Gets the value of the result.
393   template <typename T>
394   T GetResultAs() {
395     return static_cast<T>(GetResultBuffer());
396   }
397
398   void* GetResultBuffer();
399   int32 GetResultShmId();
400   uint32 GetResultShmOffset();
401
402   bool QueryAndCacheStaticState();
403
404   // Helpers used to batch synchronous GetIntergerv calls with other
405   // synchronous calls.
406   struct GetMultipleIntegervState {
407     GetMultipleIntegervState(const GLenum* pnames, GLuint pnames_count,
408                              GLint* results, GLsizeiptr results_size)
409        : pnames(pnames),
410          pnames_count(pnames_count),
411          results(results),
412          results_size(results_size)
413     { }
414     // inputs
415     const GLenum* pnames;
416     GLuint pnames_count;
417     // outputs
418     GLint* results;
419     GLsizeiptr results_size;
420     // transfer buffer
421     int num_results;
422     int transfer_buffer_size_needed;
423     void* buffer;
424     void* results_buffer;
425   };
426   bool GetMultipleIntegervSetup(
427       GetMultipleIntegervState* state);
428   void GetMultipleIntegervRequest(
429       GetMultipleIntegervState* state);
430   void GetMultipleIntegervOnCompleted(
431       GetMultipleIntegervState* state);
432
433   // Helpers used to batch synchronous GetShaderPrecision calls with other
434   // synchronous calls.
435   struct GetAllShaderPrecisionFormatsState {
436     GetAllShaderPrecisionFormatsState(
437         const GLenum (*precision_params)[2],
438         int precision_params_count)
439         : precision_params(precision_params),
440           precision_params_count(precision_params_count)
441     { }
442     const GLenum (*precision_params)[2];
443     int precision_params_count;
444     int transfer_buffer_size_needed;
445     void* results_buffer;
446   };
447   void GetAllShaderPrecisionFormatsSetup(
448       GetAllShaderPrecisionFormatsState* state);
449   void GetAllShaderPrecisionFormatsRequest(
450       GetAllShaderPrecisionFormatsState* state);
451   void GetAllShaderPrecisionFormatsOnCompleted(
452       GetAllShaderPrecisionFormatsState* state);
453
454   // Lazily determines if GL_ANGLE_pack_reverse_row_order is available
455   bool IsAnglePackReverseRowOrderAvailable();
456   bool IsChromiumFramebufferMultisampleAvailable();
457
458   bool IsExtensionAvailableHelper(
459       const char* extension, ExtensionStatus* status);
460
461   // Gets the GLError through our wrapper.
462   GLenum GetGLError();
463
464   // Sets our wrapper for the GLError.
465   void SetGLError(GLenum error, const char* function_name, const char* msg);
466   void SetGLErrorInvalidEnum(
467       const char* function_name, GLenum value, const char* label);
468
469   // Returns the last error and clears it. Useful for debugging.
470   const std::string& GetLastError() {
471     return last_error_;
472   }
473
474   // Waits for all commands to execute.
475   void WaitForCmd();
476
477   // TODO(gman): These bucket functions really seem like they belong in
478   // CommandBufferHelper (or maybe BucketHelper?). Unfortunately they need
479   // a transfer buffer to function which is currently managed by this class.
480
481   // Gets the contents of a bucket.
482   bool GetBucketContents(uint32 bucket_id, std::vector<int8>* data);
483
484   // Sets the contents of a bucket.
485   void SetBucketContents(uint32 bucket_id, const void* data, size_t size);
486
487   // Sets the contents of a bucket as a string.
488   void SetBucketAsCString(uint32 bucket_id, const char* str);
489
490   // Gets the contents of a bucket as a string. Returns false if there is no
491   // string available which is a separate case from the empty string.
492   bool GetBucketAsString(uint32 bucket_id, std::string* str);
493
494   // Sets the contents of a bucket as a string.
495   void SetBucketAsString(uint32 bucket_id, const std::string& str);
496
497   // Returns true if id is reserved.
498   bool IsBufferReservedId(GLuint id);
499   bool IsFramebufferReservedId(GLuint id) { return false;  }
500   bool IsRenderbufferReservedId(GLuint id) { return false; }
501   bool IsTextureReservedId(GLuint id) { return false; }
502   bool IsVertexArrayReservedId(GLuint id) { return false; }
503   bool IsProgramReservedId(GLuint id) { return false; }
504
505   bool BindBufferHelper(GLenum target, GLuint texture);
506   bool BindFramebufferHelper(GLenum target, GLuint texture);
507   bool BindRenderbufferHelper(GLenum target, GLuint texture);
508   bool BindTextureHelper(GLenum target, GLuint texture);
509   bool BindVertexArrayOESHelper(GLuint array);
510   bool UseProgramHelper(GLuint program);
511
512   void GenBuffersHelper(GLsizei n, const GLuint* buffers);
513   void GenFramebuffersHelper(GLsizei n, const GLuint* framebuffers);
514   void GenRenderbuffersHelper(GLsizei n, const GLuint* renderbuffers);
515   void GenTexturesHelper(GLsizei n, const GLuint* textures);
516   void GenVertexArraysOESHelper(GLsizei n, const GLuint* arrays);
517   void GenQueriesEXTHelper(GLsizei n, const GLuint* queries);
518
519   void DeleteBuffersHelper(GLsizei n, const GLuint* buffers);
520   void DeleteFramebuffersHelper(GLsizei n, const GLuint* framebuffers);
521   void DeleteRenderbuffersHelper(GLsizei n, const GLuint* renderbuffers);
522   void DeleteTexturesHelper(GLsizei n, const GLuint* textures);
523   bool DeleteProgramHelper(GLuint program);
524   bool DeleteShaderHelper(GLuint shader);
525   void DeleteQueriesEXTHelper(GLsizei n, const GLuint* queries);
526   void DeleteVertexArraysOESHelper(GLsizei n, const GLuint* arrays);
527
528   void DeleteBuffersStub(GLsizei n, const GLuint* buffers);
529   void DeleteFramebuffersStub(GLsizei n, const GLuint* framebuffers);
530   void DeleteRenderbuffersStub(GLsizei n, const GLuint* renderbuffers);
531   void DeleteTexturesStub(GLsizei n, const GLuint* textures);
532   void DeleteProgramStub(GLsizei n, const GLuint* programs);
533   void DeleteShaderStub(GLsizei n, const GLuint* shaders);
534   // TODO(gman): Remove this as queries are not shared.
535   void DeleteQueriesStub(GLsizei n, const GLuint* queries);
536   void DeleteVertexArraysOESStub(GLsizei n, const GLuint* arrays);
537
538   void BufferDataHelper(
539       GLenum target, GLsizeiptr size, const void* data, GLenum usage);
540   void BufferSubDataHelper(
541       GLenum target, GLintptr offset, GLsizeiptr size, const void* data);
542   void BufferSubDataHelperImpl(
543       GLenum target, GLintptr offset, GLsizeiptr size, const void* data,
544       ScopedTransferBufferPtr* buffer);
545
546   GLuint CreateImageCHROMIUMHelper(GLsizei width,
547                                    GLsizei height,
548                                    GLenum internalformat,
549                                    GLenum usage);
550   void DestroyImageCHROMIUMHelper(GLuint image_id);
551   void* MapImageCHROMIUMHelper(GLuint image_id);
552   void UnmapImageCHROMIUMHelper(GLuint image_id);
553   void GetImageParameterivCHROMIUMHelper(
554       GLuint image_id, GLenum pname, GLint* params);
555
556   // Helper for GetVertexAttrib
557   bool GetVertexAttribHelper(GLuint index, GLenum pname, uint32* param);
558
559   GLuint GetMaxValueInBufferCHROMIUMHelper(
560       GLuint buffer_id, GLsizei count, GLenum type, GLuint offset);
561
562   void RestoreElementAndArrayBuffers(bool restore);
563   void RestoreArrayBuffer(bool restrore);
564
565   // The pixels pointer should already account for unpack skip rows and skip
566   // pixels.
567   void TexSubImage2DImpl(
568       GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width,
569       GLsizei height, GLenum format, GLenum type, uint32 unpadded_row_size,
570       const void* pixels, uint32 pixels_padded_row_size, GLboolean internal,
571       ScopedTransferBufferPtr* buffer, uint32 buffer_padded_row_size);
572
573   // Helpers for query functions.
574   bool GetHelper(GLenum pname, GLint* params);
575   bool GetBooleanvHelper(GLenum pname, GLboolean* params);
576   bool GetBufferParameterivHelper(GLenum target, GLenum pname, GLint* params);
577   bool GetFloatvHelper(GLenum pname, GLfloat* params);
578   bool GetFramebufferAttachmentParameterivHelper(
579       GLenum target, GLenum attachment, GLenum pname, GLint* params);
580   bool GetIntegervHelper(GLenum pname, GLint* params);
581   bool GetProgramivHelper(GLuint program, GLenum pname, GLint* params);
582   bool GetRenderbufferParameterivHelper(
583       GLenum target, GLenum pname, GLint* params);
584   bool GetShaderivHelper(GLuint shader, GLenum pname, GLint* params);
585   bool GetTexParameterfvHelper(GLenum target, GLenum pname, GLfloat* params);
586   bool GetTexParameterivHelper(GLenum target, GLenum pname, GLint* params);
587   const GLubyte* GetStringHelper(GLenum name);
588
589   bool IsExtensionAvailable(const char* ext);
590
591   // Caches certain capabilties state. Return true if cached.
592   bool SetCapabilityState(GLenum cap, bool enabled);
593
594   IdHandlerInterface* GetIdHandler(int id_namespace) const;
595
596   void FinishHelper();
597
598   void RunIfContextNotLost(const base::Closure& callback);
599
600   void OnSwapBuffersComplete();
601
602   // Validate if an offset is valid, i.e., non-negative and fit into 32-bit.
603   // If not, generate an approriate error, and return false.
604   bool ValidateOffset(const char* func, GLintptr offset);
605
606   // Validate if a size is valid, i.e., non-negative and fit into 32-bit.
607   // If not, generate an approriate error, and return false.
608   bool ValidateSize(const char* func, GLsizeiptr offset);
609
610   // Remove the transfer buffer from the buffer tracker. For buffers used
611   // asynchronously the memory is free:ed if the upload has completed. For
612   // other buffers, the memory is either free:ed immediately or free:ed pending
613   // a token.
614   void RemoveTransferBuffer(BufferTracker::Buffer* buffer);
615
616   // Returns true if the async upload token has passed.
617   //
618   // NOTE: This will detect wrapped async tokens by checking if the most
619   // significant  bit of async token to check is 1 but the last read is 0, i.e.
620   // the uint32 wrapped.
621   bool HasAsyncUploadTokenPassed(uint32 token) const {
622     return async_upload_sync_->HasAsyncUploadTokenPassed(token);
623   }
624
625   // Get the next async upload token.
626   uint32 NextAsyncUploadToken();
627
628   // Ensure that the shared memory used for synchronizing async upload tokens
629   // has been mapped.
630   //
631   // Returns false on error, true on success.
632   bool EnsureAsyncUploadSync();
633
634   // Checks the last read asynchronously upload token and frees any unmanaged
635   // transfer buffer that has its async token passed.
636   void PollAsyncUploads();
637
638   // Free every async upload buffer. If some async upload buffer is still in use
639   // wait for them to finish before freeing.
640   void FreeAllAsyncUploadBuffers();
641
642   bool GetBoundPixelTransferBuffer(
643       GLenum target, const char* function_name, GLuint* buffer_id);
644   BufferTracker::Buffer* GetBoundPixelUnpackTransferBufferIfValid(
645       GLuint buffer_id,
646       const char* function_name, GLuint offset, GLsizei size);
647
648   const std::string& GetLogPrefix() const;
649
650 #if defined(GL_CLIENT_FAIL_GL_ERRORS)
651   void CheckGLError();
652   void FailGLError(GLenum error);
653 #else
654   void CheckGLError() { }
655   void FailGLError(GLenum /* error */) { }
656 #endif
657
658   GLES2Util util_;
659   GLES2CmdHelper* helper_;
660   TransferBufferInterface* transfer_buffer_;
661   std::string last_error_;
662   DebugMarkerManager debug_marker_manager_;
663   std::string this_in_hex_;
664
665   std::queue<int32> swap_buffers_tokens_;
666   std::queue<int32> rate_limit_tokens_;
667
668   ExtensionStatus angle_pack_reverse_row_order_status_;
669   ExtensionStatus chromium_framebuffer_multisample_;
670
671   GLStaticState static_state_;
672   ClientContextState state_;
673
674   // pack alignment as last set by glPixelStorei
675   GLint pack_alignment_;
676
677   // unpack alignment as last set by glPixelStorei
678   GLint unpack_alignment_;
679
680   // unpack yflip as last set by glPixelstorei
681   bool unpack_flip_y_;
682
683   // unpack row length as last set by glPixelStorei
684   GLint unpack_row_length_;
685
686   // unpack skip rows as last set by glPixelStorei
687   GLint unpack_skip_rows_;
688
689   // unpack skip pixels as last set by glPixelStorei
690   GLint unpack_skip_pixels_;
691
692   // pack reverse row order as last set by glPixelstorei
693   bool pack_reverse_row_order_;
694
695   scoped_ptr<TextureUnit[]> texture_units_;
696
697   // 0 to gl_state_.max_combined_texture_image_units.
698   GLuint active_texture_unit_;
699
700   GLuint bound_framebuffer_;
701   GLuint bound_read_framebuffer_;
702   GLuint bound_renderbuffer_;
703
704   // The program in use by glUseProgram
705   GLuint current_program_;
706
707   // The currently bound array buffer.
708   GLuint bound_array_buffer_id_;
709
710   // The currently bound pixel transfer buffers.
711   GLuint bound_pixel_pack_transfer_buffer_id_;
712   GLuint bound_pixel_unpack_transfer_buffer_id_;
713
714   // The current asynchronous pixel buffer upload token.
715   uint32 async_upload_token_;
716
717   // The shared memory used for synchronizing asynchronous upload tokens.
718   AsyncUploadSync* async_upload_sync_;
719   int32 async_upload_sync_shm_id_;
720   unsigned int async_upload_sync_shm_offset_;
721
722   // Unmanaged pixel transfer buffer memory pending asynchronous upload token.
723   typedef std::list<std::pair<void*, uint32> > DetachedAsyncUploadMemoryList;
724   DetachedAsyncUploadMemoryList detached_async_upload_memory_;
725
726   // Client side management for vertex array objects. Needed to correctly
727   // track client side arrays.
728   scoped_ptr<VertexArrayObjectManager> vertex_array_object_manager_;
729
730   GLuint reserved_ids_[2];
731
732   // Current GL error bits.
733   uint32 error_bits_;
734
735   // Whether or not to print debugging info.
736   bool debug_;
737
738   // When true, the context is lost when a GL_OUT_OF_MEMORY error occurs.
739   bool lose_context_when_out_of_memory_;
740
741   // Used to check for single threaded access.
742   int use_count_;
743
744   // Map of GLenum to Strings for glGetString.  We need to cache these because
745   // the pointer passed back to the client has to remain valid for eternity.
746   typedef std::map<uint32, std::set<std::string> > GLStringMap;
747   GLStringMap gl_strings_;
748
749   // Similar cache for glGetRequestableExtensionsCHROMIUM. We don't
750   // have an enum for this so handle it separately.
751   std::set<std::string> requestable_extensions_set_;
752
753   typedef std::map<const void*, MappedBuffer> MappedBufferMap;
754   MappedBufferMap mapped_buffers_;
755
756   typedef std::map<const void*, MappedTexture> MappedTextureMap;
757   MappedTextureMap mapped_textures_;
758
759   scoped_ptr<MappedMemoryManager> mapped_memory_;
760
761   scoped_refptr<ShareGroup> share_group_;
762   ShareGroupContextData share_group_context_data_;
763
764   scoped_ptr<QueryTracker> query_tracker_;
765   typedef std::map<GLuint, QueryTracker::Query*> QueryMap;
766   QueryMap current_queries_;
767
768   scoped_ptr<BufferTracker> buffer_tracker_;
769
770   scoped_ptr<GpuMemoryBufferTracker> gpu_memory_buffer_tracker_;
771
772   ErrorMessageCallback* error_message_callback_;
773
774   scoped_ptr<std::string> current_trace_name_;
775
776   GpuControl* gpu_control_;
777
778   Capabilities capabilities_;
779
780   base::Closure swap_buffers_complete_callback_;
781
782   base::WeakPtrFactory<GLES2Implementation> weak_ptr_factory_;
783
784   DISALLOW_COPY_AND_ASSIGN(GLES2Implementation);
785 };
786
787 inline bool GLES2Implementation::GetBufferParameterivHelper(
788     GLenum /* target */, GLenum /* pname */, GLint* /* params */) {
789   return false;
790 }
791
792 inline bool GLES2Implementation::GetFramebufferAttachmentParameterivHelper(
793     GLenum /* target */,
794     GLenum /* attachment */,
795     GLenum /* pname */,
796     GLint* /* params */) {
797   return false;
798 }
799
800 inline bool GLES2Implementation::GetRenderbufferParameterivHelper(
801     GLenum /* target */, GLenum /* pname */, GLint* /* params */) {
802   return false;
803 }
804
805 inline bool GLES2Implementation::GetShaderivHelper(
806     GLuint /* shader */, GLenum /* pname */, GLint* /* params */) {
807   return false;
808 }
809
810 inline bool GLES2Implementation::GetTexParameterfvHelper(
811     GLenum /* target */, GLenum /* pname */, GLfloat* /* params */) {
812   return false;
813 }
814
815 inline bool GLES2Implementation::GetTexParameterivHelper(
816     GLenum /* target */, GLenum /* pname */, GLint* /* params */) {
817   return false;
818 }
819
820 }  // namespace gles2
821 }  // namespace gpu
822
823 #endif  // GPU_COMMAND_BUFFER_CLIENT_GLES2_IMPLEMENTATION_H_