2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """code generator for GLES2 command buffers."""
13 from optparse
import OptionParser
16 _SIZE_OF_COMMAND_HEADER
= 4
17 _FIRST_SPECIFIC_COMMAND_ID
= 256
19 _LICENSE
= """// Copyright (c) 2014 The Chromium Authors. All rights reserved.
20 // Use of this source code is governed by a BSD-style license that can be
21 // found in the LICENSE file.
25 _DO_NOT_EDIT_WARNING
= """// This file is auto-generated from
26 // gpu/command_buffer/build_gles2_cmd_buffer.py
31 # This string is copied directly out of the gl2.h file from GLES2.0
35 # *) Any argument that is a resourceID has been changed to GLid<Type>.
36 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
37 # If it's allowed to not exist it's GLidBind<Type>
39 # *) All GLenums have been changed to GLenumTypeOfEnum
42 'GLenum': 'unsigned int',
43 'GLboolean': 'unsigned char',
44 'GLbitfield': 'unsigned int',
45 'GLbyte': 'signed char',
49 'GLubyte': 'unsigned char',
50 'GLushort': 'unsigned short',
51 'GLuint': 'unsigned int',
60 'GLintptr': 'long int',
61 'GLsizeiptr': 'long int'
65 'GLintptr': 'long long int',
66 'GLsizeiptr': 'long long int'
69 # Capabilites selected with glEnable
72 {'name': 'cull_face'},
73 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
74 {'name': 'dither', 'default': True},
75 {'name': 'polygon_offset_fill'},
76 {'name': 'sample_alpha_to_coverage'},
77 {'name': 'sample_coverage'},
78 {'name': 'scissor_test',
79 'state_flag': 'framebuffer_state_.clear_state_dirty'},
80 {'name': 'stencil_test',
81 'state_flag': 'framebuffer_state_.clear_state_dirty'},
88 'enum': 'GL_COLOR_CLEAR_VALUE',
90 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
91 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
92 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
93 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
99 'enum': 'GL_DEPTH_CLEAR_VALUE',
101 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
107 'enum': 'GL_COLOR_WRITEMASK',
109 {'name': 'color_mask_red', 'type': 'GLboolean', 'default': 'true'},
110 {'name': 'color_mask_green', 'type': 'GLboolean', 'default': 'true'},
111 {'name': 'color_mask_blue', 'type': 'GLboolean', 'default': 'true'},
112 {'name': 'color_mask_alpha', 'type': 'GLboolean', 'default': 'true'},
114 'state_flag': 'framebuffer_state_.clear_state_dirty',
118 'func': 'ClearStencil',
119 'enum': 'GL_STENCIL_CLEAR_VALUE',
121 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
126 'func': 'BlendColor',
127 'enum': 'GL_BLEND_COLOR',
129 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
130 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
131 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
132 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
137 'func': 'BlendEquationSeparate',
140 'name': 'blend_equation_rgb',
142 'enum': 'GL_BLEND_EQUATION_RGB',
143 'default': 'GL_FUNC_ADD',
146 'name': 'blend_equation_alpha',
148 'enum': 'GL_BLEND_EQUATION_ALPHA',
149 'default': 'GL_FUNC_ADD',
155 'func': 'BlendFuncSeparate',
158 'name': 'blend_source_rgb',
160 'enum': 'GL_BLEND_SRC_RGB',
164 'name': 'blend_dest_rgb',
166 'enum': 'GL_BLEND_DST_RGB',
167 'default': 'GL_ZERO',
170 'name': 'blend_source_alpha',
172 'enum': 'GL_BLEND_SRC_ALPHA',
176 'name': 'blend_dest_alpha',
178 'enum': 'GL_BLEND_DST_ALPHA',
179 'default': 'GL_ZERO',
185 'func': 'PolygonOffset',
188 'name': 'polygon_offset_factor',
190 'enum': 'GL_POLYGON_OFFSET_FACTOR',
194 'name': 'polygon_offset_units',
196 'enum': 'GL_POLYGON_OFFSET_UNITS',
204 'enum': 'GL_CULL_FACE_MODE',
209 'default': 'GL_BACK',
216 'enum': 'GL_FRONT_FACE',
217 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
222 'enum': 'GL_DEPTH_FUNC',
223 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
227 'func': 'DepthRange',
228 'enum': 'GL_DEPTH_RANGE',
230 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
231 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
236 'func': 'SampleCoverage',
239 'name': 'sample_coverage_value',
241 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
245 'name': 'sample_coverage_invert',
247 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
254 'func': 'StencilMaskSeparate',
255 'state_flag': 'framebuffer_state_.clear_state_dirty',
258 'name': 'stencil_front_writemask',
260 'enum': 'GL_STENCIL_WRITEMASK',
261 'default': '0xFFFFFFFFU',
264 'name': 'stencil_back_writemask',
266 'enum': 'GL_STENCIL_BACK_WRITEMASK',
267 'default': '0xFFFFFFFFU',
273 'func': 'StencilOpSeparate',
276 'name': 'stencil_front_fail_op',
278 'enum': 'GL_STENCIL_FAIL',
279 'default': 'GL_KEEP',
282 'name': 'stencil_front_z_fail_op',
284 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
285 'default': 'GL_KEEP',
288 'name': 'stencil_front_z_pass_op',
290 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
291 'default': 'GL_KEEP',
294 'name': 'stencil_back_fail_op',
296 'enum': 'GL_STENCIL_BACK_FAIL',
297 'default': 'GL_KEEP',
300 'name': 'stencil_back_z_fail_op',
302 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
303 'default': 'GL_KEEP',
306 'name': 'stencil_back_z_pass_op',
308 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
309 'default': 'GL_KEEP',
315 'func': 'StencilFuncSeparate',
318 'name': 'stencil_front_func',
320 'enum': 'GL_STENCIL_FUNC',
321 'default': 'GL_ALWAYS',
324 'name': 'stencil_front_ref',
326 'enum': 'GL_STENCIL_REF',
330 'name': 'stencil_front_mask',
332 'enum': 'GL_STENCIL_VALUE_MASK',
333 'default': '0xFFFFFFFFU',
336 'name': 'stencil_back_func',
338 'enum': 'GL_STENCIL_BACK_FUNC',
339 'default': 'GL_ALWAYS',
342 'name': 'stencil_back_ref',
344 'enum': 'GL_STENCIL_BACK_REF',
348 'name': 'stencil_back_mask',
350 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
351 'default': '0xFFFFFFFFU',
356 'type': 'NamedParameter',
360 'name': 'hint_generate_mipmap',
362 'enum': 'GL_GENERATE_MIPMAP_HINT',
363 'default': 'GL_DONT_CARE'
366 'name': 'hint_fragment_shader_derivative',
368 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
369 'default': 'GL_DONT_CARE',
370 'extension_flag': 'oes_standard_derivatives'
375 'type': 'NamedParameter',
376 'func': 'PixelStorei',
379 'name': 'pack_alignment',
381 'enum': 'GL_PACK_ALIGNMENT',
385 'name': 'unpack_alignment',
387 'enum': 'GL_UNPACK_ALIGNMENT',
392 # TODO: Consider implemenenting these states
397 'enum': 'GL_LINE_WIDTH',
400 'name': 'line_width',
403 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
409 'enum': 'GL_DEPTH_WRITEMASK',
411 {'name': 'depth_mask', 'type': 'GLboolean', 'default': 'true'},
413 'state_flag': 'framebuffer_state_.clear_state_dirty',
418 'enum': 'GL_SCISSOR_BOX',
420 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
425 'expected': 'kViewportX',
431 'expected': 'kViewportY',
434 'name': 'scissor_width',
437 'expected': 'kViewportWidth',
440 'name': 'scissor_height',
443 'expected': 'kViewportHeight',
450 'enum': 'GL_VIEWPORT',
452 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
454 'name': 'viewport_x',
457 'expected': 'kViewportX',
460 'name': 'viewport_y',
463 'expected': 'kViewportY',
466 'name': 'viewport_width',
469 'expected': 'kViewportWidth',
472 'name': 'viewport_height',
475 'expected': 'kViewportHeight',
481 # This is a list of enum names and their valid values. It is used to map
482 # GLenum arguments to a specific set of valid values.
491 'GL_LINEAR_MIPMAP_LINEAR',
494 'FrameBufferTarget': {
500 'GL_DRAW_FRAMEBUFFER' ,
501 'GL_READ_FRAMEBUFFER' ,
504 'RenderBufferTarget': {
517 'GL_ELEMENT_ARRAY_BUFFER',
534 'CompressedTextureFormat': {
542 # NOTE: State an Capability entries added later.
544 'GL_ALIASED_LINE_WIDTH_RANGE',
545 'GL_ALIASED_POINT_SIZE_RANGE',
547 'GL_ARRAY_BUFFER_BINDING',
549 'GL_COMPRESSED_TEXTURE_FORMATS',
550 'GL_CURRENT_PROGRAM',
553 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
554 'GL_FRAMEBUFFER_BINDING',
555 'GL_GENERATE_MIPMAP_HINT',
557 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
558 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
559 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
560 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
561 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
562 'GL_MAX_RENDERBUFFER_SIZE',
563 'GL_MAX_TEXTURE_IMAGE_UNITS',
564 'GL_MAX_TEXTURE_SIZE',
565 'GL_MAX_VARYING_VECTORS',
566 'GL_MAX_VERTEX_ATTRIBS',
567 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
568 'GL_MAX_VERTEX_UNIFORM_VECTORS',
569 'GL_MAX_VIEWPORT_DIMS',
570 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
571 'GL_NUM_SHADER_BINARY_FORMATS',
574 'GL_RENDERBUFFER_BINDING',
576 'GL_SAMPLE_COVERAGE_INVERT',
577 'GL_SAMPLE_COVERAGE_VALUE',
580 'GL_SHADER_BINARY_FORMATS',
581 'GL_SHADER_COMPILER',
584 'GL_TEXTURE_BINDING_2D',
585 'GL_TEXTURE_BINDING_CUBE_MAP',
586 'GL_UNPACK_ALIGNMENT',
587 'GL_UNPACK_FLIP_Y_CHROMIUM',
588 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
589 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
590 # we can add this because we emulate it if the driver does not support it.
591 'GL_VERTEX_ARRAY_BINDING_OES',
598 'GetTexParamTarget': {
602 'GL_TEXTURE_CUBE_MAP',
605 'GL_PROXY_TEXTURE_CUBE_MAP',
612 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
613 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
614 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
615 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
616 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
617 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
620 'GL_PROXY_TEXTURE_CUBE_MAP',
623 'TextureBindTarget': {
627 'GL_TEXTURE_CUBE_MAP',
638 'GL_FRAGMENT_SHADER',
641 'GL_GEOMETRY_SHADER',
677 'GL_FUNC_REVERSE_SUBTRACT',
690 'GL_ONE_MINUS_SRC_COLOR',
692 'GL_ONE_MINUS_DST_COLOR',
694 'GL_ONE_MINUS_SRC_ALPHA',
696 'GL_ONE_MINUS_DST_ALPHA',
698 'GL_ONE_MINUS_CONSTANT_COLOR',
700 'GL_ONE_MINUS_CONSTANT_ALPHA',
701 'GL_SRC_ALPHA_SATURATE',
710 'GL_ONE_MINUS_SRC_COLOR',
712 'GL_ONE_MINUS_DST_COLOR',
714 'GL_ONE_MINUS_SRC_ALPHA',
716 'GL_ONE_MINUS_DST_ALPHA',
718 'GL_ONE_MINUS_CONSTANT_COLOR',
720 'GL_ONE_MINUS_CONSTANT_ALPHA',
725 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
],
772 'GL_COLOR_ATTACHMENT0',
773 'GL_DEPTH_ATTACHMENT',
774 'GL_STENCIL_ATTACHMENT',
777 'BackbufferAttachment': {
792 'GL_PIXEL_PACK_BUFFER',
795 'FrameBufferParameter': {
798 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
799 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
800 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
801 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
804 'ProgramParameter': {
809 'GL_VALIDATE_STATUS',
810 'GL_INFO_LOG_LENGTH',
811 'GL_ATTACHED_SHADERS',
812 'GL_ACTIVE_ATTRIBUTES',
813 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
814 'GL_ACTIVE_UNIFORMS',
815 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
818 'QueryObjectParameter': {
821 'GL_QUERY_RESULT_EXT',
822 'GL_QUERY_RESULT_AVAILABLE_EXT',
828 'GL_CURRENT_QUERY_EXT',
834 'GL_ANY_SAMPLES_PASSED_EXT',
835 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
836 'GL_COMMANDS_ISSUED_CHROMIUM',
837 'GL_LATENCY_QUERY_CHROMIUM',
838 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
839 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
842 'RenderBufferParameter': {
845 'GL_RENDERBUFFER_RED_SIZE',
846 'GL_RENDERBUFFER_GREEN_SIZE',
847 'GL_RENDERBUFFER_BLUE_SIZE',
848 'GL_RENDERBUFFER_ALPHA_SIZE',
849 'GL_RENDERBUFFER_DEPTH_SIZE',
850 'GL_RENDERBUFFER_STENCIL_SIZE',
851 'GL_RENDERBUFFER_WIDTH',
852 'GL_RENDERBUFFER_HEIGHT',
853 'GL_RENDERBUFFER_INTERNAL_FORMAT',
862 'GL_INFO_LOG_LENGTH',
863 'GL_SHADER_SOURCE_LENGTH',
864 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
884 'GL_SHADING_LANGUAGE_VERSION',
888 'TextureParameter': {
891 'GL_TEXTURE_MAG_FILTER',
892 'GL_TEXTURE_MIN_FILTER',
893 'GL_TEXTURE_POOL_CHROMIUM',
898 'GL_GENERATE_MIPMAP',
904 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
905 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
912 'GL_MIRRORED_REPEAT',
916 'TextureMinFilterMode': {
921 'GL_NEAREST_MIPMAP_NEAREST',
922 'GL_LINEAR_MIPMAP_NEAREST',
923 'GL_NEAREST_MIPMAP_LINEAR',
924 'GL_LINEAR_MIPMAP_LINEAR',
927 'TextureMagFilterMode': {
938 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
944 # some enum that the decoder actually passes through to GL needs
945 # to be the first listed here since it's used in unit tests.
946 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
947 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
948 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
949 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
950 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
951 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
952 'GL_CURRENT_VERTEX_ATTRIB',
958 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
964 'GL_GENERATE_MIPMAP_HINT',
967 'GL_PERSPECTIVE_CORRECTION_HINT',
982 'GL_UNPACK_ALIGNMENT',
983 'GL_UNPACK_FLIP_Y_CHROMIUM',
984 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
985 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
988 'GL_PACK_SWAP_BYTES',
989 'GL_UNPACK_SWAP_BYTES',
992 'PixelStoreAlignment': {
1005 'ReadPixelFormat': {
1017 'GL_UNSIGNED_SHORT_5_6_5',
1018 'GL_UNSIGNED_SHORT_4_4_4_4',
1019 'GL_UNSIGNED_SHORT_5_5_5_1',
1030 'GL_UNSIGNED_SHORT_5_6_5',
1031 'GL_UNSIGNED_SHORT_4_4_4_4',
1032 'GL_UNSIGNED_SHORT_5_5_5_1',
1039 'RenderBufferFormat': {
1045 'GL_DEPTH_COMPONENT16',
1046 'GL_STENCIL_INDEX8',
1049 'ShaderBinaryFormat': {
1072 'GL_LUMINANCE_ALPHA',
1081 'TextureInternalFormat': {
1086 'GL_LUMINANCE_ALPHA',
1095 'TextureInternalFormatStorage': {
1102 'GL_LUMINANCE8_EXT',
1103 'GL_LUMINANCE8_ALPHA8_EXT',
1108 'VertexAttribType': {
1114 'GL_UNSIGNED_SHORT',
1115 # 'GL_FIXED', // This is not available on Desktop GL.
1131 'VertexAttribSize': {
1154 'type': 'GLboolean',
1165 'GL_GUILTY_CONTEXT_RESET_ARB',
1166 'GL_INNOCENT_CONTEXT_RESET_ARB',
1167 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1172 # This table specifies the different pepper interfaces that are supported for
1173 # GL commands. 'dev' is true if it's a dev interface.
1174 _PEPPER_INTERFACES
= [
1175 {'name': '', 'dev': False},
1176 {'name': 'InstancedArrays', 'dev': False},
1177 {'name': 'FramebufferBlit', 'dev': False},
1178 {'name': 'FramebufferMultisample', 'dev': False},
1179 {'name': 'ChromiumEnableFeature', 'dev': False},
1180 {'name': 'ChromiumMapSub', 'dev': False},
1181 {'name': 'Query', 'dev': False},
1184 # This table specifies types and other special data for the commands that
1185 # will be generated.
1187 # Must match function names specified in "cmd_buffer_functions.txt".
1189 # cmd_comment: A comment added to the cmd format.
1190 # type: defines which handler will be used to generate code.
1191 # decoder_func: defines which function to call in the decoder to execute the
1192 # corresponding GL command. If not specified the GL command will
1193 # be called directly.
1194 # gl_test_func: GL function that is expected to be called when testing.
1195 # cmd_args: The arguments to use for the command. This overrides generating
1196 # them based on the GL function arguments.
1197 # a NonImmediate type is a type that stays a pointer even in
1198 # and immediate version of acommand.
1199 # gen_cmd: Whether or not this function geneates a command. Default = True.
1200 # immediate: Whether or not to generate an immediate command for the GL
1201 # function. The default is if there is exactly 1 pointer argument
1202 # in the GL function an immediate command is generated.
1203 # bucket: True to generate a bucket version of the command.
1204 # impl_func: Whether or not to generate the GLES2Implementation part of this
1206 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1208 # needs_size: If true a data_size field is added to the command.
1209 # data_type: The type of data the command uses. For PUTn or PUT types.
1210 # count: The number of units per element. For PUTn or PUT types.
1211 # unit_test: If False no service side unit test will be generated.
1212 # client_test: If False no client side unit test will be generated.
1213 # expectation: If False the unit test will have no expected calls.
1214 # gen_func: Name of function that generates GL resource for corresponding
1216 # states: array of states that get set by this function corresponding to
1217 # the given arguments
1218 # state_flag: name of flag that is set to true when function is called.
1219 # no_gl: no GL function is called.
1220 # valid_args: A dictionary of argument indices to args to use in unit tests
1221 # when they can not be automatically determined.
1222 # pepper_interface: The pepper interface that is used for this extension
1223 # pepper_name: The name of the function as exposed to pepper.
1224 # pepper_args: A string representing the argument list (what would appear in
1225 # C/C++ between the parentheses for the function declaration)
1226 # that the Pepper API expects for this function. Use this only if
1227 # the stable Pepper API differs from the GLES2 argument list.
1228 # invalid_test: False if no invalid test needed.
1229 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1230 # first_element_only: For PUT types, True if only the first element of an
1231 # array is used and we end up calling the single value
1232 # corresponding function. eg. TexParameteriv -> TexParameteri
1236 'decoder_func': 'DoActiveTexture',
1239 'client_test': False,
1241 'AttachShader': {'decoder_func': 'DoAttachShader'},
1242 'BindAttribLocation': {
1250 'decoder_func': 'DoBindBuffer',
1251 'gen_func': 'GenBuffersARB',
1253 'BindFramebuffer': {
1255 'decoder_func': 'DoBindFramebuffer',
1256 'gl_test_func': 'glBindFramebufferEXT',
1257 'gen_func': 'GenFramebuffersEXT',
1260 'BindRenderbuffer': {
1262 'decoder_func': 'DoBindRenderbuffer',
1263 'gl_test_func': 'glBindRenderbufferEXT',
1264 'gen_func': 'GenRenderbuffersEXT',
1268 'decoder_func': 'DoBindTexture',
1269 'gen_func': 'GenTextures',
1270 # TODO(gman): remove this once client side caching works.
1271 'client_test': False,
1274 'BlitFramebufferCHROMIUM': {
1275 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1278 'pepper_interface': 'FramebufferBlit',
1279 'pepper_name': 'BlitFramebufferEXT',
1280 'defer_reads': True,
1281 'defer_draws': True,
1287 'client_test': False,
1291 'client_test': False,
1292 'decoder_func': 'DoBufferSubData',
1295 'CheckFramebufferStatus': {
1297 'decoder_func': 'DoCheckFramebufferStatus',
1298 'gl_test_func': 'glCheckFramebufferStatusEXT',
1299 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1300 'result': ['GLenum'],
1303 'decoder_func': 'DoClear',
1304 'defer_draws': True,
1309 'state': 'ClearColor',
1313 'state': 'ClearDepthf',
1314 'decoder_func': 'glClearDepth',
1315 'gl_test_func': 'glClearDepth',
1322 'state': 'ColorMask',
1324 'expectation': False,
1326 'ConsumeTextureCHROMIUM': {
1327 'decoder_func': 'DoConsumeTextureCHROMIUM',
1330 'data_type': 'GLbyte',
1331 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1333 'client_test': False,
1340 'state': 'ClearStencil',
1342 'EnableFeatureCHROMIUM': {
1345 'decoder_func': 'DoEnableFeatureCHROMIUM',
1346 'expectation': False,
1347 'cmd_args': 'GLuint bucket_id, GLint* result',
1348 'result': ['GLint'],
1351 'pepper_interface': 'ChromiumEnableFeature',
1353 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1354 'CompressedTexImage2D': {
1359 'CompressedTexSubImage2D': {
1362 'decoder_func': 'DoCompressedTexSubImage2D',
1366 'decoder_func': 'DoCopyTexImage2D',
1368 'defer_reads': True,
1370 'CopyTexSubImage2D': {
1371 'decoder_func': 'DoCopyTexSubImage2D',
1372 'defer_reads': True,
1374 'CreateImageCHROMIUM': {
1376 'cmd_args': 'GLsizei width, GLsizei height, GLenum internalformat',
1377 'result': ['GLuint'],
1378 'client_test': False,
1380 'expectation': False,
1384 'DestroyImageCHROMIUM': {
1387 'client_test': False,
1392 'GetImageParameterivCHROMIUM': {
1394 'client_test': False,
1396 'expectation': False,
1402 'client_test': False,
1406 'client_test': False,
1410 'state': 'BlendColor',
1413 'type': 'StateSetRGBAlpha',
1414 'state': 'BlendEquation',
1416 '0': 'GL_FUNC_SUBTRACT'
1419 'BlendEquationSeparate': {
1421 'state': 'BlendEquation',
1423 '0': 'GL_FUNC_SUBTRACT'
1427 'type': 'StateSetRGBAlpha',
1428 'state': 'BlendFunc',
1430 'BlendFuncSeparate': {
1432 'state': 'BlendFunc',
1434 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1436 'type': 'StateSetFrontBack',
1437 'state': 'StencilFunc',
1439 'StencilFuncSeparate': {
1440 'type': 'StateSetFrontBackSeparate',
1441 'state': 'StencilFunc',
1444 'type': 'StateSetFrontBack',
1445 'state': 'StencilOp',
1450 'StencilOpSeparate': {
1451 'type': 'StateSetFrontBackSeparate',
1452 'state': 'StencilOp',
1458 'type': 'StateSetNamedParameter',
1461 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1462 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1463 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1466 'state': 'LineWidth',
1473 'state': 'PolygonOffset',
1477 'gl_test_func': 'glDeleteBuffersARB',
1478 'resource_type': 'Buffer',
1479 'resource_types': 'Buffers',
1481 'DeleteFramebuffers': {
1483 'gl_test_func': 'glDeleteFramebuffersEXT',
1484 'resource_type': 'Framebuffer',
1485 'resource_types': 'Framebuffers',
1487 'DeleteProgram': {'type': 'Delete', 'decoder_func': 'DoDeleteProgram'},
1488 'DeleteRenderbuffers': {
1490 'gl_test_func': 'glDeleteRenderbuffersEXT',
1491 'resource_type': 'Renderbuffer',
1492 'resource_types': 'Renderbuffers',
1494 'DeleteShader': {'type': 'Delete', 'decoder_func': 'DoDeleteShader'},
1495 'DeleteSharedIdsCHROMIUM': {
1497 'decoder_func': 'DoDeleteSharedIdsCHROMIUM',
1499 'expectation': False,
1506 'resource_type': 'Texture',
1507 'resource_types': 'Textures',
1510 'decoder_func': 'DoDepthRangef',
1511 'gl_test_func': 'glDepthRange',
1515 'state': 'DepthMask',
1517 'expectation': False,
1519 'DetachShader': {'decoder_func': 'DoDetachShader'},
1521 'decoder_func': 'DoDisable',
1523 'client_test': False,
1525 'DisableVertexAttribArray': {
1526 'decoder_func': 'DoDisableVertexAttribArray',
1531 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1532 'defer_draws': True,
1537 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1538 'GLenumIndexType type, GLuint index_offset',
1539 'client_test': False,
1540 'defer_draws': True,
1544 'decoder_func': 'DoEnable',
1546 'client_test': False,
1548 'EnableVertexAttribArray': {
1549 'decoder_func': 'DoEnableVertexAttribArray',
1554 'client_test': False,
1555 'decoder_func': 'DoFinish',
1556 'defer_reads': True,
1560 'decoder_func': 'DoFlush',
1562 'FramebufferRenderbuffer': {
1563 'decoder_func': 'DoFramebufferRenderbuffer',
1564 'gl_test_func': 'glFramebufferRenderbufferEXT',
1566 'FramebufferTexture2D': {
1567 'decoder_func': 'DoFramebufferTexture2D',
1568 'gl_test_func': 'glFramebufferTexture2DEXT',
1571 'FramebufferTexture2DMultisampleEXT': {
1572 'decoder_func': 'DoFramebufferTexture2DMultisample',
1573 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1574 'expectation': False,
1580 'decoder_func': 'DoGenerateMipmap',
1581 'gl_test_func': 'glGenerateMipmapEXT',
1585 'gl_test_func': 'glGenBuffersARB',
1586 'resource_type': 'Buffer',
1587 'resource_types': 'Buffers',
1589 'GenMailboxCHROMIUM': {
1590 'type': 'HandWritten',
1596 'GenFramebuffers': {
1598 'gl_test_func': 'glGenFramebuffersEXT',
1599 'resource_type': 'Framebuffer',
1600 'resource_types': 'Framebuffers',
1602 'GenRenderbuffers': {
1603 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1604 'resource_type': 'Renderbuffer',
1605 'resource_types': 'Renderbuffers',
1609 'gl_test_func': 'glGenTextures',
1610 'resource_type': 'Texture',
1611 'resource_types': 'Textures',
1613 'GenSharedIdsCHROMIUM': {
1615 'decoder_func': 'DoGenSharedIdsCHROMIUM',
1617 'expectation': False,
1622 'GetActiveAttrib': {
1626 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1634 'GetActiveUniform': {
1638 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1646 'GetAttachedShaders': {
1649 'cmd_args': 'GLidProgram program, void* result, uint32 result_size',
1650 'result': ['SizedResult<GLuint>'],
1652 'GetAttribLocation': {
1653 'type': 'HandWritten',
1658 'GLidProgram program, const char* name, NonImmediate GLint* location',
1659 'result': ['GLint'],
1660 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml
1664 'result': ['SizedResult<GLboolean>'],
1665 'decoder_func': 'DoGetBooleanv',
1666 'gl_test_func': 'glGetBooleanv',
1668 'GetBufferParameteriv': {
1670 'result': ['SizedResult<GLint>'],
1671 'decoder_func': 'DoGetBufferParameteriv',
1672 'expectation': False,
1677 'decoder_func': 'GetErrorState()->GetGLError',
1679 'result': ['GLenum'],
1680 'client_test': False,
1684 'result': ['SizedResult<GLfloat>'],
1685 'decoder_func': 'DoGetFloatv',
1686 'gl_test_func': 'glGetFloatv',
1688 'GetFramebufferAttachmentParameteriv': {
1690 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
1691 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
1692 'result': ['SizedResult<GLint>'],
1696 'result': ['SizedResult<GLint>'],
1697 'decoder_func': 'DoGetIntegerv',
1698 'client_test': False,
1700 'GetMaxValueInBufferCHROMIUM': {
1702 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
1703 'result': ['GLuint'],
1705 'client_test': False,
1710 'GetMultipleIntegervCHROMIUM': {
1713 'expectation': False,
1716 'client_test': False,
1720 'decoder_func': 'DoGetProgramiv',
1721 'result': ['SizedResult<GLint>'],
1722 'expectation': False,
1724 'GetProgramInfoCHROMIUM': {
1727 'expectation': False,
1731 'client_test': False,
1732 'cmd_args': 'GLidProgram program, uint32 bucket_id',
1734 'uint32 link_status',
1735 'uint32 num_attribs',
1736 'uint32 num_uniforms',
1739 'GetProgramInfoLog': {
1741 'expectation': False,
1743 'GetRenderbufferParameteriv': {
1745 'decoder_func': 'DoGetRenderbufferParameteriv',
1746 'gl_test_func': 'glGetRenderbufferParameterivEXT',
1747 'result': ['SizedResult<GLint>'],
1751 'decoder_func': 'DoGetShaderiv',
1752 'result': ['SizedResult<GLint>'],
1754 'GetShaderInfoLog': {
1756 'get_len_func': 'glGetShaderiv',
1757 'get_len_enum': 'GL_INFO_LOG_LENGTH',
1760 'GetShaderPrecisionFormat': {
1764 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
1773 'GetShaderSource': {
1775 'get_len_func': 'DoGetShaderiv',
1776 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
1778 'client_test': False,
1782 'client_test': False,
1783 'cmd_args': 'GLenumStringType name, uint32 bucket_id',
1785 'GetTexParameterfv': {'type': 'GETn', 'result': ['SizedResult<GLfloat>']},
1786 'GetTexParameteriv': {'type': 'GETn', 'result': ['SizedResult<GLint>']},
1787 'GetTranslatedShaderSourceANGLE': {
1789 'get_len_func': 'DoGetShaderiv',
1790 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1797 'result': ['SizedResult<GLfloat>'],
1802 'result': ['SizedResult<GLint>'],
1804 'GetUniformLocation': {
1805 'type': 'HandWritten',
1810 'GLidProgram program, const char* name, NonImmediate GLint* location',
1811 'result': ['GLint'],
1812 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
1814 'GetVertexAttribfv': {
1816 'result': ['SizedResult<GLfloat>'],
1818 'decoder_func': 'DoGetVertexAttribfv',
1819 'expectation': False,
1820 'client_test': False,
1822 'GetVertexAttribiv': {
1824 'result': ['SizedResult<GLint>'],
1826 'decoder_func': 'DoGetVertexAttribiv',
1827 'expectation': False,
1828 'client_test': False,
1830 'GetVertexAttribPointerv': {
1833 'result': ['SizedResult<GLuint>'],
1834 'client_test': False,
1838 'decoder_func': 'DoIsBuffer',
1839 'expectation': False,
1843 'decoder_func': 'DoIsEnabled',
1845 'expectation': False,
1849 'decoder_func': 'DoIsFramebuffer',
1850 'expectation': False,
1854 'decoder_func': 'DoIsProgram',
1855 'expectation': False,
1859 'decoder_func': 'DoIsRenderbuffer',
1860 'expectation': False,
1864 'decoder_func': 'DoIsShader',
1865 'expectation': False,
1869 'decoder_func': 'DoIsTexture',
1870 'expectation': False,
1873 'decoder_func': 'DoLinkProgram',
1876 'MapBufferCHROMIUM': {
1880 'client_test': False,
1882 'MapBufferSubDataCHROMIUM': {
1886 'client_test': False,
1887 'pepper_interface': 'ChromiumMapSub',
1889 'MapImageCHROMIUM': {
1893 'client_test': False,
1895 'MapTexSubImage2DCHROMIUM': {
1899 'client_test': False,
1900 'pepper_interface': 'ChromiumMapSub',
1902 'PixelStorei': {'type': 'Manual'},
1903 'PostSubBufferCHROMIUM': {
1907 'client_test': False,
1911 'ProduceTextureCHROMIUM': {
1912 'decoder_func': 'DoProduceTextureCHROMIUM',
1915 'data_type': 'GLbyte',
1916 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1918 'client_test': False,
1923 'RenderbufferStorage': {
1924 'decoder_func': 'DoRenderbufferStorage',
1925 'gl_test_func': 'glRenderbufferStorageEXT',
1926 'expectation': False,
1928 'RenderbufferStorageMultisampleCHROMIUM': {
1930 '// GL_CHROMIUM_framebuffer_multisample\n',
1931 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
1932 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
1933 'expectation': False,
1936 'pepper_interface': 'FramebufferMultisample',
1937 'pepper_name': 'RenderbufferStorageMultisampleEXT',
1939 'RenderbufferStorageMultisampleEXT': {
1941 '// GL_EXT_multisampled_render_to_texture\n',
1942 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
1943 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
1944 'expectation': False,
1950 '// ReadPixels has the result separated from the pixel buffer so that\n'
1951 '// it is easier to specify the result going to some specific place\n'
1952 '// that exactly fits the rectangle of pixels.\n',
1956 'client_test': False,
1958 'GLint x, GLint y, GLsizei width, GLsizei height, '
1959 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
1960 'uint32 pixels_shm_id, uint32 pixels_shm_offset, '
1961 'uint32 result_shm_id, uint32 result_shm_offset, '
1963 'result': ['uint32'],
1964 'defer_reads': True,
1966 'RegisterSharedIdsCHROMIUM': {
1968 'decoder_func': 'DoRegisterSharedIdsCHROMIUM',
1970 'expectation': False,
1975 'ReleaseShaderCompiler': {
1976 'decoder_func': 'DoReleaseShaderCompiler',
1981 'client_test': False,
1988 'client_test': False,
1990 'GLuint shader, const char* data',
1992 'GLuint shader, GLsizei count, const char** str, const GLint* length',
1995 'type': 'StateSetFrontBack',
1996 'state': 'StencilMask',
1998 'expectation': False,
2000 'StencilMaskSeparate': {
2001 'type': 'StateSetFrontBackSeparate',
2002 'state': 'StencilMask',
2004 'expectation': False,
2008 'decoder_func': 'DoSwapBuffers',
2010 'client_test': False,
2017 'client_test': False,
2020 'decoder_func': 'DoTexParameterf',
2021 'gl_test_func': 'glTexParameteri',
2027 'decoder_func': 'DoTexParameteri',
2034 'data_type': 'GLfloat',
2035 'data_value': 'GL_NEAREST',
2037 'decoder_func': 'DoTexParameterfv',
2038 'gl_test_func': 'glTexParameteri',
2039 'first_element_only': True,
2043 'data_type': 'GLint',
2044 'data_value': 'GL_NEAREST',
2046 'decoder_func': 'DoTexParameteriv',
2047 'gl_test_func': 'glTexParameteri',
2048 'first_element_only': True,
2053 'client_test': False,
2054 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2055 'GLint xoffset, GLint yoffset, '
2056 'GLsizei width, GLsizei height, '
2057 'GLenumTextureFormat format, GLenumPixelType type, '
2058 'const void* pixels, GLboolean internal'
2060 'Uniform1f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 1},
2063 'data_type': 'GLfloat',
2065 'decoder_func': 'DoUniform1fv',
2067 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2070 'data_type': 'GLint',
2072 'decoder_func': 'DoUniform1iv',
2075 'Uniform2i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 2},
2076 'Uniform2f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 2},
2079 'data_type': 'GLfloat',
2081 'decoder_func': 'DoUniform2fv',
2085 'data_type': 'GLint',
2087 'decoder_func': 'DoUniform2iv',
2089 'Uniform3i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 3},
2090 'Uniform3f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 3},
2093 'data_type': 'GLfloat',
2095 'decoder_func': 'DoUniform3fv',
2099 'data_type': 'GLint',
2101 'decoder_func': 'DoUniform3iv',
2103 'Uniform4i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 4},
2104 'Uniform4f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 4},
2107 'data_type': 'GLfloat',
2109 'decoder_func': 'DoUniform4fv',
2113 'data_type': 'GLint',
2115 'decoder_func': 'DoUniform4iv',
2117 'UniformMatrix2fv': {
2119 'data_type': 'GLfloat',
2121 'decoder_func': 'DoUniformMatrix2fv',
2123 'UniformMatrix3fv': {
2125 'data_type': 'GLfloat',
2127 'decoder_func': 'DoUniformMatrix3fv',
2129 'UniformMatrix4fv': {
2131 'data_type': 'GLfloat',
2133 'decoder_func': 'DoUniformMatrix4fv',
2135 'UnmapBufferCHROMIUM': {
2139 'client_test': False,
2141 'UnmapBufferSubDataCHROMIUM': {
2145 'client_test': False,
2146 'pepper_interface': 'ChromiumMapSub',
2148 'UnmapImageCHROMIUM': {
2152 'client_test': False,
2154 'UnmapTexSubImage2DCHROMIUM': {
2158 'client_test': False,
2159 'pepper_interface': 'ChromiumMapSub',
2162 'decoder_func': 'DoUseProgram',
2166 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2167 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2168 'VertexAttrib1fv': {
2170 'data_type': 'GLfloat',
2172 'decoder_func': 'DoVertexAttrib1fv',
2174 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2175 'VertexAttrib2fv': {
2177 'data_type': 'GLfloat',
2179 'decoder_func': 'DoVertexAttrib2fv',
2181 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2182 'VertexAttrib3fv': {
2184 'data_type': 'GLfloat',
2186 'decoder_func': 'DoVertexAttrib3fv',
2188 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2189 'VertexAttrib4fv': {
2191 'data_type': 'GLfloat',
2193 'decoder_func': 'DoVertexAttrib4fv',
2195 'VertexAttribPointer': {
2197 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2198 'GLenumVertexAttribType type, GLboolean normalized, '
2199 'GLsizei stride, GLuint offset',
2200 'client_test': False,
2207 'decoder_func': 'DoViewport',
2216 'GetRequestableExtensionsCHROMIUM': {
2220 'cmd_args': 'uint32 bucket_id',
2224 'RequestExtensionCHROMIUM': {
2228 'client_test': False,
2229 'cmd_args': 'uint32 bucket_id',
2233 'RateLimitOffscreenContextCHROMIUM': {
2237 'client_test': False,
2239 'CreateStreamTextureCHROMIUM': {
2240 'type': 'HandWritten',
2247 'TexImageIOSurface2DCHROMIUM': {
2248 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2253 'CopyTextureCHROMIUM': {
2254 'decoder_func': 'DoCopyTextureCHROMIUM',
2259 'TexStorage2DEXT': {
2262 'decoder_func': 'DoTexStorage2DEXT',
2264 'DrawArraysInstancedANGLE': {
2266 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2267 'GLsizei primcount',
2270 'pepper_interface': 'InstancedArrays',
2271 'defer_draws': True,
2275 'decoder_func': 'DoDrawBuffersEXT',
2276 'data_type': 'GLenum',
2278 'client_test': False,
2282 'DrawElementsInstancedANGLE': {
2284 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2285 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2288 'client_test': False,
2289 'pepper_interface': 'InstancedArrays',
2290 'defer_draws': True,
2292 'VertexAttribDivisorANGLE': {
2294 'cmd_args': 'GLuint index, GLuint divisor',
2297 'pepper_interface': 'InstancedArrays',
2301 'gl_test_func': 'glGenQueriesARB',
2302 'resource_type': 'Query',
2303 'resource_types': 'Queries',
2305 'pepper_interface': 'Query',
2307 'DeleteQueriesEXT': {
2309 'gl_test_func': 'glDeleteQueriesARB',
2310 'resource_type': 'Query',
2311 'resource_types': 'Queries',
2313 'pepper_interface': 'Query',
2317 'client_test': False,
2318 'pepper_interface': 'Query',
2322 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2324 'gl_test_func': 'glBeginQuery',
2325 'pepper_interface': 'Query',
2329 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2330 'gl_test_func': 'glEndnQuery',
2331 'client_test': False,
2332 'pepper_interface': 'Query',
2336 'client_test': False,
2337 'gl_test_func': 'glGetQueryiv',
2338 'pepper_interface': 'Query',
2340 'GetQueryObjectuivEXT': {
2342 'client_test': False,
2343 'gl_test_func': 'glGetQueryObjectuiv',
2344 'pepper_interface': 'Query',
2346 'BindUniformLocationCHROMIUM': {
2351 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2354 'InsertEventMarkerEXT': {
2356 'decoder_func': 'DoInsertEventMarkerEXT',
2357 'expectation': False,
2360 'PushGroupMarkerEXT': {
2362 'decoder_func': 'DoPushGroupMarkerEXT',
2363 'expectation': False,
2366 'PopGroupMarkerEXT': {
2367 'decoder_func': 'DoPopGroupMarkerEXT',
2368 'expectation': False,
2373 'GenVertexArraysOES': {
2376 'gl_test_func': 'glGenVertexArraysOES',
2377 'resource_type': 'VertexArray',
2378 'resource_types': 'VertexArrays',
2381 'BindVertexArrayOES': {
2384 'gl_test_func': 'glBindVertexArrayOES',
2385 'decoder_func': 'DoBindVertexArrayOES',
2386 'gen_func': 'GenVertexArraysOES',
2388 'client_test': False,
2390 'DeleteVertexArraysOES': {
2393 'gl_test_func': 'glDeleteVertexArraysOES',
2394 'resource_type': 'VertexArray',
2395 'resource_types': 'VertexArrays',
2398 'IsVertexArrayOES': {
2401 'gl_test_func': 'glIsVertexArrayOES',
2402 'decoder_func': 'DoIsVertexArrayOES',
2403 'expectation': False,
2406 'BindTexImage2DCHROMIUM': {
2407 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2412 'ReleaseTexImage2DCHROMIUM': {
2413 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2418 'ShallowFinishCHROMIUM': {
2423 'client_test': False,
2425 'ShallowFlushCHROMIUM': {
2430 'client_test': False,
2432 'TraceBeginCHROMIUM': {
2436 'client_test': False,
2437 'cmd_args': 'GLuint bucket_id',
2441 'TraceEndCHROMIUM': {
2444 'client_test': False,
2445 'decoder_func': 'DoTraceEndCHROMIUM',
2450 'AsyncTexImage2DCHROMIUM': {
2453 'client_test': False,
2457 'AsyncTexSubImage2DCHROMIUM': {
2460 'client_test': False,
2464 'WaitAsyncTexImage2DCHROMIUM': {
2467 'client_test': False,
2471 'DiscardFramebufferEXT': {
2474 'data_type': 'GLenum',
2475 'cmd_args': 'GLenum target, GLsizei count, '
2476 'const GLenum* attachments',
2477 'decoder_func': 'DoDiscardFramebufferEXT',
2479 'client_test': False,
2482 'LoseContextCHROMIUM': {
2488 'InsertSyncPointCHROMIUM': {
2489 'type': 'HandWritten',
2494 'WaitSyncPointCHROMIUM': {
2501 'DiscardBackbufferCHROMIUM': {
2510 def Grouper(n
, iterable
, fillvalue
=None):
2511 """Collect data into fixed-length chunks or blocks"""
2512 args
= [iter(iterable
)] * n
2513 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
2516 def SplitWords(input_string
):
2517 """Transforms a input_string into a list of lower-case components.
2520 input_string: the input string.
2523 a list of lower-case words.
2525 if input_string
.find('_') > -1:
2526 # 'some_TEXT_' -> 'some text'
2527 return input_string
.replace('_', ' ').strip().lower().split()
2529 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
2531 # look for capitalization to cut input_strings
2532 # 'SomeText' -> 'Some Text'
2533 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
2534 # 'Vector3' -> 'Vector 3'
2535 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
2536 return input_string
.lower().split()
2540 """Makes a lower-case identifier from words.
2543 words: a list of lower-case words.
2546 the lower-case identifier.
2548 return '_'.join(words
)
2551 def ToUnderscore(input_string
):
2552 """converts CamelCase to camel_case."""
2553 words
= SplitWords(input_string
)
2557 class CWriter(object):
2558 """Writes to a file formatting it for Google's style guidelines."""
2560 def __init__(self
, filename
):
2561 self
.filename
= filename
2565 def SetFileNum(self
, num
):
2566 """Used to help write number files and tests."""
2569 def Write(self
, string
):
2570 """Writes a string to a file spliting if it's > 80 characters."""
2571 lines
= string
.splitlines()
2572 num_lines
= len(lines
)
2573 for ii
in range(0, num_lines
):
2574 self
.__WriteLine
(lines
[ii
], ii
< (num_lines
- 1) or string
[-1] == '\n')
2576 def __FindSplit(self
, string
):
2577 """Finds a place to split a string."""
2578 splitter
= string
.find('=')
2579 if splitter
>= 1 and not string
[splitter
+ 1] == '=' and splitter
< 80:
2581 # parts = string.split('(')
2582 parts
= re
.split("(?<=[^\"])\((?!\")", string
)
2583 fptr
= re
.compile('\*\w*\)')
2585 splitter
= len(parts
[0])
2586 for ii
in range(1, len(parts
)):
2587 # Don't split on the dot in "if (.condition)".
2588 if (not parts
[ii
- 1][-3:] == "if " and
2589 # Don't split "(.)" or "(.*fptr)".
2590 (len(parts
[ii
]) > 0 and
2591 not parts
[ii
][0] == ")" and not fptr
.match(parts
[ii
]))
2594 splitter
+= len(parts
[ii
]) + 1
2599 splitter
= string
[0:end
].rfind(',')
2600 if splitter
< 0 or (splitter
> 0 and string
[splitter
- 1] == '"'):
2601 return last_splitter
2602 elif splitter
>= 80:
2607 def __WriteLine(self
, line
, ends_with_eol
):
2608 """Given a signle line, writes it to a file, splitting if it's > 80 chars"""
2610 i
= self
.__FindSplit
(line
)
2612 line1
= line
[0:i
+ 1]
2613 if line1
[-1] == ' ':
2620 nolint
= ' // NOLINT'
2621 self
.__AddLine
(line1
+ nolint
+ lineend
+ '\n')
2622 match
= re
.match("( +)", line1
)
2625 indent
= match
.group(1)
2627 if not splitter
== ',':
2628 indent
= " " + indent
2629 self
.__WriteLine
(indent
+ line
[i
+ 1:].lstrip(), True)
2633 nolint
= ' // NOLINT'
2634 self
.__AddLine
(line
+ nolint
)
2636 self
.__AddLine
('\n')
2638 def __AddLine(self
, line
):
2639 self
.content
.append(line
)
2642 """Close the file."""
2643 content
= "".join(self
.content
)
2645 if os
.path
.exists(self
.filename
):
2646 old_file
= open(self
.filename
, "rb");
2647 old_content
= old_file
.read()
2649 if content
== old_content
:
2652 file = open(self
.filename
, "wb")
2657 class CHeaderWriter(CWriter
):
2658 """Writes a C Header file."""
2660 _non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
2662 def __init__(self
, filename
, file_comment
= None):
2663 CWriter
.__init
__(self
, filename
)
2665 base
= os
.path
.abspath(filename
)
2666 while os
.path
.basename(base
) != 'src':
2667 new_base
= os
.path
.dirname(base
)
2668 assert new_base
!= base
# Prevent infinite loop.
2671 hpath
= os
.path
.relpath(filename
, base
)
2672 self
.guard
= self
._non
_alnum
_re
.sub('_', hpath
).upper() + '_'
2674 self
.Write(_LICENSE
)
2675 self
.Write(_DO_NOT_EDIT_WARNING
)
2676 if not file_comment
== None:
2677 self
.Write(file_comment
)
2678 self
.Write("#ifndef %s\n" % self
.guard
)
2679 self
.Write("#define %s\n\n" % self
.guard
)
2682 self
.Write("#endif // %s\n\n" % self
.guard
)
2685 class TypeHandler(object):
2686 """This class emits code for a particular type of function."""
2688 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
2693 def InitFunction(self
, func
):
2694 """Add or adjust anything type specific for this function."""
2695 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
2696 func
.AddCmdArg(DataSizeArgument('data_size'))
2698 def AddImmediateFunction(self
, generator
, func
):
2699 """Adds an immediate version of a function."""
2700 # Generate an immediate command if there is only 1 pointer arg.
2701 immediate
= func
.GetInfo('immediate') # can be True, False or None
2702 if immediate
== True or immediate
== None:
2703 if func
.num_pointer_args
== 1 or immediate
:
2704 generator
.AddFunction(ImmediateFunction(func
))
2706 def AddBucketFunction(self
, generator
, func
):
2707 """Adds a bucket version of a function."""
2708 # Generate an immediate command if there is only 1 pointer arg.
2709 bucket
= func
.GetInfo('bucket') # can be True, False or None
2711 generator
.AddFunction(BucketFunction(func
))
2713 def WriteStruct(self
, func
, file):
2714 """Writes a structure that matches the arguments to a function."""
2715 comment
= func
.GetInfo('cmd_comment')
2716 if not comment
== None:
2718 file.Write("struct %s {\n" % func
.name
)
2719 file.Write(" typedef %s ValueType;\n" % func
.name
)
2720 file.Write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
2721 func
.WriteCmdArgFlag(file)
2722 func
.WriteCmdFlag(file)
2724 result
= func
.GetInfo('result')
2725 if not result
== None:
2726 if len(result
) == 1:
2727 file.Write(" typedef %s Result;\n\n" % result
[0])
2729 file.Write(" struct Result {\n")
2731 file.Write(" %s;\n" % line
)
2732 file.Write(" };\n\n")
2734 func
.WriteCmdComputeSize(file)
2735 func
.WriteCmdSetHeader(file)
2736 func
.WriteCmdInit(file)
2737 func
.WriteCmdSet(file)
2739 file.Write(" gpu::CommandHeader header;\n")
2740 args
= func
.GetCmdArgs()
2742 file.Write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
2746 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
2747 file.Write("COMPILE_ASSERT(sizeof(%s) == %d,\n" % (func
.name
, size
))
2748 file.Write(" Sizeof_%s_is_not_%d);\n" % (func
.name
, size
))
2749 file.Write("COMPILE_ASSERT(offsetof(%s, header) == 0,\n" % func
.name
)
2750 file.Write(" OffsetOf_%s_header_not_0);\n" % func
.name
)
2751 offset
= _SIZE_OF_COMMAND_HEADER
2753 file.Write("COMPILE_ASSERT(offsetof(%s, %s) == %d,\n" %
2754 (func
.name
, arg
.name
, offset
))
2755 file.Write(" OffsetOf_%s_%s_not_%d);\n" %
2756 (func
.name
, arg
.name
, offset
))
2757 offset
+= _SIZE_OF_UINT32
2758 if not result
== None and len(result
) > 1:
2761 parts
= line
.split()
2764 COMPILE_ASSERT(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
2765 OffsetOf_%(cmd_name)s_Result_%(field_name)s_not_%(offset)d);
2767 file.Write((check
.strip() + "\n") % {
2768 'cmd_name': func
.name
,
2772 offset
+= _SIZE_OF_UINT32
2775 def WriteHandlerImplementation(self
, func
, file):
2776 """Writes the handler implementation for this command."""
2777 file.Write(" %s(%s);\n" %
2778 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2780 def WriteCmdSizeTest(self
, func
, file):
2781 """Writes the size test for a command."""
2782 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2784 def WriteFormatTest(self
, func
, file):
2785 """Writes a format test for a command."""
2786 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
2787 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
2788 (func
.name
, func
.name
))
2789 file.Write(" void* next_cmd = cmd.Set(\n")
2791 args
= func
.GetCmdArgs()
2792 for value
, arg
in enumerate(args
):
2793 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
2795 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
2797 file.Write(" cmd.header.command);\n")
2798 func
.type_handler
.WriteCmdSizeTest(func
, file)
2799 for value
, arg
in enumerate(args
):
2800 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
2801 (arg
.type, value
+ 11, arg
.name
))
2802 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
2803 file.Write(" next_cmd, sizeof(cmd));\n")
2807 def WriteImmediateFormatTest(self
, func
, file):
2808 """Writes a format test for an immediate version of a command."""
2811 def WriteBucketFormatTest(self
, func
, file):
2812 """Writes a format test for a bucket version of a command."""
2815 def WriteGetDataSizeCode(self
, func
, file):
2816 """Writes the code to set data_size used in validation"""
2819 def WriteImmediateCmdSizeTest(self
, func
, file):
2820 """Writes a size test for an immediate version of a command."""
2821 file.Write(" // TODO(gman): Compute correct size.\n")
2822 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2824 def WriteImmediateHandlerImplementation (self
, func
, file):
2825 """Writes the handler impl for the immediate version of a command."""
2826 file.Write(" %s(%s);\n" %
2827 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2829 def WriteBucketHandlerImplementation (self
, func
, file):
2830 """Writes the handler impl for the bucket version of a command."""
2831 file.Write(" %s(%s);\n" %
2832 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2834 def WriteServiceImplementation(self
, func
, file):
2835 """Writes the service implementation for a command."""
2837 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
2839 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2841 self
.WriteHandlerDeferReadWrite(func
, file);
2842 if len(func
.GetOriginalArgs()) > 0:
2843 last_arg
= func
.GetLastOriginalArg()
2844 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2845 for arg
in all_but_last_arg
:
2846 arg
.WriteGetCode(file)
2847 self
.WriteGetDataSizeCode(func
, file)
2848 last_arg
.WriteGetCode(file)
2849 func
.WriteHandlerValidation(file)
2850 func
.WriteHandlerImplementation(file)
2851 file.Write(" return error::kNoError;\n")
2855 def WriteImmediateServiceImplementation(self
, func
, file):
2856 """Writes the service implementation for an immediate version of command."""
2858 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
2860 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2862 self
.WriteHandlerDeferReadWrite(func
, file);
2863 last_arg
= func
.GetLastOriginalArg()
2864 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2865 for arg
in all_but_last_arg
:
2866 arg
.WriteGetCode(file)
2867 self
.WriteGetDataSizeCode(func
, file)
2868 last_arg
.WriteGetCode(file)
2869 func
.WriteHandlerValidation(file)
2870 func
.WriteHandlerImplementation(file)
2871 file.Write(" return error::kNoError;\n")
2875 def WriteBucketServiceImplementation(self
, func
, file):
2876 """Writes the service implementation for a bucket version of command."""
2878 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
2880 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2882 self
.WriteHandlerDeferReadWrite(func
, file);
2883 last_arg
= func
.GetLastOriginalArg()
2884 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2885 for arg
in all_but_last_arg
:
2886 arg
.WriteGetCode(file)
2887 self
.WriteGetDataSizeCode(func
, file)
2888 last_arg
.WriteGetCode(file)
2889 func
.WriteHandlerValidation(file)
2890 func
.WriteHandlerImplementation(file)
2891 file.Write(" return error::kNoError;\n")
2895 def WriteHandlerDeferReadWrite(self
, func
, file):
2896 """Writes the code to handle deferring reads or writes."""
2897 defer_draws
= func
.GetInfo('defer_draws')
2898 defer_reads
= func
.GetInfo('defer_reads')
2899 if defer_draws
or defer_reads
:
2900 file.Write(" error::Error error;\n")
2902 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
2903 file.Write(" if (error != error::kNoError)\n")
2904 file.Write(" return error;\n")
2906 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
2907 file.Write(" if (error != error::kNoError)\n")
2908 file.Write(" return error;\n")
2910 def WriteValidUnitTest(self
, func
, file, test
, extra
= {}):
2911 """Writes a valid unit test."""
2912 if func
.GetInfo('expectation') == False:
2913 test
= self
._remove
_expected
_call
_re
.sub('', test
)
2916 for count
, arg
in enumerate(func
.GetOriginalArgs()):
2917 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
2919 for count
, arg
in enumerate(func
.GetOriginalArgs()):
2920 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
2921 gl_func_name
= func
.GetGLTestFunctionName()
2923 'test_name': 'GLES2DecoderTest%d' % file.file_num
,
2925 'gl_func_name': gl_func_name
,
2926 'args': ", ".join(arg_strings
),
2927 'gl_args': ", ".join(gl_arg_strings
),
2931 while (old_test
!= test
):
2934 file.Write(test
% vars)
2936 def WriteInvalidUnitTest(self
, func
, file, test
, extra
= {}):
2937 """Writes a invalid unit test."""
2938 for arg_index
, arg
in enumerate(func
.GetOriginalArgs()):
2939 num_invalid_values
= arg
.GetNumInvalidValues(func
)
2940 for value_index
in range(0, num_invalid_values
):
2942 parse_result
= "kNoError"
2944 for count
, arg
in enumerate(func
.GetOriginalArgs()):
2945 if count
== arg_index
:
2946 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
2949 arg_string
= arg
.GetValidArg(func
, count
, 0)
2950 arg_strings
.append(arg_string
)
2952 for arg
in func
.GetOriginalArgs():
2953 gl_arg_strings
.append("_")
2954 gl_func_name
= func
.GetGLTestFunctionName()
2956 if not gl_error
== None:
2957 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
2960 'test_name': 'GLES2DecoderTest%d' % file.file_num
,
2962 'arg_index': arg_index
,
2963 'value_index': value_index
,
2964 'gl_func_name': gl_func_name
,
2965 'args': ", ".join(arg_strings
),
2966 'all_but_last_args': ", ".join(arg_strings
[:-1]),
2967 'gl_args': ", ".join(gl_arg_strings
),
2968 'parse_result': parse_result
,
2969 'gl_error_test': gl_error_test
,
2972 file.Write(test
% vars)
2974 def WriteServiceUnitTest(self
, func
, file):
2975 """Writes the service unit test for a command."""
2977 TEST_F(%(test_name)s, %(name)sValidArgs) {
2978 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
2979 SpecializedSetup<cmds::%(name)s, 0>(true);
2982 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
2983 EXPECT_EQ(GL_NO_ERROR, GetGLError());
2986 self
.WriteValidUnitTest(func
, file, valid_test
)
2989 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
2990 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
2991 SpecializedSetup<cmds::%(name)s, 0>(false);
2994 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
2997 self
.WriteInvalidUnitTest(func
, file, invalid_test
)
2999 def WriteImmediateServiceUnitTest(self
, func
, file):
3000 """Writes the service unit test for an immediate command."""
3001 file.Write("// TODO(gman): %s\n" % func
.name
)
3003 def WriteImmediateValidationCode(self
, func
, file):
3004 """Writes the validation code for an immediate version of a command."""
3007 def WriteBucketServiceUnitTest(self
, func
, file):
3008 """Writes the service unit test for a bucket command."""
3009 file.Write("// TODO(gman): %s\n" % func
.name
)
3011 def WriteBucketValidationCode(self
, func
, file):
3012 """Writes the validation code for a bucket version of a command."""
3013 file.Write("// TODO(gman): %s\n" % func
.name
)
3015 def WriteGLES2ImplementationDeclaration(self
, func
, file):
3016 """Writes the GLES2 Implemention declaration."""
3017 impl_decl
= func
.GetInfo('impl_decl')
3018 if impl_decl
== None or impl_decl
== True:
3019 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3020 (func
.return_type
, func
.original_name
,
3021 func
.MakeTypedOriginalArgString("")))
3024 def WriteGLES2CLibImplementation(self
, func
, file):
3025 file.Write("%s GLES2%s(%s) {\n" %
3026 (func
.return_type
, func
.name
,
3027 func
.MakeTypedOriginalArgString("")))
3028 result_string
= "return "
3029 if func
.return_type
== "void":
3031 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3032 (result_string
, func
.original_name
,
3033 func
.MakeOriginalArgString("")))
3036 def WriteGLES2Header(self
, func
, file):
3037 """Writes a re-write macro for GLES"""
3038 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
3040 def WriteClientGLCallLog(self
, func
, file):
3041 """Writes a logging macro for the client side code."""
3043 if len(func
.GetOriginalArgs()):
3046 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3047 (func
.original_name
, comma
, func
.MakeLogArgString()))
3049 def WriteClientGLReturnLog(self
, func
, file):
3050 """Writes the return value logging code."""
3051 if func
.return_type
!= "void":
3052 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3054 def WriteGLES2ImplementationHeader(self
, func
, file):
3055 """Writes the GLES2 Implemention."""
3056 self
.WriteGLES2ImplementationDeclaration(func
, file)
3058 def WriteGLES2TraceImplementationHeader(self
, func
, file):
3059 """Writes the GLES2 Trace Implemention header."""
3060 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3061 (func
.return_type
, func
.original_name
,
3062 func
.MakeTypedOriginalArgString("")))
3064 def WriteGLES2TraceImplementation(self
, func
, file):
3065 """Writes the GLES2 Trace Implemention."""
3066 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3067 (func
.return_type
, func
.original_name
,
3068 func
.MakeTypedOriginalArgString("")))
3069 result_string
= "return "
3070 if func
.return_type
== "void":
3072 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3074 file.Write(" %sgl_->%s(%s);\n" %
3075 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
3079 def WriteGLES2Implementation(self
, func
, file):
3080 """Writes the GLES2 Implemention."""
3081 impl_func
= func
.GetInfo('impl_func')
3082 impl_decl
= func
.GetInfo('impl_decl')
3083 gen_cmd
= func
.GetInfo('gen_cmd')
3084 if (func
.can_auto_generate
and
3085 (impl_func
== None or impl_func
== True) and
3086 (impl_decl
== None or impl_decl
== True) and
3087 (gen_cmd
== None or gen_cmd
== True)):
3088 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3089 (func
.return_type
, func
.original_name
,
3090 func
.MakeTypedOriginalArgString("")))
3091 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3092 self
.WriteClientGLCallLog(func
, file)
3093 func
.WriteDestinationInitalizationValidation(file)
3094 for arg
in func
.GetOriginalArgs():
3095 arg
.WriteClientSideValidationCode(file, func
)
3096 file.Write(" helper_->%s(%s);\n" %
3097 (func
.name
, func
.MakeOriginalArgString("")))
3098 file.Write(" CheckGLError();\n")
3099 self
.WriteClientGLReturnLog(func
, file)
3103 def WriteGLES2InterfaceHeader(self
, func
, file):
3104 """Writes the GLES2 Interface."""
3105 file.Write("virtual %s %s(%s) = 0;\n" %
3106 (func
.return_type
, func
.original_name
,
3107 func
.MakeTypedOriginalArgString("")))
3109 def WriteGLES2InterfaceStub(self
, func
, file):
3110 """Writes the GLES2 Interface stub declaration."""
3111 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3112 (func
.return_type
, func
.original_name
,
3113 func
.MakeTypedOriginalArgString("")))
3115 def WriteGLES2InterfaceStubImpl(self
, func
, file):
3116 """Writes the GLES2 Interface stub declaration."""
3117 args
= func
.GetOriginalArgs()
3118 arg_string
= ", ".join(
3119 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
3120 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3121 (func
.return_type
, func
.original_name
, arg_string
))
3122 if func
.return_type
!= "void":
3123 file.Write(" return 0;\n")
3126 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3127 """Writes the GLES2 Implemention unit test."""
3128 client_test
= func
.GetInfo('client_test')
3129 if (func
.can_auto_generate
and
3130 (client_test
== None or client_test
== True)):
3132 TEST_F(GLES2ImplementationTest, %(name)s) {
3137 expected.cmd.Init(%(cmd_args)s);
3139 gl_->%(name)s(%(args)s);
3140 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3143 cmd_arg_strings
= []
3144 for count
, arg
in enumerate(func
.GetCmdArgs()):
3145 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
3148 for count
, arg
in enumerate(func
.GetOriginalArgs()):
3149 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
3152 'args': ", ".join(gl_arg_strings
),
3153 'cmd_args': ", ".join(cmd_arg_strings
),
3156 if client_test
!= False:
3157 file.Write("// TODO: Implement unit test for %s\n" % func
.name
)
3159 def WriteDestinationInitalizationValidation(self
, func
, file):
3160 """Writes the client side destintion initialization validation."""
3161 for arg
in func
.GetOriginalArgs():
3162 arg
.WriteDestinationInitalizationValidation(file, func
)
3164 def WriteTraceEvent(self
, func
, file):
3165 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3168 def WriteImmediateCmdComputeSize(self
, func
, file):
3169 """Writes the size computation code for the immediate version of a cmd."""
3170 file.Write(" static uint32 ComputeSize(uint32 size_in_bytes) {\n")
3171 file.Write(" return static_cast<uint32>(\n")
3172 file.Write(" sizeof(ValueType) + // NOLINT\n")
3173 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3177 def WriteImmediateCmdSetHeader(self
, func
, file):
3178 """Writes the SetHeader function for the immediate version of a cmd."""
3179 file.Write(" void SetHeader(uint32 size_in_bytes) {\n")
3180 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3184 def WriteImmediateCmdInit(self
, func
, file):
3185 """Writes the Init function for the immediate version of a command."""
3186 raise NotImplementedError(func
.name
)
3188 def WriteImmediateCmdSet(self
, func
, file):
3189 """Writes the Set function for the immediate version of a command."""
3190 raise NotImplementedError(func
.name
)
3192 def WriteCmdHelper(self
, func
, file):
3193 """Writes the cmd helper definition for a cmd."""
3194 code
= """ void %(name)s(%(typed_args)s) {
3195 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3204 "typed_args": func
.MakeTypedCmdArgString(""),
3205 "args": func
.MakeCmdArgString(""),
3208 def WriteImmediateCmdHelper(self
, func
, file):
3209 """Writes the cmd helper definition for the immediate version of a cmd."""
3210 code
= """ void %(name)s(%(typed_args)s) {
3211 const uint32 s = 0; // TODO(gman): compute correct size
3212 gles2::cmds::%(name)s* c =
3213 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3222 "typed_args": func
.MakeTypedCmdArgString(""),
3223 "args": func
.MakeCmdArgString(""),
3227 class StateSetHandler(TypeHandler
):
3228 """Handler for commands that simply set state."""
3231 TypeHandler
.__init
__(self
)
3233 def WriteHandlerImplementation(self
, func
, file):
3234 """Overrriden from TypeHandler."""
3235 state_name
= func
.GetInfo('state')
3236 state
= _STATES
[state_name
]
3237 states
= state
['states']
3238 args
= func
.GetOriginalArgs()
3240 for ndx
,item
in enumerate(states
):
3241 if 'range_checks' in item
:
3242 for range_check
in item
['range_checks']:
3243 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
3245 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3247 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3248 ' "%s", "%s out of range");\n' %
3249 (func
.name
, args
[ndx
].name
))
3250 file.Write(" return error::kNoError;\n")
3253 for ndx
,item
in enumerate(states
):
3254 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
3255 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3256 for ndx
,item
in enumerate(states
):
3257 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
3258 if 'state_flag' in state
:
3259 file.Write(" %s = true;\n" % state
['state_flag'])
3260 if not func
.GetInfo("no_gl"):
3261 file.Write(" %s(%s);\n" %
3262 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3265 def WriteServiceUnitTest(self
, func
, file):
3266 """Overrriden from TypeHandler."""
3267 TypeHandler
.WriteServiceUnitTest(self
, func
, file)
3268 state_name
= func
.GetInfo('state')
3269 state
= _STATES
[state_name
]
3270 states
= state
['states']
3271 for ndx
,item
in enumerate(states
):
3272 if 'range_checks' in item
:
3273 for check_ndx
, range_check
in enumerate(item
['range_checks']):
3275 TEST_F(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3276 SpecializedSetup<cmds::%(name)s, 0>(false);
3279 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3280 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3285 for count
, arg
in enumerate(func
.GetOriginalArgs()):
3286 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
3287 arg_strings
[ndx
] = range_check
['test_value']
3289 'test_name': 'GLES2DecoderTest%d' % file.file_num
,
3292 'check_ndx': check_ndx
,
3293 'args': ", ".join(arg_strings
),
3295 file.Write(valid_test
% vars)
3298 class StateSetRGBAlphaHandler(TypeHandler
):
3299 """Handler for commands that simply set state that have rgb/alpha."""
3302 TypeHandler
.__init
__(self
)
3304 def WriteHandlerImplementation(self
, func
, file):
3305 """Overrriden from TypeHandler."""
3306 state_name
= func
.GetInfo('state')
3307 state
= _STATES
[state_name
]
3308 states
= state
['states']
3309 args
= func
.GetOriginalArgs()
3310 num_args
= len(args
)
3312 for ndx
,item
in enumerate(states
):
3313 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
3314 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3315 for ndx
, item
in enumerate(states
):
3316 file.Write(" state_.%s = %s;\n" %
3317 (item
['name'], args
[ndx
% num_args
].name
))
3318 if 'state_flag' in state
:
3319 file.Write(" %s = true;\n" % state
['state_flag'])
3320 if not func
.GetInfo("no_gl"):
3321 file.Write(" %s(%s);\n" %
3322 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3326 class StateSetFrontBackSeparateHandler(TypeHandler
):
3327 """Handler for commands that simply set state that have front/back."""
3330 TypeHandler
.__init
__(self
)
3332 def WriteHandlerImplementation(self
, func
, file):
3333 """Overrriden from TypeHandler."""
3334 state_name
= func
.GetInfo('state')
3335 state
= _STATES
[state_name
]
3336 states
= state
['states']
3337 args
= func
.GetOriginalArgs()
3339 num_args
= len(args
)
3340 file.Write(" bool changed = false;\n")
3341 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
3342 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3343 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
3345 for ndx
, item
in enumerate(group
):
3346 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
3347 file.Write(" changed |= %s;\n" % " ||\n ".join(code
))
3349 file.Write(" if (changed) {\n")
3350 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
3351 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3352 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
3353 for ndx
, item
in enumerate(group
):
3354 file.Write(" state_.%s = %s;\n" %
3355 (item
['name'], args
[ndx
+ 1].name
))
3357 if 'state_flag' in state
:
3358 file.Write(" %s = true;\n" % state
['state_flag'])
3359 if not func
.GetInfo("no_gl"):
3360 file.Write(" %s(%s);\n" %
3361 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3365 class StateSetFrontBackHandler(TypeHandler
):
3366 """Handler for commands that simply set state that set both front/back."""
3369 TypeHandler
.__init
__(self
)
3371 def WriteHandlerImplementation(self
, func
, file):
3372 """Overrriden from TypeHandler."""
3373 state_name
= func
.GetInfo('state')
3374 state
= _STATES
[state_name
]
3375 states
= state
['states']
3376 args
= func
.GetOriginalArgs()
3377 num_args
= len(args
)
3379 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
3380 for ndx
, item
in enumerate(group
):
3381 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
3382 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3383 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
3384 for ndx
, item
in enumerate(group
):
3385 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
3386 if 'state_flag' in state
:
3387 file.Write(" %s = true;\n" % state
['state_flag'])
3388 if not func
.GetInfo("no_gl"):
3389 file.Write(" %s(%s);\n" %
3390 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3394 class StateSetNamedParameter(TypeHandler
):
3395 """Handler for commands that set a state chosen with an enum parameter."""
3398 TypeHandler
.__init
__(self
)
3400 def WriteHandlerImplementation(self
, func
, file):
3401 """Overridden from TypeHandler."""
3402 state_name
= func
.GetInfo('state')
3403 state
= _STATES
[state_name
]
3404 states
= state
['states']
3405 args
= func
.GetOriginalArgs()
3406 num_args
= len(args
)
3407 assert num_args
== 2
3408 file.Write(" switch (%s) {\n" % args
[0].name
)
3409 for state
in states
:
3410 file.Write(" case %s:\n" % state
['enum'])
3411 file.Write(" if (state_.%s != %s) {\n" %
3412 (state
['name'], args
[1].name
))
3413 file.Write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
3414 if not func
.GetInfo("no_gl"):
3415 file.Write(" %s(%s);\n" %
3416 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3418 file.Write(" break;\n")
3419 file.Write(" default:\n")
3420 file.Write(" NOTREACHED();\n")
3424 class CustomHandler(TypeHandler
):
3425 """Handler for commands that are auto-generated but require minor tweaks."""
3428 TypeHandler
.__init
__(self
)
3430 def WriteServiceImplementation(self
, func
, file):
3431 """Overrriden from TypeHandler."""
3434 def WriteImmediateServiceImplementation(self
, func
, file):
3435 """Overrriden from TypeHandler."""
3438 def WriteBucketServiceImplementation(self
, func
, file):
3439 """Overrriden from TypeHandler."""
3442 def WriteServiceUnitTest(self
, func
, file):
3443 """Overrriden from TypeHandler."""
3444 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3446 def WriteImmediateServiceUnitTest(self
, func
, file):
3447 """Overrriden from TypeHandler."""
3448 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3450 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3451 """Overrriden from TypeHandler."""
3452 file.Write(" uint32 total_size = 0; // TODO(gman): get correct size.\n")
3454 def WriteImmediateCmdInit(self
, func
, file):
3455 """Overrriden from TypeHandler."""
3456 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
3457 self
.WriteImmediateCmdGetTotalSize(func
, file)
3458 file.Write(" SetHeader(total_size);\n")
3459 args
= func
.GetCmdArgs()
3461 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
3465 def WriteImmediateCmdSet(self
, func
, file):
3466 """Overrriden from TypeHandler."""
3467 copy_args
= func
.MakeCmdArgString("_", False)
3468 file.Write(" void* Set(void* cmd%s) {\n" %
3469 func
.MakeTypedCmdArgString("_", True))
3470 self
.WriteImmediateCmdGetTotalSize(func
, file)
3471 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
3472 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3473 "cmd, total_size);\n")
3478 class TodoHandler(CustomHandler
):
3479 """Handle for commands that are not yet implemented."""
3481 def AddImmediateFunction(self
, generator
, func
):
3482 """Overrriden from TypeHandler."""
3485 def WriteImmediateFormatTest(self
, func
, file):
3486 """Overrriden from TypeHandler."""
3489 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3490 """Overrriden from TypeHandler."""
3493 def WriteGLES2Implementation(self
, func
, file):
3494 """Overrriden from TypeHandler."""
3495 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3496 (func
.return_type
, func
.original_name
,
3497 func
.MakeTypedOriginalArgString("")))
3498 file.Write(" // TODO: for now this is a no-op\n")
3501 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3503 if func
.return_type
!= "void":
3504 file.Write(" return 0;\n")
3508 def WriteServiceImplementation(self
, func
, file):
3509 """Overrriden from TypeHandler."""
3511 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
3513 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
3515 file.Write(" // TODO: for now this is a no-op\n")
3517 " LOCAL_SET_GL_ERROR("
3518 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3520 file.Write(" return error::kNoError;\n")
3525 class HandWrittenHandler(CustomHandler
):
3526 """Handler for comands where everything must be written by hand."""
3528 def InitFunction(self
, func
):
3529 """Add or adjust anything type specific for this function."""
3530 CustomHandler
.InitFunction(self
, func
)
3531 func
.can_auto_generate
= False
3533 def WriteStruct(self
, func
, file):
3534 """Overrriden from TypeHandler."""
3537 def WriteDocs(self
, func
, file):
3538 """Overrriden from TypeHandler."""
3541 def WriteServiceUnitTest(self
, func
, file):
3542 """Overrriden from TypeHandler."""
3543 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3545 def WriteImmediateServiceUnitTest(self
, func
, file):
3546 """Overrriden from TypeHandler."""
3547 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3549 def WriteBucketServiceUnitTest(self
, func
, file):
3550 """Overrriden from TypeHandler."""
3551 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3553 def WriteServiceImplementation(self
, func
, file):
3554 """Overrriden from TypeHandler."""
3557 def WriteImmediateServiceImplementation(self
, func
, file):
3558 """Overrriden from TypeHandler."""
3561 def WriteBucketServiceImplementation(self
, func
, file):
3562 """Overrriden from TypeHandler."""
3565 def WriteImmediateCmdHelper(self
, func
, file):
3566 """Overrriden from TypeHandler."""
3569 def WriteBucketCmdHelper(self
, func
, file):
3570 """Overrriden from TypeHandler."""
3573 def WriteCmdHelper(self
, func
, file):
3574 """Overrriden from TypeHandler."""
3577 def WriteFormatTest(self
, func
, file):
3578 """Overrriden from TypeHandler."""
3579 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3581 def WriteImmediateFormatTest(self
, func
, file):
3582 """Overrriden from TypeHandler."""
3583 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3585 def WriteBucketFormatTest(self
, func
, file):
3586 """Overrriden from TypeHandler."""
3587 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3591 class ManualHandler(CustomHandler
):
3592 """Handler for commands who's handlers must be written by hand."""
3595 CustomHandler
.__init
__(self
)
3597 def InitFunction(self
, func
):
3598 """Overrriden from TypeHandler."""
3599 if (func
.name
== 'CompressedTexImage2DBucket'):
3600 func
.cmd_args
= func
.cmd_args
[:-1]
3601 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
3603 CustomHandler
.InitFunction(self
, func
)
3605 def WriteServiceImplementation(self
, func
, file):
3606 """Overrriden from TypeHandler."""
3609 def WriteBucketServiceImplementation(self
, func
, file):
3610 """Overrriden from TypeHandler."""
3613 def WriteServiceUnitTest(self
, func
, file):
3614 """Overrriden from TypeHandler."""
3615 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3617 def WriteImmediateServiceUnitTest(self
, func
, file):
3618 """Overrriden from TypeHandler."""
3619 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3621 def WriteImmediateServiceImplementation(self
, func
, file):
3622 """Overrriden from TypeHandler."""
3625 def WriteImmediateFormatTest(self
, func
, file):
3626 """Overrriden from TypeHandler."""
3627 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
3629 def WriteGLES2Implementation(self
, func
, file):
3630 """Overrriden from TypeHandler."""
3631 if func
.GetInfo('impl_func'):
3632 super(ManualHandler
, self
).WriteGLES2Implementation(func
, file)
3634 def WriteGLES2ImplementationHeader(self
, func
, file):
3635 """Overrriden from TypeHandler."""
3636 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3637 (func
.return_type
, func
.original_name
,
3638 func
.MakeTypedOriginalArgString("")))
3641 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3642 """Overrriden from TypeHandler."""
3643 # TODO(gman): Move this data to _FUNCTION_INFO?
3644 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, file)
3647 class DataHandler(TypeHandler
):
3648 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
3649 glCompressedTexImage2D, glCompressedTexImageSub2D."""
3651 TypeHandler
.__init
__(self
)
3653 def InitFunction(self
, func
):
3654 """Overrriden from TypeHandler."""
3655 if func
.name
== 'CompressedTexSubImage2DBucket':
3656 func
.cmd_args
= func
.cmd_args
[:-1]
3657 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
3659 def WriteGetDataSizeCode(self
, func
, file):
3660 """Overrriden from TypeHandler."""
3661 # TODO(gman): Move this data to _FUNCTION_INFO?
3663 if name
.endswith("Immediate"):
3665 if name
== 'BufferData' or name
== 'BufferSubData':
3666 file.Write(" uint32 data_size = size;\n")
3667 elif (name
== 'CompressedTexImage2D' or
3668 name
== 'CompressedTexSubImage2D'):
3669 file.Write(" uint32 data_size = imageSize;\n")
3670 elif (name
== 'CompressedTexSubImage2DBucket'):
3671 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
3672 file.Write(" uint32 data_size = bucket->size();\n")
3673 file.Write(" GLsizei imageSize = data_size;\n")
3674 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
3675 code
= """ uint32 data_size;
3676 if (!GLES2Util::ComputeImageDataSize(
3677 width, height, format, type, unpack_alignment_, &data_size)) {
3678 return error::kOutOfBounds;
3683 file.Write("// uint32 data_size = 0; // TODO(gman): get correct size!\n")
3685 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3686 """Overrriden from TypeHandler."""
3689 def WriteImmediateCmdSizeTest(self
, func
, file):
3690 """Overrriden from TypeHandler."""
3691 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
3693 def WriteImmediateCmdInit(self
, func
, file):
3694 """Overrriden from TypeHandler."""
3695 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
3696 self
.WriteImmediateCmdGetTotalSize(func
, file)
3697 file.Write(" SetHeader(total_size);\n")
3698 args
= func
.GetCmdArgs()
3700 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
3704 def WriteImmediateCmdSet(self
, func
, file):
3705 """Overrriden from TypeHandler."""
3706 copy_args
= func
.MakeCmdArgString("_", False)
3707 file.Write(" void* Set(void* cmd%s) {\n" %
3708 func
.MakeTypedCmdArgString("_", True))
3709 self
.WriteImmediateCmdGetTotalSize(func
, file)
3710 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
3711 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3712 "cmd, total_size);\n")
3716 def WriteImmediateFormatTest(self
, func
, file):
3717 """Overrriden from TypeHandler."""
3718 # TODO(gman): Remove this exception.
3719 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
3722 def WriteServiceUnitTest(self
, func
, file):
3723 """Overrriden from TypeHandler."""
3724 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3726 def WriteImmediateServiceUnitTest(self
, func
, file):
3727 """Overrriden from TypeHandler."""
3728 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3730 def WriteBucketServiceImplementation(self
, func
, file):
3731 """Overrriden from TypeHandler."""
3732 if not func
.name
== 'CompressedTexSubImage2DBucket':
3733 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, file)
3736 class BindHandler(TypeHandler
):
3737 """Handler for glBind___ type functions."""
3740 TypeHandler
.__init
__(self
)
3742 def WriteServiceUnitTest(self
, func
, file):
3743 """Overrriden from TypeHandler."""
3745 if len(func
.GetOriginalArgs()) == 1:
3747 TEST_F(%(test_name)s, %(name)sValidArgs) {
3748 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3749 SpecializedSetup<cmds::%(name)s, 0>(true);
3752 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3753 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3756 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3757 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
3758 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3759 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3760 SpecializedSetup<cmds::%(name)s, 0>(true);
3762 cmd.Init(kNewClientId);
3763 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3764 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3765 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3770 self
.WriteValidUnitTest(func
, file, valid_test
, {
3771 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
3772 'gl_gen_func_name': func
.GetInfo("gen_func"),
3776 TEST_F(%(test_name)s, %(name)sValidArgs) {
3777 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3778 SpecializedSetup<cmds::%(name)s, 0>(true);
3781 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3782 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3785 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3786 EXPECT_CALL(*gl_, %(gl_func_name)s(%(first_gl_arg)s, kNewServiceId));
3787 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3788 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3789 SpecializedSetup<cmds::%(name)s, 0>(true);
3791 cmd.Init(%(first_arg)s, kNewClientId);
3792 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3793 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3794 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3799 self
.WriteValidUnitTest(func
, file, valid_test
, {
3800 'first_arg': func
.GetOriginalArgs()[0].GetValidArg(func
, 0, 0),
3801 'first_gl_arg': func
.GetOriginalArgs()[0].GetValidGLArg(func
, 0, 0),
3802 'resource_type': func
.GetOriginalArgs()[1].resource_type
,
3803 'gl_gen_func_name': func
.GetInfo("gen_func"),
3807 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3808 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3809 SpecializedSetup<cmds::%(name)s, 0>(false);
3812 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3815 self
.WriteInvalidUnitTest(func
, file, invalid_test
)
3817 def WriteGLES2Implementation(self
, func
, file):
3818 """Writes the GLES2 Implemention."""
3820 impl_func
= func
.GetInfo('impl_func')
3821 impl_decl
= func
.GetInfo('impl_decl')
3823 if (func
.can_auto_generate
and
3824 (impl_func
== None or impl_func
== True) and
3825 (impl_decl
== None or impl_decl
== True)):
3827 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3828 (func
.return_type
, func
.original_name
,
3829 func
.MakeTypedOriginalArgString("")))
3830 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3831 func
.WriteDestinationInitalizationValidation(file)
3832 self
.WriteClientGLCallLog(func
, file)
3833 for arg
in func
.GetOriginalArgs():
3834 arg
.WriteClientSideValidationCode(file, func
)
3836 code
= """ if (Is%(type)sReservedId(%(id)s)) {
3837 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
3840 if (Bind%(type)sHelper(%(arg_string)s)) {
3841 helper_->%(name)s(%(arg_string)s);
3848 if len(func
.GetOriginalArgs()) == 1:
3849 # Bind functions that have no target (like BindVertexArrayOES)
3850 name_arg
= func
.GetOriginalArgs()[0]
3852 # Bind functions that have both a target and a name (like BindTexture)
3853 name_arg
= func
.GetOriginalArgs()[1]
3857 'arg_string': func
.MakeOriginalArgString(""),
3858 'id': name_arg
.name
,
3859 'type': name_arg
.resource_type
,
3860 'lc_type': name_arg
.resource_type
.lower(),
3863 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3864 """Overrriden from TypeHandler."""
3865 client_test
= func
.GetInfo('client_test')
3866 if client_test
== False:
3869 TEST_F(GLES2ImplementationTest, %(name)s) {
3874 expected.cmd.Init(%(cmd_args)s);
3876 gl_->%(name)s(%(args)s);
3877 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3879 gl_->%(name)s(%(args)s);
3880 EXPECT_TRUE(NoCommandsWritten());
3883 cmd_arg_strings
= []
3884 for count
, arg
in enumerate(func
.GetCmdArgs()):
3885 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
3888 for count
, arg
in enumerate(func
.GetOriginalArgs()):
3889 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
3892 'args': ", ".join(gl_arg_strings
),
3893 'cmd_args': ", ".join(cmd_arg_strings
),
3897 class GENnHandler(TypeHandler
):
3898 """Handler for glGen___ type functions."""
3901 TypeHandler
.__init
__(self
)
3903 def InitFunction(self
, func
):
3904 """Overrriden from TypeHandler."""
3907 def WriteGetDataSizeCode(self
, func
, file):
3908 """Overrriden from TypeHandler."""
3909 code
= """ uint32 data_size;
3910 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
3911 return error::kOutOfBounds;
3916 def WriteHandlerImplementation (self
, func
, file):
3917 """Overrriden from TypeHandler."""
3918 file.Write(" if (!%sHelper(n, %s)) {\n"
3919 " return error::kInvalidArguments;\n"
3921 (func
.name
, func
.GetLastOriginalArg().name
))
3923 def WriteImmediateHandlerImplementation(self
, func
, file):
3924 """Overrriden from TypeHandler."""
3925 file.Write(" if (!%sHelper(n, %s)) {\n"
3926 " return error::kInvalidArguments;\n"
3928 (func
.original_name
, func
.GetLastOriginalArg().name
))
3930 def WriteGLES2Implementation(self
, func
, file):
3931 """Overrriden from TypeHandler."""
3932 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
3933 for (GLsizei i = 0; i < n; ++i) {
3934 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
3936 });""" % func
.GetOriginalArgs()[1].name
)
3938 'log_code': log_code
,
3939 'return_type': func
.return_type
,
3940 'name': func
.original_name
,
3941 'typed_args': func
.MakeTypedOriginalArgString(""),
3942 'args': func
.MakeOriginalArgString(""),
3943 'resource_types': func
.GetInfo('resource_types'),
3944 'count_name': func
.GetOriginalArgs()[0].name
,
3947 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
3949 func
.WriteDestinationInitalizationValidation(file)
3950 self
.WriteClientGLCallLog(func
, file)
3951 for arg
in func
.GetOriginalArgs():
3952 arg
.WriteClientSideValidationCode(file, func
)
3953 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
3954 GetIdHandler(id_namespaces::k%(resource_types)s)->
3955 MakeIds(this, 0, %(args)s);
3956 %(name)sHelper(%(args)s);
3957 helper_->%(name)sImmediate(%(args)s);
3958 helper_->CommandBufferHelper::Flush();
3964 file.Write(code
% args
)
3966 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3967 """Overrriden from TypeHandler."""
3969 TEST_F(GLES2ImplementationTest, %(name)s) {
3970 GLuint ids[2] = { 0, };
3972 cmds::%(name)sImmediate gen;
3976 expected.gen.Init(arraysize(ids), &ids[0]);
3977 expected.data[0] = k%(types)sStartId;
3978 expected.data[1] = k%(types)sStartId + 1;
3979 gl_->%(name)s(arraysize(ids), &ids[0]);
3980 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3981 EXPECT_EQ(k%(types)sStartId, ids[0]);
3982 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
3987 'types': func
.GetInfo('resource_types'),
3990 def WriteServiceUnitTest(self
, func
, file):
3991 """Overrriden from TypeHandler."""
3993 TEST_F(%(test_name)s, %(name)sValidArgs) {
3994 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
3995 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3996 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
3997 SpecializedSetup<cmds::%(name)s, 0>(true);
4000 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4001 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4002 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4005 self
.WriteValidUnitTest(func
, file, valid_test
, {
4006 'resource_name': func
.GetInfo('resource_type'),
4009 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4010 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4011 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4012 SpecializedSetup<cmds::%(name)s, 0>(false);
4015 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
4018 self
.WriteValidUnitTest(func
, file, invalid_test
, {
4019 'resource_name': func
.GetInfo('resource_type').lower(),
4022 def WriteImmediateServiceUnitTest(self
, func
, file):
4023 """Overrriden from TypeHandler."""
4025 TEST_F(%(test_name)s, %(name)sValidArgs) {
4026 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4027 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4028 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4029 GLuint temp = kNewClientId;
4030 SpecializedSetup<cmds::%(name)s, 0>(true);
4031 cmd->Init(1, &temp);
4032 EXPECT_EQ(error::kNoError,
4033 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4034 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4035 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4038 self
.WriteValidUnitTest(func
, file, valid_test
, {
4039 'resource_name': func
.GetInfo('resource_type'),
4042 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4043 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4044 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4045 SpecializedSetup<cmds::%(name)s, 0>(false);
4046 cmd->Init(1, &client_%(resource_name)s_id_);
4047 EXPECT_EQ(error::kInvalidArguments,
4048 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4051 self
.WriteValidUnitTest(func
, file, invalid_test
, {
4052 'resource_name': func
.GetInfo('resource_type').lower(),
4055 def WriteImmediateCmdComputeSize(self
, func
, file):
4056 """Overrriden from TypeHandler."""
4057 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4059 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4062 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4063 file.Write(" return static_cast<uint32>(\n")
4064 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4068 def WriteImmediateCmdSetHeader(self
, func
, file):
4069 """Overrriden from TypeHandler."""
4070 file.Write(" void SetHeader(GLsizei n) {\n")
4071 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4075 def WriteImmediateCmdInit(self
, func
, file):
4076 """Overrriden from TypeHandler."""
4077 last_arg
= func
.GetLastOriginalArg()
4078 file.Write(" void Init(%s, %s _%s) {\n" %
4079 (func
.MakeTypedCmdArgString("_"),
4080 last_arg
.type, last_arg
.name
))
4081 file.Write(" SetHeader(_n);\n")
4082 args
= func
.GetCmdArgs()
4084 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4085 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4086 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
4090 def WriteImmediateCmdSet(self
, func
, file):
4091 """Overrriden from TypeHandler."""
4092 last_arg
= func
.GetLastOriginalArg()
4093 copy_args
= func
.MakeCmdArgString("_", False)
4094 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4095 (func
.MakeTypedCmdArgString("_", True),
4096 last_arg
.type, last_arg
.name
))
4097 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4098 (copy_args
, last_arg
.name
))
4099 file.Write(" const uint32 size = ComputeSize(_n);\n")
4100 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4105 def WriteImmediateCmdHelper(self
, func
, file):
4106 """Overrriden from TypeHandler."""
4107 code
= """ void %(name)s(%(typed_args)s) {
4108 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4109 gles2::cmds::%(name)s* c =
4110 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4119 "typed_args": func
.MakeTypedOriginalArgString(""),
4120 "args": func
.MakeOriginalArgString(""),
4123 def WriteImmediateFormatTest(self
, func
, file):
4124 """Overrriden from TypeHandler."""
4125 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4126 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4127 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4128 (func
.name
, func
.name
))
4129 file.Write(" void* next_cmd = cmd.Set(\n")
4130 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4131 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4133 file.Write(" cmd.header.command);\n")
4134 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4135 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4136 file.Write(" cmd.header.size * 4u);\n")
4137 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4138 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4139 file.Write(" next_cmd, sizeof(cmd) +\n")
4140 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4141 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4146 class CreateHandler(TypeHandler
):
4147 """Handler for glCreate___ type functions."""
4150 TypeHandler
.__init
__(self
)
4152 def InitFunction(self
, func
):
4153 """Overrriden from TypeHandler."""
4154 func
.AddCmdArg(Argument("client_id", 'uint32'))
4156 def WriteServiceUnitTest(self
, func
, file):
4157 """Overrriden from TypeHandler."""
4159 TEST_F(%(test_name)s, %(name)sValidArgs) {
4160 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4161 .WillOnce(Return(kNewServiceId));
4162 SpecializedSetup<cmds::%(name)s, 0>(true);
4164 cmd.Init(%(args)s%(comma)skNewClientId);
4165 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4166 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4167 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4171 if len(func
.GetOriginalArgs()):
4173 self
.WriteValidUnitTest(func
, file, valid_test
, {
4175 'resource_type': func
.name
[6:],
4178 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4179 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4180 SpecializedSetup<cmds::%(name)s, 0>(false);
4182 cmd.Init(%(args)s%(comma)skNewClientId);
4183 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
4186 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
4190 def WriteHandlerImplementation (self
, func
, file):
4191 """Overrriden from TypeHandler."""
4192 file.Write(" uint32 client_id = c.client_id;\n")
4193 file.Write(" if (!%sHelper(%s)) {\n" %
4194 (func
.name
, func
.MakeCmdArgString("")))
4195 file.Write(" return error::kInvalidArguments;\n")
4198 def WriteGLES2Implementation(self
, func
, file):
4199 """Overrriden from TypeHandler."""
4200 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4201 (func
.return_type
, func
.original_name
,
4202 func
.MakeTypedOriginalArgString("")))
4203 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4204 func
.WriteDestinationInitalizationValidation(file)
4205 self
.WriteClientGLCallLog(func
, file)
4206 for arg
in func
.GetOriginalArgs():
4207 arg
.WriteClientSideValidationCode(file, func
)
4208 file.Write(" GLuint client_id;\n")
4210 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
4211 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
4212 file.Write(" helper_->%s(%s);\n" %
4213 (func
.name
, func
.MakeCmdArgString("")))
4214 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
4215 file.Write(" CheckGLError();\n")
4216 file.Write(" return client_id;\n")
4221 class DeleteHandler(TypeHandler
):
4222 """Handler for glDelete___ single resource type functions."""
4225 TypeHandler
.__init
__(self
)
4227 def WriteServiceImplementation(self
, func
, file):
4228 """Overrriden from TypeHandler."""
4231 def WriteGLES2Implementation(self
, func
, file):
4232 """Overrriden from TypeHandler."""
4233 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4234 (func
.return_type
, func
.original_name
,
4235 func
.MakeTypedOriginalArgString("")))
4236 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4237 func
.WriteDestinationInitalizationValidation(file)
4238 self
.WriteClientGLCallLog(func
, file)
4239 for arg
in func
.GetOriginalArgs():
4240 arg
.WriteClientSideValidationCode(file, func
)
4242 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
4243 file.Write(" %sHelper(%s);\n" %
4244 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
4245 file.Write(" CheckGLError();\n")
4250 class DELnHandler(TypeHandler
):
4251 """Handler for glDelete___ type functions."""
4254 TypeHandler
.__init
__(self
)
4256 def WriteGetDataSizeCode(self
, func
, file):
4257 """Overrriden from TypeHandler."""
4258 code
= """ uint32 data_size;
4259 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4260 return error::kOutOfBounds;
4265 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4266 """Overrriden from TypeHandler."""
4268 TEST_F(GLES2ImplementationTest, %(name)s) {
4269 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
4271 cmds::%(name)sImmediate del;
4275 expected.del.Init(arraysize(ids), &ids[0]);
4276 expected.data[0] = k%(types)sStartId;
4277 expected.data[1] = k%(types)sStartId + 1;
4278 gl_->%(name)s(arraysize(ids), &ids[0]);
4279 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4284 'types': func
.GetInfo('resource_types'),
4287 def WriteServiceUnitTest(self
, func
, file):
4288 """Overrriden from TypeHandler."""
4290 TEST_F(%(test_name)s, %(name)sValidArgs) {
4293 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4295 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4296 SpecializedSetup<cmds::%(name)s, 0>(true);
4299 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4300 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4302 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4305 self
.WriteValidUnitTest(func
, file, valid_test
, {
4306 'resource_name': func
.GetInfo('resource_type').lower(),
4307 'upper_resource_name': func
.GetInfo('resource_type'),
4310 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4311 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
4312 SpecializedSetup<cmds::%(name)s, 0>(false);
4315 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4318 self
.WriteValidUnitTest(func
, file, invalid_test
)
4320 def WriteImmediateServiceUnitTest(self
, func
, file):
4321 """Overrriden from TypeHandler."""
4323 TEST_F(%(test_name)s, %(name)sValidArgs) {
4326 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4328 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4329 SpecializedSetup<cmds::%(name)s, 0>(true);
4330 cmd.Init(1, &client_%(resource_name)s_id_);
4331 EXPECT_EQ(error::kNoError,
4332 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
4333 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4335 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4338 self
.WriteValidUnitTest(func
, file, valid_test
, {
4339 'resource_name': func
.GetInfo('resource_type').lower(),
4340 'upper_resource_name': func
.GetInfo('resource_type'),
4343 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4344 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4345 SpecializedSetup<cmds::%(name)s, 0>(false);
4346 GLuint temp = kInvalidClientId;
4348 EXPECT_EQ(error::kNoError,
4349 ExecuteImmediateCmd(cmd, sizeof(temp)));
4352 self
.WriteValidUnitTest(func
, file, invalid_test
)
4354 def WriteHandlerImplementation (self
, func
, file):
4355 """Overrriden from TypeHandler."""
4356 file.Write(" %sHelper(n, %s);\n" %
4357 (func
.name
, func
.GetLastOriginalArg().name
))
4359 def WriteImmediateHandlerImplementation (self
, func
, file):
4360 """Overrriden from TypeHandler."""
4361 file.Write(" %sHelper(n, %s);\n" %
4362 (func
.original_name
, func
.GetLastOriginalArg().name
))
4364 def WriteGLES2Implementation(self
, func
, file):
4365 """Overrriden from TypeHandler."""
4366 impl_decl
= func
.GetInfo('impl_decl')
4367 if impl_decl
== None or impl_decl
== True:
4369 'return_type': func
.return_type
,
4370 'name': func
.original_name
,
4371 'typed_args': func
.MakeTypedOriginalArgString(""),
4372 'args': func
.MakeOriginalArgString(""),
4373 'resource_type': func
.GetInfo('resource_type').lower(),
4374 'count_name': func
.GetOriginalArgs()[0].name
,
4377 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4379 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4380 func
.WriteDestinationInitalizationValidation(file)
4381 self
.WriteClientGLCallLog(func
, file)
4382 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
4383 for (GLsizei i = 0; i < n; ++i) {
4384 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4387 """ % func
.GetOriginalArgs()[1].name
)
4388 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
4389 for (GLsizei i = 0; i < n; ++i) {
4393 """ % func
.GetOriginalArgs()[1].name
)
4394 for arg
in func
.GetOriginalArgs():
4395 arg
.WriteClientSideValidationCode(file, func
)
4396 code
= """ %(name)sHelper(%(args)s);
4401 file.Write(code
% args
)
4403 def WriteImmediateCmdComputeSize(self
, func
, file):
4404 """Overrriden from TypeHandler."""
4405 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4407 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4410 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4411 file.Write(" return static_cast<uint32>(\n")
4412 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4416 def WriteImmediateCmdSetHeader(self
, func
, file):
4417 """Overrriden from TypeHandler."""
4418 file.Write(" void SetHeader(GLsizei n) {\n")
4419 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4423 def WriteImmediateCmdInit(self
, func
, file):
4424 """Overrriden from TypeHandler."""
4425 last_arg
= func
.GetLastOriginalArg()
4426 file.Write(" void Init(%s, %s _%s) {\n" %
4427 (func
.MakeTypedCmdArgString("_"),
4428 last_arg
.type, last_arg
.name
))
4429 file.Write(" SetHeader(_n);\n")
4430 args
= func
.GetCmdArgs()
4432 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4433 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4434 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
4438 def WriteImmediateCmdSet(self
, func
, file):
4439 """Overrriden from TypeHandler."""
4440 last_arg
= func
.GetLastOriginalArg()
4441 copy_args
= func
.MakeCmdArgString("_", False)
4442 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4443 (func
.MakeTypedCmdArgString("_", True),
4444 last_arg
.type, last_arg
.name
))
4445 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4446 (copy_args
, last_arg
.name
))
4447 file.Write(" const uint32 size = ComputeSize(_n);\n")
4448 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4453 def WriteImmediateCmdHelper(self
, func
, file):
4454 """Overrriden from TypeHandler."""
4455 code
= """ void %(name)s(%(typed_args)s) {
4456 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4457 gles2::cmds::%(name)s* c =
4458 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4467 "typed_args": func
.MakeTypedOriginalArgString(""),
4468 "args": func
.MakeOriginalArgString(""),
4471 def WriteImmediateFormatTest(self
, func
, file):
4472 """Overrriden from TypeHandler."""
4473 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4474 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4475 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4476 (func
.name
, func
.name
))
4477 file.Write(" void* next_cmd = cmd.Set(\n")
4478 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4479 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4481 file.Write(" cmd.header.command);\n")
4482 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4483 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4484 file.Write(" cmd.header.size * 4u);\n")
4485 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4486 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4487 file.Write(" next_cmd, sizeof(cmd) +\n")
4488 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4489 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4494 class GETnHandler(TypeHandler
):
4495 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
4498 TypeHandler
.__init
__(self
)
4500 def AddImmediateFunction(self
, generator
, func
):
4501 """Overrriden from TypeHandler."""
4504 def WriteServiceImplementation(self
, func
, file):
4505 """Overrriden from TypeHandler."""
4507 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
4509 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
4511 last_arg
= func
.GetLastOriginalArg()
4513 all_but_last_args
= func
.GetOriginalArgs()[:-1]
4514 for arg
in all_but_last_args
:
4515 arg
.WriteGetCode(file)
4517 code
= """ typedef cmds::%(func_name)s::Result Result;
4518 GLsizei num_values = 0;
4519 GetNumValuesReturnedForGLGet(pname, &num_values);
4520 Result* result = GetSharedMemoryAs<Result*>(
4521 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
4522 %(last_arg_type)s params = result ? result->GetData() : NULL;
4525 'last_arg_type': last_arg
.type,
4526 'func_name': func
.name
,
4528 func
.WriteHandlerValidation(file)
4529 code
= """ // Check that the client initialized the result.
4530 if (result->size != 0) {
4531 return error::kInvalidArguments;
4534 shadowed
= func
.GetInfo('shadowed')
4536 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
4538 func
.WriteHandlerImplementation(file)
4540 code
= """ result->SetNumResults(num_values);
4541 return error::kNoError;
4545 code
= """ GLenum error = glGetError();
4546 if (error == GL_NO_ERROR) {
4547 result->SetNumResults(num_values);
4549 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
4551 return error::kNoError;
4555 file.Write(code
% {'func_name': func
.name
})
4557 def WriteGLES2Implementation(self
, func
, file):
4558 """Overrriden from TypeHandler."""
4559 impl_decl
= func
.GetInfo('impl_decl')
4560 if impl_decl
== None or impl_decl
== True:
4561 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4562 (func
.return_type
, func
.original_name
,
4563 func
.MakeTypedOriginalArgString("")))
4564 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4565 func
.WriteDestinationInitalizationValidation(file)
4566 self
.WriteClientGLCallLog(func
, file)
4567 for arg
in func
.GetOriginalArgs():
4568 arg
.WriteClientSideValidationCode(file, func
)
4569 all_but_last_args
= func
.GetOriginalArgs()[:-1]
4571 ", ".join(["%s" % arg
.name
for arg
in all_but_last_args
]))
4573 ", ".join(["%s" % arg
.name
for arg
in func
.GetOriginalArgs()]))
4574 self
.WriteTraceEvent(func
, file)
4575 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
4578 typedef cmds::%(func_name)s::Result Result;
4579 Result* result = GetResultAs<Result*>();
4583 result->SetNumResults(0);
4584 helper_->%(func_name)s(%(arg_string)s,
4585 GetResultShmId(), GetResultShmOffset());
4587 result->CopyResult(params);
4588 GPU_CLIENT_LOG_CODE_BLOCK({
4589 for (int32 i = 0; i < result->GetNumResults(); ++i) {
4590 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
4597 'func_name': func
.name
,
4598 'arg_string': arg_string
,
4599 'all_arg_string': all_arg_string
,
4602 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4603 """Writes the GLES2 Implemention unit test."""
4605 TEST_F(GLES2ImplementationTest, %(name)s) {
4609 typedef cmds::%(name)s::Result Result;
4610 Result::Type result = 0;
4612 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
4613 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
4614 EXPECT_CALL(*command_buffer(), OnFlush())
4615 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
4616 .RetiresOnSaturation();
4617 gl_->%(name)s(%(args)s, &result);
4618 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4619 EXPECT_EQ(static_cast<Result::Type>(1), result);
4622 cmd_arg_strings
= []
4623 for count
, arg
in enumerate(func
.GetCmdArgs()[0:-2]):
4624 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
4625 cmd_arg_strings
[0] = '123'
4627 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
4628 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
4629 gl_arg_strings
[0] = '123'
4632 'args': ", ".join(gl_arg_strings
),
4633 'cmd_args': ", ".join(cmd_arg_strings
),
4636 def WriteServiceUnitTest(self
, func
, file):
4637 """Overrriden from TypeHandler."""
4639 TEST_F(%(test_name)s, %(name)sValidArgs) {
4640 EXPECT_CALL(*gl_, GetError())
4641 .WillOnce(Return(GL_NO_ERROR))
4642 .WillOnce(Return(GL_NO_ERROR))
4643 .RetiresOnSaturation();
4644 SpecializedSetup<cmds::%(name)s, 0>(true);
4645 typedef cmds::%(name)s::Result Result;
4646 Result* result = static_cast<Result*>(shared_memory_address_);
4647 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
4651 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4652 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
4654 result->GetNumResults());
4655 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4660 for count
, arg
in enumerate(func
.GetOriginalArgs()[:-1]):
4661 arg_value
= arg
.GetValidGLArg(func
, count
, 0)
4662 gl_arg_strings
.append(arg_value
)
4663 if arg
.name
== 'pname':
4664 valid_pname
= arg_value
4665 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
4666 gl_arg_strings
.append("_")
4668 gl_arg_strings
.append("result->GetData()")
4670 self
.WriteValidUnitTest(func
, file, valid_test
, {
4671 'local_gl_args': ", ".join(gl_arg_strings
),
4672 'valid_pname': valid_pname
,
4676 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4677 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4678 SpecializedSetup<cmds::%(name)s, 0>(false);
4679 cmds::%(name)s::Result* result =
4680 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
4684 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
4685 EXPECT_EQ(0u, result->size);%(gl_error_test)s
4688 self
.WriteInvalidUnitTest(func
, file, invalid_test
)
4691 class PUTHandler(TypeHandler
):
4692 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
4695 TypeHandler
.__init
__(self
)
4697 def WriteServiceUnitTest(self
, func
, file):
4698 """Writes the service unit test for a command."""
4699 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
4700 if func
.GetInfo("first_element_only"):
4702 for count
, arg
in enumerate(func
.GetOriginalArgs()):
4703 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
4704 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
4705 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
4706 ", ".join(gl_arg_strings
))
4708 TEST_F(%(test_name)s, %(name)sValidArgs) {
4709 SpecializedSetup<cmds::%(name)s, 0>(true);
4712 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4714 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4715 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4719 'data_type': func
.GetInfo('data_type'),
4720 'data_value': func
.GetInfo('data_value') or '0',
4721 'expected_call': expected_call
,
4723 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
4726 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4727 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4728 SpecializedSetup<cmds::%(name)s, 0>(false);
4731 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4732 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4735 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
)
4737 def WriteImmediateServiceUnitTest(self
, func
, file):
4738 """Writes the service unit test for a command."""
4740 TEST_F(%(test_name)s, %(name)sValidArgs) {
4741 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4742 SpecializedSetup<cmds::%(name)s, 0>(true);
4743 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4744 cmd.Init(%(gl_args)s, &temp[0]);
4747 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
4748 %(data_type)s*>(ImmediateDataAddress(&cmd))));
4749 EXPECT_EQ(error::kNoError,
4750 ExecuteImmediateCmd(cmd, sizeof(temp)));
4751 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4756 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
4757 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
4758 gl_any_strings
.append("_")
4760 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
4761 'data_type': func
.GetInfo('data_type'),
4762 'data_count': func
.GetInfo('count'),
4763 'data_value': func
.GetInfo('data_value') or '0',
4764 'gl_args': ", ".join(gl_arg_strings
),
4765 'gl_any_args': ", ".join(gl_any_strings
),
4767 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
4770 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4771 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4772 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
4773 SpecializedSetup<cmds::%(name)s, 0>(false);
4774 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4775 cmd.Init(%(all_but_last_args)s, &temp[0]);
4776 EXPECT_EQ(error::%(parse_result)s,
4777 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
4780 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
)
4782 def WriteGetDataSizeCode(self
, func
, file):
4783 """Overrriden from TypeHandler."""
4784 code
= """ uint32 data_size;
4785 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
4786 return error::kOutOfBounds;
4789 file.Write(code
% (func
.info
.data_type
, func
.info
.count
))
4790 if func
.is_immediate
:
4791 file.Write(" if (data_size > immediate_data_size) {\n")
4792 file.Write(" return error::kOutOfBounds;\n")
4795 def WriteGLES2Implementation(self
, func
, file):
4796 """Overrriden from TypeHandler."""
4797 impl_func
= func
.GetInfo('impl_func')
4798 if (impl_func
!= None and impl_func
!= True):
4800 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4801 (func
.return_type
, func
.original_name
,
4802 func
.MakeTypedOriginalArgString("")))
4803 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4804 func
.WriteDestinationInitalizationValidation(file)
4805 self
.WriteClientGLCallLog(func
, file)
4806 last_arg_name
= func
.GetLastOriginalArg().name
4807 values_str
= ' << ", " << '.join(
4808 ["%s[%d]" % (last_arg_name
, ndx
) for ndx
in range(0, func
.info
.count
)])
4809 file.Write(' GPU_CLIENT_LOG("values: " << %s);\n' % values_str
)
4810 for arg
in func
.GetOriginalArgs():
4811 arg
.WriteClientSideValidationCode(file, func
)
4812 file.Write(" helper_->%sImmediate(%s);\n" %
4813 (func
.name
, func
.MakeOriginalArgString("")))
4814 file.Write(" CheckGLError();\n")
4818 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4819 """Writes the GLES2 Implemention unit test."""
4820 client_test
= func
.GetInfo('client_test')
4821 if (client_test
!= None and client_test
!= True):
4824 TEST_F(GLES2ImplementationTest, %(name)s) {
4825 %(type)s data[%(count)d] = {0};
4827 cmds::%(name)sImmediate cmd;
4828 %(type)s data[%(count)d];
4831 for (int jj = 0; jj < %(count)d; ++jj) {
4832 data[jj] = static_cast<%(type)s>(jj);
4835 expected.cmd.Init(%(cmd_args)s, &data[0]);
4836 gl_->%(name)s(%(args)s, &data[0]);
4837 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4840 cmd_arg_strings
= []
4841 for count
, arg
in enumerate(func
.GetCmdArgs()[0:-2]):
4842 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
4844 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
4845 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
4848 'type': func
.GetInfo('data_type'),
4849 'count': func
.GetInfo('count'),
4850 'args': ", ".join(gl_arg_strings
),
4851 'cmd_args': ", ".join(cmd_arg_strings
),
4854 def WriteImmediateCmdComputeSize(self
, func
, file):
4855 """Overrriden from TypeHandler."""
4856 file.Write(" static uint32 ComputeDataSize() {\n")
4857 file.Write(" return static_cast<uint32>(\n")
4858 file.Write(" sizeof(%s) * %d); // NOLINT\n" %
4859 (func
.info
.data_type
, func
.info
.count
))
4862 file.Write(" static uint32 ComputeSize() {\n")
4863 file.Write(" return static_cast<uint32>(\n")
4865 " sizeof(ValueType) + ComputeDataSize()); // NOLINT\n")
4869 def WriteImmediateCmdSetHeader(self
, func
, file):
4870 """Overrriden from TypeHandler."""
4871 file.Write(" void SetHeader() {\n")
4873 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
4877 def WriteImmediateCmdInit(self
, func
, file):
4878 """Overrriden from TypeHandler."""
4879 last_arg
= func
.GetLastOriginalArg()
4880 file.Write(" void Init(%s, %s _%s) {\n" %
4881 (func
.MakeTypedCmdArgString("_"),
4882 last_arg
.type, last_arg
.name
))
4883 file.Write(" SetHeader();\n")
4884 args
= func
.GetCmdArgs()
4886 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4887 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4888 file.Write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
4892 def WriteImmediateCmdSet(self
, func
, file):
4893 """Overrriden from TypeHandler."""
4894 last_arg
= func
.GetLastOriginalArg()
4895 copy_args
= func
.MakeCmdArgString("_", False)
4896 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4897 (func
.MakeTypedCmdArgString("_", True),
4898 last_arg
.type, last_arg
.name
))
4899 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4900 (copy_args
, last_arg
.name
))
4901 file.Write(" const uint32 size = ComputeSize();\n")
4902 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4907 def WriteImmediateCmdHelper(self
, func
, file):
4908 """Overrriden from TypeHandler."""
4909 code
= """ void %(name)s(%(typed_args)s) {
4910 const uint32 size = gles2::cmds::%(name)s::ComputeSize();
4911 gles2::cmds::%(name)s* c =
4912 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4921 "typed_args": func
.MakeTypedOriginalArgString(""),
4922 "args": func
.MakeOriginalArgString(""),
4925 def WriteImmediateFormatTest(self
, func
, file):
4926 """Overrriden from TypeHandler."""
4927 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4928 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
4929 file.Write(" static %s data[] = {\n" % func
.info
.data_type
)
4930 for v
in range(0, func
.info
.count
):
4931 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
4932 (func
.info
.data_type
, v
))
4934 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4935 (func
.name
, func
.name
))
4936 file.Write(" void* next_cmd = cmd.Set(\n")
4938 args
= func
.GetCmdArgs()
4939 for value
, arg
in enumerate(args
):
4940 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
4941 file.Write(",\n data);\n")
4942 args
= func
.GetCmdArgs()
4943 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n"
4945 file.Write(" cmd.header.command);\n")
4946 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4947 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
4948 file.Write(" cmd.header.size * 4u);\n")
4949 for value
, arg
in enumerate(args
):
4950 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4951 (arg
.type, value
+ 11, arg
.name
))
4952 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4953 file.Write(" next_cmd, sizeof(cmd) +\n")
4954 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
4955 file.Write(" // TODO(gman): Check that data was inserted;\n")
4960 class PUTnHandler(TypeHandler
):
4961 """Handler for PUTn 'glUniform__v' type functions."""
4964 TypeHandler
.__init
__(self
)
4966 def WriteServiceUnitTest(self
, func
, file):
4967 """Overridden from TypeHandler."""
4968 TypeHandler
.WriteServiceUnitTest(self
, func
, file)
4971 TEST_F(%(test_name)s, %(name)sValidArgsCountTooLarge) {
4972 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4973 SpecializedSetup<cmds::%(name)s, 0>(true);
4976 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4977 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4982 for count
, arg
in enumerate(func
.GetOriginalArgs()):
4983 # hardcoded to match unit tests.
4985 # the location of the second element of the 2nd uniform.
4986 # defined in GLES2DecoderBase::SetupShaderForUniform
4987 gl_arg_strings
.append("3")
4988 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
4990 # the number of elements that gl will be called with.
4991 gl_arg_strings
.append("3")
4992 # the number of elements requested in the command.
4993 arg_strings
.append("5")
4995 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
4996 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
4998 'gl_args': ", ".join(gl_arg_strings
),
4999 'args': ", ".join(arg_strings
),
5001 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
5003 def WriteImmediateServiceUnitTest(self
, func
, file):
5004 """Overridden from TypeHandler."""
5006 TEST_F(%(test_name)s, %(name)sValidArgs) {
5007 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5010 %(gl_func_name)s(%(gl_args)s,
5011 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
5012 SpecializedSetup<cmds::%(name)s, 0>(true);
5013 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5014 cmd.Init(%(args)s, &temp[0]);
5015 EXPECT_EQ(error::kNoError,
5016 ExecuteImmediateCmd(cmd, sizeof(temp)));
5017 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5023 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
5024 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
5025 gl_any_strings
.append("_")
5026 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
5028 'data_type': func
.GetInfo('data_type'),
5029 'data_count': func
.GetInfo('count'),
5030 'args': ", ".join(arg_strings
),
5031 'gl_args': ", ".join(gl_arg_strings
),
5032 'gl_any_args': ", ".join(gl_any_strings
),
5034 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
5037 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5038 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5039 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5040 SpecializedSetup<cmds::%(name)s, 0>(false);
5041 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5042 cmd.Init(%(all_but_last_args)s, &temp[0]);
5043 EXPECT_EQ(error::%(parse_result)s,
5044 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5047 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
)
5049 def WriteGetDataSizeCode(self
, func
, file):
5050 """Overrriden from TypeHandler."""
5051 code
= """ uint32 data_size;
5052 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
5053 return error::kOutOfBounds;
5056 file.Write(code
% (func
.info
.data_type
, func
.info
.count
))
5057 if func
.is_immediate
:
5058 file.Write(" if (data_size > immediate_data_size) {\n")
5059 file.Write(" return error::kOutOfBounds;\n")
5062 def WriteGLES2Implementation(self
, func
, file):
5063 """Overrriden from TypeHandler."""
5064 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5065 (func
.return_type
, func
.original_name
,
5066 func
.MakeTypedOriginalArgString("")))
5067 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5068 func
.WriteDestinationInitalizationValidation(file)
5069 self
.WriteClientGLCallLog(func
, file)
5070 last_arg_name
= func
.GetLastOriginalArg().name
5071 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5072 for (GLsizei i = 0; i < count; ++i) {
5074 values_str
= ' << ", " << '.join(
5075 ["%s[%d + i * %d]" % (
5076 last_arg_name
, ndx
, func
.info
.count
) for ndx
in range(
5077 0, func
.info
.count
)])
5078 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
5079 file.Write(" }\n });\n")
5080 for arg
in func
.GetOriginalArgs():
5081 arg
.WriteClientSideValidationCode(file, func
)
5082 file.Write(" helper_->%sImmediate(%s);\n" %
5083 (func
.name
, func
.MakeOriginalArgString("")))
5084 file.Write(" CheckGLError();\n")
5088 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5089 """Writes the GLES2 Implemention unit test."""
5091 TEST_F(GLES2ImplementationTest, %(name)s) {
5092 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5094 cmds::%(name)sImmediate cmd;
5095 %(type)s data[%(count_param)d][%(count)d];
5099 for (int ii = 0; ii < %(count_param)d; ++ii) {
5100 for (int jj = 0; jj < %(count)d; ++jj) {
5101 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5104 expected.cmd.Init(%(cmd_args)s, &data[0][0]);
5105 gl_->%(name)s(%(args)s, &data[0][0]);
5106 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5109 cmd_arg_strings
= []
5110 for count
, arg
in enumerate(func
.GetCmdArgs()[0:-2]):
5111 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
5114 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
5115 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
5116 if arg
.name
== "count":
5117 count_param
= int(arg
.GetValidClientSideArg(func
, count
, 0))
5120 'type': func
.GetInfo('data_type'),
5121 'count': func
.GetInfo('count'),
5122 'args': ", ".join(gl_arg_strings
),
5123 'cmd_args': ", ".join(cmd_arg_strings
),
5124 'count_param': count_param
,
5127 def WriteImmediateCmdComputeSize(self
, func
, file):
5128 """Overrriden from TypeHandler."""
5129 file.Write(" static uint32 ComputeDataSize(GLsizei count) {\n")
5130 file.Write(" return static_cast<uint32>(\n")
5131 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
5132 (func
.info
.data_type
, func
.info
.count
))
5135 file.Write(" static uint32 ComputeSize(GLsizei count) {\n")
5136 file.Write(" return static_cast<uint32>(\n")
5138 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
5142 def WriteImmediateCmdSetHeader(self
, func
, file):
5143 """Overrriden from TypeHandler."""
5144 file.Write(" void SetHeader(GLsizei count) {\n")
5146 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
5150 def WriteImmediateCmdInit(self
, func
, file):
5151 """Overrriden from TypeHandler."""
5152 last_arg
= func
.GetLastOriginalArg()
5153 file.Write(" void Init(%s, %s _%s) {\n" %
5154 (func
.MakeTypedCmdArgString("_"),
5155 last_arg
.type, last_arg
.name
))
5156 file.Write(" SetHeader(_count);\n")
5157 args
= func
.GetCmdArgs()
5159 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5160 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5161 file.Write(" _%s, ComputeDataSize(_count));\n" % last_arg
.name
)
5165 def WriteImmediateCmdSet(self
, func
, file):
5166 """Overrriden from TypeHandler."""
5167 last_arg
= func
.GetLastOriginalArg()
5168 copy_args
= func
.MakeCmdArgString("_", False)
5169 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5170 (func
.MakeTypedCmdArgString("_", True),
5171 last_arg
.type, last_arg
.name
))
5172 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5173 (copy_args
, last_arg
.name
))
5174 file.Write(" const uint32 size = ComputeSize(_count);\n")
5175 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5180 def WriteImmediateCmdHelper(self
, func
, file):
5181 """Overrriden from TypeHandler."""
5182 code
= """ void %(name)s(%(typed_args)s) {
5183 const uint32 size = gles2::cmds::%(name)s::ComputeSize(count);
5184 gles2::cmds::%(name)s* c =
5185 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5194 "typed_args": func
.MakeTypedOriginalArgString(""),
5195 "args": func
.MakeOriginalArgString(""),
5198 def WriteImmediateFormatTest(self
, func
, file):
5199 """Overrriden from TypeHandler."""
5200 args
= func
.GetCmdArgs()
5202 for value
, arg
in enumerate(args
):
5203 if arg
.name
== "count":
5204 count_param
= int(arg
.GetValidClientSideArg(func
, value
, 0))
5205 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5206 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5207 file.Write(" static %s data[] = {\n" % func
.info
.data_type
)
5208 for v
in range(0, func
.info
.count
* count_param
):
5209 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5210 (func
.info
.data_type
, v
))
5212 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5213 (func
.name
, func
.name
))
5214 file.Write(" const GLsizei kNumElements = %d;\n" % count_param
)
5215 file.Write(" const size_t kExpectedCmdSize =\n")
5216 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
5217 (func
.info
.data_type
, func
.info
.count
))
5218 file.Write(" void* next_cmd = cmd.Set(\n")
5220 for value
, arg
in enumerate(args
):
5221 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
5222 file.Write(",\n data);\n")
5223 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
5225 file.Write(" cmd.header.command);\n")
5226 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
5227 for value
, arg
in enumerate(args
):
5228 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5229 (arg
.type, value
+ 1, arg
.name
))
5230 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5231 file.Write(" next_cmd, sizeof(cmd) +\n")
5232 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5233 file.Write(" // TODO(gman): Check that data was inserted;\n")
5238 class PUTXnHandler(TypeHandler
):
5239 """Handler for glUniform?f functions."""
5241 TypeHandler
.__init
__(self
)
5243 def WriteHandlerImplementation(self
, func
, file):
5244 """Overrriden from TypeHandler."""
5245 code
= """ %(type)s temp[%(count)s] = { %(values)s};
5246 Do%(name)sv(%(location)s, 1, &temp[0]);
5249 args
= func
.GetOriginalArgs()
5250 count
= int(func
.GetInfo('count'))
5251 num_args
= len(args
)
5252 for ii
in range(count
):
5253 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
5257 'count': func
.GetInfo('count'),
5258 'type': func
.GetInfo('data_type'),
5259 'location': args
[0].name
,
5260 'args': func
.MakeOriginalArgString(""),
5264 def WriteServiceUnitTest(self
, func
, file):
5265 """Overrriden from TypeHandler."""
5267 TEST_F(%(test_name)s, %(name)sValidArgs) {
5268 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
5269 SpecializedSetup<cmds::%(name)s, 0>(true);
5272 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5273 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5276 args
= func
.GetOriginalArgs()
5277 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
, 0, 0)
5278 self
.WriteValidUnitTest(func
, file, valid_test
, {
5280 'count': func
.GetInfo('count'),
5281 'local_args': local_args
,
5285 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5286 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
5287 SpecializedSetup<cmds::%(name)s, 0>(false);
5290 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5293 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5294 'name': func
.GetInfo('name'),
5295 'count': func
.GetInfo('count'),
5299 class GLcharHandler(CustomHandler
):
5300 """Handler for functions that pass a single string ."""
5303 CustomHandler
.__init
__(self
)
5305 def WriteImmediateCmdComputeSize(self
, func
, file):
5306 """Overrriden from TypeHandler."""
5307 file.Write(" static uint32 ComputeSize(uint32 data_size) {\n")
5308 file.Write(" return static_cast<uint32>(\n")
5309 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
5312 def WriteImmediateCmdSetHeader(self
, func
, file):
5313 """Overrriden from TypeHandler."""
5315 void SetHeader(uint32 data_size) {
5316 header.SetCmdBySize<ValueType>(data_size);
5321 def WriteImmediateCmdInit(self
, func
, file):
5322 """Overrriden from TypeHandler."""
5323 last_arg
= func
.GetLastOriginalArg()
5324 args
= func
.GetCmdArgs()
5327 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
5329 void Init(%(typed_args)s, uint32 _data_size) {
5330 SetHeader(_data_size);
5332 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
5337 "typed_args": func
.MakeTypedOriginalArgString("_"),
5338 "set_code": "\n".join(set_code
),
5339 "last_arg": last_arg
.name
5342 def WriteImmediateCmdSet(self
, func
, file):
5343 """Overrriden from TypeHandler."""
5344 last_arg
= func
.GetLastOriginalArg()
5345 file.Write(" void* Set(void* cmd%s, uint32 _data_size) {\n" %
5346 func
.MakeTypedOriginalArgString("_", True))
5347 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
5348 func
.MakeOriginalArgString("_"))
5349 file.Write(" return NextImmediateCmdAddress<ValueType>("
5350 "cmd, _data_size);\n")
5354 def WriteImmediateCmdHelper(self
, func
, file):
5355 """Overrriden from TypeHandler."""
5356 code
= """ void %(name)s(%(typed_args)s) {
5357 const uint32 data_size = strlen(name);
5358 gles2::cmds::%(name)s* c =
5359 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
5361 c->Init(%(args)s, data_size);
5368 "typed_args": func
.MakeTypedOriginalArgString(""),
5369 "args": func
.MakeOriginalArgString(""),
5373 def WriteImmediateFormatTest(self
, func
, file):
5374 """Overrriden from TypeHandler."""
5377 all_but_last_arg
= func
.GetCmdArgs()[:-1]
5378 for value
, arg
in enumerate(all_but_last_arg
):
5379 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
5380 for value
, arg
in enumerate(all_but_last_arg
):
5381 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
5382 (arg
.type, value
+ 11, arg
.name
))
5384 TEST_F(GLES2FormatTest, %(func_name)s) {
5385 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
5386 static const char* const test_str = \"test string\";
5387 void* next_cmd = cmd.Set(
5392 EXPECT_EQ(static_cast<uint32>(cmds::%(func_name)s::kCmdId),
5393 cmd.header.command);
5394 EXPECT_EQ(sizeof(cmd) +
5395 RoundSizeToMultipleOfEntries(strlen(test_str)),
5396 cmd.header.size * 4u);
5397 EXPECT_EQ(static_cast<char*>(next_cmd),
5398 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
5399 RoundSizeToMultipleOfEntries(strlen(test_str)));
5401 EXPECT_EQ(static_cast<uint32>(strlen(test_str)), cmd.data_size);
5402 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
5405 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
5406 sizeof(cmd) + strlen(test_str));
5411 'func_name': func
.name
,
5412 'init_code': "\n".join(init_code
),
5413 'check_code': "\n".join(check_code
),
5417 class GLcharNHandler(CustomHandler
):
5418 """Handler for functions that pass a single string with an optional len."""
5421 CustomHandler
.__init
__(self
)
5423 def InitFunction(self
, func
):
5424 """Overrriden from TypeHandler."""
5426 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5428 def AddImmediateFunction(self
, generator
, func
):
5429 """Overrriden from TypeHandler."""
5432 def AddBucketFunction(self
, generator
, func
):
5433 """Overrriden from TypeHandler."""
5436 def WriteServiceImplementation(self
, func
, file):
5437 """Overrriden from TypeHandler."""
5438 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
5439 uint32 immediate_data_size, const gles2::cmds::%(name)s& c) {
5440 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
5441 Bucket* bucket = GetBucket(bucket_id);
5442 if (!bucket || bucket->size() == 0) {
5443 return error::kInvalidArguments;
5446 if (!bucket->GetAsString(&str)) {
5447 return error::kInvalidArguments;
5449 %(gl_func_name)s(0, str.c_str());
5450 return error::kNoError;
5455 'gl_func_name': func
.GetGLFunctionName(),
5456 'bucket_id': func
.cmd_args
[0].name
,
5460 class IsHandler(TypeHandler
):
5461 """Handler for glIs____ type and glGetError functions."""
5464 TypeHandler
.__init
__(self
)
5466 def InitFunction(self
, func
):
5467 """Overrriden from TypeHandler."""
5468 func
.AddCmdArg(Argument("result_shm_id", 'uint32'))
5469 func
.AddCmdArg(Argument("result_shm_offset", 'uint32'))
5470 if func
.GetInfo('result') == None:
5471 func
.AddInfo('result', ['uint32'])
5473 def WriteServiceUnitTest(self
, func
, file):
5474 """Overrriden from TypeHandler."""
5476 TEST_F(%(test_name)s, %(name)sValidArgs) {
5477 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5478 SpecializedSetup<cmds::%(name)s, 0>(true);
5480 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5481 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5482 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5486 if len(func
.GetOriginalArgs()):
5488 self
.WriteValidUnitTest(func
, file, valid_test
, {
5493 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5494 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5495 SpecializedSetup<cmds::%(name)s, 0>(false);
5497 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5498 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5501 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5506 TEST_F(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
5507 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5508 SpecializedSetup<cmds::%(name)s, 0>(false);
5510 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
5511 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5512 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
5513 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5516 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5520 def WriteServiceImplementation(self
, func
, file):
5521 """Overrriden from TypeHandler."""
5523 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
5525 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
5527 args
= func
.GetOriginalArgs()
5529 arg
.WriteGetCode(file)
5531 code
= """ typedef cmds::%(func_name)s::Result Result;
5532 Result* result_dst = GetSharedMemoryAs<Result*>(
5533 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
5535 return error::kOutOfBounds;
5538 file.Write(code
% {'func_name': func
.name
})
5539 func
.WriteHandlerValidation(file)
5540 file.Write(" *result_dst = %s(%s);\n" %
5541 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5542 file.Write(" return error::kNoError;\n")
5546 def WriteGLES2Implementation(self
, func
, file):
5547 """Overrriden from TypeHandler."""
5548 impl_func
= func
.GetInfo('impl_func')
5549 if impl_func
== None or impl_func
== True:
5550 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
5551 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5552 (func
.return_type
, func
.original_name
,
5553 func
.MakeTypedOriginalArgString("")))
5554 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5555 self
.WriteTraceEvent(func
, file)
5556 func
.WriteDestinationInitalizationValidation(file)
5557 self
.WriteClientGLCallLog(func
, file)
5558 file.Write(" typedef cmds::%s::Result Result;\n" % func
.name
)
5559 file.Write(" Result* result = GetResultAs<Result*>();\n")
5560 file.Write(" if (!result) {\n")
5561 file.Write(" return %s;\n" % error_value
)
5563 file.Write(" *result = 0;\n")
5564 arg_string
= func
.MakeOriginalArgString("")
5566 if len(arg_string
) > 0:
5569 " helper_->%s(%s%sGetResultShmId(), GetResultShmOffset());\n" %
5570 (func
.name
, arg_string
, comma
))
5571 file.Write(" WaitForCmd();\n")
5572 file.Write(" %s result_value = *result;\n" % func
.return_type
)
5573 file.Write(' GPU_CLIENT_LOG("returned " << result_value);\n')
5574 file.Write(" CheckGLError();\n")
5575 file.Write(" return result_value;\n")
5579 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5580 """Overrriden from TypeHandler."""
5581 client_test
= func
.GetInfo('client_test')
5582 if client_test
== None or client_test
== True:
5584 TEST_F(GLES2ImplementationTest, %(name)s) {
5589 typedef cmds::%(name)s::Result Result;
5591 ExpectedMemoryInfo result1 =
5592 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
5593 expected.cmd.Init(1, result1.id, result1.offset);
5595 EXPECT_CALL(*command_buffer(), OnFlush())
5596 .WillOnce(SetMemory(result1.ptr, uint32(1)))
5597 .RetiresOnSaturation();
5599 GLboolean result = gl_->%(name)s(1);
5600 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5601 EXPECT_TRUE(result);
5609 class STRnHandler(TypeHandler
):
5610 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
5611 GetTranslatedShaderSourceANGLE."""
5614 TypeHandler
.__init
__(self
)
5616 def InitFunction(self
, func
):
5617 """Overrriden from TypeHandler."""
5618 # remove all but the first cmd args.
5619 cmd_args
= func
.GetCmdArgs()
5621 func
.AddCmdArg(cmd_args
[0])
5622 # add on a bucket id.
5623 func
.AddCmdArg(Argument('bucket_id', 'uint32'))
5625 def WriteGLES2Implementation(self
, func
, file):
5626 """Overrriden from TypeHandler."""
5627 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
5628 GPU_CLIENT_SINGLE_THREAD_CHECK();
5630 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
5631 << "] gl%(func_name)s" << "("
5634 << static_cast<void*>(%(arg2)s) << ", "
5635 << static_cast<void*>(%(arg3)s) << ")");
5636 helper_->SetBucketSize(kResultBucketId, 0);
5637 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
5639 GLsizei max_size = 0;
5640 if (GetBucketAsString(kResultBucketId, &str)) {
5643 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
5644 memcpy(%(dest_name)s, str.c_str(), max_size);
5645 %(dest_name)s[max_size] = '\\0';
5646 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
5649 if (%(length_name)s != NULL) {
5650 *%(length_name)s = max_size;
5655 args
= func
.GetOriginalArgs()
5657 'return_type': func
.return_type
,
5658 'func_name': func
.original_name
,
5659 'args': func
.MakeTypedOriginalArgString(""),
5660 'id_name': args
[0].name
,
5661 'bufsize_name': args
[1].name
,
5662 'length_name': args
[2].name
,
5663 'dest_name': args
[3].name
,
5664 'arg0': args
[0].name
,
5665 'arg1': args
[1].name
,
5666 'arg2': args
[2].name
,
5667 'arg3': args
[3].name
,
5669 file.Write(code_1
% str_args
)
5670 func
.WriteDestinationInitalizationValidation(file)
5671 file.Write(code_2
% str_args
)
5673 def WriteServiceUnitTest(self
, func
, file):
5674 """Overrriden from TypeHandler."""
5676 TEST_F(%(test_name)s, %(name)sValidArgs) {
5677 const char* kInfo = "hello";
5678 const uint32 kBucketId = 123;
5679 SpecializedSetup<cmds::%(name)s, 0>(true);
5681 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5682 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
5683 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
5686 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5687 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
5688 ASSERT_TRUE(bucket != NULL);
5689 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
5690 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
5692 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5695 args
= func
.GetOriginalArgs()
5696 id_name
= args
[0].GetValidGLArg(func
, 0, 0)
5697 get_len_func
= func
.GetInfo('get_len_func')
5698 get_len_enum
= func
.GetInfo('get_len_enum')
5701 'get_len_func': get_len_func
,
5702 'get_len_enum': get_len_enum
,
5703 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
5704 args
[0].GetValidGLArg(func
, 0, 0),
5705 'args': '%s, kBucketId' % args
[0].GetValidArg(func
, 0, 0),
5706 'expect_len_code': '',
5708 if get_len_func
and get_len_func
[0:2] == 'gl':
5709 sub
['expect_len_code'] = (
5710 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
5711 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
5712 get_len_func
[2:], id_name
, get_len_enum
)
5713 self
.WriteValidUnitTest(func
, file, valid_test
, sub
)
5716 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
5717 const uint32 kBucketId = 123;
5718 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
5721 cmd.Init(kInvalidClientId, kBucketId);
5722 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5723 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5726 self
.WriteValidUnitTest(func
, file, invalid_test
)
5728 def WriteServiceImplementation(self
, func
, file):
5729 """Overrriden from TypeHandler."""
5733 class FunctionInfo(object):
5734 """Holds info about a function."""
5736 def __init__(self
, info
, type_handler
):
5738 setattr(self
, key
, info
[key
])
5739 self
.type_handler
= type_handler
5740 if not 'type' in info
:
5744 class Argument(object):
5745 """A class that represents a function argument."""
5750 'GLintptr': 'int32',
5752 'GLsizeiptr': 'int32',
5754 'GLclampf': 'float',
5756 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
5758 def __init__(self
, name
, type):
5760 self
.optional
= type.endswith("Optional*")
5762 type = type[:-9] + "*"
5765 if type in self
.cmd_type_map_
:
5766 self
.cmd_type
= self
.cmd_type_map_
[type]
5768 self
.cmd_type
= 'uint32'
5770 def IsPointer(self
):
5771 """Returns true if argument is a pointer."""
5774 def AddCmdArgs(self
, args
):
5775 """Adds command arguments for this argument to the given list."""
5776 return args
.append(self
)
5778 def AddInitArgs(self
, args
):
5779 """Adds init arguments for this argument to the given list."""
5780 return args
.append(self
)
5782 def GetValidArg(self
, func
, offset
, index
):
5783 """Gets a valid value for this argument."""
5784 valid_arg
= func
.GetValidArg(offset
)
5785 if valid_arg
!= None:
5787 return str(offset
+ 1)
5789 def GetValidClientSideArg(self
, func
, offset
, index
):
5790 """Gets a valid value for this argument."""
5791 return str(offset
+ 1)
5793 def GetValidClientSideCmdArg(self
, func
, offset
, index
):
5794 """Gets a valid value for this argument."""
5795 return str(offset
+ 1)
5797 def GetValidGLArg(self
, func
, offset
, index
):
5798 """Gets a valid GL value for this argument."""
5799 valid_arg
= func
.GetValidArg(offset
)
5800 if valid_arg
!= None:
5802 return str(offset
+ 1)
5804 def GetNumInvalidValues(self
, func
):
5805 """returns the number of invalid values to be tested."""
5808 def GetInvalidArg(self
, offset
, index
):
5809 """returns an invalid value and expected parse result by index."""
5810 return ("---ERROR0---", "---ERROR2---", None)
5812 def GetLogArg(self
):
5813 """Get argument appropriate for LOG macro."""
5814 if self
.type == 'GLboolean':
5815 return 'GLES2Util::GetStringBool(%s)' % self
.name
5816 if self
.type == 'GLenum':
5817 return 'GLES2Util::GetStringEnum(%s)' % self
.name
5820 def WriteGetCode(self
, file):
5821 """Writes the code to get an argument from a command structure."""
5822 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
5823 (self
.type, self
.name
, self
.type, self
.name
))
5825 def WriteValidationCode(self
, file, func
):
5826 """Writes the validation code for an argument."""
5829 def WriteClientSideValidationCode(self
, file, func
):
5830 """Writes the validation code for an argument."""
5833 def WriteDestinationInitalizationValidation(self
, file, func
):
5834 """Writes the client side destintion initialization validation."""
5837 def WriteDestinationInitalizationValidatationIfNeeded(self
, file, func
):
5838 """Writes the client side destintion initialization validation if needed."""
5839 parts
= self
.type.split(" ")
5842 if parts
[0] in self
.need_validation_
:
5844 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
5845 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
5848 def WriteGetAddress(self
, file):
5849 """Writes the code to get the address this argument refers to."""
5852 def GetImmediateVersion(self
):
5853 """Gets the immediate version of this argument."""
5856 def GetBucketVersion(self
):
5857 """Gets the bucket version of this argument."""
5861 class BoolArgument(Argument
):
5862 """class for GLboolean"""
5864 def __init__(self
, name
, type):
5865 Argument
.__init
__(self
, name
, 'GLboolean')
5867 def GetValidArg(self
, func
, offset
, index
):
5868 """Gets a valid value for this argument."""
5871 def GetValidClientSideArg(self
, func
, offset
, index
):
5872 """Gets a valid value for this argument."""
5875 def GetValidClientSideCmdArg(self
, func
, offset
, index
):
5876 """Gets a valid value for this argument."""
5879 def GetValidGLArg(self
, func
, offset
, index
):
5880 """Gets a valid GL value for this argument."""
5884 class UniformLocationArgument(Argument
):
5885 """class for uniform locations."""
5887 def __init__(self
, name
):
5888 Argument
.__init
__(self
, name
, "GLint")
5890 def WriteGetCode(self
, file):
5891 """Writes the code to get an argument from a command structure."""
5892 code
= """ %s %s = static_cast<%s>(c.%s);
5894 file.Write(code
% (self
.type, self
.name
, self
.type, self
.name
))
5896 def GetValidArg(self
, func
, offset
, index
):
5897 """Gets a valid value for this argument."""
5898 return "%d" % (offset
+ 1)
5901 class DataSizeArgument(Argument
):
5902 """class for data_size which Bucket commands do not need."""
5904 def __init__(self
, name
):
5905 Argument
.__init
__(self
, name
, "uint32")
5907 def GetBucketVersion(self
):
5911 class SizeArgument(Argument
):
5912 """class for GLsizei and GLsizeiptr."""
5914 def __init__(self
, name
, type):
5915 Argument
.__init
__(self
, name
, type)
5917 def GetNumInvalidValues(self
, func
):
5918 """overridden from Argument."""
5919 if func
.is_immediate
:
5923 def GetInvalidArg(self
, offset
, index
):
5924 """overridden from Argument."""
5925 return ("-1", "kNoError", "GL_INVALID_VALUE")
5927 def WriteValidationCode(self
, file, func
):
5928 """overridden from Argument."""
5929 file.Write(" if (%s < 0) {\n" % self
.name
)
5931 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5932 (func
.original_name
, self
.name
))
5933 file.Write(" return error::kNoError;\n")
5936 def WriteClientSideValidationCode(self
, file, func
):
5937 """overridden from Argument."""
5938 file.Write(" if (%s < 0) {\n" % self
.name
)
5940 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5941 (func
.original_name
, self
.name
))
5942 file.Write(" return;\n")
5946 class SizeNotNegativeArgument(SizeArgument
):
5947 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
5949 def __init__(self
, name
, type, gl_type
):
5950 SizeArgument
.__init
__(self
, name
, gl_type
)
5952 def GetInvalidArg(self
, offset
, index
):
5953 """overridden from SizeArgument."""
5954 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
5956 def WriteValidationCode(self
, file, func
):
5957 """overridden from SizeArgument."""
5961 class EnumBaseArgument(Argument
):
5962 """Base class for EnumArgument, IntArgument and ValidatedBoolArgument"""
5964 def __init__(self
, name
, gl_type
, type, gl_error
):
5965 Argument
.__init
__(self
, name
, gl_type
)
5967 self
.local_type
= type
5968 self
.gl_error
= gl_error
5969 name
= type[len(gl_type
):]
5970 self
.type_name
= name
5971 self
.enum_info
= _ENUM_LISTS
[name
]
5973 def WriteValidationCode(self
, file, func
):
5974 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
5975 (ToUnderscore(self
.type_name
), self
.name
))
5976 if self
.gl_error
== "GL_INVALID_ENUM":
5978 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
5979 (func
.original_name
, self
.name
, self
.name
))
5982 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
5983 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
5984 file.Write(" return error::kNoError;\n")
5987 def GetValidArg(self
, func
, offset
, index
):
5988 valid_arg
= func
.GetValidArg(offset
)
5989 if valid_arg
!= None:
5991 if 'valid' in self
.enum_info
:
5992 valid
= self
.enum_info
['valid']
5993 num_valid
= len(valid
)
5994 if index
>= num_valid
:
5995 index
= num_valid
- 1
5997 return str(offset
+ 1)
5999 def GetValidClientSideArg(self
, func
, offset
, index
):
6000 """Gets a valid value for this argument."""
6001 return self
.GetValidArg(func
, offset
, index
)
6003 def GetValidClientSideCmdArg(self
, func
, offset
, index
):
6004 """Gets a valid value for this argument."""
6005 return self
.GetValidArg(func
, offset
, index
)
6007 def GetValidGLArg(self
, func
, offset
, index
):
6008 """Gets a valid value for this argument."""
6009 return self
.GetValidArg(func
, offset
, index
)
6011 def GetNumInvalidValues(self
, func
):
6012 """returns the number of invalid values to be tested."""
6013 if 'invalid' in self
.enum_info
:
6014 invalid
= self
.enum_info
['invalid']
6018 def GetInvalidArg(self
, offset
, index
):
6019 """returns an invalid value by index."""
6020 if 'invalid' in self
.enum_info
:
6021 invalid
= self
.enum_info
['invalid']
6022 num_invalid
= len(invalid
)
6023 if index
>= num_invalid
:
6024 index
= num_invalid
- 1
6025 return (invalid
[index
], "kNoError", self
.gl_error
)
6026 return ("---ERROR1---", "kNoError", self
.gl_error
)
6029 class EnumArgument(EnumBaseArgument
):
6030 """A class that represents a GLenum argument"""
6032 def __init__(self
, name
, type):
6033 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
6035 def GetLogArg(self
):
6036 """Overridden from Argument."""
6037 return ("GLES2Util::GetString%s(%s)" %
6038 (self
.type_name
, self
.name
))
6041 class IntArgument(EnumBaseArgument
):
6042 """A class for a GLint argument that can only except specific values.
6044 For example glTexImage2D takes a GLint for its internalformat
6045 argument instead of a GLenum.
6048 def __init__(self
, name
, type):
6049 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
6052 class ValidatedBoolArgument(EnumBaseArgument
):
6053 """A class for a GLboolean argument that can only except specific values.
6055 For example glUniformMatrix takes a GLboolean for it's transpose but it
6059 def __init__(self
, name
, type):
6060 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
6062 def GetLogArg(self
):
6063 """Overridden from Argument."""
6064 return 'GLES2Util::GetStringBool(%s)' % self
.name
6067 class ImmediatePointerArgument(Argument
):
6068 """A class that represents an immediate argument to a function.
6070 An immediate argument is one where the data follows the command.
6073 def __init__(self
, name
, type):
6074 Argument
.__init
__(self
, name
, type)
6076 def AddCmdArgs(self
, args
):
6077 """Overridden from Argument."""
6080 def WriteGetCode(self
, file):
6081 """Overridden from Argument."""
6083 " %s %s = GetImmediateDataAs<%s>(\n" %
6084 (self
.type, self
.name
, self
.type))
6085 file.Write(" c, data_size, immediate_data_size);\n")
6087 def WriteValidationCode(self
, file, func
):
6088 """Overridden from Argument."""
6089 file.Write(" if (%s == NULL) {\n" % self
.name
)
6090 file.Write(" return error::kOutOfBounds;\n")
6093 def GetImmediateVersion(self
):
6094 """Overridden from Argument."""
6097 def WriteDestinationInitalizationValidation(self
, file, func
):
6098 """Overridden from Argument."""
6099 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6101 def GetLogArg(self
):
6102 """Overridden from Argument."""
6103 return "static_cast<const void*>(%s)" % self
.name
6106 class BucketPointerArgument(Argument
):
6107 """A class that represents an bucket argument to a function."""
6109 def __init__(self
, name
, type):
6110 Argument
.__init
__(self
, name
, type)
6112 def AddCmdArgs(self
, args
):
6113 """Overridden from Argument."""
6116 def WriteGetCode(self
, file):
6117 """Overridden from Argument."""
6119 " %s %s = bucket->GetData(0, data_size);\n" %
6120 (self
.type, self
.name
))
6122 def WriteValidationCode(self
, file, func
):
6123 """Overridden from Argument."""
6126 def GetImmediateVersion(self
):
6127 """Overridden from Argument."""
6130 def WriteDestinationInitalizationValidation(self
, file, func
):
6131 """Overridden from Argument."""
6132 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6134 def GetLogArg(self
):
6135 """Overridden from Argument."""
6136 return "static_cast<const void*>(%s)" % self
.name
6139 class PointerArgument(Argument
):
6140 """A class that represents a pointer argument to a function."""
6142 def __init__(self
, name
, type):
6143 Argument
.__init
__(self
, name
, type)
6145 def IsPointer(self
):
6146 """Returns true if argument is a pointer."""
6149 def GetValidArg(self
, func
, offset
, index
):
6150 """Overridden from Argument."""
6151 return "shared_memory_id_, shared_memory_offset_"
6153 def GetValidGLArg(self
, func
, offset
, index
):
6154 """Overridden from Argument."""
6155 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
6157 def GetNumInvalidValues(self
, func
):
6158 """Overridden from Argument."""
6161 def GetInvalidArg(self
, offset
, index
):
6162 """Overridden from Argument."""
6164 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
6166 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
6167 "kOutOfBounds", None)
6169 def GetLogArg(self
):
6170 """Overridden from Argument."""
6171 return "static_cast<const void*>(%s)" % self
.name
6173 def AddCmdArgs(self
, args
):
6174 """Overridden from Argument."""
6175 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32'))
6176 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32'))
6178 def WriteGetCode(self
, file):
6179 """Overridden from Argument."""
6181 " %s %s = GetSharedMemoryAs<%s>(\n" %
6182 (self
.type, self
.name
, self
.type))
6184 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
6185 (self
.name
, self
.name
))
6187 def WriteGetAddress(self
, file):
6188 """Overridden from Argument."""
6190 " %s %s = GetSharedMemoryAs<%s>(\n" %
6191 (self
.type, self
.name
, self
.type))
6193 " %s_shm_id, %s_shm_offset, %s_size);\n" %
6194 (self
.name
, self
.name
, self
.name
))
6196 def WriteValidationCode(self
, file, func
):
6197 """Overridden from Argument."""
6198 file.Write(" if (%s == NULL) {\n" % self
.name
)
6199 file.Write(" return error::kOutOfBounds;\n")
6202 def GetImmediateVersion(self
):
6203 """Overridden from Argument."""
6204 return ImmediatePointerArgument(self
.name
, self
.type)
6206 def GetBucketVersion(self
):
6207 """Overridden from Argument."""
6208 if self
.type == "const char*":
6209 return InputStringBucketArgument(self
.name
, self
.type)
6210 return BucketPointerArgument(self
.name
, self
.type)
6212 def WriteDestinationInitalizationValidation(self
, file, func
):
6213 """Overridden from Argument."""
6214 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6217 class InputStringBucketArgument(Argument
):
6218 """An string input argument where the string is passed in a bucket."""
6220 def __init__(self
, name
, type):
6221 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32")
6223 def WriteGetCode(self
, file):
6224 """Overridden from Argument."""
6226 Bucket* %(name)s_bucket = GetBucket(c.%(name)s);
6227 if (!%(name)s_bucket) {
6228 return error::kInvalidArguments;
6230 std::string %(name)s_str;
6231 if (!%(name)s_bucket->GetAsString(&%(name)s_str)) {
6232 return error::kInvalidArguments;
6234 const char* %(name)s = %(name)s_str.c_str();
6240 def GetValidArg(self
, func
, offset
, index
):
6241 return "kNameBucketId"
6243 def GetValidGLArg(self
, func
, offset
, index
):
6247 class NonImmediatePointerArgument(PointerArgument
):
6248 """A pointer argument that stays a pointer even in an immediate cmd."""
6250 def __init__(self
, name
, type):
6251 PointerArgument
.__init
__(self
, name
, type)
6253 def IsPointer(self
):
6254 """Returns true if argument is a pointer."""
6257 def GetImmediateVersion(self
):
6258 """Overridden from Argument."""
6262 class ResourceIdArgument(Argument
):
6263 """A class that represents a resource id argument to a function."""
6265 def __init__(self
, name
, type):
6266 match
= re
.match("(GLid\w+)", type)
6267 self
.resource_type
= match
.group(1)[4:]
6268 type = type.replace(match
.group(1), "GLuint")
6269 Argument
.__init
__(self
, name
, type)
6271 def WriteGetCode(self
, file):
6272 """Overridden from Argument."""
6273 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
6275 def GetValidArg(self
, func
, offset
, index
):
6276 return "client_%s_id_" % self
.resource_type
.lower()
6278 def GetValidGLArg(self
, func
, offset
, index
):
6279 return "kService%sId" % self
.resource_type
6282 class ResourceIdBindArgument(Argument
):
6283 """Represents a resource id argument to a bind function."""
6285 def __init__(self
, name
, type):
6286 match
= re
.match("(GLidBind\w+)", type)
6287 self
.resource_type
= match
.group(1)[8:]
6288 type = type.replace(match
.group(1), "GLuint")
6289 Argument
.__init
__(self
, name
, type)
6291 def WriteGetCode(self
, file):
6292 """Overridden from Argument."""
6293 code
= """ %(type)s %(name)s = c.%(name)s;
6295 file.Write(code
% {'type': self
.type, 'name': self
.name
})
6297 def GetValidArg(self
, func
, offset
, index
):
6298 return "client_%s_id_" % self
.resource_type
.lower()
6300 def GetValidGLArg(self
, func
, offset
, index
):
6301 return "kService%sId" % self
.resource_type
6304 class ResourceIdZeroArgument(Argument
):
6305 """Represents a resource id argument to a function that can be zero."""
6307 def __init__(self
, name
, type):
6308 match
= re
.match("(GLidZero\w+)", type)
6309 self
.resource_type
= match
.group(1)[8:]
6310 type = type.replace(match
.group(1), "GLuint")
6311 Argument
.__init
__(self
, name
, type)
6313 def WriteGetCode(self
, file):
6314 """Overridden from Argument."""
6315 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
6317 def GetValidArg(self
, func
, offset
, index
):
6318 return "client_%s_id_" % self
.resource_type
.lower()
6320 def GetValidGLArg(self
, func
, offset
, index
):
6321 return "kService%sId" % self
.resource_type
6323 def GetNumInvalidValues(self
, func
):
6324 """returns the number of invalid values to be tested."""
6327 def GetInvalidArg(self
, offset
, index
):
6328 """returns an invalid value by index."""
6329 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
6332 class Function(object):
6333 """A class that represents a function."""
6335 def __init__(self
, original_name
, name
, info
, return_type
, original_args
,
6336 args_for_cmds
, cmd_args
, init_args
, num_pointer_args
):
6338 self
.original_name
= original_name
6340 self
.type_handler
= info
.type_handler
6341 self
.return_type
= return_type
6342 self
.original_args
= original_args
6343 self
.num_pointer_args
= num_pointer_args
6344 self
.can_auto_generate
= num_pointer_args
== 0 and return_type
== "void"
6345 self
.cmd_args
= cmd_args
6346 self
.init_args
= init_args
6348 self
.args_for_cmds
= args_for_cmds
6349 self
.is_immediate
= False
6351 def IsType(self
, type_name
):
6352 """Returns true if function is a certain type."""
6353 return self
.info
.type == type_name
6355 def InitFunction(self
):
6356 """Calls the init function for the type handler."""
6357 self
.type_handler
.InitFunction(self
)
6359 def GetInfo(self
, name
):
6360 """Returns a value from the function info for this function."""
6361 if hasattr(self
.info
, name
):
6362 return getattr(self
.info
, name
)
6365 def GetValidArg(self
, index
):
6366 """Gets a valid arg from the function info if one exists."""
6367 valid_args
= self
.GetInfo('valid_args')
6368 if valid_args
and str(index
) in valid_args
:
6369 return valid_args
[str(index
)]
6372 def AddInfo(self
, name
, value
):
6374 setattr(self
.info
, name
, value
)
6376 def IsCoreGLFunction(self
):
6377 return (not self
.GetInfo('extension') and
6378 not self
.GetInfo('pepper_interface'))
6380 def InPepperInterface(self
, interface
):
6381 ext
= self
.GetInfo('pepper_interface')
6382 if not interface
.GetName():
6383 return self
.IsCoreGLFunction()
6384 return ext
== interface
.GetName()
6386 def InAnyPepperExtension(self
):
6387 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
6389 def GetGLFunctionName(self
):
6390 """Gets the function to call to execute GL for this command."""
6391 if self
.GetInfo('decoder_func'):
6392 return self
.GetInfo('decoder_func')
6393 return "gl%s" % self
.original_name
6395 def GetGLTestFunctionName(self
):
6396 gl_func_name
= self
.GetInfo('gl_test_func')
6397 if gl_func_name
== None:
6398 gl_func_name
= self
.GetGLFunctionName()
6399 if gl_func_name
.startswith("gl"):
6400 gl_func_name
= gl_func_name
[2:]
6402 gl_func_name
= self
.original_name
6405 def AddCmdArg(self
, arg
):
6406 """Adds a cmd argument to this function."""
6407 self
.cmd_args
.append(arg
)
6409 def GetCmdArgs(self
):
6410 """Gets the command args for this function."""
6411 return self
.cmd_args
6413 def ClearCmdArgs(self
):
6414 """Clears the command args for this function."""
6417 def GetInitArgs(self
):
6418 """Gets the init args for this function."""
6419 return self
.init_args
6421 def GetOriginalArgs(self
):
6422 """Gets the original arguments to this function."""
6423 return self
.original_args
6425 def GetLastOriginalArg(self
):
6426 """Gets the last original argument to this function."""
6427 return self
.original_args
[len(self
.original_args
) - 1]
6429 def __MaybePrependComma(self
, arg_string
, add_comma
):
6430 """Adds a comma if arg_string is not empty and add_comma is true."""
6432 if add_comma
and len(arg_string
):
6434 return "%s%s" % (comma
, arg_string
)
6436 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
6437 """Gets a list of arguments as they are in GL."""
6438 args
= self
.GetOriginalArgs()
6439 arg_string
= ", ".join(
6440 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6441 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6443 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
6444 """Gets the list of arguments as they are in GL."""
6445 args
= self
.GetOriginalArgs()
6446 arg_string
= separator
.join(
6447 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6448 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6450 def MakeTypedPepperArgString(self
, prefix
):
6451 """Gets a list of arguments as they need to be for Pepper."""
6452 if self
.GetInfo("pepper_args"):
6453 return self
.GetInfo("pepper_args")
6455 return self
.MakeTypedOriginalArgString(prefix
, False)
6457 def GetPepperName(self
):
6458 if self
.GetInfo("pepper_name"):
6459 return self
.GetInfo("pepper_name")
6462 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
6463 """Gets a typed list of arguments as they need to be for command buffers."""
6464 args
= self
.GetCmdArgs()
6465 arg_string
= ", ".join(
6466 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6467 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6469 def MakeCmdArgString(self
, prefix
, add_comma
= False):
6470 """Gets the list of arguments as they need to be for command buffers."""
6471 args
= self
.GetCmdArgs()
6472 arg_string
= ", ".join(
6473 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6474 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6476 def MakeTypedInitString(self
, prefix
, add_comma
= False):
6477 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
6478 args
= self
.GetInitArgs()
6479 arg_string
= ", ".join(
6480 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6481 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6483 def MakeInitString(self
, prefix
, add_comma
= False):
6484 """Gets the list of arguments as they need to be for cmd Init/Set."""
6485 args
= self
.GetInitArgs()
6486 arg_string
= ", ".join(
6487 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6488 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6490 def MakeLogArgString(self
):
6491 """Makes a string of the arguments for the LOG macros"""
6492 args
= self
.GetOriginalArgs()
6493 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
6495 def WriteCommandDescription(self
, file):
6496 """Writes a description of the command."""
6497 file.Write("//! Command that corresponds to gl%s.\n" % self
.original_name
)
6499 def WriteHandlerValidation(self
, file):
6500 """Writes validation code for the function."""
6501 for arg
in self
.GetOriginalArgs():
6502 arg
.WriteValidationCode(file, self
)
6503 self
.WriteValidationCode(file)
6505 def WriteHandlerImplementation(self
, file):
6506 """Writes the handler implementation for this command."""
6507 self
.type_handler
.WriteHandlerImplementation(self
, file)
6509 def WriteValidationCode(self
, file):
6510 """Writes the validation code for a command."""
6513 def WriteCmdFlag(self
, file):
6514 """Writes the cmd cmd_flags constant."""
6516 trace_level
= 3 # By default trace only at the highest level
6517 if hasattr(self
.info
, 'trace_level'):
6518 if (self
.info
.trace_level
< 0) or (self
.info
.trace_level
> 3):
6519 raise KeyError("Unhandled trace_level: %d" % self
.info
.trace_level
)
6520 trace_level
= self
.info
.trace_level
6522 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
6525 cmd_flags
= ' | '.join(flags
)
6529 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
6532 def WriteCmdArgFlag(self
, file):
6533 """Writes the cmd kArgFlags constant."""
6534 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
6536 def WriteCmdComputeSize(self
, file):
6537 """Writes the ComputeSize function for the command."""
6538 file.Write(" static uint32 ComputeSize() {\n")
6540 " return static_cast<uint32>(sizeof(ValueType)); // NOLINT\n")
6544 def WriteCmdSetHeader(self
, file):
6545 """Writes the cmd's SetHeader function."""
6546 file.Write(" void SetHeader() {\n")
6547 file.Write(" header.SetCmd<ValueType>();\n")
6551 def WriteCmdInit(self
, file):
6552 """Writes the cmd's Init function."""
6553 file.Write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
6554 file.Write(" SetHeader();\n")
6555 args
= self
.GetCmdArgs()
6557 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6561 def WriteCmdSet(self
, file):
6562 """Writes the cmd's Set function."""
6563 copy_args
= self
.MakeCmdArgString("_", False)
6564 file.Write(" void* Set(void* cmd%s) {\n" %
6565 self
.MakeTypedCmdArgString("_", True))
6566 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
6567 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
6571 def WriteStruct(self
, file):
6572 self
.type_handler
.WriteStruct(self
, file)
6574 def WriteDocs(self
, file):
6575 self
.type_handler
.WriteDocs(self
, file)
6577 def WriteCmdHelper(self
, file):
6578 """Writes the cmd's helper."""
6579 self
.type_handler
.WriteCmdHelper(self
, file)
6581 def WriteServiceImplementation(self
, file):
6582 """Writes the service implementation for a command."""
6583 self
.type_handler
.WriteServiceImplementation(self
, file)
6585 def WriteServiceUnitTest(self
, file):
6586 """Writes the service implementation for a command."""
6587 self
.type_handler
.WriteServiceUnitTest(self
, file)
6589 def WriteGLES2CLibImplementation(self
, file):
6590 """Writes the GLES2 C Lib Implemention."""
6591 self
.type_handler
.WriteGLES2CLibImplementation(self
, file)
6593 def WriteGLES2InterfaceHeader(self
, file):
6594 """Writes the GLES2 Interface declaration."""
6595 self
.type_handler
.WriteGLES2InterfaceHeader(self
, file)
6597 def WriteGLES2InterfaceStub(self
, file):
6598 """Writes the GLES2 Interface Stub declaration."""
6599 self
.type_handler
.WriteGLES2InterfaceStub(self
, file)
6601 def WriteGLES2InterfaceStubImpl(self
, file):
6602 """Writes the GLES2 Interface Stub declaration."""
6603 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, file)
6605 def WriteGLES2ImplementationHeader(self
, file):
6606 """Writes the GLES2 Implemention declaration."""
6607 self
.type_handler
.WriteGLES2ImplementationHeader(self
, file)
6609 def WriteGLES2Implementation(self
, file):
6610 """Writes the GLES2 Implemention definition."""
6611 self
.type_handler
.WriteGLES2Implementation(self
, file)
6613 def WriteGLES2TraceImplementationHeader(self
, file):
6614 """Writes the GLES2 Trace Implemention declaration."""
6615 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, file)
6617 def WriteGLES2TraceImplementation(self
, file):
6618 """Writes the GLES2 Trace Implemention definition."""
6619 self
.type_handler
.WriteGLES2TraceImplementation(self
, file)
6621 def WriteGLES2Header(self
, file):
6622 """Writes the GLES2 Implemention unit test."""
6623 self
.type_handler
.WriteGLES2Header(self
, file)
6625 def WriteGLES2ImplementationUnitTest(self
, file):
6626 """Writes the GLES2 Implemention unit test."""
6627 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, file)
6629 def WriteDestinationInitalizationValidation(self
, file):
6630 """Writes the client side destintion initialization validation."""
6631 self
.type_handler
.WriteDestinationInitalizationValidation(self
, file)
6633 def WriteFormatTest(self
, file):
6634 """Writes the cmd's format test."""
6635 self
.type_handler
.WriteFormatTest(self
, file)
6638 class PepperInterface(object):
6639 """A class that represents a function."""
6641 def __init__(self
, info
):
6642 self
.name
= info
["name"]
6643 self
.dev
= info
["dev"]
6648 def GetInterfaceName(self
):
6652 upperint
= "_" + self
.name
.upper()
6655 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
6657 def GetInterfaceString(self
):
6661 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
6663 def GetStructName(self
):
6667 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
6670 class ImmediateFunction(Function
):
6671 """A class that represnets an immediate function command."""
6673 def __init__(self
, func
):
6675 for arg
in func
.GetOriginalArgs():
6676 new_arg
= arg
.GetImmediateVersion()
6678 new_args
.append(new_arg
)
6681 new_args_for_cmds
= []
6682 for arg
in func
.args_for_cmds
:
6683 new_arg
= arg
.GetImmediateVersion()
6685 new_args_for_cmds
.append(new_arg
)
6686 new_arg
.AddCmdArgs(cmd_args
)
6689 for arg
in new_args_for_cmds
:
6690 arg
.AddInitArgs(new_init_args
)
6695 "%sImmediate" % func
.name
,
6703 self
.is_immediate
= True
6705 def WriteCommandDescription(self
, file):
6706 """Overridden from Function"""
6707 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
6710 def WriteServiceImplementation(self
, file):
6711 """Overridden from Function"""
6712 self
.type_handler
.WriteImmediateServiceImplementation(self
, file)
6714 def WriteHandlerImplementation(self
, file):
6715 """Overridden from Function"""
6716 self
.type_handler
.WriteImmediateHandlerImplementation(self
, file)
6718 def WriteServiceUnitTest(self
, file):
6719 """Writes the service implementation for a command."""
6720 self
.type_handler
.WriteImmediateServiceUnitTest(self
, file)
6722 def WriteValidationCode(self
, file):
6723 """Overridden from Function"""
6724 self
.type_handler
.WriteImmediateValidationCode(self
, file)
6726 def WriteCmdArgFlag(self
, file):
6727 """Overridden from Function"""
6728 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
6730 def WriteCmdComputeSize(self
, file):
6731 """Overridden from Function"""
6732 self
.type_handler
.WriteImmediateCmdComputeSize(self
, file)
6734 def WriteCmdSetHeader(self
, file):
6735 """Overridden from Function"""
6736 self
.type_handler
.WriteImmediateCmdSetHeader(self
, file)
6738 def WriteCmdInit(self
, file):
6739 """Overridden from Function"""
6740 self
.type_handler
.WriteImmediateCmdInit(self
, file)
6742 def WriteCmdSet(self
, file):
6743 """Overridden from Function"""
6744 self
.type_handler
.WriteImmediateCmdSet(self
, file)
6746 def WriteCmdHelper(self
, file):
6747 """Overridden from Function"""
6748 self
.type_handler
.WriteImmediateCmdHelper(self
, file)
6750 def WriteFormatTest(self
, file):
6751 """Overridden from Function"""
6752 self
.type_handler
.WriteImmediateFormatTest(self
, file)
6755 class BucketFunction(Function
):
6756 """A class that represnets a bucket version of a function command."""
6758 def __init__(self
, func
):
6760 for arg
in func
.GetOriginalArgs():
6761 new_arg
= arg
.GetBucketVersion()
6763 new_args
.append(new_arg
)
6766 new_args_for_cmds
= []
6767 for arg
in func
.args_for_cmds
:
6768 new_arg
= arg
.GetBucketVersion()
6770 new_args_for_cmds
.append(new_arg
)
6771 new_arg
.AddCmdArgs(cmd_args
)
6774 for arg
in new_args_for_cmds
:
6775 arg
.AddInitArgs(new_init_args
)
6780 "%sBucket" % func
.name
,
6789 # def InitFunction(self):
6790 # """Overridden from Function"""
6793 def WriteCommandDescription(self
, file):
6794 """Overridden from Function"""
6795 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
6798 def WriteServiceImplementation(self
, file):
6799 """Overridden from Function"""
6800 self
.type_handler
.WriteBucketServiceImplementation(self
, file)
6802 def WriteHandlerImplementation(self
, file):
6803 """Overridden from Function"""
6804 self
.type_handler
.WriteBucketHandlerImplementation(self
, file)
6806 def WriteServiceUnitTest(self
, file):
6807 """Writes the service implementation for a command."""
6808 self
.type_handler
.WriteBucketServiceUnitTest(self
, file)
6811 def CreateArg(arg_string
):
6812 """Creates an Argument."""
6813 arg_parts
= arg_string
.split()
6814 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
6816 # Is this a pointer argument?
6817 elif arg_string
.find('*') >= 0:
6818 if arg_parts
[0] == 'NonImmediate':
6819 return NonImmediatePointerArgument(
6821 " ".join(arg_parts
[1:-1]))
6823 return PointerArgument(
6825 " ".join(arg_parts
[0:-1]))
6826 # Is this a resource argument? Must come after pointer check.
6827 elif arg_parts
[0].startswith('GLidBind'):
6828 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6829 elif arg_parts
[0].startswith('GLidZero'):
6830 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6831 elif arg_parts
[0].startswith('GLid'):
6832 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6833 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
6834 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6835 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
6836 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6837 elif arg_parts
[0].startswith('GLboolean'):
6838 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6839 elif arg_parts
[0].startswith('GLintUniformLocation'):
6840 return UniformLocationArgument(arg_parts
[-1])
6841 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
6842 not arg_parts
[0].startswith('GLintptr')):
6843 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6844 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
6845 arg_parts
[0].startswith('GLintptrNotNegative')):
6846 return SizeNotNegativeArgument(arg_parts
[-1],
6847 " ".join(arg_parts
[0:-1]),
6848 arg_parts
[0][0:-11])
6849 elif arg_parts
[0].startswith('GLsize'):
6850 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6852 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6855 class GLGenerator(object):
6856 """A class to generate GL command buffers."""
6858 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
6860 def __init__(self
, verbose
):
6861 self
.original_functions
= []
6863 self
.verbose
= verbose
6865 self
._function
_info
= {}
6866 self
._empty
_type
_handler
= TypeHandler()
6867 self
._empty
_function
_info
= FunctionInfo({}, self
._empty
_type
_handler
)
6868 self
.pepper_interfaces
= []
6869 self
.interface_info
= {}
6871 self
._type
_handlers
= {
6872 'Bind': BindHandler(),
6873 'Create': CreateHandler(),
6874 'Custom': CustomHandler(),
6875 'Data': DataHandler(),
6876 'Delete': DeleteHandler(),
6877 'DELn': DELnHandler(),
6878 'GENn': GENnHandler(),
6879 'GETn': GETnHandler(),
6880 'GLchar': GLcharHandler(),
6881 'GLcharN': GLcharNHandler(),
6882 'HandWritten': HandWrittenHandler(),
6884 'Manual': ManualHandler(),
6885 'PUT': PUTHandler(),
6886 'PUTn': PUTnHandler(),
6887 'PUTXn': PUTXnHandler(),
6888 'StateSet': StateSetHandler(),
6889 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
6890 'StateSetFrontBack': StateSetFrontBackHandler(),
6891 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
6892 'StateSetNamedParameter': StateSetNamedParameter(),
6893 'STRn': STRnHandler(),
6894 'Todo': TodoHandler(),
6897 for func_name
in _FUNCTION_INFO
:
6898 info
= _FUNCTION_INFO
[func_name
]
6902 self
._function
_info
[func_name
] = FunctionInfo(info
,
6903 self
.GetTypeHandler(type))
6904 for interface
in _PEPPER_INTERFACES
:
6905 interface
= PepperInterface(interface
)
6906 self
.pepper_interfaces
.append(interface
)
6907 self
.interface_info
[interface
.GetName()] = interface
6909 def AddFunction(self
, func
):
6910 """Adds a function."""
6911 self
.functions
.append(func
)
6913 def GetTypeHandler(self
, name
):
6914 """Gets a type info for the given type."""
6916 if name
in self
._type
_handlers
:
6917 return self
._type
_handlers
[name
]
6919 raise KeyError("no such type handler: %s" % name
)
6920 return self
._empty
_type
_handler
6922 def GetFunctionInfo(self
, name
):
6923 """Gets a type info for the given function name."""
6924 if name
in self
._function
_info
:
6925 return self
._function
_info
[name
]
6926 return self
._empty
_function
_info
6929 """Prints something if verbose is true."""
6933 def Error(self
, msg
):
6934 """Prints an error."""
6935 print "Error: %s" % msg
6938 def WriteLicense(self
, file):
6939 """Writes the license."""
6940 file.Write(_LICENSE
)
6942 def WriteNamespaceOpen(self
, file):
6943 """Writes the code for the namespace."""
6944 file.Write("namespace gpu {\n")
6945 file.Write("namespace gles2 {\n")
6948 def WriteNamespaceClose(self
, file):
6949 """Writes the code to close the namespace."""
6950 file.Write("} // namespace gles2\n")
6951 file.Write("} // namespace gpu\n")
6954 def ParseArgs(self
, arg_string
):
6955 """Parses a function arg string."""
6957 num_pointer_args
= 0
6958 parts
= arg_string
.split(',')
6960 for arg_string
in parts
:
6961 if arg_string
.startswith('GLenum '):
6963 arg
= CreateArg(arg_string
)
6967 num_pointer_args
+= 1
6968 return (args
, num_pointer_args
, is_gl_enum
)
6970 def ParseGLH(self
, filename
):
6971 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
6972 f
= open("gpu/command_buffer/cmd_buffer_functions.txt", "r")
6973 functions
= f
.read()
6975 for line
in functions
.splitlines():
6976 match
= self
._function
_re
.match(line
)
6978 func_name
= match
.group(2)[2:]
6979 func_info
= self
.GetFunctionInfo(func_name
)
6980 if func_info
.type != 'Noop':
6981 return_type
= match
.group(1).strip()
6982 arg_string
= match
.group(3)
6983 (args
, num_pointer_args
, is_gl_enum
) = self
.ParseArgs(arg_string
)
6984 # comment in to find out which functions use bare enums.
6986 # self.Log("%s uses bare GLenum" % func_name)
6987 args_for_cmds
= args
6988 if hasattr(func_info
, 'cmd_args'):
6989 (args_for_cmds
, num_pointer_args
, is_gl_enum
) = (
6990 self
.ParseArgs(getattr(func_info
, 'cmd_args')))
6992 for arg
in args_for_cmds
:
6993 arg
.AddCmdArgs(cmd_args
)
6995 for arg
in args_for_cmds
:
6996 arg
.AddInitArgs(init_args
)
6997 return_arg
= CreateArg(return_type
+ " result")
6999 init_args
.append(return_arg
)
7000 f
= Function(func_name
, func_name
, func_info
, return_type
, args
,
7001 args_for_cmds
, cmd_args
, init_args
, num_pointer_args
)
7002 self
.original_functions
.append(f
)
7003 gen_cmd
= f
.GetInfo('gen_cmd')
7004 if gen_cmd
== True or gen_cmd
== None:
7006 f
.type_handler
.AddImmediateFunction(self
, f
)
7007 f
.type_handler
.AddBucketFunction(self
, f
)
7009 self
.Log("Auto Generated Functions : %d" %
7010 len([f
for f
in self
.functions
if f
.can_auto_generate
or
7011 (not f
.IsType('') and not f
.IsType('Custom') and
7012 not f
.IsType('Todo'))]))
7014 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
7015 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
7016 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
7019 self
.Log(" %-10s %-20s gl%s" % (f
.info
.type, f
.return_type
, f
.name
))
7021 def WriteCommandIds(self
, filename
):
7022 """Writes the command buffer format"""
7023 file = CHeaderWriter(filename
)
7024 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
7026 for func
in self
.functions
:
7027 file.Write(" %-60s /* %d */ \\\n" %
7028 ("OP(%s)" % func
.name
, id))
7032 file.Write("enum CommandId {\n")
7033 file.Write(" kStartPoint = cmd::kLastCommonId, "
7034 "// All GLES2 commands start after this.\n")
7035 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
7036 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
7037 file.Write("#undef GLES2_CMD_OP\n")
7038 file.Write(" kNumCommands\n")
7043 def WriteFormat(self
, filename
):
7044 """Writes the command buffer format"""
7045 file = CHeaderWriter(filename
)
7046 for func
in self
.functions
:
7048 #gen_cmd = func.GetInfo('gen_cmd')
7049 #if gen_cmd == True or gen_cmd == None:
7050 func
.WriteStruct(file)
7054 def WriteDocs(self
, filename
):
7055 """Writes the command buffer doc version of the commands"""
7056 file = CWriter(filename
)
7057 for func
in self
.functions
:
7059 #gen_cmd = func.GetInfo('gen_cmd')
7060 #if gen_cmd == True or gen_cmd == None:
7061 func
.WriteDocs(file)
7065 def WriteFormatTest(self
, filename
):
7066 """Writes the command buffer format test."""
7067 file = CHeaderWriter(
7069 "// This file contains unit tests for gles2 commmands\n"
7070 "// It is included by gles2_cmd_format_test.cc\n"
7073 for func
in self
.functions
:
7075 #gen_cmd = func.GetInfo('gen_cmd')
7076 #if gen_cmd == True or gen_cmd == None:
7077 func
.WriteFormatTest(file)
7081 def WriteCmdHelperHeader(self
, filename
):
7082 """Writes the gles2 command helper."""
7083 file = CHeaderWriter(filename
)
7085 for func
in self
.functions
:
7087 #gen_cmd = func.GetInfo('gen_cmd')
7088 #if gen_cmd == True or gen_cmd == None:
7089 func
.WriteCmdHelper(file)
7093 def WriteServiceContextStateHeader(self
, filename
):
7094 """Writes the service context state header."""
7095 file = CHeaderWriter(
7097 "// It is included by context_state.h\n")
7098 file.Write("struct EnableFlags {\n")
7099 file.Write(" EnableFlags();\n")
7100 for capability
in _CAPABILITY_FLAGS
:
7101 file.Write(" bool %s;\n" % capability
['name'])
7102 file.Write("};\n\n")
7104 for state_name
in sorted(_STATES
.keys()):
7105 state
= _STATES
[state_name
]
7106 for item
in state
['states']:
7107 file.Write("%s %s;\n" % (item
['type'], item
['name']))
7112 def WriteClientContextStateHeader(self
, filename
):
7113 """Writes the client context state header."""
7114 file = CHeaderWriter(
7116 "// It is included by client_context_state.h\n")
7117 file.Write("struct EnableFlags {\n")
7118 file.Write(" EnableFlags();\n")
7119 for capability
in _CAPABILITY_FLAGS
:
7120 file.Write(" bool %s;\n" % capability
['name'])
7121 file.Write("};\n\n")
7125 def WriteContextStateGetters(self
, file, class_name
):
7126 """Writes the state getters."""
7127 for gl_type
in ["GLint", "GLfloat"]:
7129 bool %s::GetStateAs%s(
7130 GLenum pname, %s* params, GLsizei* num_written) const {
7132 """ % (class_name
, gl_type
, gl_type
))
7133 for state_name
in sorted(_STATES
.keys()):
7134 state
= _STATES
[state_name
]
7136 file.Write(" case %s:\n" % state
['enum'])
7137 file.Write(" *num_written = %d;\n" % len(state
['states']))
7138 file.Write(" if (params) {\n")
7139 for ndx
,item
in enumerate(state
['states']):
7140 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
7141 (ndx
, gl_type
, item
['name']))
7143 file.Write(" return true;\n")
7145 for item
in state
['states']:
7146 file.Write(" case %s:\n" % item
['enum'])
7147 file.Write(" *num_written = 1;\n")
7148 file.Write(" if (params) {\n")
7149 file.Write(" params[0] = static_cast<%s>(%s);\n" %
7150 (gl_type
, item
['name']))
7152 file.Write(" return true;\n")
7153 for capability
in _CAPABILITY_FLAGS
:
7154 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7155 file.Write(" *num_written = 1;\n")
7156 file.Write(" if (params) {\n")
7158 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
7159 (gl_type
, capability
['name']))
7161 file.Write(" return true;\n")
7162 file.Write(""" default:
7168 def WriteServiceContextStateImpl(self
, filename
):
7169 """Writes the context state service implementation."""
7170 file = CHeaderWriter(
7172 "// It is included by context_state.cc\n")
7174 for capability
in _CAPABILITY_FLAGS
:
7175 code
.append("%s(%s)" %
7176 (capability
['name'],
7177 ('false', 'true')['default' in capability
]))
7178 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7182 file.Write("void ContextState::Initialize() {\n")
7183 for state_name
in sorted(_STATES
.keys()):
7184 state
= _STATES
[state_name
]
7185 for item
in state
['states']:
7186 file.Write(" %s = %s;\n" % (item
['name'], item
['default']))
7190 void ContextState::InitCapabilities() const {
7192 for capability
in _CAPABILITY_FLAGS
:
7193 file.Write(" EnableDisable(GL_%s, enable_flags.%s);\n" %
7194 (capability
['name'].upper(), capability
['name']))
7197 void ContextState::InitState() const {
7200 # We need to sort the keys so the expectations match
7201 for state_name
in sorted(_STATES
.keys()):
7202 state
= _STATES
[state_name
]
7203 if state
['type'] == 'FrontBack':
7204 num_states
= len(state
['states'])
7205 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
7208 args
.append('%s' % item
['name'])
7210 " gl%s(%s, %s);\n" %
7211 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
7212 elif state
['type'] == 'NamedParameter':
7213 for item
in state
['states']:
7214 if 'extension_flag' in item
:
7215 file.Write(" if (feature_info_->feature_flags().%s)\n " %
7216 item
['extension_flag'])
7217 file.Write(" gl%s(%s, %s);\n" %
7218 (state
['func'], item
['enum'], item
['name']))
7221 for item
in state
['states']:
7222 args
.append('%s' % item
['name'])
7223 file.Write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
7226 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
7229 for capability
in _CAPABILITY_FLAGS
:
7230 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7231 file.Write(" return enable_flags.%s;\n" % capability
['name'])
7232 file.Write(""" default:
7239 self
.WriteContextStateGetters(file, "ContextState")
7242 def WriteClientContextStateImpl(self
, filename
):
7243 """Writes the context state client side implementation."""
7244 file = CHeaderWriter(
7246 "// It is included by client_context_state.cc\n")
7248 for capability
in _CAPABILITY_FLAGS
:
7249 code
.append("%s(%s)" %
7250 (capability
['name'],
7251 ('false', 'true')['default' in capability
]))
7253 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7258 bool ClientContextState::SetCapabilityState(
7259 GLenum cap, bool enabled, bool* changed) {
7263 for capability
in _CAPABILITY_FLAGS
:
7264 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7265 file.Write(""" if (enable_flags.%(name)s != enabled) {
7267 enable_flags.%(name)s = enabled;
7271 file.Write(""" default:
7276 file.Write("""bool ClientContextState::GetEnabled(
7277 GLenum cap, bool* enabled) const {
7280 for capability
in _CAPABILITY_FLAGS
:
7281 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7282 file.Write(" *enabled = enable_flags.%s;\n" % capability
['name'])
7283 file.Write(" return true;\n")
7284 file.Write(""" default:
7291 def WriteServiceImplementation(self
, filename
):
7292 """Writes the service decorder implementation."""
7293 file = CHeaderWriter(
7295 "// It is included by gles2_cmd_decoder.cc\n")
7297 for func
in self
.functions
:
7299 #gen_cmd = func.GetInfo('gen_cmd')
7300 #if gen_cmd == True or gen_cmd == None:
7301 func
.WriteServiceImplementation(file)
7304 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
7307 for capability
in _CAPABILITY_FLAGS
:
7308 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7309 if 'state_flag' in capability
:
7310 file.Write(""" if (state_.enable_flags.%(name)s != enabled) {
7311 state_.enable_flags.%(name)s = enabled;
7312 %(state_flag)s = true;
7317 file.Write(""" state_.enable_flags.%(name)s = enabled;
7320 file.Write(""" default:
7328 def WriteServiceUnitTests(self
, filename
):
7329 """Writes the service decorder unit tests."""
7330 num_tests
= len(self
.functions
)
7331 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
7333 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
7335 name
= filename
% count
7336 file = CHeaderWriter(
7338 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count
)
7339 file.SetFileNum(count
)
7340 end
= test_num
+ FUNCTIONS_PER_FILE
7343 for idx
in range(test_num
, end
):
7344 func
= self
.functions
[idx
]
7346 #gen_cmd = func.GetInfo('gen_cmd')
7347 #if gen_cmd == True or gen_cmd == None:
7348 if func
.GetInfo('unit_test') == False:
7349 file.Write("// TODO(gman): %s\n" % func
.name
)
7351 func
.WriteServiceUnitTest(file)
7354 file = CHeaderWriter(
7356 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
7358 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
7360 for capability
in _CAPABILITY_FLAGS
:
7361 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
7362 (capability
['name'].upper(),
7363 ('false', 'true')['default' in capability
]))
7366 void GLES2DecoderTestBase::SetupInitStateExpectations() {
7369 # We need to sort the keys so the expectations match
7370 for state_name
in sorted(_STATES
.keys()):
7371 state
= _STATES
[state_name
]
7372 if state
['type'] == 'FrontBack':
7373 num_states
= len(state
['states'])
7374 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
7377 if 'expected' in item
:
7378 args
.append(item
['expected'])
7380 args
.append(item
['default'])
7382 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7383 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
7384 file.Write(" .Times(1)\n")
7385 file.Write(" .RetiresOnSaturation();\n")
7386 elif state
['type'] == 'NamedParameter':
7387 for item
in state
['states']:
7388 if 'extension_flag' in item
:
7391 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7392 (state
['func'], item
['enum'], item
['default']))
7393 file.Write(" .Times(1)\n")
7394 file.Write(" .RetiresOnSaturation();\n")
7397 for item
in state
['states']:
7398 if 'expected' in item
:
7399 args
.append(item
['expected'])
7401 args
.append(item
['default'])
7402 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
7403 (state
['func'], ", ".join(args
)))
7404 file.Write(" .Times(1)\n")
7405 file.Write(" .RetiresOnSaturation();\n")
7410 def WriteGLES2Header(self
, filename
):
7411 """Writes the GLES2 header."""
7412 file = CHeaderWriter(
7414 "// This file contains Chromium-specific GLES2 declarations.\n\n")
7416 for func
in self
.original_functions
:
7417 func
.WriteGLES2Header(file)
7422 def WriteGLES2CLibImplementation(self
, filename
):
7423 """Writes the GLES2 c lib implementation."""
7424 file = CHeaderWriter(
7426 "// These functions emulate GLES2 over command buffers.\n")
7428 for func
in self
.original_functions
:
7429 func
.WriteGLES2CLibImplementation(file)
7434 extern const NameToFunc g_gles2_function_table[] = {
7436 for func
in self
.original_functions
:
7438 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
7439 (func
.name
, func
.name
))
7440 file.Write(""" { NULL, NULL, },
7443 } // namespace gles2
7447 def WriteGLES2InterfaceHeader(self
, filename
):
7448 """Writes the GLES2 interface header."""
7449 file = CHeaderWriter(
7451 "// This file is included by gles2_interface.h to declare the\n"
7452 "// GL api functions.\n")
7453 for func
in self
.original_functions
:
7454 func
.WriteGLES2InterfaceHeader(file)
7457 def WriteGLES2InterfaceStub(self
, filename
):
7458 """Writes the GLES2 interface stub header."""
7459 file = CHeaderWriter(
7461 "// This file is included by gles2_interface_stub.h.\n")
7462 for func
in self
.original_functions
:
7463 func
.WriteGLES2InterfaceStub(file)
7466 def WriteGLES2InterfaceStubImpl(self
, filename
):
7467 """Writes the GLES2 interface header."""
7468 file = CHeaderWriter(
7470 "// This file is included by gles2_interface_stub.cc.\n")
7471 for func
in self
.original_functions
:
7472 func
.WriteGLES2InterfaceStubImpl(file)
7475 def WriteGLES2ImplementationHeader(self
, filename
):
7476 """Writes the GLES2 Implementation header."""
7477 file = CHeaderWriter(
7479 "// This file is included by gles2_implementation.h to declare the\n"
7480 "// GL api functions.\n")
7481 for func
in self
.original_functions
:
7482 func
.WriteGLES2ImplementationHeader(file)
7485 def WriteGLES2Implementation(self
, filename
):
7486 """Writes the GLES2 Implementation."""
7487 file = CHeaderWriter(
7489 "// This file is included by gles2_implementation.cc to define the\n"
7490 "// GL api functions.\n")
7491 for func
in self
.original_functions
:
7492 func
.WriteGLES2Implementation(file)
7495 def WriteGLES2TraceImplementationHeader(self
, filename
):
7496 """Writes the GLES2 Trace Implementation header."""
7497 file = CHeaderWriter(
7499 "// This file is included by gles2_trace_implementation.h\n")
7500 for func
in self
.original_functions
:
7501 func
.WriteGLES2TraceImplementationHeader(file)
7504 def WriteGLES2TraceImplementation(self
, filename
):
7505 """Writes the GLES2 Trace Implementation."""
7506 file = CHeaderWriter(
7508 "// This file is included by gles2_trace_implementation.cc\n")
7509 for func
in self
.original_functions
:
7510 func
.WriteGLES2TraceImplementation(file)
7513 def WriteGLES2ImplementationUnitTests(self
, filename
):
7514 """Writes the GLES2 helper header."""
7515 file = CHeaderWriter(
7517 "// This file is included by gles2_implementation.h to declare the\n"
7518 "// GL api functions.\n")
7519 for func
in self
.original_functions
:
7520 func
.WriteGLES2ImplementationUnitTest(file)
7523 def WriteServiceUtilsHeader(self
, filename
):
7524 """Writes the gles2 auto generated utility header."""
7525 file = CHeaderWriter(filename
)
7526 for enum
in sorted(_ENUM_LISTS
.keys()):
7527 file.Write("ValueValidator<%s> %s;\n" %
7528 (_ENUM_LISTS
[enum
]['type'], ToUnderscore(enum
)))
7532 def WriteServiceUtilsImplementation(self
, filename
):
7533 """Writes the gles2 auto generated utility implementation."""
7534 file = CHeaderWriter(filename
)
7535 enums
= sorted(_ENUM_LISTS
.keys())
7537 if len(_ENUM_LISTS
[enum
]['valid']) > 0:
7538 file.Write("static const %s valid_%s_table[] = {\n" %
7539 (_ENUM_LISTS
[enum
]['type'], ToUnderscore(enum
)))
7540 for value
in _ENUM_LISTS
[enum
]['valid']:
7541 file.Write(" %s,\n" % value
)
7544 file.Write("Validators::Validators()\n")
7547 for count
, enum
in enumerate(enums
):
7548 if count
+ 1 == len(enums
):
7550 if len(_ENUM_LISTS
[enum
]['valid']) > 0:
7551 code
= """ %(pre)s%(name)s(
7552 valid_%(name)s_table, arraysize(valid_%(name)s_table))%(post)s
7555 code
= """ %(pre)s%(name)s()%(post)s
7558 'name': ToUnderscore(enum
),
7563 file.Write("}\n\n");
7566 def WriteCommonUtilsHeader(self
, filename
):
7567 """Writes the gles2 common utility header."""
7568 file = CHeaderWriter(filename
)
7569 enums
= sorted(_ENUM_LISTS
.keys())
7571 if _ENUM_LISTS
[enum
]['type'] == 'GLenum':
7572 file.Write("static std::string GetString%s(uint32 value);\n" % enum
)
7576 def WriteCommonUtilsImpl(self
, filename
):
7577 """Writes the gles2 common utility header."""
7578 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
7580 for fname
in ['../../third_party/khronos/GLES2/gl2.h',
7581 '../../third_party/khronos/GLES2/gl2ext.h',
7582 '../../gpu/GLES2/gl2chromium.h',
7583 '../../gpu/GLES2/gl2extchromium.h']:
7584 lines
= open(fname
).readlines()
7586 m
= enum_re
.match(line
)
7590 if len(value
) <= 10 and not value
in dict:
7593 file = CHeaderWriter(filename
)
7594 file.Write("static const GLES2Util::EnumToString "
7595 "enum_to_string_table[] = {\n")
7597 file.Write(' { %s, "%s", },\n' % (value
, dict[value
]))
7600 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
7601 enum_to_string_table;
7602 const size_t GLES2Util::enum_to_string_table_len_ =
7603 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
7607 enums
= sorted(_ENUM_LISTS
.keys())
7609 if _ENUM_LISTS
[enum
]['type'] == 'GLenum':
7610 file.Write("std::string GLES2Util::GetString%s(uint32 value) {\n" %
7612 if len(_ENUM_LISTS
[enum
]['valid']) > 0:
7613 file.Write(" static const EnumToString string_table[] = {\n")
7614 for value
in _ENUM_LISTS
[enum
]['valid']:
7615 file.Write(' { %s, "%s" },\n' % (value
, value
))
7617 return GLES2Util::GetQualifiedEnumString(
7618 string_table, arraysize(string_table), value);
7623 file.Write(""" return GLES2Util::GetQualifiedEnumString(
7630 def WritePepperGLES2Interface(self
, filename
, dev
):
7631 """Writes the Pepper OpenGLES interface definition."""
7632 file = CHeaderWriter(
7634 "// OpenGL ES interface.\n")
7636 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
7638 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
7640 file.Write("\n#ifndef __gl2_h_\n")
7641 for (k
, v
) in _GL_TYPES
.iteritems():
7642 file.Write("typedef %s %s;\n" % (v
, k
))
7643 file.Write("#ifdef _WIN64\n")
7644 for (k
, v
) in _GL_TYPES_64
.iteritems():
7645 file.Write("typedef %s %s;\n" % (v
, k
))
7646 file.Write("#else\n")
7647 for (k
, v
) in _GL_TYPES_32
.iteritems():
7648 file.Write("typedef %s %s;\n" % (v
, k
))
7649 file.Write("#endif // _WIN64\n")
7650 file.Write("#endif // __gl2_h_\n\n")
7652 for interface
in self
.pepper_interfaces
:
7653 if interface
.dev
!= dev
:
7655 file.Write("#define %s_1_0 \"%s;1.0\"\n" %
7656 (interface
.GetInterfaceName(), interface
.GetInterfaceString()))
7657 file.Write("#define %s %s_1_0\n" %
7658 (interface
.GetInterfaceName(), interface
.GetInterfaceName()))
7660 file.Write("\nstruct %s {\n" % interface
.GetStructName())
7661 for func
in self
.original_functions
:
7662 if not func
.InPepperInterface(interface
):
7665 original_arg
= func
.MakeTypedPepperArgString("")
7666 context_arg
= "PP_Resource context"
7667 if len(original_arg
):
7668 arg
= context_arg
+ ", " + original_arg
7671 file.Write(" %s (*%s)(%s);\n" %
7672 (func
.return_type
, func
.GetPepperName(), arg
))
7673 file.Write("};\n\n")
7678 def WritePepperGLES2Implementation(self
, filename
):
7679 """Writes the Pepper OpenGLES interface implementation."""
7681 file = CWriter(filename
)
7682 file.Write(_LICENSE
)
7683 file.Write(_DO_NOT_EDIT_WARNING
)
7685 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
7686 file.Write("#include \"base/logging.h\"\n")
7687 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
7688 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
7689 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
7691 file.Write("namespace ppapi {\n\n")
7692 file.Write("namespace {\n\n")
7694 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
7697 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
7699 file.Write(" DCHECK(enter);\n")
7700 file.Write(" DCHECK(enter->succeeded());\n")
7701 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
7703 file.Write("}\n\n");
7705 for func
in self
.original_functions
:
7706 if not func
.InAnyPepperExtension():
7709 original_arg
= func
.MakeTypedPepperArgString("")
7710 context_arg
= "PP_Resource context_id"
7711 if len(original_arg
):
7712 arg
= context_arg
+ ", " + original_arg
7715 file.Write("%s %s(%s) {\n" %
7716 (func
.return_type
, func
.GetPepperName(), arg
))
7717 file.Write(" Enter3D enter(context_id, true);\n")
7718 file.Write(" if (enter.succeeded()) {\n")
7720 return_str
= "" if func
.return_type
== "void" else "return "
7721 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
7722 (return_str
, func
.original_name
,
7723 func
.MakeOriginalArgString("")))
7725 if func
.return_type
== "void":
7728 file.Write(" else {\n")
7730 if func
.GetInfo("error_return"):
7731 error_return
= func
.GetInfo("error_return")
7732 elif func
.return_type
== "GLboolean":
7733 error_return
= "GL_FALSE"
7734 elif "*" in func
.return_type
:
7735 error_return
= "NULL"
7736 file.Write(" return %s;\n" % error_return
)
7740 file.Write("} // namespace\n")
7742 for interface
in self
.pepper_interfaces
:
7743 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
7744 (interface
.GetStructName(), interface
.GetName()))
7745 file.Write(" static const struct %s "
7746 "ppb_opengles2 = {\n" % interface
.GetStructName())
7748 file.Write(",\n &".join(
7749 f
.GetPepperName() for f
in self
.original_functions
7750 if f
.InPepperInterface(interface
)))
7754 file.Write(" return &ppb_opengles2;\n")
7757 file.Write("} // namespace ppapi\n")
7760 def WriteGLES2ToPPAPIBridge(self
, filename
):
7761 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
7763 file = CWriter(filename
)
7764 file.Write(_LICENSE
)
7765 file.Write(_DO_NOT_EDIT_WARNING
)
7767 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
7768 file.Write("#define GL_GLEXT_PROTOTYPES\n")
7769 file.Write("#endif\n")
7770 file.Write("#include <GLES2/gl2.h>\n")
7771 file.Write("#include <GLES2/gl2ext.h>\n")
7772 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
7774 for func
in self
.original_functions
:
7775 if not func
.InAnyPepperExtension():
7778 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
7780 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
7781 (func
.return_type
, func
.GetPepperName(),
7782 func
.MakeTypedPepperArgString("")))
7783 return_str
= "" if func
.return_type
== "void" else "return "
7784 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
7785 original_arg
= func
.MakeOriginalArgString("")
7786 context_arg
= "glGetCurrentContextPPAPI()"
7787 if len(original_arg
):
7788 arg
= context_arg
+ ", " + original_arg
7791 if interface
.GetName():
7792 file.Write(" const struct %s* ext = %s;\n" %
7793 (interface
.GetStructName(), interface_str
))
7794 file.Write(" if (ext)\n")
7795 file.Write(" %sext->%s(%s);\n" %
7796 (return_str
, func
.GetPepperName(), arg
))
7798 file.Write(" %s0;\n" % return_str
)
7800 file.Write(" %s%s->%s(%s);\n" %
7801 (return_str
, interface_str
, func
.GetPepperName(), arg
))
7805 def WriteMojoGLCallVisitor(self
, filename
):
7806 """Provides the GL implementation for mojo"""
7807 file = CWriter(filename
)
7808 file.Write(_LICENSE
)
7809 file.Write(_DO_NOT_EDIT_WARNING
)
7811 for func
in self
.original_functions
:
7812 if not func
.IsCoreGLFunction():
7814 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
7815 (func
.name
, func
.return_type
,
7816 func
.MakeTypedOriginalArgString(""),
7817 func
.MakeOriginalArgString("")))
7822 """This is the main function."""
7823 parser
= OptionParser()
7825 "-g", "--generate-implementation-templates", action
="store_true",
7826 help="generates files that are generally hand edited..")
7829 help="base directory for resulting files, under chrome/src. default is "
7830 "empty. Use this if you want the result stored under gen.")
7832 "-v", "--verbose", action
="store_true",
7833 help="prints more output.")
7835 (options
, args
) = parser
.parse_args(args
=argv
)
7837 # Add in states and capabilites to GLState
7838 for state_name
in sorted(_STATES
.keys()):
7839 state
= _STATES
[state_name
]
7841 _ENUM_LISTS
['GLState']['valid'].append(state
['enum'])
7843 for item
in state
['states']:
7844 if 'extension_flag' in item
:
7846 _ENUM_LISTS
['GLState']['valid'].append(item
['enum'])
7847 for capability
in _CAPABILITY_FLAGS
:
7848 _ENUM_LISTS
['GLState']['valid'].append("GL_%s" % capability
['name'].upper())
7850 # This script lives under gpu/command_buffer, cd to base directory.
7851 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
7853 gen
= GLGenerator(options
.verbose
)
7854 gen
.ParseGLH("common/GLES2/gl2.h")
7856 # Support generating files under gen/
7857 if options
.output_dir
!= None:
7858 os
.chdir(options
.output_dir
)
7860 gen
.WritePepperGLES2Interface("ppapi/c/ppb_opengles2.h", False)
7861 gen
.WritePepperGLES2Interface("ppapi/c/dev/ppb_opengles2ext_dev.h", True)
7862 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
7863 gen
.WritePepperGLES2Implementation(
7864 "ppapi/shared_impl/ppb_opengles2_shared.cc")
7865 os
.chdir("gpu/command_buffer")
7866 gen
.WriteCommandIds("common/gles2_cmd_ids_autogen.h")
7867 gen
.WriteFormat("common/gles2_cmd_format_autogen.h")
7868 gen
.WriteFormatTest("common/gles2_cmd_format_test_autogen.h")
7869 gen
.WriteGLES2InterfaceHeader("client/gles2_interface_autogen.h")
7870 gen
.WriteGLES2InterfaceStub("client/gles2_interface_stub_autogen.h")
7871 gen
.WriteGLES2InterfaceStubImpl(
7872 "client/gles2_interface_stub_impl_autogen.h")
7873 gen
.WriteGLES2ImplementationHeader("client/gles2_implementation_autogen.h")
7874 gen
.WriteGLES2Implementation("client/gles2_implementation_impl_autogen.h")
7875 gen
.WriteGLES2ImplementationUnitTests(
7876 "client/gles2_implementation_unittest_autogen.h")
7877 gen
.WriteGLES2TraceImplementationHeader(
7878 "client/gles2_trace_implementation_autogen.h")
7879 gen
.WriteGLES2TraceImplementation(
7880 "client/gles2_trace_implementation_impl_autogen.h")
7881 gen
.WriteGLES2CLibImplementation("client/gles2_c_lib_autogen.h")
7882 gen
.WriteCmdHelperHeader("client/gles2_cmd_helper_autogen.h")
7883 gen
.WriteServiceImplementation("service/gles2_cmd_decoder_autogen.h")
7884 gen
.WriteServiceContextStateHeader("service/context_state_autogen.h")
7885 gen
.WriteServiceContextStateImpl("service/context_state_impl_autogen.h")
7886 gen
.WriteClientContextStateHeader("client/client_context_state_autogen.h")
7887 gen
.WriteClientContextStateImpl(
7888 "client/client_context_state_impl_autogen.h")
7889 gen
.WriteServiceUnitTests("service/gles2_cmd_decoder_unittest_%d_autogen.h")
7890 gen
.WriteServiceUtilsHeader("service/gles2_cmd_validation_autogen.h")
7891 gen
.WriteServiceUtilsImplementation(
7892 "service/gles2_cmd_validation_implementation_autogen.h")
7893 gen
.WriteCommonUtilsHeader("common/gles2_cmd_utils_autogen.h")
7894 gen
.WriteCommonUtilsImpl("common/gles2_cmd_utils_implementation_autogen.h")
7895 gen
.WriteGLES2Header("../GLES2/gl2chromium_autogen.h")
7896 gen
.WriteMojoGLCallVisitor(
7897 "../../mojo/public/gles2/gles2_call_visitor_autogen.h")
7900 print "%d errors" % gen
.errors
7905 if __name__
== '__main__':
7906 sys
.exit(main(sys
.argv
[1:]))