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
14 from subprocess
import call
17 _SIZE_OF_COMMAND_HEADER
= 4
18 _FIRST_SPECIFIC_COMMAND_ID
= 256
20 _LICENSE
= """// Copyright 2014 The Chromium Authors. All rights reserved.
21 // Use of this source code is governed by a BSD-style license that can be
22 // found in the LICENSE file.
26 _DO_NOT_EDIT_WARNING
= """// This file is auto-generated from
27 // gpu/command_buffer/build_gles2_cmd_buffer.py
28 // It's formatted by clang-format using chromium coding style:
29 // clang-format -i -style=chromium filename
34 # This string is copied directly out of the gl2.h file from GLES2.0
38 # *) Any argument that is a resourceID has been changed to GLid<Type>.
39 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
40 # If it's allowed to not exist it's GLidBind<Type>
42 # *) All GLenums have been changed to GLenumTypeOfEnum
45 'GLenum': 'unsigned int',
46 'GLboolean': 'unsigned char',
47 'GLbitfield': 'unsigned int',
48 'GLbyte': 'signed char',
52 'GLubyte': 'unsigned char',
53 'GLushort': 'unsigned short',
54 'GLuint': 'unsigned int',
63 'GLintptr': 'long int',
64 'GLsizeiptr': 'long int'
68 'GLintptr': 'long long int',
69 'GLsizeiptr': 'long long int'
72 # Capabilites selected with glEnable
75 {'name': 'cull_face'},
76 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
77 {'name': 'dither', 'default': True},
78 {'name': 'polygon_offset_fill'},
79 {'name': 'sample_alpha_to_coverage'},
80 {'name': 'sample_coverage'},
81 {'name': 'scissor_test',
82 'state_flag': 'framebuffer_state_.clear_state_dirty'},
83 {'name': 'stencil_test',
84 'state_flag': 'framebuffer_state_.clear_state_dirty'},
91 'enum': 'GL_COLOR_CLEAR_VALUE',
93 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
94 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
95 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
101 'func': 'ClearDepth',
102 'enum': 'GL_DEPTH_CLEAR_VALUE',
104 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
110 'enum': 'GL_COLOR_WRITEMASK',
112 {'name': 'color_mask_red', 'type': 'GLboolean', 'default': 'true'},
113 {'name': 'color_mask_green', 'type': 'GLboolean', 'default': 'true'},
114 {'name': 'color_mask_blue', 'type': 'GLboolean', 'default': 'true'},
115 {'name': 'color_mask_alpha', 'type': 'GLboolean', 'default': 'true'},
117 'state_flag': 'framebuffer_state_.clear_state_dirty',
121 'func': 'ClearStencil',
122 'enum': 'GL_STENCIL_CLEAR_VALUE',
124 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
129 'func': 'BlendColor',
130 'enum': 'GL_BLEND_COLOR',
132 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
133 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
134 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
135 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
140 'func': 'BlendEquationSeparate',
143 'name': 'blend_equation_rgb',
145 'enum': 'GL_BLEND_EQUATION_RGB',
146 'default': 'GL_FUNC_ADD',
149 'name': 'blend_equation_alpha',
151 'enum': 'GL_BLEND_EQUATION_ALPHA',
152 'default': 'GL_FUNC_ADD',
158 'func': 'BlendFuncSeparate',
161 'name': 'blend_source_rgb',
163 'enum': 'GL_BLEND_SRC_RGB',
167 'name': 'blend_dest_rgb',
169 'enum': 'GL_BLEND_DST_RGB',
170 'default': 'GL_ZERO',
173 'name': 'blend_source_alpha',
175 'enum': 'GL_BLEND_SRC_ALPHA',
179 'name': 'blend_dest_alpha',
181 'enum': 'GL_BLEND_DST_ALPHA',
182 'default': 'GL_ZERO',
188 'func': 'PolygonOffset',
191 'name': 'polygon_offset_factor',
193 'enum': 'GL_POLYGON_OFFSET_FACTOR',
197 'name': 'polygon_offset_units',
199 'enum': 'GL_POLYGON_OFFSET_UNITS',
207 'enum': 'GL_CULL_FACE_MODE',
212 'default': 'GL_BACK',
219 'enum': 'GL_FRONT_FACE',
220 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
225 'enum': 'GL_DEPTH_FUNC',
226 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
230 'func': 'DepthRange',
231 'enum': 'GL_DEPTH_RANGE',
233 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
234 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
239 'func': 'SampleCoverage',
242 'name': 'sample_coverage_value',
244 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
248 'name': 'sample_coverage_invert',
250 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
257 'func': 'StencilMaskSeparate',
258 'state_flag': 'framebuffer_state_.clear_state_dirty',
261 'name': 'stencil_front_writemask',
263 'enum': 'GL_STENCIL_WRITEMASK',
264 'default': '0xFFFFFFFFU',
267 'name': 'stencil_back_writemask',
269 'enum': 'GL_STENCIL_BACK_WRITEMASK',
270 'default': '0xFFFFFFFFU',
276 'func': 'StencilOpSeparate',
279 'name': 'stencil_front_fail_op',
281 'enum': 'GL_STENCIL_FAIL',
282 'default': 'GL_KEEP',
285 'name': 'stencil_front_z_fail_op',
287 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
288 'default': 'GL_KEEP',
291 'name': 'stencil_front_z_pass_op',
293 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
294 'default': 'GL_KEEP',
297 'name': 'stencil_back_fail_op',
299 'enum': 'GL_STENCIL_BACK_FAIL',
300 'default': 'GL_KEEP',
303 'name': 'stencil_back_z_fail_op',
305 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
306 'default': 'GL_KEEP',
309 'name': 'stencil_back_z_pass_op',
311 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
312 'default': 'GL_KEEP',
318 'func': 'StencilFuncSeparate',
321 'name': 'stencil_front_func',
323 'enum': 'GL_STENCIL_FUNC',
324 'default': 'GL_ALWAYS',
327 'name': 'stencil_front_ref',
329 'enum': 'GL_STENCIL_REF',
333 'name': 'stencil_front_mask',
335 'enum': 'GL_STENCIL_VALUE_MASK',
336 'default': '0xFFFFFFFFU',
339 'name': 'stencil_back_func',
341 'enum': 'GL_STENCIL_BACK_FUNC',
342 'default': 'GL_ALWAYS',
345 'name': 'stencil_back_ref',
347 'enum': 'GL_STENCIL_BACK_REF',
351 'name': 'stencil_back_mask',
353 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
354 'default': '0xFFFFFFFFU',
359 'type': 'NamedParameter',
363 'name': 'hint_generate_mipmap',
365 'enum': 'GL_GENERATE_MIPMAP_HINT',
366 'default': 'GL_DONT_CARE'
369 'name': 'hint_fragment_shader_derivative',
371 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
372 'default': 'GL_DONT_CARE',
373 'extension_flag': 'oes_standard_derivatives'
378 'type': 'NamedParameter',
379 'func': 'PixelStorei',
382 'name': 'pack_alignment',
384 'enum': 'GL_PACK_ALIGNMENT',
388 'name': 'unpack_alignment',
390 'enum': 'GL_UNPACK_ALIGNMENT',
395 # TODO: Consider implemenenting these states
400 'enum': 'GL_LINE_WIDTH',
403 'name': 'line_width',
406 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
412 'enum': 'GL_DEPTH_WRITEMASK',
414 {'name': 'depth_mask', 'type': 'GLboolean', 'default': 'true'},
416 'state_flag': 'framebuffer_state_.clear_state_dirty',
421 'enum': 'GL_SCISSOR_BOX',
423 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
428 'expected': 'kViewportX',
434 'expected': 'kViewportY',
437 'name': 'scissor_width',
440 'expected': 'kViewportWidth',
443 'name': 'scissor_height',
446 'expected': 'kViewportHeight',
453 'enum': 'GL_VIEWPORT',
455 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
457 'name': 'viewport_x',
460 'expected': 'kViewportX',
463 'name': 'viewport_y',
466 'expected': 'kViewportY',
469 'name': 'viewport_width',
472 'expected': 'kViewportWidth',
475 'name': 'viewport_height',
478 'expected': 'kViewportHeight',
484 # This is a list of enum names and their valid values. It is used to map
485 # GLenum arguments to a specific set of valid values.
494 'GL_LINEAR_MIPMAP_LINEAR',
497 'FrameBufferTarget': {
503 'GL_DRAW_FRAMEBUFFER' ,
504 'GL_READ_FRAMEBUFFER' ,
507 'RenderBufferTarget': {
520 'GL_ELEMENT_ARRAY_BUFFER',
537 'CompressedTextureFormat': {
545 # NOTE: State an Capability entries added later.
547 'GL_ALIASED_LINE_WIDTH_RANGE',
548 'GL_ALIASED_POINT_SIZE_RANGE',
550 'GL_ARRAY_BUFFER_BINDING',
552 'GL_COMPRESSED_TEXTURE_FORMATS',
553 'GL_CURRENT_PROGRAM',
556 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
557 'GL_FRAMEBUFFER_BINDING',
558 'GL_GENERATE_MIPMAP_HINT',
560 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
561 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
562 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
563 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
564 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
565 'GL_MAX_RENDERBUFFER_SIZE',
566 'GL_MAX_TEXTURE_IMAGE_UNITS',
567 'GL_MAX_TEXTURE_SIZE',
568 'GL_MAX_VARYING_VECTORS',
569 'GL_MAX_VERTEX_ATTRIBS',
570 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
571 'GL_MAX_VERTEX_UNIFORM_VECTORS',
572 'GL_MAX_VIEWPORT_DIMS',
573 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
574 'GL_NUM_SHADER_BINARY_FORMATS',
577 'GL_RENDERBUFFER_BINDING',
579 'GL_SAMPLE_COVERAGE_INVERT',
580 'GL_SAMPLE_COVERAGE_VALUE',
583 'GL_SHADER_BINARY_FORMATS',
584 'GL_SHADER_COMPILER',
587 'GL_TEXTURE_BINDING_2D',
588 'GL_TEXTURE_BINDING_CUBE_MAP',
589 'GL_UNPACK_ALIGNMENT',
590 'GL_UNPACK_FLIP_Y_CHROMIUM',
591 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
592 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
593 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
594 # we can add this because we emulate it if the driver does not support it.
595 'GL_VERTEX_ARRAY_BINDING_OES',
602 'GetTexParamTarget': {
606 'GL_TEXTURE_CUBE_MAP',
609 'GL_PROXY_TEXTURE_CUBE_MAP',
616 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
617 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
618 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
619 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
620 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
621 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
624 'GL_PROXY_TEXTURE_CUBE_MAP',
627 'TextureBindTarget': {
631 'GL_TEXTURE_CUBE_MAP',
642 'GL_FRAGMENT_SHADER',
645 'GL_GEOMETRY_SHADER',
681 'GL_FUNC_REVERSE_SUBTRACT',
694 'GL_ONE_MINUS_SRC_COLOR',
696 'GL_ONE_MINUS_DST_COLOR',
698 'GL_ONE_MINUS_SRC_ALPHA',
700 'GL_ONE_MINUS_DST_ALPHA',
702 'GL_ONE_MINUS_CONSTANT_COLOR',
704 'GL_ONE_MINUS_CONSTANT_ALPHA',
705 'GL_SRC_ALPHA_SATURATE',
714 'GL_ONE_MINUS_SRC_COLOR',
716 'GL_ONE_MINUS_DST_COLOR',
718 'GL_ONE_MINUS_SRC_ALPHA',
720 'GL_ONE_MINUS_DST_ALPHA',
722 'GL_ONE_MINUS_CONSTANT_COLOR',
724 'GL_ONE_MINUS_CONSTANT_ALPHA',
729 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
],
776 'GL_COLOR_ATTACHMENT0',
777 'GL_DEPTH_ATTACHMENT',
778 'GL_STENCIL_ATTACHMENT',
781 'BackbufferAttachment': {
796 'GL_PIXEL_PACK_BUFFER',
799 'FrameBufferParameter': {
802 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
803 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
804 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
805 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
808 'ProgramParameter': {
813 'GL_VALIDATE_STATUS',
814 'GL_INFO_LOG_LENGTH',
815 'GL_ATTACHED_SHADERS',
816 'GL_ACTIVE_ATTRIBUTES',
817 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
818 'GL_ACTIVE_UNIFORMS',
819 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
822 'QueryObjectParameter': {
825 'GL_QUERY_RESULT_EXT',
826 'GL_QUERY_RESULT_AVAILABLE_EXT',
832 'GL_CURRENT_QUERY_EXT',
838 'GL_ANY_SAMPLES_PASSED_EXT',
839 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
840 'GL_COMMANDS_ISSUED_CHROMIUM',
841 'GL_LATENCY_QUERY_CHROMIUM',
842 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
843 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
844 'GL_COMMANDS_COMPLETED_CHROMIUM',
847 'RenderBufferParameter': {
850 'GL_RENDERBUFFER_RED_SIZE',
851 'GL_RENDERBUFFER_GREEN_SIZE',
852 'GL_RENDERBUFFER_BLUE_SIZE',
853 'GL_RENDERBUFFER_ALPHA_SIZE',
854 'GL_RENDERBUFFER_DEPTH_SIZE',
855 'GL_RENDERBUFFER_STENCIL_SIZE',
856 'GL_RENDERBUFFER_WIDTH',
857 'GL_RENDERBUFFER_HEIGHT',
858 'GL_RENDERBUFFER_INTERNAL_FORMAT',
867 'GL_INFO_LOG_LENGTH',
868 'GL_SHADER_SOURCE_LENGTH',
869 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
889 'GL_SHADING_LANGUAGE_VERSION',
893 'TextureParameter': {
896 'GL_TEXTURE_MAG_FILTER',
897 'GL_TEXTURE_MIN_FILTER',
898 'GL_TEXTURE_POOL_CHROMIUM',
903 'GL_GENERATE_MIPMAP',
909 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
910 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
917 'GL_MIRRORED_REPEAT',
921 'TextureMinFilterMode': {
926 'GL_NEAREST_MIPMAP_NEAREST',
927 'GL_LINEAR_MIPMAP_NEAREST',
928 'GL_NEAREST_MIPMAP_LINEAR',
929 'GL_LINEAR_MIPMAP_LINEAR',
932 'TextureMagFilterMode': {
943 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
949 # some enum that the decoder actually passes through to GL needs
950 # to be the first listed here since it's used in unit tests.
951 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
952 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
953 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
954 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
955 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
956 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
957 'GL_CURRENT_VERTEX_ATTRIB',
963 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
969 'GL_GENERATE_MIPMAP_HINT',
972 'GL_PERSPECTIVE_CORRECTION_HINT',
987 'GL_UNPACK_ALIGNMENT',
988 'GL_UNPACK_FLIP_Y_CHROMIUM',
989 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
990 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
993 'GL_PACK_SWAP_BYTES',
994 'GL_UNPACK_SWAP_BYTES',
997 'PixelStoreAlignment': {
1010 'ReadPixelFormat': {
1022 'GL_UNSIGNED_SHORT_5_6_5',
1023 'GL_UNSIGNED_SHORT_4_4_4_4',
1024 'GL_UNSIGNED_SHORT_5_5_5_1',
1035 'GL_UNSIGNED_SHORT_5_6_5',
1036 'GL_UNSIGNED_SHORT_4_4_4_4',
1037 'GL_UNSIGNED_SHORT_5_5_5_1',
1044 'RenderBufferFormat': {
1050 'GL_DEPTH_COMPONENT16',
1051 'GL_STENCIL_INDEX8',
1054 'ShaderBinaryFormat': {
1077 'GL_LUMINANCE_ALPHA',
1086 'TextureInternalFormat': {
1091 'GL_LUMINANCE_ALPHA',
1100 'TextureInternalFormatStorage': {
1107 'GL_LUMINANCE8_EXT',
1108 'GL_LUMINANCE8_ALPHA8_EXT',
1113 'VertexAttribType': {
1119 'GL_UNSIGNED_SHORT',
1120 # 'GL_FIXED', // This is not available on Desktop GL.
1136 'VertexAttribSize': {
1159 'type': 'GLboolean',
1170 'GL_GUILTY_CONTEXT_RESET_ARB',
1171 'GL_INNOCENT_CONTEXT_RESET_ARB',
1172 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1177 # This table specifies the different pepper interfaces that are supported for
1178 # GL commands. 'dev' is true if it's a dev interface.
1179 _PEPPER_INTERFACES
= [
1180 {'name': '', 'dev': False},
1181 {'name': 'InstancedArrays', 'dev': False},
1182 {'name': 'FramebufferBlit', 'dev': False},
1183 {'name': 'FramebufferMultisample', 'dev': False},
1184 {'name': 'ChromiumEnableFeature', 'dev': False},
1185 {'name': 'ChromiumMapSub', 'dev': False},
1186 {'name': 'Query', 'dev': False},
1187 {'name': 'DrawBuffers', 'dev': True},
1190 # This table specifies types and other special data for the commands that
1191 # will be generated.
1193 # Must match function names specified in "cmd_buffer_functions.txt".
1195 # cmd_comment: A comment added to the cmd format.
1196 # type: defines which handler will be used to generate code.
1197 # decoder_func: defines which function to call in the decoder to execute the
1198 # corresponding GL command. If not specified the GL command will
1199 # be called directly.
1200 # gl_test_func: GL function that is expected to be called when testing.
1201 # cmd_args: The arguments to use for the command. This overrides generating
1202 # them based on the GL function arguments.
1203 # a NonImmediate type is a type that stays a pointer even in
1204 # and immediate version of acommand.
1205 # gen_cmd: Whether or not this function geneates a command. Default = True.
1206 # immediate: Whether or not to generate an immediate command for the GL
1207 # function. The default is if there is exactly 1 pointer argument
1208 # in the GL function an immediate command is generated.
1209 # bucket: True to generate a bucket version of the command.
1210 # impl_func: Whether or not to generate the GLES2Implementation part of this
1212 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1214 # needs_size: If true a data_size field is added to the command.
1215 # data_type: The type of data the command uses. For PUTn or PUT types.
1216 # count: The number of units per element. For PUTn or PUT types.
1217 # unit_test: If False no service side unit test will be generated.
1218 # client_test: If False no client side unit test will be generated.
1219 # expectation: If False the unit test will have no expected calls.
1220 # gen_func: Name of function that generates GL resource for corresponding
1222 # states: array of states that get set by this function corresponding to
1223 # the given arguments
1224 # state_flag: name of flag that is set to true when function is called.
1225 # no_gl: no GL function is called.
1226 # valid_args: A dictionary of argument indices to args to use in unit tests
1227 # when they can not be automatically determined.
1228 # pepper_interface: The pepper interface that is used for this extension
1229 # pepper_name: The name of the function as exposed to pepper.
1230 # pepper_args: A string representing the argument list (what would appear in
1231 # C/C++ between the parentheses for the function declaration)
1232 # that the Pepper API expects for this function. Use this only if
1233 # the stable Pepper API differs from the GLES2 argument list.
1234 # invalid_test: False if no invalid test needed.
1235 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1236 # first_element_only: For PUT types, True if only the first element of an
1237 # array is used and we end up calling the single value
1238 # corresponding function. eg. TexParameteriv -> TexParameteri
1242 'decoder_func': 'DoActiveTexture',
1245 'client_test': False,
1247 'AttachShader': {'decoder_func': 'DoAttachShader'},
1248 'BindAttribLocation': {
1256 'decoder_func': 'DoBindBuffer',
1257 'gen_func': 'GenBuffersARB',
1259 'BindFramebuffer': {
1261 'decoder_func': 'DoBindFramebuffer',
1262 'gl_test_func': 'glBindFramebufferEXT',
1263 'gen_func': 'GenFramebuffersEXT',
1266 'BindRenderbuffer': {
1268 'decoder_func': 'DoBindRenderbuffer',
1269 'gl_test_func': 'glBindRenderbufferEXT',
1270 'gen_func': 'GenRenderbuffersEXT',
1274 'decoder_func': 'DoBindTexture',
1275 'gen_func': 'GenTextures',
1276 # TODO(gman): remove this once client side caching works.
1277 'client_test': False,
1280 'BlitFramebufferCHROMIUM': {
1281 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1284 'pepper_interface': 'FramebufferBlit',
1285 'pepper_name': 'BlitFramebufferEXT',
1286 'defer_reads': True,
1287 'defer_draws': True,
1293 'client_test': False,
1297 'client_test': False,
1298 'decoder_func': 'DoBufferSubData',
1301 'CheckFramebufferStatus': {
1303 'decoder_func': 'DoCheckFramebufferStatus',
1304 'gl_test_func': 'glCheckFramebufferStatusEXT',
1305 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1306 'result': ['GLenum'],
1309 'decoder_func': 'DoClear',
1310 'defer_draws': True,
1315 'state': 'ClearColor',
1319 'state': 'ClearDepthf',
1320 'decoder_func': 'glClearDepth',
1321 'gl_test_func': 'glClearDepth',
1328 'state': 'ColorMask',
1330 'expectation': False,
1332 'ConsumeTextureCHROMIUM': {
1333 'decoder_func': 'DoConsumeTextureCHROMIUM',
1336 'data_type': 'GLbyte',
1337 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1339 'client_test': False,
1346 'state': 'ClearStencil',
1348 'EnableFeatureCHROMIUM': {
1351 'decoder_func': 'DoEnableFeatureCHROMIUM',
1352 'expectation': False,
1353 'cmd_args': 'GLuint bucket_id, GLint* result',
1354 'result': ['GLint'],
1357 'pepper_interface': 'ChromiumEnableFeature',
1359 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1360 'CompressedTexImage2D': {
1365 'CompressedTexSubImage2D': {
1368 'decoder_func': 'DoCompressedTexSubImage2D',
1372 'decoder_func': 'DoCopyTexImage2D',
1374 'defer_reads': True,
1376 'CopyTexSubImage2D': {
1377 'decoder_func': 'DoCopyTexSubImage2D',
1378 'defer_reads': True,
1380 'CreateImageCHROMIUM': {
1382 'cmd_args': 'GLsizei width, GLsizei height, GLenum internalformat',
1383 'result': ['GLuint'],
1384 'client_test': False,
1386 'expectation': False,
1390 'DestroyImageCHROMIUM': {
1393 'client_test': False,
1398 'GetImageParameterivCHROMIUM': {
1400 'client_test': False,
1402 'expectation': False,
1408 'client_test': False,
1412 'client_test': False,
1416 'state': 'BlendColor',
1419 'type': 'StateSetRGBAlpha',
1420 'state': 'BlendEquation',
1422 '0': 'GL_FUNC_SUBTRACT'
1425 'BlendEquationSeparate': {
1427 'state': 'BlendEquation',
1429 '0': 'GL_FUNC_SUBTRACT'
1433 'type': 'StateSetRGBAlpha',
1434 'state': 'BlendFunc',
1436 'BlendFuncSeparate': {
1438 'state': 'BlendFunc',
1440 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1442 'type': 'StateSetFrontBack',
1443 'state': 'StencilFunc',
1445 'StencilFuncSeparate': {
1446 'type': 'StateSetFrontBackSeparate',
1447 'state': 'StencilFunc',
1450 'type': 'StateSetFrontBack',
1451 'state': 'StencilOp',
1456 'StencilOpSeparate': {
1457 'type': 'StateSetFrontBackSeparate',
1458 'state': 'StencilOp',
1464 'type': 'StateSetNamedParameter',
1467 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1468 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1469 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1472 'state': 'LineWidth',
1479 'state': 'PolygonOffset',
1483 'gl_test_func': 'glDeleteBuffersARB',
1484 'resource_type': 'Buffer',
1485 'resource_types': 'Buffers',
1487 'DeleteFramebuffers': {
1489 'gl_test_func': 'glDeleteFramebuffersEXT',
1490 'resource_type': 'Framebuffer',
1491 'resource_types': 'Framebuffers',
1493 'DeleteProgram': {'type': 'Delete', 'decoder_func': 'DoDeleteProgram'},
1494 'DeleteRenderbuffers': {
1496 'gl_test_func': 'glDeleteRenderbuffersEXT',
1497 'resource_type': 'Renderbuffer',
1498 'resource_types': 'Renderbuffers',
1500 'DeleteShader': {'type': 'Delete', 'decoder_func': 'DoDeleteShader'},
1501 'DeleteSharedIdsCHROMIUM': {
1503 'decoder_func': 'DoDeleteSharedIdsCHROMIUM',
1505 'expectation': False,
1512 'resource_type': 'Texture',
1513 'resource_types': 'Textures',
1516 'decoder_func': 'DoDepthRangef',
1517 'gl_test_func': 'glDepthRange',
1521 'state': 'DepthMask',
1523 'expectation': False,
1525 'DetachShader': {'decoder_func': 'DoDetachShader'},
1527 'decoder_func': 'DoDisable',
1529 'client_test': False,
1531 'DisableVertexAttribArray': {
1532 'decoder_func': 'DoDisableVertexAttribArray',
1537 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1538 'defer_draws': True,
1543 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1544 'GLenumIndexType type, GLuint index_offset',
1545 'client_test': False,
1546 'defer_draws': True,
1550 'decoder_func': 'DoEnable',
1552 'client_test': False,
1554 'EnableVertexAttribArray': {
1555 'decoder_func': 'DoEnableVertexAttribArray',
1560 'client_test': False,
1561 'decoder_func': 'DoFinish',
1562 'defer_reads': True,
1566 'decoder_func': 'DoFlush',
1568 'FramebufferRenderbuffer': {
1569 'decoder_func': 'DoFramebufferRenderbuffer',
1570 'gl_test_func': 'glFramebufferRenderbufferEXT',
1572 'FramebufferTexture2D': {
1573 'decoder_func': 'DoFramebufferTexture2D',
1574 'gl_test_func': 'glFramebufferTexture2DEXT',
1577 'FramebufferTexture2DMultisampleEXT': {
1578 'decoder_func': 'DoFramebufferTexture2DMultisample',
1579 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1580 'expectation': False,
1586 'decoder_func': 'DoGenerateMipmap',
1587 'gl_test_func': 'glGenerateMipmapEXT',
1591 'gl_test_func': 'glGenBuffersARB',
1592 'resource_type': 'Buffer',
1593 'resource_types': 'Buffers',
1595 'GenMailboxCHROMIUM': {
1596 'type': 'HandWritten',
1602 'GenFramebuffers': {
1604 'gl_test_func': 'glGenFramebuffersEXT',
1605 'resource_type': 'Framebuffer',
1606 'resource_types': 'Framebuffers',
1608 'GenRenderbuffers': {
1609 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1610 'resource_type': 'Renderbuffer',
1611 'resource_types': 'Renderbuffers',
1615 'gl_test_func': 'glGenTextures',
1616 'resource_type': 'Texture',
1617 'resource_types': 'Textures',
1619 'GenSharedIdsCHROMIUM': {
1621 'decoder_func': 'DoGenSharedIdsCHROMIUM',
1623 'expectation': False,
1628 'GetActiveAttrib': {
1632 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1640 'GetActiveUniform': {
1644 'GLidProgram program, GLuint index, uint32 name_bucket_id, '
1652 'GetAttachedShaders': {
1655 'cmd_args': 'GLidProgram program, void* result, uint32 result_size',
1656 'result': ['SizedResult<GLuint>'],
1658 'GetAttribLocation': {
1659 'type': 'HandWritten',
1664 'GLidProgram program, const char* name, NonImmediate GLint* location',
1665 'result': ['GLint'],
1666 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml
1670 'result': ['SizedResult<GLboolean>'],
1671 'decoder_func': 'DoGetBooleanv',
1672 'gl_test_func': 'glGetBooleanv',
1674 'GetBufferParameteriv': {
1676 'result': ['SizedResult<GLint>'],
1677 'decoder_func': 'DoGetBufferParameteriv',
1678 'expectation': False,
1683 'decoder_func': 'GetErrorState()->GetGLError',
1685 'result': ['GLenum'],
1686 'client_test': False,
1690 'result': ['SizedResult<GLfloat>'],
1691 'decoder_func': 'DoGetFloatv',
1692 'gl_test_func': 'glGetFloatv',
1694 'GetFramebufferAttachmentParameteriv': {
1696 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
1697 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
1698 'result': ['SizedResult<GLint>'],
1702 'result': ['SizedResult<GLint>'],
1703 'decoder_func': 'DoGetIntegerv',
1704 'client_test': False,
1706 'GetMaxValueInBufferCHROMIUM': {
1708 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
1709 'result': ['GLuint'],
1711 'client_test': False,
1716 'GetMultipleIntegervCHROMIUM': {
1719 'expectation': False,
1722 'client_test': False,
1726 'decoder_func': 'DoGetProgramiv',
1727 'result': ['SizedResult<GLint>'],
1728 'expectation': False,
1730 'GetProgramInfoCHROMIUM': {
1733 'expectation': False,
1737 'client_test': False,
1738 'cmd_args': 'GLidProgram program, uint32 bucket_id',
1740 'uint32 link_status',
1741 'uint32 num_attribs',
1742 'uint32 num_uniforms',
1745 'GetProgramInfoLog': {
1747 'expectation': False,
1749 'GetRenderbufferParameteriv': {
1751 'decoder_func': 'DoGetRenderbufferParameteriv',
1752 'gl_test_func': 'glGetRenderbufferParameterivEXT',
1753 'result': ['SizedResult<GLint>'],
1757 'decoder_func': 'DoGetShaderiv',
1758 'result': ['SizedResult<GLint>'],
1760 'GetShaderInfoLog': {
1762 'get_len_func': 'glGetShaderiv',
1763 'get_len_enum': 'GL_INFO_LOG_LENGTH',
1766 'GetShaderPrecisionFormat': {
1770 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
1779 'GetShaderSource': {
1781 'get_len_func': 'DoGetShaderiv',
1782 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
1784 'client_test': False,
1788 'client_test': False,
1789 'cmd_args': 'GLenumStringType name, uint32 bucket_id',
1791 'GetTexParameterfv': {
1793 'decoder_func': 'DoGetTexParameterfv',
1794 'result': ['SizedResult<GLfloat>']
1796 'GetTexParameteriv': {
1798 'decoder_func': 'DoGetTexParameteriv',
1799 'result': ['SizedResult<GLint>']
1801 'GetTranslatedShaderSourceANGLE': {
1803 'get_len_func': 'DoGetShaderiv',
1804 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1811 'result': ['SizedResult<GLfloat>'],
1816 'result': ['SizedResult<GLint>'],
1818 'GetUniformLocation': {
1819 'type': 'HandWritten',
1824 'GLidProgram program, const char* name, NonImmediate GLint* location',
1825 'result': ['GLint'],
1826 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
1828 'GetVertexAttribfv': {
1830 'result': ['SizedResult<GLfloat>'],
1832 'decoder_func': 'DoGetVertexAttribfv',
1833 'expectation': False,
1834 'client_test': False,
1836 'GetVertexAttribiv': {
1838 'result': ['SizedResult<GLint>'],
1840 'decoder_func': 'DoGetVertexAttribiv',
1841 'expectation': False,
1842 'client_test': False,
1844 'GetVertexAttribPointerv': {
1847 'result': ['SizedResult<GLuint>'],
1848 'client_test': False,
1852 'decoder_func': 'DoIsBuffer',
1853 'expectation': False,
1857 'decoder_func': 'DoIsEnabled',
1859 'expectation': False,
1863 'decoder_func': 'DoIsFramebuffer',
1864 'expectation': False,
1868 'decoder_func': 'DoIsProgram',
1869 'expectation': False,
1873 'decoder_func': 'DoIsRenderbuffer',
1874 'expectation': False,
1878 'decoder_func': 'DoIsShader',
1879 'expectation': False,
1883 'decoder_func': 'DoIsTexture',
1884 'expectation': False,
1887 'decoder_func': 'DoLinkProgram',
1890 'MapBufferCHROMIUM': {
1894 'client_test': False,
1896 'MapBufferSubDataCHROMIUM': {
1900 'client_test': False,
1901 'pepper_interface': 'ChromiumMapSub',
1903 'MapImageCHROMIUM': {
1907 'client_test': False,
1909 'MapTexSubImage2DCHROMIUM': {
1913 'client_test': False,
1914 'pepper_interface': 'ChromiumMapSub',
1916 'PixelStorei': {'type': 'Manual'},
1917 'PostSubBufferCHROMIUM': {
1921 'client_test': False,
1925 'ProduceTextureCHROMIUM': {
1926 'decoder_func': 'DoProduceTextureCHROMIUM',
1929 'data_type': 'GLbyte',
1930 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1932 'client_test': False,
1937 'RenderbufferStorage': {
1938 'decoder_func': 'DoRenderbufferStorage',
1939 'gl_test_func': 'glRenderbufferStorageEXT',
1940 'expectation': False,
1942 'RenderbufferStorageMultisampleCHROMIUM': {
1944 '// GL_CHROMIUM_framebuffer_multisample\n',
1945 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
1946 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
1947 'expectation': False,
1950 'pepper_interface': 'FramebufferMultisample',
1951 'pepper_name': 'RenderbufferStorageMultisampleEXT',
1953 'RenderbufferStorageMultisampleEXT': {
1955 '// GL_EXT_multisampled_render_to_texture\n',
1956 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
1957 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
1958 'expectation': False,
1964 '// ReadPixels has the result separated from the pixel buffer so that\n'
1965 '// it is easier to specify the result going to some specific place\n'
1966 '// that exactly fits the rectangle of pixels.\n',
1970 'client_test': False,
1972 'GLint x, GLint y, GLsizei width, GLsizei height, '
1973 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
1974 'uint32 pixels_shm_id, uint32 pixels_shm_offset, '
1975 'uint32 result_shm_id, uint32 result_shm_offset, '
1977 'result': ['uint32'],
1978 'defer_reads': True,
1980 'RegisterSharedIdsCHROMIUM': {
1982 'decoder_func': 'DoRegisterSharedIdsCHROMIUM',
1984 'expectation': False,
1989 'ReleaseShaderCompiler': {
1990 'decoder_func': 'DoReleaseShaderCompiler',
1995 'client_test': False,
2002 'client_test': False,
2004 'GLuint shader, const char* data',
2006 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2009 'type': 'StateSetFrontBack',
2010 'state': 'StencilMask',
2012 'expectation': False,
2014 'StencilMaskSeparate': {
2015 'type': 'StateSetFrontBackSeparate',
2016 'state': 'StencilMask',
2018 'expectation': False,
2022 'decoder_func': 'DoSwapBuffers',
2024 'client_test': False,
2031 'client_test': False,
2034 'decoder_func': 'DoTexParameterf',
2040 'decoder_func': 'DoTexParameteri',
2047 'data_type': 'GLfloat',
2048 'data_value': 'GL_NEAREST',
2050 'decoder_func': 'DoTexParameterfv',
2051 'gl_test_func': 'glTexParameterf',
2052 'first_element_only': True,
2056 'data_type': 'GLint',
2057 'data_value': 'GL_NEAREST',
2059 'decoder_func': 'DoTexParameteriv',
2060 'gl_test_func': 'glTexParameteri',
2061 'first_element_only': True,
2066 'client_test': False,
2067 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2068 'GLint xoffset, GLint yoffset, '
2069 'GLsizei width, GLsizei height, '
2070 'GLenumTextureFormat format, GLenumPixelType type, '
2071 'const void* pixels, GLboolean internal'
2073 'Uniform1f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 1},
2076 'data_type': 'GLfloat',
2078 'decoder_func': 'DoUniform1fv',
2080 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2083 'data_type': 'GLint',
2085 'decoder_func': 'DoUniform1iv',
2088 'Uniform2i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 2},
2089 'Uniform2f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 2},
2092 'data_type': 'GLfloat',
2094 'decoder_func': 'DoUniform2fv',
2098 'data_type': 'GLint',
2100 'decoder_func': 'DoUniform2iv',
2102 'Uniform3i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 3},
2103 'Uniform3f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 3},
2106 'data_type': 'GLfloat',
2108 'decoder_func': 'DoUniform3fv',
2112 'data_type': 'GLint',
2114 'decoder_func': 'DoUniform3iv',
2116 'Uniform4i': {'type': 'PUTXn', 'data_type': 'GLint', 'count': 4},
2117 'Uniform4f': {'type': 'PUTXn', 'data_type': 'GLfloat', 'count': 4},
2120 'data_type': 'GLfloat',
2122 'decoder_func': 'DoUniform4fv',
2126 'data_type': 'GLint',
2128 'decoder_func': 'DoUniform4iv',
2130 'UniformMatrix2fv': {
2132 'data_type': 'GLfloat',
2134 'decoder_func': 'DoUniformMatrix2fv',
2136 'UniformMatrix3fv': {
2138 'data_type': 'GLfloat',
2140 'decoder_func': 'DoUniformMatrix3fv',
2142 'UniformMatrix4fv': {
2144 'data_type': 'GLfloat',
2146 'decoder_func': 'DoUniformMatrix4fv',
2148 'UnmapBufferCHROMIUM': {
2152 'client_test': False,
2154 'UnmapBufferSubDataCHROMIUM': {
2158 'client_test': False,
2159 'pepper_interface': 'ChromiumMapSub',
2161 'UnmapImageCHROMIUM': {
2165 'client_test': False,
2167 'UnmapTexSubImage2DCHROMIUM': {
2171 'client_test': False,
2172 'pepper_interface': 'ChromiumMapSub',
2176 'decoder_func': 'DoUseProgram',
2178 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2179 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2180 'VertexAttrib1fv': {
2182 'data_type': 'GLfloat',
2184 'decoder_func': 'DoVertexAttrib1fv',
2186 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2187 'VertexAttrib2fv': {
2189 'data_type': 'GLfloat',
2191 'decoder_func': 'DoVertexAttrib2fv',
2193 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2194 'VertexAttrib3fv': {
2196 'data_type': 'GLfloat',
2198 'decoder_func': 'DoVertexAttrib3fv',
2200 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2201 'VertexAttrib4fv': {
2203 'data_type': 'GLfloat',
2205 'decoder_func': 'DoVertexAttrib4fv',
2207 'VertexAttribPointer': {
2209 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2210 'GLenumVertexAttribType type, GLboolean normalized, '
2211 'GLsizei stride, GLuint offset',
2212 'client_test': False,
2219 'decoder_func': 'DoViewport',
2228 'GetRequestableExtensionsCHROMIUM': {
2232 'cmd_args': 'uint32 bucket_id',
2236 'RequestExtensionCHROMIUM': {
2240 'client_test': False,
2241 'cmd_args': 'uint32 bucket_id',
2245 'RateLimitOffscreenContextCHROMIUM': {
2249 'client_test': False,
2251 'CreateStreamTextureCHROMIUM': {
2252 'type': 'HandWritten',
2259 'TexImageIOSurface2DCHROMIUM': {
2260 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2265 'CopyTextureCHROMIUM': {
2266 'decoder_func': 'DoCopyTextureCHROMIUM',
2271 'TexStorage2DEXT': {
2274 'decoder_func': 'DoTexStorage2DEXT',
2276 'DrawArraysInstancedANGLE': {
2278 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2279 'GLsizei primcount',
2282 'pepper_interface': 'InstancedArrays',
2283 'defer_draws': True,
2287 'decoder_func': 'DoDrawBuffersEXT',
2288 'data_type': 'GLenum',
2290 'client_test': False,
2293 'pepper_interface': 'DrawBuffers',
2295 'DrawElementsInstancedANGLE': {
2297 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2298 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2301 'client_test': False,
2302 'pepper_interface': 'InstancedArrays',
2303 'defer_draws': True,
2305 'VertexAttribDivisorANGLE': {
2307 'cmd_args': 'GLuint index, GLuint divisor',
2310 'pepper_interface': 'InstancedArrays',
2314 'gl_test_func': 'glGenQueriesARB',
2315 'resource_type': 'Query',
2316 'resource_types': 'Queries',
2318 'pepper_interface': 'Query',
2320 'DeleteQueriesEXT': {
2322 'gl_test_func': 'glDeleteQueriesARB',
2323 'resource_type': 'Query',
2324 'resource_types': 'Queries',
2326 'pepper_interface': 'Query',
2330 'client_test': False,
2331 'pepper_interface': 'Query',
2335 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2337 'gl_test_func': 'glBeginQuery',
2338 'pepper_interface': 'Query',
2342 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2343 'gl_test_func': 'glEndnQuery',
2344 'client_test': False,
2345 'pepper_interface': 'Query',
2349 'client_test': False,
2350 'gl_test_func': 'glGetQueryiv',
2351 'pepper_interface': 'Query',
2353 'GetQueryObjectuivEXT': {
2355 'client_test': False,
2356 'gl_test_func': 'glGetQueryObjectuiv',
2357 'pepper_interface': 'Query',
2359 'BindUniformLocationCHROMIUM': {
2364 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2367 'InsertEventMarkerEXT': {
2369 'decoder_func': 'DoInsertEventMarkerEXT',
2370 'expectation': False,
2373 'PushGroupMarkerEXT': {
2375 'decoder_func': 'DoPushGroupMarkerEXT',
2376 'expectation': False,
2379 'PopGroupMarkerEXT': {
2380 'decoder_func': 'DoPopGroupMarkerEXT',
2381 'expectation': False,
2386 'GenVertexArraysOES': {
2389 'gl_test_func': 'glGenVertexArraysOES',
2390 'resource_type': 'VertexArray',
2391 'resource_types': 'VertexArrays',
2394 'BindVertexArrayOES': {
2397 'gl_test_func': 'glBindVertexArrayOES',
2398 'decoder_func': 'DoBindVertexArrayOES',
2399 'gen_func': 'GenVertexArraysOES',
2401 'client_test': False,
2403 'DeleteVertexArraysOES': {
2406 'gl_test_func': 'glDeleteVertexArraysOES',
2407 'resource_type': 'VertexArray',
2408 'resource_types': 'VertexArrays',
2411 'IsVertexArrayOES': {
2414 'gl_test_func': 'glIsVertexArrayOES',
2415 'decoder_func': 'DoIsVertexArrayOES',
2416 'expectation': False,
2419 'BindTexImage2DCHROMIUM': {
2420 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2425 'ReleaseTexImage2DCHROMIUM': {
2426 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2431 'ShallowFinishCHROMIUM': {
2436 'client_test': False,
2438 'ShallowFlushCHROMIUM': {
2443 'client_test': False,
2445 'TraceBeginCHROMIUM': {
2449 'client_test': False,
2450 'cmd_args': 'GLuint bucket_id',
2454 'TraceEndCHROMIUM': {
2457 'client_test': False,
2458 'decoder_func': 'DoTraceEndCHROMIUM',
2463 'AsyncTexImage2DCHROMIUM': {
2466 'client_test': False,
2467 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2468 'GLintTextureInternalFormat internalformat, '
2469 'GLsizei width, GLsizei height, '
2470 'GLintTextureBorder border, '
2471 'GLenumTextureFormat format, GLenumPixelType type, '
2472 'const void* pixels, '
2473 'uint32 async_upload_token, '
2478 'AsyncTexSubImage2DCHROMIUM': {
2481 'client_test': False,
2482 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2483 'GLint xoffset, GLint yoffset, '
2484 'GLsizei width, GLsizei height, '
2485 'GLenumTextureFormat format, GLenumPixelType type, '
2486 'const void* data, '
2487 'uint32 async_upload_token, '
2492 'WaitAsyncTexImage2DCHROMIUM': {
2495 'client_test': False,
2499 'WaitAllAsyncTexImage2DCHROMIUM': {
2502 'client_test': False,
2506 'DiscardFramebufferEXT': {
2509 'data_type': 'GLenum',
2510 'cmd_args': 'GLenum target, GLsizei count, '
2511 'const GLenum* attachments',
2512 'decoder_func': 'DoDiscardFramebufferEXT',
2514 'client_test': False,
2517 'LoseContextCHROMIUM': {
2523 'InsertSyncPointCHROMIUM': {
2524 'type': 'HandWritten',
2529 'WaitSyncPointCHROMIUM': {
2536 'DiscardBackbufferCHROMIUM': {
2542 'ScheduleOverlayPlaneCHROMIUM': {
2546 'client_test': False,
2553 def Grouper(n
, iterable
, fillvalue
=None):
2554 """Collect data into fixed-length chunks or blocks"""
2555 args
= [iter(iterable
)] * n
2556 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
2559 def SplitWords(input_string
):
2560 """Transforms a input_string into a list of lower-case components.
2563 input_string: the input string.
2566 a list of lower-case words.
2568 if input_string
.find('_') > -1:
2569 # 'some_TEXT_' -> 'some text'
2570 return input_string
.replace('_', ' ').strip().lower().split()
2572 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
2574 # look for capitalization to cut input_strings
2575 # 'SomeText' -> 'Some Text'
2576 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
2577 # 'Vector3' -> 'Vector 3'
2578 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
2579 return input_string
.lower().split()
2583 """Makes a lower-case identifier from words.
2586 words: a list of lower-case words.
2589 the lower-case identifier.
2591 return '_'.join(words
)
2594 def ToUnderscore(input_string
):
2595 """converts CamelCase to camel_case."""
2596 words
= SplitWords(input_string
)
2600 class CWriter(object):
2601 """Writes to a file formatting it for Google's style guidelines."""
2603 def __init__(self
, filename
):
2604 self
.filename
= filename
2608 def SetFileNum(self
, num
):
2609 """Used to help write number files and tests."""
2612 def Write(self
, string
):
2613 """Writes a string to a file spliting if it's > 80 characters."""
2614 lines
= string
.splitlines()
2615 num_lines
= len(lines
)
2616 for ii
in range(0, num_lines
):
2617 self
.content
.append(lines
[ii
])
2618 if ii
< (num_lines
- 1) or string
[-1] == '\n':
2619 self
.content
.append('\n')
2622 """Close the file."""
2623 content
= "".join(self
.content
)
2625 if os
.path
.exists(self
.filename
):
2626 old_file
= open(self
.filename
, "rb");
2627 old_content
= old_file
.read()
2629 if content
== old_content
:
2632 file = open(self
.filename
, "wb")
2637 class CHeaderWriter(CWriter
):
2638 """Writes a C Header file."""
2640 _non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
2642 def __init__(self
, filename
, file_comment
= None):
2643 CWriter
.__init
__(self
, filename
)
2645 base
= os
.path
.abspath(filename
)
2646 while os
.path
.basename(base
) != 'src':
2647 new_base
= os
.path
.dirname(base
)
2648 assert new_base
!= base
# Prevent infinite loop.
2651 hpath
= os
.path
.relpath(filename
, base
)
2652 self
.guard
= self
._non
_alnum
_re
.sub('_', hpath
).upper() + '_'
2654 self
.Write(_LICENSE
)
2655 self
.Write(_DO_NOT_EDIT_WARNING
)
2656 if not file_comment
== None:
2657 self
.Write(file_comment
)
2658 self
.Write("#ifndef %s\n" % self
.guard
)
2659 self
.Write("#define %s\n\n" % self
.guard
)
2662 self
.Write("#endif // %s\n\n" % self
.guard
)
2665 class TypeHandler(object):
2666 """This class emits code for a particular type of function."""
2668 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
2673 def InitFunction(self
, func
):
2674 """Add or adjust anything type specific for this function."""
2675 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
2676 func
.AddCmdArg(DataSizeArgument('data_size'))
2678 def AddImmediateFunction(self
, generator
, func
):
2679 """Adds an immediate version of a function."""
2680 # Generate an immediate command if there is only 1 pointer arg.
2681 immediate
= func
.GetInfo('immediate') # can be True, False or None
2682 if immediate
== True or immediate
== None:
2683 if func
.num_pointer_args
== 1 or immediate
:
2684 generator
.AddFunction(ImmediateFunction(func
))
2686 def AddBucketFunction(self
, generator
, func
):
2687 """Adds a bucket version of a function."""
2688 # Generate an immediate command if there is only 1 pointer arg.
2689 bucket
= func
.GetInfo('bucket') # can be True, False or None
2691 generator
.AddFunction(BucketFunction(func
))
2693 def WriteStruct(self
, func
, file):
2694 """Writes a structure that matches the arguments to a function."""
2695 comment
= func
.GetInfo('cmd_comment')
2696 if not comment
== None:
2698 file.Write("struct %s {\n" % func
.name
)
2699 file.Write(" typedef %s ValueType;\n" % func
.name
)
2700 file.Write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
2701 func
.WriteCmdArgFlag(file)
2702 func
.WriteCmdFlag(file)
2704 result
= func
.GetInfo('result')
2705 if not result
== None:
2706 if len(result
) == 1:
2707 file.Write(" typedef %s Result;\n\n" % result
[0])
2709 file.Write(" struct Result {\n")
2711 file.Write(" %s;\n" % line
)
2712 file.Write(" };\n\n")
2714 func
.WriteCmdComputeSize(file)
2715 func
.WriteCmdSetHeader(file)
2716 func
.WriteCmdInit(file)
2717 func
.WriteCmdSet(file)
2719 file.Write(" gpu::CommandHeader header;\n")
2720 args
= func
.GetCmdArgs()
2722 file.Write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
2726 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
2727 file.Write("COMPILE_ASSERT(sizeof(%s) == %d,\n" % (func
.name
, size
))
2728 file.Write(" Sizeof_%s_is_not_%d);\n" % (func
.name
, size
))
2729 file.Write("COMPILE_ASSERT(offsetof(%s, header) == 0,\n" % func
.name
)
2730 file.Write(" OffsetOf_%s_header_not_0);\n" % func
.name
)
2731 offset
= _SIZE_OF_COMMAND_HEADER
2733 file.Write("COMPILE_ASSERT(offsetof(%s, %s) == %d,\n" %
2734 (func
.name
, arg
.name
, offset
))
2735 file.Write(" OffsetOf_%s_%s_not_%d);\n" %
2736 (func
.name
, arg
.name
, offset
))
2737 offset
+= _SIZE_OF_UINT32
2738 if not result
== None and len(result
) > 1:
2741 parts
= line
.split()
2744 COMPILE_ASSERT(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
2745 OffsetOf_%(cmd_name)s_Result_%(field_name)s_not_%(offset)d);
2747 file.Write((check
.strip() + "\n") % {
2748 'cmd_name': func
.name
,
2752 offset
+= _SIZE_OF_UINT32
2755 def WriteHandlerImplementation(self
, func
, file):
2756 """Writes the handler implementation for this command."""
2757 file.Write(" %s(%s);\n" %
2758 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2760 def WriteCmdSizeTest(self
, func
, file):
2761 """Writes the size test for a command."""
2762 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2764 def WriteFormatTest(self
, func
, file):
2765 """Writes a format test for a command."""
2766 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
2767 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
2768 (func
.name
, func
.name
))
2769 file.Write(" void* next_cmd = cmd.Set(\n")
2771 args
= func
.GetCmdArgs()
2772 for value
, arg
in enumerate(args
):
2773 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
2775 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
2777 file.Write(" cmd.header.command);\n")
2778 func
.type_handler
.WriteCmdSizeTest(func
, file)
2779 for value
, arg
in enumerate(args
):
2780 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
2781 (arg
.type, value
+ 11, arg
.name
))
2782 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
2783 file.Write(" next_cmd, sizeof(cmd));\n")
2787 def WriteImmediateFormatTest(self
, func
, file):
2788 """Writes a format test for an immediate version of a command."""
2791 def WriteBucketFormatTest(self
, func
, file):
2792 """Writes a format test for a bucket version of a command."""
2795 def WriteGetDataSizeCode(self
, func
, file):
2796 """Writes the code to set data_size used in validation"""
2799 def WriteImmediateCmdSizeTest(self
, func
, file):
2800 """Writes a size test for an immediate version of a command."""
2801 file.Write(" // TODO(gman): Compute correct size.\n")
2802 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2804 def WriteImmediateHandlerImplementation (self
, func
, file):
2805 """Writes the handler impl for the immediate version of a command."""
2806 file.Write(" %s(%s);\n" %
2807 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2809 def WriteBucketHandlerImplementation (self
, func
, file):
2810 """Writes the handler impl for the bucket version of a command."""
2811 file.Write(" %s(%s);\n" %
2812 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2814 def WriteServiceImplementation(self
, func
, file):
2815 """Writes the service implementation for a command."""
2817 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
2819 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2821 self
.WriteHandlerDeferReadWrite(func
, file);
2822 if len(func
.GetOriginalArgs()) > 0:
2823 last_arg
= func
.GetLastOriginalArg()
2824 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2825 for arg
in all_but_last_arg
:
2826 arg
.WriteGetCode(file)
2827 self
.WriteGetDataSizeCode(func
, file)
2828 last_arg
.WriteGetCode(file)
2829 func
.WriteHandlerValidation(file)
2830 func
.WriteHandlerImplementation(file)
2831 file.Write(" return error::kNoError;\n")
2835 def WriteImmediateServiceImplementation(self
, func
, file):
2836 """Writes the service implementation for an immediate version of command."""
2838 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
2840 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
2842 self
.WriteHandlerDeferReadWrite(func
, file);
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 WriteBucketServiceImplementation(self
, func
, file):
2856 """Writes the service implementation for a bucket 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 WriteHandlerDeferReadWrite(self
, func
, file):
2876 """Writes the code to handle deferring reads or writes."""
2877 defer_draws
= func
.GetInfo('defer_draws')
2878 defer_reads
= func
.GetInfo('defer_reads')
2879 if defer_draws
or defer_reads
:
2880 file.Write(" error::Error error;\n")
2882 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
2883 file.Write(" if (error != error::kNoError)\n")
2884 file.Write(" return error;\n")
2886 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
2887 file.Write(" if (error != error::kNoError)\n")
2888 file.Write(" return error;\n")
2890 def WriteValidUnitTest(self
, func
, file, test
, extra
= {}):
2891 """Writes a valid unit test."""
2892 if func
.GetInfo('expectation') == False:
2893 test
= self
._remove
_expected
_call
_re
.sub('', test
)
2896 for count
, arg
in enumerate(func
.GetOriginalArgs()):
2897 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
2899 for count
, arg
in enumerate(func
.GetOriginalArgs()):
2900 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
2901 gl_func_name
= func
.GetGLTestFunctionName()
2903 'test_name': 'GLES2DecoderTest%d' % file.file_num
,
2905 'gl_func_name': gl_func_name
,
2906 'args': ", ".join(arg_strings
),
2907 'gl_args': ", ".join(gl_arg_strings
),
2911 while (old_test
!= test
):
2914 file.Write(test
% vars)
2916 def WriteInvalidUnitTest(self
, func
, file, test
, extra
= {}):
2917 """Writes a invalid unit test."""
2918 for arg_index
, arg
in enumerate(func
.GetOriginalArgs()):
2919 num_invalid_values
= arg
.GetNumInvalidValues(func
)
2920 for value_index
in range(0, num_invalid_values
):
2922 parse_result
= "kNoError"
2924 for count
, arg
in enumerate(func
.GetOriginalArgs()):
2925 if count
== arg_index
:
2926 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
2929 arg_string
= arg
.GetValidArg(func
, count
, 0)
2930 arg_strings
.append(arg_string
)
2932 for arg
in func
.GetOriginalArgs():
2933 gl_arg_strings
.append("_")
2934 gl_func_name
= func
.GetGLTestFunctionName()
2936 if not gl_error
== None:
2937 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
2940 'test_name': 'GLES2DecoderTest%d' % file.file_num
,
2942 'arg_index': arg_index
,
2943 'value_index': value_index
,
2944 'gl_func_name': gl_func_name
,
2945 'args': ", ".join(arg_strings
),
2946 'all_but_last_args': ", ".join(arg_strings
[:-1]),
2947 'gl_args': ", ".join(gl_arg_strings
),
2948 'parse_result': parse_result
,
2949 'gl_error_test': gl_error_test
,
2952 file.Write(test
% vars)
2954 def WriteServiceUnitTest(self
, func
, file):
2955 """Writes the service unit test for a command."""
2957 TEST_F(%(test_name)s, %(name)sValidArgs) {
2958 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
2959 SpecializedSetup<cmds::%(name)s, 0>(true);
2962 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
2963 EXPECT_EQ(GL_NO_ERROR, GetGLError());
2966 self
.WriteValidUnitTest(func
, file, valid_test
)
2969 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
2970 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
2971 SpecializedSetup<cmds::%(name)s, 0>(false);
2974 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
2977 self
.WriteInvalidUnitTest(func
, file, invalid_test
)
2979 def WriteImmediateServiceUnitTest(self
, func
, file):
2980 """Writes the service unit test for an immediate command."""
2981 file.Write("// TODO(gman): %s\n" % func
.name
)
2983 def WriteImmediateValidationCode(self
, func
, file):
2984 """Writes the validation code for an immediate version of a command."""
2987 def WriteBucketServiceUnitTest(self
, func
, file):
2988 """Writes the service unit test for a bucket command."""
2989 file.Write("// TODO(gman): %s\n" % func
.name
)
2991 def WriteBucketValidationCode(self
, func
, file):
2992 """Writes the validation code for a bucket version of a command."""
2993 file.Write("// TODO(gman): %s\n" % func
.name
)
2995 def WriteGLES2ImplementationDeclaration(self
, func
, file):
2996 """Writes the GLES2 Implemention declaration."""
2997 impl_decl
= func
.GetInfo('impl_decl')
2998 if impl_decl
== None or impl_decl
== True:
2999 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3000 (func
.return_type
, func
.original_name
,
3001 func
.MakeTypedOriginalArgString("")))
3004 def WriteGLES2CLibImplementation(self
, func
, file):
3005 file.Write("%s GLES2%s(%s) {\n" %
3006 (func
.return_type
, func
.name
,
3007 func
.MakeTypedOriginalArgString("")))
3008 result_string
= "return "
3009 if func
.return_type
== "void":
3011 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3012 (result_string
, func
.original_name
,
3013 func
.MakeOriginalArgString("")))
3016 def WriteGLES2Header(self
, func
, file):
3017 """Writes a re-write macro for GLES"""
3018 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
3020 def WriteClientGLCallLog(self
, func
, file):
3021 """Writes a logging macro for the client side code."""
3023 if len(func
.GetOriginalArgs()):
3026 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3027 (func
.original_name
, comma
, func
.MakeLogArgString()))
3029 def WriteClientGLReturnLog(self
, func
, file):
3030 """Writes the return value logging code."""
3031 if func
.return_type
!= "void":
3032 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3034 def WriteGLES2ImplementationHeader(self
, func
, file):
3035 """Writes the GLES2 Implemention."""
3036 self
.WriteGLES2ImplementationDeclaration(func
, file)
3038 def WriteGLES2TraceImplementationHeader(self
, func
, file):
3039 """Writes the GLES2 Trace Implemention header."""
3040 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3041 (func
.return_type
, func
.original_name
,
3042 func
.MakeTypedOriginalArgString("")))
3044 def WriteGLES2TraceImplementation(self
, func
, file):
3045 """Writes the GLES2 Trace Implemention."""
3046 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3047 (func
.return_type
, func
.original_name
,
3048 func
.MakeTypedOriginalArgString("")))
3049 result_string
= "return "
3050 if func
.return_type
== "void":
3052 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3054 file.Write(" %sgl_->%s(%s);\n" %
3055 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
3059 def WriteGLES2Implementation(self
, func
, file):
3060 """Writes the GLES2 Implemention."""
3061 impl_func
= func
.GetInfo('impl_func')
3062 impl_decl
= func
.GetInfo('impl_decl')
3063 gen_cmd
= func
.GetInfo('gen_cmd')
3064 if (func
.can_auto_generate
and
3065 (impl_func
== None or impl_func
== True) and
3066 (impl_decl
== None or impl_decl
== True) and
3067 (gen_cmd
== None or gen_cmd
== True)):
3068 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3069 (func
.return_type
, func
.original_name
,
3070 func
.MakeTypedOriginalArgString("")))
3071 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3072 self
.WriteClientGLCallLog(func
, file)
3073 func
.WriteDestinationInitalizationValidation(file)
3074 for arg
in func
.GetOriginalArgs():
3075 arg
.WriteClientSideValidationCode(file, func
)
3076 file.Write(" helper_->%s(%s);\n" %
3077 (func
.name
, func
.MakeOriginalArgString("")))
3078 file.Write(" CheckGLError();\n")
3079 self
.WriteClientGLReturnLog(func
, file)
3083 def WriteGLES2InterfaceHeader(self
, func
, file):
3084 """Writes the GLES2 Interface."""
3085 file.Write("virtual %s %s(%s) = 0;\n" %
3086 (func
.return_type
, func
.original_name
,
3087 func
.MakeTypedOriginalArgString("")))
3089 def WriteGLES2InterfaceStub(self
, func
, file):
3090 """Writes the GLES2 Interface stub declaration."""
3091 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3092 (func
.return_type
, func
.original_name
,
3093 func
.MakeTypedOriginalArgString("")))
3095 def WriteGLES2InterfaceStubImpl(self
, func
, file):
3096 """Writes the GLES2 Interface stub declaration."""
3097 args
= func
.GetOriginalArgs()
3098 arg_string
= ", ".join(
3099 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
3100 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3101 (func
.return_type
, func
.original_name
, arg_string
))
3102 if func
.return_type
!= "void":
3103 file.Write(" return 0;\n")
3106 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3107 """Writes the GLES2 Implemention unit test."""
3108 client_test
= func
.GetInfo('client_test')
3109 if (func
.can_auto_generate
and
3110 (client_test
== None or client_test
== True)):
3112 TEST_F(GLES2ImplementationTest, %(name)s) {
3117 expected.cmd.Init(%(cmd_args)s);
3119 gl_->%(name)s(%(args)s);
3120 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3123 cmd_arg_strings
= []
3124 for count
, arg
in enumerate(func
.GetCmdArgs()):
3125 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
3128 for count
, arg
in enumerate(func
.GetOriginalArgs()):
3129 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
3132 'args': ", ".join(gl_arg_strings
),
3133 'cmd_args': ", ".join(cmd_arg_strings
),
3136 if client_test
!= False:
3137 file.Write("// TODO: Implement unit test for %s\n" % func
.name
)
3139 def WriteDestinationInitalizationValidation(self
, func
, file):
3140 """Writes the client side destintion initialization validation."""
3141 for arg
in func
.GetOriginalArgs():
3142 arg
.WriteDestinationInitalizationValidation(file, func
)
3144 def WriteTraceEvent(self
, func
, file):
3145 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3148 def WriteImmediateCmdComputeSize(self
, func
, file):
3149 """Writes the size computation code for the immediate version of a cmd."""
3150 file.Write(" static uint32 ComputeSize(uint32 size_in_bytes) {\n")
3151 file.Write(" return static_cast<uint32>(\n")
3152 file.Write(" sizeof(ValueType) + // NOLINT\n")
3153 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3157 def WriteImmediateCmdSetHeader(self
, func
, file):
3158 """Writes the SetHeader function for the immediate version of a cmd."""
3159 file.Write(" void SetHeader(uint32 size_in_bytes) {\n")
3160 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3164 def WriteImmediateCmdInit(self
, func
, file):
3165 """Writes the Init function for the immediate version of a command."""
3166 raise NotImplementedError(func
.name
)
3168 def WriteImmediateCmdSet(self
, func
, file):
3169 """Writes the Set function for the immediate version of a command."""
3170 raise NotImplementedError(func
.name
)
3172 def WriteCmdHelper(self
, func
, file):
3173 """Writes the cmd helper definition for a cmd."""
3174 code
= """ void %(name)s(%(typed_args)s) {
3175 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3184 "typed_args": func
.MakeTypedCmdArgString(""),
3185 "args": func
.MakeCmdArgString(""),
3188 def WriteImmediateCmdHelper(self
, func
, file):
3189 """Writes the cmd helper definition for the immediate version of a cmd."""
3190 code
= """ void %(name)s(%(typed_args)s) {
3191 const uint32 s = 0; // TODO(gman): compute correct size
3192 gles2::cmds::%(name)s* c =
3193 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3202 "typed_args": func
.MakeTypedCmdArgString(""),
3203 "args": func
.MakeCmdArgString(""),
3207 class StateSetHandler(TypeHandler
):
3208 """Handler for commands that simply set state."""
3211 TypeHandler
.__init
__(self
)
3213 def WriteHandlerImplementation(self
, func
, file):
3214 """Overrriden from TypeHandler."""
3215 state_name
= func
.GetInfo('state')
3216 state
= _STATES
[state_name
]
3217 states
= state
['states']
3218 args
= func
.GetOriginalArgs()
3220 for ndx
,item
in enumerate(states
):
3221 if 'range_checks' in item
:
3222 for range_check
in item
['range_checks']:
3223 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
3225 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3227 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3228 ' "%s", "%s out of range");\n' %
3229 (func
.name
, args
[ndx
].name
))
3230 file.Write(" return error::kNoError;\n")
3233 for ndx
,item
in enumerate(states
):
3234 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
3235 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3236 for ndx
,item
in enumerate(states
):
3237 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
3238 if 'state_flag' in state
:
3239 file.Write(" %s = true;\n" % state
['state_flag'])
3240 if not func
.GetInfo("no_gl"):
3241 file.Write(" %s(%s);\n" %
3242 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3245 def WriteServiceUnitTest(self
, func
, file):
3246 """Overrriden from TypeHandler."""
3247 TypeHandler
.WriteServiceUnitTest(self
, func
, file)
3248 state_name
= func
.GetInfo('state')
3249 state
= _STATES
[state_name
]
3250 states
= state
['states']
3251 for ndx
,item
in enumerate(states
):
3252 if 'range_checks' in item
:
3253 for check_ndx
, range_check
in enumerate(item
['range_checks']):
3255 TEST_F(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3256 SpecializedSetup<cmds::%(name)s, 0>(false);
3259 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3260 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3265 for count
, arg
in enumerate(func
.GetOriginalArgs()):
3266 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
3267 arg_strings
[ndx
] = range_check
['test_value']
3269 'test_name': 'GLES2DecoderTest%d' % file.file_num
,
3272 'check_ndx': check_ndx
,
3273 'args': ", ".join(arg_strings
),
3275 file.Write(valid_test
% vars)
3278 class StateSetRGBAlphaHandler(TypeHandler
):
3279 """Handler for commands that simply set state that have rgb/alpha."""
3282 TypeHandler
.__init
__(self
)
3284 def WriteHandlerImplementation(self
, func
, file):
3285 """Overrriden from TypeHandler."""
3286 state_name
= func
.GetInfo('state')
3287 state
= _STATES
[state_name
]
3288 states
= state
['states']
3289 args
= func
.GetOriginalArgs()
3290 num_args
= len(args
)
3292 for ndx
,item
in enumerate(states
):
3293 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
3294 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3295 for ndx
, item
in enumerate(states
):
3296 file.Write(" state_.%s = %s;\n" %
3297 (item
['name'], args
[ndx
% num_args
].name
))
3298 if 'state_flag' in state
:
3299 file.Write(" %s = true;\n" % state
['state_flag'])
3300 if not func
.GetInfo("no_gl"):
3301 file.Write(" %s(%s);\n" %
3302 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3306 class StateSetFrontBackSeparateHandler(TypeHandler
):
3307 """Handler for commands that simply set state that have front/back."""
3310 TypeHandler
.__init
__(self
)
3312 def WriteHandlerImplementation(self
, func
, file):
3313 """Overrriden from TypeHandler."""
3314 state_name
= func
.GetInfo('state')
3315 state
= _STATES
[state_name
]
3316 states
= state
['states']
3317 args
= func
.GetOriginalArgs()
3319 num_args
= len(args
)
3320 file.Write(" bool changed = false;\n")
3321 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
3322 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3323 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
3325 for ndx
, item
in enumerate(group
):
3326 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
3327 file.Write(" changed |= %s;\n" % " ||\n ".join(code
))
3329 file.Write(" if (changed) {\n")
3330 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
3331 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3332 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
3333 for ndx
, item
in enumerate(group
):
3334 file.Write(" state_.%s = %s;\n" %
3335 (item
['name'], args
[ndx
+ 1].name
))
3337 if 'state_flag' in state
:
3338 file.Write(" %s = true;\n" % state
['state_flag'])
3339 if not func
.GetInfo("no_gl"):
3340 file.Write(" %s(%s);\n" %
3341 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3345 class StateSetFrontBackHandler(TypeHandler
):
3346 """Handler for commands that simply set state that set both front/back."""
3349 TypeHandler
.__init
__(self
)
3351 def WriteHandlerImplementation(self
, func
, file):
3352 """Overrriden from TypeHandler."""
3353 state_name
= func
.GetInfo('state')
3354 state
= _STATES
[state_name
]
3355 states
= state
['states']
3356 args
= func
.GetOriginalArgs()
3357 num_args
= len(args
)
3359 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
3360 for ndx
, item
in enumerate(group
):
3361 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
3362 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3363 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
3364 for ndx
, item
in enumerate(group
):
3365 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
3366 if 'state_flag' in state
:
3367 file.Write(" %s = true;\n" % state
['state_flag'])
3368 if not func
.GetInfo("no_gl"):
3369 file.Write(" %s(%s);\n" %
3370 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3374 class StateSetNamedParameter(TypeHandler
):
3375 """Handler for commands that set a state chosen with an enum parameter."""
3378 TypeHandler
.__init
__(self
)
3380 def WriteHandlerImplementation(self
, func
, file):
3381 """Overridden from TypeHandler."""
3382 state_name
= func
.GetInfo('state')
3383 state
= _STATES
[state_name
]
3384 states
= state
['states']
3385 args
= func
.GetOriginalArgs()
3386 num_args
= len(args
)
3387 assert num_args
== 2
3388 file.Write(" switch (%s) {\n" % args
[0].name
)
3389 for state
in states
:
3390 file.Write(" case %s:\n" % state
['enum'])
3391 file.Write(" if (state_.%s != %s) {\n" %
3392 (state
['name'], args
[1].name
))
3393 file.Write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
3394 if not func
.GetInfo("no_gl"):
3395 file.Write(" %s(%s);\n" %
3396 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3398 file.Write(" break;\n")
3399 file.Write(" default:\n")
3400 file.Write(" NOTREACHED();\n")
3404 class CustomHandler(TypeHandler
):
3405 """Handler for commands that are auto-generated but require minor tweaks."""
3408 TypeHandler
.__init
__(self
)
3410 def WriteServiceImplementation(self
, func
, file):
3411 """Overrriden from TypeHandler."""
3414 def WriteImmediateServiceImplementation(self
, func
, file):
3415 """Overrriden from TypeHandler."""
3418 def WriteBucketServiceImplementation(self
, func
, file):
3419 """Overrriden from TypeHandler."""
3422 def WriteServiceUnitTest(self
, func
, file):
3423 """Overrriden from TypeHandler."""
3424 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3426 def WriteImmediateServiceUnitTest(self
, func
, file):
3427 """Overrriden from TypeHandler."""
3428 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3430 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3431 """Overrriden from TypeHandler."""
3432 file.Write(" uint32 total_size = 0; // TODO(gman): get correct size.\n")
3434 def WriteImmediateCmdInit(self
, func
, file):
3435 """Overrriden from TypeHandler."""
3436 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
3437 self
.WriteImmediateCmdGetTotalSize(func
, file)
3438 file.Write(" SetHeader(total_size);\n")
3439 args
= func
.GetCmdArgs()
3441 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
3445 def WriteImmediateCmdSet(self
, func
, file):
3446 """Overrriden from TypeHandler."""
3447 copy_args
= func
.MakeCmdArgString("_", False)
3448 file.Write(" void* Set(void* cmd%s) {\n" %
3449 func
.MakeTypedCmdArgString("_", True))
3450 self
.WriteImmediateCmdGetTotalSize(func
, file)
3451 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
3452 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3453 "cmd, total_size);\n")
3458 class TodoHandler(CustomHandler
):
3459 """Handle for commands that are not yet implemented."""
3461 def AddImmediateFunction(self
, generator
, func
):
3462 """Overrriden from TypeHandler."""
3465 def WriteImmediateFormatTest(self
, func
, file):
3466 """Overrriden from TypeHandler."""
3469 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3470 """Overrriden from TypeHandler."""
3473 def WriteGLES2Implementation(self
, func
, file):
3474 """Overrriden from TypeHandler."""
3475 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3476 (func
.return_type
, func
.original_name
,
3477 func
.MakeTypedOriginalArgString("")))
3478 file.Write(" // TODO: for now this is a no-op\n")
3481 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3483 if func
.return_type
!= "void":
3484 file.Write(" return 0;\n")
3488 def WriteServiceImplementation(self
, func
, file):
3489 """Overrriden from TypeHandler."""
3491 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
3493 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
3495 file.Write(" // TODO: for now this is a no-op\n")
3497 " LOCAL_SET_GL_ERROR("
3498 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3500 file.Write(" return error::kNoError;\n")
3505 class HandWrittenHandler(CustomHandler
):
3506 """Handler for comands where everything must be written by hand."""
3508 def InitFunction(self
, func
):
3509 """Add or adjust anything type specific for this function."""
3510 CustomHandler
.InitFunction(self
, func
)
3511 func
.can_auto_generate
= False
3513 def WriteStruct(self
, func
, file):
3514 """Overrriden from TypeHandler."""
3517 def WriteDocs(self
, func
, file):
3518 """Overrriden from TypeHandler."""
3521 def WriteServiceUnitTest(self
, func
, file):
3522 """Overrriden from TypeHandler."""
3523 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3525 def WriteImmediateServiceUnitTest(self
, func
, file):
3526 """Overrriden from TypeHandler."""
3527 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3529 def WriteBucketServiceUnitTest(self
, func
, file):
3530 """Overrriden from TypeHandler."""
3531 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3533 def WriteServiceImplementation(self
, func
, file):
3534 """Overrriden from TypeHandler."""
3537 def WriteImmediateServiceImplementation(self
, func
, file):
3538 """Overrriden from TypeHandler."""
3541 def WriteBucketServiceImplementation(self
, func
, file):
3542 """Overrriden from TypeHandler."""
3545 def WriteImmediateCmdHelper(self
, func
, file):
3546 """Overrriden from TypeHandler."""
3549 def WriteBucketCmdHelper(self
, func
, file):
3550 """Overrriden from TypeHandler."""
3553 def WriteCmdHelper(self
, func
, file):
3554 """Overrriden from TypeHandler."""
3557 def WriteFormatTest(self
, func
, file):
3558 """Overrriden from TypeHandler."""
3559 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3561 def WriteImmediateFormatTest(self
, func
, file):
3562 """Overrriden from TypeHandler."""
3563 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3565 def WriteBucketFormatTest(self
, func
, file):
3566 """Overrriden from TypeHandler."""
3567 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3571 class ManualHandler(CustomHandler
):
3572 """Handler for commands who's handlers must be written by hand."""
3575 CustomHandler
.__init
__(self
)
3577 def InitFunction(self
, func
):
3578 """Overrriden from TypeHandler."""
3579 if (func
.name
== 'CompressedTexImage2DBucket'):
3580 func
.cmd_args
= func
.cmd_args
[:-1]
3581 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
3583 CustomHandler
.InitFunction(self
, func
)
3585 def WriteServiceImplementation(self
, func
, file):
3586 """Overrriden from TypeHandler."""
3589 def WriteBucketServiceImplementation(self
, func
, file):
3590 """Overrriden from TypeHandler."""
3593 def WriteServiceUnitTest(self
, func
, file):
3594 """Overrriden from TypeHandler."""
3595 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3597 def WriteImmediateServiceUnitTest(self
, func
, file):
3598 """Overrriden from TypeHandler."""
3599 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3601 def WriteImmediateServiceImplementation(self
, func
, file):
3602 """Overrriden from TypeHandler."""
3605 def WriteImmediateFormatTest(self
, func
, file):
3606 """Overrriden from TypeHandler."""
3607 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
3609 def WriteGLES2Implementation(self
, func
, file):
3610 """Overrriden from TypeHandler."""
3611 if func
.GetInfo('impl_func'):
3612 super(ManualHandler
, self
).WriteGLES2Implementation(func
, file)
3614 def WriteGLES2ImplementationHeader(self
, func
, file):
3615 """Overrriden from TypeHandler."""
3616 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3617 (func
.return_type
, func
.original_name
,
3618 func
.MakeTypedOriginalArgString("")))
3621 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3622 """Overrriden from TypeHandler."""
3623 # TODO(gman): Move this data to _FUNCTION_INFO?
3624 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, file)
3627 class DataHandler(TypeHandler
):
3628 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
3629 glCompressedTexImage2D, glCompressedTexImageSub2D."""
3631 TypeHandler
.__init
__(self
)
3633 def InitFunction(self
, func
):
3634 """Overrriden from TypeHandler."""
3635 if func
.name
== 'CompressedTexSubImage2DBucket':
3636 func
.cmd_args
= func
.cmd_args
[:-1]
3637 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
3639 def WriteGetDataSizeCode(self
, func
, file):
3640 """Overrriden from TypeHandler."""
3641 # TODO(gman): Move this data to _FUNCTION_INFO?
3643 if name
.endswith("Immediate"):
3645 if name
== 'BufferData' or name
== 'BufferSubData':
3646 file.Write(" uint32 data_size = size;\n")
3647 elif (name
== 'CompressedTexImage2D' or
3648 name
== 'CompressedTexSubImage2D'):
3649 file.Write(" uint32 data_size = imageSize;\n")
3650 elif (name
== 'CompressedTexSubImage2DBucket'):
3651 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
3652 file.Write(" uint32 data_size = bucket->size();\n")
3653 file.Write(" GLsizei imageSize = data_size;\n")
3654 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
3655 code
= """ uint32 data_size;
3656 if (!GLES2Util::ComputeImageDataSize(
3657 width, height, format, type, unpack_alignment_, &data_size)) {
3658 return error::kOutOfBounds;
3663 file.Write("// uint32 data_size = 0; // TODO(gman): get correct size!\n")
3665 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3666 """Overrriden from TypeHandler."""
3669 def WriteImmediateCmdSizeTest(self
, func
, file):
3670 """Overrriden from TypeHandler."""
3671 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
3673 def WriteImmediateCmdInit(self
, func
, file):
3674 """Overrriden from TypeHandler."""
3675 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
3676 self
.WriteImmediateCmdGetTotalSize(func
, file)
3677 file.Write(" SetHeader(total_size);\n")
3678 args
= func
.GetCmdArgs()
3680 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
3684 def WriteImmediateCmdSet(self
, func
, file):
3685 """Overrriden from TypeHandler."""
3686 copy_args
= func
.MakeCmdArgString("_", False)
3687 file.Write(" void* Set(void* cmd%s) {\n" %
3688 func
.MakeTypedCmdArgString("_", True))
3689 self
.WriteImmediateCmdGetTotalSize(func
, file)
3690 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
3691 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3692 "cmd, total_size);\n")
3696 def WriteImmediateFormatTest(self
, func
, file):
3697 """Overrriden from TypeHandler."""
3698 # TODO(gman): Remove this exception.
3699 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
3702 def WriteServiceUnitTest(self
, func
, file):
3703 """Overrriden from TypeHandler."""
3704 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3706 def WriteImmediateServiceUnitTest(self
, func
, file):
3707 """Overrriden from TypeHandler."""
3708 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3710 def WriteBucketServiceImplementation(self
, func
, file):
3711 """Overrriden from TypeHandler."""
3712 if not func
.name
== 'CompressedTexSubImage2DBucket':
3713 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, file)
3716 class BindHandler(TypeHandler
):
3717 """Handler for glBind___ type functions."""
3720 TypeHandler
.__init
__(self
)
3722 def WriteServiceUnitTest(self
, func
, file):
3723 """Overrriden from TypeHandler."""
3725 if len(func
.GetOriginalArgs()) == 1:
3727 TEST_F(%(test_name)s, %(name)sValidArgs) {
3728 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3729 SpecializedSetup<cmds::%(name)s, 0>(true);
3732 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3733 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3736 if func
.GetInfo("gen_func"):
3738 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3739 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
3740 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3741 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3742 SpecializedSetup<cmds::%(name)s, 0>(true);
3744 cmd.Init(kNewClientId);
3745 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3746 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3747 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3750 self
.WriteValidUnitTest(func
, file, valid_test
, {
3751 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
3752 'gl_gen_func_name': func
.GetInfo("gen_func"),
3756 TEST_F(%(test_name)s, %(name)sValidArgs) {
3757 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3758 SpecializedSetup<cmds::%(name)s, 0>(true);
3761 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3762 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3765 if func
.GetInfo("gen_func"):
3767 TEST_F(%(test_name)s, %(name)sValidArgsNewId) {
3768 EXPECT_CALL(*gl_, %(gl_func_name)s(%(first_gl_arg)s, kNewServiceId));
3769 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3770 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3771 SpecializedSetup<cmds::%(name)s, 0>(true);
3773 cmd.Init(%(first_arg)s, kNewClientId);
3774 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3775 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3776 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3779 self
.WriteValidUnitTest(func
, file, valid_test
, {
3780 'first_arg': func
.GetOriginalArgs()[0].GetValidArg(func
, 0, 0),
3781 'first_gl_arg': func
.GetOriginalArgs()[0].GetValidGLArg(func
, 0, 0),
3782 'resource_type': func
.GetOriginalArgs()[1].resource_type
,
3783 'gl_gen_func_name': func
.GetInfo("gen_func"),
3787 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3788 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3789 SpecializedSetup<cmds::%(name)s, 0>(false);
3792 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3795 self
.WriteInvalidUnitTest(func
, file, invalid_test
)
3797 def WriteGLES2Implementation(self
, func
, file):
3798 """Writes the GLES2 Implemention."""
3800 impl_func
= func
.GetInfo('impl_func')
3801 impl_decl
= func
.GetInfo('impl_decl')
3803 if (func
.can_auto_generate
and
3804 (impl_func
== None or impl_func
== True) and
3805 (impl_decl
== None or impl_decl
== True)):
3807 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3808 (func
.return_type
, func
.original_name
,
3809 func
.MakeTypedOriginalArgString("")))
3810 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3811 func
.WriteDestinationInitalizationValidation(file)
3812 self
.WriteClientGLCallLog(func
, file)
3813 for arg
in func
.GetOriginalArgs():
3814 arg
.WriteClientSideValidationCode(file, func
)
3816 code
= """ if (Is%(type)sReservedId(%(id)s)) {
3817 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
3820 if (%(name)sHelper(%(arg_string)s)) {
3821 helper_->%(name)s(%(arg_string)s);
3828 if len(func
.GetOriginalArgs()) == 1:
3829 # Bind functions that have no target (like BindVertexArrayOES)
3830 name_arg
= func
.GetOriginalArgs()[0]
3832 # Bind functions that have both a target and a name (like BindTexture)
3833 name_arg
= func
.GetOriginalArgs()[1]
3837 'arg_string': func
.MakeOriginalArgString(""),
3838 'id': name_arg
.name
,
3839 'type': name_arg
.resource_type
,
3840 'lc_type': name_arg
.resource_type
.lower(),
3843 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3844 """Overrriden from TypeHandler."""
3845 client_test
= func
.GetInfo('client_test')
3846 if client_test
== False:
3849 TEST_F(GLES2ImplementationTest, %(name)s) {
3854 expected.cmd.Init(%(cmd_args)s);
3856 gl_->%(name)s(%(args)s);
3857 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3859 gl_->%(name)s(%(args)s);
3860 EXPECT_TRUE(NoCommandsWritten());
3863 cmd_arg_strings
= []
3864 for count
, arg
in enumerate(func
.GetCmdArgs()):
3865 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
3868 for count
, arg
in enumerate(func
.GetOriginalArgs()):
3869 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
3872 'args': ", ".join(gl_arg_strings
),
3873 'cmd_args': ", ".join(cmd_arg_strings
),
3877 class GENnHandler(TypeHandler
):
3878 """Handler for glGen___ type functions."""
3881 TypeHandler
.__init
__(self
)
3883 def InitFunction(self
, func
):
3884 """Overrriden from TypeHandler."""
3887 def WriteGetDataSizeCode(self
, func
, file):
3888 """Overrriden from TypeHandler."""
3889 code
= """ uint32 data_size;
3890 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
3891 return error::kOutOfBounds;
3896 def WriteHandlerImplementation (self
, func
, file):
3897 """Overrriden from TypeHandler."""
3898 file.Write(" if (!%sHelper(n, %s)) {\n"
3899 " return error::kInvalidArguments;\n"
3901 (func
.name
, func
.GetLastOriginalArg().name
))
3903 def WriteImmediateHandlerImplementation(self
, func
, file):
3904 """Overrriden from TypeHandler."""
3905 file.Write(" if (!%sHelper(n, %s)) {\n"
3906 " return error::kInvalidArguments;\n"
3908 (func
.original_name
, func
.GetLastOriginalArg().name
))
3910 def WriteGLES2Implementation(self
, func
, file):
3911 """Overrriden from TypeHandler."""
3912 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
3913 for (GLsizei i = 0; i < n; ++i) {
3914 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
3916 });""" % func
.GetOriginalArgs()[1].name
)
3918 'log_code': log_code
,
3919 'return_type': func
.return_type
,
3920 'name': func
.original_name
,
3921 'typed_args': func
.MakeTypedOriginalArgString(""),
3922 'args': func
.MakeOriginalArgString(""),
3923 'resource_types': func
.GetInfo('resource_types'),
3924 'count_name': func
.GetOriginalArgs()[0].name
,
3927 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
3929 func
.WriteDestinationInitalizationValidation(file)
3930 self
.WriteClientGLCallLog(func
, file)
3931 for arg
in func
.GetOriginalArgs():
3932 arg
.WriteClientSideValidationCode(file, func
)
3933 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
3934 GetIdHandler(id_namespaces::k%(resource_types)s)->
3935 MakeIds(this, 0, %(args)s);
3936 %(name)sHelper(%(args)s);
3937 helper_->%(name)sImmediate(%(args)s);
3938 if (share_group_->bind_generates_resource())
3939 helper_->CommandBufferHelper::Flush();
3945 file.Write(code
% args
)
3947 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3948 """Overrriden from TypeHandler."""
3950 TEST_F(GLES2ImplementationTest, %(name)s) {
3951 GLuint ids[2] = { 0, };
3953 cmds::%(name)sImmediate gen;
3957 expected.gen.Init(arraysize(ids), &ids[0]);
3958 expected.data[0] = k%(types)sStartId;
3959 expected.data[1] = k%(types)sStartId + 1;
3960 gl_->%(name)s(arraysize(ids), &ids[0]);
3961 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3962 EXPECT_EQ(k%(types)sStartId, ids[0]);
3963 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
3968 'types': func
.GetInfo('resource_types'),
3971 def WriteServiceUnitTest(self
, func
, file):
3972 """Overrriden from TypeHandler."""
3974 TEST_F(%(test_name)s, %(name)sValidArgs) {
3975 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
3976 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3977 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
3978 SpecializedSetup<cmds::%(name)s, 0>(true);
3981 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3982 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3983 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
3986 self
.WriteValidUnitTest(func
, file, valid_test
, {
3987 'resource_name': func
.GetInfo('resource_type'),
3990 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
3991 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
3992 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
3993 SpecializedSetup<cmds::%(name)s, 0>(false);
3996 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
3999 self
.WriteValidUnitTest(func
, file, invalid_test
, {
4000 'resource_name': func
.GetInfo('resource_type').lower(),
4003 def WriteImmediateServiceUnitTest(self
, func
, file):
4004 """Overrriden from TypeHandler."""
4006 TEST_F(%(test_name)s, %(name)sValidArgs) {
4007 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4008 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4009 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4010 GLuint temp = kNewClientId;
4011 SpecializedSetup<cmds::%(name)s, 0>(true);
4012 cmd->Init(1, &temp);
4013 EXPECT_EQ(error::kNoError,
4014 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4015 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4016 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4019 self
.WriteValidUnitTest(func
, file, valid_test
, {
4020 'resource_name': func
.GetInfo('resource_type'),
4023 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4024 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4025 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4026 SpecializedSetup<cmds::%(name)s, 0>(false);
4027 cmd->Init(1, &client_%(resource_name)s_id_);
4028 EXPECT_EQ(error::kInvalidArguments,
4029 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4032 self
.WriteValidUnitTest(func
, file, invalid_test
, {
4033 'resource_name': func
.GetInfo('resource_type').lower(),
4036 def WriteImmediateCmdComputeSize(self
, func
, file):
4037 """Overrriden from TypeHandler."""
4038 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4040 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4043 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4044 file.Write(" return static_cast<uint32>(\n")
4045 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4049 def WriteImmediateCmdSetHeader(self
, func
, file):
4050 """Overrriden from TypeHandler."""
4051 file.Write(" void SetHeader(GLsizei n) {\n")
4052 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4056 def WriteImmediateCmdInit(self
, func
, file):
4057 """Overrriden from TypeHandler."""
4058 last_arg
= func
.GetLastOriginalArg()
4059 file.Write(" void Init(%s, %s _%s) {\n" %
4060 (func
.MakeTypedCmdArgString("_"),
4061 last_arg
.type, last_arg
.name
))
4062 file.Write(" SetHeader(_n);\n")
4063 args
= func
.GetCmdArgs()
4065 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4066 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4067 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
4071 def WriteImmediateCmdSet(self
, func
, file):
4072 """Overrriden from TypeHandler."""
4073 last_arg
= func
.GetLastOriginalArg()
4074 copy_args
= func
.MakeCmdArgString("_", False)
4075 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4076 (func
.MakeTypedCmdArgString("_", True),
4077 last_arg
.type, last_arg
.name
))
4078 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4079 (copy_args
, last_arg
.name
))
4080 file.Write(" const uint32 size = ComputeSize(_n);\n")
4081 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4086 def WriteImmediateCmdHelper(self
, func
, file):
4087 """Overrriden from TypeHandler."""
4088 code
= """ void %(name)s(%(typed_args)s) {
4089 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4090 gles2::cmds::%(name)s* c =
4091 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4100 "typed_args": func
.MakeTypedOriginalArgString(""),
4101 "args": func
.MakeOriginalArgString(""),
4104 def WriteImmediateFormatTest(self
, func
, file):
4105 """Overrriden from TypeHandler."""
4106 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4107 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4108 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4109 (func
.name
, func
.name
))
4110 file.Write(" void* next_cmd = cmd.Set(\n")
4111 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4112 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4114 file.Write(" cmd.header.command);\n")
4115 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4116 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4117 file.Write(" cmd.header.size * 4u);\n")
4118 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4119 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4120 file.Write(" next_cmd, sizeof(cmd) +\n")
4121 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4122 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4127 class CreateHandler(TypeHandler
):
4128 """Handler for glCreate___ type functions."""
4131 TypeHandler
.__init
__(self
)
4133 def InitFunction(self
, func
):
4134 """Overrriden from TypeHandler."""
4135 func
.AddCmdArg(Argument("client_id", 'uint32'))
4137 def WriteServiceUnitTest(self
, func
, file):
4138 """Overrriden from TypeHandler."""
4140 TEST_F(%(test_name)s, %(name)sValidArgs) {
4141 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4142 .WillOnce(Return(kNewServiceId));
4143 SpecializedSetup<cmds::%(name)s, 0>(true);
4145 cmd.Init(%(args)s%(comma)skNewClientId);
4146 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4147 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4148 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4152 if len(func
.GetOriginalArgs()):
4154 self
.WriteValidUnitTest(func
, file, valid_test
, {
4156 'resource_type': func
.name
[6:],
4159 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4160 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4161 SpecializedSetup<cmds::%(name)s, 0>(false);
4163 cmd.Init(%(args)s%(comma)skNewClientId);
4164 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
4167 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
4171 def WriteHandlerImplementation (self
, func
, file):
4172 """Overrriden from TypeHandler."""
4173 file.Write(" uint32 client_id = c.client_id;\n")
4174 file.Write(" if (!%sHelper(%s)) {\n" %
4175 (func
.name
, func
.MakeCmdArgString("")))
4176 file.Write(" return error::kInvalidArguments;\n")
4179 def WriteGLES2Implementation(self
, func
, file):
4180 """Overrriden from TypeHandler."""
4181 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4182 (func
.return_type
, func
.original_name
,
4183 func
.MakeTypedOriginalArgString("")))
4184 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4185 func
.WriteDestinationInitalizationValidation(file)
4186 self
.WriteClientGLCallLog(func
, file)
4187 for arg
in func
.GetOriginalArgs():
4188 arg
.WriteClientSideValidationCode(file, func
)
4189 file.Write(" GLuint client_id;\n")
4191 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
4192 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
4193 file.Write(" helper_->%s(%s);\n" %
4194 (func
.name
, func
.MakeCmdArgString("")))
4195 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
4196 file.Write(" CheckGLError();\n")
4197 file.Write(" return client_id;\n")
4202 class DeleteHandler(TypeHandler
):
4203 """Handler for glDelete___ single resource type functions."""
4206 TypeHandler
.__init
__(self
)
4208 def WriteServiceImplementation(self
, func
, file):
4209 """Overrriden from TypeHandler."""
4212 def WriteGLES2Implementation(self
, func
, file):
4213 """Overrriden from TypeHandler."""
4214 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4215 (func
.return_type
, func
.original_name
,
4216 func
.MakeTypedOriginalArgString("")))
4217 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4218 func
.WriteDestinationInitalizationValidation(file)
4219 self
.WriteClientGLCallLog(func
, file)
4220 for arg
in func
.GetOriginalArgs():
4221 arg
.WriteClientSideValidationCode(file, func
)
4223 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
4224 file.Write(" %sHelper(%s);\n" %
4225 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
4226 file.Write(" CheckGLError();\n")
4231 class DELnHandler(TypeHandler
):
4232 """Handler for glDelete___ type functions."""
4235 TypeHandler
.__init
__(self
)
4237 def WriteGetDataSizeCode(self
, func
, file):
4238 """Overrriden from TypeHandler."""
4239 code
= """ uint32 data_size;
4240 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4241 return error::kOutOfBounds;
4246 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4247 """Overrriden from TypeHandler."""
4249 TEST_F(GLES2ImplementationTest, %(name)s) {
4250 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
4252 cmds::%(name)sImmediate del;
4256 expected.del.Init(arraysize(ids), &ids[0]);
4257 expected.data[0] = k%(types)sStartId;
4258 expected.data[1] = k%(types)sStartId + 1;
4259 gl_->%(name)s(arraysize(ids), &ids[0]);
4260 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4265 'types': func
.GetInfo('resource_types'),
4268 def WriteServiceUnitTest(self
, func
, file):
4269 """Overrriden from TypeHandler."""
4271 TEST_F(%(test_name)s, %(name)sValidArgs) {
4274 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4276 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4277 SpecializedSetup<cmds::%(name)s, 0>(true);
4280 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4281 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4283 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4286 self
.WriteValidUnitTest(func
, file, valid_test
, {
4287 'resource_name': func
.GetInfo('resource_type').lower(),
4288 'upper_resource_name': func
.GetInfo('resource_type'),
4291 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4292 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
4293 SpecializedSetup<cmds::%(name)s, 0>(false);
4296 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4299 self
.WriteValidUnitTest(func
, file, invalid_test
)
4301 def WriteImmediateServiceUnitTest(self
, func
, file):
4302 """Overrriden from TypeHandler."""
4304 TEST_F(%(test_name)s, %(name)sValidArgs) {
4307 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4309 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4310 SpecializedSetup<cmds::%(name)s, 0>(true);
4311 cmd.Init(1, &client_%(resource_name)s_id_);
4312 EXPECT_EQ(error::kNoError,
4313 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
4314 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4316 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4319 self
.WriteValidUnitTest(func
, file, valid_test
, {
4320 'resource_name': func
.GetInfo('resource_type').lower(),
4321 'upper_resource_name': func
.GetInfo('resource_type'),
4324 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
4325 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4326 SpecializedSetup<cmds::%(name)s, 0>(false);
4327 GLuint temp = kInvalidClientId;
4329 EXPECT_EQ(error::kNoError,
4330 ExecuteImmediateCmd(cmd, sizeof(temp)));
4333 self
.WriteValidUnitTest(func
, file, invalid_test
)
4335 def WriteHandlerImplementation (self
, func
, file):
4336 """Overrriden from TypeHandler."""
4337 file.Write(" %sHelper(n, %s);\n" %
4338 (func
.name
, func
.GetLastOriginalArg().name
))
4340 def WriteImmediateHandlerImplementation (self
, func
, file):
4341 """Overrriden from TypeHandler."""
4342 file.Write(" %sHelper(n, %s);\n" %
4343 (func
.original_name
, func
.GetLastOriginalArg().name
))
4345 def WriteGLES2Implementation(self
, func
, file):
4346 """Overrriden from TypeHandler."""
4347 impl_decl
= func
.GetInfo('impl_decl')
4348 if impl_decl
== None or impl_decl
== True:
4350 'return_type': func
.return_type
,
4351 'name': func
.original_name
,
4352 'typed_args': func
.MakeTypedOriginalArgString(""),
4353 'args': func
.MakeOriginalArgString(""),
4354 'resource_type': func
.GetInfo('resource_type').lower(),
4355 'count_name': func
.GetOriginalArgs()[0].name
,
4358 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4360 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4361 func
.WriteDestinationInitalizationValidation(file)
4362 self
.WriteClientGLCallLog(func
, file)
4363 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
4364 for (GLsizei i = 0; i < n; ++i) {
4365 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4368 """ % func
.GetOriginalArgs()[1].name
)
4369 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
4370 for (GLsizei i = 0; i < n; ++i) {
4374 """ % func
.GetOriginalArgs()[1].name
)
4375 for arg
in func
.GetOriginalArgs():
4376 arg
.WriteClientSideValidationCode(file, func
)
4377 code
= """ %(name)sHelper(%(args)s);
4382 file.Write(code
% args
)
4384 def WriteImmediateCmdComputeSize(self
, func
, file):
4385 """Overrriden from TypeHandler."""
4386 file.Write(" static uint32 ComputeDataSize(GLsizei n) {\n")
4388 " return static_cast<uint32>(sizeof(GLuint) * n); // NOLINT\n")
4391 file.Write(" static uint32 ComputeSize(GLsizei n) {\n")
4392 file.Write(" return static_cast<uint32>(\n")
4393 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4397 def WriteImmediateCmdSetHeader(self
, func
, file):
4398 """Overrriden from TypeHandler."""
4399 file.Write(" void SetHeader(GLsizei n) {\n")
4400 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4404 def WriteImmediateCmdInit(self
, func
, file):
4405 """Overrriden from TypeHandler."""
4406 last_arg
= func
.GetLastOriginalArg()
4407 file.Write(" void Init(%s, %s _%s) {\n" %
4408 (func
.MakeTypedCmdArgString("_"),
4409 last_arg
.type, last_arg
.name
))
4410 file.Write(" SetHeader(_n);\n")
4411 args
= func
.GetCmdArgs()
4413 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4414 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4415 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
4419 def WriteImmediateCmdSet(self
, func
, file):
4420 """Overrriden from TypeHandler."""
4421 last_arg
= func
.GetLastOriginalArg()
4422 copy_args
= func
.MakeCmdArgString("_", False)
4423 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4424 (func
.MakeTypedCmdArgString("_", True),
4425 last_arg
.type, last_arg
.name
))
4426 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4427 (copy_args
, last_arg
.name
))
4428 file.Write(" const uint32 size = ComputeSize(_n);\n")
4429 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4434 def WriteImmediateCmdHelper(self
, func
, file):
4435 """Overrriden from TypeHandler."""
4436 code
= """ void %(name)s(%(typed_args)s) {
4437 const uint32 size = gles2::cmds::%(name)s::ComputeSize(n);
4438 gles2::cmds::%(name)s* c =
4439 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4448 "typed_args": func
.MakeTypedOriginalArgString(""),
4449 "args": func
.MakeOriginalArgString(""),
4452 def WriteImmediateFormatTest(self
, func
, file):
4453 """Overrriden from TypeHandler."""
4454 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4455 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4456 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4457 (func
.name
, func
.name
))
4458 file.Write(" void* next_cmd = cmd.Set(\n")
4459 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4460 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
4462 file.Write(" cmd.header.command);\n")
4463 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4464 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4465 file.Write(" cmd.header.size * 4u);\n")
4466 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4467 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4468 file.Write(" next_cmd, sizeof(cmd) +\n")
4469 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4470 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4475 class GETnHandler(TypeHandler
):
4476 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
4479 TypeHandler
.__init
__(self
)
4481 def AddImmediateFunction(self
, generator
, func
):
4482 """Overrriden from TypeHandler."""
4485 def WriteServiceImplementation(self
, func
, file):
4486 """Overrriden from TypeHandler."""
4488 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
4490 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
4492 last_arg
= func
.GetLastOriginalArg()
4494 all_but_last_args
= func
.GetOriginalArgs()[:-1]
4495 for arg
in all_but_last_args
:
4496 arg
.WriteGetCode(file)
4498 code
= """ typedef cmds::%(func_name)s::Result Result;
4499 GLsizei num_values = 0;
4500 GetNumValuesReturnedForGLGet(pname, &num_values);
4501 Result* result = GetSharedMemoryAs<Result*>(
4502 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
4503 %(last_arg_type)s params = result ? result->GetData() : NULL;
4506 'last_arg_type': last_arg
.type,
4507 'func_name': func
.name
,
4509 func
.WriteHandlerValidation(file)
4510 code
= """ // Check that the client initialized the result.
4511 if (result->size != 0) {
4512 return error::kInvalidArguments;
4515 shadowed
= func
.GetInfo('shadowed')
4517 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
4519 func
.WriteHandlerImplementation(file)
4521 code
= """ result->SetNumResults(num_values);
4522 return error::kNoError;
4526 code
= """ GLenum error = glGetError();
4527 if (error == GL_NO_ERROR) {
4528 result->SetNumResults(num_values);
4530 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
4532 return error::kNoError;
4536 file.Write(code
% {'func_name': func
.name
})
4538 def WriteGLES2Implementation(self
, func
, file):
4539 """Overrriden from TypeHandler."""
4540 impl_decl
= func
.GetInfo('impl_decl')
4541 if impl_decl
== None or impl_decl
== True:
4542 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4543 (func
.return_type
, func
.original_name
,
4544 func
.MakeTypedOriginalArgString("")))
4545 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4546 func
.WriteDestinationInitalizationValidation(file)
4547 self
.WriteClientGLCallLog(func
, file)
4548 for arg
in func
.GetOriginalArgs():
4549 arg
.WriteClientSideValidationCode(file, func
)
4550 all_but_last_args
= func
.GetOriginalArgs()[:-1]
4552 ", ".join(["%s" % arg
.name
for arg
in all_but_last_args
]))
4554 ", ".join(["%s" % arg
.name
for arg
in func
.GetOriginalArgs()]))
4555 self
.WriteTraceEvent(func
, file)
4556 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
4559 typedef cmds::%(func_name)s::Result Result;
4560 Result* result = GetResultAs<Result*>();
4564 result->SetNumResults(0);
4565 helper_->%(func_name)s(%(arg_string)s,
4566 GetResultShmId(), GetResultShmOffset());
4568 result->CopyResult(params);
4569 GPU_CLIENT_LOG_CODE_BLOCK({
4570 for (int32 i = 0; i < result->GetNumResults(); ++i) {
4571 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
4578 'func_name': func
.name
,
4579 'arg_string': arg_string
,
4580 'all_arg_string': all_arg_string
,
4583 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4584 """Writes the GLES2 Implemention unit test."""
4586 TEST_F(GLES2ImplementationTest, %(name)s) {
4590 typedef cmds::%(name)s::Result Result;
4591 Result::Type result = 0;
4593 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
4594 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
4595 EXPECT_CALL(*command_buffer(), OnFlush())
4596 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
4597 .RetiresOnSaturation();
4598 gl_->%(name)s(%(args)s, &result);
4599 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4600 EXPECT_EQ(static_cast<Result::Type>(1), result);
4603 cmd_arg_strings
= []
4604 for count
, arg
in enumerate(func
.GetCmdArgs()[0:-2]):
4605 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
4606 cmd_arg_strings
[0] = '123'
4608 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
4609 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
4610 gl_arg_strings
[0] = '123'
4613 'args': ", ".join(gl_arg_strings
),
4614 'cmd_args': ", ".join(cmd_arg_strings
),
4617 def WriteServiceUnitTest(self
, func
, file):
4618 """Overrriden from TypeHandler."""
4620 TEST_F(%(test_name)s, %(name)sValidArgs) {
4621 EXPECT_CALL(*gl_, GetError())
4622 .WillOnce(Return(GL_NO_ERROR))
4623 .WillOnce(Return(GL_NO_ERROR))
4624 .RetiresOnSaturation();
4625 SpecializedSetup<cmds::%(name)s, 0>(true);
4626 typedef cmds::%(name)s::Result Result;
4627 Result* result = static_cast<Result*>(shared_memory_address_);
4628 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
4632 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4633 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
4635 result->GetNumResults());
4636 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4641 for count
, arg
in enumerate(func
.GetOriginalArgs()[:-1]):
4642 arg_value
= arg
.GetValidGLArg(func
, count
, 0)
4643 gl_arg_strings
.append(arg_value
)
4644 if arg
.name
== 'pname':
4645 valid_pname
= arg_value
4646 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
4647 gl_arg_strings
.append("_")
4649 gl_arg_strings
.append("result->GetData()")
4651 self
.WriteValidUnitTest(func
, file, valid_test
, {
4652 'local_gl_args': ", ".join(gl_arg_strings
),
4653 'valid_pname': valid_pname
,
4657 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4658 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4659 SpecializedSetup<cmds::%(name)s, 0>(false);
4660 cmds::%(name)s::Result* result =
4661 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
4665 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
4666 EXPECT_EQ(0u, result->size);%(gl_error_test)s
4669 self
.WriteInvalidUnitTest(func
, file, invalid_test
)
4672 class PUTHandler(TypeHandler
):
4673 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
4676 TypeHandler
.__init
__(self
)
4678 def WriteServiceUnitTest(self
, func
, file):
4679 """Writes the service unit test for a command."""
4680 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
4681 if func
.GetInfo("first_element_only"):
4683 for count
, arg
in enumerate(func
.GetOriginalArgs()):
4684 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
4685 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
4686 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
4687 ", ".join(gl_arg_strings
))
4689 TEST_F(%(test_name)s, %(name)sValidArgs) {
4690 SpecializedSetup<cmds::%(name)s, 0>(true);
4693 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4695 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4696 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4700 'data_type': func
.GetInfo('data_type'),
4701 'data_value': func
.GetInfo('data_value') or '0',
4702 'expected_call': expected_call
,
4704 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
4707 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4708 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4709 SpecializedSetup<cmds::%(name)s, 0>(false);
4712 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4713 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4716 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
)
4718 def WriteImmediateServiceUnitTest(self
, func
, file):
4719 """Writes the service unit test for a command."""
4721 TEST_F(%(test_name)s, %(name)sValidArgs) {
4722 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4723 SpecializedSetup<cmds::%(name)s, 0>(true);
4724 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4725 cmd.Init(%(gl_args)s, &temp[0]);
4728 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
4729 %(data_type)s*>(ImmediateDataAddress(&cmd))));
4730 EXPECT_EQ(error::kNoError,
4731 ExecuteImmediateCmd(cmd, sizeof(temp)));
4732 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4737 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
4738 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
4739 gl_any_strings
.append("_")
4741 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
4742 'data_type': func
.GetInfo('data_type'),
4743 'data_count': func
.GetInfo('count'),
4744 'data_value': func
.GetInfo('data_value') or '0',
4745 'gl_args': ", ".join(gl_arg_strings
),
4746 'gl_any_args': ", ".join(gl_any_strings
),
4748 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
4751 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4752 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4753 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
4754 SpecializedSetup<cmds::%(name)s, 0>(false);
4755 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
4756 cmd.Init(%(all_but_last_args)s, &temp[0]);
4757 EXPECT_EQ(error::%(parse_result)s,
4758 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
4761 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
)
4763 def WriteGetDataSizeCode(self
, func
, file):
4764 """Overrriden from TypeHandler."""
4765 code
= """ uint32 data_size;
4766 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
4767 return error::kOutOfBounds;
4770 file.Write(code
% (func
.info
.data_type
, func
.info
.count
))
4771 if func
.is_immediate
:
4772 file.Write(" if (data_size > immediate_data_size) {\n")
4773 file.Write(" return error::kOutOfBounds;\n")
4776 def WriteGLES2Implementation(self
, func
, file):
4777 """Overrriden from TypeHandler."""
4778 impl_func
= func
.GetInfo('impl_func')
4779 if (impl_func
!= None and impl_func
!= True):
4781 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4782 (func
.return_type
, func
.original_name
,
4783 func
.MakeTypedOriginalArgString("")))
4784 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4785 func
.WriteDestinationInitalizationValidation(file)
4786 self
.WriteClientGLCallLog(func
, file)
4787 last_arg_name
= func
.GetLastOriginalArg().name
4788 values_str
= ' << ", " << '.join(
4789 ["%s[%d]" % (last_arg_name
, ndx
) for ndx
in range(0, func
.info
.count
)])
4790 file.Write(' GPU_CLIENT_LOG("values: " << %s);\n' % values_str
)
4791 for arg
in func
.GetOriginalArgs():
4792 arg
.WriteClientSideValidationCode(file, func
)
4793 file.Write(" helper_->%sImmediate(%s);\n" %
4794 (func
.name
, func
.MakeOriginalArgString("")))
4795 file.Write(" CheckGLError();\n")
4799 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4800 """Writes the GLES2 Implemention unit test."""
4801 client_test
= func
.GetInfo('client_test')
4802 if (client_test
!= None and client_test
!= True):
4805 TEST_F(GLES2ImplementationTest, %(name)s) {
4806 %(type)s data[%(count)d] = {0};
4808 cmds::%(name)sImmediate cmd;
4809 %(type)s data[%(count)d];
4812 for (int jj = 0; jj < %(count)d; ++jj) {
4813 data[jj] = static_cast<%(type)s>(jj);
4816 expected.cmd.Init(%(cmd_args)s, &data[0]);
4817 gl_->%(name)s(%(args)s, &data[0]);
4818 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4821 cmd_arg_strings
= []
4822 for count
, arg
in enumerate(func
.GetCmdArgs()[0:-2]):
4823 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
4825 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
4826 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
4829 'type': func
.GetInfo('data_type'),
4830 'count': func
.GetInfo('count'),
4831 'args': ", ".join(gl_arg_strings
),
4832 'cmd_args': ", ".join(cmd_arg_strings
),
4835 def WriteImmediateCmdComputeSize(self
, func
, file):
4836 """Overrriden from TypeHandler."""
4837 file.Write(" static uint32 ComputeDataSize() {\n")
4838 file.Write(" return static_cast<uint32>(\n")
4839 file.Write(" sizeof(%s) * %d); // NOLINT\n" %
4840 (func
.info
.data_type
, func
.info
.count
))
4843 file.Write(" static uint32 ComputeSize() {\n")
4844 file.Write(" return static_cast<uint32>(\n")
4846 " sizeof(ValueType) + ComputeDataSize()); // NOLINT\n")
4850 def WriteImmediateCmdSetHeader(self
, func
, file):
4851 """Overrriden from TypeHandler."""
4852 file.Write(" void SetHeader() {\n")
4854 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
4858 def WriteImmediateCmdInit(self
, func
, file):
4859 """Overrriden from TypeHandler."""
4860 last_arg
= func
.GetLastOriginalArg()
4861 file.Write(" void Init(%s, %s _%s) {\n" %
4862 (func
.MakeTypedCmdArgString("_"),
4863 last_arg
.type, last_arg
.name
))
4864 file.Write(" SetHeader();\n")
4865 args
= func
.GetCmdArgs()
4867 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4868 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4869 file.Write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
4873 def WriteImmediateCmdSet(self
, func
, file):
4874 """Overrriden from TypeHandler."""
4875 last_arg
= func
.GetLastOriginalArg()
4876 copy_args
= func
.MakeCmdArgString("_", False)
4877 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4878 (func
.MakeTypedCmdArgString("_", True),
4879 last_arg
.type, last_arg
.name
))
4880 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4881 (copy_args
, last_arg
.name
))
4882 file.Write(" const uint32 size = ComputeSize();\n")
4883 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4888 def WriteImmediateCmdHelper(self
, func
, file):
4889 """Overrriden from TypeHandler."""
4890 code
= """ void %(name)s(%(typed_args)s) {
4891 const uint32 size = gles2::cmds::%(name)s::ComputeSize();
4892 gles2::cmds::%(name)s* c =
4893 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4902 "typed_args": func
.MakeTypedOriginalArgString(""),
4903 "args": func
.MakeOriginalArgString(""),
4906 def WriteImmediateFormatTest(self
, func
, file):
4907 """Overrriden from TypeHandler."""
4908 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4909 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
4910 file.Write(" static %s data[] = {\n" % func
.info
.data_type
)
4911 for v
in range(0, func
.info
.count
):
4912 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
4913 (func
.info
.data_type
, v
))
4915 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4916 (func
.name
, func
.name
))
4917 file.Write(" void* next_cmd = cmd.Set(\n")
4919 args
= func
.GetCmdArgs()
4920 for value
, arg
in enumerate(args
):
4921 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
4922 file.Write(",\n data);\n")
4923 args
= func
.GetCmdArgs()
4924 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n"
4926 file.Write(" cmd.header.command);\n")
4927 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4928 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
4929 file.Write(" cmd.header.size * 4u);\n")
4930 for value
, arg
in enumerate(args
):
4931 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4932 (arg
.type, value
+ 11, arg
.name
))
4933 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4934 file.Write(" next_cmd, sizeof(cmd) +\n")
4935 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
4936 file.Write(" // TODO(gman): Check that data was inserted;\n")
4941 class PUTnHandler(TypeHandler
):
4942 """Handler for PUTn 'glUniform__v' type functions."""
4945 TypeHandler
.__init
__(self
)
4947 def WriteServiceUnitTest(self
, func
, file):
4948 """Overridden from TypeHandler."""
4949 TypeHandler
.WriteServiceUnitTest(self
, func
, file)
4952 TEST_F(%(test_name)s, %(name)sValidArgsCountTooLarge) {
4953 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4954 SpecializedSetup<cmds::%(name)s, 0>(true);
4957 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4958 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4963 for count
, arg
in enumerate(func
.GetOriginalArgs()):
4964 # hardcoded to match unit tests.
4966 # the location of the second element of the 2nd uniform.
4967 # defined in GLES2DecoderBase::SetupShaderForUniform
4968 gl_arg_strings
.append("3")
4969 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
4971 # the number of elements that gl will be called with.
4972 gl_arg_strings
.append("3")
4973 # the number of elements requested in the command.
4974 arg_strings
.append("5")
4976 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
4977 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
4979 'gl_args': ", ".join(gl_arg_strings
),
4980 'args': ", ".join(arg_strings
),
4982 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
4984 def WriteImmediateServiceUnitTest(self
, func
, file):
4985 """Overridden from TypeHandler."""
4987 TEST_F(%(test_name)s, %(name)sValidArgs) {
4988 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4991 %(gl_func_name)s(%(gl_args)s,
4992 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
4993 SpecializedSetup<cmds::%(name)s, 0>(true);
4994 %(data_type)s temp[%(data_count)s * 2] = { 0, };
4995 cmd.Init(%(args)s, &temp[0]);
4996 EXPECT_EQ(error::kNoError,
4997 ExecuteImmediateCmd(cmd, sizeof(temp)));
4998 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5004 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
5005 gl_arg_strings
.append(arg
.GetValidGLArg(func
, count
, 0))
5006 gl_any_strings
.append("_")
5007 arg_strings
.append(arg
.GetValidArg(func
, count
, 0))
5009 'data_type': func
.GetInfo('data_type'),
5010 'data_count': func
.GetInfo('count'),
5011 'args': ", ".join(arg_strings
),
5012 'gl_args': ", ".join(gl_arg_strings
),
5013 'gl_any_args': ", ".join(gl_any_strings
),
5015 self
.WriteValidUnitTest(func
, file, valid_test
, extra
)
5018 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5019 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5020 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5021 SpecializedSetup<cmds::%(name)s, 0>(false);
5022 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5023 cmd.Init(%(all_but_last_args)s, &temp[0]);
5024 EXPECT_EQ(error::%(parse_result)s,
5025 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5028 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
)
5030 def WriteGetDataSizeCode(self
, func
, file):
5031 """Overrriden from TypeHandler."""
5032 code
= """ uint32 data_size;
5033 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
5034 return error::kOutOfBounds;
5037 file.Write(code
% (func
.info
.data_type
, func
.info
.count
))
5038 if func
.is_immediate
:
5039 file.Write(" if (data_size > immediate_data_size) {\n")
5040 file.Write(" return error::kOutOfBounds;\n")
5043 def WriteGLES2Implementation(self
, func
, file):
5044 """Overrriden from TypeHandler."""
5045 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5046 (func
.return_type
, func
.original_name
,
5047 func
.MakeTypedOriginalArgString("")))
5048 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5049 func
.WriteDestinationInitalizationValidation(file)
5050 self
.WriteClientGLCallLog(func
, file)
5051 last_arg_name
= func
.GetLastOriginalArg().name
5052 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5053 for (GLsizei i = 0; i < count; ++i) {
5055 values_str
= ' << ", " << '.join(
5056 ["%s[%d + i * %d]" % (
5057 last_arg_name
, ndx
, func
.info
.count
) for ndx
in range(
5058 0, func
.info
.count
)])
5059 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
5060 file.Write(" }\n });\n")
5061 for arg
in func
.GetOriginalArgs():
5062 arg
.WriteClientSideValidationCode(file, func
)
5063 file.Write(" helper_->%sImmediate(%s);\n" %
5064 (func
.name
, func
.MakeOriginalArgString("")))
5065 file.Write(" CheckGLError();\n")
5069 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5070 """Writes the GLES2 Implemention unit test."""
5072 TEST_F(GLES2ImplementationTest, %(name)s) {
5073 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5075 cmds::%(name)sImmediate cmd;
5076 %(type)s data[%(count_param)d][%(count)d];
5080 for (int ii = 0; ii < %(count_param)d; ++ii) {
5081 for (int jj = 0; jj < %(count)d; ++jj) {
5082 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5085 expected.cmd.Init(%(cmd_args)s, &data[0][0]);
5086 gl_->%(name)s(%(args)s, &data[0][0]);
5087 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5090 cmd_arg_strings
= []
5091 for count
, arg
in enumerate(func
.GetCmdArgs()[0:-2]):
5092 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
, count
, 0))
5095 for count
, arg
in enumerate(func
.GetOriginalArgs()[0:-1]):
5096 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
, count
, 0))
5097 if arg
.name
== "count":
5098 count_param
= int(arg
.GetValidClientSideArg(func
, count
, 0))
5101 'type': func
.GetInfo('data_type'),
5102 'count': func
.GetInfo('count'),
5103 'args': ", ".join(gl_arg_strings
),
5104 'cmd_args': ", ".join(cmd_arg_strings
),
5105 'count_param': count_param
,
5108 def WriteImmediateCmdComputeSize(self
, func
, file):
5109 """Overrriden from TypeHandler."""
5110 file.Write(" static uint32 ComputeDataSize(GLsizei count) {\n")
5111 file.Write(" return static_cast<uint32>(\n")
5112 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
5113 (func
.info
.data_type
, func
.info
.count
))
5116 file.Write(" static uint32 ComputeSize(GLsizei count) {\n")
5117 file.Write(" return static_cast<uint32>(\n")
5119 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
5123 def WriteImmediateCmdSetHeader(self
, func
, file):
5124 """Overrriden from TypeHandler."""
5125 file.Write(" void SetHeader(GLsizei count) {\n")
5127 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
5131 def WriteImmediateCmdInit(self
, func
, file):
5132 """Overrriden from TypeHandler."""
5133 last_arg
= func
.GetLastOriginalArg()
5134 file.Write(" void Init(%s, %s _%s) {\n" %
5135 (func
.MakeTypedCmdArgString("_"),
5136 last_arg
.type, last_arg
.name
))
5137 file.Write(" SetHeader(_count);\n")
5138 args
= func
.GetCmdArgs()
5140 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5141 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5142 file.Write(" _%s, ComputeDataSize(_count));\n" % last_arg
.name
)
5146 def WriteImmediateCmdSet(self
, func
, file):
5147 """Overrriden from TypeHandler."""
5148 last_arg
= func
.GetLastOriginalArg()
5149 copy_args
= func
.MakeCmdArgString("_", False)
5150 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5151 (func
.MakeTypedCmdArgString("_", True),
5152 last_arg
.type, last_arg
.name
))
5153 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5154 (copy_args
, last_arg
.name
))
5155 file.Write(" const uint32 size = ComputeSize(_count);\n")
5156 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5161 def WriteImmediateCmdHelper(self
, func
, file):
5162 """Overrriden from TypeHandler."""
5163 code
= """ void %(name)s(%(typed_args)s) {
5164 const uint32 size = gles2::cmds::%(name)s::ComputeSize(count);
5165 gles2::cmds::%(name)s* c =
5166 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5175 "typed_args": func
.MakeTypedOriginalArgString(""),
5176 "args": func
.MakeOriginalArgString(""),
5179 def WriteImmediateFormatTest(self
, func
, file):
5180 """Overrriden from TypeHandler."""
5181 args
= func
.GetCmdArgs()
5183 for value
, arg
in enumerate(args
):
5184 if arg
.name
== "count":
5185 count_param
= int(arg
.GetValidClientSideArg(func
, value
, 0))
5186 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5187 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5188 file.Write(" static %s data[] = {\n" % func
.info
.data_type
)
5189 for v
in range(0, func
.info
.count
* count_param
):
5190 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5191 (func
.info
.data_type
, v
))
5193 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5194 (func
.name
, func
.name
))
5195 file.Write(" const GLsizei kNumElements = %d;\n" % count_param
)
5196 file.Write(" const size_t kExpectedCmdSize =\n")
5197 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
5198 (func
.info
.data_type
, func
.info
.count
))
5199 file.Write(" void* next_cmd = cmd.Set(\n")
5201 for value
, arg
in enumerate(args
):
5202 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
5203 file.Write(",\n data);\n")
5204 file.Write(" EXPECT_EQ(static_cast<uint32>(cmds::%s::kCmdId),\n" %
5206 file.Write(" cmd.header.command);\n")
5207 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
5208 for value
, arg
in enumerate(args
):
5209 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5210 (arg
.type, value
+ 1, arg
.name
))
5211 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5212 file.Write(" next_cmd, sizeof(cmd) +\n")
5213 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5214 file.Write(" // TODO(gman): Check that data was inserted;\n")
5219 class PUTXnHandler(TypeHandler
):
5220 """Handler for glUniform?f functions."""
5222 TypeHandler
.__init
__(self
)
5224 def WriteHandlerImplementation(self
, func
, file):
5225 """Overrriden from TypeHandler."""
5226 code
= """ %(type)s temp[%(count)s] = { %(values)s};
5227 Do%(name)sv(%(location)s, 1, &temp[0]);
5230 args
= func
.GetOriginalArgs()
5231 count
= int(func
.GetInfo('count'))
5232 num_args
= len(args
)
5233 for ii
in range(count
):
5234 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
5238 'count': func
.GetInfo('count'),
5239 'type': func
.GetInfo('data_type'),
5240 'location': args
[0].name
,
5241 'args': func
.MakeOriginalArgString(""),
5245 def WriteServiceUnitTest(self
, func
, file):
5246 """Overrriden from TypeHandler."""
5248 TEST_F(%(test_name)s, %(name)sValidArgs) {
5249 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
5250 SpecializedSetup<cmds::%(name)s, 0>(true);
5253 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5254 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5257 args
= func
.GetOriginalArgs()
5258 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
, 0, 0)
5259 self
.WriteValidUnitTest(func
, file, valid_test
, {
5261 'count': func
.GetInfo('count'),
5262 'local_args': local_args
,
5266 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5267 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
5268 SpecializedSetup<cmds::%(name)s, 0>(false);
5271 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5274 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5275 'name': func
.GetInfo('name'),
5276 'count': func
.GetInfo('count'),
5280 class GLcharHandler(CustomHandler
):
5281 """Handler for functions that pass a single string ."""
5284 CustomHandler
.__init
__(self
)
5286 def WriteImmediateCmdComputeSize(self
, func
, file):
5287 """Overrriden from TypeHandler."""
5288 file.Write(" static uint32 ComputeSize(uint32 data_size) {\n")
5289 file.Write(" return static_cast<uint32>(\n")
5290 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
5293 def WriteImmediateCmdSetHeader(self
, func
, file):
5294 """Overrriden from TypeHandler."""
5296 void SetHeader(uint32 data_size) {
5297 header.SetCmdBySize<ValueType>(data_size);
5302 def WriteImmediateCmdInit(self
, func
, file):
5303 """Overrriden from TypeHandler."""
5304 last_arg
= func
.GetLastOriginalArg()
5305 args
= func
.GetCmdArgs()
5308 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
5310 void Init(%(typed_args)s, uint32 _data_size) {
5311 SetHeader(_data_size);
5313 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
5318 "typed_args": func
.MakeTypedOriginalArgString("_"),
5319 "set_code": "\n".join(set_code
),
5320 "last_arg": last_arg
.name
5323 def WriteImmediateCmdSet(self
, func
, file):
5324 """Overrriden from TypeHandler."""
5325 last_arg
= func
.GetLastOriginalArg()
5326 file.Write(" void* Set(void* cmd%s, uint32 _data_size) {\n" %
5327 func
.MakeTypedOriginalArgString("_", True))
5328 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
5329 func
.MakeOriginalArgString("_"))
5330 file.Write(" return NextImmediateCmdAddress<ValueType>("
5331 "cmd, _data_size);\n")
5335 def WriteImmediateCmdHelper(self
, func
, file):
5336 """Overrriden from TypeHandler."""
5337 code
= """ void %(name)s(%(typed_args)s) {
5338 const uint32 data_size = strlen(name);
5339 gles2::cmds::%(name)s* c =
5340 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
5342 c->Init(%(args)s, data_size);
5349 "typed_args": func
.MakeTypedOriginalArgString(""),
5350 "args": func
.MakeOriginalArgString(""),
5354 def WriteImmediateFormatTest(self
, func
, file):
5355 """Overrriden from TypeHandler."""
5358 all_but_last_arg
= func
.GetCmdArgs()[:-1]
5359 for value
, arg
in enumerate(all_but_last_arg
):
5360 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
5361 for value
, arg
in enumerate(all_but_last_arg
):
5362 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
5363 (arg
.type, value
+ 11, arg
.name
))
5365 TEST_F(GLES2FormatTest, %(func_name)s) {
5366 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
5367 static const char* const test_str = \"test string\";
5368 void* next_cmd = cmd.Set(
5373 EXPECT_EQ(static_cast<uint32>(cmds::%(func_name)s::kCmdId),
5374 cmd.header.command);
5375 EXPECT_EQ(sizeof(cmd) +
5376 RoundSizeToMultipleOfEntries(strlen(test_str)),
5377 cmd.header.size * 4u);
5378 EXPECT_EQ(static_cast<char*>(next_cmd),
5379 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
5380 RoundSizeToMultipleOfEntries(strlen(test_str)));
5382 EXPECT_EQ(static_cast<uint32>(strlen(test_str)), cmd.data_size);
5383 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
5386 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
5387 sizeof(cmd) + strlen(test_str));
5392 'func_name': func
.name
,
5393 'init_code': "\n".join(init_code
),
5394 'check_code': "\n".join(check_code
),
5398 class GLcharNHandler(CustomHandler
):
5399 """Handler for functions that pass a single string with an optional len."""
5402 CustomHandler
.__init
__(self
)
5404 def InitFunction(self
, func
):
5405 """Overrriden from TypeHandler."""
5407 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5409 def AddImmediateFunction(self
, generator
, func
):
5410 """Overrriden from TypeHandler."""
5413 def AddBucketFunction(self
, generator
, func
):
5414 """Overrriden from TypeHandler."""
5417 def WriteServiceImplementation(self
, func
, file):
5418 """Overrriden from TypeHandler."""
5419 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
5420 uint32 immediate_data_size, const gles2::cmds::%(name)s& c) {
5421 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
5422 Bucket* bucket = GetBucket(bucket_id);
5423 if (!bucket || bucket->size() == 0) {
5424 return error::kInvalidArguments;
5427 if (!bucket->GetAsString(&str)) {
5428 return error::kInvalidArguments;
5430 %(gl_func_name)s(0, str.c_str());
5431 return error::kNoError;
5436 'gl_func_name': func
.GetGLFunctionName(),
5437 'bucket_id': func
.cmd_args
[0].name
,
5441 class IsHandler(TypeHandler
):
5442 """Handler for glIs____ type and glGetError functions."""
5445 TypeHandler
.__init
__(self
)
5447 def InitFunction(self
, func
):
5448 """Overrriden from TypeHandler."""
5449 func
.AddCmdArg(Argument("result_shm_id", 'uint32'))
5450 func
.AddCmdArg(Argument("result_shm_offset", 'uint32'))
5451 if func
.GetInfo('result') == None:
5452 func
.AddInfo('result', ['uint32'])
5454 def WriteServiceUnitTest(self
, func
, file):
5455 """Overrriden from TypeHandler."""
5457 TEST_F(%(test_name)s, %(name)sValidArgs) {
5458 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5459 SpecializedSetup<cmds::%(name)s, 0>(true);
5461 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5462 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5463 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5467 if len(func
.GetOriginalArgs()):
5469 self
.WriteValidUnitTest(func
, file, valid_test
, {
5474 TEST_F(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5475 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5476 SpecializedSetup<cmds::%(name)s, 0>(false);
5478 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5479 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5482 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5487 TEST_F(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
5488 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5489 SpecializedSetup<cmds::%(name)s, 0>(false);
5491 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
5492 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5493 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
5494 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5497 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5501 def WriteServiceImplementation(self
, func
, file):
5502 """Overrriden from TypeHandler."""
5504 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
5506 " uint32 immediate_data_size, const gles2::cmds::%s& c) {\n" %
5508 args
= func
.GetOriginalArgs()
5510 arg
.WriteGetCode(file)
5512 code
= """ typedef cmds::%(func_name)s::Result Result;
5513 Result* result_dst = GetSharedMemoryAs<Result*>(
5514 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
5516 return error::kOutOfBounds;
5519 file.Write(code
% {'func_name': func
.name
})
5520 func
.WriteHandlerValidation(file)
5521 file.Write(" *result_dst = %s(%s);\n" %
5522 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5523 file.Write(" return error::kNoError;\n")
5527 def WriteGLES2Implementation(self
, func
, file):
5528 """Overrriden from TypeHandler."""
5529 impl_func
= func
.GetInfo('impl_func')
5530 if impl_func
== None or impl_func
== True:
5531 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
5532 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5533 (func
.return_type
, func
.original_name
,
5534 func
.MakeTypedOriginalArgString("")))
5535 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5536 self
.WriteTraceEvent(func
, file)
5537 func
.WriteDestinationInitalizationValidation(file)
5538 self
.WriteClientGLCallLog(func
, file)
5539 file.Write(" typedef cmds::%s::Result Result;\n" % func
.name
)
5540 file.Write(" Result* result = GetResultAs<Result*>();\n")
5541 file.Write(" if (!result) {\n")
5542 file.Write(" return %s;\n" % error_value
)
5544 file.Write(" *result = 0;\n")
5545 arg_string
= func
.MakeOriginalArgString("")
5547 if len(arg_string
) > 0:
5550 " helper_->%s(%s%sGetResultShmId(), GetResultShmOffset());\n" %
5551 (func
.name
, arg_string
, comma
))
5552 file.Write(" WaitForCmd();\n")
5553 file.Write(" %s result_value = *result;\n" % func
.return_type
)
5554 file.Write(' GPU_CLIENT_LOG("returned " << result_value);\n')
5555 file.Write(" CheckGLError();\n")
5556 file.Write(" return result_value;\n")
5560 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5561 """Overrriden from TypeHandler."""
5562 client_test
= func
.GetInfo('client_test')
5563 if client_test
== None or client_test
== True:
5565 TEST_F(GLES2ImplementationTest, %(name)s) {
5571 ExpectedMemoryInfo result1 =
5572 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
5573 expected.cmd.Init(1, result1.id, result1.offset);
5575 EXPECT_CALL(*command_buffer(), OnFlush())
5576 .WillOnce(SetMemory(result1.ptr, uint32(1)))
5577 .RetiresOnSaturation();
5579 GLboolean result = gl_->%(name)s(1);
5580 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5581 EXPECT_TRUE(result);
5589 class STRnHandler(TypeHandler
):
5590 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
5591 GetTranslatedShaderSourceANGLE."""
5594 TypeHandler
.__init
__(self
)
5596 def InitFunction(self
, func
):
5597 """Overrriden from TypeHandler."""
5598 # remove all but the first cmd args.
5599 cmd_args
= func
.GetCmdArgs()
5601 func
.AddCmdArg(cmd_args
[0])
5602 # add on a bucket id.
5603 func
.AddCmdArg(Argument('bucket_id', 'uint32'))
5605 def WriteGLES2Implementation(self
, func
, file):
5606 """Overrriden from TypeHandler."""
5607 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
5608 GPU_CLIENT_SINGLE_THREAD_CHECK();
5610 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
5611 << "] gl%(func_name)s" << "("
5614 << static_cast<void*>(%(arg2)s) << ", "
5615 << static_cast<void*>(%(arg3)s) << ")");
5616 helper_->SetBucketSize(kResultBucketId, 0);
5617 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
5619 GLsizei max_size = 0;
5620 if (GetBucketAsString(kResultBucketId, &str)) {
5623 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
5624 memcpy(%(dest_name)s, str.c_str(), max_size);
5625 %(dest_name)s[max_size] = '\\0';
5626 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
5629 if (%(length_name)s != NULL) {
5630 *%(length_name)s = max_size;
5635 args
= func
.GetOriginalArgs()
5637 'return_type': func
.return_type
,
5638 'func_name': func
.original_name
,
5639 'args': func
.MakeTypedOriginalArgString(""),
5640 'id_name': args
[0].name
,
5641 'bufsize_name': args
[1].name
,
5642 'length_name': args
[2].name
,
5643 'dest_name': args
[3].name
,
5644 'arg0': args
[0].name
,
5645 'arg1': args
[1].name
,
5646 'arg2': args
[2].name
,
5647 'arg3': args
[3].name
,
5649 file.Write(code_1
% str_args
)
5650 func
.WriteDestinationInitalizationValidation(file)
5651 file.Write(code_2
% str_args
)
5653 def WriteServiceUnitTest(self
, func
, file):
5654 """Overrriden from TypeHandler."""
5656 TEST_F(%(test_name)s, %(name)sValidArgs) {
5657 const char* kInfo = "hello";
5658 const uint32 kBucketId = 123;
5659 SpecializedSetup<cmds::%(name)s, 0>(true);
5661 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5662 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
5663 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
5666 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5667 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
5668 ASSERT_TRUE(bucket != NULL);
5669 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
5670 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
5672 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5675 args
= func
.GetOriginalArgs()
5676 id_name
= args
[0].GetValidGLArg(func
, 0, 0)
5677 get_len_func
= func
.GetInfo('get_len_func')
5678 get_len_enum
= func
.GetInfo('get_len_enum')
5681 'get_len_func': get_len_func
,
5682 'get_len_enum': get_len_enum
,
5683 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
5684 args
[0].GetValidGLArg(func
, 0, 0),
5685 'args': '%s, kBucketId' % args
[0].GetValidArg(func
, 0, 0),
5686 'expect_len_code': '',
5688 if get_len_func
and get_len_func
[0:2] == 'gl':
5689 sub
['expect_len_code'] = (
5690 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
5691 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
5692 get_len_func
[2:], id_name
, get_len_enum
)
5693 self
.WriteValidUnitTest(func
, file, valid_test
, sub
)
5696 TEST_F(%(test_name)s, %(name)sInvalidArgs) {
5697 const uint32 kBucketId = 123;
5698 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
5701 cmd.Init(kInvalidClientId, kBucketId);
5702 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5703 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5706 self
.WriteValidUnitTest(func
, file, invalid_test
)
5708 def WriteServiceImplementation(self
, func
, file):
5709 """Overrriden from TypeHandler."""
5713 class FunctionInfo(object):
5714 """Holds info about a function."""
5716 def __init__(self
, info
, type_handler
):
5718 setattr(self
, key
, info
[key
])
5719 self
.type_handler
= type_handler
5720 if not 'type' in info
:
5724 class Argument(object):
5725 """A class that represents a function argument."""
5730 'GLintptr': 'int32',
5732 'GLsizeiptr': 'int32',
5734 'GLclampf': 'float',
5736 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
5738 def __init__(self
, name
, type):
5740 self
.optional
= type.endswith("Optional*")
5742 type = type[:-9] + "*"
5745 if type in self
.cmd_type_map_
:
5746 self
.cmd_type
= self
.cmd_type_map_
[type]
5748 self
.cmd_type
= 'uint32'
5750 def IsPointer(self
):
5751 """Returns true if argument is a pointer."""
5754 def AddCmdArgs(self
, args
):
5755 """Adds command arguments for this argument to the given list."""
5756 return args
.append(self
)
5758 def AddInitArgs(self
, args
):
5759 """Adds init arguments for this argument to the given list."""
5760 return args
.append(self
)
5762 def GetValidArg(self
, func
, offset
, index
):
5763 """Gets a valid value for this argument."""
5764 valid_arg
= func
.GetValidArg(offset
)
5765 if valid_arg
!= None:
5767 return str(offset
+ 1)
5769 def GetValidClientSideArg(self
, func
, offset
, index
):
5770 """Gets a valid value for this argument."""
5771 return str(offset
+ 1)
5773 def GetValidClientSideCmdArg(self
, func
, offset
, index
):
5774 """Gets a valid value for this argument."""
5775 return str(offset
+ 1)
5777 def GetValidGLArg(self
, func
, offset
, index
):
5778 """Gets a valid GL value for this argument."""
5779 valid_arg
= func
.GetValidArg(offset
)
5780 if valid_arg
!= None:
5782 return str(offset
+ 1)
5784 def GetNumInvalidValues(self
, func
):
5785 """returns the number of invalid values to be tested."""
5788 def GetInvalidArg(self
, offset
, index
):
5789 """returns an invalid value and expected parse result by index."""
5790 return ("---ERROR0---", "---ERROR2---", None)
5792 def GetLogArg(self
):
5793 """Get argument appropriate for LOG macro."""
5794 if self
.type == 'GLboolean':
5795 return 'GLES2Util::GetStringBool(%s)' % self
.name
5796 if self
.type == 'GLenum':
5797 return 'GLES2Util::GetStringEnum(%s)' % self
.name
5800 def WriteGetCode(self
, file):
5801 """Writes the code to get an argument from a command structure."""
5802 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
5803 (self
.type, self
.name
, self
.type, self
.name
))
5805 def WriteValidationCode(self
, file, func
):
5806 """Writes the validation code for an argument."""
5809 def WriteClientSideValidationCode(self
, file, func
):
5810 """Writes the validation code for an argument."""
5813 def WriteDestinationInitalizationValidation(self
, file, func
):
5814 """Writes the client side destintion initialization validation."""
5817 def WriteDestinationInitalizationValidatationIfNeeded(self
, file, func
):
5818 """Writes the client side destintion initialization validation if needed."""
5819 parts
= self
.type.split(" ")
5822 if parts
[0] in self
.need_validation_
:
5824 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
5825 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
5828 def WriteGetAddress(self
, file):
5829 """Writes the code to get the address this argument refers to."""
5832 def GetImmediateVersion(self
):
5833 """Gets the immediate version of this argument."""
5836 def GetBucketVersion(self
):
5837 """Gets the bucket version of this argument."""
5841 class BoolArgument(Argument
):
5842 """class for GLboolean"""
5844 def __init__(self
, name
, type):
5845 Argument
.__init
__(self
, name
, 'GLboolean')
5847 def GetValidArg(self
, func
, offset
, index
):
5848 """Gets a valid value for this argument."""
5851 def GetValidClientSideArg(self
, func
, offset
, index
):
5852 """Gets a valid value for this argument."""
5855 def GetValidClientSideCmdArg(self
, func
, offset
, index
):
5856 """Gets a valid value for this argument."""
5859 def GetValidGLArg(self
, func
, offset
, index
):
5860 """Gets a valid GL value for this argument."""
5864 class UniformLocationArgument(Argument
):
5865 """class for uniform locations."""
5867 def __init__(self
, name
):
5868 Argument
.__init
__(self
, name
, "GLint")
5870 def WriteGetCode(self
, file):
5871 """Writes the code to get an argument from a command structure."""
5872 code
= """ %s %s = static_cast<%s>(c.%s);
5874 file.Write(code
% (self
.type, self
.name
, self
.type, self
.name
))
5876 def GetValidArg(self
, func
, offset
, index
):
5877 """Gets a valid value for this argument."""
5878 return "%d" % (offset
+ 1)
5881 class DataSizeArgument(Argument
):
5882 """class for data_size which Bucket commands do not need."""
5884 def __init__(self
, name
):
5885 Argument
.__init
__(self
, name
, "uint32")
5887 def GetBucketVersion(self
):
5891 class SizeArgument(Argument
):
5892 """class for GLsizei and GLsizeiptr."""
5894 def __init__(self
, name
, type):
5895 Argument
.__init
__(self
, name
, type)
5897 def GetNumInvalidValues(self
, func
):
5898 """overridden from Argument."""
5899 if func
.is_immediate
:
5903 def GetInvalidArg(self
, offset
, index
):
5904 """overridden from Argument."""
5905 return ("-1", "kNoError", "GL_INVALID_VALUE")
5907 def WriteValidationCode(self
, file, func
):
5908 """overridden from Argument."""
5909 file.Write(" if (%s < 0) {\n" % self
.name
)
5911 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5912 (func
.original_name
, self
.name
))
5913 file.Write(" return error::kNoError;\n")
5916 def WriteClientSideValidationCode(self
, file, func
):
5917 """overridden from Argument."""
5918 file.Write(" if (%s < 0) {\n" % self
.name
)
5920 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
5921 (func
.original_name
, self
.name
))
5922 file.Write(" return;\n")
5926 class SizeNotNegativeArgument(SizeArgument
):
5927 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
5929 def __init__(self
, name
, type, gl_type
):
5930 SizeArgument
.__init
__(self
, name
, gl_type
)
5932 def GetInvalidArg(self
, offset
, index
):
5933 """overridden from SizeArgument."""
5934 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
5936 def WriteValidationCode(self
, file, func
):
5937 """overridden from SizeArgument."""
5941 class EnumBaseArgument(Argument
):
5942 """Base class for EnumArgument, IntArgument and ValidatedBoolArgument"""
5944 def __init__(self
, name
, gl_type
, type, gl_error
):
5945 Argument
.__init
__(self
, name
, gl_type
)
5947 self
.local_type
= type
5948 self
.gl_error
= gl_error
5949 name
= type[len(gl_type
):]
5950 self
.type_name
= name
5951 self
.enum_info
= _ENUM_LISTS
[name
]
5953 def WriteValidationCode(self
, file, func
):
5954 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
5955 (ToUnderscore(self
.type_name
), self
.name
))
5956 if self
.gl_error
== "GL_INVALID_ENUM":
5958 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
5959 (func
.original_name
, self
.name
, self
.name
))
5962 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
5963 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
5964 file.Write(" return error::kNoError;\n")
5967 def GetValidArg(self
, func
, offset
, index
):
5968 valid_arg
= func
.GetValidArg(offset
)
5969 if valid_arg
!= None:
5971 if 'valid' in self
.enum_info
:
5972 valid
= self
.enum_info
['valid']
5973 num_valid
= len(valid
)
5974 if index
>= num_valid
:
5975 index
= num_valid
- 1
5977 return str(offset
+ 1)
5979 def GetValidClientSideArg(self
, func
, offset
, index
):
5980 """Gets a valid value for this argument."""
5981 return self
.GetValidArg(func
, offset
, index
)
5983 def GetValidClientSideCmdArg(self
, func
, offset
, index
):
5984 """Gets a valid value for this argument."""
5985 return self
.GetValidArg(func
, offset
, index
)
5987 def GetValidGLArg(self
, func
, offset
, index
):
5988 """Gets a valid value for this argument."""
5989 return self
.GetValidArg(func
, offset
, index
)
5991 def GetNumInvalidValues(self
, func
):
5992 """returns the number of invalid values to be tested."""
5993 if 'invalid' in self
.enum_info
:
5994 invalid
= self
.enum_info
['invalid']
5998 def GetInvalidArg(self
, offset
, index
):
5999 """returns an invalid value by index."""
6000 if 'invalid' in self
.enum_info
:
6001 invalid
= self
.enum_info
['invalid']
6002 num_invalid
= len(invalid
)
6003 if index
>= num_invalid
:
6004 index
= num_invalid
- 1
6005 return (invalid
[index
], "kNoError", self
.gl_error
)
6006 return ("---ERROR1---", "kNoError", self
.gl_error
)
6009 class EnumArgument(EnumBaseArgument
):
6010 """A class that represents a GLenum argument"""
6012 def __init__(self
, name
, type):
6013 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
6015 def GetLogArg(self
):
6016 """Overridden from Argument."""
6017 return ("GLES2Util::GetString%s(%s)" %
6018 (self
.type_name
, self
.name
))
6021 class IntArgument(EnumBaseArgument
):
6022 """A class for a GLint argument that can only except specific values.
6024 For example glTexImage2D takes a GLint for its internalformat
6025 argument instead of a GLenum.
6028 def __init__(self
, name
, type):
6029 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
6032 class ValidatedBoolArgument(EnumBaseArgument
):
6033 """A class for a GLboolean argument that can only except specific values.
6035 For example glUniformMatrix takes a GLboolean for it's transpose but it
6039 def __init__(self
, name
, type):
6040 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
6042 def GetLogArg(self
):
6043 """Overridden from Argument."""
6044 return 'GLES2Util::GetStringBool(%s)' % self
.name
6047 class ImmediatePointerArgument(Argument
):
6048 """A class that represents an immediate argument to a function.
6050 An immediate argument is one where the data follows the command.
6053 def __init__(self
, name
, type):
6054 Argument
.__init
__(self
, name
, type)
6056 def AddCmdArgs(self
, args
):
6057 """Overridden from Argument."""
6060 def WriteGetCode(self
, file):
6061 """Overridden from Argument."""
6063 " %s %s = GetImmediateDataAs<%s>(\n" %
6064 (self
.type, self
.name
, self
.type))
6065 file.Write(" c, data_size, immediate_data_size);\n")
6067 def WriteValidationCode(self
, file, func
):
6068 """Overridden from Argument."""
6069 file.Write(" if (%s == NULL) {\n" % self
.name
)
6070 file.Write(" return error::kOutOfBounds;\n")
6073 def GetImmediateVersion(self
):
6074 """Overridden from Argument."""
6077 def WriteDestinationInitalizationValidation(self
, file, func
):
6078 """Overridden from Argument."""
6079 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6081 def GetLogArg(self
):
6082 """Overridden from Argument."""
6083 return "static_cast<const void*>(%s)" % self
.name
6086 class BucketPointerArgument(Argument
):
6087 """A class that represents an bucket argument to a function."""
6089 def __init__(self
, name
, type):
6090 Argument
.__init
__(self
, name
, type)
6092 def AddCmdArgs(self
, args
):
6093 """Overridden from Argument."""
6096 def WriteGetCode(self
, file):
6097 """Overridden from Argument."""
6099 " %s %s = bucket->GetData(0, data_size);\n" %
6100 (self
.type, self
.name
))
6102 def WriteValidationCode(self
, file, func
):
6103 """Overridden from Argument."""
6106 def GetImmediateVersion(self
):
6107 """Overridden from Argument."""
6110 def WriteDestinationInitalizationValidation(self
, file, func
):
6111 """Overridden from Argument."""
6112 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6114 def GetLogArg(self
):
6115 """Overridden from Argument."""
6116 return "static_cast<const void*>(%s)" % self
.name
6119 class PointerArgument(Argument
):
6120 """A class that represents a pointer argument to a function."""
6122 def __init__(self
, name
, type):
6123 Argument
.__init
__(self
, name
, type)
6125 def IsPointer(self
):
6126 """Returns true if argument is a pointer."""
6129 def GetValidArg(self
, func
, offset
, index
):
6130 """Overridden from Argument."""
6131 return "shared_memory_id_, shared_memory_offset_"
6133 def GetValidGLArg(self
, func
, offset
, index
):
6134 """Overridden from Argument."""
6135 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
6137 def GetNumInvalidValues(self
, func
):
6138 """Overridden from Argument."""
6141 def GetInvalidArg(self
, offset
, index
):
6142 """Overridden from Argument."""
6144 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
6146 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
6147 "kOutOfBounds", None)
6149 def GetLogArg(self
):
6150 """Overridden from Argument."""
6151 return "static_cast<const void*>(%s)" % self
.name
6153 def AddCmdArgs(self
, args
):
6154 """Overridden from Argument."""
6155 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32'))
6156 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32'))
6158 def WriteGetCode(self
, file):
6159 """Overridden from Argument."""
6161 " %s %s = GetSharedMemoryAs<%s>(\n" %
6162 (self
.type, self
.name
, self
.type))
6164 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
6165 (self
.name
, self
.name
))
6167 def WriteGetAddress(self
, file):
6168 """Overridden from Argument."""
6170 " %s %s = GetSharedMemoryAs<%s>(\n" %
6171 (self
.type, self
.name
, self
.type))
6173 " %s_shm_id, %s_shm_offset, %s_size);\n" %
6174 (self
.name
, self
.name
, self
.name
))
6176 def WriteValidationCode(self
, file, func
):
6177 """Overridden from Argument."""
6178 file.Write(" if (%s == NULL) {\n" % self
.name
)
6179 file.Write(" return error::kOutOfBounds;\n")
6182 def GetImmediateVersion(self
):
6183 """Overridden from Argument."""
6184 return ImmediatePointerArgument(self
.name
, self
.type)
6186 def GetBucketVersion(self
):
6187 """Overridden from Argument."""
6188 if self
.type == "const char*":
6189 return InputStringBucketArgument(self
.name
, self
.type)
6190 return BucketPointerArgument(self
.name
, self
.type)
6192 def WriteDestinationInitalizationValidation(self
, file, func
):
6193 """Overridden from Argument."""
6194 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6197 class InputStringBucketArgument(Argument
):
6198 """An string input argument where the string is passed in a bucket."""
6200 def __init__(self
, name
, type):
6201 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32")
6203 def WriteGetCode(self
, file):
6204 """Overridden from Argument."""
6206 Bucket* %(name)s_bucket = GetBucket(c.%(name)s);
6207 if (!%(name)s_bucket) {
6208 return error::kInvalidArguments;
6210 std::string %(name)s_str;
6211 if (!%(name)s_bucket->GetAsString(&%(name)s_str)) {
6212 return error::kInvalidArguments;
6214 const char* %(name)s = %(name)s_str.c_str();
6220 def GetValidArg(self
, func
, offset
, index
):
6221 return "kNameBucketId"
6223 def GetValidGLArg(self
, func
, offset
, index
):
6227 class NonImmediatePointerArgument(PointerArgument
):
6228 """A pointer argument that stays a pointer even in an immediate cmd."""
6230 def __init__(self
, name
, type):
6231 PointerArgument
.__init
__(self
, name
, type)
6233 def IsPointer(self
):
6234 """Returns true if argument is a pointer."""
6237 def GetImmediateVersion(self
):
6238 """Overridden from Argument."""
6242 class ResourceIdArgument(Argument
):
6243 """A class that represents a resource id argument to a function."""
6245 def __init__(self
, name
, type):
6246 match
= re
.match("(GLid\w+)", type)
6247 self
.resource_type
= match
.group(1)[4:]
6248 type = type.replace(match
.group(1), "GLuint")
6249 Argument
.__init
__(self
, name
, type)
6251 def WriteGetCode(self
, file):
6252 """Overridden from Argument."""
6253 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
6255 def GetValidArg(self
, func
, offset
, index
):
6256 return "client_%s_id_" % self
.resource_type
.lower()
6258 def GetValidGLArg(self
, func
, offset
, index
):
6259 return "kService%sId" % self
.resource_type
6262 class ResourceIdBindArgument(Argument
):
6263 """Represents a resource id argument to a bind function."""
6265 def __init__(self
, name
, type):
6266 match
= re
.match("(GLidBind\w+)", type)
6267 self
.resource_type
= match
.group(1)[8:]
6268 type = type.replace(match
.group(1), "GLuint")
6269 Argument
.__init
__(self
, name
, type)
6271 def WriteGetCode(self
, file):
6272 """Overridden from Argument."""
6273 code
= """ %(type)s %(name)s = c.%(name)s;
6275 file.Write(code
% {'type': self
.type, 'name': self
.name
})
6277 def GetValidArg(self
, func
, offset
, index
):
6278 return "client_%s_id_" % self
.resource_type
.lower()
6280 def GetValidGLArg(self
, func
, offset
, index
):
6281 return "kService%sId" % self
.resource_type
6284 class ResourceIdZeroArgument(Argument
):
6285 """Represents a resource id argument to a function that can be zero."""
6287 def __init__(self
, name
, type):
6288 match
= re
.match("(GLidZero\w+)", type)
6289 self
.resource_type
= match
.group(1)[8:]
6290 type = type.replace(match
.group(1), "GLuint")
6291 Argument
.__init
__(self
, name
, type)
6293 def WriteGetCode(self
, file):
6294 """Overridden from Argument."""
6295 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.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
6303 def GetNumInvalidValues(self
, func
):
6304 """returns the number of invalid values to be tested."""
6307 def GetInvalidArg(self
, offset
, index
):
6308 """returns an invalid value by index."""
6309 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
6312 class Function(object):
6313 """A class that represents a function."""
6315 def __init__(self
, original_name
, name
, info
, return_type
, original_args
,
6316 args_for_cmds
, cmd_args
, init_args
, num_pointer_args
):
6318 self
.original_name
= original_name
6320 self
.type_handler
= info
.type_handler
6321 self
.return_type
= return_type
6322 self
.original_args
= original_args
6323 self
.num_pointer_args
= num_pointer_args
6324 self
.can_auto_generate
= num_pointer_args
== 0 and return_type
== "void"
6325 self
.cmd_args
= cmd_args
6326 self
.init_args
= init_args
6328 self
.args_for_cmds
= args_for_cmds
6329 self
.is_immediate
= False
6331 def IsType(self
, type_name
):
6332 """Returns true if function is a certain type."""
6333 return self
.info
.type == type_name
6335 def InitFunction(self
):
6336 """Calls the init function for the type handler."""
6337 self
.type_handler
.InitFunction(self
)
6339 def GetInfo(self
, name
):
6340 """Returns a value from the function info for this function."""
6341 if hasattr(self
.info
, name
):
6342 return getattr(self
.info
, name
)
6345 def GetValidArg(self
, index
):
6346 """Gets a valid arg from the function info if one exists."""
6347 valid_args
= self
.GetInfo('valid_args')
6348 if valid_args
and str(index
) in valid_args
:
6349 return valid_args
[str(index
)]
6352 def AddInfo(self
, name
, value
):
6354 setattr(self
.info
, name
, value
)
6356 def IsCoreGLFunction(self
):
6357 return (not self
.GetInfo('extension') and
6358 not self
.GetInfo('pepper_interface'))
6360 def InPepperInterface(self
, interface
):
6361 ext
= self
.GetInfo('pepper_interface')
6362 if not interface
.GetName():
6363 return self
.IsCoreGLFunction()
6364 return ext
== interface
.GetName()
6366 def InAnyPepperExtension(self
):
6367 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
6369 def GetGLFunctionName(self
):
6370 """Gets the function to call to execute GL for this command."""
6371 if self
.GetInfo('decoder_func'):
6372 return self
.GetInfo('decoder_func')
6373 return "gl%s" % self
.original_name
6375 def GetGLTestFunctionName(self
):
6376 gl_func_name
= self
.GetInfo('gl_test_func')
6377 if gl_func_name
== None:
6378 gl_func_name
= self
.GetGLFunctionName()
6379 if gl_func_name
.startswith("gl"):
6380 gl_func_name
= gl_func_name
[2:]
6382 gl_func_name
= self
.original_name
6385 def AddCmdArg(self
, arg
):
6386 """Adds a cmd argument to this function."""
6387 self
.cmd_args
.append(arg
)
6389 def GetCmdArgs(self
):
6390 """Gets the command args for this function."""
6391 return self
.cmd_args
6393 def ClearCmdArgs(self
):
6394 """Clears the command args for this function."""
6397 def GetInitArgs(self
):
6398 """Gets the init args for this function."""
6399 return self
.init_args
6401 def GetOriginalArgs(self
):
6402 """Gets the original arguments to this function."""
6403 return self
.original_args
6405 def GetLastOriginalArg(self
):
6406 """Gets the last original argument to this function."""
6407 return self
.original_args
[len(self
.original_args
) - 1]
6409 def __MaybePrependComma(self
, arg_string
, add_comma
):
6410 """Adds a comma if arg_string is not empty and add_comma is true."""
6412 if add_comma
and len(arg_string
):
6414 return "%s%s" % (comma
, arg_string
)
6416 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
6417 """Gets a list of arguments as they are in GL."""
6418 args
= self
.GetOriginalArgs()
6419 arg_string
= ", ".join(
6420 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6421 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6423 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
6424 """Gets the list of arguments as they are in GL."""
6425 args
= self
.GetOriginalArgs()
6426 arg_string
= separator
.join(
6427 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6428 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6430 def MakeTypedPepperArgString(self
, prefix
):
6431 """Gets a list of arguments as they need to be for Pepper."""
6432 if self
.GetInfo("pepper_args"):
6433 return self
.GetInfo("pepper_args")
6435 return self
.MakeTypedOriginalArgString(prefix
, False)
6437 def GetPepperName(self
):
6438 if self
.GetInfo("pepper_name"):
6439 return self
.GetInfo("pepper_name")
6442 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
6443 """Gets a typed list of arguments as they need to be for command buffers."""
6444 args
= self
.GetCmdArgs()
6445 arg_string
= ", ".join(
6446 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6447 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6449 def MakeCmdArgString(self
, prefix
, add_comma
= False):
6450 """Gets the list of arguments as they need to be for command buffers."""
6451 args
= self
.GetCmdArgs()
6452 arg_string
= ", ".join(
6453 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6454 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6456 def MakeTypedInitString(self
, prefix
, add_comma
= False):
6457 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
6458 args
= self
.GetInitArgs()
6459 arg_string
= ", ".join(
6460 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6461 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6463 def MakeInitString(self
, prefix
, add_comma
= False):
6464 """Gets the list of arguments as they need to be for cmd Init/Set."""
6465 args
= self
.GetInitArgs()
6466 arg_string
= ", ".join(
6467 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6468 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6470 def MakeLogArgString(self
):
6471 """Makes a string of the arguments for the LOG macros"""
6472 args
= self
.GetOriginalArgs()
6473 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
6475 def WriteCommandDescription(self
, file):
6476 """Writes a description of the command."""
6477 file.Write("//! Command that corresponds to gl%s.\n" % self
.original_name
)
6479 def WriteHandlerValidation(self
, file):
6480 """Writes validation code for the function."""
6481 for arg
in self
.GetOriginalArgs():
6482 arg
.WriteValidationCode(file, self
)
6483 self
.WriteValidationCode(file)
6485 def WriteHandlerImplementation(self
, file):
6486 """Writes the handler implementation for this command."""
6487 self
.type_handler
.WriteHandlerImplementation(self
, file)
6489 def WriteValidationCode(self
, file):
6490 """Writes the validation code for a command."""
6493 def WriteCmdFlag(self
, file):
6494 """Writes the cmd cmd_flags constant."""
6496 trace_level
= 3 # By default trace only at the highest level
6497 if hasattr(self
.info
, 'trace_level'):
6498 if (self
.info
.trace_level
< 0) or (self
.info
.trace_level
> 3):
6499 raise KeyError("Unhandled trace_level: %d" % self
.info
.trace_level
)
6500 trace_level
= self
.info
.trace_level
6502 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
6505 cmd_flags
= ' | '.join(flags
)
6509 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
6512 def WriteCmdArgFlag(self
, file):
6513 """Writes the cmd kArgFlags constant."""
6514 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
6516 def WriteCmdComputeSize(self
, file):
6517 """Writes the ComputeSize function for the command."""
6518 file.Write(" static uint32 ComputeSize() {\n")
6520 " return static_cast<uint32>(sizeof(ValueType)); // NOLINT\n")
6524 def WriteCmdSetHeader(self
, file):
6525 """Writes the cmd's SetHeader function."""
6526 file.Write(" void SetHeader() {\n")
6527 file.Write(" header.SetCmd<ValueType>();\n")
6531 def WriteCmdInit(self
, file):
6532 """Writes the cmd's Init function."""
6533 file.Write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
6534 file.Write(" SetHeader();\n")
6535 args
= self
.GetCmdArgs()
6537 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6541 def WriteCmdSet(self
, file):
6542 """Writes the cmd's Set function."""
6543 copy_args
= self
.MakeCmdArgString("_", False)
6544 file.Write(" void* Set(void* cmd%s) {\n" %
6545 self
.MakeTypedCmdArgString("_", True))
6546 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
6547 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
6551 def WriteStruct(self
, file):
6552 self
.type_handler
.WriteStruct(self
, file)
6554 def WriteDocs(self
, file):
6555 self
.type_handler
.WriteDocs(self
, file)
6557 def WriteCmdHelper(self
, file):
6558 """Writes the cmd's helper."""
6559 self
.type_handler
.WriteCmdHelper(self
, file)
6561 def WriteServiceImplementation(self
, file):
6562 """Writes the service implementation for a command."""
6563 self
.type_handler
.WriteServiceImplementation(self
, file)
6565 def WriteServiceUnitTest(self
, file):
6566 """Writes the service implementation for a command."""
6567 self
.type_handler
.WriteServiceUnitTest(self
, file)
6569 def WriteGLES2CLibImplementation(self
, file):
6570 """Writes the GLES2 C Lib Implemention."""
6571 self
.type_handler
.WriteGLES2CLibImplementation(self
, file)
6573 def WriteGLES2InterfaceHeader(self
, file):
6574 """Writes the GLES2 Interface declaration."""
6575 self
.type_handler
.WriteGLES2InterfaceHeader(self
, file)
6577 def WriteGLES2InterfaceStub(self
, file):
6578 """Writes the GLES2 Interface Stub declaration."""
6579 self
.type_handler
.WriteGLES2InterfaceStub(self
, file)
6581 def WriteGLES2InterfaceStubImpl(self
, file):
6582 """Writes the GLES2 Interface Stub declaration."""
6583 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, file)
6585 def WriteGLES2ImplementationHeader(self
, file):
6586 """Writes the GLES2 Implemention declaration."""
6587 self
.type_handler
.WriteGLES2ImplementationHeader(self
, file)
6589 def WriteGLES2Implementation(self
, file):
6590 """Writes the GLES2 Implemention definition."""
6591 self
.type_handler
.WriteGLES2Implementation(self
, file)
6593 def WriteGLES2TraceImplementationHeader(self
, file):
6594 """Writes the GLES2 Trace Implemention declaration."""
6595 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, file)
6597 def WriteGLES2TraceImplementation(self
, file):
6598 """Writes the GLES2 Trace Implemention definition."""
6599 self
.type_handler
.WriteGLES2TraceImplementation(self
, file)
6601 def WriteGLES2Header(self
, file):
6602 """Writes the GLES2 Implemention unit test."""
6603 self
.type_handler
.WriteGLES2Header(self
, file)
6605 def WriteGLES2ImplementationUnitTest(self
, file):
6606 """Writes the GLES2 Implemention unit test."""
6607 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, file)
6609 def WriteDestinationInitalizationValidation(self
, file):
6610 """Writes the client side destintion initialization validation."""
6611 self
.type_handler
.WriteDestinationInitalizationValidation(self
, file)
6613 def WriteFormatTest(self
, file):
6614 """Writes the cmd's format test."""
6615 self
.type_handler
.WriteFormatTest(self
, file)
6618 class PepperInterface(object):
6619 """A class that represents a function."""
6621 def __init__(self
, info
):
6622 self
.name
= info
["name"]
6623 self
.dev
= info
["dev"]
6628 def GetInterfaceName(self
):
6632 upperint
= "_" + self
.name
.upper()
6635 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
6637 def GetInterfaceString(self
):
6641 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
6643 def GetStructName(self
):
6647 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
6650 class ImmediateFunction(Function
):
6651 """A class that represnets an immediate function command."""
6653 def __init__(self
, func
):
6655 for arg
in func
.GetOriginalArgs():
6656 new_arg
= arg
.GetImmediateVersion()
6658 new_args
.append(new_arg
)
6661 new_args_for_cmds
= []
6662 for arg
in func
.args_for_cmds
:
6663 new_arg
= arg
.GetImmediateVersion()
6665 new_args_for_cmds
.append(new_arg
)
6666 new_arg
.AddCmdArgs(cmd_args
)
6669 for arg
in new_args_for_cmds
:
6670 arg
.AddInitArgs(new_init_args
)
6675 "%sImmediate" % func
.name
,
6683 self
.is_immediate
= True
6685 def WriteCommandDescription(self
, file):
6686 """Overridden from Function"""
6687 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
6690 def WriteServiceImplementation(self
, file):
6691 """Overridden from Function"""
6692 self
.type_handler
.WriteImmediateServiceImplementation(self
, file)
6694 def WriteHandlerImplementation(self
, file):
6695 """Overridden from Function"""
6696 self
.type_handler
.WriteImmediateHandlerImplementation(self
, file)
6698 def WriteServiceUnitTest(self
, file):
6699 """Writes the service implementation for a command."""
6700 self
.type_handler
.WriteImmediateServiceUnitTest(self
, file)
6702 def WriteValidationCode(self
, file):
6703 """Overridden from Function"""
6704 self
.type_handler
.WriteImmediateValidationCode(self
, file)
6706 def WriteCmdArgFlag(self
, file):
6707 """Overridden from Function"""
6708 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
6710 def WriteCmdComputeSize(self
, file):
6711 """Overridden from Function"""
6712 self
.type_handler
.WriteImmediateCmdComputeSize(self
, file)
6714 def WriteCmdSetHeader(self
, file):
6715 """Overridden from Function"""
6716 self
.type_handler
.WriteImmediateCmdSetHeader(self
, file)
6718 def WriteCmdInit(self
, file):
6719 """Overridden from Function"""
6720 self
.type_handler
.WriteImmediateCmdInit(self
, file)
6722 def WriteCmdSet(self
, file):
6723 """Overridden from Function"""
6724 self
.type_handler
.WriteImmediateCmdSet(self
, file)
6726 def WriteCmdHelper(self
, file):
6727 """Overridden from Function"""
6728 self
.type_handler
.WriteImmediateCmdHelper(self
, file)
6730 def WriteFormatTest(self
, file):
6731 """Overridden from Function"""
6732 self
.type_handler
.WriteImmediateFormatTest(self
, file)
6735 class BucketFunction(Function
):
6736 """A class that represnets a bucket version of a function command."""
6738 def __init__(self
, func
):
6740 for arg
in func
.GetOriginalArgs():
6741 new_arg
= arg
.GetBucketVersion()
6743 new_args
.append(new_arg
)
6746 new_args_for_cmds
= []
6747 for arg
in func
.args_for_cmds
:
6748 new_arg
= arg
.GetBucketVersion()
6750 new_args_for_cmds
.append(new_arg
)
6751 new_arg
.AddCmdArgs(cmd_args
)
6754 for arg
in new_args_for_cmds
:
6755 arg
.AddInitArgs(new_init_args
)
6760 "%sBucket" % func
.name
,
6769 # def InitFunction(self):
6770 # """Overridden from Function"""
6773 def WriteCommandDescription(self
, file):
6774 """Overridden from Function"""
6775 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
6778 def WriteServiceImplementation(self
, file):
6779 """Overridden from Function"""
6780 self
.type_handler
.WriteBucketServiceImplementation(self
, file)
6782 def WriteHandlerImplementation(self
, file):
6783 """Overridden from Function"""
6784 self
.type_handler
.WriteBucketHandlerImplementation(self
, file)
6786 def WriteServiceUnitTest(self
, file):
6787 """Writes the service implementation for a command."""
6788 self
.type_handler
.WriteBucketServiceUnitTest(self
, file)
6791 def CreateArg(arg_string
):
6792 """Creates an Argument."""
6793 arg_parts
= arg_string
.split()
6794 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
6796 # Is this a pointer argument?
6797 elif arg_string
.find('*') >= 0:
6798 if arg_parts
[0] == 'NonImmediate':
6799 return NonImmediatePointerArgument(
6801 " ".join(arg_parts
[1:-1]))
6803 return PointerArgument(
6805 " ".join(arg_parts
[0:-1]))
6806 # Is this a resource argument? Must come after pointer check.
6807 elif arg_parts
[0].startswith('GLidBind'):
6808 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6809 elif arg_parts
[0].startswith('GLidZero'):
6810 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6811 elif arg_parts
[0].startswith('GLid'):
6812 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6813 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
6814 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6815 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
6816 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6817 elif arg_parts
[0].startswith('GLboolean'):
6818 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6819 elif arg_parts
[0].startswith('GLintUniformLocation'):
6820 return UniformLocationArgument(arg_parts
[-1])
6821 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
6822 not arg_parts
[0].startswith('GLintptr')):
6823 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6824 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
6825 arg_parts
[0].startswith('GLintptrNotNegative')):
6826 return SizeNotNegativeArgument(arg_parts
[-1],
6827 " ".join(arg_parts
[0:-1]),
6828 arg_parts
[0][0:-11])
6829 elif arg_parts
[0].startswith('GLsize'):
6830 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6832 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
6835 class GLGenerator(object):
6836 """A class to generate GL command buffers."""
6838 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
6840 def __init__(self
, verbose
):
6841 self
.original_functions
= []
6843 self
.verbose
= verbose
6845 self
._function
_info
= {}
6846 self
._empty
_type
_handler
= TypeHandler()
6847 self
._empty
_function
_info
= FunctionInfo({}, self
._empty
_type
_handler
)
6848 self
.pepper_interfaces
= []
6849 self
.interface_info
= {}
6851 self
._type
_handlers
= {
6852 'Bind': BindHandler(),
6853 'Create': CreateHandler(),
6854 'Custom': CustomHandler(),
6855 'Data': DataHandler(),
6856 'Delete': DeleteHandler(),
6857 'DELn': DELnHandler(),
6858 'GENn': GENnHandler(),
6859 'GETn': GETnHandler(),
6860 'GLchar': GLcharHandler(),
6861 'GLcharN': GLcharNHandler(),
6862 'HandWritten': HandWrittenHandler(),
6864 'Manual': ManualHandler(),
6865 'PUT': PUTHandler(),
6866 'PUTn': PUTnHandler(),
6867 'PUTXn': PUTXnHandler(),
6868 'StateSet': StateSetHandler(),
6869 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
6870 'StateSetFrontBack': StateSetFrontBackHandler(),
6871 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
6872 'StateSetNamedParameter': StateSetNamedParameter(),
6873 'STRn': STRnHandler(),
6874 'Todo': TodoHandler(),
6877 for func_name
in _FUNCTION_INFO
:
6878 info
= _FUNCTION_INFO
[func_name
]
6882 self
._function
_info
[func_name
] = FunctionInfo(info
,
6883 self
.GetTypeHandler(type))
6884 for interface
in _PEPPER_INTERFACES
:
6885 interface
= PepperInterface(interface
)
6886 self
.pepper_interfaces
.append(interface
)
6887 self
.interface_info
[interface
.GetName()] = interface
6889 def AddFunction(self
, func
):
6890 """Adds a function."""
6891 self
.functions
.append(func
)
6893 def GetTypeHandler(self
, name
):
6894 """Gets a type info for the given type."""
6896 if name
in self
._type
_handlers
:
6897 return self
._type
_handlers
[name
]
6899 raise KeyError("no such type handler: %s" % name
)
6900 return self
._empty
_type
_handler
6902 def GetFunctionInfo(self
, name
):
6903 """Gets a type info for the given function name."""
6904 if name
in self
._function
_info
:
6905 return self
._function
_info
[name
]
6906 return self
._empty
_function
_info
6909 """Prints something if verbose is true."""
6913 def Error(self
, msg
):
6914 """Prints an error."""
6915 print "Error: %s" % msg
6918 def WriteLicense(self
, file):
6919 """Writes the license."""
6920 file.Write(_LICENSE
)
6922 def WriteNamespaceOpen(self
, file):
6923 """Writes the code for the namespace."""
6924 file.Write("namespace gpu {\n")
6925 file.Write("namespace gles2 {\n")
6928 def WriteNamespaceClose(self
, file):
6929 """Writes the code to close the namespace."""
6930 file.Write("} // namespace gles2\n")
6931 file.Write("} // namespace gpu\n")
6934 def ParseArgs(self
, arg_string
):
6935 """Parses a function arg string."""
6937 num_pointer_args
= 0
6938 parts
= arg_string
.split(',')
6940 for arg_string
in parts
:
6941 if arg_string
.startswith('GLenum '):
6943 arg
= CreateArg(arg_string
)
6947 num_pointer_args
+= 1
6948 return (args
, num_pointer_args
, is_gl_enum
)
6950 def ParseGLH(self
, filename
):
6951 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
6952 f
= open(filename
, "r")
6953 functions
= f
.read()
6955 for line
in functions
.splitlines():
6956 match
= self
._function
_re
.match(line
)
6958 func_name
= match
.group(2)[2:]
6959 func_info
= self
.GetFunctionInfo(func_name
)
6960 if func_info
.type != 'Noop':
6961 return_type
= match
.group(1).strip()
6962 arg_string
= match
.group(3)
6963 (args
, num_pointer_args
, is_gl_enum
) = self
.ParseArgs(arg_string
)
6964 # comment in to find out which functions use bare enums.
6966 # self.Log("%s uses bare GLenum" % func_name)
6967 args_for_cmds
= args
6968 if hasattr(func_info
, 'cmd_args'):
6969 (args_for_cmds
, num_pointer_args
, is_gl_enum
) = (
6970 self
.ParseArgs(getattr(func_info
, 'cmd_args')))
6972 for arg
in args_for_cmds
:
6973 arg
.AddCmdArgs(cmd_args
)
6975 for arg
in args_for_cmds
:
6976 arg
.AddInitArgs(init_args
)
6977 return_arg
= CreateArg(return_type
+ " result")
6979 init_args
.append(return_arg
)
6980 f
= Function(func_name
, func_name
, func_info
, return_type
, args
,
6981 args_for_cmds
, cmd_args
, init_args
, num_pointer_args
)
6982 self
.original_functions
.append(f
)
6983 gen_cmd
= f
.GetInfo('gen_cmd')
6984 if gen_cmd
== True or gen_cmd
== None:
6986 f
.type_handler
.AddImmediateFunction(self
, f
)
6987 f
.type_handler
.AddBucketFunction(self
, f
)
6989 self
.Log("Auto Generated Functions : %d" %
6990 len([f
for f
in self
.functions
if f
.can_auto_generate
or
6991 (not f
.IsType('') and not f
.IsType('Custom') and
6992 not f
.IsType('Todo'))]))
6994 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
6995 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
6996 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
6999 self
.Log(" %-10s %-20s gl%s" % (f
.info
.type, f
.return_type
, f
.name
))
7001 def WriteCommandIds(self
, filename
):
7002 """Writes the command buffer format"""
7003 file = CHeaderWriter(filename
)
7004 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
7006 for func
in self
.functions
:
7007 file.Write(" %-60s /* %d */ \\\n" %
7008 ("OP(%s)" % func
.name
, id))
7012 file.Write("enum CommandId {\n")
7013 file.Write(" kStartPoint = cmd::kLastCommonId, "
7014 "// All GLES2 commands start after this.\n")
7015 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
7016 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
7017 file.Write("#undef GLES2_CMD_OP\n")
7018 file.Write(" kNumCommands\n")
7023 def WriteFormat(self
, filename
):
7024 """Writes the command buffer format"""
7025 file = CHeaderWriter(filename
)
7026 for func
in self
.functions
:
7028 #gen_cmd = func.GetInfo('gen_cmd')
7029 #if gen_cmd == True or gen_cmd == None:
7030 func
.WriteStruct(file)
7034 def WriteDocs(self
, filename
):
7035 """Writes the command buffer doc version of the commands"""
7036 file = CWriter(filename
)
7037 for func
in self
.functions
:
7039 #gen_cmd = func.GetInfo('gen_cmd')
7040 #if gen_cmd == True or gen_cmd == None:
7041 func
.WriteDocs(file)
7045 def WriteFormatTest(self
, filename
):
7046 """Writes the command buffer format test."""
7047 file = CHeaderWriter(
7049 "// This file contains unit tests for gles2 commmands\n"
7050 "// It is included by gles2_cmd_format_test.cc\n"
7053 for func
in self
.functions
:
7055 #gen_cmd = func.GetInfo('gen_cmd')
7056 #if gen_cmd == True or gen_cmd == None:
7057 func
.WriteFormatTest(file)
7061 def WriteCmdHelperHeader(self
, filename
):
7062 """Writes the gles2 command helper."""
7063 file = CHeaderWriter(filename
)
7065 for func
in self
.functions
:
7067 #gen_cmd = func.GetInfo('gen_cmd')
7068 #if gen_cmd == True or gen_cmd == None:
7069 func
.WriteCmdHelper(file)
7073 def WriteServiceContextStateHeader(self
, filename
):
7074 """Writes the service context state header."""
7075 file = CHeaderWriter(
7077 "// It is included by context_state.h\n")
7078 file.Write("struct EnableFlags {\n")
7079 file.Write(" EnableFlags();\n")
7080 for capability
in _CAPABILITY_FLAGS
:
7081 file.Write(" bool %s;\n" % capability
['name'])
7082 file.Write("};\n\n")
7084 for state_name
in sorted(_STATES
.keys()):
7085 state
= _STATES
[state_name
]
7086 for item
in state
['states']:
7087 file.Write("%s %s;\n" % (item
['type'], item
['name']))
7092 def WriteClientContextStateHeader(self
, filename
):
7093 """Writes the client context state header."""
7094 file = CHeaderWriter(
7096 "// It is included by client_context_state.h\n")
7097 file.Write("struct EnableFlags {\n")
7098 file.Write(" EnableFlags();\n")
7099 for capability
in _CAPABILITY_FLAGS
:
7100 file.Write(" bool %s;\n" % capability
['name'])
7101 file.Write("};\n\n")
7105 def WriteContextStateGetters(self
, file, class_name
):
7106 """Writes the state getters."""
7107 for gl_type
in ["GLint", "GLfloat"]:
7109 bool %s::GetStateAs%s(
7110 GLenum pname, %s* params, GLsizei* num_written) const {
7112 """ % (class_name
, gl_type
, gl_type
))
7113 for state_name
in sorted(_STATES
.keys()):
7114 state
= _STATES
[state_name
]
7116 file.Write(" case %s:\n" % state
['enum'])
7117 file.Write(" *num_written = %d;\n" % len(state
['states']))
7118 file.Write(" if (params) {\n")
7119 for ndx
,item
in enumerate(state
['states']):
7120 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
7121 (ndx
, gl_type
, item
['name']))
7123 file.Write(" return true;\n")
7125 for item
in state
['states']:
7126 file.Write(" case %s:\n" % item
['enum'])
7127 file.Write(" *num_written = 1;\n")
7128 file.Write(" if (params) {\n")
7129 file.Write(" params[0] = static_cast<%s>(%s);\n" %
7130 (gl_type
, item
['name']))
7132 file.Write(" return true;\n")
7133 for capability
in _CAPABILITY_FLAGS
:
7134 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7135 file.Write(" *num_written = 1;\n")
7136 file.Write(" if (params) {\n")
7138 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
7139 (gl_type
, capability
['name']))
7141 file.Write(" return true;\n")
7142 file.Write(""" default:
7148 def WriteServiceContextStateImpl(self
, filename
):
7149 """Writes the context state service implementation."""
7150 file = CHeaderWriter(
7152 "// It is included by context_state.cc\n")
7154 for capability
in _CAPABILITY_FLAGS
:
7155 code
.append("%s(%s)" %
7156 (capability
['name'],
7157 ('false', 'true')['default' in capability
]))
7158 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7162 file.Write("void ContextState::Initialize() {\n")
7163 for state_name
in sorted(_STATES
.keys()):
7164 state
= _STATES
[state_name
]
7165 for item
in state
['states']:
7166 file.Write(" %s = %s;\n" % (item
['name'], item
['default']))
7170 void ContextState::InitCapabilities(const ContextState* prev_state) const {
7172 def WriteCapabilities(test_prev
):
7173 for capability
in _CAPABILITY_FLAGS
:
7174 capability_name
= capability
['name']
7176 file.Write(" if (prev_state->enable_flags.%s != enable_flags.%s)\n" %
7177 (capability_name
, capability_name
))
7178 file.Write(" EnableDisable(GL_%s, enable_flags.%s);\n" %
7179 (capability_name
.upper(), capability_name
))
7181 file.Write(" if (prev_state) {")
7182 WriteCapabilities(True)
7183 file.Write(" } else {")
7184 WriteCapabilities(False)
7189 void ContextState::InitState(const ContextState *prev_state) const {
7192 def WriteStates(test_prev
):
7193 # We need to sort the keys so the expectations match
7194 for state_name
in sorted(_STATES
.keys()):
7195 state
= _STATES
[state_name
]
7196 if state
['type'] == 'FrontBack':
7197 num_states
= len(state
['states'])
7198 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
7202 for place
, item
in enumerate(group
):
7203 item_name
= item
['name']
7204 args
.append('%s' % item_name
)
7208 file.Write("(%s != prev_state->%s)" % (item_name
, item_name
))
7212 " gl%s(%s, %s);\n" %
7213 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
7214 elif state
['type'] == 'NamedParameter':
7215 for item
in state
['states']:
7216 if 'extension_flag' in item
:
7217 file.Write(" if (feature_info_->feature_flags().%s)\n " %
7218 item
['extension_flag'])
7220 file.Write(" if (prev_state->%s != %s)\n" %
7221 (item
['name'], item
['name']))
7222 file.Write(" gl%s(%s, %s);\n" %
7223 (state
['func'], item
['enum'], item
['name']))
7228 for place
, item
in enumerate(state
['states']):
7229 item_name
= item
['name']
7230 args
.append('%s' % item_name
)
7234 file.Write("(%s != prev_state->%s)" %
7235 (item_name
, item_name
))
7238 file.Write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
7240 file.Write(" if (prev_state) {")
7242 file.Write(" } else {")
7248 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
7251 for capability
in _CAPABILITY_FLAGS
:
7252 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7253 file.Write(" return enable_flags.%s;\n" % capability
['name'])
7254 file.Write(""" default:
7261 self
.WriteContextStateGetters(file, "ContextState")
7264 def WriteClientContextStateImpl(self
, filename
):
7265 """Writes the context state client side implementation."""
7266 file = CHeaderWriter(
7268 "// It is included by client_context_state.cc\n")
7270 for capability
in _CAPABILITY_FLAGS
:
7271 code
.append("%s(%s)" %
7272 (capability
['name'],
7273 ('false', 'true')['default' in capability
]))
7275 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7280 bool ClientContextState::SetCapabilityState(
7281 GLenum cap, bool enabled, bool* changed) {
7285 for capability
in _CAPABILITY_FLAGS
:
7286 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7287 file.Write(""" if (enable_flags.%(name)s != enabled) {
7289 enable_flags.%(name)s = enabled;
7293 file.Write(""" default:
7298 file.Write("""bool ClientContextState::GetEnabled(
7299 GLenum cap, bool* enabled) const {
7302 for capability
in _CAPABILITY_FLAGS
:
7303 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7304 file.Write(" *enabled = enable_flags.%s;\n" % capability
['name'])
7305 file.Write(" return true;\n")
7306 file.Write(""" default:
7313 def WriteServiceImplementation(self
, filename
):
7314 """Writes the service decorder implementation."""
7315 file = CHeaderWriter(
7317 "// It is included by gles2_cmd_decoder.cc\n")
7319 for func
in self
.functions
:
7321 #gen_cmd = func.GetInfo('gen_cmd')
7322 #if gen_cmd == True or gen_cmd == None:
7323 func
.WriteServiceImplementation(file)
7326 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
7329 for capability
in _CAPABILITY_FLAGS
:
7330 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7331 if 'state_flag' in capability
:
7332 file.Write(""" if (state_.enable_flags.%(name)s != enabled) {
7333 state_.enable_flags.%(name)s = enabled;
7334 %(state_flag)s = true;
7339 file.Write(""" state_.enable_flags.%(name)s = enabled;
7342 file.Write(""" default:
7350 def WriteServiceUnitTests(self
, filename
):
7351 """Writes the service decorder unit tests."""
7352 num_tests
= len(self
.functions
)
7353 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
7355 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
7357 name
= filename
% count
7358 file = CHeaderWriter(
7360 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count
)
7361 file.SetFileNum(count
)
7362 end
= test_num
+ FUNCTIONS_PER_FILE
7365 for idx
in range(test_num
, end
):
7366 func
= self
.functions
[idx
]
7368 #gen_cmd = func.GetInfo('gen_cmd')
7369 #if gen_cmd == True or gen_cmd == None:
7370 if func
.GetInfo('unit_test') == False:
7371 file.Write("// TODO(gman): %s\n" % func
.name
)
7373 func
.WriteServiceUnitTest(file)
7376 file = CHeaderWriter(
7378 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
7380 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
7382 for capability
in _CAPABILITY_FLAGS
:
7383 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
7384 (capability
['name'].upper(),
7385 ('false', 'true')['default' in capability
]))
7388 void GLES2DecoderTestBase::SetupInitStateExpectations() {
7391 # We need to sort the keys so the expectations match
7392 for state_name
in sorted(_STATES
.keys()):
7393 state
= _STATES
[state_name
]
7394 if state
['type'] == 'FrontBack':
7395 num_states
= len(state
['states'])
7396 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
7399 if 'expected' in item
:
7400 args
.append(item
['expected'])
7402 args
.append(item
['default'])
7404 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7405 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
7406 file.Write(" .Times(1)\n")
7407 file.Write(" .RetiresOnSaturation();\n")
7408 elif state
['type'] == 'NamedParameter':
7409 for item
in state
['states']:
7410 if 'extension_flag' in item
:
7413 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7414 (state
['func'], item
['enum'], item
['default']))
7415 file.Write(" .Times(1)\n")
7416 file.Write(" .RetiresOnSaturation();\n")
7419 for item
in state
['states']:
7420 if 'expected' in item
:
7421 args
.append(item
['expected'])
7423 args
.append(item
['default'])
7424 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
7425 (state
['func'], ", ".join(args
)))
7426 file.Write(" .Times(1)\n")
7427 file.Write(" .RetiresOnSaturation();\n")
7432 def WriteGLES2Header(self
, filename
):
7433 """Writes the GLES2 header."""
7434 file = CHeaderWriter(
7436 "// This file contains Chromium-specific GLES2 declarations.\n\n")
7438 for func
in self
.original_functions
:
7439 func
.WriteGLES2Header(file)
7444 def WriteGLES2CLibImplementation(self
, filename
):
7445 """Writes the GLES2 c lib implementation."""
7446 file = CHeaderWriter(
7448 "// These functions emulate GLES2 over command buffers.\n")
7450 for func
in self
.original_functions
:
7451 func
.WriteGLES2CLibImplementation(file)
7456 extern const NameToFunc g_gles2_function_table[] = {
7458 for func
in self
.original_functions
:
7460 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
7461 (func
.name
, func
.name
))
7462 file.Write(""" { NULL, NULL, },
7465 } // namespace gles2
7469 def WriteGLES2InterfaceHeader(self
, filename
):
7470 """Writes the GLES2 interface header."""
7471 file = CHeaderWriter(
7473 "// This file is included by gles2_interface.h to declare the\n"
7474 "// GL api functions.\n")
7475 for func
in self
.original_functions
:
7476 func
.WriteGLES2InterfaceHeader(file)
7479 def WriteGLES2InterfaceStub(self
, filename
):
7480 """Writes the GLES2 interface stub header."""
7481 file = CHeaderWriter(
7483 "// This file is included by gles2_interface_stub.h.\n")
7484 for func
in self
.original_functions
:
7485 func
.WriteGLES2InterfaceStub(file)
7488 def WriteGLES2InterfaceStubImpl(self
, filename
):
7489 """Writes the GLES2 interface header."""
7490 file = CHeaderWriter(
7492 "// This file is included by gles2_interface_stub.cc.\n")
7493 for func
in self
.original_functions
:
7494 func
.WriteGLES2InterfaceStubImpl(file)
7497 def WriteGLES2ImplementationHeader(self
, filename
):
7498 """Writes the GLES2 Implementation header."""
7499 file = CHeaderWriter(
7501 "// This file is included by gles2_implementation.h to declare the\n"
7502 "// GL api functions.\n")
7503 for func
in self
.original_functions
:
7504 func
.WriteGLES2ImplementationHeader(file)
7507 def WriteGLES2Implementation(self
, filename
):
7508 """Writes the GLES2 Implementation."""
7509 file = CHeaderWriter(
7511 "// This file is included by gles2_implementation.cc to define the\n"
7512 "// GL api functions.\n")
7513 for func
in self
.original_functions
:
7514 func
.WriteGLES2Implementation(file)
7517 def WriteGLES2TraceImplementationHeader(self
, filename
):
7518 """Writes the GLES2 Trace Implementation header."""
7519 file = CHeaderWriter(
7521 "// This file is included by gles2_trace_implementation.h\n")
7522 for func
in self
.original_functions
:
7523 func
.WriteGLES2TraceImplementationHeader(file)
7526 def WriteGLES2TraceImplementation(self
, filename
):
7527 """Writes the GLES2 Trace Implementation."""
7528 file = CHeaderWriter(
7530 "// This file is included by gles2_trace_implementation.cc\n")
7531 for func
in self
.original_functions
:
7532 func
.WriteGLES2TraceImplementation(file)
7535 def WriteGLES2ImplementationUnitTests(self
, filename
):
7536 """Writes the GLES2 helper header."""
7537 file = CHeaderWriter(
7539 "// This file is included by gles2_implementation.h to declare the\n"
7540 "// GL api functions.\n")
7541 for func
in self
.original_functions
:
7542 func
.WriteGLES2ImplementationUnitTest(file)
7545 def WriteServiceUtilsHeader(self
, filename
):
7546 """Writes the gles2 auto generated utility header."""
7547 file = CHeaderWriter(filename
)
7548 for enum
in sorted(_ENUM_LISTS
.keys()):
7549 file.Write("ValueValidator<%s> %s;\n" %
7550 (_ENUM_LISTS
[enum
]['type'], ToUnderscore(enum
)))
7554 def WriteServiceUtilsImplementation(self
, filename
):
7555 """Writes the gles2 auto generated utility implementation."""
7556 file = CHeaderWriter(filename
)
7557 enums
= sorted(_ENUM_LISTS
.keys())
7559 if len(_ENUM_LISTS
[enum
]['valid']) > 0:
7560 file.Write("static const %s valid_%s_table[] = {\n" %
7561 (_ENUM_LISTS
[enum
]['type'], ToUnderscore(enum
)))
7562 for value
in _ENUM_LISTS
[enum
]['valid']:
7563 file.Write(" %s,\n" % value
)
7566 file.Write("Validators::Validators()\n")
7569 for count
, enum
in enumerate(enums
):
7570 if count
+ 1 == len(enums
):
7572 if len(_ENUM_LISTS
[enum
]['valid']) > 0:
7573 code
= """ %(pre)s%(name)s(
7574 valid_%(name)s_table, arraysize(valid_%(name)s_table))%(post)s
7577 code
= """ %(pre)s%(name)s()%(post)s
7580 'name': ToUnderscore(enum
),
7585 file.Write("}\n\n");
7588 def WriteCommonUtilsHeader(self
, filename
):
7589 """Writes the gles2 common utility header."""
7590 file = CHeaderWriter(filename
)
7591 enums
= sorted(_ENUM_LISTS
.keys())
7593 if _ENUM_LISTS
[enum
]['type'] == 'GLenum':
7594 file.Write("static std::string GetString%s(uint32 value);\n" % enum
)
7598 def WriteCommonUtilsImpl(self
, filename
):
7599 """Writes the gles2 common utility header."""
7600 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
7602 for fname
in ['../../third_party/khronos/GLES2/gl2.h',
7603 '../../third_party/khronos/GLES2/gl2ext.h',
7604 '../../gpu/GLES2/gl2chromium.h',
7605 '../../gpu/GLES2/gl2extchromium.h']:
7606 lines
= open(fname
).readlines()
7608 m
= enum_re
.match(line
)
7612 if len(value
) <= 10 and not value
in dict:
7615 file = CHeaderWriter(filename
)
7616 file.Write("static const GLES2Util::EnumToString "
7617 "enum_to_string_table[] = {\n")
7619 file.Write(' { %s, "%s", },\n' % (value
, dict[value
]))
7622 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
7623 enum_to_string_table;
7624 const size_t GLES2Util::enum_to_string_table_len_ =
7625 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
7629 enums
= sorted(_ENUM_LISTS
.keys())
7631 if _ENUM_LISTS
[enum
]['type'] == 'GLenum':
7632 file.Write("std::string GLES2Util::GetString%s(uint32 value) {\n" %
7634 if len(_ENUM_LISTS
[enum
]['valid']) > 0:
7635 file.Write(" static const EnumToString string_table[] = {\n")
7636 for value
in _ENUM_LISTS
[enum
]['valid']:
7637 file.Write(' { %s, "%s" },\n' % (value
, value
))
7639 return GLES2Util::GetQualifiedEnumString(
7640 string_table, arraysize(string_table), value);
7645 file.Write(""" return GLES2Util::GetQualifiedEnumString(
7652 def WritePepperGLES2Interface(self
, filename
, dev
):
7653 """Writes the Pepper OpenGLES interface definition."""
7654 file = CHeaderWriter(
7656 "// OpenGL ES interface.\n")
7658 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
7660 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
7662 file.Write("\n#ifndef __gl2_h_\n")
7663 for (k
, v
) in _GL_TYPES
.iteritems():
7664 file.Write("typedef %s %s;\n" % (v
, k
))
7665 file.Write("#ifdef _WIN64\n")
7666 for (k
, v
) in _GL_TYPES_64
.iteritems():
7667 file.Write("typedef %s %s;\n" % (v
, k
))
7668 file.Write("#else\n")
7669 for (k
, v
) in _GL_TYPES_32
.iteritems():
7670 file.Write("typedef %s %s;\n" % (v
, k
))
7671 file.Write("#endif // _WIN64\n")
7672 file.Write("#endif // __gl2_h_\n\n")
7674 for interface
in self
.pepper_interfaces
:
7675 if interface
.dev
!= dev
:
7677 file.Write("#define %s_1_0 \"%s;1.0\"\n" %
7678 (interface
.GetInterfaceName(), interface
.GetInterfaceString()))
7679 file.Write("#define %s %s_1_0\n" %
7680 (interface
.GetInterfaceName(), interface
.GetInterfaceName()))
7682 file.Write("\nstruct %s {\n" % interface
.GetStructName())
7683 for func
in self
.original_functions
:
7684 if not func
.InPepperInterface(interface
):
7687 original_arg
= func
.MakeTypedPepperArgString("")
7688 context_arg
= "PP_Resource context"
7689 if len(original_arg
):
7690 arg
= context_arg
+ ", " + original_arg
7693 file.Write(" %s (*%s)(%s);\n" %
7694 (func
.return_type
, func
.GetPepperName(), arg
))
7695 file.Write("};\n\n")
7700 def WritePepperGLES2Implementation(self
, filename
):
7701 """Writes the Pepper OpenGLES interface implementation."""
7703 file = CWriter(filename
)
7704 file.Write(_LICENSE
)
7705 file.Write(_DO_NOT_EDIT_WARNING
)
7707 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
7708 file.Write("#include \"base/logging.h\"\n")
7709 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
7710 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
7711 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
7713 file.Write("namespace ppapi {\n\n")
7714 file.Write("namespace {\n\n")
7716 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
7719 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
7721 file.Write(" DCHECK(enter);\n")
7722 file.Write(" DCHECK(enter->succeeded());\n")
7723 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
7725 file.Write("}\n\n");
7727 for func
in self
.original_functions
:
7728 if not func
.InAnyPepperExtension():
7731 original_arg
= func
.MakeTypedPepperArgString("")
7732 context_arg
= "PP_Resource context_id"
7733 if len(original_arg
):
7734 arg
= context_arg
+ ", " + original_arg
7737 file.Write("%s %s(%s) {\n" %
7738 (func
.return_type
, func
.GetPepperName(), arg
))
7739 file.Write(" Enter3D enter(context_id, true);\n")
7740 file.Write(" if (enter.succeeded()) {\n")
7742 return_str
= "" if func
.return_type
== "void" else "return "
7743 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
7744 (return_str
, func
.original_name
,
7745 func
.MakeOriginalArgString("")))
7747 if func
.return_type
== "void":
7750 file.Write(" else {\n")
7752 if func
.GetInfo("error_return"):
7753 error_return
= func
.GetInfo("error_return")
7754 elif func
.return_type
== "GLboolean":
7755 error_return
= "GL_FALSE"
7756 elif "*" in func
.return_type
:
7757 error_return
= "NULL"
7758 file.Write(" return %s;\n" % error_return
)
7762 file.Write("} // namespace\n")
7764 for interface
in self
.pepper_interfaces
:
7765 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
7766 (interface
.GetStructName(), interface
.GetName()))
7767 file.Write(" static const struct %s "
7768 "ppb_opengles2 = {\n" % interface
.GetStructName())
7770 file.Write(",\n &".join(
7771 f
.GetPepperName() for f
in self
.original_functions
7772 if f
.InPepperInterface(interface
)))
7776 file.Write(" return &ppb_opengles2;\n")
7779 file.Write("} // namespace ppapi\n")
7782 def WriteGLES2ToPPAPIBridge(self
, filename
):
7783 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
7785 file = CWriter(filename
)
7786 file.Write(_LICENSE
)
7787 file.Write(_DO_NOT_EDIT_WARNING
)
7789 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
7790 file.Write("#define GL_GLEXT_PROTOTYPES\n")
7791 file.Write("#endif\n")
7792 file.Write("#include <GLES2/gl2.h>\n")
7793 file.Write("#include <GLES2/gl2ext.h>\n")
7794 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
7796 for func
in self
.original_functions
:
7797 if not func
.InAnyPepperExtension():
7800 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
7802 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
7803 (func
.return_type
, func
.GetPepperName(),
7804 func
.MakeTypedPepperArgString("")))
7805 return_str
= "" if func
.return_type
== "void" else "return "
7806 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
7807 original_arg
= func
.MakeOriginalArgString("")
7808 context_arg
= "glGetCurrentContextPPAPI()"
7809 if len(original_arg
):
7810 arg
= context_arg
+ ", " + original_arg
7813 if interface
.GetName():
7814 file.Write(" const struct %s* ext = %s;\n" %
7815 (interface
.GetStructName(), interface_str
))
7816 file.Write(" if (ext)\n")
7817 file.Write(" %sext->%s(%s);\n" %
7818 (return_str
, func
.GetPepperName(), arg
))
7820 file.Write(" %s0;\n" % return_str
)
7822 file.Write(" %s%s->%s(%s);\n" %
7823 (return_str
, interface_str
, func
.GetPepperName(), arg
))
7827 def WriteMojoGLCallVisitor(self
, filename
):
7828 """Provides the GL implementation for mojo"""
7829 file = CWriter(filename
)
7830 file.Write(_LICENSE
)
7831 file.Write(_DO_NOT_EDIT_WARNING
)
7833 for func
in self
.original_functions
:
7834 if not func
.IsCoreGLFunction():
7836 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
7837 (func
.name
, func
.return_type
,
7838 func
.MakeTypedOriginalArgString(""),
7839 func
.MakeOriginalArgString("")))
7843 def Format(generated_files
):
7844 for filename
in generated_files
:
7845 call(["clang-format", "-i", "-style=chromium", filename
])
7848 """This is the main function."""
7849 parser
= OptionParser()
7852 help="base directory for resulting files, under chrome/src. default is "
7853 "empty. Use this if you want the result stored under gen.")
7855 "-v", "--verbose", action
="store_true",
7856 help="prints more output.")
7858 (options
, args
) = parser
.parse_args(args
=argv
)
7860 # Add in states and capabilites to GLState
7861 for state_name
in sorted(_STATES
.keys()):
7862 state
= _STATES
[state_name
]
7864 _ENUM_LISTS
['GLState']['valid'].append(state
['enum'])
7866 for item
in state
['states']:
7867 if 'extension_flag' in item
:
7869 _ENUM_LISTS
['GLState']['valid'].append(item
['enum'])
7870 for capability
in _CAPABILITY_FLAGS
:
7871 _ENUM_LISTS
['GLState']['valid'].append("GL_%s" % capability
['name'].upper())
7873 # This script lives under gpu/command_buffer, cd to base directory.
7874 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
7876 gen
= GLGenerator(options
.verbose
)
7877 gen
.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
7879 # Support generating files under gen/
7880 if options
.output_dir
!= None:
7881 os
.chdir(options
.output_dir
)
7883 gen
.WritePepperGLES2Interface("ppapi/c/ppb_opengles2.h", False)
7884 gen
.WritePepperGLES2Interface("ppapi/c/dev/ppb_opengles2ext_dev.h", True)
7885 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
7886 gen
.WritePepperGLES2Implementation(
7887 "ppapi/shared_impl/ppb_opengles2_shared.cc")
7888 os
.chdir("gpu/command_buffer")
7889 gen
.WriteCommandIds("common/gles2_cmd_ids_autogen.h")
7890 gen
.WriteFormat("common/gles2_cmd_format_autogen.h")
7891 gen
.WriteFormatTest("common/gles2_cmd_format_test_autogen.h")
7892 gen
.WriteGLES2InterfaceHeader("client/gles2_interface_autogen.h")
7893 gen
.WriteGLES2InterfaceStub("client/gles2_interface_stub_autogen.h")
7894 gen
.WriteGLES2InterfaceStubImpl(
7895 "client/gles2_interface_stub_impl_autogen.h")
7896 gen
.WriteGLES2ImplementationHeader("client/gles2_implementation_autogen.h")
7897 gen
.WriteGLES2Implementation("client/gles2_implementation_impl_autogen.h")
7898 gen
.WriteGLES2ImplementationUnitTests(
7899 "client/gles2_implementation_unittest_autogen.h")
7900 gen
.WriteGLES2TraceImplementationHeader(
7901 "client/gles2_trace_implementation_autogen.h")
7902 gen
.WriteGLES2TraceImplementation(
7903 "client/gles2_trace_implementation_impl_autogen.h")
7904 gen
.WriteGLES2CLibImplementation("client/gles2_c_lib_autogen.h")
7905 gen
.WriteCmdHelperHeader("client/gles2_cmd_helper_autogen.h")
7906 gen
.WriteServiceImplementation("service/gles2_cmd_decoder_autogen.h")
7907 gen
.WriteServiceContextStateHeader("service/context_state_autogen.h")
7908 gen
.WriteServiceContextStateImpl("service/context_state_impl_autogen.h")
7909 gen
.WriteClientContextStateHeader("client/client_context_state_autogen.h")
7910 gen
.WriteClientContextStateImpl(
7911 "client/client_context_state_impl_autogen.h")
7912 gen
.WriteServiceUnitTests("service/gles2_cmd_decoder_unittest_%d_autogen.h")
7913 gen
.WriteServiceUtilsHeader("service/gles2_cmd_validation_autogen.h")
7914 gen
.WriteServiceUtilsImplementation(
7915 "service/gles2_cmd_validation_implementation_autogen.h")
7916 gen
.WriteCommonUtilsHeader("common/gles2_cmd_utils_autogen.h")
7917 gen
.WriteCommonUtilsImpl("common/gles2_cmd_utils_implementation_autogen.h")
7918 gen
.WriteGLES2Header("../GLES2/gl2chromium_autogen.h")
7919 gen
.WriteMojoGLCallVisitor(
7920 "../../mojo/public/c/gles2/gles2_call_visitor_autogen.h")
7923 "common/gles2_cmd_format_autogen.h",
7924 "common/gles2_cmd_format_test_autogen.h",
7925 "common/gles2_cmd_ids_autogen.h",
7926 "common/gles2_cmd_utils_autogen.h",
7927 "common/gles2_cmd_utils_implementation_autogen.h",
7928 "client/client_context_state_autogen.h",
7929 "client/client_context_state_impl_autogen.h",
7930 "client/gles2_cmd_helper_autogen.h",
7931 "client/gles2_c_lib_autogen.h",
7932 "client/gles2_implementation_autogen.h",
7933 "client/gles2_implementation_impl_autogen.h",
7934 "client/gles2_implementation_unittest_autogen.h",
7935 "client/gles2_interface_autogen.h",
7936 "client/gles2_interface_stub_autogen.h",
7937 "client/gles2_interface_stub_impl_autogen.h",
7938 "client/gles2_trace_implementation_autogen.h",
7939 "client/gles2_trace_implementation_impl_autogen.h",
7940 "service/context_state_autogen.h",
7941 "service/context_state_impl_autogen.h",
7942 "service/gles2_cmd_decoder_autogen.h",
7943 "service/gles2_cmd_decoder_unittest_0_autogen.h",
7944 "service/gles2_cmd_decoder_unittest_1_autogen.h",
7945 "service/gles2_cmd_decoder_unittest_2_autogen.h",
7946 "service/gles2_cmd_decoder_unittest_3_autogen.h",
7947 "service/gles2_cmd_validation_autogen.h",
7948 "service/gles2_cmd_validation_implementation_autogen.h"])
7951 "gpu/GLES2/gl2chromium_autogen.h",
7952 "mojo/public/c/gles2/gles2_call_visitor_autogen.h",
7953 "ppapi/c/dev/ppb_opengles2ext_dev.h",
7954 "ppapi/c/ppb_opengles2.h",
7955 "ppapi/lib/gl/gles2/gles2.c",
7956 "ppapi/shared_impl/ppb_opengles2_shared.cc"])
7959 print "%d errors" % gen
.errors
7964 if __name__
== '__main__':
7965 sys
.exit(main(sys
.argv
[1:]))