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."""
14 from optparse
import OptionParser
15 from subprocess
import call
18 _SIZE_OF_COMMAND_HEADER
= 4
19 _FIRST_SPECIFIC_COMMAND_ID
= 256
21 _LICENSE
= """// Copyright 2014 The Chromium Authors. All rights reserved.
22 // Use of this source code is governed by a BSD-style license that can be
23 // found in the LICENSE file.
27 _DO_NOT_EDIT_WARNING
= """// This file is auto-generated from
28 // gpu/command_buffer/build_gles2_cmd_buffer.py
29 // It's formatted by clang-format using chromium coding style:
30 // clang-format -i -style=chromium filename
35 # This string is copied directly out of the gl2.h file from GLES2.0
39 # *) Any argument that is a resourceID has been changed to GLid<Type>.
40 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
41 # If it's allowed to not exist it's GLidBind<Type>
43 # *) All GLenums have been changed to GLenumTypeOfEnum
46 'GLenum': 'unsigned int',
47 'GLboolean': 'unsigned char',
48 'GLbitfield': 'unsigned int',
49 'GLbyte': 'signed char',
53 'GLubyte': 'unsigned char',
54 'GLushort': 'unsigned short',
55 'GLuint': 'unsigned int',
64 'GLintptr': 'long int',
65 'GLsizeiptr': 'long int'
69 'GLintptr': 'long long int',
70 'GLsizeiptr': 'long long int'
73 # Capabilites selected with glEnable
76 {'name': 'cull_face'},
77 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
78 {'name': 'dither', 'default': True},
79 {'name': 'polygon_offset_fill'},
80 {'name': 'sample_alpha_to_coverage'},
81 {'name': 'sample_coverage'},
82 {'name': 'scissor_test'},
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',
113 'name': 'color_mask_red',
119 'name': 'color_mask_green',
125 'name': 'color_mask_blue',
131 'name': 'color_mask_alpha',
137 'state_flag': 'framebuffer_state_.clear_state_dirty',
141 'func': 'ClearStencil',
142 'enum': 'GL_STENCIL_CLEAR_VALUE',
144 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
149 'func': 'BlendColor',
150 'enum': 'GL_BLEND_COLOR',
152 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
153 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
154 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
155 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
160 'func': 'BlendEquationSeparate',
163 'name': 'blend_equation_rgb',
165 'enum': 'GL_BLEND_EQUATION_RGB',
166 'default': 'GL_FUNC_ADD',
169 'name': 'blend_equation_alpha',
171 'enum': 'GL_BLEND_EQUATION_ALPHA',
172 'default': 'GL_FUNC_ADD',
178 'func': 'BlendFuncSeparate',
181 'name': 'blend_source_rgb',
183 'enum': 'GL_BLEND_SRC_RGB',
187 'name': 'blend_dest_rgb',
189 'enum': 'GL_BLEND_DST_RGB',
190 'default': 'GL_ZERO',
193 'name': 'blend_source_alpha',
195 'enum': 'GL_BLEND_SRC_ALPHA',
199 'name': 'blend_dest_alpha',
201 'enum': 'GL_BLEND_DST_ALPHA',
202 'default': 'GL_ZERO',
208 'func': 'PolygonOffset',
211 'name': 'polygon_offset_factor',
213 'enum': 'GL_POLYGON_OFFSET_FACTOR',
217 'name': 'polygon_offset_units',
219 'enum': 'GL_POLYGON_OFFSET_UNITS',
227 'enum': 'GL_CULL_FACE_MODE',
232 'default': 'GL_BACK',
239 'enum': 'GL_FRONT_FACE',
240 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
245 'enum': 'GL_DEPTH_FUNC',
246 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
250 'func': 'DepthRange',
251 'enum': 'GL_DEPTH_RANGE',
253 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
254 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
259 'func': 'SampleCoverage',
262 'name': 'sample_coverage_value',
264 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
268 'name': 'sample_coverage_invert',
270 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
277 'func': 'StencilMaskSeparate',
278 'state_flag': 'framebuffer_state_.clear_state_dirty',
281 'name': 'stencil_front_writemask',
283 'enum': 'GL_STENCIL_WRITEMASK',
284 'default': '0xFFFFFFFFU',
288 'name': 'stencil_back_writemask',
290 'enum': 'GL_STENCIL_BACK_WRITEMASK',
291 'default': '0xFFFFFFFFU',
298 'func': 'StencilOpSeparate',
301 'name': 'stencil_front_fail_op',
303 'enum': 'GL_STENCIL_FAIL',
304 'default': 'GL_KEEP',
307 'name': 'stencil_front_z_fail_op',
309 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
310 'default': 'GL_KEEP',
313 'name': 'stencil_front_z_pass_op',
315 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
316 'default': 'GL_KEEP',
319 'name': 'stencil_back_fail_op',
321 'enum': 'GL_STENCIL_BACK_FAIL',
322 'default': 'GL_KEEP',
325 'name': 'stencil_back_z_fail_op',
327 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
328 'default': 'GL_KEEP',
331 'name': 'stencil_back_z_pass_op',
333 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
334 'default': 'GL_KEEP',
340 'func': 'StencilFuncSeparate',
343 'name': 'stencil_front_func',
345 'enum': 'GL_STENCIL_FUNC',
346 'default': 'GL_ALWAYS',
349 'name': 'stencil_front_ref',
351 'enum': 'GL_STENCIL_REF',
355 'name': 'stencil_front_mask',
357 'enum': 'GL_STENCIL_VALUE_MASK',
358 'default': '0xFFFFFFFFU',
361 'name': 'stencil_back_func',
363 'enum': 'GL_STENCIL_BACK_FUNC',
364 'default': 'GL_ALWAYS',
367 'name': 'stencil_back_ref',
369 'enum': 'GL_STENCIL_BACK_REF',
373 'name': 'stencil_back_mask',
375 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
376 'default': '0xFFFFFFFFU',
381 'type': 'NamedParameter',
385 'name': 'hint_generate_mipmap',
387 'enum': 'GL_GENERATE_MIPMAP_HINT',
388 'default': 'GL_DONT_CARE'
391 'name': 'hint_fragment_shader_derivative',
393 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
394 'default': 'GL_DONT_CARE',
395 'extension_flag': 'oes_standard_derivatives'
400 'type': 'NamedParameter',
401 'func': 'PixelStorei',
404 'name': 'pack_alignment',
406 'enum': 'GL_PACK_ALIGNMENT',
410 'name': 'unpack_alignment',
412 'enum': 'GL_UNPACK_ALIGNMENT',
417 # TODO: Consider implemenenting these states
422 'enum': 'GL_LINE_WIDTH',
425 'name': 'line_width',
428 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
435 'enum': 'GL_DEPTH_WRITEMASK',
438 'name': 'depth_mask',
444 'state_flag': 'framebuffer_state_.clear_state_dirty',
449 'enum': 'GL_SCISSOR_BOX',
451 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
456 'expected': 'kViewportX',
462 'expected': 'kViewportY',
465 'name': 'scissor_width',
468 'expected': 'kViewportWidth',
471 'name': 'scissor_height',
474 'expected': 'kViewportHeight',
481 'enum': 'GL_VIEWPORT',
483 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
485 'name': 'viewport_x',
488 'expected': 'kViewportX',
491 'name': 'viewport_y',
494 'expected': 'kViewportY',
497 'name': 'viewport_width',
500 'expected': 'kViewportWidth',
503 'name': 'viewport_height',
506 'expected': 'kViewportHeight',
510 'MatrixValuesCHROMIUM': {
511 'type': 'NamedParameter',
512 'func': 'MatrixLoadfEXT',
514 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
515 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
516 'name': 'modelview_matrix',
519 '1.0f', '0.0f','0.0f','0.0f',
520 '0.0f', '1.0f','0.0f','0.0f',
521 '0.0f', '0.0f','1.0f','0.0f',
522 '0.0f', '0.0f','0.0f','1.0f',
524 'extension_flag': 'chromium_path_rendering',
526 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
527 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
528 'name': 'projection_matrix',
531 '1.0f', '0.0f','0.0f','0.0f',
532 '0.0f', '1.0f','0.0f','0.0f',
533 '0.0f', '0.0f','1.0f','0.0f',
534 '0.0f', '0.0f','0.0f','1.0f',
536 'extension_flag': 'chromium_path_rendering',
542 # Named type info object represents a named type that is used in OpenGL call
543 # arguments. Each named type defines a set of valid OpenGL call arguments. The
544 # named types are used in 'cmd_buffer_functions.txt'.
545 # type: The actual GL type of the named type.
546 # valid: The list of values that are valid for both the client and the service.
547 # invalid: Examples of invalid values for the type. At least these values
548 # should be tested to be invalid.
549 # is_complete: The list of valid values of type are final and will not be
550 # modified during runtime.
559 'GL_LINEAR_MIPMAP_LINEAR',
562 'FrameBufferTarget': {
568 'GL_DRAW_FRAMEBUFFER' ,
569 'GL_READ_FRAMEBUFFER' ,
572 'RenderBufferTarget': {
585 'GL_ELEMENT_ARRAY_BUFFER',
591 'IndexedBufferTarget': {
594 'GL_TRANSFORM_FEEDBACK_BUFFER',
650 'CompressedTextureFormat': {
658 # NOTE: State an Capability entries added later.
660 'GL_ALIASED_LINE_WIDTH_RANGE',
661 'GL_ALIASED_POINT_SIZE_RANGE',
663 'GL_ARRAY_BUFFER_BINDING',
665 'GL_COMPRESSED_TEXTURE_FORMATS',
666 'GL_CURRENT_PROGRAM',
669 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
670 'GL_FRAMEBUFFER_BINDING',
671 'GL_GENERATE_MIPMAP_HINT',
673 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
674 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
675 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
676 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
677 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
678 'GL_MAX_RENDERBUFFER_SIZE',
679 'GL_MAX_TEXTURE_IMAGE_UNITS',
680 'GL_MAX_TEXTURE_SIZE',
681 'GL_MAX_VARYING_VECTORS',
682 'GL_MAX_VERTEX_ATTRIBS',
683 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
684 'GL_MAX_VERTEX_UNIFORM_VECTORS',
685 'GL_MAX_VIEWPORT_DIMS',
686 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
687 'GL_NUM_SHADER_BINARY_FORMATS',
690 'GL_RENDERBUFFER_BINDING',
692 'GL_SAMPLE_COVERAGE_INVERT',
693 'GL_SAMPLE_COVERAGE_VALUE',
696 'GL_SHADER_BINARY_FORMATS',
697 'GL_SHADER_COMPILER',
700 'GL_TEXTURE_BINDING_2D',
701 'GL_TEXTURE_BINDING_CUBE_MAP',
702 'GL_UNPACK_ALIGNMENT',
703 'GL_UNPACK_FLIP_Y_CHROMIUM',
704 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
705 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
706 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
707 # we can add this because we emulate it if the driver does not support it.
708 'GL_VERTEX_ARRAY_BINDING_OES',
715 'GetTexParamTarget': {
719 'GL_TEXTURE_CUBE_MAP',
722 'GL_PROXY_TEXTURE_CUBE_MAP',
729 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
730 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
731 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
732 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
733 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
734 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
737 'GL_PROXY_TEXTURE_CUBE_MAP',
744 'GL_TEXTURE_2D_ARRAY',
750 'TextureBindTarget': {
754 'GL_TEXTURE_CUBE_MAP',
761 'TransformFeedbackBindTarget': {
764 'GL_TRANSFORM_FEEDBACK',
770 'TransformFeedbackPrimitiveMode': {
785 'GL_FRAGMENT_SHADER',
788 'GL_GEOMETRY_SHADER',
824 'GL_FUNC_REVERSE_SUBTRACT',
837 'GL_ONE_MINUS_SRC_COLOR',
839 'GL_ONE_MINUS_DST_COLOR',
841 'GL_ONE_MINUS_SRC_ALPHA',
843 'GL_ONE_MINUS_DST_ALPHA',
845 'GL_ONE_MINUS_CONSTANT_COLOR',
847 'GL_ONE_MINUS_CONSTANT_ALPHA',
848 'GL_SRC_ALPHA_SATURATE',
857 'GL_ONE_MINUS_SRC_COLOR',
859 'GL_ONE_MINUS_DST_COLOR',
861 'GL_ONE_MINUS_SRC_ALPHA',
863 'GL_ONE_MINUS_DST_ALPHA',
865 'GL_ONE_MINUS_CONSTANT_COLOR',
867 'GL_ONE_MINUS_CONSTANT_ALPHA',
872 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
],
919 'GL_COLOR_ATTACHMENT0',
920 'GL_DEPTH_ATTACHMENT',
921 'GL_STENCIL_ATTACHMENT',
924 'BackbufferAttachment': {
939 'GL_PIXEL_PACK_BUFFER',
942 'FrameBufferParameter': {
945 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
946 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
947 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
948 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
954 'GL_PATH_PROJECTION_CHROMIUM',
955 'GL_PATH_MODELVIEW_CHROMIUM',
958 'ProgramParameter': {
963 'GL_VALIDATE_STATUS',
964 'GL_INFO_LOG_LENGTH',
965 'GL_ATTACHED_SHADERS',
966 'GL_ACTIVE_ATTRIBUTES',
967 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
968 'GL_ACTIVE_UNIFORMS',
969 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
972 'QueryObjectParameter': {
975 'GL_QUERY_RESULT_EXT',
976 'GL_QUERY_RESULT_AVAILABLE_EXT',
982 'GL_CURRENT_QUERY_EXT',
988 'GL_ANY_SAMPLES_PASSED_EXT',
989 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
990 'GL_COMMANDS_ISSUED_CHROMIUM',
991 'GL_LATENCY_QUERY_CHROMIUM',
992 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
993 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
994 'GL_COMMANDS_COMPLETED_CHROMIUM',
997 'RenderBufferParameter': {
1000 'GL_RENDERBUFFER_RED_SIZE',
1001 'GL_RENDERBUFFER_GREEN_SIZE',
1002 'GL_RENDERBUFFER_BLUE_SIZE',
1003 'GL_RENDERBUFFER_ALPHA_SIZE',
1004 'GL_RENDERBUFFER_DEPTH_SIZE',
1005 'GL_RENDERBUFFER_STENCIL_SIZE',
1006 'GL_RENDERBUFFER_WIDTH',
1007 'GL_RENDERBUFFER_HEIGHT',
1008 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1011 'SamplerParameter': {
1014 'GL_TEXTURE_MAG_FILTER',
1015 'GL_TEXTURE_MIN_FILTER',
1016 'GL_TEXTURE_MIN_LOD',
1017 'GL_TEXTURE_MAX_LOD',
1018 'GL_TEXTURE_WRAP_S',
1019 'GL_TEXTURE_WRAP_T',
1020 'GL_TEXTURE_WRAP_R',
1021 'GL_TEXTURE_COMPARE_MODE',
1022 'GL_TEXTURE_COMPARE_FUNC',
1025 'GL_GENERATE_MIPMAP',
1028 'ShaderParameter': {
1033 'GL_COMPILE_STATUS',
1034 'GL_INFO_LOG_LENGTH',
1035 'GL_SHADER_SOURCE_LENGTH',
1036 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1039 'ShaderPrecision': {
1056 'GL_SHADING_LANGUAGE_VERSION',
1060 'TextureParameter': {
1063 'GL_TEXTURE_MAG_FILTER',
1064 'GL_TEXTURE_MIN_FILTER',
1065 'GL_TEXTURE_POOL_CHROMIUM',
1066 'GL_TEXTURE_WRAP_S',
1067 'GL_TEXTURE_WRAP_T',
1070 'GL_GENERATE_MIPMAP',
1076 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1077 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1080 'TextureWrapMode': {
1084 'GL_MIRRORED_REPEAT',
1088 'TextureMinFilterMode': {
1093 'GL_NEAREST_MIPMAP_NEAREST',
1094 'GL_LINEAR_MIPMAP_NEAREST',
1095 'GL_NEAREST_MIPMAP_LINEAR',
1096 'GL_LINEAR_MIPMAP_LINEAR',
1099 'TextureMagFilterMode': {
1110 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1113 'VertexAttribute': {
1116 # some enum that the decoder actually passes through to GL needs
1117 # to be the first listed here since it's used in unit tests.
1118 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1119 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1120 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1121 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1122 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1123 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1124 'GL_CURRENT_VERTEX_ATTRIB',
1130 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1136 'GL_GENERATE_MIPMAP_HINT',
1139 'GL_PERSPECTIVE_CORRECTION_HINT',
1153 'GL_PACK_ALIGNMENT',
1154 'GL_UNPACK_ALIGNMENT',
1155 'GL_UNPACK_FLIP_Y_CHROMIUM',
1156 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
1157 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
1160 'GL_PACK_SWAP_BYTES',
1161 'GL_UNPACK_SWAP_BYTES',
1164 'PixelStoreAlignment': {
1177 'ReadPixelFormat': {
1189 'GL_UNSIGNED_SHORT_5_6_5',
1190 'GL_UNSIGNED_SHORT_4_4_4_4',
1191 'GL_UNSIGNED_SHORT_5_5_5_1',
1202 'GL_UNSIGNED_SHORT_5_6_5',
1203 'GL_UNSIGNED_SHORT_4_4_4_4',
1204 'GL_UNSIGNED_SHORT_5_5_5_1',
1211 'RenderBufferFormat': {
1217 'GL_DEPTH_COMPONENT16',
1218 'GL_STENCIL_INDEX8',
1221 'ShaderBinaryFormat': {
1244 'GL_LUMINANCE_ALPHA',
1253 'TextureInternalFormat': {
1258 'GL_LUMINANCE_ALPHA',
1267 'TextureInternalFormatStorage': {
1274 'GL_LUMINANCE8_EXT',
1275 'GL_LUMINANCE8_ALPHA8_EXT',
1280 'ImageInternalFormat': {
1291 'GL_SCANOUT_CHROMIUM'
1294 'ValueBufferTarget': {
1297 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1300 'SubscriptionTarget': {
1303 'GL_MOUSE_POSITION_CHROMIUM',
1306 'VertexAttribType': {
1312 'GL_UNSIGNED_SHORT',
1313 # 'GL_FIXED', // This is not available on Desktop GL.
1322 'is_complete': True,
1330 'VertexAttribSize': {
1345 'is_complete': True,
1354 'type': 'GLboolean',
1355 'is_complete': True,
1366 'GL_GUILTY_CONTEXT_RESET_ARB',
1367 'GL_INNOCENT_CONTEXT_RESET_ARB',
1368 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1373 'is_complete': True,
1375 #TODO(zmo): avoid using the direct number.
1376 '0x9117', # GL_SYNC_GPU_COMMANDS_COMPLETE
1383 'type': 'GLbitfield',
1384 'is_complete': True,
1394 # This table specifies the different pepper interfaces that are supported for
1395 # GL commands. 'dev' is true if it's a dev interface.
1396 _PEPPER_INTERFACES
= [
1397 {'name': '', 'dev': False},
1398 {'name': 'InstancedArrays', 'dev': False},
1399 {'name': 'FramebufferBlit', 'dev': False},
1400 {'name': 'FramebufferMultisample', 'dev': False},
1401 {'name': 'ChromiumEnableFeature', 'dev': False},
1402 {'name': 'ChromiumMapSub', 'dev': False},
1403 {'name': 'Query', 'dev': False},
1404 {'name': 'VertexArrayObject', 'dev': False},
1405 {'name': 'DrawBuffers', 'dev': True},
1408 # A function info object specifies the type and other special data for the
1409 # command that will be generated. A base function info object is generated by
1410 # parsing the "cmd_buffer_functions.txt", one for each function in the
1411 # file. These function info objects can be augmented and their values can be
1412 # overridden by adding an object to the table below.
1414 # Must match function names specified in "cmd_buffer_functions.txt".
1416 # cmd_comment: A comment added to the cmd format.
1417 # type: defines which handler will be used to generate code.
1418 # decoder_func: defines which function to call in the decoder to execute the
1419 # corresponding GL command. If not specified the GL command will
1420 # be called directly.
1421 # gl_test_func: GL function that is expected to be called when testing.
1422 # cmd_args: The arguments to use for the command. This overrides generating
1423 # them based on the GL function arguments.
1424 # gen_cmd: Whether or not this function geneates a command. Default = True.
1425 # data_transfer_methods: Array of methods that are used for transfering the
1426 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1427 # The default is 'immediate' if the command has one pointer
1428 # argument, otherwise 'shm'. One command is generated for each
1429 # transfer method. Affects only commands which are not of type
1430 # 'HandWritten', 'GETn' or 'GLcharN'.
1431 # Note: the command arguments that affect this are the final args,
1432 # taking cmd_args override into consideration.
1433 # impl_func: Whether or not to generate the GLES2Implementation part of this
1435 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1437 # needs_size: If True a data_size field is added to the command.
1438 # count: The number of units per element. For PUTn or PUT types.
1439 # use_count_func: If True the actual data count needs to be computed; the count
1440 # argument specifies the maximum count.
1441 # unit_test: If False no service side unit test will be generated.
1442 # client_test: If False no client side unit test will be generated.
1443 # expectation: If False the unit test will have no expected calls.
1444 # gen_func: Name of function that generates GL resource for corresponding
1446 # states: array of states that get set by this function corresponding to
1447 # the given arguments
1448 # state_flag: name of flag that is set to true when function is called.
1449 # no_gl: no GL function is called.
1450 # valid_args: A dictionary of argument indices to args to use in unit tests
1451 # when they can not be automatically determined.
1452 # pepper_interface: The pepper interface that is used for this extension
1453 # pepper_name: The name of the function as exposed to pepper.
1454 # pepper_args: A string representing the argument list (what would appear in
1455 # C/C++ between the parentheses for the function declaration)
1456 # that the Pepper API expects for this function. Use this only if
1457 # the stable Pepper API differs from the GLES2 argument list.
1458 # invalid_test: False if no invalid test needed.
1459 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1460 # first_element_only: For PUT types, True if only the first element of an
1461 # array is used and we end up calling the single value
1462 # corresponding function. eg. TexParameteriv -> TexParameteri
1463 # extension: Function is an extension to GL and should not be exposed to
1464 # pepper unless pepper_interface is defined.
1465 # extension_flag: Function is an extension and should be enabled only when
1466 # the corresponding feature info flag is enabled. Implies
1467 # 'extension': True.
1468 # not_shared: For GENn types, True if objects can't be shared between contexts
1469 # unsafe: True = no validation is implemented on the service side and the
1470 # command is only available with --enable-unsafe-es3-apis.
1471 # id_mapping: A list of resource type names whose client side IDs need to be
1472 # mapped to service side IDs. This is only used for unsafe APIs.
1476 'decoder_func': 'DoActiveTexture',
1479 'client_test': False,
1481 'AttachShader': {'decoder_func': 'DoAttachShader'},
1482 'BindAttribLocation': {
1484 'data_transfer_methods': ['bucket'],
1489 'decoder_func': 'DoBindBuffer',
1490 'gen_func': 'GenBuffersARB',
1494 'id_mapping': [ 'Buffer' ],
1495 'gen_func': 'GenBuffersARB',
1498 'BindBufferRange': {
1500 'id_mapping': [ 'Buffer' ],
1501 'gen_func': 'GenBuffersARB',
1504 'BindFramebuffer': {
1506 'decoder_func': 'DoBindFramebuffer',
1507 'gl_test_func': 'glBindFramebufferEXT',
1508 'gen_func': 'GenFramebuffersEXT',
1511 'BindRenderbuffer': {
1513 'decoder_func': 'DoBindRenderbuffer',
1514 'gl_test_func': 'glBindRenderbufferEXT',
1515 'gen_func': 'GenRenderbuffersEXT',
1519 'id_mapping': [ 'Sampler' ],
1524 'decoder_func': 'DoBindTexture',
1525 'gen_func': 'GenTextures',
1526 # TODO(gman): remove this once client side caching works.
1527 'client_test': False,
1530 'BindTransformFeedback': {
1532 'id_mapping': [ 'TransformFeedback' ],
1535 'BlitFramebufferCHROMIUM': {
1536 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1538 'extension_flag': 'chromium_framebuffer_multisample',
1539 'pepper_interface': 'FramebufferBlit',
1540 'pepper_name': 'BlitFramebufferEXT',
1541 'defer_reads': True,
1542 'defer_draws': True,
1547 'data_transfer_methods': ['shm'],
1548 'client_test': False,
1552 'client_test': False,
1553 'decoder_func': 'DoBufferSubData',
1554 'data_transfer_methods': ['shm'],
1556 'CheckFramebufferStatus': {
1558 'decoder_func': 'DoCheckFramebufferStatus',
1559 'gl_test_func': 'glCheckFramebufferStatusEXT',
1560 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1561 'result': ['GLenum'],
1564 'decoder_func': 'DoClear',
1565 'defer_draws': True,
1570 'use_count_func': True,
1581 'use_count_func': True,
1590 'state': 'ClearColor',
1594 'state': 'ClearDepthf',
1595 'decoder_func': 'glClearDepth',
1596 'gl_test_func': 'glClearDepth',
1603 'state': 'ColorMask',
1605 'expectation': False,
1607 'ConsumeTextureCHROMIUM': {
1608 'decoder_func': 'DoConsumeTextureCHROMIUM',
1611 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1613 'client_test': False,
1614 'extension': "CHROMIUM_texture_mailbox",
1618 'CopyBufferSubData': {
1621 'CreateAndConsumeTextureCHROMIUM': {
1622 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
1624 'type': 'HandWritten',
1625 'data_transfer_methods': ['immediate'],
1627 'client_test': False,
1628 'extension': "CHROMIUM_texture_mailbox",
1631 'GenValuebuffersCHROMIUM': {
1633 'gl_test_func': 'glGenValuebuffersCHROMIUM',
1634 'resource_type': 'Valuebuffer',
1635 'resource_types': 'Valuebuffers',
1640 'DeleteValuebuffersCHROMIUM': {
1642 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
1643 'resource_type': 'Valuebuffer',
1644 'resource_types': 'Valuebuffers',
1649 'IsValuebufferCHROMIUM': {
1651 'decoder_func': 'DoIsValuebufferCHROMIUM',
1652 'expectation': False,
1656 'BindValuebufferCHROMIUM': {
1658 'decoder_func': 'DoBindValueBufferCHROMIUM',
1659 'gen_func': 'GenValueBuffersCHROMIUM',
1664 'SubscribeValueCHROMIUM': {
1665 'decoder_func': 'DoSubscribeValueCHROMIUM',
1670 'PopulateSubscribedValuesCHROMIUM': {
1671 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
1676 'UniformValuebufferCHROMIUM': {
1677 'decoder_func': 'DoUniformValueBufferCHROMIUM',
1684 'state': 'ClearStencil',
1686 'EnableFeatureCHROMIUM': {
1688 'data_transfer_methods': ['shm'],
1689 'decoder_func': 'DoEnableFeatureCHROMIUM',
1690 'expectation': False,
1691 'cmd_args': 'GLuint bucket_id, GLint* result',
1692 'result': ['GLint'],
1695 'pepper_interface': 'ChromiumEnableFeature',
1697 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1698 'CompressedTexImage2D': {
1700 'data_transfer_methods': ['bucket', 'shm'],
1702 'CompressedTexSubImage2D': {
1704 'data_transfer_methods': ['bucket', 'shm'],
1705 'decoder_func': 'DoCompressedTexSubImage2D',
1708 'decoder_func': 'DoCopyTexImage2D',
1710 'defer_reads': True,
1712 'CopyTexSubImage2D': {
1713 'decoder_func': 'DoCopyTexSubImage2D',
1714 'defer_reads': True,
1716 'CreateImageCHROMIUM': {
1719 'ClientBuffer buffer, GLsizei width, GLsizei height, '
1720 'GLenum internalformat',
1721 'result': ['GLuint'],
1722 'client_test': False,
1724 'expectation': False,
1728 'DestroyImageCHROMIUM': {
1730 'client_test': False,
1735 'CreateGpuMemoryBufferImageCHROMIUM': {
1738 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
1739 'result': ['GLuint'],
1740 'client_test': False,
1742 'expectation': False,
1748 'client_test': False,
1752 'client_test': False,
1756 'state': 'BlendColor',
1759 'type': 'StateSetRGBAlpha',
1760 'state': 'BlendEquation',
1762 '0': 'GL_FUNC_SUBTRACT'
1765 'BlendEquationSeparate': {
1767 'state': 'BlendEquation',
1769 '0': 'GL_FUNC_SUBTRACT'
1773 'type': 'StateSetRGBAlpha',
1774 'state': 'BlendFunc',
1776 'BlendFuncSeparate': {
1778 'state': 'BlendFunc',
1780 'BlendBarrierKHR': {
1781 'gl_test_func': 'glBlendBarrierKHR',
1783 'extension_flag': 'blend_equation_advanced',
1784 'client_test': False,
1786 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1788 'type': 'StateSetFrontBack',
1789 'state': 'StencilFunc',
1791 'StencilFuncSeparate': {
1792 'type': 'StateSetFrontBackSeparate',
1793 'state': 'StencilFunc',
1796 'type': 'StateSetFrontBack',
1797 'state': 'StencilOp',
1802 'StencilOpSeparate': {
1803 'type': 'StateSetFrontBackSeparate',
1804 'state': 'StencilOp',
1810 'type': 'StateSetNamedParameter',
1813 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1814 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1815 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1818 'state': 'LineWidth',
1825 'state': 'PolygonOffset',
1829 'gl_test_func': 'glDeleteBuffersARB',
1830 'resource_type': 'Buffer',
1831 'resource_types': 'Buffers',
1833 'DeleteFramebuffers': {
1835 'gl_test_func': 'glDeleteFramebuffersEXT',
1836 'resource_type': 'Framebuffer',
1837 'resource_types': 'Framebuffers',
1839 'DeleteProgram': { 'type': 'Delete' },
1840 'DeleteRenderbuffers': {
1842 'gl_test_func': 'glDeleteRenderbuffersEXT',
1843 'resource_type': 'Renderbuffer',
1844 'resource_types': 'Renderbuffers',
1848 'resource_type': 'Sampler',
1849 'resource_types': 'Samplers',
1852 'DeleteShader': { 'type': 'Delete' },
1855 'cmd_args': 'GLuint sync',
1856 'resource_type': 'Sync',
1861 'resource_type': 'Texture',
1862 'resource_types': 'Textures',
1864 'DeleteTransformFeedbacks': {
1866 'resource_type': 'TransformFeedback',
1867 'resource_types': 'TransformFeedbacks',
1871 'decoder_func': 'DoDepthRangef',
1872 'gl_test_func': 'glDepthRange',
1876 'state': 'DepthMask',
1878 'expectation': False,
1880 'DetachShader': {'decoder_func': 'DoDetachShader'},
1882 'decoder_func': 'DoDisable',
1884 'client_test': False,
1886 'DisableVertexAttribArray': {
1887 'decoder_func': 'DoDisableVertexAttribArray',
1892 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1893 'defer_draws': True,
1898 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1899 'GLenumIndexType type, GLuint index_offset',
1900 'client_test': False,
1901 'defer_draws': True,
1905 'decoder_func': 'DoEnable',
1907 'client_test': False,
1909 'EnableVertexAttribArray': {
1910 'decoder_func': 'DoEnableVertexAttribArray',
1915 'client_test': False,
1920 'client_test': False,
1921 'decoder_func': 'DoFinish',
1922 'defer_reads': True,
1926 'decoder_func': 'DoFlush',
1928 'FramebufferRenderbuffer': {
1929 'decoder_func': 'DoFramebufferRenderbuffer',
1930 'gl_test_func': 'glFramebufferRenderbufferEXT',
1932 'FramebufferTexture2D': {
1933 'decoder_func': 'DoFramebufferTexture2D',
1934 'gl_test_func': 'glFramebufferTexture2DEXT',
1937 'FramebufferTexture2DMultisampleEXT': {
1938 'decoder_func': 'DoFramebufferTexture2DMultisample',
1939 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1940 'expectation': False,
1942 'extension_flag': 'multisampled_render_to_texture',
1945 'FramebufferTextureLayer': {
1946 'decoder_func': 'DoFramebufferTextureLayer',
1950 'decoder_func': 'DoGenerateMipmap',
1951 'gl_test_func': 'glGenerateMipmapEXT',
1955 'gl_test_func': 'glGenBuffersARB',
1956 'resource_type': 'Buffer',
1957 'resource_types': 'Buffers',
1959 'GenMailboxCHROMIUM': {
1960 'type': 'HandWritten',
1962 'extension': "CHROMIUM_texture_mailbox",
1965 'GenFramebuffers': {
1967 'gl_test_func': 'glGenFramebuffersEXT',
1968 'resource_type': 'Framebuffer',
1969 'resource_types': 'Framebuffers',
1971 'GenRenderbuffers': {
1972 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1973 'resource_type': 'Renderbuffer',
1974 'resource_types': 'Renderbuffers',
1978 'gl_test_func': 'glGenSamplers',
1979 'resource_type': 'Sampler',
1980 'resource_types': 'Samplers',
1985 'gl_test_func': 'glGenTextures',
1986 'resource_type': 'Texture',
1987 'resource_types': 'Textures',
1989 'GenTransformFeedbacks': {
1991 'gl_test_func': 'glGenTransformFeedbacks',
1992 'resource_type': 'TransformFeedback',
1993 'resource_types': 'TransformFeedbacks',
1996 'GetActiveAttrib': {
1998 'data_transfer_methods': ['shm'],
2000 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2008 'GetActiveUniform': {
2010 'data_transfer_methods': ['shm'],
2012 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2020 'GetAttachedShaders': {
2022 'data_transfer_methods': ['shm'],
2023 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2024 'result': ['SizedResult<GLuint>'],
2026 'GetAttribLocation': {
2028 'data_transfer_methods': ['shm'],
2030 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2031 'result': ['GLint'],
2032 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml
2036 'result': ['SizedResult<GLboolean>'],
2037 'decoder_func': 'DoGetBooleanv',
2038 'gl_test_func': 'glGetBooleanv',
2040 'GetBufferParameteriv': {
2042 'result': ['SizedResult<GLint>'],
2043 'decoder_func': 'DoGetBufferParameteriv',
2044 'expectation': False,
2049 'decoder_func': 'GetErrorState()->GetGLError',
2051 'result': ['GLenum'],
2052 'client_test': False,
2056 'result': ['SizedResult<GLfloat>'],
2057 'decoder_func': 'DoGetFloatv',
2058 'gl_test_func': 'glGetFloatv',
2060 'GetFramebufferAttachmentParameteriv': {
2062 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2063 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2064 'result': ['SizedResult<GLint>'],
2068 'result': ['SizedResult<GLint>'],
2069 'decoder_func': 'DoGetIntegerv',
2070 'client_test': False,
2072 'GetInternalformativ': {
2074 'result': ['SizedResult<GLint>'],
2077 'GetMaxValueInBufferCHROMIUM': {
2079 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2080 'result': ['GLuint'],
2082 'client_test': False,
2089 'decoder_func': 'DoGetProgramiv',
2090 'result': ['SizedResult<GLint>'],
2091 'expectation': False,
2093 'GetProgramInfoCHROMIUM': {
2095 'expectation': False,
2099 'client_test': False,
2100 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2102 'uint32_t link_status',
2103 'uint32_t num_attribs',
2104 'uint32_t num_uniforms',
2107 'GetProgramInfoLog': {
2109 'expectation': False,
2111 'GetRenderbufferParameteriv': {
2113 'decoder_func': 'DoGetRenderbufferParameteriv',
2114 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2115 'result': ['SizedResult<GLint>'],
2117 'GetSamplerParameterfv': {
2119 'result': ['SizedResult<GLfloat>'],
2120 'id_mapping': [ 'Sampler' ],
2123 'GetSamplerParameteriv': {
2125 'result': ['SizedResult<GLint>'],
2126 'id_mapping': [ 'Sampler' ],
2131 'decoder_func': 'DoGetShaderiv',
2132 'result': ['SizedResult<GLint>'],
2134 'GetShaderInfoLog': {
2136 'get_len_func': 'glGetShaderiv',
2137 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2140 'GetShaderPrecisionFormat': {
2142 'data_transfer_methods': ['shm'],
2144 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2148 'int32_t min_range',
2149 'int32_t max_range',
2150 'int32_t precision',
2153 'GetShaderSource': {
2155 'get_len_func': 'DoGetShaderiv',
2156 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2158 'client_test': False,
2162 'client_test': False,
2163 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2165 'GetTexParameterfv': {
2167 'decoder_func': 'DoGetTexParameterfv',
2168 'result': ['SizedResult<GLfloat>']
2170 'GetTexParameteriv': {
2172 'decoder_func': 'DoGetTexParameteriv',
2173 'result': ['SizedResult<GLint>']
2175 'GetTranslatedShaderSourceANGLE': {
2177 'get_len_func': 'DoGetShaderiv',
2178 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2184 'data_transfer_methods': ['shm'],
2185 'result': ['SizedResult<GLfloat>'],
2189 'data_transfer_methods': ['shm'],
2190 'result': ['SizedResult<GLint>'],
2192 'GetUniformLocation': {
2194 'data_transfer_methods': ['shm'],
2196 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2197 'result': ['GLint'],
2198 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
2200 'GetVertexAttribfv': {
2202 'result': ['SizedResult<GLfloat>'],
2204 'decoder_func': 'DoGetVertexAttribfv',
2205 'expectation': False,
2206 'client_test': False,
2208 'GetVertexAttribiv': {
2210 'result': ['SizedResult<GLint>'],
2212 'decoder_func': 'DoGetVertexAttribiv',
2213 'expectation': False,
2214 'client_test': False,
2216 'GetVertexAttribPointerv': {
2218 'data_transfer_methods': ['shm'],
2219 'result': ['SizedResult<GLuint>'],
2220 'client_test': False,
2222 'InvalidateFramebuffer': {
2225 'client_test': False,
2229 'InvalidateSubFramebuffer': {
2232 'client_test': False,
2238 'decoder_func': 'DoIsBuffer',
2239 'expectation': False,
2243 'decoder_func': 'DoIsEnabled',
2244 'client_test': False,
2246 'expectation': False,
2250 'decoder_func': 'DoIsFramebuffer',
2251 'expectation': False,
2255 'decoder_func': 'DoIsProgram',
2256 'expectation': False,
2260 'decoder_func': 'DoIsRenderbuffer',
2261 'expectation': False,
2265 'decoder_func': 'DoIsShader',
2266 'expectation': False,
2270 'id_mapping': [ 'Sampler' ],
2271 'expectation': False,
2276 'id_mapping': [ 'Sync' ],
2277 'cmd_args': 'GLuint sync',
2278 'expectation': False,
2283 'decoder_func': 'DoIsTexture',
2284 'expectation': False,
2286 'IsTransformFeedback': {
2288 'id_mapping': [ 'TransformFeedback' ],
2289 'expectation': False,
2293 'decoder_func': 'DoLinkProgram',
2296 'MapBufferCHROMIUM': {
2300 'client_test': False,
2302 'MapBufferSubDataCHROMIUM': {
2306 'client_test': False,
2307 'pepper_interface': 'ChromiumMapSub',
2309 'MapTexSubImage2DCHROMIUM': {
2313 'client_test': False,
2314 'pepper_interface': 'ChromiumMapSub',
2316 'PauseTransformFeedback': {
2319 'PixelStorei': {'type': 'Manual'},
2320 'PostSubBufferCHROMIUM': {
2324 'client_test': False,
2328 'ProduceTextureCHROMIUM': {
2329 'decoder_func': 'DoProduceTextureCHROMIUM',
2332 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2334 'client_test': False,
2335 'extension': "CHROMIUM_texture_mailbox",
2339 'ProduceTextureDirectCHROMIUM': {
2340 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
2343 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2345 'client_test': False,
2346 'extension': "CHROMIUM_texture_mailbox",
2350 'RenderbufferStorage': {
2351 'decoder_func': 'DoRenderbufferStorage',
2352 'gl_test_func': 'glRenderbufferStorageEXT',
2353 'expectation': False,
2355 'RenderbufferStorageMultisampleCHROMIUM': {
2357 '// GL_CHROMIUM_framebuffer_multisample\n',
2358 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
2359 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
2360 'expectation': False,
2362 'extension_flag': 'chromium_framebuffer_multisample',
2363 'pepper_interface': 'FramebufferMultisample',
2364 'pepper_name': 'RenderbufferStorageMultisampleEXT',
2366 'RenderbufferStorageMultisampleEXT': {
2368 '// GL_EXT_multisampled_render_to_texture\n',
2369 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
2370 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
2371 'expectation': False,
2373 'extension_flag': 'multisampled_render_to_texture',
2380 '// ReadPixels has the result separated from the pixel buffer so that\n'
2381 '// it is easier to specify the result going to some specific place\n'
2382 '// that exactly fits the rectangle of pixels.\n',
2384 'data_transfer_methods': ['shm'],
2386 'client_test': False,
2388 'GLint x, GLint y, GLsizei width, GLsizei height, '
2389 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
2390 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
2391 'uint32_t result_shm_id, uint32_t result_shm_offset, '
2393 'result': ['uint32_t'],
2394 'defer_reads': True,
2396 'ReleaseShaderCompiler': {
2397 'decoder_func': 'DoReleaseShaderCompiler',
2400 'ResumeTransformFeedback': {
2403 'SamplerParameterf': {
2407 'id_mapping': [ 'Sampler' ],
2410 'SamplerParameterfv': {
2412 'data_value': 'GL_NEAREST',
2414 'gl_test_func': 'glSamplerParameterf',
2415 'decoder_func': 'DoSamplerParameterfv',
2416 'first_element_only': True,
2417 'id_mapping': [ 'Sampler' ],
2420 'SamplerParameteri': {
2424 'id_mapping': [ 'Sampler' ],
2427 'SamplerParameteriv': {
2429 'data_value': 'GL_NEAREST',
2431 'gl_test_func': 'glSamplerParameteri',
2432 'decoder_func': 'DoSamplerParameteriv',
2433 'first_element_only': True,
2438 'client_test': False,
2442 'decoder_func': 'DoShaderSource',
2443 'data_transfer_methods': ['bucket'],
2444 'client_test': False,
2446 'GLuint shader, const char** str',
2448 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2451 'type': 'StateSetFrontBack',
2452 'state': 'StencilMask',
2454 'expectation': False,
2456 'StencilMaskSeparate': {
2457 'type': 'StateSetFrontBackSeparate',
2458 'state': 'StencilMask',
2460 'expectation': False,
2464 'decoder_func': 'DoSwapBuffers',
2466 'client_test': False,
2472 'decoder_func': 'DoSwapInterval',
2474 'client_test': False,
2480 'data_transfer_methods': ['shm'],
2481 'client_test': False,
2485 'data_transfer_methods': ['shm'],
2486 'client_test': False,
2490 'decoder_func': 'DoTexParameterf',
2496 'decoder_func': 'DoTexParameteri',
2503 'data_value': 'GL_NEAREST',
2505 'decoder_func': 'DoTexParameterfv',
2506 'gl_test_func': 'glTexParameterf',
2507 'first_element_only': True,
2511 'data_value': 'GL_NEAREST',
2513 'decoder_func': 'DoTexParameteriv',
2514 'gl_test_func': 'glTexParameteri',
2515 'first_element_only': True,
2522 'data_transfer_methods': ['shm'],
2523 'client_test': False,
2524 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2525 'GLint xoffset, GLint yoffset, '
2526 'GLsizei width, GLsizei height, '
2527 'GLenumTextureFormat format, GLenumPixelType type, '
2528 'const void* pixels, GLboolean internal'
2532 'data_transfer_methods': ['shm'],
2533 'client_test': False,
2534 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2535 'GLint xoffset, GLint yoffset, GLint zoffset, '
2536 'GLsizei width, GLsizei height, GLsizei depth, '
2537 'GLenumTextureFormat format, GLenumPixelType type, '
2538 'const void* pixels, GLboolean internal',
2541 'Uniform1f': {'type': 'PUTXn', 'count': 1},
2545 'decoder_func': 'DoUniform1fv',
2547 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2551 'decoder_func': 'DoUniform1iv',
2564 'Uniform2i': {'type': 'PUTXn', 'count': 2},
2565 'Uniform2f': {'type': 'PUTXn', 'count': 2},
2569 'decoder_func': 'DoUniform2fv',
2574 'decoder_func': 'DoUniform2iv',
2586 'Uniform3i': {'type': 'PUTXn', 'count': 3},
2587 'Uniform3f': {'type': 'PUTXn', 'count': 3},
2591 'decoder_func': 'DoUniform3fv',
2596 'decoder_func': 'DoUniform3iv',
2608 'Uniform4i': {'type': 'PUTXn', 'count': 4},
2609 'Uniform4f': {'type': 'PUTXn', 'count': 4},
2613 'decoder_func': 'DoUniform4fv',
2618 'decoder_func': 'DoUniform4iv',
2630 'UniformMatrix2fv': {
2633 'decoder_func': 'DoUniformMatrix2fv',
2635 'UniformMatrix2x3fv': {
2640 'UniformMatrix2x4fv': {
2645 'UniformMatrix3fv': {
2648 'decoder_func': 'DoUniformMatrix3fv',
2650 'UniformMatrix3x2fv': {
2655 'UniformMatrix3x4fv': {
2660 'UniformMatrix4fv': {
2663 'decoder_func': 'DoUniformMatrix4fv',
2665 'UniformMatrix4x2fv': {
2670 'UniformMatrix4x3fv': {
2675 'UnmapBufferCHROMIUM': {
2679 'client_test': False,
2681 'UnmapBufferSubDataCHROMIUM': {
2685 'client_test': False,
2686 'pepper_interface': 'ChromiumMapSub',
2688 'UnmapTexSubImage2DCHROMIUM': {
2692 'client_test': False,
2693 'pepper_interface': 'ChromiumMapSub',
2697 'decoder_func': 'DoUseProgram',
2699 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2700 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2701 'VertexAttrib1fv': {
2704 'decoder_func': 'DoVertexAttrib1fv',
2706 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2707 'VertexAttrib2fv': {
2710 'decoder_func': 'DoVertexAttrib2fv',
2712 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2713 'VertexAttrib3fv': {
2716 'decoder_func': 'DoVertexAttrib3fv',
2718 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2719 'VertexAttrib4fv': {
2722 'decoder_func': 'DoVertexAttrib4fv',
2724 'VertexAttribI4i': {
2727 'VertexAttribI4iv': {
2732 'VertexAttribI4ui': {
2735 'VertexAttribI4uiv': {
2740 'VertexAttribIPointer': {
2742 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2743 'GLenumVertexAttribType type, GLsizei stride, '
2745 'client_test': False,
2748 'VertexAttribPointer': {
2750 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2751 'GLenumVertexAttribType type, GLboolean normalized, '
2752 'GLsizei stride, GLuint offset',
2753 'client_test': False,
2760 'decoder_func': 'DoViewport',
2769 'GetRequestableExtensionsCHROMIUM': {
2772 'cmd_args': 'uint32_t bucket_id',
2776 'RequestExtensionCHROMIUM': {
2779 'client_test': False,
2780 'cmd_args': 'uint32_t bucket_id',
2784 'RateLimitOffscreenContextCHROMIUM': {
2788 'client_test': False,
2790 'CreateStreamTextureCHROMIUM': {
2791 'type': 'HandWritten',
2797 'TexImageIOSurface2DCHROMIUM': {
2798 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2803 'CopyTextureCHROMIUM': {
2804 'decoder_func': 'DoCopyTextureCHROMIUM',
2809 'TexStorage2DEXT': {
2812 'decoder_func': 'DoTexStorage2DEXT',
2814 'DrawArraysInstancedANGLE': {
2816 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2817 'GLsizei primcount',
2820 'pepper_interface': 'InstancedArrays',
2821 'defer_draws': True,
2825 'decoder_func': 'DoDrawBuffersEXT',
2827 'client_test': False,
2829 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
2832 'pepper_interface': 'DrawBuffers',
2834 'DrawElementsInstancedANGLE': {
2836 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2837 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2840 'client_test': False,
2841 'pepper_interface': 'InstancedArrays',
2842 'defer_draws': True,
2844 'VertexAttribDivisorANGLE': {
2846 'cmd_args': 'GLuint index, GLuint divisor',
2849 'pepper_interface': 'InstancedArrays',
2853 'gl_test_func': 'glGenQueriesARB',
2854 'resource_type': 'Query',
2855 'resource_types': 'Queries',
2857 'pepper_interface': 'Query',
2858 'not_shared': 'True',
2860 'DeleteQueriesEXT': {
2862 'gl_test_func': 'glDeleteQueriesARB',
2863 'resource_type': 'Query',
2864 'resource_types': 'Queries',
2866 'pepper_interface': 'Query',
2870 'client_test': False,
2871 'pepper_interface': 'Query',
2875 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2876 'data_transfer_methods': ['shm'],
2877 'gl_test_func': 'glBeginQuery',
2878 'pepper_interface': 'Query',
2880 'BeginTransformFeedback': {
2885 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2886 'gl_test_func': 'glEndnQuery',
2887 'client_test': False,
2888 'pepper_interface': 'Query',
2890 'EndTransformFeedback': {
2895 'client_test': False,
2896 'gl_test_func': 'glGetQueryiv',
2897 'pepper_interface': 'Query',
2899 'GetQueryObjectuivEXT': {
2901 'client_test': False,
2902 'gl_test_func': 'glGetQueryObjectuiv',
2903 'pepper_interface': 'Query',
2905 'BindUniformLocationCHROMIUM': {
2908 'data_transfer_methods': ['bucket'],
2910 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2912 'InsertEventMarkerEXT': {
2914 'decoder_func': 'DoInsertEventMarkerEXT',
2915 'expectation': False,
2918 'PushGroupMarkerEXT': {
2920 'decoder_func': 'DoPushGroupMarkerEXT',
2921 'expectation': False,
2924 'PopGroupMarkerEXT': {
2925 'decoder_func': 'DoPopGroupMarkerEXT',
2926 'expectation': False,
2931 'GenVertexArraysOES': {
2934 'gl_test_func': 'glGenVertexArraysOES',
2935 'resource_type': 'VertexArray',
2936 'resource_types': 'VertexArrays',
2938 'pepper_interface': 'VertexArrayObject',
2940 'BindVertexArrayOES': {
2943 'gl_test_func': 'glBindVertexArrayOES',
2944 'decoder_func': 'DoBindVertexArrayOES',
2945 'gen_func': 'GenVertexArraysOES',
2947 'client_test': False,
2948 'pepper_interface': 'VertexArrayObject',
2950 'DeleteVertexArraysOES': {
2953 'gl_test_func': 'glDeleteVertexArraysOES',
2954 'resource_type': 'VertexArray',
2955 'resource_types': 'VertexArrays',
2957 'pepper_interface': 'VertexArrayObject',
2959 'IsVertexArrayOES': {
2962 'gl_test_func': 'glIsVertexArrayOES',
2963 'decoder_func': 'DoIsVertexArrayOES',
2964 'expectation': False,
2966 'pepper_interface': 'VertexArrayObject',
2968 'BindTexImage2DCHROMIUM': {
2969 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2974 'ReleaseTexImage2DCHROMIUM': {
2975 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2980 'ShallowFinishCHROMIUM': {
2985 'client_test': False,
2987 'ShallowFlushCHROMIUM': {
2992 'client_test': False,
2994 'TraceBeginCHROMIUM': {
2997 'client_test': False,
2998 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3002 'TraceEndCHROMIUM': {
3004 'client_test': False,
3005 'decoder_func': 'DoTraceEndCHROMIUM',
3010 'AsyncTexImage2DCHROMIUM': {
3012 'data_transfer_methods': ['shm'],
3013 'client_test': False,
3014 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3015 'GLintTextureInternalFormat internalformat, '
3016 'GLsizei width, GLsizei height, '
3017 'GLintTextureBorder border, '
3018 'GLenumTextureFormat format, GLenumPixelType type, '
3019 'const void* pixels, '
3020 'uint32_t async_upload_token, '
3025 'AsyncTexSubImage2DCHROMIUM': {
3027 'data_transfer_methods': ['shm'],
3028 'client_test': False,
3029 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3030 'GLint xoffset, GLint yoffset, '
3031 'GLsizei width, GLsizei height, '
3032 'GLenumTextureFormat format, GLenumPixelType type, '
3033 'const void* data, '
3034 'uint32_t async_upload_token, '
3039 'WaitAsyncTexImage2DCHROMIUM': {
3041 'client_test': False,
3045 'WaitAllAsyncTexImage2DCHROMIUM': {
3047 'client_test': False,
3051 'DiscardFramebufferEXT': {
3054 'decoder_func': 'DoDiscardFramebufferEXT',
3056 'client_test': False,
3057 'extension_flag': 'ext_discard_framebuffer',
3059 'LoseContextCHROMIUM': {
3060 'decoder_func': 'DoLoseContextCHROMIUM',
3065 'InsertSyncPointCHROMIUM': {
3066 'type': 'HandWritten',
3068 'extension': "CHROMIUM_sync_point",
3071 'WaitSyncPointCHROMIUM': {
3074 'extension': "CHROMIUM_sync_point",
3078 'DiscardBackbufferCHROMIUM': {
3084 'ScheduleOverlayPlaneCHROMIUM': {
3088 'client_test': False,
3092 'MatrixLoadfCHROMIUM': {
3095 'data_type': 'GLfloat',
3096 'decoder_func': 'DoMatrixLoadfCHROMIUM',
3097 'gl_test_func': 'glMatrixLoadfEXT',
3100 'extension_flag': 'chromium_path_rendering',
3102 'MatrixLoadIdentityCHROMIUM': {
3103 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
3104 'gl_test_func': 'glMatrixLoadIdentityEXT',
3107 'extension_flag': 'chromium_path_rendering',
3112 def Grouper(n
, iterable
, fillvalue
=None):
3113 """Collect data into fixed-length chunks or blocks"""
3114 args
= [iter(iterable
)] * n
3115 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
3118 def SplitWords(input_string
):
3119 """Transforms a input_string into a list of lower-case components.
3122 input_string: the input string.
3125 a list of lower-case words.
3127 if input_string
.find('_') > -1:
3128 # 'some_TEXT_' -> 'some text'
3129 return input_string
.replace('_', ' ').strip().lower().split()
3131 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
3133 # look for capitalization to cut input_strings
3134 # 'SomeText' -> 'Some Text'
3135 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
3136 # 'Vector3' -> 'Vector 3'
3137 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
3138 return input_string
.lower().split()
3142 """Makes a lower-case identifier from words.
3145 words: a list of lower-case words.
3148 the lower-case identifier.
3150 return '_'.join(words
)
3153 def ToUnderscore(input_string
):
3154 """converts CamelCase to camel_case."""
3155 words
= SplitWords(input_string
)
3158 def CachedStateName(item
):
3159 if item
.get('cached', False):
3160 return 'cached_' + item
['name']
3163 def ToGLExtensionString(extension_flag
):
3164 """Returns GL-type extension string of a extension flag."""
3165 if extension_flag
== "oes_compressed_etc1_rgb8_texture":
3166 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
3168 uppercase_words
= [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
3169 'egl', 'atc', 'etc1', 'angle']
3170 parts
= extension_flag
.split('_')
3172 [part
.upper() if part
in uppercase_words
else part
for part
in parts
])
3174 def ToCamelCase(input_string
):
3175 """converts ABC_underscore_case to ABCUnderscoreCase."""
3176 return ''.join(w
[0].upper() + w
[1:] for w
in input_string
.split('_'))
3178 def GetGLGetTypeConversion(result_type
, value_type
, value
):
3179 """Makes a gl compatible type conversion string for accessing state variables.
3181 Useful when accessing state variables through glGetXXX calls.
3182 glGet documetation (for example, the manual pages):
3183 [...] If glGetIntegerv is called, [...] most floating-point values are
3184 rounded to the nearest integer value. [...]
3187 result_type: the gl type to be obtained
3188 value_type: the GL type of the state variable
3189 value: the name of the state variable
3192 String that converts the state variable to desired GL type according to GL
3196 if result_type
== 'GLint':
3197 if value_type
== 'GLfloat':
3198 return 'static_cast<GLint>(round(%s))' % value
3199 return 'static_cast<%s>(%s)' % (result_type
, value
)
3201 class CWriter(object):
3202 """Writes to a file formatting it for Google's style guidelines."""
3204 def __init__(self
, filename
):
3205 self
.filename
= filename
3208 def Write(self
, string
):
3209 """Writes a string to a file spliting if it's > 80 characters."""
3210 lines
= string
.splitlines()
3211 num_lines
= len(lines
)
3212 for ii
in range(0, num_lines
):
3213 self
.content
.append(lines
[ii
])
3214 if ii
< (num_lines
- 1) or string
[-1] == '\n':
3215 self
.content
.append('\n')
3218 """Close the file."""
3219 content
= "".join(self
.content
)
3221 if os
.path
.exists(self
.filename
):
3222 old_file
= open(self
.filename
, "rb");
3223 old_content
= old_file
.read()
3225 if content
== old_content
:
3228 file = open(self
.filename
, "wb")
3233 class CHeaderWriter(CWriter
):
3234 """Writes a C Header file."""
3236 _non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
3238 def __init__(self
, filename
, file_comment
= None):
3239 CWriter
.__init
__(self
, filename
)
3241 base
= os
.path
.abspath(filename
)
3242 while os
.path
.basename(base
) != 'src':
3243 new_base
= os
.path
.dirname(base
)
3244 assert new_base
!= base
# Prevent infinite loop.
3247 hpath
= os
.path
.relpath(filename
, base
)
3248 self
.guard
= self
._non
_alnum
_re
.sub('_', hpath
).upper() + '_'
3250 self
.Write(_LICENSE
)
3251 self
.Write(_DO_NOT_EDIT_WARNING
)
3252 if not file_comment
== None:
3253 self
.Write(file_comment
)
3254 self
.Write("#ifndef %s\n" % self
.guard
)
3255 self
.Write("#define %s\n\n" % self
.guard
)
3258 self
.Write("#endif // %s\n\n" % self
.guard
)
3261 class TypeHandler(object):
3262 """This class emits code for a particular type of function."""
3264 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
3269 def InitFunction(self
, func
):
3270 """Add or adjust anything type specific for this function."""
3271 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
3272 func
.AddCmdArg(DataSizeArgument('data_size'))
3274 def NeedsDataTransferFunction(self
, func
):
3275 """Overriden from TypeHandler."""
3276 return func
.num_pointer_args
>= 1
3278 def WriteStruct(self
, func
, file):
3279 """Writes a structure that matches the arguments to a function."""
3280 comment
= func
.GetInfo('cmd_comment')
3281 if not comment
== None:
3283 file.Write("struct %s {\n" % func
.name
)
3284 file.Write(" typedef %s ValueType;\n" % func
.name
)
3285 file.Write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
3286 func
.WriteCmdArgFlag(file)
3287 func
.WriteCmdFlag(file)
3289 result
= func
.GetInfo('result')
3290 if not result
== None:
3291 if len(result
) == 1:
3292 file.Write(" typedef %s Result;\n\n" % result
[0])
3294 file.Write(" struct Result {\n")
3296 file.Write(" %s;\n" % line
)
3297 file.Write(" };\n\n")
3299 func
.WriteCmdComputeSize(file)
3300 func
.WriteCmdSetHeader(file)
3301 func
.WriteCmdInit(file)
3302 func
.WriteCmdSet(file)
3304 file.Write(" gpu::CommandHeader header;\n")
3305 args
= func
.GetCmdArgs()
3307 file.Write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
3309 consts
= func
.GetCmdConstants()
3310 for const
in consts
:
3311 file.Write(" static const %s %s = %s;\n" %
3312 (const
.cmd_type
, const
.name
, const
.GetConstantValue()))
3317 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
3318 file.Write("static_assert(sizeof(%s) == %d,\n" % (func
.name
, size
))
3319 file.Write(" \"size of %s should be %d\");\n" %
3321 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func
.name
)
3322 file.Write(" \"offset of %s header should be 0\");\n" %
3324 offset
= _SIZE_OF_COMMAND_HEADER
3326 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
3327 (func
.name
, arg
.name
, offset
))
3328 file.Write(" \"offset of %s %s should be %d\");\n" %
3329 (func
.name
, arg
.name
, offset
))
3330 offset
+= _SIZE_OF_UINT32
3331 if not result
== None and len(result
) > 1:
3334 parts
= line
.split()
3337 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
3338 "offset of %(cmd_name)s Result %(field_name)s should be "
3341 file.Write((check
.strip() + "\n") % {
3342 'cmd_name': func
.name
,
3346 offset
+= _SIZE_OF_UINT32
3349 def WriteHandlerImplementation(self
, func
, file):
3350 """Writes the handler implementation for this command."""
3351 if func
.IsUnsafe() and func
.GetInfo('id_mapping'):
3352 code_no_gen
= """ if (!group_->Get%(type)sServiceId(%(var)s, &%(var)s)) {
3353 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3354 return error::kNoError;
3357 code_gen
= """ if (!group_->Get%(type)sServiceId(%(var)s, &%(var)s)) {
3358 if (!group_->bind_generates_resource()) {
3360 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3361 return error::kNoError;
3363 GLuint client_id = %(var)s;
3364 gl%(gen_func)s(1, &%(var)s);
3365 Create%(type)s(client_id, %(var)s);
3368 gen_func
= func
.GetInfo('gen_func')
3369 for id_type
in func
.GetInfo('id_mapping'):
3370 if gen_func
and id_type
in gen_func
:
3371 file.Write(code_gen
% { 'type': id_type
,
3372 'var': id_type
.lower(),
3373 'func': func
.GetGLFunctionName(),
3374 'gen_func': gen_func
})
3376 file.Write(code_no_gen
% { 'type': id_type
,
3377 'var': id_type
.lower(),
3378 'func': func
.GetGLFunctionName() })
3379 file.Write(" %s(%s);\n" %
3380 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3382 def WriteCmdSizeTest(self
, func
, file):
3383 """Writes the size test for a command."""
3384 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3386 def WriteFormatTest(self
, func
, file):
3387 """Writes a format test for a command."""
3388 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
3389 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
3390 (func
.name
, func
.name
))
3391 file.Write(" void* next_cmd = cmd.Set(\n")
3393 args
= func
.GetCmdArgs()
3394 for value
, arg
in enumerate(args
):
3395 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
3397 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
3399 file.Write(" cmd.header.command);\n")
3400 func
.type_handler
.WriteCmdSizeTest(func
, file)
3401 for value
, arg
in enumerate(args
):
3402 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
3403 (arg
.type, value
+ 11, arg
.name
))
3404 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
3405 file.Write(" next_cmd, sizeof(cmd));\n")
3409 def WriteImmediateFormatTest(self
, func
, file):
3410 """Writes a format test for an immediate version of a command."""
3413 def WriteBucketFormatTest(self
, func
, file):
3414 """Writes a format test for a bucket version of a command."""
3417 def WriteGetDataSizeCode(self
, func
, file):
3418 """Writes the code to set data_size used in validation"""
3421 def WriteImmediateCmdSizeTest(self
, func
, file):
3422 """Writes a size test for an immediate version of a command."""
3423 file.Write(" // TODO(gman): Compute correct size.\n")
3424 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3426 def __WriteIdMapping(self
, func
, file):
3427 """Writes client side / service side ID mapping."""
3428 if not func
.IsUnsafe() or not func
.GetInfo('id_mapping'):
3430 for id_type
in func
.GetInfo('id_mapping'):
3431 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
3432 (id_type
, id_type
.lower(), id_type
.lower()))
3434 def WriteImmediateHandlerImplementation (self
, func
, file):
3435 """Writes the handler impl for the immediate version of a command."""
3436 self
.__WriteIdMapping
(func
, file)
3437 file.Write(" %s(%s);\n" %
3438 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3440 def WriteBucketHandlerImplementation (self
, func
, file):
3441 """Writes the handler impl for the bucket version of a command."""
3442 self
.__WriteIdMapping
(func
, file)
3443 file.Write(" %s(%s);\n" %
3444 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3446 def WriteServiceHandlerFunctionHeader(self
, func
, file):
3447 """Writes function header for service implementation handlers."""
3448 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
3449 uint32_t immediate_data_size, const void* cmd_data) {
3450 """ % {'name': func
.name
})
3452 file.Write("""if (!unsafe_es3_apis_enabled())
3453 return error::kUnknownCommand;
3455 file.Write("""const gles2::cmds::%(name)s& c =
3456 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
3458 """ % {'name': func
.name
})
3460 def WriteServiceImplementation(self
, func
, file):
3461 """Writes the service implementation for a command."""
3462 self
.WriteServiceHandlerFunctionHeader(func
, file)
3463 self
.WriteHandlerExtensionCheck(func
, file)
3464 self
.WriteHandlerDeferReadWrite(func
, file);
3465 if len(func
.GetOriginalArgs()) > 0:
3466 last_arg
= func
.GetLastOriginalArg()
3467 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
3468 for arg
in all_but_last_arg
:
3469 arg
.WriteGetCode(file)
3470 self
.WriteGetDataSizeCode(func
, file)
3471 last_arg
.WriteGetCode(file)
3472 func
.WriteHandlerValidation(file)
3473 func
.WriteHandlerImplementation(file)
3474 file.Write(" return error::kNoError;\n")
3478 def WriteImmediateServiceImplementation(self
, func
, file):
3479 """Writes the service implementation for an immediate version of command."""
3480 self
.WriteServiceHandlerFunctionHeader(func
, file)
3481 self
.WriteHandlerExtensionCheck(func
, file)
3482 self
.WriteHandlerDeferReadWrite(func
, file);
3483 for arg
in func
.GetOriginalArgs():
3485 self
.WriteGetDataSizeCode(func
, file)
3486 arg
.WriteGetCode(file)
3487 func
.WriteHandlerValidation(file)
3488 func
.WriteHandlerImplementation(file)
3489 file.Write(" return error::kNoError;\n")
3493 def WriteBucketServiceImplementation(self
, func
, file):
3494 """Writes the service implementation for a bucket version of command."""
3495 self
.WriteServiceHandlerFunctionHeader(func
, file)
3496 self
.WriteHandlerExtensionCheck(func
, file)
3497 self
.WriteHandlerDeferReadWrite(func
, file);
3498 for arg
in func
.GetCmdArgs():
3499 arg
.WriteGetCode(file)
3500 func
.WriteHandlerValidation(file)
3501 func
.WriteHandlerImplementation(file)
3502 file.Write(" return error::kNoError;\n")
3506 def WriteHandlerExtensionCheck(self
, func
, file):
3507 if func
.GetInfo('extension_flag'):
3508 file.Write(" if (!features().%s) {\n" % func
.GetInfo('extension_flag'))
3509 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
3510 " \"function not available\");\n" % func
.original_name
)
3511 file.Write(" return error::kNoError;")
3512 file.Write(" }\n\n")
3514 def WriteHandlerDeferReadWrite(self
, func
, file):
3515 """Writes the code to handle deferring reads or writes."""
3516 defer_draws
= func
.GetInfo('defer_draws')
3517 defer_reads
= func
.GetInfo('defer_reads')
3518 if defer_draws
or defer_reads
:
3519 file.Write(" error::Error error;\n")
3521 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
3522 file.Write(" if (error != error::kNoError)\n")
3523 file.Write(" return error;\n")
3525 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
3526 file.Write(" if (error != error::kNoError)\n")
3527 file.Write(" return error;\n")
3529 def WriteValidUnitTest(self
, func
, file, test
, *extras
):
3530 """Writes a valid unit test for the service implementation."""
3531 if func
.GetInfo('expectation') == False:
3532 test
= self
._remove
_expected
_call
_re
.sub('', test
)
3535 arg
.GetValidArg(func
) \
3536 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
3539 arg
.GetValidGLArg(func
) \
3540 for arg
in func
.GetOriginalArgs()
3542 gl_func_name
= func
.GetGLTestFunctionName()
3545 'gl_func_name': gl_func_name
,
3546 'args': ", ".join(arg_strings
),
3547 'gl_args': ", ".join(gl_arg_strings
),
3549 for extra
in extras
:
3552 while (old_test
!= test
):
3555 file.Write(test
% vars)
3557 def WriteInvalidUnitTest(self
, func
, file, test
, *extras
):
3558 """Writes an invalid unit test for the service implementation."""
3561 for invalid_arg_index
, invalid_arg
in enumerate(func
.GetOriginalArgs()):
3562 # Service implementation does not test constants, as they are not part of
3563 # the call in the service side.
3564 if invalid_arg
.IsConstant():
3567 num_invalid_values
= invalid_arg
.GetNumInvalidValues(func
)
3568 for value_index
in range(0, num_invalid_values
):
3570 parse_result
= "kNoError"
3572 for arg
in func
.GetOriginalArgs():
3573 if arg
.IsConstant():
3575 if invalid_arg
is arg
:
3576 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
3579 arg_string
= arg
.GetValidArg(func
)
3580 arg_strings
.append(arg_string
)
3582 for arg
in func
.GetOriginalArgs():
3583 gl_arg_strings
.append("_")
3584 gl_func_name
= func
.GetGLTestFunctionName()
3586 if not gl_error
== None:
3587 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
3591 'arg_index': invalid_arg_index
,
3592 'value_index': value_index
,
3593 'gl_func_name': gl_func_name
,
3594 'args': ", ".join(arg_strings
),
3595 'all_but_last_args': ", ".join(arg_strings
[:-1]),
3596 'gl_args': ", ".join(gl_arg_strings
),
3597 'parse_result': parse_result
,
3598 'gl_error_test': gl_error_test
,
3600 for extra
in extras
:
3602 file.Write(test
% vars)
3604 def WriteServiceUnitTest(self
, func
, file, *extras
):
3605 """Writes the service unit test for a command."""
3607 if func
.name
== 'Enable':
3609 TEST_P(%(test_name)s, %(name)sValidArgs) {
3610 SetupExpectationsForEnableDisable(%(gl_args)s, true);
3611 SpecializedSetup<cmds::%(name)s, 0>(true);
3613 cmd.Init(%(args)s);"""
3614 elif func
.name
== 'Disable':
3616 TEST_P(%(test_name)s, %(name)sValidArgs) {
3617 SetupExpectationsForEnableDisable(%(gl_args)s, false);
3618 SpecializedSetup<cmds::%(name)s, 0>(true);
3620 cmd.Init(%(args)s);"""
3623 TEST_P(%(test_name)s, %(name)sValidArgs) {
3624 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3625 SpecializedSetup<cmds::%(name)s, 0>(true);
3627 cmd.Init(%(args)s);"""
3630 decoder_->set_unsafe_es3_apis_enabled(true);
3631 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3632 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3633 decoder_->set_unsafe_es3_apis_enabled(false);
3634 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
3639 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3640 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3643 self
.WriteValidUnitTest(func
, file, valid_test
, *extras
)
3645 if not func
.IsUnsafe():
3647 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3648 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3649 SpecializedSetup<cmds::%(name)s, 0>(false);
3652 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3655 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
3657 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
3658 """Writes the service unit test for an immediate command."""
3659 file.Write("// TODO(gman): %s\n" % func
.name
)
3661 def WriteImmediateValidationCode(self
, func
, file):
3662 """Writes the validation code for an immediate version of a command."""
3665 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
3666 """Writes the service unit test for a bucket command."""
3667 file.Write("// TODO(gman): %s\n" % func
.name
)
3669 def WriteBucketValidationCode(self
, func
, file):
3670 """Writes the validation code for a bucket version of a command."""
3671 file.Write("// TODO(gman): %s\n" % func
.name
)
3673 def WriteGLES2ImplementationDeclaration(self
, func
, file):
3674 """Writes the GLES2 Implemention declaration."""
3675 impl_decl
= func
.GetInfo('impl_decl')
3676 if impl_decl
== None or impl_decl
== True:
3677 file.Write("%s %s(%s) override;\n" %
3678 (func
.return_type
, func
.original_name
,
3679 func
.MakeTypedOriginalArgString("")))
3682 def WriteGLES2CLibImplementation(self
, func
, file):
3683 file.Write("%s GLES2%s(%s) {\n" %
3684 (func
.return_type
, func
.name
,
3685 func
.MakeTypedOriginalArgString("")))
3686 result_string
= "return "
3687 if func
.return_type
== "void":
3689 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3690 (result_string
, func
.original_name
,
3691 func
.MakeOriginalArgString("")))
3694 def WriteGLES2Header(self
, func
, file):
3695 """Writes a re-write macro for GLES"""
3696 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
3698 def WriteClientGLCallLog(self
, func
, file):
3699 """Writes a logging macro for the client side code."""
3701 if len(func
.GetOriginalArgs()):
3704 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3705 (func
.original_name
, comma
, func
.MakeLogArgString()))
3707 def WriteClientGLReturnLog(self
, func
, file):
3708 """Writes the return value logging code."""
3709 if func
.return_type
!= "void":
3710 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3712 def WriteGLES2ImplementationHeader(self
, func
, file):
3713 """Writes the GLES2 Implemention."""
3714 self
.WriteGLES2ImplementationDeclaration(func
, file)
3716 def WriteGLES2TraceImplementationHeader(self
, func
, file):
3717 """Writes the GLES2 Trace Implemention header."""
3718 file.Write("%s %s(%s) override;\n" %
3719 (func
.return_type
, func
.original_name
,
3720 func
.MakeTypedOriginalArgString("")))
3722 def WriteGLES2TraceImplementation(self
, func
, file):
3723 """Writes the GLES2 Trace Implemention."""
3724 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3725 (func
.return_type
, func
.original_name
,
3726 func
.MakeTypedOriginalArgString("")))
3727 result_string
= "return "
3728 if func
.return_type
== "void":
3730 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3732 file.Write(" %sgl_->%s(%s);\n" %
3733 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
3737 def WriteGLES2Implementation(self
, func
, file):
3738 """Writes the GLES2 Implemention."""
3739 impl_func
= func
.GetInfo('impl_func')
3740 impl_decl
= func
.GetInfo('impl_decl')
3741 gen_cmd
= func
.GetInfo('gen_cmd')
3742 if (func
.can_auto_generate
and
3743 (impl_func
== None or impl_func
== True) and
3744 (impl_decl
== None or impl_decl
== True) and
3745 (gen_cmd
== None or gen_cmd
== True)):
3746 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3747 (func
.return_type
, func
.original_name
,
3748 func
.MakeTypedOriginalArgString("")))
3749 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3750 self
.WriteClientGLCallLog(func
, file)
3751 func
.WriteDestinationInitalizationValidation(file)
3752 for arg
in func
.GetOriginalArgs():
3753 arg
.WriteClientSideValidationCode(file, func
)
3754 file.Write(" helper_->%s(%s);\n" %
3755 (func
.name
, func
.MakeHelperArgString("")))
3756 file.Write(" CheckGLError();\n")
3757 self
.WriteClientGLReturnLog(func
, file)
3761 def WriteGLES2InterfaceHeader(self
, func
, file):
3762 """Writes the GLES2 Interface."""
3763 file.Write("virtual %s %s(%s) = 0;\n" %
3764 (func
.return_type
, func
.original_name
,
3765 func
.MakeTypedOriginalArgString("")))
3767 def WriteGLES2InterfaceStub(self
, func
, file):
3768 """Writes the GLES2 Interface stub declaration."""
3769 file.Write("%s %s(%s) override;\n" %
3770 (func
.return_type
, func
.original_name
,
3771 func
.MakeTypedOriginalArgString("")))
3773 def WriteGLES2InterfaceStubImpl(self
, func
, file):
3774 """Writes the GLES2 Interface stub declaration."""
3775 args
= func
.GetOriginalArgs()
3776 arg_string
= ", ".join(
3777 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
3778 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3779 (func
.return_type
, func
.original_name
, arg_string
))
3780 if func
.return_type
!= "void":
3781 file.Write(" return 0;\n")
3784 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3785 """Writes the GLES2 Implemention unit test."""
3786 client_test
= func
.GetInfo('client_test')
3787 if (func
.can_auto_generate
and
3788 (client_test
== None or client_test
== True)):
3790 TEST_F(GLES2ImplementationTest, %(name)s) {
3795 expected.cmd.Init(%(cmd_args)s);
3797 gl_->%(name)s(%(args)s);
3798 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3802 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
3806 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
3811 'args': ", ".join(gl_arg_strings
),
3812 'cmd_args': ", ".join(cmd_arg_strings
),
3815 # Test constants for invalid values, as they are not tested by the
3817 constants
= [arg
for arg
in func
.GetOriginalArgs() if arg
.IsConstant()]
3820 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
3821 gl_->%(name)s(%(args)s);
3822 EXPECT_TRUE(NoCommandsWritten());
3823 EXPECT_EQ(%(gl_error)s, CheckError());
3826 for invalid_arg
in constants
:
3828 invalid
= invalid_arg
.GetInvalidArg(func
)
3829 for arg
in func
.GetOriginalArgs():
3830 if arg
is invalid_arg
:
3831 gl_arg_strings
.append(invalid
[0])
3833 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
3837 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
3838 'args': ", ".join(gl_arg_strings
),
3839 'gl_error': invalid
[2],
3842 if client_test
!= False:
3843 file.Write("// TODO: Implement unit test for %s\n" % func
.name
)
3845 def WriteDestinationInitalizationValidation(self
, func
, file):
3846 """Writes the client side destintion initialization validation."""
3847 for arg
in func
.GetOriginalArgs():
3848 arg
.WriteDestinationInitalizationValidation(file, func
)
3850 def WriteTraceEvent(self
, func
, file):
3851 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3854 def WriteImmediateCmdComputeSize(self
, func
, file):
3855 """Writes the size computation code for the immediate version of a cmd."""
3856 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
3857 file.Write(" return static_cast<uint32_t>(\n")
3858 file.Write(" sizeof(ValueType) + // NOLINT\n")
3859 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3863 def WriteImmediateCmdSetHeader(self
, func
, file):
3864 """Writes the SetHeader function for the immediate version of a cmd."""
3865 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
3866 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3870 def WriteImmediateCmdInit(self
, func
, file):
3871 """Writes the Init function for the immediate version of a command."""
3872 raise NotImplementedError(func
.name
)
3874 def WriteImmediateCmdSet(self
, func
, file):
3875 """Writes the Set function for the immediate version of a command."""
3876 raise NotImplementedError(func
.name
)
3878 def WriteCmdHelper(self
, func
, file):
3879 """Writes the cmd helper definition for a cmd."""
3880 code
= """ void %(name)s(%(typed_args)s) {
3881 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3890 "typed_args": func
.MakeTypedCmdArgString(""),
3891 "args": func
.MakeCmdArgString(""),
3894 def WriteImmediateCmdHelper(self
, func
, file):
3895 """Writes the cmd helper definition for the immediate version of a cmd."""
3896 code
= """ void %(name)s(%(typed_args)s) {
3897 const uint32_t s = 0; // TODO(gman): compute correct size
3898 gles2::cmds::%(name)s* c =
3899 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3908 "typed_args": func
.MakeTypedCmdArgString(""),
3909 "args": func
.MakeCmdArgString(""),
3913 class StateSetHandler(TypeHandler
):
3914 """Handler for commands that simply set state."""
3917 TypeHandler
.__init
__(self
)
3919 def WriteHandlerImplementation(self
, func
, file):
3920 """Overrriden from TypeHandler."""
3921 state_name
= func
.GetInfo('state')
3922 state
= _STATES
[state_name
]
3923 states
= state
['states']
3924 args
= func
.GetOriginalArgs()
3925 for ndx
,item
in enumerate(states
):
3927 if 'range_checks' in item
:
3928 for range_check
in item
['range_checks']:
3929 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
3930 if 'nan_check' in item
:
3931 # Drivers might generate an INVALID_VALUE error when a value is set
3932 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
3933 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
3934 # Make this behavior consistent within Chromium, and avoid leaking GL
3935 # errors by generating the error in the command buffer instead of
3936 # letting the GL driver generate it.
3937 code
.append("base::IsNaN(%s)" % args
[ndx
].name
)
3939 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3941 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3942 ' "%s", "%s out of range");\n' %
3943 (func
.name
, args
[ndx
].name
))
3944 file.Write(" return error::kNoError;\n")
3947 for ndx
,item
in enumerate(states
):
3948 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
3949 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3950 for ndx
,item
in enumerate(states
):
3951 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
3952 if 'state_flag' in state
:
3953 file.Write(" %s = true;\n" % state
['state_flag'])
3954 if not func
.GetInfo("no_gl"):
3955 for ndx
,item
in enumerate(states
):
3956 if item
.get('cached', False):
3957 file.Write(" state_.%s = %s;\n" %
3958 (CachedStateName(item
), args
[ndx
].name
))
3959 file.Write(" %s(%s);\n" %
3960 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3963 def WriteServiceUnitTest(self
, func
, file, *extras
):
3964 """Overrriden from TypeHandler."""
3965 TypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
3966 state_name
= func
.GetInfo('state')
3967 state
= _STATES
[state_name
]
3968 states
= state
['states']
3969 for ndx
,item
in enumerate(states
):
3970 if 'range_checks' in item
:
3971 for check_ndx
, range_check
in enumerate(item
['range_checks']):
3973 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3974 SpecializedSetup<cmds::%(name)s, 0>(false);
3977 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3978 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3983 arg
.GetValidArg(func
) \
3984 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
3987 arg_strings
[ndx
] = range_check
['test_value']
3991 'check_ndx': check_ndx
,
3992 'args': ", ".join(arg_strings
),
3994 for extra
in extras
:
3996 file.Write(valid_test
% vars)
3997 if 'nan_check' in item
:
3999 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
4000 SpecializedSetup<cmds::%(name)s, 0>(false);
4003 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4004 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4009 arg
.GetValidArg(func
) \
4010 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4013 arg_strings
[ndx
] = 'nanf("")'
4017 'args': ", ".join(arg_strings
),
4019 for extra
in extras
:
4021 file.Write(valid_test
% vars)
4024 class StateSetRGBAlphaHandler(TypeHandler
):
4025 """Handler for commands that simply set state that have rgb/alpha."""
4028 TypeHandler
.__init
__(self
)
4030 def WriteHandlerImplementation(self
, func
, file):
4031 """Overrriden from TypeHandler."""
4032 state_name
= func
.GetInfo('state')
4033 state
= _STATES
[state_name
]
4034 states
= state
['states']
4035 args
= func
.GetOriginalArgs()
4036 num_args
= len(args
)
4038 for ndx
,item
in enumerate(states
):
4039 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
4040 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4041 for ndx
, item
in enumerate(states
):
4042 file.Write(" state_.%s = %s;\n" %
4043 (item
['name'], args
[ndx
% num_args
].name
))
4044 if 'state_flag' in state
:
4045 file.Write(" %s = true;\n" % state
['state_flag'])
4046 if not func
.GetInfo("no_gl"):
4047 file.Write(" %s(%s);\n" %
4048 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4052 class StateSetFrontBackSeparateHandler(TypeHandler
):
4053 """Handler for commands that simply set state that have front/back."""
4056 TypeHandler
.__init
__(self
)
4058 def WriteHandlerImplementation(self
, func
, file):
4059 """Overrriden from TypeHandler."""
4060 state_name
= func
.GetInfo('state')
4061 state
= _STATES
[state_name
]
4062 states
= state
['states']
4063 args
= func
.GetOriginalArgs()
4065 num_args
= len(args
)
4066 file.Write(" bool changed = false;\n")
4067 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
4068 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4069 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
4071 for ndx
, item
in enumerate(group
):
4072 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
4073 file.Write(" changed |= %s;\n" % " ||\n ".join(code
))
4075 file.Write(" if (changed) {\n")
4076 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
4077 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4078 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
4079 for ndx
, item
in enumerate(group
):
4080 file.Write(" state_.%s = %s;\n" %
4081 (item
['name'], args
[ndx
+ 1].name
))
4083 if 'state_flag' in state
:
4084 file.Write(" %s = true;\n" % state
['state_flag'])
4085 if not func
.GetInfo("no_gl"):
4086 file.Write(" %s(%s);\n" %
4087 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4091 class StateSetFrontBackHandler(TypeHandler
):
4092 """Handler for commands that simply set state that set both front/back."""
4095 TypeHandler
.__init
__(self
)
4097 def WriteHandlerImplementation(self
, func
, file):
4098 """Overrriden from TypeHandler."""
4099 state_name
= func
.GetInfo('state')
4100 state
= _STATES
[state_name
]
4101 states
= state
['states']
4102 args
= func
.GetOriginalArgs()
4103 num_args
= len(args
)
4105 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
4106 for ndx
, item
in enumerate(group
):
4107 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
4108 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4109 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
4110 for ndx
, item
in enumerate(group
):
4111 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
4112 if 'state_flag' in state
:
4113 file.Write(" %s = true;\n" % state
['state_flag'])
4114 if not func
.GetInfo("no_gl"):
4115 file.Write(" %s(%s);\n" %
4116 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4120 class StateSetNamedParameter(TypeHandler
):
4121 """Handler for commands that set a state chosen with an enum parameter."""
4124 TypeHandler
.__init
__(self
)
4126 def WriteHandlerImplementation(self
, func
, file):
4127 """Overridden from TypeHandler."""
4128 state_name
= func
.GetInfo('state')
4129 state
= _STATES
[state_name
]
4130 states
= state
['states']
4131 args
= func
.GetOriginalArgs()
4132 num_args
= len(args
)
4133 assert num_args
== 2
4134 file.Write(" switch (%s) {\n" % args
[0].name
)
4135 for state
in states
:
4136 file.Write(" case %s:\n" % state
['enum'])
4137 file.Write(" if (state_.%s != %s) {\n" %
4138 (state
['name'], args
[1].name
))
4139 file.Write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
4140 if not func
.GetInfo("no_gl"):
4141 file.Write(" %s(%s);\n" %
4142 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4144 file.Write(" break;\n")
4145 file.Write(" default:\n")
4146 file.Write(" NOTREACHED();\n")
4150 class CustomHandler(TypeHandler
):
4151 """Handler for commands that are auto-generated but require minor tweaks."""
4154 TypeHandler
.__init
__(self
)
4156 def WriteServiceImplementation(self
, func
, file):
4157 """Overrriden from TypeHandler."""
4160 def WriteImmediateServiceImplementation(self
, func
, file):
4161 """Overrriden from TypeHandler."""
4164 def WriteBucketServiceImplementation(self
, func
, file):
4165 """Overrriden from TypeHandler."""
4168 def WriteServiceUnitTest(self
, func
, file, *extras
):
4169 """Overrriden from TypeHandler."""
4170 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4172 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4173 """Overrriden from TypeHandler."""
4174 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4176 def WriteImmediateCmdGetTotalSize(self
, func
, file):
4177 """Overrriden from TypeHandler."""
4179 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
4181 def WriteImmediateCmdInit(self
, func
, file):
4182 """Overrriden from TypeHandler."""
4183 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
4184 self
.WriteImmediateCmdGetTotalSize(func
, file)
4185 file.Write(" SetHeader(total_size);\n")
4186 args
= func
.GetCmdArgs()
4188 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4192 def WriteImmediateCmdSet(self
, func
, file):
4193 """Overrriden from TypeHandler."""
4194 copy_args
= func
.MakeCmdArgString("_", False)
4195 file.Write(" void* Set(void* cmd%s) {\n" %
4196 func
.MakeTypedCmdArgString("_", True))
4197 self
.WriteImmediateCmdGetTotalSize(func
, file)
4198 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
4199 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4200 "cmd, total_size);\n")
4205 class TodoHandler(CustomHandler
):
4206 """Handle for commands that are not yet implemented."""
4208 def NeedsDataTransferFunction(self
, func
):
4209 """Overriden from TypeHandler."""
4212 def WriteImmediateFormatTest(self
, func
, file):
4213 """Overrriden from TypeHandler."""
4216 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4217 """Overrriden from TypeHandler."""
4220 def WriteGLES2Implementation(self
, func
, file):
4221 """Overrriden from TypeHandler."""
4222 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4223 (func
.return_type
, func
.original_name
,
4224 func
.MakeTypedOriginalArgString("")))
4225 file.Write(" // TODO: for now this is a no-op\n")
4228 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4230 if func
.return_type
!= "void":
4231 file.Write(" return 0;\n")
4235 def WriteServiceImplementation(self
, func
, file):
4236 """Overrriden from TypeHandler."""
4237 self
.WriteServiceHandlerFunctionHeader(func
, file)
4238 file.Write(" // TODO: for now this is a no-op\n")
4240 " LOCAL_SET_GL_ERROR("
4241 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4243 file.Write(" return error::kNoError;\n")
4248 class HandWrittenHandler(CustomHandler
):
4249 """Handler for comands where everything must be written by hand."""
4251 def InitFunction(self
, func
):
4252 """Add or adjust anything type specific for this function."""
4253 CustomHandler
.InitFunction(self
, func
)
4254 func
.can_auto_generate
= False
4256 def NeedsDataTransferFunction(self
, func
):
4257 """Overriden from TypeHandler."""
4258 # If specified explicitly, force the data transfer method.
4259 if func
.GetInfo('data_transfer_methods'):
4263 def WriteStruct(self
, func
, file):
4264 """Overrriden from TypeHandler."""
4267 def WriteDocs(self
, func
, file):
4268 """Overrriden from TypeHandler."""
4271 def WriteServiceUnitTest(self
, func
, file, *extras
):
4272 """Overrriden from TypeHandler."""
4273 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4275 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4276 """Overrriden from TypeHandler."""
4277 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4279 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
4280 """Overrriden from TypeHandler."""
4281 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4283 def WriteServiceImplementation(self
, func
, file):
4284 """Overrriden from TypeHandler."""
4287 def WriteImmediateServiceImplementation(self
, func
, file):
4288 """Overrriden from TypeHandler."""
4291 def WriteBucketServiceImplementation(self
, func
, file):
4292 """Overrriden from TypeHandler."""
4295 def WriteImmediateCmdHelper(self
, func
, file):
4296 """Overrriden from TypeHandler."""
4299 def WriteCmdHelper(self
, func
, file):
4300 """Overrriden from TypeHandler."""
4303 def WriteFormatTest(self
, func
, file):
4304 """Overrriden from TypeHandler."""
4305 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
4307 def WriteImmediateFormatTest(self
, func
, file):
4308 """Overrriden from TypeHandler."""
4309 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
4311 def WriteBucketFormatTest(self
, func
, file):
4312 """Overrriden from TypeHandler."""
4313 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
4317 class ManualHandler(CustomHandler
):
4318 """Handler for commands who's handlers must be written by hand."""
4321 CustomHandler
.__init
__(self
)
4323 def InitFunction(self
, func
):
4324 """Overrriden from TypeHandler."""
4325 if (func
.name
== 'CompressedTexImage2DBucket'):
4326 func
.cmd_args
= func
.cmd_args
[:-1]
4327 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
4329 CustomHandler
.InitFunction(self
, func
)
4331 def WriteServiceImplementation(self
, func
, file):
4332 """Overrriden from TypeHandler."""
4335 def WriteBucketServiceImplementation(self
, func
, file):
4336 """Overrriden from TypeHandler."""
4339 def WriteServiceUnitTest(self
, func
, file, *extras
):
4340 """Overrriden from TypeHandler."""
4341 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4343 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4344 """Overrriden from TypeHandler."""
4345 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4347 def WriteImmediateServiceImplementation(self
, func
, file):
4348 """Overrriden from TypeHandler."""
4351 def WriteImmediateFormatTest(self
, func
, file):
4352 """Overrriden from TypeHandler."""
4353 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
4355 def WriteGLES2Implementation(self
, func
, file):
4356 """Overrriden from TypeHandler."""
4357 if func
.GetInfo('impl_func'):
4358 super(ManualHandler
, self
).WriteGLES2Implementation(func
, file)
4360 def WriteGLES2ImplementationHeader(self
, func
, file):
4361 """Overrriden from TypeHandler."""
4362 file.Write("%s %s(%s) override;\n" %
4363 (func
.return_type
, func
.original_name
,
4364 func
.MakeTypedOriginalArgString("")))
4367 def WriteImmediateCmdGetTotalSize(self
, func
, file):
4368 """Overrriden from TypeHandler."""
4369 # TODO(gman): Move this data to _FUNCTION_INFO?
4370 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, file)
4373 class DataHandler(TypeHandler
):
4374 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
4375 glCompressedTexImage2D, glCompressedTexImageSub2D."""
4377 TypeHandler
.__init
__(self
)
4379 def InitFunction(self
, func
):
4380 """Overrriden from TypeHandler."""
4381 if func
.name
== 'CompressedTexSubImage2DBucket':
4382 func
.cmd_args
= func
.cmd_args
[:-1]
4383 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
4385 def WriteGetDataSizeCode(self
, func
, file):
4386 """Overrriden from TypeHandler."""
4387 # TODO(gman): Move this data to _FUNCTION_INFO?
4389 if name
.endswith("Immediate"):
4391 if name
== 'BufferData' or name
== 'BufferSubData':
4392 file.Write(" uint32_t data_size = size;\n")
4393 elif (name
== 'CompressedTexImage2D' or
4394 name
== 'CompressedTexSubImage2D'):
4395 file.Write(" uint32_t data_size = imageSize;\n")
4396 elif (name
== 'CompressedTexSubImage2DBucket'):
4397 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
4398 file.Write(" uint32_t data_size = bucket->size();\n")
4399 file.Write(" GLsizei imageSize = data_size;\n")
4400 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
4401 code
= """ uint32_t data_size;
4402 if (!GLES2Util::ComputeImageDataSize(
4403 width, height, format, type, unpack_alignment_, &data_size)) {
4404 return error::kOutOfBounds;
4410 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
4412 def WriteImmediateCmdGetTotalSize(self
, func
, file):
4413 """Overrriden from TypeHandler."""
4416 def WriteImmediateCmdSizeTest(self
, func
, file):
4417 """Overrriden from TypeHandler."""
4418 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
4420 def WriteImmediateCmdInit(self
, func
, file):
4421 """Overrriden from TypeHandler."""
4422 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
4423 self
.WriteImmediateCmdGetTotalSize(func
, file)
4424 file.Write(" SetHeader(total_size);\n")
4425 args
= func
.GetCmdArgs()
4427 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4431 def WriteImmediateCmdSet(self
, func
, file):
4432 """Overrriden from TypeHandler."""
4433 copy_args
= func
.MakeCmdArgString("_", False)
4434 file.Write(" void* Set(void* cmd%s) {\n" %
4435 func
.MakeTypedCmdArgString("_", True))
4436 self
.WriteImmediateCmdGetTotalSize(func
, file)
4437 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
4438 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4439 "cmd, total_size);\n")
4443 def WriteImmediateFormatTest(self
, func
, file):
4444 """Overrriden from TypeHandler."""
4445 # TODO(gman): Remove this exception.
4446 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
4449 def WriteServiceUnitTest(self
, func
, file, *extras
):
4450 """Overrriden from TypeHandler."""
4451 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4453 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4454 """Overrriden from TypeHandler."""
4455 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4457 def WriteBucketServiceImplementation(self
, func
, file):
4458 """Overrriden from TypeHandler."""
4459 if not func
.name
== 'CompressedTexSubImage2DBucket':
4460 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, file)
4463 class BindHandler(TypeHandler
):
4464 """Handler for glBind___ type functions."""
4467 TypeHandler
.__init
__(self
)
4469 def WriteServiceUnitTest(self
, func
, file, *extras
):
4470 """Overrriden from TypeHandler."""
4472 if len(func
.GetOriginalArgs()) == 1:
4474 TEST_P(%(test_name)s, %(name)sValidArgs) {
4475 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4476 SpecializedSetup<cmds::%(name)s, 0>(true);
4478 cmd.Init(%(args)s);"""
4481 decoder_->set_unsafe_es3_apis_enabled(true);
4482 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4483 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4484 decoder_->set_unsafe_es3_apis_enabled(false);
4485 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4490 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4491 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4494 if func
.GetInfo("gen_func"):
4496 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
4497 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
4498 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
4499 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4500 SpecializedSetup<cmds::%(name)s, 0>(true);
4502 cmd.Init(kNewClientId);
4503 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4504 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4505 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4508 self
.WriteValidUnitTest(func
, file, valid_test
, {
4509 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
4510 'gl_gen_func_name': func
.GetInfo("gen_func"),
4514 TEST_P(%(test_name)s, %(name)sValidArgs) {
4515 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4516 SpecializedSetup<cmds::%(name)s, 0>(true);
4518 cmd.Init(%(args)s);"""
4521 decoder_->set_unsafe_es3_apis_enabled(true);
4522 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4523 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4524 decoder_->set_unsafe_es3_apis_enabled(false);
4525 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4530 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4531 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4534 if func
.GetInfo("gen_func"):
4536 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
4538 %(gl_func_name)s(%(gl_args_with_new_id)s));
4539 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
4540 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4541 SpecializedSetup<cmds::%(name)s, 0>(true);
4543 cmd.Init(%(args_with_new_id)s);"""
4546 decoder_->set_unsafe_es3_apis_enabled(true);
4547 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4548 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4549 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4550 decoder_->set_unsafe_es3_apis_enabled(false);
4551 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4556 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4557 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4558 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4562 gl_args_with_new_id
= []
4563 args_with_new_id
= []
4564 for arg
in func
.GetOriginalArgs():
4565 if hasattr(arg
, 'resource_type'):
4566 gl_args_with_new_id
.append('kNewServiceId')
4567 args_with_new_id
.append('kNewClientId')
4569 gl_args_with_new_id
.append(arg
.GetValidGLArg(func
))
4570 args_with_new_id
.append(arg
.GetValidArg(func
))
4571 self
.WriteValidUnitTest(func
, file, valid_test
, {
4572 'args_with_new_id': ", ".join(args_with_new_id
),
4573 'gl_args_with_new_id': ", ".join(gl_args_with_new_id
),
4574 'resource_type': func
.GetResourceIdArg().resource_type
,
4575 'gl_gen_func_name': func
.GetInfo("gen_func"),
4579 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4580 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4581 SpecializedSetup<cmds::%(name)s, 0>(false);
4584 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4587 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
4589 def WriteGLES2Implementation(self
, func
, file):
4590 """Writes the GLES2 Implemention."""
4592 impl_func
= func
.GetInfo('impl_func')
4593 impl_decl
= func
.GetInfo('impl_decl')
4595 if (func
.can_auto_generate
and
4596 (impl_func
== None or impl_func
== True) and
4597 (impl_decl
== None or impl_decl
== True)):
4599 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4600 (func
.return_type
, func
.original_name
,
4601 func
.MakeTypedOriginalArgString("")))
4602 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4603 func
.WriteDestinationInitalizationValidation(file)
4604 self
.WriteClientGLCallLog(func
, file)
4605 for arg
in func
.GetOriginalArgs():
4606 arg
.WriteClientSideValidationCode(file, func
)
4608 code
= """ if (Is%(type)sReservedId(%(id)s)) {
4609 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
4612 %(name)sHelper(%(arg_string)s);
4617 name_arg
= func
.GetResourceIdArg()
4620 'arg_string': func
.MakeOriginalArgString(""),
4621 'id': name_arg
.name
,
4622 'type': name_arg
.resource_type
,
4623 'lc_type': name_arg
.resource_type
.lower(),
4626 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4627 """Overrriden from TypeHandler."""
4628 client_test
= func
.GetInfo('client_test')
4629 if client_test
== False:
4632 TEST_F(GLES2ImplementationTest, %(name)s) {
4637 expected.cmd.Init(%(cmd_args)s);
4639 gl_->%(name)s(%(args)s);
4640 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
4641 if not func
.IsUnsafe():
4644 gl_->%(name)s(%(args)s);
4645 EXPECT_TRUE(NoCommandsWritten());"""
4650 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
4653 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
4658 'args': ", ".join(gl_arg_strings
),
4659 'cmd_args': ", ".join(cmd_arg_strings
),
4663 class GENnHandler(TypeHandler
):
4664 """Handler for glGen___ type functions."""
4667 TypeHandler
.__init
__(self
)
4669 def InitFunction(self
, func
):
4670 """Overrriden from TypeHandler."""
4673 def WriteGetDataSizeCode(self
, func
, file):
4674 """Overrriden from TypeHandler."""
4675 code
= """ uint32_t data_size;
4676 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4677 return error::kOutOfBounds;
4682 def WriteHandlerImplementation (self
, func
, file):
4683 """Overrriden from TypeHandler."""
4684 file.Write(" if (!%sHelper(n, %s)) {\n"
4685 " return error::kInvalidArguments;\n"
4687 (func
.name
, func
.GetLastOriginalArg().name
))
4689 def WriteImmediateHandlerImplementation(self
, func
, file):
4690 """Overrriden from TypeHandler."""
4692 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
4693 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
4694 return error::kInvalidArguments;
4697 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
4698 gl%(func_name)s(n, service_ids.get());
4699 for (GLsizei ii = 0; ii < n; ++ii) {
4700 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
4702 """ % { 'func_name': func
.original_name
,
4703 'last_arg_name': func
.GetLastOriginalArg().name
,
4704 'resource_name': func
.GetInfo('resource_type') })
4706 file.Write(" if (!%sHelper(n, %s)) {\n"
4707 " return error::kInvalidArguments;\n"
4709 (func
.original_name
, func
.GetLastOriginalArg().name
))
4711 def WriteGLES2Implementation(self
, func
, file):
4712 """Overrriden from TypeHandler."""
4713 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
4714 for (GLsizei i = 0; i < n; ++i) {
4715 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4717 });""" % func
.GetOriginalArgs()[1].name
)
4719 'log_code': log_code
,
4720 'return_type': func
.return_type
,
4721 'name': func
.original_name
,
4722 'typed_args': func
.MakeTypedOriginalArgString(""),
4723 'args': func
.MakeOriginalArgString(""),
4724 'resource_types': func
.GetInfo('resource_types'),
4725 'count_name': func
.GetOriginalArgs()[0].name
,
4728 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4730 func
.WriteDestinationInitalizationValidation(file)
4731 self
.WriteClientGLCallLog(func
, file)
4732 for arg
in func
.GetOriginalArgs():
4733 arg
.WriteClientSideValidationCode(file, func
)
4734 not_shared
= func
.GetInfo('not_shared')
4738 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
4739 for (GLsizei ii = 0; ii < n; ++ii)
4740 %s[ii] = id_allocator->AllocateID();""" %
4741 (func
.GetInfo('resource_types'), func
.GetOriginalArgs()[1].name
))
4743 alloc_code
= (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
4744 MakeIds(this, 0, %(args)s);""" % args
)
4745 args
['alloc_code'] = alloc_code
4747 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
4749 %(name)sHelper(%(args)s);
4750 helper_->%(name)sImmediate(%(args)s);
4751 if (share_group_->bind_generates_resource())
4752 helper_->CommandBufferHelper::Flush();
4758 file.Write(code
% args
)
4760 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4761 """Overrriden from TypeHandler."""
4763 TEST_F(GLES2ImplementationTest, %(name)s) {
4764 GLuint ids[2] = { 0, };
4766 cmds::%(name)sImmediate gen;
4770 expected.gen.Init(arraysize(ids), &ids[0]);
4771 expected.data[0] = k%(types)sStartId;
4772 expected.data[1] = k%(types)sStartId + 1;
4773 gl_->%(name)s(arraysize(ids), &ids[0]);
4774 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4775 EXPECT_EQ(k%(types)sStartId, ids[0]);
4776 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
4781 'types': func
.GetInfo('resource_types'),
4784 def WriteServiceUnitTest(self
, func
, file, *extras
):
4785 """Overrriden from TypeHandler."""
4787 TEST_P(%(test_name)s, %(name)sValidArgs) {
4788 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4789 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4790 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
4791 SpecializedSetup<cmds::%(name)s, 0>(true);
4794 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4795 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
4799 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
4800 EXPECT_EQ(kNewServiceId, service_id)
4805 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
4808 self
.WriteValidUnitTest(func
, file, valid_test
, {
4809 'resource_name': func
.GetInfo('resource_type'),
4812 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4813 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4814 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4815 SpecializedSetup<cmds::%(name)s, 0>(false);
4818 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
4821 self
.WriteValidUnitTest(func
, file, invalid_test
, {
4822 'resource_name': func
.GetInfo('resource_type').lower(),
4825 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4826 """Overrriden from TypeHandler."""
4828 TEST_P(%(test_name)s, %(name)sValidArgs) {
4829 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4830 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4831 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4832 GLuint temp = kNewClientId;
4833 SpecializedSetup<cmds::%(name)s, 0>(true);"""
4836 decoder_->set_unsafe_es3_apis_enabled(true);"""
4838 cmd->Init(1, &temp);
4839 EXPECT_EQ(error::kNoError,
4840 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4841 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
4845 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
4846 EXPECT_EQ(kNewServiceId, service_id);
4847 decoder_->set_unsafe_es3_apis_enabled(false);
4848 EXPECT_EQ(error::kUnknownCommand,
4849 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4854 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4857 self
.WriteValidUnitTest(func
, file, valid_test
, {
4858 'resource_name': func
.GetInfo('resource_type'),
4861 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4862 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4863 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4864 SpecializedSetup<cmds::%(name)s, 0>(false);
4865 cmd->Init(1, &client_%(resource_name)s_id_);"""
4868 decoder_->set_unsafe_es3_apis_enabled(true);
4869 EXPECT_EQ(error::kInvalidArguments,
4870 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4871 decoder_->set_unsafe_es3_apis_enabled(false);
4876 EXPECT_EQ(error::kInvalidArguments,
4877 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4880 self
.WriteValidUnitTest(func
, file, invalid_test
, {
4881 'resource_name': func
.GetInfo('resource_type').lower(),
4884 def WriteImmediateCmdComputeSize(self
, func
, file):
4885 """Overrriden from TypeHandler."""
4886 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
4888 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
4891 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
4892 file.Write(" return static_cast<uint32_t>(\n")
4893 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4897 def WriteImmediateCmdSetHeader(self
, func
, file):
4898 """Overrriden from TypeHandler."""
4899 file.Write(" void SetHeader(GLsizei n) {\n")
4900 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4904 def WriteImmediateCmdInit(self
, func
, file):
4905 """Overrriden from TypeHandler."""
4906 last_arg
= func
.GetLastOriginalArg()
4907 file.Write(" void Init(%s, %s _%s) {\n" %
4908 (func
.MakeTypedCmdArgString("_"),
4909 last_arg
.type, last_arg
.name
))
4910 file.Write(" SetHeader(_n);\n")
4911 args
= func
.GetCmdArgs()
4913 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4914 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4915 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
4919 def WriteImmediateCmdSet(self
, func
, file):
4920 """Overrriden from TypeHandler."""
4921 last_arg
= func
.GetLastOriginalArg()
4922 copy_args
= func
.MakeCmdArgString("_", False)
4923 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4924 (func
.MakeTypedCmdArgString("_", True),
4925 last_arg
.type, last_arg
.name
))
4926 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4927 (copy_args
, last_arg
.name
))
4928 file.Write(" const uint32_t size = ComputeSize(_n);\n")
4929 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4934 def WriteImmediateCmdHelper(self
, func
, file):
4935 """Overrriden from TypeHandler."""
4936 code
= """ void %(name)s(%(typed_args)s) {
4937 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
4938 gles2::cmds::%(name)s* c =
4939 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4948 "typed_args": func
.MakeTypedOriginalArgString(""),
4949 "args": func
.MakeOriginalArgString(""),
4952 def WriteImmediateFormatTest(self
, func
, file):
4953 """Overrriden from TypeHandler."""
4954 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4955 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4956 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4957 (func
.name
, func
.name
))
4958 file.Write(" void* next_cmd = cmd.Set(\n")
4959 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4960 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4962 file.Write(" cmd.header.command);\n")
4963 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4964 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4965 file.Write(" cmd.header.size * 4u);\n")
4966 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4967 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4968 file.Write(" next_cmd, sizeof(cmd) +\n")
4969 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4970 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4975 class CreateHandler(TypeHandler
):
4976 """Handler for glCreate___ type functions."""
4979 TypeHandler
.__init
__(self
)
4981 def InitFunction(self
, func
):
4982 """Overrriden from TypeHandler."""
4983 func
.AddCmdArg(Argument("client_id", 'uint32_t'))
4985 def __GetResourceType(self
, func
):
4986 if func
.return_type
== "GLsync":
4989 return func
.name
[6:] # Create*
4991 def WriteServiceUnitTest(self
, func
, file, *extras
):
4992 """Overrriden from TypeHandler."""
4994 TEST_P(%(test_name)s, %(name)sValidArgs) {
4995 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4996 .WillOnce(Return(%(const_service_id)s));
4997 SpecializedSetup<cmds::%(name)s, 0>(true);
4999 cmd.Init(%(args)s%(comma)skNewClientId);"""
5002 decoder_->set_unsafe_es3_apis_enabled(true);"""
5004 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5005 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5008 %(return_type)s service_id = 0;
5009 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
5010 EXPECT_EQ(%(const_service_id)s, service_id);
5011 decoder_->set_unsafe_es3_apis_enabled(false);
5012 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5017 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
5022 for arg
in func
.GetOriginalArgs():
5023 if not arg
.IsConstant():
5027 if func
.return_type
== 'GLsync':
5028 id_type_cast
= ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
5029 "<GLsync>(kNewServiceId);\n ")
5030 const_service_id
= "kNewServiceIdGLuint"
5033 const_service_id
= "kNewServiceId"
5034 self
.WriteValidUnitTest(func
, file, valid_test
, {
5036 'resource_type': self
.__GetResourceType
(func
),
5037 'return_type': func
.return_type
,
5038 'id_type_cast': id_type_cast
,
5039 'const_service_id': const_service_id
,
5042 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5043 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5044 SpecializedSetup<cmds::%(name)s, 0>(false);
5046 cmd.Init(%(args)s%(comma)skNewClientId);
5047 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
5050 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5054 def WriteHandlerImplementation (self
, func
, file):
5055 """Overrriden from TypeHandler."""
5057 code
= """ uint32_t client_id = c.client_id;
5058 %(return_type)s service_id = 0;
5059 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
5060 return error::kInvalidArguments;
5062 service_id = %(gl_func_name)s(%(gl_args)s);
5064 group_->Add%(resource_name)sId(client_id, service_id);
5068 code
= """ uint32_t client_id = c.client_id;
5069 if (Get%(resource_name)s(client_id)) {
5070 return error::kInvalidArguments;
5072 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
5074 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
5078 'resource_name': self
.__GetResourceType
(func
),
5079 'return_type': func
.return_type
,
5080 'gl_func_name': func
.GetGLFunctionName(),
5081 'gl_args': func
.MakeOriginalArgString(""),
5082 'gl_args_with_comma': func
.MakeOriginalArgString("", True) })
5084 def WriteGLES2Implementation(self
, func
, file):
5085 """Overrriden from TypeHandler."""
5086 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5087 (func
.return_type
, func
.original_name
,
5088 func
.MakeTypedOriginalArgString("")))
5089 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5090 func
.WriteDestinationInitalizationValidation(file)
5091 self
.WriteClientGLCallLog(func
, file)
5092 for arg
in func
.GetOriginalArgs():
5093 arg
.WriteClientSideValidationCode(file, func
)
5094 file.Write(" GLuint client_id;\n")
5095 if func
.return_type
== "GLsync":
5097 " GetIdHandler(id_namespaces::kSyncs)->\n")
5100 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
5101 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
5102 file.Write(" helper_->%s(%s);\n" %
5103 (func
.name
, func
.MakeCmdArgString("")))
5104 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
5105 file.Write(" CheckGLError();\n")
5106 if func
.return_type
== "GLsync":
5107 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
5109 file.Write(" return client_id;\n")
5114 class DeleteHandler(TypeHandler
):
5115 """Handler for glDelete___ single resource type functions."""
5118 TypeHandler
.__init
__(self
)
5120 def WriteServiceImplementation(self
, func
, file):
5121 """Overrriden from TypeHandler."""
5123 TypeHandler
.WriteServiceImplementation(self
, func
, file)
5124 # HandleDeleteShader and HandleDeleteProgram are manually written.
5127 def WriteGLES2Implementation(self
, func
, file):
5128 """Overrriden from TypeHandler."""
5129 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5130 (func
.return_type
, func
.original_name
,
5131 func
.MakeTypedOriginalArgString("")))
5132 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5133 func
.WriteDestinationInitalizationValidation(file)
5134 self
.WriteClientGLCallLog(func
, file)
5135 for arg
in func
.GetOriginalArgs():
5136 arg
.WriteClientSideValidationCode(file, func
)
5138 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
5139 file.Write(" %sHelper(%s);\n" %
5140 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
5141 file.Write(" CheckGLError();\n")
5145 def WriteHandlerImplementation (self
, func
, file):
5146 """Overrriden from TypeHandler."""
5147 assert len(func
.GetOriginalArgs()) == 1
5148 arg
= func
.GetOriginalArgs()[0]
5150 file.Write(""" %(arg_type)s service_id = 0;
5151 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
5152 glDelete%(resource_type)s(service_id);
5153 group_->Remove%(resource_type)sId(%(arg_name)s);
5156 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
5158 """ % { 'resource_type': func
.GetInfo('resource_type'),
5159 'arg_name': arg
.name
,
5160 'arg_type': arg
.type,
5161 'func_name': func
.original_name
})
5163 file.Write(" %sHelper(%s);\n" % (func
.original_name
, arg
.name
))
5165 class DELnHandler(TypeHandler
):
5166 """Handler for glDelete___ type functions."""
5169 TypeHandler
.__init
__(self
)
5171 def WriteGetDataSizeCode(self
, func
, file):
5172 """Overrriden from TypeHandler."""
5173 code
= """ uint32_t data_size;
5174 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5175 return error::kOutOfBounds;
5180 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5181 """Overrriden from TypeHandler."""
5183 TEST_F(GLES2ImplementationTest, %(name)s) {
5184 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
5186 cmds::%(name)sImmediate del;
5190 expected.del.Init(arraysize(ids), &ids[0]);
5191 expected.data[0] = k%(types)sStartId;
5192 expected.data[1] = k%(types)sStartId + 1;
5193 gl_->%(name)s(arraysize(ids), &ids[0]);
5194 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5199 'types': func
.GetInfo('resource_types'),
5202 def WriteServiceUnitTest(self
, func
, file, *extras
):
5203 """Overrriden from TypeHandler."""
5205 TEST_P(%(test_name)s, %(name)sValidArgs) {
5208 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5210 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5211 SpecializedSetup<cmds::%(name)s, 0>(true);
5214 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5215 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5217 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5220 self
.WriteValidUnitTest(func
, file, valid_test
, {
5221 'resource_name': func
.GetInfo('resource_type').lower(),
5222 'upper_resource_name': func
.GetInfo('resource_type'),
5225 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5226 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
5227 SpecializedSetup<cmds::%(name)s, 0>(false);
5230 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5233 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
5235 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5236 """Overrriden from TypeHandler."""
5238 TEST_P(%(test_name)s, %(name)sValidArgs) {
5241 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5243 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5244 SpecializedSetup<cmds::%(name)s, 0>(true);
5245 cmd.Init(1, &client_%(resource_name)s_id_);"""
5248 decoder_->set_unsafe_es3_apis_enabled(true);"""
5250 EXPECT_EQ(error::kNoError,
5251 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5252 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5255 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
5256 client_%(resource_name)s_id_, NULL));
5257 decoder_->set_unsafe_es3_apis_enabled(false);
5258 EXPECT_EQ(error::kUnknownCommand,
5259 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5265 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5268 self
.WriteValidUnitTest(func
, file, valid_test
, {
5269 'resource_name': func
.GetInfo('resource_type').lower(),
5270 'upper_resource_name': func
.GetInfo('resource_type'),
5273 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5274 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5275 SpecializedSetup<cmds::%(name)s, 0>(false);
5276 GLuint temp = kInvalidClientId;
5277 cmd.Init(1, &temp);"""
5280 decoder_->set_unsafe_es3_apis_enabled(true);
5281 EXPECT_EQ(error::kNoError,
5282 ExecuteImmediateCmd(cmd, sizeof(temp)));
5283 decoder_->set_unsafe_es3_apis_enabled(false);
5284 EXPECT_EQ(error::kUnknownCommand,
5285 ExecuteImmediateCmd(cmd, sizeof(temp)));
5290 EXPECT_EQ(error::kNoError,
5291 ExecuteImmediateCmd(cmd, sizeof(temp)));
5294 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
5296 def WriteHandlerImplementation (self
, func
, file):
5297 """Overrriden from TypeHandler."""
5298 file.Write(" %sHelper(n, %s);\n" %
5299 (func
.name
, func
.GetLastOriginalArg().name
))
5301 def WriteImmediateHandlerImplementation (self
, func
, file):
5302 """Overrriden from TypeHandler."""
5304 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5305 GLuint service_id = 0;
5306 if (group_->Get%(resource_type)sServiceId(
5307 %(last_arg_name)s[ii], &service_id)) {
5308 glDelete%(resource_type)ss(1, &service_id);
5309 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
5312 """ % { 'resource_type': func
.GetInfo('resource_type'),
5313 'last_arg_name': func
.GetLastOriginalArg().name
})
5315 file.Write(" %sHelper(n, %s);\n" %
5316 (func
.original_name
, func
.GetLastOriginalArg().name
))
5318 def WriteGLES2Implementation(self
, func
, file):
5319 """Overrriden from TypeHandler."""
5320 impl_decl
= func
.GetInfo('impl_decl')
5321 if impl_decl
== None or impl_decl
== True:
5323 'return_type': func
.return_type
,
5324 'name': func
.original_name
,
5325 'typed_args': func
.MakeTypedOriginalArgString(""),
5326 'args': func
.MakeOriginalArgString(""),
5327 'resource_type': func
.GetInfo('resource_type').lower(),
5328 'count_name': func
.GetOriginalArgs()[0].name
,
5331 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5333 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5334 func
.WriteDestinationInitalizationValidation(file)
5335 self
.WriteClientGLCallLog(func
, file)
5336 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5337 for (GLsizei i = 0; i < n; ++i) {
5338 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5341 """ % func
.GetOriginalArgs()[1].name
)
5342 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
5343 for (GLsizei i = 0; i < n; ++i) {
5347 """ % func
.GetOriginalArgs()[1].name
)
5348 for arg
in func
.GetOriginalArgs():
5349 arg
.WriteClientSideValidationCode(file, func
)
5350 code
= """ %(name)sHelper(%(args)s);
5355 file.Write(code
% args
)
5357 def WriteImmediateCmdComputeSize(self
, func
, file):
5358 """Overrriden from TypeHandler."""
5359 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5361 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5364 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5365 file.Write(" return static_cast<uint32_t>(\n")
5366 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5370 def WriteImmediateCmdSetHeader(self
, func
, file):
5371 """Overrriden from TypeHandler."""
5372 file.Write(" void SetHeader(GLsizei n) {\n")
5373 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5377 def WriteImmediateCmdInit(self
, func
, file):
5378 """Overrriden from TypeHandler."""
5379 last_arg
= func
.GetLastOriginalArg()
5380 file.Write(" void Init(%s, %s _%s) {\n" %
5381 (func
.MakeTypedCmdArgString("_"),
5382 last_arg
.type, last_arg
.name
))
5383 file.Write(" SetHeader(_n);\n")
5384 args
= func
.GetCmdArgs()
5386 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5387 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5388 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
5392 def WriteImmediateCmdSet(self
, func
, file):
5393 """Overrriden from TypeHandler."""
5394 last_arg
= func
.GetLastOriginalArg()
5395 copy_args
= func
.MakeCmdArgString("_", False)
5396 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5397 (func
.MakeTypedCmdArgString("_", True),
5398 last_arg
.type, last_arg
.name
))
5399 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5400 (copy_args
, last_arg
.name
))
5401 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5402 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5407 def WriteImmediateCmdHelper(self
, func
, file):
5408 """Overrriden from TypeHandler."""
5409 code
= """ void %(name)s(%(typed_args)s) {
5410 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5411 gles2::cmds::%(name)s* c =
5412 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5421 "typed_args": func
.MakeTypedOriginalArgString(""),
5422 "args": func
.MakeOriginalArgString(""),
5425 def WriteImmediateFormatTest(self
, func
, file):
5426 """Overrriden from TypeHandler."""
5427 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5428 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5429 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5430 (func
.name
, func
.name
))
5431 file.Write(" void* next_cmd = cmd.Set(\n")
5432 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5433 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5435 file.Write(" cmd.header.command);\n")
5436 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5437 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5438 file.Write(" cmd.header.size * 4u);\n")
5439 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5440 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5441 file.Write(" next_cmd, sizeof(cmd) +\n")
5442 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5443 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5448 class GETnHandler(TypeHandler
):
5449 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
5452 TypeHandler
.__init
__(self
)
5454 def NeedsDataTransferFunction(self
, func
):
5455 """Overriden from TypeHandler."""
5458 def WriteServiceImplementation(self
, func
, file):
5459 """Overrriden from TypeHandler."""
5460 self
.WriteServiceHandlerFunctionHeader(func
, file)
5461 last_arg
= func
.GetLastOriginalArg()
5463 all_but_last_args
= func
.GetOriginalArgs()[:-1]
5464 for arg
in all_but_last_args
:
5465 arg
.WriteGetCode(file)
5467 code
= """ typedef cmds::%(func_name)s::Result Result;
5468 GLsizei num_values = 0;
5469 GetNumValuesReturnedForGLGet(pname, &num_values);
5470 Result* result = GetSharedMemoryAs<Result*>(
5471 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
5472 %(last_arg_type)s params = result ? result->GetData() : NULL;
5475 'last_arg_type': last_arg
.type,
5476 'func_name': func
.name
,
5478 func
.WriteHandlerValidation(file)
5479 code
= """ // Check that the client initialized the result.
5480 if (result->size != 0) {
5481 return error::kInvalidArguments;
5484 shadowed
= func
.GetInfo('shadowed')
5486 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
5488 func
.WriteHandlerImplementation(file)
5490 code
= """ result->SetNumResults(num_values);
5491 return error::kNoError;
5495 code
= """ GLenum error = glGetError();
5496 if (error == GL_NO_ERROR) {
5497 result->SetNumResults(num_values);
5499 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
5501 return error::kNoError;
5505 file.Write(code
% {'func_name': func
.name
})
5507 def WriteGLES2Implementation(self
, func
, file):
5508 """Overrriden from TypeHandler."""
5509 impl_decl
= func
.GetInfo('impl_decl')
5510 if impl_decl
== None or impl_decl
== True:
5511 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5512 (func
.return_type
, func
.original_name
,
5513 func
.MakeTypedOriginalArgString("")))
5514 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5515 func
.WriteDestinationInitalizationValidation(file)
5516 self
.WriteClientGLCallLog(func
, file)
5517 for arg
in func
.GetOriginalArgs():
5518 arg
.WriteClientSideValidationCode(file, func
)
5519 all_but_last_args
= func
.GetOriginalArgs()[:-1]
5521 ", ".join(["%s" % arg
.name
for arg
in all_but_last_args
]))
5525 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()]))
5526 self
.WriteTraceEvent(func
, file)
5527 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
5530 typedef cmds::%(func_name)s::Result Result;
5531 Result* result = GetResultAs<Result*>();
5535 result->SetNumResults(0);
5536 helper_->%(func_name)s(%(arg_string)s,
5537 GetResultShmId(), GetResultShmOffset());
5539 result->CopyResult(params);
5540 GPU_CLIENT_LOG_CODE_BLOCK({
5541 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
5542 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
5549 'func_name': func
.name
,
5550 'arg_string': arg_string
,
5551 'all_arg_string': all_arg_string
,
5554 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5555 """Writes the GLES2 Implemention unit test."""
5557 TEST_F(GLES2ImplementationTest, %(name)s) {
5561 typedef cmds::%(name)s::Result Result;
5562 Result::Type result = 0;
5564 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
5565 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
5566 EXPECT_CALL(*command_buffer(), OnFlush())
5567 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
5568 .RetiresOnSaturation();
5569 gl_->%(name)s(%(args)s, &result);
5570 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5571 EXPECT_EQ(static_cast<Result::Type>(1), result);
5574 first_cmd_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func
)
5575 if not first_cmd_arg
:
5578 first_gl_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideArg(func
)
5579 cmd_arg_strings
= [first_cmd_arg
]
5580 for arg
in func
.GetCmdArgs()[1:-2]:
5581 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
5582 gl_arg_strings
= [first_gl_arg
]
5583 for arg
in func
.GetOriginalArgs()[1:-1]:
5584 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
5588 'args': ", ".join(gl_arg_strings
),
5589 'cmd_args': ", ".join(cmd_arg_strings
),
5592 def WriteServiceUnitTest(self
, func
, file, *extras
):
5593 """Overrriden from TypeHandler."""
5595 TEST_P(%(test_name)s, %(name)sValidArgs) {
5596 EXPECT_CALL(*gl_, GetError())
5597 .WillOnce(Return(GL_NO_ERROR))
5598 .WillOnce(Return(GL_NO_ERROR))
5599 .RetiresOnSaturation();
5600 SpecializedSetup<cmds::%(name)s, 0>(true);
5601 typedef cmds::%(name)s::Result Result;
5602 Result* result = static_cast<Result*>(shared_memory_address_);
5603 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
5606 cmd.Init(%(args)s);"""
5609 decoder_->set_unsafe_es3_apis_enabled(true);"""
5611 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5612 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
5614 result->GetNumResults());
5615 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5618 decoder_->set_unsafe_es3_apis_enabled(false);
5619 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
5625 for arg
in func
.GetOriginalArgs()[:-1]:
5626 arg_value
= arg
.GetValidGLArg(func
)
5627 gl_arg_strings
.append(arg_value
)
5628 if arg
.name
== 'pname':
5629 valid_pname
= arg_value
5630 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
5631 gl_arg_strings
.append("_")
5633 gl_arg_strings
.append("result->GetData()")
5635 self
.WriteValidUnitTest(func
, file, valid_test
, {
5636 'local_gl_args': ", ".join(gl_arg_strings
),
5637 'valid_pname': valid_pname
,
5640 if not func
.IsUnsafe():
5642 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5643 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5644 SpecializedSetup<cmds::%(name)s, 0>(false);
5645 cmds::%(name)s::Result* result =
5646 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
5650 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
5651 EXPECT_EQ(0u, result->size);%(gl_error_test)s
5654 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
5656 class ArrayArgTypeHandler(TypeHandler
):
5657 """Base class for type handlers that handle args that are arrays"""
5660 TypeHandler
.__init
__(self
)
5662 def GetArrayType(self
, func
):
5663 """Returns the type of the element in the element array being PUT to."""
5664 for arg
in func
.GetOriginalArgs():
5666 element_type
= arg
.GetPointedType()
5669 # Special case: array type handler is used for a function that is forwarded
5670 # to the actual array type implementation
5671 element_type
= func
.GetOriginalArgs()[-1].type
5672 assert all(arg
.type == element_type \
5673 for arg
in func
.GetOriginalArgs()[-self
.GetArrayCount(func
):])
5676 def GetArrayCount(self
, func
):
5677 """Returns the count of the elements in the array being PUT to."""
5678 return func
.GetInfo('count')
5680 class PUTHandler(ArrayArgTypeHandler
):
5681 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
5684 ArrayArgTypeHandler
.__init
__(self
)
5686 def WriteServiceUnitTest(self
, func
, file, *extras
):
5687 """Writes the service unit test for a command."""
5688 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
5689 if func
.GetInfo("first_element_only"):
5691 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()
5693 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
5694 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
5695 ", ".join(gl_arg_strings
))
5697 TEST_P(%(test_name)s, %(name)sValidArgs) {
5698 SpecializedSetup<cmds::%(name)s, 0>(true);
5701 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
5703 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5704 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5708 'data_type': self
.GetArrayType(func
),
5709 'data_value': func
.GetInfo('data_value') or '0',
5710 'expected_call': expected_call
,
5712 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
5715 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5716 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5717 SpecializedSetup<cmds::%(name)s, 0>(false);
5720 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
5721 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5724 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
5726 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5727 """Writes the service unit test for a command."""
5729 TEST_P(%(test_name)s, %(name)sValidArgs) {
5730 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5731 SpecializedSetup<cmds::%(name)s, 0>(true);
5732 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
5733 cmd.Init(%(gl_args)s, &temp[0]);
5736 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
5737 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
5740 decoder_->set_unsafe_es3_apis_enabled(true);"""
5742 EXPECT_EQ(error::kNoError,
5743 ExecuteImmediateCmd(cmd, sizeof(temp)));
5744 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5747 decoder_->set_unsafe_es3_apis_enabled(false);
5748 EXPECT_EQ(error::kUnknownCommand,
5749 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
5754 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
5756 gl_any_strings
= ["_"] * len(gl_arg_strings
)
5759 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
5760 'data_type': self
.GetArrayType(func
),
5761 'data_count': self
.GetArrayCount(func
),
5762 'data_value': func
.GetInfo('data_value') or '0',
5763 'gl_args': ", ".join(gl_arg_strings
),
5764 'gl_any_args': ", ".join(gl_any_strings
),
5766 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
5769 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5770 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
5773 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
5777 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5780 SpecializedSetup<cmds::%(name)s, 0>(false);
5781 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
5782 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
5785 decoder_->set_unsafe_es3_apis_enabled(true);
5786 EXPECT_EQ(error::%(parse_result)s,
5787 ExecuteImmediateCmd(cmd, sizeof(temp)));
5788 decoder_->set_unsafe_es3_apis_enabled(false);
5793 EXPECT_EQ(error::%(parse_result)s,
5794 ExecuteImmediateCmd(cmd, sizeof(temp)));
5798 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
5800 def WriteGetDataSizeCode(self
, func
, file):
5801 """Overrriden from TypeHandler."""
5802 code
= """ uint32_t data_size;
5803 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
5804 return error::kOutOfBounds;
5807 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
5808 if func
.IsImmediate():
5809 file.Write(" if (data_size > immediate_data_size) {\n")
5810 file.Write(" return error::kOutOfBounds;\n")
5813 def __NeedsToCalcDataCount(self
, func
):
5814 use_count_func
= func
.GetInfo('use_count_func')
5815 return use_count_func
!= None and use_count_func
!= False
5817 def WriteGLES2Implementation(self
, func
, file):
5818 """Overrriden from TypeHandler."""
5819 impl_func
= func
.GetInfo('impl_func')
5820 if (impl_func
!= None and impl_func
!= True):
5822 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5823 (func
.return_type
, func
.original_name
,
5824 func
.MakeTypedOriginalArgString("")))
5825 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5826 func
.WriteDestinationInitalizationValidation(file)
5827 self
.WriteClientGLCallLog(func
, file)
5829 if self
.__NeedsToCalcDataCount
(func
):
5830 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
5831 (func
.name
, func
.GetOriginalArgs()[0].name
))
5832 file.Write(" DCHECK_LE(count, %du);\n" % self
.GetArrayCount(func
))
5834 file.Write(" size_t count = %d;" % self
.GetArrayCount(func
))
5835 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
5836 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
5837 func
.GetLastOriginalArg().name
)
5838 for arg
in func
.GetOriginalArgs():
5839 arg
.WriteClientSideValidationCode(file, func
)
5840 file.Write(" helper_->%sImmediate(%s);\n" %
5841 (func
.name
, func
.MakeOriginalArgString("")))
5842 file.Write(" CheckGLError();\n")
5846 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5847 """Writes the GLES2 Implemention unit test."""
5848 client_test
= func
.GetInfo('client_test')
5849 if (client_test
!= None and client_test
!= True):
5852 TEST_F(GLES2ImplementationTest, %(name)s) {
5853 %(type)s data[%(count)d] = {0};
5855 cmds::%(name)sImmediate cmd;
5856 %(type)s data[%(count)d];
5859 for (int jj = 0; jj < %(count)d; ++jj) {
5860 data[jj] = static_cast<%(type)s>(jj);
5863 expected.cmd.Init(%(cmd_args)s, &data[0]);
5864 gl_->%(name)s(%(args)s, &data[0]);
5865 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5869 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
5872 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
5877 'type': self
.GetArrayType(func
),
5878 'count': self
.GetArrayCount(func
),
5879 'args': ", ".join(gl_arg_strings
),
5880 'cmd_args': ", ".join(cmd_arg_strings
),
5883 def WriteImmediateCmdComputeSize(self
, func
, file):
5884 """Overrriden from TypeHandler."""
5885 file.Write(" static uint32_t ComputeDataSize() {\n")
5886 file.Write(" return static_cast<uint32_t>(\n")
5887 file.Write(" sizeof(%s) * %d);\n" %
5888 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
5891 if self
.__NeedsToCalcDataCount
(func
):
5892 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
5893 (func
.GetOriginalArgs()[0].type,
5894 func
.GetOriginalArgs()[0].name
))
5895 file.Write(" return static_cast<uint32_t>(\n")
5896 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
5897 (self
.GetArrayType(func
), func
.original_name
,
5898 func
.GetOriginalArgs()[0].name
))
5901 file.Write(" static uint32_t ComputeSize() {\n")
5902 file.Write(" return static_cast<uint32_t>(\n")
5904 " sizeof(ValueType) + ComputeDataSize());\n")
5908 def WriteImmediateCmdSetHeader(self
, func
, file):
5909 """Overrriden from TypeHandler."""
5910 file.Write(" void SetHeader() {\n")
5912 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
5916 def WriteImmediateCmdInit(self
, func
, file):
5917 """Overrriden from TypeHandler."""
5918 last_arg
= func
.GetLastOriginalArg()
5919 file.Write(" void Init(%s, %s _%s) {\n" %
5920 (func
.MakeTypedCmdArgString("_"),
5921 last_arg
.type, last_arg
.name
))
5922 file.Write(" SetHeader();\n")
5923 args
= func
.GetCmdArgs()
5925 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5926 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5927 if self
.__NeedsToCalcDataCount
(func
):
5928 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
5929 (last_arg
.name
, func
.GetOriginalArgs()[0].name
))
5931 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
5932 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
5933 ComputeEffectiveDataSize(%(arg)s);
5934 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
5935 """ % { 'arg': func
.GetOriginalArgs()[0].name
, })
5937 file.Write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
5941 def WriteImmediateCmdSet(self
, func
, file):
5942 """Overrriden from TypeHandler."""
5943 last_arg
= func
.GetLastOriginalArg()
5944 copy_args
= func
.MakeCmdArgString("_", False)
5945 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5946 (func
.MakeTypedCmdArgString("_", True),
5947 last_arg
.type, last_arg
.name
))
5948 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5949 (copy_args
, last_arg
.name
))
5950 file.Write(" const uint32_t size = ComputeSize();\n")
5951 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5956 def WriteImmediateCmdHelper(self
, func
, file):
5957 """Overrriden from TypeHandler."""
5958 code
= """ void %(name)s(%(typed_args)s) {
5959 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
5960 gles2::cmds::%(name)s* c =
5961 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5970 "typed_args": func
.MakeTypedOriginalArgString(""),
5971 "args": func
.MakeOriginalArgString(""),
5974 def WriteImmediateFormatTest(self
, func
, file):
5975 """Overrriden from TypeHandler."""
5976 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5977 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5978 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
5979 for v
in range(0, self
.GetArrayCount(func
)):
5980 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5981 (self
.GetArrayType(func
), v
))
5983 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5984 (func
.name
, func
.name
))
5985 file.Write(" void* next_cmd = cmd.Set(\n")
5987 args
= func
.GetCmdArgs()
5988 for value
, arg
in enumerate(args
):
5989 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
5990 file.Write(",\n data);\n")
5991 args
= func
.GetCmdArgs()
5992 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
5994 file.Write(" cmd.header.command);\n")
5995 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5996 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
5997 file.Write(" cmd.header.size * 4u);\n")
5998 for value
, arg
in enumerate(args
):
5999 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6000 (arg
.type, value
+ 11, arg
.name
))
6001 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6002 file.Write(" next_cmd, sizeof(cmd) +\n")
6003 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6004 file.Write(" // TODO(gman): Check that data was inserted;\n")
6009 class PUTnHandler(ArrayArgTypeHandler
):
6010 """Handler for PUTn 'glUniform__v' type functions."""
6013 ArrayArgTypeHandler
.__init
__(self
)
6015 def WriteServiceUnitTest(self
, func
, file, *extras
):
6016 """Overridden from TypeHandler."""
6017 ArrayArgTypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
6020 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
6021 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6022 SpecializedSetup<cmds::%(name)s, 0>(true);
6025 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6026 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6031 for count
, arg
in enumerate(func
.GetOriginalArgs()):
6032 # hardcoded to match unit tests.
6034 # the location of the second element of the 2nd uniform.
6035 # defined in GLES2DecoderBase::SetupShaderForUniform
6036 gl_arg_strings
.append("3")
6037 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
6039 # the number of elements that gl will be called with.
6040 gl_arg_strings
.append("3")
6041 # the number of elements requested in the command.
6042 arg_strings
.append("5")
6044 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
6045 if not arg
.IsConstant():
6046 arg_strings
.append(arg
.GetValidArg(func
))
6048 'gl_args': ", ".join(gl_arg_strings
),
6049 'args': ", ".join(arg_strings
),
6051 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6053 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6054 """Overridden from TypeHandler."""
6056 TEST_P(%(test_name)s, %(name)sValidArgs) {
6057 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6060 %(gl_func_name)s(%(gl_args)s,
6061 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
6062 SpecializedSetup<cmds::%(name)s, 0>(true);
6063 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6064 cmd.Init(%(args)s, &temp[0]);"""
6067 decoder_->set_unsafe_es3_apis_enabled(true);"""
6069 EXPECT_EQ(error::kNoError,
6070 ExecuteImmediateCmd(cmd, sizeof(temp)));
6071 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6074 decoder_->set_unsafe_es3_apis_enabled(false);
6075 EXPECT_EQ(error::kUnknownCommand,
6076 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6083 for arg
in func
.GetOriginalArgs()[0:-1]:
6084 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
6085 gl_any_strings
.append("_")
6086 if not arg
.IsConstant():
6087 arg_strings
.append(arg
.GetValidArg(func
))
6089 'data_type': self
.GetArrayType(func
),
6090 'data_count': self
.GetArrayCount(func
),
6091 'args': ", ".join(arg_strings
),
6092 'gl_args': ", ".join(gl_arg_strings
),
6093 'gl_any_args': ", ".join(gl_any_strings
),
6095 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6098 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6099 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6100 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6101 SpecializedSetup<cmds::%(name)s, 0>(false);
6102 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6103 cmd.Init(%(all_but_last_args)s, &temp[0]);
6104 EXPECT_EQ(error::%(parse_result)s,
6105 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
6108 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6110 def WriteGetDataSizeCode(self
, func
, file):
6111 """Overrriden from TypeHandler."""
6112 code
= """ uint32_t data_size;
6113 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
6114 return error::kOutOfBounds;
6117 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6118 if func
.IsImmediate():
6119 file.Write(" if (data_size > immediate_data_size) {\n")
6120 file.Write(" return error::kOutOfBounds;\n")
6123 def WriteGLES2Implementation(self
, func
, file):
6124 """Overrriden from TypeHandler."""
6125 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6126 (func
.return_type
, func
.original_name
,
6127 func
.MakeTypedOriginalArgString("")))
6128 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6129 func
.WriteDestinationInitalizationValidation(file)
6130 self
.WriteClientGLCallLog(func
, file)
6131 last_pointer_name
= func
.GetLastOriginalPointerArg().name
6132 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6133 for (GLsizei i = 0; i < count; ++i) {
6135 values_str
= ' << ", " << '.join(
6136 ["%s[%d + i * %d]" % (
6137 last_pointer_name
, ndx
, self
.GetArrayCount(func
)) for ndx
in range(
6138 0, self
.GetArrayCount(func
))])
6139 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
6140 file.Write(" }\n });\n")
6141 for arg
in func
.GetOriginalArgs():
6142 arg
.WriteClientSideValidationCode(file, func
)
6143 file.Write(" helper_->%sImmediate(%s);\n" %
6144 (func
.name
, func
.MakeInitString("")))
6145 file.Write(" CheckGLError();\n")
6149 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6150 """Writes the GLES2 Implemention unit test."""
6152 TEST_F(GLES2ImplementationTest, %(name)s) {
6153 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6155 cmds::%(name)sImmediate cmd;
6156 %(type)s data[%(count_param)d][%(count)d];
6160 for (int ii = 0; ii < %(count_param)d; ++ii) {
6161 for (int jj = 0; jj < %(count)d; ++jj) {
6162 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6165 expected.cmd.Init(%(cmd_args)s);
6166 gl_->%(name)s(%(args)s);
6167 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6170 cmd_arg_strings
= []
6171 for arg
in func
.GetCmdArgs():
6172 if arg
.name
.endswith("_shm_id"):
6173 cmd_arg_strings
.append("&data[0][0]")
6174 elif arg
.name
.endswith("_shm_offset"):
6177 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
6180 for arg
in func
.GetOriginalArgs():
6182 valid_value
= "&data[0][0]"
6184 valid_value
= arg
.GetValidClientSideArg(func
)
6185 gl_arg_strings
.append(valid_value
)
6186 if arg
.name
== "count":
6187 count_param
= int(valid_value
)
6190 'type': self
.GetArrayType(func
),
6191 'count': self
.GetArrayCount(func
),
6192 'args': ", ".join(gl_arg_strings
),
6193 'cmd_args': ", ".join(cmd_arg_strings
),
6194 'count_param': count_param
,
6197 # Test constants for invalid values, as they are not tested by the
6200 arg
for arg
in func
.GetOriginalArgs()[0:-1] if arg
.IsConstant()
6206 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
6207 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6208 for (int ii = 0; ii < %(count_param)d; ++ii) {
6209 for (int jj = 0; jj < %(count)d; ++jj) {
6210 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6213 gl_->%(name)s(%(args)s);
6214 EXPECT_TRUE(NoCommandsWritten());
6215 EXPECT_EQ(%(gl_error)s, CheckError());
6218 for invalid_arg
in constants
:
6220 invalid
= invalid_arg
.GetInvalidArg(func
)
6221 for arg
in func
.GetOriginalArgs():
6222 if arg
is invalid_arg
:
6223 gl_arg_strings
.append(invalid
[0])
6224 elif arg
.IsPointer():
6225 gl_arg_strings
.append("&data[0][0]")
6227 valid_value
= arg
.GetValidClientSideArg(func
)
6228 gl_arg_strings
.append(valid_value
)
6229 if arg
.name
== "count":
6230 count_param
= int(valid_value
)
6234 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
6235 'type': self
.GetArrayType(func
),
6236 'count': self
.GetArrayCount(func
),
6237 'args': ", ".join(gl_arg_strings
),
6238 'gl_error': invalid
[2],
6239 'count_param': count_param
,
6243 def WriteImmediateCmdComputeSize(self
, func
, file):
6244 """Overrriden from TypeHandler."""
6245 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
6246 file.Write(" return static_cast<uint32_t>(\n")
6247 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
6248 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6251 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
6252 file.Write(" return static_cast<uint32_t>(\n")
6254 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
6258 def WriteImmediateCmdSetHeader(self
, func
, file):
6259 """Overrriden from TypeHandler."""
6260 file.Write(" void SetHeader(GLsizei count) {\n")
6262 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
6266 def WriteImmediateCmdInit(self
, func
, file):
6267 """Overrriden from TypeHandler."""
6268 file.Write(" void Init(%s) {\n" %
6269 func
.MakeTypedInitString("_"))
6270 file.Write(" SetHeader(_count);\n")
6271 args
= func
.GetCmdArgs()
6273 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6274 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6275 pointer_arg
= func
.GetLastOriginalPointerArg()
6276 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg
.name
)
6280 def WriteImmediateCmdSet(self
, func
, file):
6281 """Overrriden from TypeHandler."""
6282 file.Write(" void* Set(void* cmd%s) {\n" %
6283 func
.MakeTypedInitString("_", True))
6284 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
6285 func
.MakeInitString("_"))
6286 file.Write(" const uint32_t size = ComputeSize(_count);\n")
6287 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6292 def WriteImmediateCmdHelper(self
, func
, file):
6293 """Overrriden from TypeHandler."""
6294 code
= """ void %(name)s(%(typed_args)s) {
6295 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
6296 gles2::cmds::%(name)s* c =
6297 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6306 "typed_args": func
.MakeTypedInitString(""),
6307 "args": func
.MakeInitString("")
6310 def WriteImmediateFormatTest(self
, func
, file):
6311 """Overrriden from TypeHandler."""
6312 args
= func
.GetOriginalArgs()
6315 if arg
.name
== "count":
6316 count_param
= int(arg
.GetValidClientSideCmdArg(func
))
6317 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6318 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6319 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
6320 for v
in range(0, self
.GetArrayCount(func
) * count_param
):
6321 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6322 (self
.GetArrayType(func
), v
))
6324 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6325 (func
.name
, func
.name
))
6326 file.Write(" const GLsizei kNumElements = %d;\n" % count_param
)
6327 file.Write(" const size_t kExpectedCmdSize =\n")
6328 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
6329 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6330 file.Write(" void* next_cmd = cmd.Set(\n")
6332 for value
, arg
in enumerate(args
):
6334 file.Write(",\n data")
6335 elif arg
.IsConstant():
6338 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
6340 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6342 file.Write(" cmd.header.command);\n")
6343 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
6344 for value
, arg
in enumerate(args
):
6345 if arg
.IsPointer() or arg
.IsConstant():
6347 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6348 (arg
.type, value
+ 1, arg
.name
))
6349 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6350 file.Write(" next_cmd, sizeof(cmd) +\n")
6351 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6352 file.Write(" // TODO(gman): Check that data was inserted;\n")
6356 class PUTSTRHandler(ArrayArgTypeHandler
):
6357 """Handler for functions that pass a string array."""
6360 ArrayArgTypeHandler
.__init
__(self
)
6362 def __GetDataArg(self
, func
):
6363 """Return the argument that points to the 2D char arrays"""
6364 for arg
in func
.GetOriginalArgs():
6365 if arg
.IsPointer2D():
6369 def __GetLengthArg(self
, func
):
6370 """Return the argument that holds length for each char array"""
6371 for arg
in func
.GetOriginalArgs():
6372 if arg
.IsPointer() and not arg
.IsPointer2D():
6376 def WriteGLES2Implementation(self
, func
, file):
6377 """Overrriden from TypeHandler."""
6378 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6379 (func
.return_type
, func
.original_name
,
6380 func
.MakeTypedOriginalArgString("")))
6381 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6382 func
.WriteDestinationInitalizationValidation(file)
6383 self
.WriteClientGLCallLog(func
, file)
6384 data_arg
= self
.__GetDataArg
(func
)
6385 length_arg
= self
.__GetLengthArg
(func
)
6386 log_code_block
= """ GPU_CLIENT_LOG_CODE_BLOCK({
6387 for (GLsizei ii = 0; ii < count; ++ii) {
6388 if (%(data)s[ii]) {"""
6389 if length_arg
== None:
6390 log_code_block
+= """
6391 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
6393 log_code_block
+= """
6394 if (%(length)s && %(length)s[ii] >= 0) {
6395 const std::string my_str(%(data)s[ii], %(length)s[ii]);
6396 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
6398 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
6400 log_code_block
+= """
6402 GPU_CLIENT_LOG(" " << ii << ": NULL");
6407 file.Write(log_code_block
% {
6408 'data': data_arg
.name
,
6409 'length': length_arg
.name
if not length_arg
== None else ''
6411 for arg
in func
.GetOriginalArgs():
6412 arg
.WriteClientSideValidationCode(file, func
)
6413 size_code_block
= """ // Compute the total size.
6414 base::CheckedNumeric<size_t> total_size = count;
6416 total_size *= sizeof(GLint);
6417 if (!total_size.IsValid()) {
6418 SetGLError(GL_INVALID_VALUE, "glShaderSource", "overflow");
6421 size_t header_size = total_size.ValueOrDefault(0);
6422 std::vector<GLint> header(count + 1);
6423 header[0] = static_cast<GLint>(count);
6424 for (GLsizei ii = 0; ii < count; ++ii) {
6426 if (%(data)s[ii]) {"""
6427 if length_arg
== None:
6428 size_code_block
+= """
6429 len = base::static_cast<GLint>(strlen(%(data)s[ii]));"""
6431 size_code_block
+= """
6432 len = (%(length)s && %(length)s[ii] >= 0) ?
6433 %(length)s[ii] : base::checked_cast<GLint>(strlen(%(data)s[ii]));"""
6434 size_code_block
+= """
6437 total_size += 1; // NULL at the end of each char array.
6438 if (!total_size.IsValid()) {
6439 SetGLError(GL_INVALID_VALUE, "glShaderSource", "overflow");
6442 header[ii + 1] = len;
6445 file.Write(size_code_block
% {
6446 'data': data_arg
.name
,
6447 'length': length_arg
.name
if not length_arg
== None else ''
6449 data_code_block
= """ // Pack data into a bucket on the service.
6450 helper_->SetBucketSize(kResultBucketId, total_size.ValueOrDefault(0));
6452 for (GLsizei ii = 0; ii <= count; ++ii) {
6453 const char* src = (ii == 0) ? reinterpret_cast<const char*>(&header[0]) :
6455 base::CheckedNumeric<size_t> checked_size = (ii == 0) ? header_size :
6456 static_cast<size_t>(header[ii]);
6458 checked_size += 1; // NULL in the end.
6460 if (!checked_size.IsValid()) {
6461 SetGLError(GL_INVALID_VALUE, "glShaderSource", "overflow");
6464 size_t size = checked_size.ValueOrDefault(0);
6466 ScopedTransferBufferPtr buffer(size, helper_, transfer_buffer_);
6467 if (!buffer.valid() || buffer.size() == 0) {
6468 SetGLError(GL_OUT_OF_MEMORY, "glShaderSource", "too large");
6471 size_t copy_size = buffer.size();
6472 if (ii > 0 && buffer.size() == size)
6475 memcpy(buffer.address(), src, copy_size);
6476 if (copy_size < buffer.size()) {
6477 // Append NULL in the end.
6478 DCHECK(copy_size + 1 == buffer.size());
6479 char* str = reinterpret_cast<char*>(buffer.address());
6482 helper_->SetBucketData(kResultBucketId, offset, buffer.size(),
6483 buffer.shm_id(), buffer.offset());
6484 offset += buffer.size();
6485 src += buffer.size();
6486 size -= buffer.size();
6489 DCHECK_EQ(total_size.ValueOrDefault(0), offset);
6491 file.Write(data_code_block
% {
6492 'data': data_arg
.name
,
6493 'length': length_arg
.name
if not length_arg
== None else ''
6495 bucket_cmd_arg_string
= ""
6496 for arg
in func
.GetCmdArgs()[0:-2]:
6497 if bucket_cmd_arg_string
:
6498 bucket_cmd_arg_string
+= ", "
6499 bucket_cmd_arg_string
+= arg
.name
6500 if bucket_cmd_arg_string
:
6501 bucket_cmd_arg_string
+= ", "
6502 bucket_cmd_arg_string
+= 'kResultBucketId'
6503 file.Write(" helper_->%sBucket(%s);\n" %
6504 (func
.name
, bucket_cmd_arg_string
))
6505 file.Write(" helper_->SetBucketSize(kResultBucketId, 0);");
6506 file.Write(" CheckGLError();\n")
6511 class PUTXnHandler(ArrayArgTypeHandler
):
6512 """Handler for glUniform?f functions."""
6514 ArrayArgTypeHandler
.__init
__(self
)
6516 def WriteHandlerImplementation(self
, func
, file):
6517 """Overrriden from TypeHandler."""
6518 code
= """ %(type)s temp[%(count)s] = { %(values)s};"""
6521 gl%(name)sv(%(location)s, 1, &temp[0]);
6525 Do%(name)sv(%(location)s, 1, &temp[0]);
6528 args
= func
.GetOriginalArgs()
6529 count
= int(self
.GetArrayCount(func
))
6530 num_args
= len(args
)
6531 for ii
in range(count
):
6532 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
6536 'count': self
.GetArrayCount(func
),
6537 'type': self
.GetArrayType(func
),
6538 'location': args
[0].name
,
6539 'args': func
.MakeOriginalArgString(""),
6543 def WriteServiceUnitTest(self
, func
, file, *extras
):
6544 """Overrriden from TypeHandler."""
6546 TEST_P(%(test_name)s, %(name)sValidArgs) {
6547 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
6548 SpecializedSetup<cmds::%(name)s, 0>(true);
6550 cmd.Init(%(args)s);"""
6553 decoder_->set_unsafe_es3_apis_enabled(true);"""
6555 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6556 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6559 decoder_->set_unsafe_es3_apis_enabled(false);
6560 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6564 args
= func
.GetOriginalArgs()
6565 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
)
6566 self
.WriteValidUnitTest(func
, file, valid_test
, {
6568 'count': self
.GetArrayCount(func
),
6569 'local_args': local_args
,
6573 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6574 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
6575 SpecializedSetup<cmds::%(name)s, 0>(false);
6578 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6581 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
6582 'name': func
.GetInfo('name'),
6583 'count': self
.GetArrayCount(func
),
6587 class GLcharHandler(CustomHandler
):
6588 """Handler for functions that pass a single string ."""
6591 CustomHandler
.__init
__(self
)
6593 def WriteImmediateCmdComputeSize(self
, func
, file):
6594 """Overrriden from TypeHandler."""
6595 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
6596 file.Write(" return static_cast<uint32_t>(\n")
6597 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
6600 def WriteImmediateCmdSetHeader(self
, func
, file):
6601 """Overrriden from TypeHandler."""
6603 void SetHeader(uint32_t data_size) {
6604 header.SetCmdBySize<ValueType>(data_size);
6609 def WriteImmediateCmdInit(self
, func
, file):
6610 """Overrriden from TypeHandler."""
6611 last_arg
= func
.GetLastOriginalArg()
6612 args
= func
.GetCmdArgs()
6615 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
6617 void Init(%(typed_args)s, uint32_t _data_size) {
6618 SetHeader(_data_size);
6620 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
6625 "typed_args": func
.MakeTypedArgString("_"),
6626 "set_code": "\n".join(set_code
),
6627 "last_arg": last_arg
.name
6630 def WriteImmediateCmdSet(self
, func
, file):
6631 """Overrriden from TypeHandler."""
6632 last_arg
= func
.GetLastOriginalArg()
6633 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
6634 func
.MakeTypedCmdArgString("_", True))
6635 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
6636 func
.MakeCmdArgString("_"))
6637 file.Write(" return NextImmediateCmdAddress<ValueType>("
6638 "cmd, _data_size);\n")
6642 def WriteImmediateCmdHelper(self
, func
, file):
6643 """Overrriden from TypeHandler."""
6644 code
= """ void %(name)s(%(typed_args)s) {
6645 const uint32_t data_size = strlen(name);
6646 gles2::cmds::%(name)s* c =
6647 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
6649 c->Init(%(args)s, data_size);
6656 "typed_args": func
.MakeTypedOriginalArgString(""),
6657 "args": func
.MakeOriginalArgString(""),
6661 def WriteImmediateFormatTest(self
, func
, file):
6662 """Overrriden from TypeHandler."""
6665 all_but_last_arg
= func
.GetCmdArgs()[:-1]
6666 for value
, arg
in enumerate(all_but_last_arg
):
6667 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
6668 for value
, arg
in enumerate(all_but_last_arg
):
6669 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
6670 (arg
.type, value
+ 11, arg
.name
))
6672 TEST_F(GLES2FormatTest, %(func_name)s) {
6673 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
6674 static const char* const test_str = \"test string\";
6675 void* next_cmd = cmd.Set(
6680 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
6681 cmd.header.command);
6682 EXPECT_EQ(sizeof(cmd) +
6683 RoundSizeToMultipleOfEntries(strlen(test_str)),
6684 cmd.header.size * 4u);
6685 EXPECT_EQ(static_cast<char*>(next_cmd),
6686 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
6687 RoundSizeToMultipleOfEntries(strlen(test_str)));
6689 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
6690 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
6693 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
6694 sizeof(cmd) + strlen(test_str));
6699 'func_name': func
.name
,
6700 'init_code': "\n".join(init_code
),
6701 'check_code': "\n".join(check_code
),
6705 class GLcharNHandler(CustomHandler
):
6706 """Handler for functions that pass a single string with an optional len."""
6709 CustomHandler
.__init
__(self
)
6711 def InitFunction(self
, func
):
6712 """Overrriden from TypeHandler."""
6714 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
6716 def NeedsDataTransferFunction(self
, func
):
6717 """Overriden from TypeHandler."""
6720 def AddBucketFunction(self
, generator
, func
):
6721 """Overrriden from TypeHandler."""
6724 def WriteServiceImplementation(self
, func
, file):
6725 """Overrriden from TypeHandler."""
6726 self
.WriteServiceHandlerFunctionHeader(func
, file)
6728 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
6729 Bucket* bucket = GetBucket(bucket_id);
6730 if (!bucket || bucket->size() == 0) {
6731 return error::kInvalidArguments;
6734 if (!bucket->GetAsString(&str)) {
6735 return error::kInvalidArguments;
6737 %(gl_func_name)s(0, str.c_str());
6738 return error::kNoError;
6743 'gl_func_name': func
.GetGLFunctionName(),
6744 'bucket_id': func
.cmd_args
[0].name
,
6748 class IsHandler(TypeHandler
):
6749 """Handler for glIs____ type and glGetError functions."""
6752 TypeHandler
.__init
__(self
)
6754 def InitFunction(self
, func
):
6755 """Overrriden from TypeHandler."""
6756 func
.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
6757 func
.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
6758 if func
.GetInfo('result') == None:
6759 func
.AddInfo('result', ['uint32_t'])
6761 def WriteServiceUnitTest(self
, func
, file, *extras
):
6762 """Overrriden from TypeHandler."""
6764 TEST_P(%(test_name)s, %(name)sValidArgs) {
6765 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6766 SpecializedSetup<cmds::%(name)s, 0>(true);
6768 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
6771 decoder_->set_unsafe_es3_apis_enabled(true);"""
6773 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6774 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6777 decoder_->set_unsafe_es3_apis_enabled(false);
6778 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6783 if len(func
.GetOriginalArgs()):
6785 self
.WriteValidUnitTest(func
, file, valid_test
, {
6790 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6791 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6792 SpecializedSetup<cmds::%(name)s, 0>(false);
6794 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
6795 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6798 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
6803 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
6804 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6805 SpecializedSetup<cmds::%(name)s, 0>(false);"""
6808 decoder_->set_unsafe_es3_apis_enabled(true);"""
6811 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
6812 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
6813 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
6814 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
6817 decoder_->set_unsafe_es3_apis_enabled(true);"""
6821 self
.WriteValidUnitTest(func
, file, invalid_test
, {
6825 def WriteServiceImplementation(self
, func
, file):
6826 """Overrriden from TypeHandler."""
6827 self
.WriteServiceHandlerFunctionHeader(func
, file)
6828 args
= func
.GetOriginalArgs()
6830 arg
.WriteGetCode(file)
6832 code
= """ typedef cmds::%(func_name)s::Result Result;
6833 Result* result_dst = GetSharedMemoryAs<Result*>(
6834 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
6836 return error::kOutOfBounds;
6839 file.Write(code
% {'func_name': func
.name
})
6840 func
.WriteHandlerValidation(file)
6842 assert func
.GetInfo('id_mapping')
6843 assert len(func
.GetInfo('id_mapping')) == 1
6844 assert len(args
) == 1
6845 id_type
= func
.GetInfo('id_mapping')[0]
6846 file.Write(" %s service_%s = 0;\n" % (args
[0].type, id_type
.lower()))
6847 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
6848 (id_type
, id_type
.lower(), id_type
.lower()))
6850 file.Write(" *result_dst = %s(%s);\n" %
6851 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
6852 file.Write(" return error::kNoError;\n")
6856 def WriteGLES2Implementation(self
, func
, file):
6857 """Overrriden from TypeHandler."""
6858 impl_func
= func
.GetInfo('impl_func')
6859 if impl_func
== None or impl_func
== True:
6860 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
6861 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6862 (func
.return_type
, func
.original_name
,
6863 func
.MakeTypedOriginalArgString("")))
6864 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6865 self
.WriteTraceEvent(func
, file)
6866 func
.WriteDestinationInitalizationValidation(file)
6867 self
.WriteClientGLCallLog(func
, file)
6868 file.Write(" typedef cmds::%s::Result Result;\n" % func
.name
)
6869 file.Write(" Result* result = GetResultAs<Result*>();\n")
6870 file.Write(" if (!result) {\n")
6871 file.Write(" return %s;\n" % error_value
)
6873 file.Write(" *result = 0;\n")
6874 assert len(func
.GetOriginalArgs()) == 1
6875 id_arg
= func
.GetOriginalArgs()[0]
6876 if id_arg
.type == 'GLsync':
6877 arg_string
= "ToGLuint(%s)" % func
.MakeOriginalArgString("")
6879 arg_string
= func
.MakeOriginalArgString("")
6881 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
6882 (func
.name
, arg_string
))
6883 file.Write(" WaitForCmd();\n")
6884 file.Write(" %s result_value = *result" % func
.return_type
)
6885 if func
.return_type
== "GLboolean":
6887 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
6888 file.Write(" CheckGLError();\n")
6889 file.Write(" return result_value;\n")
6893 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6894 """Overrriden from TypeHandler."""
6895 client_test
= func
.GetInfo('client_test')
6896 if client_test
== None or client_test
== True:
6898 TEST_F(GLES2ImplementationTest, %(name)s) {
6904 ExpectedMemoryInfo result1 =
6905 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
6906 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
6908 EXPECT_CALL(*command_buffer(), OnFlush())
6909 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
6910 .RetiresOnSaturation();
6912 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
6913 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6914 EXPECT_TRUE(result);
6917 args
= func
.GetOriginalArgs()
6918 assert len(args
) == 1
6921 'cmd_id_value': args
[0].GetValidClientSideCmdArg(func
),
6922 'gl_id_value': args
[0].GetValidClientSideArg(func
) })
6925 class STRnHandler(TypeHandler
):
6926 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
6927 GetTranslatedShaderSourceANGLE."""
6930 TypeHandler
.__init
__(self
)
6932 def InitFunction(self
, func
):
6933 """Overrriden from TypeHandler."""
6934 # remove all but the first cmd args.
6935 cmd_args
= func
.GetCmdArgs()
6937 func
.AddCmdArg(cmd_args
[0])
6938 # add on a bucket id.
6939 func
.AddCmdArg(Argument('bucket_id', 'uint32_t'))
6941 def WriteGLES2Implementation(self
, func
, file):
6942 """Overrriden from TypeHandler."""
6943 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
6944 GPU_CLIENT_SINGLE_THREAD_CHECK();
6946 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
6947 << "] gl%(func_name)s" << "("
6950 << static_cast<void*>(%(arg2)s) << ", "
6951 << static_cast<void*>(%(arg3)s) << ")");
6952 helper_->SetBucketSize(kResultBucketId, 0);
6953 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
6955 GLsizei max_size = 0;
6956 if (GetBucketAsString(kResultBucketId, &str)) {
6959 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
6960 memcpy(%(dest_name)s, str.c_str(), max_size);
6961 %(dest_name)s[max_size] = '\\0';
6962 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
6965 if (%(length_name)s != NULL) {
6966 *%(length_name)s = max_size;
6971 args
= func
.GetOriginalArgs()
6973 'return_type': func
.return_type
,
6974 'func_name': func
.original_name
,
6975 'args': func
.MakeTypedOriginalArgString(""),
6976 'id_name': args
[0].name
,
6977 'bufsize_name': args
[1].name
,
6978 'length_name': args
[2].name
,
6979 'dest_name': args
[3].name
,
6980 'arg0': args
[0].name
,
6981 'arg1': args
[1].name
,
6982 'arg2': args
[2].name
,
6983 'arg3': args
[3].name
,
6985 file.Write(code_1
% str_args
)
6986 func
.WriteDestinationInitalizationValidation(file)
6987 file.Write(code_2
% str_args
)
6989 def WriteServiceUnitTest(self
, func
, file, *extras
):
6990 """Overrriden from TypeHandler."""
6992 TEST_P(%(test_name)s, %(name)sValidArgs) {
6993 const char* kInfo = "hello";
6994 const uint32_t kBucketId = 123;
6995 SpecializedSetup<cmds::%(name)s, 0>(true);
6997 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
6998 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
6999 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
7002 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7003 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
7004 ASSERT_TRUE(bucket != NULL);
7005 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
7006 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
7008 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7011 args
= func
.GetOriginalArgs()
7012 id_name
= args
[0].GetValidGLArg(func
)
7013 get_len_func
= func
.GetInfo('get_len_func')
7014 get_len_enum
= func
.GetInfo('get_len_enum')
7017 'get_len_func': get_len_func
,
7018 'get_len_enum': get_len_enum
,
7019 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
7020 args
[0].GetValidGLArg(func
),
7021 'args': '%s, kBucketId' % args
[0].GetValidArg(func
),
7022 'expect_len_code': '',
7024 if get_len_func
and get_len_func
[0:2] == 'gl':
7025 sub
['expect_len_code'] = (
7026 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
7027 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
7028 get_len_func
[2:], id_name
, get_len_enum
)
7029 self
.WriteValidUnitTest(func
, file, valid_test
, sub
, *extras
)
7032 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7033 const uint32_t kBucketId = 123;
7034 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
7037 cmd.Init(kInvalidClientId, kBucketId);
7038 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7039 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7042 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
7044 def WriteServiceImplementation(self
, func
, file):
7045 """Overrriden from TypeHandler."""
7048 class NamedType(object):
7049 """A class that represents a type of an argument in a client function.
7051 A type of an argument that is to be passed through in the command buffer
7052 command. Currently used only for the arguments that are specificly named in
7053 the 'cmd_buffer_functions.txt' file, mostly enums.
7056 def __init__(self
, info
):
7057 assert not 'is_complete' in info
or info
['is_complete'] == True
7059 self
.valid
= info
['valid']
7060 if 'invalid' in info
:
7061 self
.invalid
= info
['invalid']
7066 return self
.info
['type']
7068 def GetInvalidValues(self
):
7071 def GetValidValues(self
):
7074 def IsConstant(self
):
7075 if not 'is_complete' in self
.info
:
7078 return len(self
.GetValidValues()) == 1
7080 def GetConstantValue(self
):
7081 return self
.GetValidValues()[0]
7083 class Argument(object):
7084 """A class that represents a function argument."""
7087 'GLenum': 'uint32_t',
7089 'GLintptr': 'int32_t',
7090 'GLsizei': 'int32_t',
7091 'GLsizeiptr': 'int32_t',
7093 'GLclampf': 'float',
7095 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
7097 def __init__(self
, name
, type):
7099 self
.optional
= type.endswith("Optional*")
7101 type = type[:-9] + "*"
7104 if type in self
.cmd_type_map_
:
7105 self
.cmd_type
= self
.cmd_type_map_
[type]
7107 self
.cmd_type
= 'uint32_t'
7109 def IsPointer(self
):
7110 """Returns true if argument is a pointer."""
7113 def IsPointer2D(self
):
7114 """Returns true if argument is a 2D pointer."""
7117 def IsConstant(self
):
7118 """Returns true if the argument has only one valid value."""
7121 def AddCmdArgs(self
, args
):
7122 """Adds command arguments for this argument to the given list."""
7123 if not self
.IsConstant():
7124 return args
.append(self
)
7126 def AddInitArgs(self
, args
):
7127 """Adds init arguments for this argument to the given list."""
7128 if not self
.IsConstant():
7129 return args
.append(self
)
7131 def GetValidArg(self
, func
):
7132 """Gets a valid value for this argument."""
7133 valid_arg
= func
.GetValidArg(self
)
7134 if valid_arg
!= None:
7137 index
= func
.GetOriginalArgs().index(self
)
7138 return str(index
+ 1)
7140 def GetValidClientSideArg(self
, func
):
7141 """Gets a valid value for this argument."""
7142 valid_arg
= func
.GetValidArg(self
)
7143 if valid_arg
!= None:
7146 index
= func
.GetOriginalArgs().index(self
)
7147 if self
.type == 'GLsync':
7148 return ("reinterpret_cast<GLsync>(%d)" % (index
+ 1))
7149 return str(index
+ 1)
7151 def GetValidClientSideCmdArg(self
, func
):
7152 """Gets a valid value for this argument."""
7153 valid_arg
= func
.GetValidArg(self
)
7154 if valid_arg
!= None:
7157 index
= func
.GetOriginalArgs().index(self
)
7158 return str(index
+ 1)
7161 index
= func
.GetCmdArgs().index(self
)
7162 return str(index
+ 1)
7164 def GetValidGLArg(self
, func
):
7165 """Gets a valid GL value for this argument."""
7166 value
= self
.GetValidArg(func
)
7167 if self
.type == 'GLsync':
7168 return ("reinterpret_cast<GLsync>(%s)" % value
)
7171 def GetValidNonCachedClientSideArg(self
, func
):
7172 """Returns a valid value for this argument in a GL call.
7173 Using the value will produce a command buffer service invocation.
7174 Returns None if there is no such value."""
7177 def GetValidNonCachedClientSideCmdArg(self
, func
):
7178 """Returns a valid value for this argument in a command buffer command.
7179 Calling the GL function with the value returned by
7180 GetValidNonCachedClientSideArg will result in a command buffer command
7181 that contains the value returned by this function. """
7184 def GetNumInvalidValues(self
, func
):
7185 """returns the number of invalid values to be tested."""
7188 def GetInvalidArg(self
, index
):
7189 """returns an invalid value and expected parse result by index."""
7190 return ("---ERROR0---", "---ERROR2---", None)
7192 def GetLogArg(self
):
7193 """Get argument appropriate for LOG macro."""
7194 if self
.type == 'GLboolean':
7195 return 'GLES2Util::GetStringBool(%s)' % self
.name
7196 if self
.type == 'GLenum':
7197 return 'GLES2Util::GetStringEnum(%s)' % self
.name
7200 def WriteGetCode(self
, file):
7201 """Writes the code to get an argument from a command structure."""
7202 if self
.type == 'GLsync':
7206 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
7207 (my_type
, self
.name
, my_type
, self
.name
))
7209 def WriteValidationCode(self
, file, func
):
7210 """Writes the validation code for an argument."""
7213 def WriteClientSideValidationCode(self
, file, func
):
7214 """Writes the validation code for an argument."""
7217 def WriteDestinationInitalizationValidation(self
, file, func
):
7218 """Writes the client side destintion initialization validation."""
7221 def WriteDestinationInitalizationValidatationIfNeeded(self
, file, func
):
7222 """Writes the client side destintion initialization validation if needed."""
7223 parts
= self
.type.split(" ")
7226 if parts
[0] in self
.need_validation_
:
7228 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
7229 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
7232 def WriteGetAddress(self
, file):
7233 """Writes the code to get the address this argument refers to."""
7236 def GetImmediateVersion(self
):
7237 """Gets the immediate version of this argument."""
7240 def GetBucketVersion(self
):
7241 """Gets the bucket version of this argument."""
7245 class BoolArgument(Argument
):
7246 """class for GLboolean"""
7248 def __init__(self
, name
, type):
7249 Argument
.__init
__(self
, name
, 'GLboolean')
7251 def GetValidArg(self
, func
):
7252 """Gets a valid value for this argument."""
7255 def GetValidClientSideArg(self
, func
):
7256 """Gets a valid value for this argument."""
7259 def GetValidClientSideCmdArg(self
, func
):
7260 """Gets a valid value for this argument."""
7263 def GetValidGLArg(self
, func
):
7264 """Gets a valid GL value for this argument."""
7268 class UniformLocationArgument(Argument
):
7269 """class for uniform locations."""
7271 def __init__(self
, name
):
7272 Argument
.__init
__(self
, name
, "GLint")
7274 def WriteGetCode(self
, file):
7275 """Writes the code to get an argument from a command structure."""
7276 code
= """ %s %s = static_cast<%s>(c.%s);
7278 file.Write(code
% (self
.type, self
.name
, self
.type, self
.name
))
7280 class DataSizeArgument(Argument
):
7281 """class for data_size which Bucket commands do not need."""
7283 def __init__(self
, name
):
7284 Argument
.__init
__(self
, name
, "uint32_t")
7286 def GetBucketVersion(self
):
7290 class SizeArgument(Argument
):
7291 """class for GLsizei and GLsizeiptr."""
7293 def __init__(self
, name
, type):
7294 Argument
.__init
__(self
, name
, type)
7296 def GetNumInvalidValues(self
, func
):
7297 """overridden from Argument."""
7298 if func
.IsImmediate():
7302 def GetInvalidArg(self
, index
):
7303 """overridden from Argument."""
7304 return ("-1", "kNoError", "GL_INVALID_VALUE")
7306 def WriteValidationCode(self
, file, func
):
7307 """overridden from Argument."""
7308 file.Write(" if (%s < 0) {\n" % self
.name
)
7310 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
7311 (func
.original_name
, self
.name
))
7312 file.Write(" return error::kNoError;\n")
7315 def WriteClientSideValidationCode(self
, file, func
):
7316 """overridden from Argument."""
7317 file.Write(" if (%s < 0) {\n" % self
.name
)
7319 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
7320 (func
.original_name
, self
.name
))
7321 file.Write(" return;\n")
7325 class SizeNotNegativeArgument(SizeArgument
):
7326 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
7328 def __init__(self
, name
, type, gl_type
):
7329 SizeArgument
.__init
__(self
, name
, gl_type
)
7331 def GetInvalidArg(self
, index
):
7332 """overridden from SizeArgument."""
7333 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
7335 def WriteValidationCode(self
, file, func
):
7336 """overridden from SizeArgument."""
7340 class EnumBaseArgument(Argument
):
7341 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
7342 ValidatedBoolArgument."""
7344 def __init__(self
, name
, gl_type
, type, gl_error
):
7345 Argument
.__init
__(self
, name
, gl_type
)
7347 self
.local_type
= type
7348 self
.gl_error
= gl_error
7349 name
= type[len(gl_type
):]
7350 self
.type_name
= name
7351 self
.named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
7353 def IsConstant(self
):
7354 return self
.named_type
.IsConstant()
7356 def GetConstantValue(self
):
7357 return self
.named_type
.GetConstantValue()
7359 def WriteValidationCode(self
, file, func
):
7362 if self
.named_type
.IsConstant():
7364 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
7365 (ToUnderscore(self
.type_name
), self
.name
))
7366 if self
.gl_error
== "GL_INVALID_ENUM":
7368 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
7369 (func
.original_name
, self
.name
, self
.name
))
7372 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
7373 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
7374 file.Write(" return error::kNoError;\n")
7377 def WriteClientSideValidationCode(self
, file, func
):
7378 if not self
.named_type
.IsConstant():
7380 file.Write(" if (%s != %s) {" % (self
.name
,
7381 self
.GetConstantValue()))
7383 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
7384 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
7385 if func
.return_type
== "void":
7386 file.Write(" return;\n")
7388 file.Write(" return %s;\n" % func
.GetErrorReturnString())
7391 def GetValidArg(self
, func
):
7392 valid_arg
= func
.GetValidArg(self
)
7393 if valid_arg
!= None:
7395 valid
= self
.named_type
.GetValidValues()
7397 num_valid
= len(valid
)
7400 index
= func
.GetOriginalArgs().index(self
)
7401 return str(index
+ 1)
7403 def GetValidClientSideArg(self
, func
):
7404 """Gets a valid value for this argument."""
7405 return self
.GetValidArg(func
)
7407 def GetValidClientSideCmdArg(self
, func
):
7408 """Gets a valid value for this argument."""
7409 valid_arg
= func
.GetValidArg(self
)
7410 if valid_arg
!= None:
7413 valid
= self
.named_type
.GetValidValues()
7415 num_valid
= len(valid
)
7419 index
= func
.GetOriginalArgs().index(self
)
7420 return str(index
+ 1)
7423 index
= func
.GetCmdArgs().index(self
)
7424 return str(index
+ 1)
7426 def GetValidGLArg(self
, func
):
7427 """Gets a valid value for this argument."""
7428 return self
.GetValidArg(func
)
7430 def GetNumInvalidValues(self
, func
):
7431 """returns the number of invalid values to be tested."""
7432 return len(self
.named_type
.GetInvalidValues())
7434 def GetInvalidArg(self
, index
):
7435 """returns an invalid value by index."""
7436 invalid
= self
.named_type
.GetInvalidValues()
7438 num_invalid
= len(invalid
)
7439 if index
>= num_invalid
:
7440 index
= num_invalid
- 1
7441 return (invalid
[index
], "kNoError", self
.gl_error
)
7442 return ("---ERROR1---", "kNoError", self
.gl_error
)
7445 class EnumArgument(EnumBaseArgument
):
7446 """A class that represents a GLenum argument"""
7448 def __init__(self
, name
, type):
7449 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
7451 def GetLogArg(self
):
7452 """Overridden from Argument."""
7453 return ("GLES2Util::GetString%s(%s)" %
7454 (self
.type_name
, self
.name
))
7457 class IntArgument(EnumBaseArgument
):
7458 """A class for a GLint argument that can only accept specific values.
7460 For example glTexImage2D takes a GLint for its internalformat
7461 argument instead of a GLenum.
7464 def __init__(self
, name
, type):
7465 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
7468 class ValidatedBoolArgument(EnumBaseArgument
):
7469 """A class for a GLboolean argument that can only accept specific values.
7471 For example glUniformMatrix takes a GLboolean for it's transpose but it
7475 def __init__(self
, name
, type):
7476 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
7478 def GetLogArg(self
):
7479 """Overridden from Argument."""
7480 return 'GLES2Util::GetStringBool(%s)' % self
.name
7483 class BitFieldArgument(EnumBaseArgument
):
7484 """A class for a GLbitfield argument that can only accept specific values.
7486 For example glFenceSync takes a GLbitfield for its flags argument bit it
7490 def __init__(self
, name
, type):
7491 EnumBaseArgument
.__init
__(self
, name
, "GLbitfield", type,
7495 class ImmediatePointerArgument(Argument
):
7496 """A class that represents an immediate argument to a function.
7498 An immediate argument is one where the data follows the command.
7501 def __init__(self
, name
, type):
7502 Argument
.__init
__(self
, name
, type)
7504 def IsPointer(self
):
7507 def GetPointedType(self
):
7508 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
7510 return match
.groupdict()['element_type']
7512 def AddCmdArgs(self
, args
):
7513 """Overridden from Argument."""
7516 def WriteGetCode(self
, file):
7517 """Overridden from Argument."""
7519 " %s %s = GetImmediateDataAs<%s>(\n" %
7520 (self
.type, self
.name
, self
.type))
7521 file.Write(" c, data_size, immediate_data_size);\n")
7523 def WriteValidationCode(self
, file, func
):
7524 """Overridden from Argument."""
7525 file.Write(" if (%s == NULL) {\n" % self
.name
)
7526 file.Write(" return error::kOutOfBounds;\n")
7529 def GetImmediateVersion(self
):
7530 """Overridden from Argument."""
7533 def WriteDestinationInitalizationValidation(self
, file, func
):
7534 """Overridden from Argument."""
7535 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
7537 def GetLogArg(self
):
7538 """Overridden from Argument."""
7539 return "static_cast<const void*>(%s)" % self
.name
7542 class BucketPointerArgument(Argument
):
7543 """A class that represents an bucket argument to a function."""
7545 def __init__(self
, name
, type):
7546 Argument
.__init
__(self
, name
, type)
7548 def AddCmdArgs(self
, args
):
7549 """Overridden from Argument."""
7552 def WriteGetCode(self
, file):
7553 """Overridden from Argument."""
7555 " %s %s = bucket->GetData(0, data_size);\n" %
7556 (self
.type, self
.name
))
7558 def WriteValidationCode(self
, file, func
):
7559 """Overridden from Argument."""
7562 def GetImmediateVersion(self
):
7563 """Overridden from Argument."""
7566 def WriteDestinationInitalizationValidation(self
, file, func
):
7567 """Overridden from Argument."""
7568 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
7570 def GetLogArg(self
):
7571 """Overridden from Argument."""
7572 return "static_cast<const void*>(%s)" % self
.name
7575 class PointerArgument(Argument
):
7576 """A class that represents a pointer argument to a function."""
7578 def __init__(self
, name
, type):
7579 Argument
.__init
__(self
, name
, type)
7581 def IsPointer(self
):
7582 """Returns true if argument is a pointer."""
7585 def IsPointer2D(self
):
7586 """Returns true if argument is a 2D pointer."""
7587 return self
.type.count('*') == 2
7589 def GetPointedType(self
):
7590 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
7592 return match
.groupdict()['element_type']
7594 def GetValidArg(self
, func
):
7595 """Overridden from Argument."""
7596 return "shared_memory_id_, shared_memory_offset_"
7598 def GetValidGLArg(self
, func
):
7599 """Overridden from Argument."""
7600 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
7602 def GetNumInvalidValues(self
, func
):
7603 """Overridden from Argument."""
7606 def GetInvalidArg(self
, index
):
7607 """Overridden from Argument."""
7609 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
7611 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
7612 "kOutOfBounds", None)
7614 def GetLogArg(self
):
7615 """Overridden from Argument."""
7616 return "static_cast<const void*>(%s)" % self
.name
7618 def AddCmdArgs(self
, args
):
7619 """Overridden from Argument."""
7620 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32_t'))
7621 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32_t'))
7623 def WriteGetCode(self
, file):
7624 """Overridden from Argument."""
7626 " %s %s = GetSharedMemoryAs<%s>(\n" %
7627 (self
.type, self
.name
, self
.type))
7629 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
7630 (self
.name
, self
.name
))
7632 def WriteGetAddress(self
, file):
7633 """Overridden from Argument."""
7635 " %s %s = GetSharedMemoryAs<%s>(\n" %
7636 (self
.type, self
.name
, self
.type))
7638 " %s_shm_id, %s_shm_offset, %s_size);\n" %
7639 (self
.name
, self
.name
, self
.name
))
7641 def WriteValidationCode(self
, file, func
):
7642 """Overridden from Argument."""
7643 file.Write(" if (%s == NULL) {\n" % self
.name
)
7644 file.Write(" return error::kOutOfBounds;\n")
7647 def GetImmediateVersion(self
):
7648 """Overridden from Argument."""
7649 return ImmediatePointerArgument(self
.name
, self
.type)
7651 def GetBucketVersion(self
):
7652 """Overridden from Argument."""
7653 if self
.type.find('char') >= 0:
7654 if self
.IsPointer2D():
7655 return InputStringArrayBucketArgument(self
.name
, self
.type)
7656 return InputStringBucketArgument(self
.name
, self
.type)
7657 return BucketPointerArgument(self
.name
, self
.type)
7659 def WriteDestinationInitalizationValidation(self
, file, func
):
7660 """Overridden from Argument."""
7661 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
7664 class InputStringBucketArgument(Argument
):
7665 """A string input argument where the string is passed in a bucket."""
7667 def __init__(self
, name
, type):
7668 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
7671 class InputStringArrayBucketArgument(Argument
):
7672 """A string array input argument where the strings are passed in a bucket."""
7674 def __init__(self
, name
, type):
7675 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
7676 self
._original
_name
= name
7678 def WriteGetCode(self
, file):
7679 """Overridden from Argument."""
7681 const size_t kMinBucketSize = sizeof(GLint);
7682 // Each string has at least |length| in the header and a NUL character.
7683 const size_t kMinStringSize = sizeof(GLint) + 1;
7684 Bucket* bucket = GetBucket(c.%(name)s);
7686 return error::kInvalidArguments;
7688 const size_t bucket_size = bucket->size();
7689 if (bucket_size < kMinBucketSize) {
7690 return error::kInvalidArguments;
7692 const char* bucket_data = bucket->GetDataAs<const char*>(0, bucket_size);
7693 const GLint* header = reinterpret_cast<const GLint*>(bucket_data);
7694 GLsizei count = static_cast<GLsizei>(header[0]);
7696 return error::kInvalidArguments;
7698 const size_t max_count = (bucket_size - kMinBucketSize) / kMinStringSize;
7699 if (max_count < static_cast<size_t>(count)) {
7700 return error::kInvalidArguments;
7702 const GLint* length = header + 1;
7703 scoped_ptr<const char*[]> strs;
7705 strs.reset(new const char*[count]);
7706 const char** %(original_name)s = strs.get();
7707 base::CheckedNumeric<size_t> total_size = sizeof(GLint);
7708 total_size *= count + 1; // Header size.
7709 if (!total_size.IsValid())
7710 return error::kInvalidArguments;
7711 for (GLsizei ii = 0; ii < count; ++ii) {
7712 %(original_name)s[ii] = bucket_data + total_size.ValueOrDefault(0);
7713 total_size += length[ii];
7714 total_size += 1; // NUL char at the end of each char array.
7715 if (!total_size.IsValid() || total_size.ValueOrDefault(0) > bucket_size ||
7716 %(original_name)s[ii][length[ii]] != 0) {
7717 return error::kInvalidArguments;
7720 if (total_size.ValueOrDefault(0) != bucket_size) {
7721 return error::kInvalidArguments;
7726 'original_name': self
._original
_name
,
7729 def GetValidArg(self
, func
):
7730 return "kNameBucketId"
7732 def GetValidGLArg(self
, func
):
7736 class ResourceIdArgument(Argument
):
7737 """A class that represents a resource id argument to a function."""
7739 def __init__(self
, name
, type):
7740 match
= re
.match("(GLid\w+)", type)
7741 self
.resource_type
= match
.group(1)[4:]
7742 if self
.resource_type
== "Sync":
7743 type = type.replace(match
.group(1), "GLsync")
7745 type = type.replace(match
.group(1), "GLuint")
7746 Argument
.__init
__(self
, name
, type)
7748 def WriteGetCode(self
, file):
7749 """Overridden from Argument."""
7750 if self
.type == "GLsync":
7754 file.Write(" %s %s = c.%s;\n" % (my_type
, self
.name
, self
.name
))
7756 def GetValidArg(self
, func
):
7757 return "client_%s_id_" % self
.resource_type
.lower()
7759 def GetValidGLArg(self
, func
):
7760 if self
.resource_type
== "Sync":
7761 return "reinterpret_cast<GLsync>(kService%sId)" % self
.resource_type
7762 return "kService%sId" % self
.resource_type
7765 class ResourceIdBindArgument(Argument
):
7766 """Represents a resource id argument to a bind function."""
7768 def __init__(self
, name
, type):
7769 match
= re
.match("(GLidBind\w+)", type)
7770 self
.resource_type
= match
.group(1)[8:]
7771 type = type.replace(match
.group(1), "GLuint")
7772 Argument
.__init
__(self
, name
, type)
7774 def WriteGetCode(self
, file):
7775 """Overridden from Argument."""
7776 code
= """ %(type)s %(name)s = c.%(name)s;
7778 file.Write(code
% {'type': self
.type, 'name': self
.name
})
7780 def GetValidArg(self
, func
):
7781 return "client_%s_id_" % self
.resource_type
.lower()
7783 def GetValidGLArg(self
, func
):
7784 return "kService%sId" % self
.resource_type
7787 class ResourceIdZeroArgument(Argument
):
7788 """Represents a resource id argument to a function that can be zero."""
7790 def __init__(self
, name
, type):
7791 match
= re
.match("(GLidZero\w+)", type)
7792 self
.resource_type
= match
.group(1)[8:]
7793 type = type.replace(match
.group(1), "GLuint")
7794 Argument
.__init
__(self
, name
, type)
7796 def WriteGetCode(self
, file):
7797 """Overridden from Argument."""
7798 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
7800 def GetValidArg(self
, func
):
7801 return "client_%s_id_" % self
.resource_type
.lower()
7803 def GetValidGLArg(self
, func
):
7804 return "kService%sId" % self
.resource_type
7806 def GetNumInvalidValues(self
, func
):
7807 """returns the number of invalid values to be tested."""
7810 def GetInvalidArg(self
, index
):
7811 """returns an invalid value by index."""
7812 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
7815 class Function(object):
7816 """A class that represents a function."""
7820 'Bind': BindHandler(),
7821 'Create': CreateHandler(),
7822 'Custom': CustomHandler(),
7823 'Data': DataHandler(),
7824 'Delete': DeleteHandler(),
7825 'DELn': DELnHandler(),
7826 'GENn': GENnHandler(),
7827 'GETn': GETnHandler(),
7828 'GLchar': GLcharHandler(),
7829 'GLcharN': GLcharNHandler(),
7830 'HandWritten': HandWrittenHandler(),
7832 'Manual': ManualHandler(),
7833 'PUT': PUTHandler(),
7834 'PUTn': PUTnHandler(),
7835 'PUTSTR': PUTSTRHandler(),
7836 'PUTXn': PUTXnHandler(),
7837 'StateSet': StateSetHandler(),
7838 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
7839 'StateSetFrontBack': StateSetFrontBackHandler(),
7840 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
7841 'StateSetNamedParameter': StateSetNamedParameter(),
7842 'STRn': STRnHandler(),
7843 'Todo': TodoHandler(),
7846 def __init__(self
, name
, info
):
7848 self
.original_name
= info
['original_name']
7850 self
.original_args
= self
.ParseArgs(info
['original_args'])
7852 if 'cmd_args' in info
:
7853 self
.args_for_cmds
= self
.ParseArgs(info
['cmd_args'])
7855 self
.args_for_cmds
= self
.original_args
[:]
7857 self
.return_type
= info
['return_type']
7858 if self
.return_type
!= 'void':
7859 self
.return_arg
= CreateArg(info
['return_type'] + " result")
7861 self
.return_arg
= None
7863 self
.num_pointer_args
= sum(
7864 [1 for arg
in self
.args_for_cmds
if arg
.IsPointer()])
7865 if self
.num_pointer_args
> 0:
7866 for arg
in reversed(self
.original_args
):
7868 self
.last_original_pointer_arg
= arg
7871 self
.last_original_pointer_arg
= None
7873 self
.type_handler
= self
.type_handlers
[info
['type']]
7874 self
.can_auto_generate
= (self
.num_pointer_args
== 0 and
7875 info
['return_type'] == "void")
7878 def ParseArgs(self
, arg_string
):
7879 """Parses a function arg string."""
7881 parts
= arg_string
.split(',')
7882 for arg_string
in parts
:
7883 arg
= CreateArg(arg_string
)
7888 def IsType(self
, type_name
):
7889 """Returns true if function is a certain type."""
7890 return self
.info
['type'] == type_name
7892 def InitFunction(self
):
7893 """Creates command args and calls the init function for the type handler.
7895 Creates argument lists for command buffer commands, eg. self.cmd_args and
7897 Calls the type function initialization.
7898 Override to create different kind of command buffer command argument lists.
7901 for arg
in self
.args_for_cmds
:
7902 arg
.AddCmdArgs(self
.cmd_args
)
7905 for arg
in self
.args_for_cmds
:
7906 arg
.AddInitArgs(self
.init_args
)
7909 self
.init_args
.append(self
.return_arg
)
7911 self
.type_handler
.InitFunction(self
)
7913 def IsImmediate(self
):
7914 """Returns whether the function is immediate data function or not."""
7918 """Returns whether the function has service side validation or not."""
7919 return self
.GetInfo('unsafe', False)
7921 def GetInfo(self
, name
, default
= None):
7922 """Returns a value from the function info for this function."""
7923 if name
in self
.info
:
7924 return self
.info
[name
]
7927 def GetValidArg(self
, arg
):
7928 """Gets a valid argument value for the parameter arg from the function info
7931 index
= self
.GetOriginalArgs().index(arg
)
7935 valid_args
= self
.GetInfo('valid_args')
7936 if valid_args
and str(index
) in valid_args
:
7937 return valid_args
[str(index
)]
7940 def AddInfo(self
, name
, value
):
7942 self
.info
[name
] = value
7944 def IsExtension(self
):
7945 return self
.GetInfo('extension') or self
.GetInfo('extension_flag')
7947 def IsCoreGLFunction(self
):
7948 return (not self
.IsExtension() and
7949 not self
.GetInfo('pepper_interface') and
7950 not self
.IsUnsafe())
7952 def InPepperInterface(self
, interface
):
7953 ext
= self
.GetInfo('pepper_interface')
7954 if not interface
.GetName():
7955 return self
.IsCoreGLFunction()
7956 return ext
== interface
.GetName()
7958 def InAnyPepperExtension(self
):
7959 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
7961 def GetErrorReturnString(self
):
7962 if self
.GetInfo("error_return"):
7963 return self
.GetInfo("error_return")
7964 elif self
.return_type
== "GLboolean":
7966 elif "*" in self
.return_type
:
7970 def GetGLFunctionName(self
):
7971 """Gets the function to call to execute GL for this command."""
7972 if self
.GetInfo('decoder_func'):
7973 return self
.GetInfo('decoder_func')
7974 return "gl%s" % self
.original_name
7976 def GetGLTestFunctionName(self
):
7977 gl_func_name
= self
.GetInfo('gl_test_func')
7978 if gl_func_name
== None:
7979 gl_func_name
= self
.GetGLFunctionName()
7980 if gl_func_name
.startswith("gl"):
7981 gl_func_name
= gl_func_name
[2:]
7983 gl_func_name
= self
.original_name
7986 def GetDataTransferMethods(self
):
7987 return self
.GetInfo('data_transfer_methods',
7988 ['immediate' if self
.num_pointer_args
== 1 else 'shm'])
7990 def AddCmdArg(self
, arg
):
7991 """Adds a cmd argument to this function."""
7992 self
.cmd_args
.append(arg
)
7994 def GetCmdArgs(self
):
7995 """Gets the command args for this function."""
7996 return self
.cmd_args
7998 def ClearCmdArgs(self
):
7999 """Clears the command args for this function."""
8002 def GetCmdConstants(self
):
8003 """Gets the constants for this function."""
8004 return [arg
for arg
in self
.args_for_cmds
if arg
.IsConstant()]
8006 def GetInitArgs(self
):
8007 """Gets the init args for this function."""
8008 return self
.init_args
8010 def GetOriginalArgs(self
):
8011 """Gets the original arguments to this function."""
8012 return self
.original_args
8014 def GetLastOriginalArg(self
):
8015 """Gets the last original argument to this function."""
8016 return self
.original_args
[len(self
.original_args
) - 1]
8018 def GetLastOriginalPointerArg(self
):
8019 return self
.last_original_pointer_arg
8021 def GetResourceIdArg(self
):
8022 for arg
in self
.original_args
:
8023 if hasattr(arg
, 'resource_type'):
8027 def _MaybePrependComma(self
, arg_string
, add_comma
):
8028 """Adds a comma if arg_string is not empty and add_comma is true."""
8030 if add_comma
and len(arg_string
):
8032 return "%s%s" % (comma
, arg_string
)
8034 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
8035 """Gets a list of arguments as they are in GL."""
8036 args
= self
.GetOriginalArgs()
8037 arg_string
= ", ".join(
8038 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
8039 return self
._MaybePrependComma
(arg_string
, add_comma
)
8041 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
8042 """Gets the list of arguments as they are in GL."""
8043 args
= self
.GetOriginalArgs()
8044 arg_string
= separator
.join(
8045 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
8046 return self
._MaybePrependComma
(arg_string
, add_comma
)
8048 def MakeTypedHelperArgString(self
, prefix
, add_comma
= False):
8049 """Gets a list of typed GL arguments after removing unneeded arguments."""
8050 args
= self
.GetOriginalArgs()
8051 arg_string
= ", ".join(
8056 ) for arg
in args
if not arg
.IsConstant()])
8057 return self
._MaybePrependComma
(arg_string
, add_comma
)
8059 def MakeHelperArgString(self
, prefix
, add_comma
= False, separator
= ", "):
8060 """Gets a list of GL arguments after removing unneeded arguments."""
8061 args
= self
.GetOriginalArgs()
8062 arg_string
= separator
.join(
8063 ["%s%s" % (prefix
, arg
.name
)
8064 for arg
in args
if not arg
.IsConstant()])
8065 return self
._MaybePrependComma
(arg_string
, add_comma
)
8067 def MakeTypedPepperArgString(self
, prefix
):
8068 """Gets a list of arguments as they need to be for Pepper."""
8069 if self
.GetInfo("pepper_args"):
8070 return self
.GetInfo("pepper_args")
8072 return self
.MakeTypedOriginalArgString(prefix
, False)
8074 def MapCTypeToPepperIdlType(self
, ctype
, is_for_return_type
=False):
8075 """Converts a C type name to the corresponding Pepper IDL type."""
8077 'char*': '[out] str_t',
8078 'const GLchar* const*': '[out] cstr_t',
8079 'const char*': 'cstr_t',
8080 'const void*': 'mem_t',
8081 'void*': '[out] mem_t',
8082 'void**': '[out] mem_ptr_t',
8084 # We use "GLxxx_ptr_t" for "GLxxx*".
8085 matched
= re
.match(r
'(const )?(GL\w+)\*$', ctype
)
8087 idltype
= matched
.group(2) + '_ptr_t'
8088 if not matched
.group(1):
8089 idltype
= '[out] ' + idltype
8090 # If an in/out specifier is not specified yet, prepend [in].
8091 if idltype
[0] != '[':
8092 idltype
= '[in] ' + idltype
8093 # Strip the in/out specifier for a return type.
8094 if is_for_return_type
:
8095 idltype
= re
.sub(r
'\[\w+\] ', '', idltype
)
8098 def MakeTypedPepperIdlArgStrings(self
):
8099 """Gets a list of arguments as they need to be for Pepper IDL."""
8100 args
= self
.GetOriginalArgs()
8101 return ["%s %s" % (self
.MapCTypeToPepperIdlType(arg
.type), arg
.name
)
8104 def GetPepperName(self
):
8105 if self
.GetInfo("pepper_name"):
8106 return self
.GetInfo("pepper_name")
8109 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
8110 """Gets a typed list of arguments as they need to be for command buffers."""
8111 args
= self
.GetCmdArgs()
8112 arg_string
= ", ".join(
8113 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
8114 return self
._MaybePrependComma
(arg_string
, add_comma
)
8116 def MakeCmdArgString(self
, prefix
, add_comma
= False):
8117 """Gets the list of arguments as they need to be for command buffers."""
8118 args
= self
.GetCmdArgs()
8119 arg_string
= ", ".join(
8120 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
8121 return self
._MaybePrependComma
(arg_string
, add_comma
)
8123 def MakeTypedInitString(self
, prefix
, add_comma
= False):
8124 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
8125 args
= self
.GetInitArgs()
8126 arg_string
= ", ".join(
8127 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
8128 return self
._MaybePrependComma
(arg_string
, add_comma
)
8130 def MakeInitString(self
, prefix
, add_comma
= False):
8131 """Gets the list of arguments as they need to be for cmd Init/Set."""
8132 args
= self
.GetInitArgs()
8133 arg_string
= ", ".join(
8134 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
8135 return self
._MaybePrependComma
(arg_string
, add_comma
)
8137 def MakeLogArgString(self
):
8138 """Makes a string of the arguments for the LOG macros"""
8139 args
= self
.GetOriginalArgs()
8140 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
8142 def WriteCommandDescription(self
, file):
8143 """Writes a description of the command."""
8144 file.Write("//! Command that corresponds to gl%s.\n" % self
.original_name
)
8146 def WriteHandlerValidation(self
, file):
8147 """Writes validation code for the function."""
8148 for arg
in self
.GetOriginalArgs():
8149 arg
.WriteValidationCode(file, self
)
8150 self
.WriteValidationCode(file)
8152 def WriteHandlerImplementation(self
, file):
8153 """Writes the handler implementation for this command."""
8154 self
.type_handler
.WriteHandlerImplementation(self
, file)
8156 def WriteValidationCode(self
, file):
8157 """Writes the validation code for a command."""
8160 def WriteCmdFlag(self
, file):
8161 """Writes the cmd cmd_flags constant."""
8163 # By default trace only at the highest level 3.
8164 trace_level
= int(self
.GetInfo('trace_level', default
= 3))
8165 if trace_level
not in xrange(0, 4):
8166 raise KeyError("Unhandled trace_level: %d" % trace_level
)
8168 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
8171 cmd_flags
= ' | '.join(flags
)
8175 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
8178 def WriteCmdArgFlag(self
, file):
8179 """Writes the cmd kArgFlags constant."""
8180 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
8182 def WriteCmdComputeSize(self
, file):
8183 """Writes the ComputeSize function for the command."""
8184 file.Write(" static uint32_t ComputeSize() {\n")
8186 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
8190 def WriteCmdSetHeader(self
, file):
8191 """Writes the cmd's SetHeader function."""
8192 file.Write(" void SetHeader() {\n")
8193 file.Write(" header.SetCmd<ValueType>();\n")
8197 def WriteCmdInit(self
, file):
8198 """Writes the cmd's Init function."""
8199 file.Write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
8200 file.Write(" SetHeader();\n")
8201 args
= self
.GetCmdArgs()
8203 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
8207 def WriteCmdSet(self
, file):
8208 """Writes the cmd's Set function."""
8209 copy_args
= self
.MakeCmdArgString("_", False)
8210 file.Write(" void* Set(void* cmd%s) {\n" %
8211 self
.MakeTypedCmdArgString("_", True))
8212 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
8213 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
8217 def WriteStruct(self
, file):
8218 self
.type_handler
.WriteStruct(self
, file)
8220 def WriteDocs(self
, file):
8221 self
.type_handler
.WriteDocs(self
, file)
8223 def WriteCmdHelper(self
, file):
8224 """Writes the cmd's helper."""
8225 self
.type_handler
.WriteCmdHelper(self
, file)
8227 def WriteServiceImplementation(self
, file):
8228 """Writes the service implementation for a command."""
8229 self
.type_handler
.WriteServiceImplementation(self
, file)
8231 def WriteServiceUnitTest(self
, file, *extras
):
8232 """Writes the service implementation for a command."""
8233 self
.type_handler
.WriteServiceUnitTest(self
, file, *extras
)
8235 def WriteGLES2CLibImplementation(self
, file):
8236 """Writes the GLES2 C Lib Implemention."""
8237 self
.type_handler
.WriteGLES2CLibImplementation(self
, file)
8239 def WriteGLES2InterfaceHeader(self
, file):
8240 """Writes the GLES2 Interface declaration."""
8241 self
.type_handler
.WriteGLES2InterfaceHeader(self
, file)
8243 def WriteGLES2InterfaceStub(self
, file):
8244 """Writes the GLES2 Interface Stub declaration."""
8245 self
.type_handler
.WriteGLES2InterfaceStub(self
, file)
8247 def WriteGLES2InterfaceStubImpl(self
, file):
8248 """Writes the GLES2 Interface Stub declaration."""
8249 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, file)
8251 def WriteGLES2ImplementationHeader(self
, file):
8252 """Writes the GLES2 Implemention declaration."""
8253 self
.type_handler
.WriteGLES2ImplementationHeader(self
, file)
8255 def WriteGLES2Implementation(self
, file):
8256 """Writes the GLES2 Implemention definition."""
8257 self
.type_handler
.WriteGLES2Implementation(self
, file)
8259 def WriteGLES2TraceImplementationHeader(self
, file):
8260 """Writes the GLES2 Trace Implemention declaration."""
8261 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, file)
8263 def WriteGLES2TraceImplementation(self
, file):
8264 """Writes the GLES2 Trace Implemention definition."""
8265 self
.type_handler
.WriteGLES2TraceImplementation(self
, file)
8267 def WriteGLES2Header(self
, file):
8268 """Writes the GLES2 Implemention unit test."""
8269 self
.type_handler
.WriteGLES2Header(self
, file)
8271 def WriteGLES2ImplementationUnitTest(self
, file):
8272 """Writes the GLES2 Implemention unit test."""
8273 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, file)
8275 def WriteDestinationInitalizationValidation(self
, file):
8276 """Writes the client side destintion initialization validation."""
8277 self
.type_handler
.WriteDestinationInitalizationValidation(self
, file)
8279 def WriteFormatTest(self
, file):
8280 """Writes the cmd's format test."""
8281 self
.type_handler
.WriteFormatTest(self
, file)
8284 class PepperInterface(object):
8285 """A class that represents a function."""
8287 def __init__(self
, info
):
8288 self
.name
= info
["name"]
8289 self
.dev
= info
["dev"]
8294 def GetInterfaceName(self
):
8298 upperint
= "_" + self
.name
.upper()
8301 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
8303 def GetInterfaceString(self
):
8307 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
8309 def GetStructName(self
):
8313 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
8316 class ImmediateFunction(Function
):
8317 """A class that represnets an immediate function command."""
8319 def __init__(self
, func
):
8322 "%sImmediate" % func
.name
,
8325 def InitFunction(self
):
8326 # Override args in original_args and args_for_cmds with immediate versions
8329 new_original_args
= []
8330 for arg
in self
.original_args
:
8331 new_arg
= arg
.GetImmediateVersion()
8333 new_original_args
.append(new_arg
)
8334 self
.original_args
= new_original_args
8336 new_args_for_cmds
= []
8337 for arg
in self
.args_for_cmds
:
8338 new_arg
= arg
.GetImmediateVersion()
8340 new_args_for_cmds
.append(new_arg
)
8342 self
.args_for_cmds
= new_args_for_cmds
8344 Function
.InitFunction(self
)
8346 def IsImmediate(self
):
8349 def WriteCommandDescription(self
, file):
8350 """Overridden from Function"""
8351 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
8354 def WriteServiceImplementation(self
, file):
8355 """Overridden from Function"""
8356 self
.type_handler
.WriteImmediateServiceImplementation(self
, file)
8358 def WriteHandlerImplementation(self
, file):
8359 """Overridden from Function"""
8360 self
.type_handler
.WriteImmediateHandlerImplementation(self
, file)
8362 def WriteServiceUnitTest(self
, file, *extras
):
8363 """Writes the service implementation for a command."""
8364 self
.type_handler
.WriteImmediateServiceUnitTest(self
, file, *extras
)
8366 def WriteValidationCode(self
, file):
8367 """Overridden from Function"""
8368 self
.type_handler
.WriteImmediateValidationCode(self
, file)
8370 def WriteCmdArgFlag(self
, file):
8371 """Overridden from Function"""
8372 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
8374 def WriteCmdComputeSize(self
, file):
8375 """Overridden from Function"""
8376 self
.type_handler
.WriteImmediateCmdComputeSize(self
, file)
8378 def WriteCmdSetHeader(self
, file):
8379 """Overridden from Function"""
8380 self
.type_handler
.WriteImmediateCmdSetHeader(self
, file)
8382 def WriteCmdInit(self
, file):
8383 """Overridden from Function"""
8384 self
.type_handler
.WriteImmediateCmdInit(self
, file)
8386 def WriteCmdSet(self
, file):
8387 """Overridden from Function"""
8388 self
.type_handler
.WriteImmediateCmdSet(self
, file)
8390 def WriteCmdHelper(self
, file):
8391 """Overridden from Function"""
8392 self
.type_handler
.WriteImmediateCmdHelper(self
, file)
8394 def WriteFormatTest(self
, file):
8395 """Overridden from Function"""
8396 self
.type_handler
.WriteImmediateFormatTest(self
, file)
8399 class BucketFunction(Function
):
8400 """A class that represnets a bucket version of a function command."""
8402 def __init__(self
, func
):
8405 "%sBucket" % func
.name
,
8408 def InitFunction(self
):
8409 # Override args in original_args and args_for_cmds with bucket versions
8412 new_original_args
= []
8413 for arg
in self
.original_args
:
8414 new_arg
= arg
.GetBucketVersion()
8416 new_original_args
.append(new_arg
)
8417 self
.original_args
= new_original_args
8419 new_args_for_cmds
= []
8420 for arg
in self
.args_for_cmds
:
8421 new_arg
= arg
.GetBucketVersion()
8423 new_args_for_cmds
.append(new_arg
)
8425 self
.args_for_cmds
= new_args_for_cmds
8427 Function
.InitFunction(self
)
8429 def WriteCommandDescription(self
, file):
8430 """Overridden from Function"""
8431 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
8434 def WriteServiceImplementation(self
, file):
8435 """Overridden from Function"""
8436 self
.type_handler
.WriteBucketServiceImplementation(self
, file)
8438 def WriteHandlerImplementation(self
, file):
8439 """Overridden from Function"""
8440 self
.type_handler
.WriteBucketHandlerImplementation(self
, file)
8442 def WriteServiceUnitTest(self
, file, *extras
):
8443 """Overridden from Function"""
8444 self
.type_handler
.WriteBucketServiceUnitTest(self
, file, *extras
)
8446 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
8447 """Overridden from Function"""
8448 args
= self
.GetOriginalArgs()
8449 arg_string
= separator
.join(
8450 ["%s%s" % (prefix
, arg
.name
[0:-10] if arg
.name
.endswith("_bucket_id")
8451 else arg
.name
) for arg
in args
])
8452 return super(BucketFunction
, self
)._MaybePrependComma
(arg_string
, add_comma
)
8455 def CreateArg(arg_string
):
8456 """Creates an Argument."""
8457 arg_parts
= arg_string
.split()
8458 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
8460 # Is this a pointer argument?
8461 elif arg_string
.find('*') >= 0:
8462 return PointerArgument(
8464 " ".join(arg_parts
[0:-1]))
8465 # Is this a resource argument? Must come after pointer check.
8466 elif arg_parts
[0].startswith('GLidBind'):
8467 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8468 elif arg_parts
[0].startswith('GLidZero'):
8469 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8470 elif arg_parts
[0].startswith('GLid'):
8471 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8472 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
8473 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8474 elif arg_parts
[0].startswith('GLbitfield') and len(arg_parts
[0]) > 10:
8475 return BitFieldArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8476 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
8477 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8478 elif arg_parts
[0].startswith('GLboolean'):
8479 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8480 elif arg_parts
[0].startswith('GLintUniformLocation'):
8481 return UniformLocationArgument(arg_parts
[-1])
8482 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
8483 not arg_parts
[0].startswith('GLintptr')):
8484 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8485 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
8486 arg_parts
[0].startswith('GLintptrNotNegative')):
8487 return SizeNotNegativeArgument(arg_parts
[-1],
8488 " ".join(arg_parts
[0:-1]),
8489 arg_parts
[0][0:-11])
8490 elif arg_parts
[0].startswith('GLsize'):
8491 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8493 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
8496 class GLGenerator(object):
8497 """A class to generate GL command buffers."""
8499 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
8501 def __init__(self
, verbose
):
8502 self
.original_functions
= []
8504 self
.verbose
= verbose
8506 self
.pepper_interfaces
= []
8507 self
.interface_info
= {}
8508 self
.generated_cpp_filenames
= []
8510 for interface
in _PEPPER_INTERFACES
:
8511 interface
= PepperInterface(interface
)
8512 self
.pepper_interfaces
.append(interface
)
8513 self
.interface_info
[interface
.GetName()] = interface
8515 def AddFunction(self
, func
):
8516 """Adds a function."""
8517 self
.functions
.append(func
)
8519 def GetFunctionInfo(self
, name
):
8520 """Gets a type info for the given function name."""
8521 if name
in _FUNCTION_INFO
:
8522 func_info
= _FUNCTION_INFO
[name
].copy()
8526 if not 'type' in func_info
:
8527 func_info
['type'] = ''
8532 """Prints something if verbose is true."""
8536 def Error(self
, msg
):
8537 """Prints an error."""
8538 print "Error: %s" % msg
8541 def WriteLicense(self
, file):
8542 """Writes the license."""
8543 file.Write(_LICENSE
)
8545 def WriteNamespaceOpen(self
, file):
8546 """Writes the code for the namespace."""
8547 file.Write("namespace gpu {\n")
8548 file.Write("namespace gles2 {\n")
8551 def WriteNamespaceClose(self
, file):
8552 """Writes the code to close the namespace."""
8553 file.Write("} // namespace gles2\n")
8554 file.Write("} // namespace gpu\n")
8557 def ParseGLH(self
, filename
):
8558 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
8559 f
= open(filename
, "r")
8560 functions
= f
.read()
8562 for line
in functions
.splitlines():
8563 match
= self
._function
_re
.match(line
)
8565 func_name
= match
.group(2)[2:]
8566 func_info
= self
.GetFunctionInfo(func_name
)
8567 if func_info
['type'] == 'Noop':
8570 parsed_func_info
= {
8571 'original_name': func_name
,
8572 'original_args': match
.group(3),
8573 'return_type': match
.group(1).strip(),
8576 for k
in parsed_func_info
.keys():
8577 if not k
in func_info
:
8578 func_info
[k
] = parsed_func_info
[k
]
8580 f
= Function(func_name
, func_info
)
8581 self
.original_functions
.append(f
)
8583 #for arg in f.GetOriginalArgs():
8584 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
8585 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
8587 gen_cmd
= f
.GetInfo('gen_cmd')
8588 if gen_cmd
== True or gen_cmd
== None:
8589 if f
.type_handler
.NeedsDataTransferFunction(f
):
8590 methods
= f
.GetDataTransferMethods()
8591 if 'immediate' in methods
:
8592 self
.AddFunction(ImmediateFunction(f
))
8593 if 'bucket' in methods
:
8594 self
.AddFunction(BucketFunction(f
))
8595 if 'shm' in methods
:
8600 self
.Log("Auto Generated Functions : %d" %
8601 len([f
for f
in self
.functions
if f
.can_auto_generate
or
8602 (not f
.IsType('') and not f
.IsType('Custom') and
8603 not f
.IsType('Todo'))]))
8605 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
8606 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
8607 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
8610 self
.Log(" %-10s %-20s gl%s" % (f
.info
['type'], f
.return_type
, f
.name
))
8612 def WriteCommandIds(self
, filename
):
8613 """Writes the command buffer format"""
8614 file = CHeaderWriter(filename
)
8615 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
8617 for func
in self
.functions
:
8618 file.Write(" %-60s /* %d */ \\\n" %
8619 ("OP(%s)" % func
.name
, id))
8623 file.Write("enum CommandId {\n")
8624 file.Write(" kStartPoint = cmd::kLastCommonId, "
8625 "// All GLES2 commands start after this.\n")
8626 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
8627 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
8628 file.Write("#undef GLES2_CMD_OP\n")
8629 file.Write(" kNumCommands\n")
8633 self
.generated_cpp_filenames
.append(file.filename
)
8635 def WriteFormat(self
, filename
):
8636 """Writes the command buffer format"""
8637 file = CHeaderWriter(filename
)
8638 for func
in self
.functions
:
8640 #gen_cmd = func.GetInfo('gen_cmd')
8641 #if gen_cmd == True or gen_cmd == None:
8642 func
.WriteStruct(file)
8645 self
.generated_cpp_filenames
.append(file.filename
)
8647 def WriteDocs(self
, filename
):
8648 """Writes the command buffer doc version of the commands"""
8649 file = CWriter(filename
)
8650 for func
in self
.functions
:
8652 #gen_cmd = func.GetInfo('gen_cmd')
8653 #if gen_cmd == True or gen_cmd == None:
8654 func
.WriteDocs(file)
8657 self
.generated_cpp_filenames
.append(file.filename
)
8659 def WriteFormatTest(self
, filename
):
8660 """Writes the command buffer format test."""
8661 file = CHeaderWriter(
8663 "// This file contains unit tests for gles2 commmands\n"
8664 "// It is included by gles2_cmd_format_test.cc\n"
8667 for func
in self
.functions
:
8669 #gen_cmd = func.GetInfo('gen_cmd')
8670 #if gen_cmd == True or gen_cmd == None:
8671 func
.WriteFormatTest(file)
8674 self
.generated_cpp_filenames
.append(file.filename
)
8676 def WriteCmdHelperHeader(self
, filename
):
8677 """Writes the gles2 command helper."""
8678 file = CHeaderWriter(filename
)
8680 for func
in self
.functions
:
8682 #gen_cmd = func.GetInfo('gen_cmd')
8683 #if gen_cmd == True or gen_cmd == None:
8684 func
.WriteCmdHelper(file)
8687 self
.generated_cpp_filenames
.append(file.filename
)
8689 def WriteServiceContextStateHeader(self
, filename
):
8690 """Writes the service context state header."""
8691 file = CHeaderWriter(
8693 "// It is included by context_state.h\n")
8694 file.Write("struct EnableFlags {\n")
8695 file.Write(" EnableFlags();\n")
8696 for capability
in _CAPABILITY_FLAGS
:
8697 file.Write(" bool %s;\n" % capability
['name'])
8698 file.Write(" bool cached_%s;\n" % capability
['name'])
8699 file.Write("};\n\n")
8701 for state_name
in sorted(_STATES
.keys()):
8702 state
= _STATES
[state_name
]
8703 for item
in state
['states']:
8704 if isinstance(item
['default'], list):
8705 file.Write("%s %s[%d];\n" % (item
['type'], item
['name'],
8706 len(item
['default'])))
8708 file.Write("%s %s;\n" % (item
['type'], item
['name']))
8710 if item
.get('cached', False):
8711 if isinstance(item
['default'], list):
8712 file.Write("%s cached_%s[%d];\n" % (item
['type'], item
['name'],
8713 len(item
['default'])))
8715 file.Write("%s cached_%s;\n" % (item
['type'], item
['name']))
8720 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
8723 for capability
in _CAPABILITY_FLAGS
:
8726 """ % capability
['name'].upper())
8728 if (enable_flags.cached_%(name)s == enable &&
8729 !ignore_cached_state)
8731 enable_flags.cached_%(name)s = enable;
8748 self
.generated_cpp_filenames
.append(file.filename
)
8750 def WriteClientContextStateHeader(self
, filename
):
8751 """Writes the client context state header."""
8752 file = CHeaderWriter(
8754 "// It is included by client_context_state.h\n")
8755 file.Write("struct EnableFlags {\n")
8756 file.Write(" EnableFlags();\n")
8757 for capability
in _CAPABILITY_FLAGS
:
8758 file.Write(" bool %s;\n" % capability
['name'])
8759 file.Write("};\n\n")
8762 self
.generated_cpp_filenames
.append(file.filename
)
8764 def WriteContextStateGetters(self
, file, class_name
):
8765 """Writes the state getters."""
8766 for gl_type
in ["GLint", "GLfloat"]:
8768 bool %s::GetStateAs%s(
8769 GLenum pname, %s* params, GLsizei* num_written) const {
8771 """ % (class_name
, gl_type
, gl_type
))
8772 for state_name
in sorted(_STATES
.keys()):
8773 state
= _STATES
[state_name
]
8775 file.Write(" case %s:\n" % state
['enum'])
8776 file.Write(" *num_written = %d;\n" % len(state
['states']))
8777 file.Write(" if (params) {\n")
8778 for ndx
,item
in enumerate(state
['states']):
8779 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
8780 (ndx
, gl_type
, item
['name']))
8782 file.Write(" return true;\n")
8784 for item
in state
['states']:
8785 file.Write(" case %s:\n" % item
['enum'])
8786 if isinstance(item
['default'], list):
8787 item_len
= len(item
['default'])
8788 file.Write(" *num_written = %d;\n" % item_len
)
8789 file.Write(" if (params) {\n")
8790 if item
['type'] == gl_type
:
8791 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
8792 (item
['name'], item
['type'], item_len
))
8794 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
8796 file.Write(" params[i] = %s;\n" %
8797 (GetGLGetTypeConversion(gl_type
, item
['type'],
8798 "%s[i]" % item
['name'])))
8801 file.Write(" *num_written = 1;\n")
8802 file.Write(" if (params) {\n")
8803 file.Write(" params[0] = %s;\n" %
8804 (GetGLGetTypeConversion(gl_type
, item
['type'],
8807 file.Write(" return true;\n")
8808 for capability
in _CAPABILITY_FLAGS
:
8809 file.Write(" case GL_%s:\n" % capability
['name'].upper())
8810 file.Write(" *num_written = 1;\n")
8811 file.Write(" if (params) {\n")
8813 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
8814 (gl_type
, capability
['name']))
8816 file.Write(" return true;\n")
8817 file.Write(""" default:
8823 def WriteServiceContextStateImpl(self
, filename
):
8824 """Writes the context state service implementation."""
8825 file = CHeaderWriter(
8827 "// It is included by context_state.cc\n")
8829 for capability
in _CAPABILITY_FLAGS
:
8830 code
.append("%s(%s)" %
8831 (capability
['name'],
8832 ('false', 'true')['default' in capability
]))
8833 code
.append("cached_%s(%s)" %
8834 (capability
['name'],
8835 ('false', 'true')['default' in capability
]))
8836 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
8840 file.Write("void ContextState::Initialize() {\n")
8841 for state_name
in sorted(_STATES
.keys()):
8842 state
= _STATES
[state_name
]
8843 for item
in state
['states']:
8844 if isinstance(item
['default'], list):
8845 for ndx
, value
in enumerate(item
['default']):
8846 file.Write(" %s[%d] = %s;\n" % (item
['name'], ndx
, value
))
8848 file.Write(" %s = %s;\n" % (item
['name'], item
['default']))
8849 if item
.get('cached', False):
8850 if isinstance(item
['default'], list):
8851 for ndx
, value
in enumerate(item
['default']):
8852 file.Write(" cached_%s[%d] = %s;\n" % (item
['name'], ndx
, value
))
8854 file.Write(" cached_%s = %s;\n" % (item
['name'], item
['default']))
8858 void ContextState::InitCapabilities(const ContextState* prev_state) const {
8860 def WriteCapabilities(test_prev
):
8861 for capability
in _CAPABILITY_FLAGS
:
8862 capability_name
= capability
['name']
8864 file.Write(""" if (prev_state->enable_flags.cached_%s !=
8865 enable_flags.cached_%s)\n""" %
8866 (capability_name
, capability_name
))
8867 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
8868 (capability_name
.upper(), capability_name
))
8870 file.Write(" if (prev_state) {")
8871 WriteCapabilities(True)
8872 file.Write(" } else {")
8873 WriteCapabilities(False)
8878 void ContextState::InitState(const ContextState *prev_state) const {
8881 def WriteStates(test_prev
):
8882 # We need to sort the keys so the expectations match
8883 for state_name
in sorted(_STATES
.keys()):
8884 state
= _STATES
[state_name
]
8885 if state
['type'] == 'FrontBack':
8886 num_states
= len(state
['states'])
8887 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
8891 for place
, item
in enumerate(group
):
8892 item_name
= CachedStateName(item
)
8893 args
.append('%s' % item_name
)
8897 file.Write("(%s != prev_state->%s)" % (item_name
, item_name
))
8901 " gl%s(%s, %s);\n" %
8902 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
8903 elif state
['type'] == 'NamedParameter':
8904 for item
in state
['states']:
8905 item_name
= CachedStateName(item
)
8907 if 'extension_flag' in item
:
8908 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
8909 item
['extension_flag'])
8911 if isinstance(item
['default'], list):
8912 file.Write(" if (memcmp(prev_state->%s, %s, "
8913 "sizeof(%s) * %d)) {\n" %
8914 (item_name
, item_name
, item
['type'],
8915 len(item
['default'])))
8917 file.Write(" if (prev_state->%s != %s) {\n " %
8918 (item_name
, item_name
))
8919 file.Write(" gl%s(%s, %s);\n" %
8922 if 'enum_set' in item
else item
['enum']),
8925 if 'extension_flag' in item
:
8928 if 'extension_flag' in item
:
8931 if 'extension_flag' in state
:
8932 file.Write(" if (feature_info_->feature_flags().%s)\n " %
8933 state
['extension_flag'])
8937 for place
, item
in enumerate(state
['states']):
8938 item_name
= CachedStateName(item
)
8939 args
.append('%s' % item_name
)
8943 file.Write("(%s != prev_state->%s)" %
8944 (item_name
, item_name
))
8947 file.Write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
8949 file.Write(" if (prev_state) {")
8951 file.Write(" } else {")
8956 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
8959 for capability
in _CAPABILITY_FLAGS
:
8960 file.Write(" case GL_%s:\n" % capability
['name'].upper())
8961 file.Write(" return enable_flags.%s;\n" % capability
['name'])
8962 file.Write(""" default:
8969 self
.WriteContextStateGetters(file, "ContextState")
8971 self
.generated_cpp_filenames
.append(file.filename
)
8973 def WriteClientContextStateImpl(self
, filename
):
8974 """Writes the context state client side implementation."""
8975 file = CHeaderWriter(
8977 "// It is included by client_context_state.cc\n")
8979 for capability
in _CAPABILITY_FLAGS
:
8980 code
.append("%s(%s)" %
8981 (capability
['name'],
8982 ('false', 'true')['default' in capability
]))
8984 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
8989 bool ClientContextState::SetCapabilityState(
8990 GLenum cap, bool enabled, bool* changed) {
8994 for capability
in _CAPABILITY_FLAGS
:
8995 file.Write(" case GL_%s:\n" % capability
['name'].upper())
8996 file.Write(""" if (enable_flags.%(name)s != enabled) {
8998 enable_flags.%(name)s = enabled;
9002 file.Write(""" default:
9007 file.Write("""bool ClientContextState::GetEnabled(
9008 GLenum cap, bool* enabled) const {
9011 for capability
in _CAPABILITY_FLAGS
:
9012 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9013 file.Write(" *enabled = enable_flags.%s;\n" % capability
['name'])
9014 file.Write(" return true;\n")
9015 file.Write(""" default:
9021 self
.generated_cpp_filenames
.append(file.filename
)
9023 def WriteServiceImplementation(self
, filename
):
9024 """Writes the service decorder implementation."""
9025 file = CHeaderWriter(
9027 "// It is included by gles2_cmd_decoder.cc\n")
9029 for func
in self
.functions
:
9031 #gen_cmd = func.GetInfo('gen_cmd')
9032 #if gen_cmd == True or gen_cmd == None:
9033 func
.WriteServiceImplementation(file)
9036 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
9039 for capability
in _CAPABILITY_FLAGS
:
9040 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9041 if 'state_flag' in capability
:
9044 state_.enable_flags.%(name)s = enabled;
9045 if (state_.enable_flags.cached_%(name)s != enabled
9046 || state_.ignore_cached_state) {
9047 %(state_flag)s = true;
9053 state_.enable_flags.%(name)s = enabled;
9054 if (state_.enable_flags.cached_%(name)s != enabled
9055 || state_.ignore_cached_state) {
9056 state_.enable_flags.cached_%(name)s = enabled;
9061 file.Write(""" default:
9068 self
.generated_cpp_filenames
.append(file.filename
)
9070 def WriteServiceUnitTests(self
, filename
):
9071 """Writes the service decorder unit tests."""
9072 num_tests
= len(self
.functions
)
9073 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
9075 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
9077 name
= filename
% count
9078 file = CHeaderWriter(
9080 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count
)
9081 test_name
= 'GLES2DecoderTest%d' % count
9082 end
= test_num
+ FUNCTIONS_PER_FILE
9085 for idx
in range(test_num
, end
):
9086 func
= self
.functions
[idx
]
9088 # Do any filtering of the functions here, so that the functions
9089 # will not move between the numbered files if filtering properties
9091 if func
.GetInfo('extension_flag'):
9095 #gen_cmd = func.GetInfo('gen_cmd')
9096 #if gen_cmd == True or gen_cmd == None:
9097 if func
.GetInfo('unit_test') == False:
9098 file.Write("// TODO(gman): %s\n" % func
.name
)
9100 func
.WriteServiceUnitTest(file, {
9101 'test_name': test_name
9104 self
.generated_cpp_filenames
.append(file.filename
)
9105 file = CHeaderWriter(
9107 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
9109 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
9111 for capability
in _CAPABILITY_FLAGS
:
9112 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
9113 (capability
['name'].upper(),
9114 ('false', 'true')['default' in capability
]))
9117 void GLES2DecoderTestBase::SetupInitStateExpectations() {
9120 # We need to sort the keys so the expectations match
9121 for state_name
in sorted(_STATES
.keys()):
9122 state
= _STATES
[state_name
]
9123 if state
['type'] == 'FrontBack':
9124 num_states
= len(state
['states'])
9125 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
9128 if 'expected' in item
:
9129 args
.append(item
['expected'])
9131 args
.append(item
['default'])
9133 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
9134 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
9135 file.Write(" .Times(1)\n")
9136 file.Write(" .RetiresOnSaturation();\n")
9137 elif state
['type'] == 'NamedParameter':
9138 for item
in state
['states']:
9139 if 'extension_flag' in item
:
9140 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
9141 item
['extension_flag'])
9143 expect_value
= item
['default']
9144 if isinstance(expect_value
, list):
9145 # TODO: Currently we do not check array values.
9149 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
9152 if 'enum_set' in item
else item
['enum']),
9154 file.Write(" .Times(1)\n")
9155 file.Write(" .RetiresOnSaturation();\n")
9156 if 'extension_flag' in item
:
9159 if 'extension_flag' in state
:
9160 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
9161 state
['extension_flag'])
9164 for item
in state
['states']:
9165 if 'expected' in item
:
9166 args
.append(item
['expected'])
9168 args
.append(item
['default'])
9169 # TODO: Currently we do not check array values.
9170 args
= ["_" if isinstance(arg
, list) else arg
for arg
in args
]
9171 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
9172 (state
['func'], ", ".join(args
)))
9173 file.Write(" .Times(1)\n")
9174 file.Write(" .RetiresOnSaturation();\n")
9175 if 'extension_flag' in state
:
9180 self
.generated_cpp_filenames
.append(file.filename
)
9182 def WriteServiceUnitTestsForExtensions(self
, filename
):
9183 """Writes the service decorder unit tests for functions with extension_flag.
9185 The functions are special in that they need a specific unit test
9186 baseclass to turn on the extension.
9188 functions
= [f
for f
in self
.functions
if f
.GetInfo('extension_flag')]
9189 file = CHeaderWriter(
9191 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
9192 for func
in functions
:
9194 if func
.GetInfo('unit_test') == False:
9195 file.Write("// TODO(gman): %s\n" % func
.name
)
9197 extension
= ToCamelCase(
9198 ToGLExtensionString(func
.GetInfo('extension_flag')))
9199 func
.WriteServiceUnitTest(file, {
9200 'test_name': 'GLES2DecoderTestWith%s' % extension
9204 self
.generated_cpp_filenames
.append(file.filename
)
9206 def WriteGLES2Header(self
, filename
):
9207 """Writes the GLES2 header."""
9208 file = CHeaderWriter(
9210 "// This file contains Chromium-specific GLES2 declarations.\n\n")
9212 for func
in self
.original_functions
:
9213 func
.WriteGLES2Header(file)
9217 self
.generated_cpp_filenames
.append(file.filename
)
9219 def WriteGLES2CLibImplementation(self
, filename
):
9220 """Writes the GLES2 c lib implementation."""
9221 file = CHeaderWriter(
9223 "// These functions emulate GLES2 over command buffers.\n")
9225 for func
in self
.original_functions
:
9226 func
.WriteGLES2CLibImplementation(file)
9231 extern const NameToFunc g_gles2_function_table[] = {
9233 for func
in self
.original_functions
:
9235 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
9236 (func
.name
, func
.name
))
9237 file.Write(""" { NULL, NULL, },
9240 } // namespace gles2
9243 self
.generated_cpp_filenames
.append(file.filename
)
9245 def WriteGLES2InterfaceHeader(self
, filename
):
9246 """Writes the GLES2 interface header."""
9247 file = CHeaderWriter(
9249 "// This file is included by gles2_interface.h to declare the\n"
9250 "// GL api functions.\n")
9251 for func
in self
.original_functions
:
9252 func
.WriteGLES2InterfaceHeader(file)
9254 self
.generated_cpp_filenames
.append(file.filename
)
9256 def WriteGLES2InterfaceStub(self
, filename
):
9257 """Writes the GLES2 interface stub header."""
9258 file = CHeaderWriter(
9260 "// This file is included by gles2_interface_stub.h.\n")
9261 for func
in self
.original_functions
:
9262 func
.WriteGLES2InterfaceStub(file)
9264 self
.generated_cpp_filenames
.append(file.filename
)
9266 def WriteGLES2InterfaceStubImpl(self
, filename
):
9267 """Writes the GLES2 interface header."""
9268 file = CHeaderWriter(
9270 "// This file is included by gles2_interface_stub.cc.\n")
9271 for func
in self
.original_functions
:
9272 func
.WriteGLES2InterfaceStubImpl(file)
9274 self
.generated_cpp_filenames
.append(file.filename
)
9276 def WriteGLES2ImplementationHeader(self
, filename
):
9277 """Writes the GLES2 Implementation header."""
9278 file = CHeaderWriter(
9280 "// This file is included by gles2_implementation.h to declare the\n"
9281 "// GL api functions.\n")
9282 for func
in self
.original_functions
:
9283 func
.WriteGLES2ImplementationHeader(file)
9285 self
.generated_cpp_filenames
.append(file.filename
)
9287 def WriteGLES2Implementation(self
, filename
):
9288 """Writes the GLES2 Implementation."""
9289 file = CHeaderWriter(
9291 "// This file is included by gles2_implementation.cc to define the\n"
9292 "// GL api functions.\n")
9293 for func
in self
.original_functions
:
9294 func
.WriteGLES2Implementation(file)
9296 self
.generated_cpp_filenames
.append(file.filename
)
9298 def WriteGLES2TraceImplementationHeader(self
, filename
):
9299 """Writes the GLES2 Trace Implementation header."""
9300 file = CHeaderWriter(
9302 "// This file is included by gles2_trace_implementation.h\n")
9303 for func
in self
.original_functions
:
9304 func
.WriteGLES2TraceImplementationHeader(file)
9306 self
.generated_cpp_filenames
.append(file.filename
)
9308 def WriteGLES2TraceImplementation(self
, filename
):
9309 """Writes the GLES2 Trace Implementation."""
9310 file = CHeaderWriter(
9312 "// This file is included by gles2_trace_implementation.cc\n")
9313 for func
in self
.original_functions
:
9314 func
.WriteGLES2TraceImplementation(file)
9316 self
.generated_cpp_filenames
.append(file.filename
)
9318 def WriteGLES2ImplementationUnitTests(self
, filename
):
9319 """Writes the GLES2 helper header."""
9320 file = CHeaderWriter(
9322 "// This file is included by gles2_implementation.h to declare the\n"
9323 "// GL api functions.\n")
9324 for func
in self
.original_functions
:
9325 func
.WriteGLES2ImplementationUnitTest(file)
9327 self
.generated_cpp_filenames
.append(file.filename
)
9329 def WriteServiceUtilsHeader(self
, filename
):
9330 """Writes the gles2 auto generated utility header."""
9331 file = CHeaderWriter(filename
)
9332 for name
in sorted(_NAMED_TYPE_INFO
.keys()):
9333 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
9334 if named_type
.IsConstant():
9336 file.Write("ValueValidator<%s> %s;\n" %
9337 (named_type
.GetType(), ToUnderscore(name
)))
9340 self
.generated_cpp_filenames
.append(file.filename
)
9342 def WriteServiceUtilsImplementation(self
, filename
):
9343 """Writes the gles2 auto generated utility implementation."""
9344 file = CHeaderWriter(filename
)
9345 names
= sorted(_NAMED_TYPE_INFO
.keys())
9347 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
9348 if named_type
.IsConstant():
9350 if named_type
.GetValidValues():
9351 file.Write("static const %s valid_%s_table[] = {\n" %
9352 (named_type
.GetType(), ToUnderscore(name
)))
9353 for value
in named_type
.GetValidValues():
9354 file.Write(" %s,\n" % value
)
9357 file.Write("Validators::Validators()")
9359 for count
, name
in enumerate(names
):
9360 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
9361 if named_type
.IsConstant():
9363 if named_type
.GetValidValues():
9364 code
= """%(pre)s%(name)s(
9365 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
9367 code
= "%(pre)s%(name)s()"
9369 'name': ToUnderscore(name
),
9374 file.Write("}\n\n");
9376 self
.generated_cpp_filenames
.append(file.filename
)
9378 def WriteCommonUtilsHeader(self
, filename
):
9379 """Writes the gles2 common utility header."""
9380 file = CHeaderWriter(filename
)
9381 type_infos
= sorted(_NAMED_TYPE_INFO
.keys())
9382 for type_info
in type_infos
:
9383 if _NAMED_TYPE_INFO
[type_info
]['type'] == 'GLenum':
9384 file.Write("static std::string GetString%s(uint32_t value);\n" %
9388 self
.generated_cpp_filenames
.append(file.filename
)
9390 def WriteCommonUtilsImpl(self
, filename
):
9391 """Writes the gles2 common utility header."""
9392 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
9394 for fname
in ['third_party/khronos/GLES2/gl2.h',
9395 'third_party/khronos/GLES2/gl2ext.h',
9396 'third_party/khronos/GLES3/gl3.h',
9397 'gpu/GLES2/gl2chromium.h',
9398 'gpu/GLES2/gl2extchromium.h']:
9399 lines
= open(fname
).readlines()
9401 m
= enum_re
.match(line
)
9405 if len(value
) <= 10:
9406 if not value
in dict:
9408 # check our own _CHROMIUM macro conflicts with khronos GL headers.
9409 elif dict[value
] != name
and (name
.endswith('_CHROMIUM') or
9410 dict[value
].endswith('_CHROMIUM')):
9411 self
.Error("code collision: %s and %s have the same code %s" %
9412 (dict[value
], name
, value
))
9414 file = CHeaderWriter(filename
)
9415 file.Write("static const GLES2Util::EnumToString "
9416 "enum_to_string_table[] = {\n")
9418 file.Write(' { %s, "%s", },\n' % (value
, dict[value
]))
9421 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
9422 enum_to_string_table;
9423 const size_t GLES2Util::enum_to_string_table_len_ =
9424 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
9428 enums
= sorted(_NAMED_TYPE_INFO
.keys())
9430 if _NAMED_TYPE_INFO
[enum
]['type'] == 'GLenum':
9431 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
9433 if len(_NAMED_TYPE_INFO
[enum
]['valid']) > 0:
9434 file.Write(" static const EnumToString string_table[] = {\n")
9435 for value
in _NAMED_TYPE_INFO
[enum
]['valid']:
9436 file.Write(' { %s, "%s" },\n' % (value
, value
))
9438 return GLES2Util::GetQualifiedEnumString(
9439 string_table, arraysize(string_table), value);
9444 file.Write(""" return GLES2Util::GetQualifiedEnumString(
9450 self
.generated_cpp_filenames
.append(file.filename
)
9452 def WritePepperGLES2Interface(self
, filename
, dev
):
9453 """Writes the Pepper OpenGLES interface definition."""
9454 file = CWriter(filename
)
9455 file.Write(_LICENSE
)
9456 file.Write(_DO_NOT_EDIT_WARNING
)
9458 file.Write("label Chrome {\n")
9459 file.Write(" M39 = 1.0\n")
9460 file.Write("};\n\n")
9464 file.Write("[version=1.0]\n")
9465 file.Write("describe {\n")
9466 for gltype
in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
9467 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
9468 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
9469 'GLubyte', 'GLuint', 'GLushort']:
9470 file.Write(" %s;\n" % gltype
)
9471 file.Write(" %s_ptr_t;\n" % gltype
)
9472 file.Write("};\n\n")
9475 file.Write("#inline c\n")
9476 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
9478 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
9480 file.Write("\n#ifndef __gl2_h_\n")
9481 for (k
, v
) in _GL_TYPES
.iteritems():
9482 file.Write("typedef %s %s;\n" % (v
, k
))
9483 file.Write("#ifdef _WIN64\n")
9484 for (k
, v
) in _GL_TYPES_64
.iteritems():
9485 file.Write("typedef %s %s;\n" % (v
, k
))
9486 file.Write("#else\n")
9487 for (k
, v
) in _GL_TYPES_32
.iteritems():
9488 file.Write("typedef %s %s;\n" % (v
, k
))
9489 file.Write("#endif // _WIN64\n")
9490 file.Write("#endif // __gl2_h_\n\n")
9491 file.Write("#endinl\n")
9493 for interface
in self
.pepper_interfaces
:
9494 if interface
.dev
!= dev
:
9496 # Historically, we provide OpenGLES2 interfaces with struct
9497 # namespace. Not to break code which uses the interface as
9498 # "struct OpenGLES2", we put it in struct namespace.
9499 file.Write('\n[macro="%s", force_struct_namespace]\n' %
9500 interface
.GetInterfaceName())
9501 file.Write("interface %s {\n" % interface
.GetStructName())
9502 for func
in self
.original_functions
:
9503 if not func
.InPepperInterface(interface
):
9506 ret_type
= func
.MapCTypeToPepperIdlType(func
.return_type
,
9507 is_for_return_type
=True)
9508 func_prefix
= " %s %s(" % (ret_type
, func
.GetPepperName())
9509 file.Write(func_prefix
)
9510 file.Write("[in] PP_Resource context")
9511 for arg
in func
.MakeTypedPepperIdlArgStrings():
9512 file.Write(",\n" + " " * len(func_prefix
) + arg
)
9514 file.Write("};\n\n")
9519 def WritePepperGLES2Implementation(self
, filename
):
9520 """Writes the Pepper OpenGLES interface implementation."""
9522 file = CWriter(filename
)
9523 file.Write(_LICENSE
)
9524 file.Write(_DO_NOT_EDIT_WARNING
)
9526 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
9527 file.Write("#include \"base/logging.h\"\n")
9528 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
9529 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
9530 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
9532 file.Write("namespace ppapi {\n\n")
9533 file.Write("namespace {\n\n")
9535 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
9538 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
9540 file.Write(" DCHECK(enter);\n")
9541 file.Write(" DCHECK(enter->succeeded());\n")
9542 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
9544 file.Write("}\n\n");
9546 for func
in self
.original_functions
:
9547 if not func
.InAnyPepperExtension():
9550 original_arg
= func
.MakeTypedPepperArgString("")
9551 context_arg
= "PP_Resource context_id"
9552 if len(original_arg
):
9553 arg
= context_arg
+ ", " + original_arg
9556 file.Write("%s %s(%s) {\n" %
9557 (func
.return_type
, func
.GetPepperName(), arg
))
9558 file.Write(" Enter3D enter(context_id, true);\n")
9559 file.Write(" if (enter.succeeded()) {\n")
9561 return_str
= "" if func
.return_type
== "void" else "return "
9562 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
9563 (return_str
, func
.original_name
,
9564 func
.MakeOriginalArgString("")))
9566 if func
.return_type
== "void":
9569 file.Write(" else {\n")
9570 file.Write(" return %s;\n" % func
.GetErrorReturnString())
9574 file.Write("} // namespace\n")
9576 for interface
in self
.pepper_interfaces
:
9577 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
9578 (interface
.GetStructName(), interface
.GetName()))
9579 file.Write(" static const struct %s "
9580 "ppb_opengles2 = {\n" % interface
.GetStructName())
9582 file.Write(",\n &".join(
9583 f
.GetPepperName() for f
in self
.original_functions
9584 if f
.InPepperInterface(interface
)))
9588 file.Write(" return &ppb_opengles2;\n")
9591 file.Write("} // namespace ppapi\n")
9593 self
.generated_cpp_filenames
.append(file.filename
)
9595 def WriteGLES2ToPPAPIBridge(self
, filename
):
9596 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
9598 file = CWriter(filename
)
9599 file.Write(_LICENSE
)
9600 file.Write(_DO_NOT_EDIT_WARNING
)
9602 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
9603 file.Write("#define GL_GLEXT_PROTOTYPES\n")
9604 file.Write("#endif\n")
9605 file.Write("#include <GLES2/gl2.h>\n")
9606 file.Write("#include <GLES2/gl2ext.h>\n")
9607 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
9609 for func
in self
.original_functions
:
9610 if not func
.InAnyPepperExtension():
9613 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
9615 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
9616 (func
.return_type
, func
.GetPepperName(),
9617 func
.MakeTypedPepperArgString("")))
9618 return_str
= "" if func
.return_type
== "void" else "return "
9619 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
9620 original_arg
= func
.MakeOriginalArgString("")
9621 context_arg
= "glGetCurrentContextPPAPI()"
9622 if len(original_arg
):
9623 arg
= context_arg
+ ", " + original_arg
9626 if interface
.GetName():
9627 file.Write(" const struct %s* ext = %s;\n" %
9628 (interface
.GetStructName(), interface_str
))
9629 file.Write(" if (ext)\n")
9630 file.Write(" %sext->%s(%s);\n" %
9631 (return_str
, func
.GetPepperName(), arg
))
9633 file.Write(" %s0;\n" % return_str
)
9635 file.Write(" %s%s->%s(%s);\n" %
9636 (return_str
, interface_str
, func
.GetPepperName(), arg
))
9639 self
.generated_cpp_filenames
.append(file.filename
)
9641 def WriteMojoGLCallVisitor(self
, filename
):
9642 """Provides the GL implementation for mojo"""
9643 file = CWriter(filename
)
9644 file.Write(_LICENSE
)
9645 file.Write(_DO_NOT_EDIT_WARNING
)
9647 for func
in self
.original_functions
:
9648 if not func
.IsCoreGLFunction():
9650 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
9651 (func
.name
, func
.return_type
,
9652 func
.MakeTypedOriginalArgString(""),
9653 func
.MakeOriginalArgString("")))
9656 self
.generated_cpp_filenames
.append(file.filename
)
9658 def WriteMojoGLCallVisitorForExtension(self
, filename
, extension
):
9659 """Provides the GL implementation for mojo for a particular extension"""
9660 file = CWriter(filename
)
9661 file.Write(_LICENSE
)
9662 file.Write(_DO_NOT_EDIT_WARNING
)
9664 for func
in self
.original_functions
:
9665 if func
.GetInfo("extension") != extension
:
9667 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
9668 (func
.name
, func
.return_type
,
9669 func
.MakeTypedOriginalArgString(""),
9670 func
.MakeOriginalArgString("")))
9673 self
.generated_cpp_filenames
.append(file.filename
)
9675 def Format(generated_files
):
9676 formatter
= "clang-format"
9677 if platform
.system() == "Windows":
9679 for filename
in generated_files
:
9680 call([formatter
, "-i", "-style=chromium", filename
])
9683 """This is the main function."""
9684 parser
= OptionParser()
9687 help="base directory for resulting files, under chrome/src. default is "
9688 "empty. Use this if you want the result stored under gen.")
9690 "-v", "--verbose", action
="store_true",
9691 help="prints more output.")
9693 (options
, args
) = parser
.parse_args(args
=argv
)
9695 # Add in states and capabilites to GLState
9696 gl_state_valid
= _NAMED_TYPE_INFO
['GLState']['valid']
9697 for state_name
in sorted(_STATES
.keys()):
9698 state
= _STATES
[state_name
]
9699 if 'extension_flag' in state
:
9702 if not state
['enum'] in gl_state_valid
:
9703 gl_state_valid
.append(state
['enum'])
9705 for item
in state
['states']:
9706 if 'extension_flag' in item
:
9708 if not item
['enum'] in gl_state_valid
:
9709 gl_state_valid
.append(item
['enum'])
9710 for capability
in _CAPABILITY_FLAGS
:
9711 valid_value
= "GL_%s" % capability
['name'].upper()
9712 if not valid_value
in gl_state_valid
:
9713 gl_state_valid
.append(valid_value
)
9715 # This script lives under gpu/command_buffer, cd to base directory.
9716 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
9717 base_dir
= os
.getcwd()
9718 gen
= GLGenerator(options
.verbose
)
9719 gen
.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
9721 # Support generating files under gen/
9722 if options
.output_dir
!= None:
9723 os
.chdir(options
.output_dir
)
9725 gen
.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
9726 gen
.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
9727 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
9728 gen
.WritePepperGLES2Implementation(
9729 "ppapi/shared_impl/ppb_opengles2_shared.cc")
9731 gen
.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
9732 gen
.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
9733 gen
.WriteFormatTest(
9734 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
9735 gen
.WriteGLES2InterfaceHeader(
9736 "gpu/command_buffer/client/gles2_interface_autogen.h")
9737 gen
.WriteGLES2InterfaceStub(
9738 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
9739 gen
.WriteGLES2InterfaceStubImpl(
9740 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
9741 gen
.WriteGLES2ImplementationHeader(
9742 "gpu/command_buffer/client/gles2_implementation_autogen.h")
9743 gen
.WriteGLES2Implementation(
9744 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
9745 gen
.WriteGLES2ImplementationUnitTests(
9746 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
9747 gen
.WriteGLES2TraceImplementationHeader(
9748 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
9749 gen
.WriteGLES2TraceImplementation(
9750 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
9751 gen
.WriteGLES2CLibImplementation(
9752 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
9753 gen
.WriteCmdHelperHeader(
9754 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
9755 gen
.WriteServiceImplementation(
9756 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
9757 gen
.WriteServiceContextStateHeader(
9758 "gpu/command_buffer/service/context_state_autogen.h")
9759 gen
.WriteServiceContextStateImpl(
9760 "gpu/command_buffer/service/context_state_impl_autogen.h")
9761 gen
.WriteClientContextStateHeader(
9762 "gpu/command_buffer/client/client_context_state_autogen.h")
9763 gen
.WriteClientContextStateImpl(
9764 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
9765 gen
.WriteServiceUnitTests(
9766 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
9767 gen
.WriteServiceUnitTestsForExtensions(
9768 "gpu/command_buffer/service/"
9769 "gles2_cmd_decoder_unittest_extensions_autogen.h")
9770 gen
.WriteServiceUtilsHeader(
9771 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
9772 gen
.WriteServiceUtilsImplementation(
9773 "gpu/command_buffer/service/"
9774 "gles2_cmd_validation_implementation_autogen.h")
9775 gen
.WriteCommonUtilsHeader(
9776 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
9777 gen
.WriteCommonUtilsImpl(
9778 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
9779 gen
.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
9780 mojo_gles2_prefix
= ("third_party/mojo/src/mojo/public/c/gles2/"
9781 "gles2_call_visitor")
9782 gen
.WriteMojoGLCallVisitor(mojo_gles2_prefix
+ "_autogen.h")
9783 gen
.WriteMojoGLCallVisitorForExtension(
9784 mojo_gles2_prefix
+ "_chromium_texture_mailbox_autogen.h",
9785 "CHROMIUM_texture_mailbox")
9786 gen
.WriteMojoGLCallVisitorForExtension(
9787 mojo_gles2_prefix
+ "_chromium_sync_point_autogen.h",
9788 "CHROMIUM_sync_point")
9790 Format(gen
.generated_cpp_filenames
)
9793 print "%d errors" % gen
.errors
9798 if __name__
== '__main__':
9799 sys
.exit(main(sys
.argv
[1:]))