2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """code generator for GLES2 command buffers."""
13 from optparse
import OptionParser
14 from subprocess
import call
17 _SIZE_OF_COMMAND_HEADER
= 4
18 _FIRST_SPECIFIC_COMMAND_ID
= 256
20 _LICENSE
= """// Copyright 2014 The Chromium Authors. All rights reserved.
21 // Use of this source code is governed by a BSD-style license that can be
22 // found in the LICENSE file.
26 _DO_NOT_EDIT_WARNING
= """// This file is auto-generated from
27 // gpu/command_buffer/build_gles2_cmd_buffer.py
28 // It's formatted by clang-format using chromium coding style:
29 // clang-format -i -style=chromium filename
34 # This string is copied directly out of the gl2.h file from GLES2.0
38 # *) Any argument that is a resourceID has been changed to GLid<Type>.
39 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
40 # If it's allowed to not exist it's GLidBind<Type>
42 # *) All GLenums have been changed to GLenumTypeOfEnum
45 'GLenum': 'unsigned int',
46 'GLboolean': 'unsigned char',
47 'GLbitfield': 'unsigned int',
48 'GLbyte': 'signed char',
52 'GLubyte': 'unsigned char',
53 'GLushort': 'unsigned short',
54 'GLuint': 'unsigned int',
63 'GLintptr': 'long int',
64 'GLsizeiptr': 'long int'
68 'GLintptr': 'long long int',
69 'GLsizeiptr': 'long long int'
72 # Capabilites selected with glEnable
75 {'name': 'cull_face'},
76 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
77 {'name': 'dither', 'default': True},
78 {'name': 'polygon_offset_fill'},
79 {'name': 'sample_alpha_to_coverage'},
80 {'name': 'sample_coverage'},
81 {'name': 'scissor_test'},
82 {'name': 'stencil_test',
83 'state_flag': 'framebuffer_state_.clear_state_dirty'},
90 'enum': 'GL_COLOR_CLEAR_VALUE',
92 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
93 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
94 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
95 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
100 'func': 'ClearDepth',
101 'enum': 'GL_DEPTH_CLEAR_VALUE',
103 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
109 'enum': 'GL_COLOR_WRITEMASK',
112 'name': 'color_mask_red',
118 'name': 'color_mask_green',
124 'name': 'color_mask_blue',
130 'name': 'color_mask_alpha',
136 'state_flag': 'framebuffer_state_.clear_state_dirty',
140 'func': 'ClearStencil',
141 'enum': 'GL_STENCIL_CLEAR_VALUE',
143 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
148 'func': 'BlendColor',
149 'enum': 'GL_BLEND_COLOR',
151 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
152 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
153 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
154 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
159 'func': 'BlendEquationSeparate',
162 'name': 'blend_equation_rgb',
164 'enum': 'GL_BLEND_EQUATION_RGB',
165 'default': 'GL_FUNC_ADD',
168 'name': 'blend_equation_alpha',
170 'enum': 'GL_BLEND_EQUATION_ALPHA',
171 'default': 'GL_FUNC_ADD',
177 'func': 'BlendFuncSeparate',
180 'name': 'blend_source_rgb',
182 'enum': 'GL_BLEND_SRC_RGB',
186 'name': 'blend_dest_rgb',
188 'enum': 'GL_BLEND_DST_RGB',
189 'default': 'GL_ZERO',
192 'name': 'blend_source_alpha',
194 'enum': 'GL_BLEND_SRC_ALPHA',
198 'name': 'blend_dest_alpha',
200 'enum': 'GL_BLEND_DST_ALPHA',
201 'default': 'GL_ZERO',
207 'func': 'PolygonOffset',
210 'name': 'polygon_offset_factor',
212 'enum': 'GL_POLYGON_OFFSET_FACTOR',
216 'name': 'polygon_offset_units',
218 'enum': 'GL_POLYGON_OFFSET_UNITS',
226 'enum': 'GL_CULL_FACE_MODE',
231 'default': 'GL_BACK',
238 'enum': 'GL_FRONT_FACE',
239 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
244 'enum': 'GL_DEPTH_FUNC',
245 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
249 'func': 'DepthRange',
250 'enum': 'GL_DEPTH_RANGE',
252 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
253 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
258 'func': 'SampleCoverage',
261 'name': 'sample_coverage_value',
263 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
267 'name': 'sample_coverage_invert',
269 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
276 'func': 'StencilMaskSeparate',
277 'state_flag': 'framebuffer_state_.clear_state_dirty',
280 'name': 'stencil_front_writemask',
282 'enum': 'GL_STENCIL_WRITEMASK',
283 'default': '0xFFFFFFFFU',
287 'name': 'stencil_back_writemask',
289 'enum': 'GL_STENCIL_BACK_WRITEMASK',
290 'default': '0xFFFFFFFFU',
297 'func': 'StencilOpSeparate',
300 'name': 'stencil_front_fail_op',
302 'enum': 'GL_STENCIL_FAIL',
303 'default': 'GL_KEEP',
306 'name': 'stencil_front_z_fail_op',
308 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
309 'default': 'GL_KEEP',
312 'name': 'stencil_front_z_pass_op',
314 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
315 'default': 'GL_KEEP',
318 'name': 'stencil_back_fail_op',
320 'enum': 'GL_STENCIL_BACK_FAIL',
321 'default': 'GL_KEEP',
324 'name': 'stencil_back_z_fail_op',
326 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
327 'default': 'GL_KEEP',
330 'name': 'stencil_back_z_pass_op',
332 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
333 'default': 'GL_KEEP',
339 'func': 'StencilFuncSeparate',
342 'name': 'stencil_front_func',
344 'enum': 'GL_STENCIL_FUNC',
345 'default': 'GL_ALWAYS',
348 'name': 'stencil_front_ref',
350 'enum': 'GL_STENCIL_REF',
354 'name': 'stencil_front_mask',
356 'enum': 'GL_STENCIL_VALUE_MASK',
357 'default': '0xFFFFFFFFU',
360 'name': 'stencil_back_func',
362 'enum': 'GL_STENCIL_BACK_FUNC',
363 'default': 'GL_ALWAYS',
366 'name': 'stencil_back_ref',
368 'enum': 'GL_STENCIL_BACK_REF',
372 'name': 'stencil_back_mask',
374 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
375 'default': '0xFFFFFFFFU',
380 'type': 'NamedParameter',
384 'name': 'hint_generate_mipmap',
386 'enum': 'GL_GENERATE_MIPMAP_HINT',
387 'default': 'GL_DONT_CARE'
390 'name': 'hint_fragment_shader_derivative',
392 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
393 'default': 'GL_DONT_CARE',
394 'extension_flag': 'oes_standard_derivatives'
399 'type': 'NamedParameter',
400 'func': 'PixelStorei',
403 'name': 'pack_alignment',
405 'enum': 'GL_PACK_ALIGNMENT',
409 'name': 'unpack_alignment',
411 'enum': 'GL_UNPACK_ALIGNMENT',
416 # TODO: Consider implemenenting these states
421 'enum': 'GL_LINE_WIDTH',
424 'name': 'line_width',
427 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
434 'enum': 'GL_DEPTH_WRITEMASK',
437 'name': 'depth_mask',
443 'state_flag': 'framebuffer_state_.clear_state_dirty',
448 'enum': 'GL_SCISSOR_BOX',
450 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
455 'expected': 'kViewportX',
461 'expected': 'kViewportY',
464 'name': 'scissor_width',
467 'expected': 'kViewportWidth',
470 'name': 'scissor_height',
473 'expected': 'kViewportHeight',
480 'enum': 'GL_VIEWPORT',
482 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
484 'name': 'viewport_x',
487 'expected': 'kViewportX',
490 'name': 'viewport_y',
493 'expected': 'kViewportY',
496 'name': 'viewport_width',
499 'expected': 'kViewportWidth',
502 'name': 'viewport_height',
505 'expected': 'kViewportHeight',
509 'MatrixValuesCHROMIUM': {
510 'type': 'NamedParameter',
511 'func': 'MatrixLoadfEXT',
513 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
514 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
515 'name': 'modelview_matrix',
518 '1.0f', '0.0f','0.0f','0.0f',
519 '0.0f', '1.0f','0.0f','0.0f',
520 '0.0f', '0.0f','1.0f','0.0f',
521 '0.0f', '0.0f','0.0f','1.0f',
523 'extension_flag': 'chromium_path_rendering',
525 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
526 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
527 'name': 'projection_matrix',
530 '1.0f', '0.0f','0.0f','0.0f',
531 '0.0f', '1.0f','0.0f','0.0f',
532 '0.0f', '0.0f','1.0f','0.0f',
533 '0.0f', '0.0f','0.0f','1.0f',
535 'extension_flag': 'chromium_path_rendering',
541 # Named type info object represents a named type that is used in OpenGL call
542 # arguments. Each named type defines a set of valid OpenGL call arguments. The
543 # named types are used in 'cmd_buffer_functions.txt'.
544 # type: The actual GL type of the named type.
545 # valid: The list of values that are valid for both the client and the service.
546 # invalid: Examples of invalid values for the type. At least these values
547 # should be tested to be invalid.
548 # is_complete: The list of valid values of type are final and will not be
549 # modified during runtime.
558 'GL_LINEAR_MIPMAP_LINEAR',
561 'FrameBufferTarget': {
567 'GL_DRAW_FRAMEBUFFER' ,
568 'GL_READ_FRAMEBUFFER' ,
571 'RenderBufferTarget': {
584 'GL_ELEMENT_ARRAY_BUFFER',
601 'CompressedTextureFormat': {
609 # NOTE: State an Capability entries added later.
611 'GL_ALIASED_LINE_WIDTH_RANGE',
612 'GL_ALIASED_POINT_SIZE_RANGE',
614 'GL_ARRAY_BUFFER_BINDING',
616 'GL_COMPRESSED_TEXTURE_FORMATS',
617 'GL_CURRENT_PROGRAM',
620 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
621 'GL_FRAMEBUFFER_BINDING',
622 'GL_GENERATE_MIPMAP_HINT',
624 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
625 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
626 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
627 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
628 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
629 'GL_MAX_RENDERBUFFER_SIZE',
630 'GL_MAX_TEXTURE_IMAGE_UNITS',
631 'GL_MAX_TEXTURE_SIZE',
632 'GL_MAX_VARYING_VECTORS',
633 'GL_MAX_VERTEX_ATTRIBS',
634 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
635 'GL_MAX_VERTEX_UNIFORM_VECTORS',
636 'GL_MAX_VIEWPORT_DIMS',
637 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
638 'GL_NUM_SHADER_BINARY_FORMATS',
641 'GL_RENDERBUFFER_BINDING',
643 'GL_SAMPLE_COVERAGE_INVERT',
644 'GL_SAMPLE_COVERAGE_VALUE',
647 'GL_SHADER_BINARY_FORMATS',
648 'GL_SHADER_COMPILER',
651 'GL_TEXTURE_BINDING_2D',
652 'GL_TEXTURE_BINDING_CUBE_MAP',
653 'GL_UNPACK_ALIGNMENT',
654 'GL_UNPACK_FLIP_Y_CHROMIUM',
655 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
656 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
657 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
658 # we can add this because we emulate it if the driver does not support it.
659 'GL_VERTEX_ARRAY_BINDING_OES',
666 'GetTexParamTarget': {
670 'GL_TEXTURE_CUBE_MAP',
673 'GL_PROXY_TEXTURE_CUBE_MAP',
680 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
681 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
682 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
683 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
684 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
685 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
688 'GL_PROXY_TEXTURE_CUBE_MAP',
691 'TextureBindTarget': {
695 'GL_TEXTURE_CUBE_MAP',
706 'GL_FRAGMENT_SHADER',
709 'GL_GEOMETRY_SHADER',
745 'GL_FUNC_REVERSE_SUBTRACT',
758 'GL_ONE_MINUS_SRC_COLOR',
760 'GL_ONE_MINUS_DST_COLOR',
762 'GL_ONE_MINUS_SRC_ALPHA',
764 'GL_ONE_MINUS_DST_ALPHA',
766 'GL_ONE_MINUS_CONSTANT_COLOR',
768 'GL_ONE_MINUS_CONSTANT_ALPHA',
769 'GL_SRC_ALPHA_SATURATE',
778 'GL_ONE_MINUS_SRC_COLOR',
780 'GL_ONE_MINUS_DST_COLOR',
782 'GL_ONE_MINUS_SRC_ALPHA',
784 'GL_ONE_MINUS_DST_ALPHA',
786 'GL_ONE_MINUS_CONSTANT_COLOR',
788 'GL_ONE_MINUS_CONSTANT_ALPHA',
793 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
],
840 'GL_COLOR_ATTACHMENT0',
841 'GL_DEPTH_ATTACHMENT',
842 'GL_STENCIL_ATTACHMENT',
845 'BackbufferAttachment': {
860 'GL_PIXEL_PACK_BUFFER',
863 'FrameBufferParameter': {
866 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
867 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
868 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
869 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
875 'GL_PATH_PROJECTION_CHROMIUM',
876 'GL_PATH_MODELVIEW_CHROMIUM',
879 'ProgramParameter': {
884 'GL_VALIDATE_STATUS',
885 'GL_INFO_LOG_LENGTH',
886 'GL_ATTACHED_SHADERS',
887 'GL_ACTIVE_ATTRIBUTES',
888 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
889 'GL_ACTIVE_UNIFORMS',
890 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
893 'QueryObjectParameter': {
896 'GL_QUERY_RESULT_EXT',
897 'GL_QUERY_RESULT_AVAILABLE_EXT',
903 'GL_CURRENT_QUERY_EXT',
909 'GL_ANY_SAMPLES_PASSED_EXT',
910 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
911 'GL_COMMANDS_ISSUED_CHROMIUM',
912 'GL_LATENCY_QUERY_CHROMIUM',
913 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
914 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
915 'GL_COMMANDS_COMPLETED_CHROMIUM',
918 'RenderBufferParameter': {
921 'GL_RENDERBUFFER_RED_SIZE',
922 'GL_RENDERBUFFER_GREEN_SIZE',
923 'GL_RENDERBUFFER_BLUE_SIZE',
924 'GL_RENDERBUFFER_ALPHA_SIZE',
925 'GL_RENDERBUFFER_DEPTH_SIZE',
926 'GL_RENDERBUFFER_STENCIL_SIZE',
927 'GL_RENDERBUFFER_WIDTH',
928 'GL_RENDERBUFFER_HEIGHT',
929 'GL_RENDERBUFFER_INTERNAL_FORMAT',
938 'GL_INFO_LOG_LENGTH',
939 'GL_SHADER_SOURCE_LENGTH',
940 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
960 'GL_SHADING_LANGUAGE_VERSION',
964 'TextureParameter': {
967 'GL_TEXTURE_MAG_FILTER',
968 'GL_TEXTURE_MIN_FILTER',
969 'GL_TEXTURE_POOL_CHROMIUM',
974 'GL_GENERATE_MIPMAP',
980 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
981 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
988 'GL_MIRRORED_REPEAT',
992 'TextureMinFilterMode': {
997 'GL_NEAREST_MIPMAP_NEAREST',
998 'GL_LINEAR_MIPMAP_NEAREST',
999 'GL_NEAREST_MIPMAP_LINEAR',
1000 'GL_LINEAR_MIPMAP_LINEAR',
1003 'TextureMagFilterMode': {
1014 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1017 'VertexAttribute': {
1020 # some enum that the decoder actually passes through to GL needs
1021 # to be the first listed here since it's used in unit tests.
1022 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1023 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1024 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1025 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1026 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1027 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1028 'GL_CURRENT_VERTEX_ATTRIB',
1034 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1040 'GL_GENERATE_MIPMAP_HINT',
1043 'GL_PERSPECTIVE_CORRECTION_HINT',
1057 'GL_PACK_ALIGNMENT',
1058 'GL_UNPACK_ALIGNMENT',
1059 'GL_UNPACK_FLIP_Y_CHROMIUM',
1060 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
1061 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
1064 'GL_PACK_SWAP_BYTES',
1065 'GL_UNPACK_SWAP_BYTES',
1068 'PixelStoreAlignment': {
1081 'ReadPixelFormat': {
1093 'GL_UNSIGNED_SHORT_5_6_5',
1094 'GL_UNSIGNED_SHORT_4_4_4_4',
1095 'GL_UNSIGNED_SHORT_5_5_5_1',
1106 'GL_UNSIGNED_SHORT_5_6_5',
1107 'GL_UNSIGNED_SHORT_4_4_4_4',
1108 'GL_UNSIGNED_SHORT_5_5_5_1',
1115 'RenderBufferFormat': {
1121 'GL_DEPTH_COMPONENT16',
1122 'GL_STENCIL_INDEX8',
1125 'ShaderBinaryFormat': {
1148 'GL_LUMINANCE_ALPHA',
1157 'TextureInternalFormat': {
1162 'GL_LUMINANCE_ALPHA',
1171 'TextureInternalFormatStorage': {
1178 'GL_LUMINANCE8_EXT',
1179 'GL_LUMINANCE8_ALPHA8_EXT',
1184 'VertexAttribType': {
1190 'GL_UNSIGNED_SHORT',
1191 # 'GL_FIXED', // This is not available on Desktop GL.
1200 'is_complete': True,
1208 'VertexAttribSize': {
1223 'is_complete': True,
1232 'type': 'GLboolean',
1233 'is_complete': True,
1244 'GL_GUILTY_CONTEXT_RESET_ARB',
1245 'GL_INNOCENT_CONTEXT_RESET_ARB',
1246 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1251 # This table specifies the different pepper interfaces that are supported for
1252 # GL commands. 'dev' is true if it's a dev interface.
1253 _PEPPER_INTERFACES
= [
1254 {'name': '', 'dev': False},
1255 {'name': 'InstancedArrays', 'dev': False},
1256 {'name': 'FramebufferBlit', 'dev': False},
1257 {'name': 'FramebufferMultisample', 'dev': False},
1258 {'name': 'ChromiumEnableFeature', 'dev': False},
1259 {'name': 'ChromiumMapSub', 'dev': False},
1260 {'name': 'Query', 'dev': False},
1261 {'name': 'VertexArrayObject', 'dev': False},
1262 {'name': 'DrawBuffers', 'dev': True},
1265 # A function info object specifies the type and other special data for the
1266 # command that will be generated. A base function info object is generated by
1267 # parsing the "cmd_buffer_functions.txt", one for each function in the
1268 # file. These function info objects can be augmented and their values can be
1269 # overridden by adding an object to the table below.
1271 # Must match function names specified in "cmd_buffer_functions.txt".
1273 # cmd_comment: A comment added to the cmd format.
1274 # type: defines which handler will be used to generate code.
1275 # decoder_func: defines which function to call in the decoder to execute the
1276 # corresponding GL command. If not specified the GL command will
1277 # be called directly.
1278 # gl_test_func: GL function that is expected to be called when testing.
1279 # cmd_args: The arguments to use for the command. This overrides generating
1280 # them based on the GL function arguments.
1281 # gen_cmd: Whether or not this function geneates a command. Default = True.
1282 # data_transfer_methods: Array of methods that are used for transfering the
1283 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1284 # The default is 'immediate' if the command has one pointer
1285 # argument, otherwise 'shm'. One command is generated for each
1286 # transfer method. Affects only commands which are not of type
1287 # 'HandWritten', 'GETn' or 'GLcharN'.
1288 # Note: the command arguments that affect this are the final args,
1289 # taking cmd_args override into consideration.
1290 # impl_func: Whether or not to generate the GLES2Implementation part of this
1292 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1294 # needs_size: If true a data_size field is added to the command.
1295 # count: The number of units per element. For PUTn or PUT types.
1296 # unit_test: If False no service side unit test will be generated.
1297 # client_test: If False no client side unit test will be generated.
1298 # expectation: If False the unit test will have no expected calls.
1299 # gen_func: Name of function that generates GL resource for corresponding
1301 # states: array of states that get set by this function corresponding to
1302 # the given arguments
1303 # state_flag: name of flag that is set to true when function is called.
1304 # no_gl: no GL function is called.
1305 # valid_args: A dictionary of argument indices to args to use in unit tests
1306 # when they can not be automatically determined.
1307 # pepper_interface: The pepper interface that is used for this extension
1308 # pepper_name: The name of the function as exposed to pepper.
1309 # pepper_args: A string representing the argument list (what would appear in
1310 # C/C++ between the parentheses for the function declaration)
1311 # that the Pepper API expects for this function. Use this only if
1312 # the stable Pepper API differs from the GLES2 argument list.
1313 # invalid_test: False if no invalid test needed.
1314 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1315 # first_element_only: For PUT types, True if only the first element of an
1316 # array is used and we end up calling the single value
1317 # corresponding function. eg. TexParameteriv -> TexParameteri
1318 # extension: Function is an extension to GL and should not be exposed to
1319 # pepper unless pepper_interface is defined.
1320 # extension_flag: Function is an extension and should be enabled only when
1321 # the corresponding feature info flag is enabled. Implies
1322 # 'extension': True.
1323 # not_shared: For GENn types, True if objects can't be shared between contexts
1327 'decoder_func': 'DoActiveTexture',
1330 'client_test': False,
1332 'AttachShader': {'decoder_func': 'DoAttachShader'},
1333 'BindAttribLocation': {
1335 'data_transfer_methods': ['bucket'],
1340 'decoder_func': 'DoBindBuffer',
1341 'gen_func': 'GenBuffersARB',
1343 'BindFramebuffer': {
1345 'decoder_func': 'DoBindFramebuffer',
1346 'gl_test_func': 'glBindFramebufferEXT',
1347 'gen_func': 'GenFramebuffersEXT',
1350 'BindRenderbuffer': {
1352 'decoder_func': 'DoBindRenderbuffer',
1353 'gl_test_func': 'glBindRenderbufferEXT',
1354 'gen_func': 'GenRenderbuffersEXT',
1358 'decoder_func': 'DoBindTexture',
1359 'gen_func': 'GenTextures',
1360 # TODO(gman): remove this once client side caching works.
1361 'client_test': False,
1364 'BlitFramebufferCHROMIUM': {
1365 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1367 'extension_flag': 'chromium_framebuffer_multisample',
1368 'pepper_interface': 'FramebufferBlit',
1369 'pepper_name': 'BlitFramebufferEXT',
1370 'defer_reads': True,
1371 'defer_draws': True,
1376 'data_transfer_methods': ['shm'],
1377 'client_test': False,
1381 'client_test': False,
1382 'decoder_func': 'DoBufferSubData',
1383 'data_transfer_methods': ['shm'],
1385 'CheckFramebufferStatus': {
1387 'decoder_func': 'DoCheckFramebufferStatus',
1388 'gl_test_func': 'glCheckFramebufferStatusEXT',
1389 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1390 'result': ['GLenum'],
1393 'decoder_func': 'DoClear',
1394 'defer_draws': True,
1399 'state': 'ClearColor',
1403 'state': 'ClearDepthf',
1404 'decoder_func': 'glClearDepth',
1405 'gl_test_func': 'glClearDepth',
1412 'state': 'ColorMask',
1414 'expectation': False,
1416 'ConsumeTextureCHROMIUM': {
1417 'decoder_func': 'DoConsumeTextureCHROMIUM',
1420 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1422 'client_test': False,
1423 'extension': "CHROMIUM_texture_mailbox",
1427 'CreateAndConsumeTextureCHROMIUM': {
1428 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
1430 'type': 'HandWritten',
1431 'data_transfer_methods': ['immediate'],
1433 'client_test': False,
1434 'extension': "CHROMIUM_texture_mailbox",
1439 'state': 'ClearStencil',
1441 'EnableFeatureCHROMIUM': {
1443 'data_transfer_methods': ['shm'],
1444 'decoder_func': 'DoEnableFeatureCHROMIUM',
1445 'expectation': False,
1446 'cmd_args': 'GLuint bucket_id, GLint* result',
1447 'result': ['GLint'],
1450 'pepper_interface': 'ChromiumEnableFeature',
1452 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1453 'CompressedTexImage2D': {
1455 'data_transfer_methods': ['bucket', 'shm'],
1457 'CompressedTexSubImage2D': {
1459 'data_transfer_methods': ['bucket', 'shm'],
1460 'decoder_func': 'DoCompressedTexSubImage2D',
1463 'decoder_func': 'DoCopyTexImage2D',
1465 'defer_reads': True,
1467 'CopyTexSubImage2D': {
1468 'decoder_func': 'DoCopyTexSubImage2D',
1469 'defer_reads': True,
1471 'CreateImageCHROMIUM': {
1474 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
1475 'result': ['GLuint'],
1476 'client_test': False,
1478 'expectation': False,
1482 'DestroyImageCHROMIUM': {
1484 'client_test': False,
1489 'GetImageParameterivCHROMIUM': {
1491 'client_test': False,
1493 'expectation': False,
1499 'client_test': False,
1503 'client_test': False,
1507 'state': 'BlendColor',
1510 'type': 'StateSetRGBAlpha',
1511 'state': 'BlendEquation',
1513 '0': 'GL_FUNC_SUBTRACT'
1516 'BlendEquationSeparate': {
1518 'state': 'BlendEquation',
1520 '0': 'GL_FUNC_SUBTRACT'
1524 'type': 'StateSetRGBAlpha',
1525 'state': 'BlendFunc',
1527 'BlendFuncSeparate': {
1529 'state': 'BlendFunc',
1531 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1533 'type': 'StateSetFrontBack',
1534 'state': 'StencilFunc',
1536 'StencilFuncSeparate': {
1537 'type': 'StateSetFrontBackSeparate',
1538 'state': 'StencilFunc',
1541 'type': 'StateSetFrontBack',
1542 'state': 'StencilOp',
1547 'StencilOpSeparate': {
1548 'type': 'StateSetFrontBackSeparate',
1549 'state': 'StencilOp',
1555 'type': 'StateSetNamedParameter',
1558 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1559 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1560 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1563 'state': 'LineWidth',
1570 'state': 'PolygonOffset',
1574 'gl_test_func': 'glDeleteBuffersARB',
1575 'resource_type': 'Buffer',
1576 'resource_types': 'Buffers',
1578 'DeleteFramebuffers': {
1580 'gl_test_func': 'glDeleteFramebuffersEXT',
1581 'resource_type': 'Framebuffer',
1582 'resource_types': 'Framebuffers',
1584 'DeleteProgram': {'type': 'Delete', 'decoder_func': 'DoDeleteProgram'},
1585 'DeleteRenderbuffers': {
1587 'gl_test_func': 'glDeleteRenderbuffersEXT',
1588 'resource_type': 'Renderbuffer',
1589 'resource_types': 'Renderbuffers',
1591 'DeleteShader': {'type': 'Delete', 'decoder_func': 'DoDeleteShader'},
1592 'DeleteSharedIdsCHROMIUM': {
1594 'decoder_func': 'DoDeleteSharedIdsCHROMIUM',
1596 'expectation': False,
1597 'data_transfer_methods': ['shm'],
1603 'resource_type': 'Texture',
1604 'resource_types': 'Textures',
1607 'decoder_func': 'DoDepthRangef',
1608 'gl_test_func': 'glDepthRange',
1612 'state': 'DepthMask',
1614 'expectation': False,
1616 'DetachShader': {'decoder_func': 'DoDetachShader'},
1618 'decoder_func': 'DoDisable',
1620 'client_test': False,
1622 'DisableVertexAttribArray': {
1623 'decoder_func': 'DoDisableVertexAttribArray',
1628 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1629 'defer_draws': True,
1634 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1635 'GLenumIndexType type, GLuint index_offset',
1636 'client_test': False,
1637 'defer_draws': True,
1641 'decoder_func': 'DoEnable',
1643 'client_test': False,
1645 'EnableVertexAttribArray': {
1646 'decoder_func': 'DoEnableVertexAttribArray',
1651 'client_test': False,
1652 'decoder_func': 'DoFinish',
1653 'defer_reads': True,
1657 'decoder_func': 'DoFlush',
1659 'FramebufferRenderbuffer': {
1660 'decoder_func': 'DoFramebufferRenderbuffer',
1661 'gl_test_func': 'glFramebufferRenderbufferEXT',
1663 'FramebufferTexture2D': {
1664 'decoder_func': 'DoFramebufferTexture2D',
1665 'gl_test_func': 'glFramebufferTexture2DEXT',
1668 'FramebufferTexture2DMultisampleEXT': {
1669 'decoder_func': 'DoFramebufferTexture2DMultisample',
1670 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1671 'expectation': False,
1673 'extension_flag': 'multisampled_render_to_texture',
1677 'decoder_func': 'DoGenerateMipmap',
1678 'gl_test_func': 'glGenerateMipmapEXT',
1682 'gl_test_func': 'glGenBuffersARB',
1683 'resource_type': 'Buffer',
1684 'resource_types': 'Buffers',
1686 'GenMailboxCHROMIUM': {
1687 'type': 'HandWritten',
1689 'extension': "CHROMIUM_texture_mailbox",
1692 'GenFramebuffers': {
1694 'gl_test_func': 'glGenFramebuffersEXT',
1695 'resource_type': 'Framebuffer',
1696 'resource_types': 'Framebuffers',
1698 'GenRenderbuffers': {
1699 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1700 'resource_type': 'Renderbuffer',
1701 'resource_types': 'Renderbuffers',
1705 'gl_test_func': 'glGenTextures',
1706 'resource_type': 'Texture',
1707 'resource_types': 'Textures',
1709 'GenSharedIdsCHROMIUM': {
1711 'decoder_func': 'DoGenSharedIdsCHROMIUM',
1713 'expectation': False,
1714 'data_transfer_methods': ['shm'],
1718 'GetActiveAttrib': {
1720 'data_transfer_methods': ['shm'],
1722 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
1730 'GetActiveUniform': {
1732 'data_transfer_methods': ['shm'],
1734 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
1742 'GetAttachedShaders': {
1744 'data_transfer_methods': ['shm'],
1745 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
1746 'result': ['SizedResult<GLuint>'],
1748 'GetAttribLocation': {
1750 'data_transfer_methods': ['shm'],
1752 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
1753 'result': ['GLint'],
1754 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml
1758 'result': ['SizedResult<GLboolean>'],
1759 'decoder_func': 'DoGetBooleanv',
1760 'gl_test_func': 'glGetBooleanv',
1762 'GetBufferParameteriv': {
1764 'result': ['SizedResult<GLint>'],
1765 'decoder_func': 'DoGetBufferParameteriv',
1766 'expectation': False,
1771 'decoder_func': 'GetErrorState()->GetGLError',
1773 'result': ['GLenum'],
1774 'client_test': False,
1778 'result': ['SizedResult<GLfloat>'],
1779 'decoder_func': 'DoGetFloatv',
1780 'gl_test_func': 'glGetFloatv',
1782 'GetFramebufferAttachmentParameteriv': {
1784 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
1785 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
1786 'result': ['SizedResult<GLint>'],
1790 'result': ['SizedResult<GLint>'],
1791 'decoder_func': 'DoGetIntegerv',
1792 'client_test': False,
1794 'GetMaxValueInBufferCHROMIUM': {
1796 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
1797 'result': ['GLuint'],
1799 'client_test': False,
1804 'GetMultipleIntegervCHROMIUM': {
1806 'data_transfer_methods': ['shm'],
1807 'expectation': False,
1810 'client_test': False,
1814 'decoder_func': 'DoGetProgramiv',
1815 'result': ['SizedResult<GLint>'],
1816 'expectation': False,
1818 'GetProgramInfoCHROMIUM': {
1820 'expectation': False,
1824 'client_test': False,
1825 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
1827 'uint32_t link_status',
1828 'uint32_t num_attribs',
1829 'uint32_t num_uniforms',
1832 'GetProgramInfoLog': {
1834 'expectation': False,
1836 'GetRenderbufferParameteriv': {
1838 'decoder_func': 'DoGetRenderbufferParameteriv',
1839 'gl_test_func': 'glGetRenderbufferParameterivEXT',
1840 'result': ['SizedResult<GLint>'],
1844 'decoder_func': 'DoGetShaderiv',
1845 'result': ['SizedResult<GLint>'],
1847 'GetShaderInfoLog': {
1849 'get_len_func': 'glGetShaderiv',
1850 'get_len_enum': 'GL_INFO_LOG_LENGTH',
1853 'GetShaderPrecisionFormat': {
1855 'data_transfer_methods': ['shm'],
1857 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
1861 'int32_t min_range',
1862 'int32_t max_range',
1863 'int32_t precision',
1866 'GetShaderSource': {
1868 'get_len_func': 'DoGetShaderiv',
1869 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
1871 'client_test': False,
1875 'client_test': False,
1876 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
1878 'GetTexParameterfv': {
1880 'decoder_func': 'DoGetTexParameterfv',
1881 'result': ['SizedResult<GLfloat>']
1883 'GetTexParameteriv': {
1885 'decoder_func': 'DoGetTexParameteriv',
1886 'result': ['SizedResult<GLint>']
1888 'GetTranslatedShaderSourceANGLE': {
1890 'get_len_func': 'DoGetShaderiv',
1891 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1897 'data_transfer_methods': ['shm'],
1898 'result': ['SizedResult<GLfloat>'],
1902 'data_transfer_methods': ['shm'],
1903 'result': ['SizedResult<GLint>'],
1905 'GetUniformLocation': {
1907 'data_transfer_methods': ['shm'],
1909 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
1910 'result': ['GLint'],
1911 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
1913 'GetVertexAttribfv': {
1915 'result': ['SizedResult<GLfloat>'],
1917 'decoder_func': 'DoGetVertexAttribfv',
1918 'expectation': False,
1919 'client_test': False,
1921 'GetVertexAttribiv': {
1923 'result': ['SizedResult<GLint>'],
1925 'decoder_func': 'DoGetVertexAttribiv',
1926 'expectation': False,
1927 'client_test': False,
1929 'GetVertexAttribPointerv': {
1931 'data_transfer_methods': ['shm'],
1932 'result': ['SizedResult<GLuint>'],
1933 'client_test': False,
1937 'decoder_func': 'DoIsBuffer',
1938 'expectation': False,
1942 'decoder_func': 'DoIsEnabled',
1944 'expectation': False,
1948 'decoder_func': 'DoIsFramebuffer',
1949 'expectation': False,
1953 'decoder_func': 'DoIsProgram',
1954 'expectation': False,
1958 'decoder_func': 'DoIsRenderbuffer',
1959 'expectation': False,
1963 'decoder_func': 'DoIsShader',
1964 'expectation': False,
1968 'decoder_func': 'DoIsTexture',
1969 'expectation': False,
1972 'decoder_func': 'DoLinkProgram',
1975 'MapBufferCHROMIUM': {
1979 'client_test': False,
1981 'MapBufferSubDataCHROMIUM': {
1985 'client_test': False,
1986 'pepper_interface': 'ChromiumMapSub',
1988 'MapImageCHROMIUM': {
1992 'client_test': False,
1994 'MapTexSubImage2DCHROMIUM': {
1998 'client_test': False,
1999 'pepper_interface': 'ChromiumMapSub',
2001 'PixelStorei': {'type': 'Manual'},
2002 'PostSubBufferCHROMIUM': {
2006 'client_test': False,
2010 'ProduceTextureCHROMIUM': {
2011 'decoder_func': 'DoProduceTextureCHROMIUM',
2014 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2016 'client_test': False,
2017 'extension': "CHROMIUM_texture_mailbox",
2021 'ProduceTextureDirectCHROMIUM': {
2022 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
2025 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2027 'client_test': False,
2028 'extension': "CHROMIUM_texture_mailbox",
2032 'RenderbufferStorage': {
2033 'decoder_func': 'DoRenderbufferStorage',
2034 'gl_test_func': 'glRenderbufferStorageEXT',
2035 'expectation': False,
2037 'RenderbufferStorageMultisampleCHROMIUM': {
2039 '// GL_CHROMIUM_framebuffer_multisample\n',
2040 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
2041 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
2042 'expectation': False,
2044 'extension_flag': 'chromium_framebuffer_multisample',
2045 'pepper_interface': 'FramebufferMultisample',
2046 'pepper_name': 'RenderbufferStorageMultisampleEXT',
2048 'RenderbufferStorageMultisampleEXT': {
2050 '// GL_EXT_multisampled_render_to_texture\n',
2051 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
2052 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
2053 'expectation': False,
2055 'extension_flag': 'multisampled_render_to_texture',
2059 '// ReadPixels has the result separated from the pixel buffer so that\n'
2060 '// it is easier to specify the result going to some specific place\n'
2061 '// that exactly fits the rectangle of pixels.\n',
2063 'data_transfer_methods': ['shm'],
2065 'client_test': False,
2067 'GLint x, GLint y, GLsizei width, GLsizei height, '
2068 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
2069 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
2070 'uint32_t result_shm_id, uint32_t result_shm_offset, '
2072 'result': ['uint32_t'],
2073 'defer_reads': True,
2075 'RegisterSharedIdsCHROMIUM': {
2077 'decoder_func': 'DoRegisterSharedIdsCHROMIUM',
2079 'expectation': False,
2080 'data_transfer_methods': ['shm'],
2084 'ReleaseShaderCompiler': {
2085 'decoder_func': 'DoReleaseShaderCompiler',
2090 'client_test': False,
2094 'data_transfer_methods': ['bucket'],
2096 'client_test': False,
2098 'GLuint shader, const char* data',
2100 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2103 'type': 'StateSetFrontBack',
2104 'state': 'StencilMask',
2106 'expectation': False,
2108 'StencilMaskSeparate': {
2109 'type': 'StateSetFrontBackSeparate',
2110 'state': 'StencilMask',
2112 'expectation': False,
2116 'decoder_func': 'DoSwapBuffers',
2118 'client_test': False,
2124 'data_transfer_methods': ['shm'],
2125 'client_test': False,
2128 'decoder_func': 'DoTexParameterf',
2134 'decoder_func': 'DoTexParameteri',
2141 'data_value': 'GL_NEAREST',
2143 'decoder_func': 'DoTexParameterfv',
2144 'gl_test_func': 'glTexParameterf',
2145 'first_element_only': True,
2149 'data_value': 'GL_NEAREST',
2151 'decoder_func': 'DoTexParameteriv',
2152 'gl_test_func': 'glTexParameteri',
2153 'first_element_only': True,
2157 'data_transfer_methods': ['shm'],
2158 'client_test': False,
2159 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2160 'GLint xoffset, GLint yoffset, '
2161 'GLsizei width, GLsizei height, '
2162 'GLenumTextureFormat format, GLenumPixelType type, '
2163 'const void* pixels, GLboolean internal'
2165 'Uniform1f': {'type': 'PUTXn', 'count': 1},
2169 'decoder_func': 'DoUniform1fv',
2171 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2175 'decoder_func': 'DoUniform1iv',
2178 'Uniform2i': {'type': 'PUTXn', 'count': 2},
2179 'Uniform2f': {'type': 'PUTXn', 'count': 2},
2183 'decoder_func': 'DoUniform2fv',
2188 'decoder_func': 'DoUniform2iv',
2190 'Uniform3i': {'type': 'PUTXn', 'count': 3},
2191 'Uniform3f': {'type': 'PUTXn', 'count': 3},
2195 'decoder_func': 'DoUniform3fv',
2200 'decoder_func': 'DoUniform3iv',
2202 'Uniform4i': {'type': 'PUTXn', 'count': 4},
2203 'Uniform4f': {'type': 'PUTXn', 'count': 4},
2207 'decoder_func': 'DoUniform4fv',
2212 'decoder_func': 'DoUniform4iv',
2214 'UniformMatrix2fv': {
2217 'decoder_func': 'DoUniformMatrix2fv',
2219 'UniformMatrix3fv': {
2222 'decoder_func': 'DoUniformMatrix3fv',
2224 'UniformMatrix4fv': {
2227 'decoder_func': 'DoUniformMatrix4fv',
2229 'UnmapBufferCHROMIUM': {
2233 'client_test': False,
2235 'UnmapBufferSubDataCHROMIUM': {
2239 'client_test': False,
2240 'pepper_interface': 'ChromiumMapSub',
2242 'UnmapImageCHROMIUM': {
2246 'client_test': False,
2248 'UnmapTexSubImage2DCHROMIUM': {
2252 'client_test': False,
2253 'pepper_interface': 'ChromiumMapSub',
2257 'decoder_func': 'DoUseProgram',
2259 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2260 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2261 'VertexAttrib1fv': {
2264 'decoder_func': 'DoVertexAttrib1fv',
2266 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2267 'VertexAttrib2fv': {
2270 'decoder_func': 'DoVertexAttrib2fv',
2272 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2273 'VertexAttrib3fv': {
2276 'decoder_func': 'DoVertexAttrib3fv',
2278 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2279 'VertexAttrib4fv': {
2282 'decoder_func': 'DoVertexAttrib4fv',
2284 'VertexAttribPointer': {
2286 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2287 'GLenumVertexAttribType type, GLboolean normalized, '
2288 'GLsizei stride, GLuint offset',
2289 'client_test': False,
2296 'decoder_func': 'DoViewport',
2305 'GetRequestableExtensionsCHROMIUM': {
2308 'cmd_args': 'uint32_t bucket_id',
2312 'RequestExtensionCHROMIUM': {
2315 'client_test': False,
2316 'cmd_args': 'uint32_t bucket_id',
2320 'RateLimitOffscreenContextCHROMIUM': {
2324 'client_test': False,
2326 'CreateStreamTextureCHROMIUM': {
2327 'type': 'HandWritten',
2333 'TexImageIOSurface2DCHROMIUM': {
2334 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2339 'CopyTextureCHROMIUM': {
2340 'decoder_func': 'DoCopyTextureCHROMIUM',
2345 'TexStorage2DEXT': {
2348 'decoder_func': 'DoTexStorage2DEXT',
2350 'DrawArraysInstancedANGLE': {
2352 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2353 'GLsizei primcount',
2356 'pepper_interface': 'InstancedArrays',
2357 'defer_draws': True,
2361 'decoder_func': 'DoDrawBuffersEXT',
2363 'client_test': False,
2365 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
2368 'pepper_interface': 'DrawBuffers',
2370 'DrawElementsInstancedANGLE': {
2372 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2373 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2376 'client_test': False,
2377 'pepper_interface': 'InstancedArrays',
2378 'defer_draws': True,
2380 'VertexAttribDivisorANGLE': {
2382 'cmd_args': 'GLuint index, GLuint divisor',
2385 'pepper_interface': 'InstancedArrays',
2389 'gl_test_func': 'glGenQueriesARB',
2390 'resource_type': 'Query',
2391 'resource_types': 'Queries',
2393 'pepper_interface': 'Query',
2394 'not_shared': 'True',
2396 'DeleteQueriesEXT': {
2398 'gl_test_func': 'glDeleteQueriesARB',
2399 'resource_type': 'Query',
2400 'resource_types': 'Queries',
2402 'pepper_interface': 'Query',
2406 'client_test': False,
2407 'pepper_interface': 'Query',
2411 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2412 'data_transfer_methods': ['shm'],
2413 'gl_test_func': 'glBeginQuery',
2414 'pepper_interface': 'Query',
2418 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2419 'gl_test_func': 'glEndnQuery',
2420 'client_test': False,
2421 'pepper_interface': 'Query',
2425 'client_test': False,
2426 'gl_test_func': 'glGetQueryiv',
2427 'pepper_interface': 'Query',
2429 'GetQueryObjectuivEXT': {
2431 'client_test': False,
2432 'gl_test_func': 'glGetQueryObjectuiv',
2433 'pepper_interface': 'Query',
2435 'BindUniformLocationCHROMIUM': {
2438 'data_transfer_methods': ['bucket'],
2440 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2442 'InsertEventMarkerEXT': {
2444 'decoder_func': 'DoInsertEventMarkerEXT',
2445 'expectation': False,
2448 'PushGroupMarkerEXT': {
2450 'decoder_func': 'DoPushGroupMarkerEXT',
2451 'expectation': False,
2454 'PopGroupMarkerEXT': {
2455 'decoder_func': 'DoPopGroupMarkerEXT',
2456 'expectation': False,
2461 'GenVertexArraysOES': {
2464 'gl_test_func': 'glGenVertexArraysOES',
2465 'resource_type': 'VertexArray',
2466 'resource_types': 'VertexArrays',
2468 'pepper_interface': 'VertexArrayObject',
2470 'BindVertexArrayOES': {
2473 'gl_test_func': 'glBindVertexArrayOES',
2474 'decoder_func': 'DoBindVertexArrayOES',
2475 'gen_func': 'GenVertexArraysOES',
2477 'client_test': False,
2478 'pepper_interface': 'VertexArrayObject',
2480 'DeleteVertexArraysOES': {
2483 'gl_test_func': 'glDeleteVertexArraysOES',
2484 'resource_type': 'VertexArray',
2485 'resource_types': 'VertexArrays',
2487 'pepper_interface': 'VertexArrayObject',
2489 'IsVertexArrayOES': {
2492 'gl_test_func': 'glIsVertexArrayOES',
2493 'decoder_func': 'DoIsVertexArrayOES',
2494 'expectation': False,
2496 'pepper_interface': 'VertexArrayObject',
2498 'BindTexImage2DCHROMIUM': {
2499 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2504 'ReleaseTexImage2DCHROMIUM': {
2505 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2510 'ShallowFinishCHROMIUM': {
2515 'client_test': False,
2517 'ShallowFlushCHROMIUM': {
2522 'client_test': False,
2524 'TraceBeginCHROMIUM': {
2527 'client_test': False,
2528 'cmd_args': 'GLuint bucket_id',
2532 'TraceEndCHROMIUM': {
2534 'client_test': False,
2535 'decoder_func': 'DoTraceEndCHROMIUM',
2540 'AsyncTexImage2DCHROMIUM': {
2542 'data_transfer_methods': ['shm'],
2543 'client_test': False,
2544 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2545 'GLintTextureInternalFormat internalformat, '
2546 'GLsizei width, GLsizei height, '
2547 'GLintTextureBorder border, '
2548 'GLenumTextureFormat format, GLenumPixelType type, '
2549 'const void* pixels, '
2550 'uint32_t async_upload_token, '
2555 'AsyncTexSubImage2DCHROMIUM': {
2557 'data_transfer_methods': ['shm'],
2558 'client_test': False,
2559 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2560 'GLint xoffset, GLint yoffset, '
2561 'GLsizei width, GLsizei height, '
2562 'GLenumTextureFormat format, GLenumPixelType type, '
2563 'const void* data, '
2564 'uint32_t async_upload_token, '
2569 'WaitAsyncTexImage2DCHROMIUM': {
2571 'client_test': False,
2575 'WaitAllAsyncTexImage2DCHROMIUM': {
2577 'client_test': False,
2581 'DiscardFramebufferEXT': {
2584 'cmd_args': 'GLenum target, GLsizei count, '
2585 'const GLenum* attachments',
2586 'decoder_func': 'DoDiscardFramebufferEXT',
2588 'client_test': False,
2589 'extension_flag': 'ext_discard_framebuffer',
2591 'LoseContextCHROMIUM': {
2592 'decoder_func': 'DoLoseContextCHROMIUM',
2597 'InsertSyncPointCHROMIUM': {
2598 'type': 'HandWritten',
2600 'extension': "CHROMIUM_sync_point",
2603 'WaitSyncPointCHROMIUM': {
2606 'extension': "CHROMIUM_sync_point",
2610 'DiscardBackbufferCHROMIUM': {
2616 'ScheduleOverlayPlaneCHROMIUM': {
2620 'client_test': False,
2624 'MatrixLoadfCHROMIUM': {
2627 'data_type': 'GLfloat',
2628 'decoder_func': 'DoMatrixLoadfCHROMIUM',
2629 'gl_test_func': 'glMatrixLoadfEXT',
2632 'extension_flag': 'chromium_path_rendering',
2634 'MatrixLoadIdentityCHROMIUM': {
2635 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
2636 'gl_test_func': 'glMatrixLoadIdentityEXT',
2639 'extension_flag': 'chromium_path_rendering',
2644 def Grouper(n
, iterable
, fillvalue
=None):
2645 """Collect data into fixed-length chunks or blocks"""
2646 args
= [iter(iterable
)] * n
2647 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
2650 def SplitWords(input_string
):
2651 """Transforms a input_string into a list of lower-case components.
2654 input_string: the input string.
2657 a list of lower-case words.
2659 if input_string
.find('_') > -1:
2660 # 'some_TEXT_' -> 'some text'
2661 return input_string
.replace('_', ' ').strip().lower().split()
2663 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
2665 # look for capitalization to cut input_strings
2666 # 'SomeText' -> 'Some Text'
2667 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
2668 # 'Vector3' -> 'Vector 3'
2669 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
2670 return input_string
.lower().split()
2674 """Makes a lower-case identifier from words.
2677 words: a list of lower-case words.
2680 the lower-case identifier.
2682 return '_'.join(words
)
2685 def ToUnderscore(input_string
):
2686 """converts CamelCase to camel_case."""
2687 words
= SplitWords(input_string
)
2690 def CachedStateName(item
):
2691 if item
.get('cached', False):
2692 return 'cached_' + item
['name']
2695 def ToGLExtensionString(extension_flag
):
2696 """Returns GL-type extension string of a extension flag."""
2697 if extension_flag
== "oes_compressed_etc1_rgb8_texture":
2698 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
2700 uppercase_words
= [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
2701 'egl', 'atc', 'etc1', 'angle']
2702 parts
= extension_flag
.split('_')
2704 [part
.upper() if part
in uppercase_words
else part
for part
in parts
])
2706 def ToCamelCase(input_string
):
2707 """converts ABC_underscore_case to ABCUnderscoreCase."""
2708 return ''.join(w
[0].upper() + w
[1:] for w
in input_string
.split('_'))
2710 def GetGLGetTypeConversion(result_type
, value_type
, value
):
2711 """Makes a gl compatible type conversion string for accessing state variables.
2713 Useful when accessing state variables through glGetXXX calls.
2714 glGet documetation (for example, the manual pages):
2715 [...] If glGetIntegerv is called, [...] most floating-point values are
2716 rounded to the nearest integer value. [...]
2719 result_type: the gl type to be obtained
2720 value_type: the GL type of the state variable
2721 value: the name of the state variable
2724 String that converts the state variable to desired GL type according to GL
2728 if result_type
== 'GLint':
2729 if value_type
== 'GLfloat':
2730 return 'static_cast<GLint>(round(%s))' % value
2731 return 'static_cast<%s>(%s)' % (result_type
, value
)
2733 class CWriter(object):
2734 """Writes to a file formatting it for Google's style guidelines."""
2736 def __init__(self
, filename
):
2737 self
.filename
= filename
2740 def Write(self
, string
):
2741 """Writes a string to a file spliting if it's > 80 characters."""
2742 lines
= string
.splitlines()
2743 num_lines
= len(lines
)
2744 for ii
in range(0, num_lines
):
2745 self
.content
.append(lines
[ii
])
2746 if ii
< (num_lines
- 1) or string
[-1] == '\n':
2747 self
.content
.append('\n')
2750 """Close the file."""
2751 content
= "".join(self
.content
)
2753 if os
.path
.exists(self
.filename
):
2754 old_file
= open(self
.filename
, "rb");
2755 old_content
= old_file
.read()
2757 if content
== old_content
:
2760 file = open(self
.filename
, "wb")
2765 class CHeaderWriter(CWriter
):
2766 """Writes a C Header file."""
2768 _non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
2770 def __init__(self
, filename
, file_comment
= None):
2771 CWriter
.__init
__(self
, filename
)
2773 base
= os
.path
.abspath(filename
)
2774 while os
.path
.basename(base
) != 'src':
2775 new_base
= os
.path
.dirname(base
)
2776 assert new_base
!= base
# Prevent infinite loop.
2779 hpath
= os
.path
.relpath(filename
, base
)
2780 self
.guard
= self
._non
_alnum
_re
.sub('_', hpath
).upper() + '_'
2782 self
.Write(_LICENSE
)
2783 self
.Write(_DO_NOT_EDIT_WARNING
)
2784 if not file_comment
== None:
2785 self
.Write(file_comment
)
2786 self
.Write("#ifndef %s\n" % self
.guard
)
2787 self
.Write("#define %s\n\n" % self
.guard
)
2790 self
.Write("#endif // %s\n\n" % self
.guard
)
2793 class TypeHandler(object):
2794 """This class emits code for a particular type of function."""
2796 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
2801 def InitFunction(self
, func
):
2802 """Add or adjust anything type specific for this function."""
2803 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
2804 func
.AddCmdArg(DataSizeArgument('data_size'))
2806 def NeedsDataTransferFunction(self
, func
):
2807 """Overriden from TypeHandler."""
2808 return func
.num_pointer_args
>= 1
2810 def WriteStruct(self
, func
, file):
2811 """Writes a structure that matches the arguments to a function."""
2812 comment
= func
.GetInfo('cmd_comment')
2813 if not comment
== None:
2815 file.Write("struct %s {\n" % func
.name
)
2816 file.Write(" typedef %s ValueType;\n" % func
.name
)
2817 file.Write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
2818 func
.WriteCmdArgFlag(file)
2819 func
.WriteCmdFlag(file)
2821 result
= func
.GetInfo('result')
2822 if not result
== None:
2823 if len(result
) == 1:
2824 file.Write(" typedef %s Result;\n\n" % result
[0])
2826 file.Write(" struct Result {\n")
2828 file.Write(" %s;\n" % line
)
2829 file.Write(" };\n\n")
2831 func
.WriteCmdComputeSize(file)
2832 func
.WriteCmdSetHeader(file)
2833 func
.WriteCmdInit(file)
2834 func
.WriteCmdSet(file)
2836 file.Write(" gpu::CommandHeader header;\n")
2837 args
= func
.GetCmdArgs()
2839 file.Write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
2841 consts
= func
.GetCmdConstants()
2842 for const
in consts
:
2843 file.Write(" static const %s %s = %s;\n" %
2844 (const
.cmd_type
, const
.name
, const
.GetConstantValue()))
2849 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
2850 file.Write("COMPILE_ASSERT(sizeof(%s) == %d,\n" % (func
.name
, size
))
2851 file.Write(" Sizeof_%s_is_not_%d);\n" % (func
.name
, size
))
2852 file.Write("COMPILE_ASSERT(offsetof(%s, header) == 0,\n" % func
.name
)
2853 file.Write(" OffsetOf_%s_header_not_0);\n" % func
.name
)
2854 offset
= _SIZE_OF_COMMAND_HEADER
2856 file.Write("COMPILE_ASSERT(offsetof(%s, %s) == %d,\n" %
2857 (func
.name
, arg
.name
, offset
))
2858 file.Write(" OffsetOf_%s_%s_not_%d);\n" %
2859 (func
.name
, arg
.name
, offset
))
2860 offset
+= _SIZE_OF_UINT32
2861 if not result
== None and len(result
) > 1:
2864 parts
= line
.split()
2867 COMPILE_ASSERT(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
2868 OffsetOf_%(cmd_name)s_Result_%(field_name)s_not_%(offset)d);
2870 file.Write((check
.strip() + "\n") % {
2871 'cmd_name': func
.name
,
2875 offset
+= _SIZE_OF_UINT32
2878 def WriteHandlerImplementation(self
, func
, file):
2879 """Writes the handler implementation for this command."""
2880 file.Write(" %s(%s);\n" %
2881 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2883 def WriteCmdSizeTest(self
, func
, file):
2884 """Writes the size test for a command."""
2885 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2887 def WriteFormatTest(self
, func
, file):
2888 """Writes a format test for a command."""
2889 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
2890 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
2891 (func
.name
, func
.name
))
2892 file.Write(" void* next_cmd = cmd.Set(\n")
2894 args
= func
.GetCmdArgs()
2895 for value
, arg
in enumerate(args
):
2896 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
2898 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
2900 file.Write(" cmd.header.command);\n")
2901 func
.type_handler
.WriteCmdSizeTest(func
, file)
2902 for value
, arg
in enumerate(args
):
2903 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
2904 (arg
.type, value
+ 11, arg
.name
))
2905 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
2906 file.Write(" next_cmd, sizeof(cmd));\n")
2910 def WriteImmediateFormatTest(self
, func
, file):
2911 """Writes a format test for an immediate version of a command."""
2914 def WriteBucketFormatTest(self
, func
, file):
2915 """Writes a format test for a bucket version of a command."""
2918 def WriteGetDataSizeCode(self
, func
, file):
2919 """Writes the code to set data_size used in validation"""
2922 def WriteImmediateCmdSizeTest(self
, func
, file):
2923 """Writes a size test for an immediate version of a command."""
2924 file.Write(" // TODO(gman): Compute correct size.\n")
2925 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
2927 def WriteImmediateHandlerImplementation (self
, func
, file):
2928 """Writes the handler impl for the immediate version of a command."""
2929 file.Write(" %s(%s);\n" %
2930 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2932 def WriteBucketHandlerImplementation (self
, func
, file):
2933 """Writes the handler impl for the bucket version of a command."""
2934 file.Write(" %s(%s);\n" %
2935 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
2937 def WriteServiceImplementation(self
, func
, file):
2938 """Writes the service implementation for a command."""
2940 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
2942 " uint32_t immediate_data_size, const gles2::cmds::%s& c) {\n" %
2944 self
.WriteHandlerExtensionCheck(func
, file)
2945 self
.WriteHandlerDeferReadWrite(func
, file);
2946 if len(func
.GetOriginalArgs()) > 0:
2947 last_arg
= func
.GetLastOriginalArg()
2948 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2949 for arg
in all_but_last_arg
:
2950 arg
.WriteGetCode(file)
2951 self
.WriteGetDataSizeCode(func
, file)
2952 last_arg
.WriteGetCode(file)
2953 func
.WriteHandlerValidation(file)
2954 func
.WriteHandlerImplementation(file)
2955 file.Write(" return error::kNoError;\n")
2959 def WriteImmediateServiceImplementation(self
, func
, file):
2960 """Writes the service implementation for an immediate version of command."""
2962 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
2964 " uint32_t immediate_data_size, const gles2::cmds::%s& c) {\n" %
2966 self
.WriteHandlerExtensionCheck(func
, file)
2967 self
.WriteHandlerDeferReadWrite(func
, file);
2968 last_arg
= func
.GetLastOriginalArg()
2969 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2970 for arg
in all_but_last_arg
:
2971 arg
.WriteGetCode(file)
2972 self
.WriteGetDataSizeCode(func
, file)
2973 last_arg
.WriteGetCode(file)
2974 func
.WriteHandlerValidation(file)
2975 func
.WriteHandlerImplementation(file)
2976 file.Write(" return error::kNoError;\n")
2980 def WriteBucketServiceImplementation(self
, func
, file):
2981 """Writes the service implementation for a bucket version of command."""
2983 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
2985 " uint32_t immediate_data_size, const gles2::cmds::%s& c) {\n" %
2987 self
.WriteHandlerExtensionCheck(func
, file)
2988 self
.WriteHandlerDeferReadWrite(func
, file);
2989 last_arg
= func
.GetLastOriginalArg()
2990 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
2991 for arg
in all_but_last_arg
:
2992 arg
.WriteGetCode(file)
2993 self
.WriteGetDataSizeCode(func
, file)
2994 last_arg
.WriteGetCode(file)
2995 func
.WriteHandlerValidation(file)
2996 func
.WriteHandlerImplementation(file)
2997 file.Write(" return error::kNoError;\n")
3001 def WriteHandlerExtensionCheck(self
, func
, file):
3002 if func
.GetInfo('extension_flag'):
3003 file.Write(" if (!features().%s) {\n" % func
.GetInfo('extension_flag'))
3004 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
3005 " \"function not available\");\n" % func
.original_name
)
3006 file.Write(" return error::kNoError;")
3007 file.Write(" }\n\n")
3009 def WriteHandlerDeferReadWrite(self
, func
, file):
3010 """Writes the code to handle deferring reads or writes."""
3011 defer_draws
= func
.GetInfo('defer_draws')
3012 defer_reads
= func
.GetInfo('defer_reads')
3013 if defer_draws
or defer_reads
:
3014 file.Write(" error::Error error;\n")
3016 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
3017 file.Write(" if (error != error::kNoError)\n")
3018 file.Write(" return error;\n")
3020 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
3021 file.Write(" if (error != error::kNoError)\n")
3022 file.Write(" return error;\n")
3024 def WriteValidUnitTest(self
, func
, file, test
, *extras
):
3025 """Writes a valid unit test for the service implementation."""
3026 if func
.GetInfo('expectation') == False:
3027 test
= self
._remove
_expected
_call
_re
.sub('', test
)
3030 arg
.GetValidArg(func
) \
3031 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
3034 arg
.GetValidGLArg(func
) \
3035 for arg
in func
.GetOriginalArgs()
3037 gl_func_name
= func
.GetGLTestFunctionName()
3040 'gl_func_name': gl_func_name
,
3041 'args': ", ".join(arg_strings
),
3042 'gl_args': ", ".join(gl_arg_strings
),
3044 for extra
in extras
:
3047 while (old_test
!= test
):
3050 file.Write(test
% vars)
3052 def WriteInvalidUnitTest(self
, func
, file, test
, *extras
):
3053 """Writes an invalid unit test for the service implementation."""
3054 for invalid_arg_index
, invalid_arg
in enumerate(func
.GetOriginalArgs()):
3055 # Service implementation does not test constants, as they are not part of
3056 # the call in the service side.
3057 if invalid_arg
.IsConstant():
3060 num_invalid_values
= invalid_arg
.GetNumInvalidValues(func
)
3061 for value_index
in range(0, num_invalid_values
):
3063 parse_result
= "kNoError"
3065 for arg
in func
.GetOriginalArgs():
3066 if arg
.IsConstant():
3068 if invalid_arg
is arg
:
3069 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
3072 arg_string
= arg
.GetValidArg(func
)
3073 arg_strings
.append(arg_string
)
3075 for arg
in func
.GetOriginalArgs():
3076 gl_arg_strings
.append("_")
3077 gl_func_name
= func
.GetGLTestFunctionName()
3079 if not gl_error
== None:
3080 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
3084 'arg_index': invalid_arg_index
,
3085 'value_index': value_index
,
3086 'gl_func_name': gl_func_name
,
3087 'args': ", ".join(arg_strings
),
3088 'all_but_last_args': ", ".join(arg_strings
[:-1]),
3089 'gl_args': ", ".join(gl_arg_strings
),
3090 'parse_result': parse_result
,
3091 'gl_error_test': gl_error_test
,
3093 for extra
in extras
:
3095 file.Write(test
% vars)
3097 def WriteServiceUnitTest(self
, func
, file, *extras
):
3098 """Writes the service unit test for a command."""
3100 if func
.name
== 'Enable':
3102 TEST_P(%(test_name)s, %(name)sValidArgs) {
3103 SetupExpectationsForEnableDisable(%(gl_args)s, true);
3104 SpecializedSetup<cmds::%(name)s, 0>(true);
3107 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3108 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3111 elif func
.name
== 'Disable':
3113 TEST_P(%(test_name)s, %(name)sValidArgs) {
3114 SetupExpectationsForEnableDisable(%(gl_args)s, false);
3115 SpecializedSetup<cmds::%(name)s, 0>(true);
3118 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3119 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3124 TEST_P(%(test_name)s, %(name)sValidArgs) {
3125 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3126 SpecializedSetup<cmds::%(name)s, 0>(true);
3129 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3130 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3133 self
.WriteValidUnitTest(func
, file, valid_test
, *extras
)
3136 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3137 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3138 SpecializedSetup<cmds::%(name)s, 0>(false);
3141 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3144 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
3146 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
3147 """Writes the service unit test for an immediate command."""
3148 file.Write("// TODO(gman): %s\n" % func
.name
)
3150 def WriteImmediateValidationCode(self
, func
, file):
3151 """Writes the validation code for an immediate version of a command."""
3154 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
3155 """Writes the service unit test for a bucket command."""
3156 file.Write("// TODO(gman): %s\n" % func
.name
)
3158 def WriteBucketValidationCode(self
, func
, file):
3159 """Writes the validation code for a bucket version of a command."""
3160 file.Write("// TODO(gman): %s\n" % func
.name
)
3162 def WriteGLES2ImplementationDeclaration(self
, func
, file):
3163 """Writes the GLES2 Implemention declaration."""
3164 impl_decl
= func
.GetInfo('impl_decl')
3165 if impl_decl
== None or impl_decl
== True:
3166 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3167 (func
.return_type
, func
.original_name
,
3168 func
.MakeTypedOriginalArgString("")))
3171 def WriteGLES2CLibImplementation(self
, func
, file):
3172 file.Write("%s GLES2%s(%s) {\n" %
3173 (func
.return_type
, func
.name
,
3174 func
.MakeTypedOriginalArgString("")))
3175 result_string
= "return "
3176 if func
.return_type
== "void":
3178 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3179 (result_string
, func
.original_name
,
3180 func
.MakeOriginalArgString("")))
3183 def WriteGLES2Header(self
, func
, file):
3184 """Writes a re-write macro for GLES"""
3185 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
3187 def WriteClientGLCallLog(self
, func
, file):
3188 """Writes a logging macro for the client side code."""
3190 if len(func
.GetOriginalArgs()):
3193 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3194 (func
.original_name
, comma
, func
.MakeLogArgString()))
3196 def WriteClientGLReturnLog(self
, func
, file):
3197 """Writes the return value logging code."""
3198 if func
.return_type
!= "void":
3199 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3201 def WriteGLES2ImplementationHeader(self
, func
, file):
3202 """Writes the GLES2 Implemention."""
3203 self
.WriteGLES2ImplementationDeclaration(func
, file)
3205 def WriteGLES2TraceImplementationHeader(self
, func
, file):
3206 """Writes the GLES2 Trace Implemention header."""
3207 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3208 (func
.return_type
, func
.original_name
,
3209 func
.MakeTypedOriginalArgString("")))
3211 def WriteGLES2TraceImplementation(self
, func
, file):
3212 """Writes the GLES2 Trace Implemention."""
3213 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3214 (func
.return_type
, func
.original_name
,
3215 func
.MakeTypedOriginalArgString("")))
3216 result_string
= "return "
3217 if func
.return_type
== "void":
3219 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3221 file.Write(" %sgl_->%s(%s);\n" %
3222 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
3226 def WriteGLES2Implementation(self
, func
, file):
3227 """Writes the GLES2 Implemention."""
3228 impl_func
= func
.GetInfo('impl_func')
3229 impl_decl
= func
.GetInfo('impl_decl')
3230 gen_cmd
= func
.GetInfo('gen_cmd')
3231 if (func
.can_auto_generate
and
3232 (impl_func
== None or impl_func
== True) and
3233 (impl_decl
== None or impl_decl
== True) and
3234 (gen_cmd
== None or gen_cmd
== True)):
3235 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3236 (func
.return_type
, func
.original_name
,
3237 func
.MakeTypedOriginalArgString("")))
3238 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3239 self
.WriteClientGLCallLog(func
, file)
3240 func
.WriteDestinationInitalizationValidation(file)
3241 for arg
in func
.GetOriginalArgs():
3242 arg
.WriteClientSideValidationCode(file, func
)
3243 file.Write(" helper_->%s(%s);\n" %
3244 (func
.name
, func
.MakeHelperArgString("")))
3245 file.Write(" CheckGLError();\n")
3246 self
.WriteClientGLReturnLog(func
, file)
3250 def WriteGLES2InterfaceHeader(self
, func
, file):
3251 """Writes the GLES2 Interface."""
3252 file.Write("virtual %s %s(%s) = 0;\n" %
3253 (func
.return_type
, func
.original_name
,
3254 func
.MakeTypedOriginalArgString("")))
3256 def WriteGLES2InterfaceStub(self
, func
, file):
3257 """Writes the GLES2 Interface stub declaration."""
3258 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3259 (func
.return_type
, func
.original_name
,
3260 func
.MakeTypedOriginalArgString("")))
3262 def WriteGLES2InterfaceStubImpl(self
, func
, file):
3263 """Writes the GLES2 Interface stub declaration."""
3264 args
= func
.GetOriginalArgs()
3265 arg_string
= ", ".join(
3266 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
3267 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3268 (func
.return_type
, func
.original_name
, arg_string
))
3269 if func
.return_type
!= "void":
3270 file.Write(" return 0;\n")
3273 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3274 """Writes the GLES2 Implemention unit test."""
3275 client_test
= func
.GetInfo('client_test')
3276 if (func
.can_auto_generate
and
3277 (client_test
== None or client_test
== True)):
3279 TEST_F(GLES2ImplementationTest, %(name)s) {
3284 expected.cmd.Init(%(cmd_args)s);
3286 gl_->%(name)s(%(args)s);
3287 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3291 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
3295 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
3300 'args': ", ".join(gl_arg_strings
),
3301 'cmd_args': ", ".join(cmd_arg_strings
),
3304 # Test constants for invalid values, as they are not tested by the
3306 constants
= [arg
for arg
in func
.GetOriginalArgs() if arg
.IsConstant()]
3309 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
3310 gl_->%(name)s(%(args)s);
3311 EXPECT_TRUE(NoCommandsWritten());
3312 EXPECT_EQ(%(gl_error)s, CheckError());
3315 for invalid_arg
in constants
:
3317 invalid
= invalid_arg
.GetInvalidArg(func
)
3318 for arg
in func
.GetOriginalArgs():
3319 if arg
is invalid_arg
:
3320 gl_arg_strings
.append(invalid
[0])
3322 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
3326 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
3327 'args': ", ".join(gl_arg_strings
),
3328 'gl_error': invalid
[2],
3331 if client_test
!= False:
3332 file.Write("// TODO: Implement unit test for %s\n" % func
.name
)
3334 def WriteDestinationInitalizationValidation(self
, func
, file):
3335 """Writes the client side destintion initialization validation."""
3336 for arg
in func
.GetOriginalArgs():
3337 arg
.WriteDestinationInitalizationValidation(file, func
)
3339 def WriteTraceEvent(self
, func
, file):
3340 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3343 def WriteImmediateCmdComputeSize(self
, func
, file):
3344 """Writes the size computation code for the immediate version of a cmd."""
3345 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
3346 file.Write(" return static_cast<uint32_t>(\n")
3347 file.Write(" sizeof(ValueType) + // NOLINT\n")
3348 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3352 def WriteImmediateCmdSetHeader(self
, func
, file):
3353 """Writes the SetHeader function for the immediate version of a cmd."""
3354 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
3355 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3359 def WriteImmediateCmdInit(self
, func
, file):
3360 """Writes the Init function for the immediate version of a command."""
3361 raise NotImplementedError(func
.name
)
3363 def WriteImmediateCmdSet(self
, func
, file):
3364 """Writes the Set function for the immediate version of a command."""
3365 raise NotImplementedError(func
.name
)
3367 def WriteCmdHelper(self
, func
, file):
3368 """Writes the cmd helper definition for a cmd."""
3369 code
= """ void %(name)s(%(typed_args)s) {
3370 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3379 "typed_args": func
.MakeTypedCmdArgString(""),
3380 "args": func
.MakeCmdArgString(""),
3383 def WriteImmediateCmdHelper(self
, func
, file):
3384 """Writes the cmd helper definition for the immediate version of a cmd."""
3385 code
= """ void %(name)s(%(typed_args)s) {
3386 const uint32_t s = 0; // TODO(gman): compute correct size
3387 gles2::cmds::%(name)s* c =
3388 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3397 "typed_args": func
.MakeTypedCmdArgString(""),
3398 "args": func
.MakeCmdArgString(""),
3402 class StateSetHandler(TypeHandler
):
3403 """Handler for commands that simply set state."""
3406 TypeHandler
.__init
__(self
)
3408 def WriteHandlerImplementation(self
, func
, file):
3409 """Overrriden from TypeHandler."""
3410 state_name
= func
.GetInfo('state')
3411 state
= _STATES
[state_name
]
3412 states
= state
['states']
3413 args
= func
.GetOriginalArgs()
3414 for ndx
,item
in enumerate(states
):
3416 if 'range_checks' in item
:
3417 for range_check
in item
['range_checks']:
3418 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
3419 if 'nan_check' in item
:
3420 # Drivers might generate an INVALID_VALUE error when a value is set
3421 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
3422 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
3423 # Make this behavior consistent within Chromium, and avoid leaking GL
3424 # errors by generating the error in the command buffer instead of
3425 # letting the GL driver generate it.
3426 code
.append("base::IsNaN(%s)" % args
[ndx
].name
)
3428 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3430 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3431 ' "%s", "%s out of range");\n' %
3432 (func
.name
, args
[ndx
].name
))
3433 file.Write(" return error::kNoError;\n")
3436 for ndx
,item
in enumerate(states
):
3437 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
3438 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3439 for ndx
,item
in enumerate(states
):
3440 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
3441 if 'state_flag' in state
:
3442 file.Write(" %s = true;\n" % state
['state_flag'])
3443 if not func
.GetInfo("no_gl"):
3444 for ndx
,item
in enumerate(states
):
3445 if item
.get('cached', False):
3446 file.Write(" state_.%s = %s;\n" %
3447 (CachedStateName(item
), args
[ndx
].name
))
3448 file.Write(" %s(%s);\n" %
3449 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3452 def WriteServiceUnitTest(self
, func
, file, *extras
):
3453 """Overrriden from TypeHandler."""
3454 TypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
3455 state_name
= func
.GetInfo('state')
3456 state
= _STATES
[state_name
]
3457 states
= state
['states']
3458 for ndx
,item
in enumerate(states
):
3459 if 'range_checks' in item
:
3460 for check_ndx
, range_check
in enumerate(item
['range_checks']):
3462 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3463 SpecializedSetup<cmds::%(name)s, 0>(false);
3466 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3467 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3472 arg
.GetValidArg(func
) \
3473 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
3476 arg_strings
[ndx
] = range_check
['test_value']
3480 'check_ndx': check_ndx
,
3481 'args': ", ".join(arg_strings
),
3483 for extra
in extras
:
3485 file.Write(valid_test
% vars)
3486 if 'nan_check' in item
:
3488 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
3489 SpecializedSetup<cmds::%(name)s, 0>(false);
3492 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3493 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3498 arg
.GetValidArg(func
) \
3499 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
3502 arg_strings
[ndx
] = 'nanf("")'
3506 'args': ", ".join(arg_strings
),
3508 for extra
in extras
:
3510 file.Write(valid_test
% vars)
3513 class StateSetRGBAlphaHandler(TypeHandler
):
3514 """Handler for commands that simply set state that have rgb/alpha."""
3517 TypeHandler
.__init
__(self
)
3519 def WriteHandlerImplementation(self
, func
, file):
3520 """Overrriden from TypeHandler."""
3521 state_name
= func
.GetInfo('state')
3522 state
= _STATES
[state_name
]
3523 states
= state
['states']
3524 args
= func
.GetOriginalArgs()
3525 num_args
= len(args
)
3527 for ndx
,item
in enumerate(states
):
3528 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
3529 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3530 for ndx
, item
in enumerate(states
):
3531 file.Write(" state_.%s = %s;\n" %
3532 (item
['name'], args
[ndx
% num_args
].name
))
3533 if 'state_flag' in state
:
3534 file.Write(" %s = true;\n" % state
['state_flag'])
3535 if not func
.GetInfo("no_gl"):
3536 file.Write(" %s(%s);\n" %
3537 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3541 class StateSetFrontBackSeparateHandler(TypeHandler
):
3542 """Handler for commands that simply set state that have front/back."""
3545 TypeHandler
.__init
__(self
)
3547 def WriteHandlerImplementation(self
, func
, file):
3548 """Overrriden from TypeHandler."""
3549 state_name
= func
.GetInfo('state')
3550 state
= _STATES
[state_name
]
3551 states
= state
['states']
3552 args
= func
.GetOriginalArgs()
3554 num_args
= len(args
)
3555 file.Write(" bool changed = false;\n")
3556 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
3557 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3558 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
3560 for ndx
, item
in enumerate(group
):
3561 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
3562 file.Write(" changed |= %s;\n" % " ||\n ".join(code
))
3564 file.Write(" if (changed) {\n")
3565 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
3566 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
3567 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
3568 for ndx
, item
in enumerate(group
):
3569 file.Write(" state_.%s = %s;\n" %
3570 (item
['name'], args
[ndx
+ 1].name
))
3572 if 'state_flag' in state
:
3573 file.Write(" %s = true;\n" % state
['state_flag'])
3574 if not func
.GetInfo("no_gl"):
3575 file.Write(" %s(%s);\n" %
3576 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3580 class StateSetFrontBackHandler(TypeHandler
):
3581 """Handler for commands that simply set state that set both front/back."""
3584 TypeHandler
.__init
__(self
)
3586 def WriteHandlerImplementation(self
, func
, file):
3587 """Overrriden from TypeHandler."""
3588 state_name
= func
.GetInfo('state')
3589 state
= _STATES
[state_name
]
3590 states
= state
['states']
3591 args
= func
.GetOriginalArgs()
3592 num_args
= len(args
)
3594 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
3595 for ndx
, item
in enumerate(group
):
3596 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
3597 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
3598 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
3599 for ndx
, item
in enumerate(group
):
3600 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
3601 if 'state_flag' in state
:
3602 file.Write(" %s = true;\n" % state
['state_flag'])
3603 if not func
.GetInfo("no_gl"):
3604 file.Write(" %s(%s);\n" %
3605 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3609 class StateSetNamedParameter(TypeHandler
):
3610 """Handler for commands that set a state chosen with an enum parameter."""
3613 TypeHandler
.__init
__(self
)
3615 def WriteHandlerImplementation(self
, func
, file):
3616 """Overridden from TypeHandler."""
3617 state_name
= func
.GetInfo('state')
3618 state
= _STATES
[state_name
]
3619 states
= state
['states']
3620 args
= func
.GetOriginalArgs()
3621 num_args
= len(args
)
3622 assert num_args
== 2
3623 file.Write(" switch (%s) {\n" % args
[0].name
)
3624 for state
in states
:
3625 file.Write(" case %s:\n" % state
['enum'])
3626 file.Write(" if (state_.%s != %s) {\n" %
3627 (state
['name'], args
[1].name
))
3628 file.Write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
3629 if not func
.GetInfo("no_gl"):
3630 file.Write(" %s(%s);\n" %
3631 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3633 file.Write(" break;\n")
3634 file.Write(" default:\n")
3635 file.Write(" NOTREACHED();\n")
3639 class CustomHandler(TypeHandler
):
3640 """Handler for commands that are auto-generated but require minor tweaks."""
3643 TypeHandler
.__init
__(self
)
3645 def WriteServiceImplementation(self
, func
, file):
3646 """Overrriden from TypeHandler."""
3649 def WriteImmediateServiceImplementation(self
, func
, file):
3650 """Overrriden from TypeHandler."""
3653 def WriteBucketServiceImplementation(self
, func
, file):
3654 """Overrriden from TypeHandler."""
3657 def WriteServiceUnitTest(self
, func
, file, *extras
):
3658 """Overrriden from TypeHandler."""
3659 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3661 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
3662 """Overrriden from TypeHandler."""
3663 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3665 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3666 """Overrriden from TypeHandler."""
3668 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
3670 def WriteImmediateCmdInit(self
, func
, file):
3671 """Overrriden from TypeHandler."""
3672 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
3673 self
.WriteImmediateCmdGetTotalSize(func
, file)
3674 file.Write(" SetHeader(total_size);\n")
3675 args
= func
.GetCmdArgs()
3677 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
3681 def WriteImmediateCmdSet(self
, func
, file):
3682 """Overrriden from TypeHandler."""
3683 copy_args
= func
.MakeCmdArgString("_", False)
3684 file.Write(" void* Set(void* cmd%s) {\n" %
3685 func
.MakeTypedCmdArgString("_", True))
3686 self
.WriteImmediateCmdGetTotalSize(func
, file)
3687 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
3688 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3689 "cmd, total_size);\n")
3694 class TodoHandler(CustomHandler
):
3695 """Handle for commands that are not yet implemented."""
3697 def NeedsDataTransferFunction(self
, func
):
3698 """Overriden from TypeHandler."""
3701 def WriteImmediateFormatTest(self
, func
, file):
3702 """Overrriden from TypeHandler."""
3705 def WriteGLES2ImplementationUnitTest(self
, func
, file):
3706 """Overrriden from TypeHandler."""
3709 def WriteGLES2Implementation(self
, func
, file):
3710 """Overrriden from TypeHandler."""
3711 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3712 (func
.return_type
, func
.original_name
,
3713 func
.MakeTypedOriginalArgString("")))
3714 file.Write(" // TODO: for now this is a no-op\n")
3717 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3719 if func
.return_type
!= "void":
3720 file.Write(" return 0;\n")
3724 def WriteServiceImplementation(self
, func
, file):
3725 """Overrriden from TypeHandler."""
3727 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
3729 " uint32_t immediate_data_size, const gles2::cmds::%s& c) {\n" %
3731 file.Write(" // TODO: for now this is a no-op\n")
3733 " LOCAL_SET_GL_ERROR("
3734 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
3736 file.Write(" return error::kNoError;\n")
3741 class HandWrittenHandler(CustomHandler
):
3742 """Handler for comands where everything must be written by hand."""
3744 def InitFunction(self
, func
):
3745 """Add or adjust anything type specific for this function."""
3746 CustomHandler
.InitFunction(self
, func
)
3747 func
.can_auto_generate
= False
3749 def NeedsDataTransferFunction(self
, func
):
3750 """Overriden from TypeHandler."""
3751 # If specified explicitly, force the data transfer method.
3752 if func
.GetInfo('data_transfer_methods'):
3756 def WriteStruct(self
, func
, file):
3757 """Overrriden from TypeHandler."""
3760 def WriteDocs(self
, func
, file):
3761 """Overrriden from TypeHandler."""
3764 def WriteServiceUnitTest(self
, func
, file, *extras
):
3765 """Overrriden from TypeHandler."""
3766 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3768 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
3769 """Overrriden from TypeHandler."""
3770 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3772 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
3773 """Overrriden from TypeHandler."""
3774 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3776 def WriteServiceImplementation(self
, func
, file):
3777 """Overrriden from TypeHandler."""
3780 def WriteImmediateServiceImplementation(self
, func
, file):
3781 """Overrriden from TypeHandler."""
3784 def WriteBucketServiceImplementation(self
, func
, file):
3785 """Overrriden from TypeHandler."""
3788 def WriteImmediateCmdHelper(self
, func
, file):
3789 """Overrriden from TypeHandler."""
3792 def WriteBucketCmdHelper(self
, func
, file):
3793 """Overrriden from TypeHandler."""
3796 def WriteCmdHelper(self
, func
, file):
3797 """Overrriden from TypeHandler."""
3800 def WriteFormatTest(self
, func
, file):
3801 """Overrriden from TypeHandler."""
3802 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3804 def WriteImmediateFormatTest(self
, func
, file):
3805 """Overrriden from TypeHandler."""
3806 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3808 def WriteBucketFormatTest(self
, func
, file):
3809 """Overrriden from TypeHandler."""
3810 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
3814 class ManualHandler(CustomHandler
):
3815 """Handler for commands who's handlers must be written by hand."""
3818 CustomHandler
.__init
__(self
)
3820 def InitFunction(self
, func
):
3821 """Overrriden from TypeHandler."""
3822 if (func
.name
== 'CompressedTexImage2DBucket'):
3823 func
.cmd_args
= func
.cmd_args
[:-1]
3824 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
3826 CustomHandler
.InitFunction(self
, func
)
3828 def WriteServiceImplementation(self
, func
, file):
3829 """Overrriden from TypeHandler."""
3832 def WriteBucketServiceImplementation(self
, func
, file):
3833 """Overrriden from TypeHandler."""
3836 def WriteServiceUnitTest(self
, func
, file, *extras
):
3837 """Overrriden from TypeHandler."""
3838 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3840 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
3841 """Overrriden from TypeHandler."""
3842 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3844 def WriteImmediateServiceImplementation(self
, func
, file):
3845 """Overrriden from TypeHandler."""
3848 def WriteImmediateFormatTest(self
, func
, file):
3849 """Overrriden from TypeHandler."""
3850 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
3852 def WriteGLES2Implementation(self
, func
, file):
3853 """Overrriden from TypeHandler."""
3854 if func
.GetInfo('impl_func'):
3855 super(ManualHandler
, self
).WriteGLES2Implementation(func
, file)
3857 def WriteGLES2ImplementationHeader(self
, func
, file):
3858 """Overrriden from TypeHandler."""
3859 file.Write("virtual %s %s(%s) OVERRIDE;\n" %
3860 (func
.return_type
, func
.original_name
,
3861 func
.MakeTypedOriginalArgString("")))
3864 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3865 """Overrriden from TypeHandler."""
3866 # TODO(gman): Move this data to _FUNCTION_INFO?
3867 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, file)
3870 class DataHandler(TypeHandler
):
3871 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
3872 glCompressedTexImage2D, glCompressedTexImageSub2D."""
3874 TypeHandler
.__init
__(self
)
3876 def InitFunction(self
, func
):
3877 """Overrriden from TypeHandler."""
3878 if func
.name
== 'CompressedTexSubImage2DBucket':
3879 func
.cmd_args
= func
.cmd_args
[:-1]
3880 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
3882 def WriteGetDataSizeCode(self
, func
, file):
3883 """Overrriden from TypeHandler."""
3884 # TODO(gman): Move this data to _FUNCTION_INFO?
3886 if name
.endswith("Immediate"):
3888 if name
== 'BufferData' or name
== 'BufferSubData':
3889 file.Write(" uint32_t data_size = size;\n")
3890 elif (name
== 'CompressedTexImage2D' or
3891 name
== 'CompressedTexSubImage2D'):
3892 file.Write(" uint32_t data_size = imageSize;\n")
3893 elif (name
== 'CompressedTexSubImage2DBucket'):
3894 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
3895 file.Write(" uint32_t data_size = bucket->size();\n")
3896 file.Write(" GLsizei imageSize = data_size;\n")
3897 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
3898 code
= """ uint32_t data_size;
3899 if (!GLES2Util::ComputeImageDataSize(
3900 width, height, format, type, unpack_alignment_, &data_size)) {
3901 return error::kOutOfBounds;
3907 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
3909 def WriteImmediateCmdGetTotalSize(self
, func
, file):
3910 """Overrriden from TypeHandler."""
3913 def WriteImmediateCmdSizeTest(self
, func
, file):
3914 """Overrriden from TypeHandler."""
3915 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
3917 def WriteImmediateCmdInit(self
, func
, file):
3918 """Overrriden from TypeHandler."""
3919 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
3920 self
.WriteImmediateCmdGetTotalSize(func
, file)
3921 file.Write(" SetHeader(total_size);\n")
3922 args
= func
.GetCmdArgs()
3924 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
3928 def WriteImmediateCmdSet(self
, func
, file):
3929 """Overrriden from TypeHandler."""
3930 copy_args
= func
.MakeCmdArgString("_", False)
3931 file.Write(" void* Set(void* cmd%s) {\n" %
3932 func
.MakeTypedCmdArgString("_", True))
3933 self
.WriteImmediateCmdGetTotalSize(func
, file)
3934 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
3935 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
3936 "cmd, total_size);\n")
3940 def WriteImmediateFormatTest(self
, func
, file):
3941 """Overrriden from TypeHandler."""
3942 # TODO(gman): Remove this exception.
3943 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
3946 def WriteServiceUnitTest(self
, func
, file, *extras
):
3947 """Overrriden from TypeHandler."""
3948 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3950 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
3951 """Overrriden from TypeHandler."""
3952 file.Write("// TODO(gman): %s\n\n" % func
.name
)
3954 def WriteBucketServiceImplementation(self
, func
, file):
3955 """Overrriden from TypeHandler."""
3956 if not func
.name
== 'CompressedTexSubImage2DBucket':
3957 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, file)
3960 class BindHandler(TypeHandler
):
3961 """Handler for glBind___ type functions."""
3964 TypeHandler
.__init
__(self
)
3966 def WriteServiceUnitTest(self
, func
, file, *extras
):
3967 """Overrriden from TypeHandler."""
3969 if len(func
.GetOriginalArgs()) == 1:
3971 TEST_P(%(test_name)s, %(name)sValidArgs) {
3972 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3973 SpecializedSetup<cmds::%(name)s, 0>(true);
3976 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3977 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3980 if func
.GetInfo("gen_func"):
3982 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
3983 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
3984 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
3985 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
3986 SpecializedSetup<cmds::%(name)s, 0>(true);
3988 cmd.Init(kNewClientId);
3989 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3990 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3991 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
3994 self
.WriteValidUnitTest(func
, file, valid_test
, {
3995 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
3996 'gl_gen_func_name': func
.GetInfo("gen_func"),
4000 TEST_P(%(test_name)s, %(name)sValidArgs) {
4001 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4002 SpecializedSetup<cmds::%(name)s, 0>(true);
4005 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4006 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4009 if func
.GetInfo("gen_func"):
4011 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
4012 EXPECT_CALL(*gl_, %(gl_func_name)s(%(first_gl_arg)s, kNewServiceId));
4013 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
4014 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4015 SpecializedSetup<cmds::%(name)s, 0>(true);
4017 cmd.Init(%(first_arg)s, kNewClientId);
4018 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4019 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4020 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4023 self
.WriteValidUnitTest(func
, file, valid_test
, {
4024 'first_arg': func
.GetOriginalArgs()[0].GetValidArg(func
),
4025 'first_gl_arg': func
.GetOriginalArgs()[0].GetValidGLArg(func
),
4026 'resource_type': func
.GetOriginalArgs()[1].resource_type
,
4027 'gl_gen_func_name': func
.GetInfo("gen_func"),
4031 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4032 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4033 SpecializedSetup<cmds::%(name)s, 0>(false);
4036 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4039 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
4041 def WriteGLES2Implementation(self
, func
, file):
4042 """Writes the GLES2 Implemention."""
4044 impl_func
= func
.GetInfo('impl_func')
4045 impl_decl
= func
.GetInfo('impl_decl')
4047 if (func
.can_auto_generate
and
4048 (impl_func
== None or impl_func
== True) and
4049 (impl_decl
== None or impl_decl
== True)):
4051 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4052 (func
.return_type
, func
.original_name
,
4053 func
.MakeTypedOriginalArgString("")))
4054 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4055 func
.WriteDestinationInitalizationValidation(file)
4056 self
.WriteClientGLCallLog(func
, file)
4057 for arg
in func
.GetOriginalArgs():
4058 arg
.WriteClientSideValidationCode(file, func
)
4060 code
= """ if (Is%(type)sReservedId(%(id)s)) {
4061 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
4064 if (%(name)sHelper(%(arg_string)s)) {
4065 helper_->%(name)s(%(arg_string)s);
4072 if len(func
.GetOriginalArgs()) == 1:
4073 # Bind functions that have no target (like BindVertexArrayOES)
4074 name_arg
= func
.GetOriginalArgs()[0]
4076 # Bind functions that have both a target and a name (like BindTexture)
4077 name_arg
= func
.GetOriginalArgs()[1]
4081 'arg_string': func
.MakeOriginalArgString(""),
4082 'id': name_arg
.name
,
4083 'type': name_arg
.resource_type
,
4084 'lc_type': name_arg
.resource_type
.lower(),
4087 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4088 """Overrriden from TypeHandler."""
4089 client_test
= func
.GetInfo('client_test')
4090 if client_test
== False:
4093 TEST_F(GLES2ImplementationTest, %(name)s) {
4098 expected.cmd.Init(%(cmd_args)s);
4100 gl_->%(name)s(%(args)s);
4101 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4103 gl_->%(name)s(%(args)s);
4104 EXPECT_TRUE(NoCommandsWritten());
4108 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
4111 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
4116 'args': ", ".join(gl_arg_strings
),
4117 'cmd_args': ", ".join(cmd_arg_strings
),
4121 class GENnHandler(TypeHandler
):
4122 """Handler for glGen___ type functions."""
4125 TypeHandler
.__init
__(self
)
4127 def InitFunction(self
, func
):
4128 """Overrriden from TypeHandler."""
4131 def WriteGetDataSizeCode(self
, func
, file):
4132 """Overrriden from TypeHandler."""
4133 code
= """ uint32_t data_size;
4134 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4135 return error::kOutOfBounds;
4140 def WriteHandlerImplementation (self
, func
, file):
4141 """Overrriden from TypeHandler."""
4142 file.Write(" if (!%sHelper(n, %s)) {\n"
4143 " return error::kInvalidArguments;\n"
4145 (func
.name
, func
.GetLastOriginalArg().name
))
4147 def WriteImmediateHandlerImplementation(self
, func
, file):
4148 """Overrriden from TypeHandler."""
4149 file.Write(" if (!%sHelper(n, %s)) {\n"
4150 " return error::kInvalidArguments;\n"
4152 (func
.original_name
, func
.GetLastOriginalArg().name
))
4154 def WriteGLES2Implementation(self
, func
, file):
4155 """Overrriden from TypeHandler."""
4156 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
4157 for (GLsizei i = 0; i < n; ++i) {
4158 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4160 });""" % func
.GetOriginalArgs()[1].name
)
4162 'log_code': log_code
,
4163 'return_type': func
.return_type
,
4164 'name': func
.original_name
,
4165 'typed_args': func
.MakeTypedOriginalArgString(""),
4166 'args': func
.MakeOriginalArgString(""),
4167 'resource_types': func
.GetInfo('resource_types'),
4168 'count_name': func
.GetOriginalArgs()[0].name
,
4171 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4173 func
.WriteDestinationInitalizationValidation(file)
4174 self
.WriteClientGLCallLog(func
, file)
4175 for arg
in func
.GetOriginalArgs():
4176 arg
.WriteClientSideValidationCode(file, func
)
4177 not_shared
= func
.GetInfo('not_shared')
4180 """ IdAllocatorInterface* id_allocator = GetIdAllocator(id_namespaces::k%s);
4181 for (GLsizei ii = 0; ii < n; ++ii)
4182 %s[ii] = id_allocator->AllocateID();""" %
4183 (func
.GetInfo('resource_types'), func
.GetOriginalArgs()[1].name
))
4185 alloc_code
= (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
4186 MakeIds(this, 0, %(args)s);""" % args
)
4187 args
['alloc_code'] = alloc_code
4189 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
4191 %(name)sHelper(%(args)s);
4192 helper_->%(name)sImmediate(%(args)s);
4193 if (share_group_->bind_generates_resource())
4194 helper_->CommandBufferHelper::Flush();
4200 file.Write(code
% args
)
4202 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4203 """Overrriden from TypeHandler."""
4205 TEST_F(GLES2ImplementationTest, %(name)s) {
4206 GLuint ids[2] = { 0, };
4208 cmds::%(name)sImmediate gen;
4212 expected.gen.Init(arraysize(ids), &ids[0]);
4213 expected.data[0] = k%(types)sStartId;
4214 expected.data[1] = k%(types)sStartId + 1;
4215 gl_->%(name)s(arraysize(ids), &ids[0]);
4216 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4217 EXPECT_EQ(k%(types)sStartId, ids[0]);
4218 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
4223 'types': func
.GetInfo('resource_types'),
4226 def WriteServiceUnitTest(self
, func
, file, *extras
):
4227 """Overrriden from TypeHandler."""
4229 TEST_P(%(test_name)s, %(name)sValidArgs) {
4230 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4231 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4232 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
4233 SpecializedSetup<cmds::%(name)s, 0>(true);
4236 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4237 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4238 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4241 self
.WriteValidUnitTest(func
, file, valid_test
, {
4242 'resource_name': func
.GetInfo('resource_type'),
4245 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4246 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4247 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4248 SpecializedSetup<cmds::%(name)s, 0>(false);
4251 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
4254 self
.WriteValidUnitTest(func
, file, invalid_test
, {
4255 'resource_name': func
.GetInfo('resource_type').lower(),
4258 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4259 """Overrriden from TypeHandler."""
4261 TEST_P(%(test_name)s, %(name)sValidArgs) {
4262 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4263 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4264 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4265 GLuint temp = kNewClientId;
4266 SpecializedSetup<cmds::%(name)s, 0>(true);
4267 cmd->Init(1, &temp);
4268 EXPECT_EQ(error::kNoError,
4269 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4270 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4271 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4274 self
.WriteValidUnitTest(func
, file, valid_test
, {
4275 'resource_name': func
.GetInfo('resource_type'),
4278 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4279 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4280 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4281 SpecializedSetup<cmds::%(name)s, 0>(false);
4282 cmd->Init(1, &client_%(resource_name)s_id_);
4283 EXPECT_EQ(error::kInvalidArguments,
4284 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4287 self
.WriteValidUnitTest(func
, file, invalid_test
, {
4288 'resource_name': func
.GetInfo('resource_type').lower(),
4291 def WriteImmediateCmdComputeSize(self
, func
, file):
4292 """Overrriden from TypeHandler."""
4293 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
4295 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
4298 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
4299 file.Write(" return static_cast<uint32_t>(\n")
4300 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4304 def WriteImmediateCmdSetHeader(self
, func
, file):
4305 """Overrriden from TypeHandler."""
4306 file.Write(" void SetHeader(GLsizei n) {\n")
4307 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4311 def WriteImmediateCmdInit(self
, func
, file):
4312 """Overrriden from TypeHandler."""
4313 last_arg
= func
.GetLastOriginalArg()
4314 file.Write(" void Init(%s, %s _%s) {\n" %
4315 (func
.MakeTypedCmdArgString("_"),
4316 last_arg
.type, last_arg
.name
))
4317 file.Write(" SetHeader(_n);\n")
4318 args
= func
.GetCmdArgs()
4320 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4321 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4322 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
4326 def WriteImmediateCmdSet(self
, func
, file):
4327 """Overrriden from TypeHandler."""
4328 last_arg
= func
.GetLastOriginalArg()
4329 copy_args
= func
.MakeCmdArgString("_", False)
4330 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4331 (func
.MakeTypedCmdArgString("_", True),
4332 last_arg
.type, last_arg
.name
))
4333 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4334 (copy_args
, last_arg
.name
))
4335 file.Write(" const uint32_t size = ComputeSize(_n);\n")
4336 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4341 def WriteImmediateCmdHelper(self
, func
, file):
4342 """Overrriden from TypeHandler."""
4343 code
= """ void %(name)s(%(typed_args)s) {
4344 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
4345 gles2::cmds::%(name)s* c =
4346 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4355 "typed_args": func
.MakeTypedOriginalArgString(""),
4356 "args": func
.MakeOriginalArgString(""),
4359 def WriteImmediateFormatTest(self
, func
, file):
4360 """Overrriden from TypeHandler."""
4361 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4362 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4363 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4364 (func
.name
, func
.name
))
4365 file.Write(" void* next_cmd = cmd.Set(\n")
4366 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4367 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4369 file.Write(" cmd.header.command);\n")
4370 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4371 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4372 file.Write(" cmd.header.size * 4u);\n")
4373 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4374 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4375 file.Write(" next_cmd, sizeof(cmd) +\n")
4376 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4377 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4382 class CreateHandler(TypeHandler
):
4383 """Handler for glCreate___ type functions."""
4386 TypeHandler
.__init
__(self
)
4388 def InitFunction(self
, func
):
4389 """Overrriden from TypeHandler."""
4390 func
.AddCmdArg(Argument("client_id", 'uint32_t'))
4392 def WriteServiceUnitTest(self
, func
, file, *extras
):
4393 """Overrriden from TypeHandler."""
4395 TEST_P(%(test_name)s, %(name)sValidArgs) {
4396 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4397 .WillOnce(Return(kNewServiceId));
4398 SpecializedSetup<cmds::%(name)s, 0>(true);
4400 cmd.Init(%(args)s%(comma)skNewClientId);
4401 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4402 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4403 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4407 if len(func
.GetOriginalArgs()):
4409 self
.WriteValidUnitTest(func
, file, valid_test
, {
4411 'resource_type': func
.name
[6:],
4414 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4415 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4416 SpecializedSetup<cmds::%(name)s, 0>(false);
4418 cmd.Init(%(args)s%(comma)skNewClientId);
4419 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
4422 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
4426 def WriteHandlerImplementation (self
, func
, file):
4427 """Overrriden from TypeHandler."""
4428 file.Write(" uint32_t client_id = c.client_id;\n")
4429 file.Write(" if (!%sHelper(%s)) {\n" %
4430 (func
.name
, func
.MakeCmdArgString("")))
4431 file.Write(" return error::kInvalidArguments;\n")
4434 def WriteGLES2Implementation(self
, func
, file):
4435 """Overrriden from TypeHandler."""
4436 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4437 (func
.return_type
, func
.original_name
,
4438 func
.MakeTypedOriginalArgString("")))
4439 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4440 func
.WriteDestinationInitalizationValidation(file)
4441 self
.WriteClientGLCallLog(func
, file)
4442 for arg
in func
.GetOriginalArgs():
4443 arg
.WriteClientSideValidationCode(file, func
)
4444 file.Write(" GLuint client_id;\n")
4446 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
4447 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
4448 file.Write(" helper_->%s(%s);\n" %
4449 (func
.name
, func
.MakeCmdArgString("")))
4450 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
4451 file.Write(" CheckGLError();\n")
4452 file.Write(" return client_id;\n")
4457 class DeleteHandler(TypeHandler
):
4458 """Handler for glDelete___ single resource type functions."""
4461 TypeHandler
.__init
__(self
)
4463 def WriteServiceImplementation(self
, func
, file):
4464 """Overrriden from TypeHandler."""
4467 def WriteGLES2Implementation(self
, func
, file):
4468 """Overrriden from TypeHandler."""
4469 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4470 (func
.return_type
, func
.original_name
,
4471 func
.MakeTypedOriginalArgString("")))
4472 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4473 func
.WriteDestinationInitalizationValidation(file)
4474 self
.WriteClientGLCallLog(func
, file)
4475 for arg
in func
.GetOriginalArgs():
4476 arg
.WriteClientSideValidationCode(file, func
)
4478 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
4479 file.Write(" %sHelper(%s);\n" %
4480 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
4481 file.Write(" CheckGLError();\n")
4486 class DELnHandler(TypeHandler
):
4487 """Handler for glDelete___ type functions."""
4490 TypeHandler
.__init
__(self
)
4492 def WriteGetDataSizeCode(self
, func
, file):
4493 """Overrriden from TypeHandler."""
4494 code
= """ uint32_t data_size;
4495 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4496 return error::kOutOfBounds;
4501 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4502 """Overrriden from TypeHandler."""
4504 TEST_F(GLES2ImplementationTest, %(name)s) {
4505 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
4507 cmds::%(name)sImmediate del;
4511 expected.del.Init(arraysize(ids), &ids[0]);
4512 expected.data[0] = k%(types)sStartId;
4513 expected.data[1] = k%(types)sStartId + 1;
4514 gl_->%(name)s(arraysize(ids), &ids[0]);
4515 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4520 'types': func
.GetInfo('resource_types'),
4523 def WriteServiceUnitTest(self
, func
, file, *extras
):
4524 """Overrriden from TypeHandler."""
4526 TEST_P(%(test_name)s, %(name)sValidArgs) {
4529 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4531 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4532 SpecializedSetup<cmds::%(name)s, 0>(true);
4535 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4536 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4538 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4541 self
.WriteValidUnitTest(func
, file, valid_test
, {
4542 'resource_name': func
.GetInfo('resource_type').lower(),
4543 'upper_resource_name': func
.GetInfo('resource_type'),
4546 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4547 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
4548 SpecializedSetup<cmds::%(name)s, 0>(false);
4551 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4554 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
4556 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4557 """Overrriden from TypeHandler."""
4559 TEST_P(%(test_name)s, %(name)sValidArgs) {
4562 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
4564 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4565 SpecializedSetup<cmds::%(name)s, 0>(true);
4566 cmd.Init(1, &client_%(resource_name)s_id_);
4567 EXPECT_EQ(error::kNoError,
4568 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
4569 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4571 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
4574 self
.WriteValidUnitTest(func
, file, valid_test
, {
4575 'resource_name': func
.GetInfo('resource_type').lower(),
4576 'upper_resource_name': func
.GetInfo('resource_type'),
4579 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4580 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
4581 SpecializedSetup<cmds::%(name)s, 0>(false);
4582 GLuint temp = kInvalidClientId;
4584 EXPECT_EQ(error::kNoError,
4585 ExecuteImmediateCmd(cmd, sizeof(temp)));
4588 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
4590 def WriteHandlerImplementation (self
, func
, file):
4591 """Overrriden from TypeHandler."""
4592 file.Write(" %sHelper(n, %s);\n" %
4593 (func
.name
, func
.GetLastOriginalArg().name
))
4595 def WriteImmediateHandlerImplementation (self
, func
, file):
4596 """Overrriden from TypeHandler."""
4597 file.Write(" %sHelper(n, %s);\n" %
4598 (func
.original_name
, func
.GetLastOriginalArg().name
))
4600 def WriteGLES2Implementation(self
, func
, file):
4601 """Overrriden from TypeHandler."""
4602 impl_decl
= func
.GetInfo('impl_decl')
4603 if impl_decl
== None or impl_decl
== True:
4605 'return_type': func
.return_type
,
4606 'name': func
.original_name
,
4607 'typed_args': func
.MakeTypedOriginalArgString(""),
4608 'args': func
.MakeOriginalArgString(""),
4609 'resource_type': func
.GetInfo('resource_type').lower(),
4610 'count_name': func
.GetOriginalArgs()[0].name
,
4613 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4615 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4616 func
.WriteDestinationInitalizationValidation(file)
4617 self
.WriteClientGLCallLog(func
, file)
4618 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
4619 for (GLsizei i = 0; i < n; ++i) {
4620 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4623 """ % func
.GetOriginalArgs()[1].name
)
4624 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
4625 for (GLsizei i = 0; i < n; ++i) {
4629 """ % func
.GetOriginalArgs()[1].name
)
4630 for arg
in func
.GetOriginalArgs():
4631 arg
.WriteClientSideValidationCode(file, func
)
4632 code
= """ %(name)sHelper(%(args)s);
4637 file.Write(code
% args
)
4639 def WriteImmediateCmdComputeSize(self
, func
, file):
4640 """Overrriden from TypeHandler."""
4641 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
4643 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
4646 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
4647 file.Write(" return static_cast<uint32_t>(\n")
4648 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4652 def WriteImmediateCmdSetHeader(self
, func
, file):
4653 """Overrriden from TypeHandler."""
4654 file.Write(" void SetHeader(GLsizei n) {\n")
4655 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4659 def WriteImmediateCmdInit(self
, func
, file):
4660 """Overrriden from TypeHandler."""
4661 last_arg
= func
.GetLastOriginalArg()
4662 file.Write(" void Init(%s, %s _%s) {\n" %
4663 (func
.MakeTypedCmdArgString("_"),
4664 last_arg
.type, last_arg
.name
))
4665 file.Write(" SetHeader(_n);\n")
4666 args
= func
.GetCmdArgs()
4668 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4669 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4670 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
4674 def WriteImmediateCmdSet(self
, func
, file):
4675 """Overrriden from TypeHandler."""
4676 last_arg
= func
.GetLastOriginalArg()
4677 copy_args
= func
.MakeCmdArgString("_", False)
4678 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4679 (func
.MakeTypedCmdArgString("_", True),
4680 last_arg
.type, last_arg
.name
))
4681 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4682 (copy_args
, last_arg
.name
))
4683 file.Write(" const uint32_t size = ComputeSize(_n);\n")
4684 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4689 def WriteImmediateCmdHelper(self
, func
, file):
4690 """Overrriden from TypeHandler."""
4691 code
= """ void %(name)s(%(typed_args)s) {
4692 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
4693 gles2::cmds::%(name)s* c =
4694 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4703 "typed_args": func
.MakeTypedOriginalArgString(""),
4704 "args": func
.MakeOriginalArgString(""),
4707 def WriteImmediateFormatTest(self
, func
, file):
4708 """Overrriden from TypeHandler."""
4709 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4710 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4711 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4712 (func
.name
, func
.name
))
4713 file.Write(" void* next_cmd = cmd.Set(\n")
4714 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4715 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4717 file.Write(" cmd.header.command);\n")
4718 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4719 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4720 file.Write(" cmd.header.size * 4u);\n")
4721 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4722 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4723 file.Write(" next_cmd, sizeof(cmd) +\n")
4724 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4725 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4730 class GETnHandler(TypeHandler
):
4731 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
4734 TypeHandler
.__init
__(self
)
4736 def NeedsDataTransferFunction(self
, func
):
4737 """Overriden from TypeHandler."""
4740 def WriteServiceImplementation(self
, func
, file):
4741 """Overrriden from TypeHandler."""
4743 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
4745 " uint32_t immediate_data_size, const gles2::cmds::%s& c) {\n" %
4747 last_arg
= func
.GetLastOriginalArg()
4749 all_but_last_args
= func
.GetOriginalArgs()[:-1]
4750 for arg
in all_but_last_args
:
4751 arg
.WriteGetCode(file)
4753 code
= """ typedef cmds::%(func_name)s::Result Result;
4754 GLsizei num_values = 0;
4755 GetNumValuesReturnedForGLGet(pname, &num_values);
4756 Result* result = GetSharedMemoryAs<Result*>(
4757 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
4758 %(last_arg_type)s params = result ? result->GetData() : NULL;
4761 'last_arg_type': last_arg
.type,
4762 'func_name': func
.name
,
4764 func
.WriteHandlerValidation(file)
4765 code
= """ // Check that the client initialized the result.
4766 if (result->size != 0) {
4767 return error::kInvalidArguments;
4770 shadowed
= func
.GetInfo('shadowed')
4772 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
4774 func
.WriteHandlerImplementation(file)
4776 code
= """ result->SetNumResults(num_values);
4777 return error::kNoError;
4781 code
= """ GLenum error = glGetError();
4782 if (error == GL_NO_ERROR) {
4783 result->SetNumResults(num_values);
4785 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
4787 return error::kNoError;
4791 file.Write(code
% {'func_name': func
.name
})
4793 def WriteGLES2Implementation(self
, func
, file):
4794 """Overrriden from TypeHandler."""
4795 impl_decl
= func
.GetInfo('impl_decl')
4796 if impl_decl
== None or impl_decl
== True:
4797 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4798 (func
.return_type
, func
.original_name
,
4799 func
.MakeTypedOriginalArgString("")))
4800 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4801 func
.WriteDestinationInitalizationValidation(file)
4802 self
.WriteClientGLCallLog(func
, file)
4803 for arg
in func
.GetOriginalArgs():
4804 arg
.WriteClientSideValidationCode(file, func
)
4805 all_but_last_args
= func
.GetOriginalArgs()[:-1]
4807 ", ".join(["%s" % arg
.name
for arg
in all_but_last_args
]))
4811 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()]))
4812 self
.WriteTraceEvent(func
, file)
4813 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
4816 typedef cmds::%(func_name)s::Result Result;
4817 Result* result = GetResultAs<Result*>();
4821 result->SetNumResults(0);
4822 helper_->%(func_name)s(%(arg_string)s,
4823 GetResultShmId(), GetResultShmOffset());
4825 result->CopyResult(params);
4826 GPU_CLIENT_LOG_CODE_BLOCK({
4827 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
4828 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
4835 'func_name': func
.name
,
4836 'arg_string': arg_string
,
4837 'all_arg_string': all_arg_string
,
4840 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4841 """Writes the GLES2 Implemention unit test."""
4843 TEST_F(GLES2ImplementationTest, %(name)s) {
4847 typedef cmds::%(name)s::Result Result;
4848 Result::Type result = 0;
4850 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
4851 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
4852 EXPECT_CALL(*command_buffer(), OnFlush())
4853 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
4854 .RetiresOnSaturation();
4855 gl_->%(name)s(%(args)s, &result);
4856 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4857 EXPECT_EQ(static_cast<Result::Type>(1), result);
4860 first_cmd_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func
)
4861 if not first_cmd_arg
:
4864 first_gl_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideArg(func
)
4865 cmd_arg_strings
= [first_cmd_arg
]
4866 for arg
in func
.GetCmdArgs()[1:-2]:
4867 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
4868 gl_arg_strings
= [first_gl_arg
]
4869 for arg
in func
.GetOriginalArgs()[1:-1]:
4870 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
4874 'args': ", ".join(gl_arg_strings
),
4875 'cmd_args': ", ".join(cmd_arg_strings
),
4878 def WriteServiceUnitTest(self
, func
, file, *extras
):
4879 """Overrriden from TypeHandler."""
4881 TEST_P(%(test_name)s, %(name)sValidArgs) {
4882 EXPECT_CALL(*gl_, GetError())
4883 .WillOnce(Return(GL_NO_ERROR))
4884 .WillOnce(Return(GL_NO_ERROR))
4885 .RetiresOnSaturation();
4886 SpecializedSetup<cmds::%(name)s, 0>(true);
4887 typedef cmds::%(name)s::Result Result;
4888 Result* result = static_cast<Result*>(shared_memory_address_);
4889 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
4893 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4894 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
4896 result->GetNumResults());
4897 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4902 for arg
in func
.GetOriginalArgs()[:-1]:
4903 arg_value
= arg
.GetValidGLArg(func
)
4904 gl_arg_strings
.append(arg_value
)
4905 if arg
.name
== 'pname':
4906 valid_pname
= arg_value
4907 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
4908 gl_arg_strings
.append("_")
4910 gl_arg_strings
.append("result->GetData()")
4912 self
.WriteValidUnitTest(func
, file, valid_test
, {
4913 'local_gl_args': ", ".join(gl_arg_strings
),
4914 'valid_pname': valid_pname
,
4918 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4919 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4920 SpecializedSetup<cmds::%(name)s, 0>(false);
4921 cmds::%(name)s::Result* result =
4922 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
4926 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
4927 EXPECT_EQ(0u, result->size);%(gl_error_test)s
4930 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
4932 class ArrayArgTypeHandler(TypeHandler
):
4933 """Base class for type handlers that handle args that are arrays"""
4936 TypeHandler
.__init
__(self
)
4938 def GetArrayType(self
, func
):
4939 """Returns the type of the element in the element array being PUT to."""
4940 for arg
in func
.GetOriginalArgs():
4942 element_type
= arg
.GetPointedType()
4945 # Special case: array type handler is used for a function that is forwarded
4946 # to the actual array type implementation
4947 element_type
= func
.GetOriginalArgs()[-1].type
4948 assert all(arg
.type == element_type \
4949 for arg
in func
.GetOriginalArgs()[-self
.GetArrayCount(func
):])
4952 def GetArrayCount(self
, func
):
4953 """Returns the count of the elements in the array being PUT to."""
4954 return func
.GetInfo('count')
4956 class PUTHandler(ArrayArgTypeHandler
):
4957 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
4960 ArrayArgTypeHandler
.__init
__(self
)
4962 def WriteServiceUnitTest(self
, func
, file, *extras
):
4963 """Writes the service unit test for a command."""
4964 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
4965 if func
.GetInfo("first_element_only"):
4967 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()
4969 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
4970 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
4971 ", ".join(gl_arg_strings
))
4973 TEST_P(%(test_name)s, %(name)sValidArgs) {
4974 SpecializedSetup<cmds::%(name)s, 0>(true);
4977 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4979 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4980 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4984 'data_type': self
.GetArrayType(func
),
4985 'data_value': func
.GetInfo('data_value') or '0',
4986 'expected_call': expected_call
,
4988 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
4991 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4992 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4993 SpecializedSetup<cmds::%(name)s, 0>(false);
4996 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
4997 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5000 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
5002 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5003 """Writes the service unit test for a command."""
5005 TEST_P(%(test_name)s, %(name)sValidArgs) {
5006 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5007 SpecializedSetup<cmds::%(name)s, 0>(true);
5008 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
5009 cmd.Init(%(gl_args)s, &temp[0]);
5012 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
5013 %(data_type)s*>(ImmediateDataAddress(&cmd))));
5014 EXPECT_EQ(error::kNoError,
5015 ExecuteImmediateCmd(cmd, sizeof(temp)));
5016 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5020 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
5022 gl_any_strings
= ["_"] * len(gl_arg_strings
)
5025 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
5026 'data_type': self
.GetArrayType(func
),
5027 'data_count': self
.GetArrayCount(func
),
5028 'data_value': func
.GetInfo('data_value') or '0',
5029 'gl_args': ", ".join(gl_arg_strings
),
5030 'gl_any_args': ", ".join(gl_any_strings
),
5032 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
5035 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5036 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5037 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5038 SpecializedSetup<cmds::%(name)s, 0>(false);
5039 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
5040 cmd.Init(%(all_but_last_args)s, &temp[0]);
5041 EXPECT_EQ(error::%(parse_result)s,
5042 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5045 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
5047 def WriteGetDataSizeCode(self
, func
, file):
5048 """Overrriden from TypeHandler."""
5049 code
= """ uint32_t data_size;
5050 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
5051 return error::kOutOfBounds;
5054 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
5055 if func
.IsImmediate():
5056 file.Write(" if (data_size > immediate_data_size) {\n")
5057 file.Write(" return error::kOutOfBounds;\n")
5060 def WriteGLES2Implementation(self
, func
, file):
5061 """Overrriden from TypeHandler."""
5062 impl_func
= func
.GetInfo('impl_func')
5063 if (impl_func
!= None and impl_func
!= True):
5065 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5066 (func
.return_type
, func
.original_name
,
5067 func
.MakeTypedOriginalArgString("")))
5068 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5069 func
.WriteDestinationInitalizationValidation(file)
5070 self
.WriteClientGLCallLog(func
, file)
5071 last_arg_name
= func
.GetLastOriginalArg().name
5072 values_str
= ' << ", " << '.join(
5073 ["%s[%d]" % (last_arg_name
, ndx
) \
5074 for ndx
in range(0, self
.GetArrayCount(func
))])
5075 file.Write(' GPU_CLIENT_LOG("values: " << %s);\n' % values_str
)
5076 for arg
in func
.GetOriginalArgs():
5077 arg
.WriteClientSideValidationCode(file, func
)
5078 file.Write(" helper_->%sImmediate(%s);\n" %
5079 (func
.name
, func
.MakeOriginalArgString("")))
5080 file.Write(" CheckGLError();\n")
5084 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5085 """Writes the GLES2 Implemention unit test."""
5086 client_test
= func
.GetInfo('client_test')
5087 if (client_test
!= None and client_test
!= True):
5090 TEST_F(GLES2ImplementationTest, %(name)s) {
5091 %(type)s data[%(count)d] = {0};
5093 cmds::%(name)sImmediate cmd;
5094 %(type)s data[%(count)d];
5097 for (int jj = 0; jj < %(count)d; ++jj) {
5098 data[jj] = static_cast<%(type)s>(jj);
5101 expected.cmd.Init(%(cmd_args)s, &data[0]);
5102 gl_->%(name)s(%(args)s, &data[0]);
5103 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5107 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
5110 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
5115 'type': self
.GetArrayType(func
),
5116 'count': self
.GetArrayCount(func
),
5117 'args': ", ".join(gl_arg_strings
),
5118 'cmd_args': ", ".join(cmd_arg_strings
),
5121 def WriteImmediateCmdComputeSize(self
, func
, file):
5122 """Overrriden from TypeHandler."""
5123 file.Write(" static uint32_t ComputeDataSize() {\n")
5124 file.Write(" return static_cast<uint32_t>(\n")
5125 file.Write(" sizeof(%s) * %d); // NOLINT\n" %
5126 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
5129 file.Write(" static uint32_t ComputeSize() {\n")
5130 file.Write(" return static_cast<uint32_t>(\n")
5132 " sizeof(ValueType) + ComputeDataSize()); // NOLINT\n")
5136 def WriteImmediateCmdSetHeader(self
, func
, file):
5137 """Overrriden from TypeHandler."""
5138 file.Write(" void SetHeader() {\n")
5140 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
5144 def WriteImmediateCmdInit(self
, func
, file):
5145 """Overrriden from TypeHandler."""
5146 last_arg
= func
.GetLastOriginalArg()
5147 file.Write(" void Init(%s, %s _%s) {\n" %
5148 (func
.MakeTypedCmdArgString("_"),
5149 last_arg
.type, last_arg
.name
))
5150 file.Write(" SetHeader();\n")
5151 args
= func
.GetCmdArgs()
5153 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5154 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5155 file.Write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
5159 def WriteImmediateCmdSet(self
, func
, file):
5160 """Overrriden from TypeHandler."""
5161 last_arg
= func
.GetLastOriginalArg()
5162 copy_args
= func
.MakeCmdArgString("_", False)
5163 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5164 (func
.MakeTypedCmdArgString("_", True),
5165 last_arg
.type, last_arg
.name
))
5166 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5167 (copy_args
, last_arg
.name
))
5168 file.Write(" const uint32_t size = ComputeSize();\n")
5169 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5174 def WriteImmediateCmdHelper(self
, func
, file):
5175 """Overrriden from TypeHandler."""
5176 code
= """ void %(name)s(%(typed_args)s) {
5177 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
5178 gles2::cmds::%(name)s* c =
5179 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5188 "typed_args": func
.MakeTypedOriginalArgString(""),
5189 "args": func
.MakeOriginalArgString(""),
5192 def WriteImmediateFormatTest(self
, func
, file):
5193 """Overrriden from TypeHandler."""
5194 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5195 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5196 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
5197 for v
in range(0, self
.GetArrayCount(func
)):
5198 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5199 (self
.GetArrayType(func
), v
))
5201 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5202 (func
.name
, func
.name
))
5203 file.Write(" void* next_cmd = cmd.Set(\n")
5205 args
= func
.GetCmdArgs()
5206 for value
, arg
in enumerate(args
):
5207 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
5208 file.Write(",\n data);\n")
5209 args
= func
.GetCmdArgs()
5210 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
5212 file.Write(" cmd.header.command);\n")
5213 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5214 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
5215 file.Write(" cmd.header.size * 4u);\n")
5216 for value
, arg
in enumerate(args
):
5217 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5218 (arg
.type, value
+ 11, arg
.name
))
5219 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5220 file.Write(" next_cmd, sizeof(cmd) +\n")
5221 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5222 file.Write(" // TODO(gman): Check that data was inserted;\n")
5227 class PUTnHandler(ArrayArgTypeHandler
):
5228 """Handler for PUTn 'glUniform__v' type functions."""
5231 ArrayArgTypeHandler
.__init
__(self
)
5233 def WriteServiceUnitTest(self
, func
, file, *extras
):
5234 """Overridden from TypeHandler."""
5235 ArrayArgTypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
5238 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
5239 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5240 SpecializedSetup<cmds::%(name)s, 0>(true);
5243 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5244 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5249 for count
, arg
in enumerate(func
.GetOriginalArgs()):
5250 # hardcoded to match unit tests.
5252 # the location of the second element of the 2nd uniform.
5253 # defined in GLES2DecoderBase::SetupShaderForUniform
5254 gl_arg_strings
.append("3")
5255 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
5257 # the number of elements that gl will be called with.
5258 gl_arg_strings
.append("3")
5259 # the number of elements requested in the command.
5260 arg_strings
.append("5")
5262 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
5263 if not arg
.IsConstant():
5264 arg_strings
.append(arg
.GetValidArg(func
))
5266 'gl_args': ", ".join(gl_arg_strings
),
5267 'args': ", ".join(arg_strings
),
5269 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
5271 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5272 """Overridden from TypeHandler."""
5274 TEST_P(%(test_name)s, %(name)sValidArgs) {
5275 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5278 %(gl_func_name)s(%(gl_args)s,
5279 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
5280 SpecializedSetup<cmds::%(name)s, 0>(true);
5281 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5282 cmd.Init(%(args)s, &temp[0]);
5283 EXPECT_EQ(error::kNoError,
5284 ExecuteImmediateCmd(cmd, sizeof(temp)));
5285 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5291 for arg
in func
.GetOriginalArgs()[0:-1]:
5292 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
5293 gl_any_strings
.append("_")
5294 if not arg
.IsConstant():
5295 arg_strings
.append(arg
.GetValidArg(func
))
5297 'data_type': self
.GetArrayType(func
),
5298 'data_count': self
.GetArrayCount(func
),
5299 'args': ", ".join(arg_strings
),
5300 'gl_args': ", ".join(gl_arg_strings
),
5301 'gl_any_args': ", ".join(gl_any_strings
),
5303 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
5306 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5307 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5308 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5309 SpecializedSetup<cmds::%(name)s, 0>(false);
5310 %(data_type)s temp[%(data_count)s * 2] = { 0, };
5311 cmd.Init(%(all_but_last_args)s, &temp[0]);
5312 EXPECT_EQ(error::%(parse_result)s,
5313 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
5316 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
5318 def WriteGetDataSizeCode(self
, func
, file):
5319 """Overrriden from TypeHandler."""
5320 code
= """ uint32_t data_size;
5321 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
5322 return error::kOutOfBounds;
5325 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
5326 if func
.IsImmediate():
5327 file.Write(" if (data_size > immediate_data_size) {\n")
5328 file.Write(" return error::kOutOfBounds;\n")
5331 def WriteGLES2Implementation(self
, func
, file):
5332 """Overrriden from TypeHandler."""
5333 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5334 (func
.return_type
, func
.original_name
,
5335 func
.MakeTypedOriginalArgString("")))
5336 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5337 func
.WriteDestinationInitalizationValidation(file)
5338 self
.WriteClientGLCallLog(func
, file)
5339 last_arg_name
= func
.GetLastOriginalArg().name
5340 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5341 for (GLsizei i = 0; i < count; ++i) {
5343 values_str
= ' << ", " << '.join(
5344 ["%s[%d + i * %d]" % (
5345 last_arg_name
, ndx
, self
.GetArrayCount(func
)) for ndx
in range(
5346 0, self
.GetArrayCount(func
))])
5347 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
5348 file.Write(" }\n });\n")
5349 for arg
in func
.GetOriginalArgs():
5350 arg
.WriteClientSideValidationCode(file, func
)
5351 file.Write(" helper_->%sImmediate(%s);\n" %
5352 (func
.name
, func
.MakeInitString("")))
5353 file.Write(" CheckGLError();\n")
5357 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5358 """Writes the GLES2 Implemention unit test."""
5360 TEST_F(GLES2ImplementationTest, %(name)s) {
5361 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5363 cmds::%(name)sImmediate cmd;
5364 %(type)s data[%(count_param)d][%(count)d];
5368 for (int ii = 0; ii < %(count_param)d; ++ii) {
5369 for (int jj = 0; jj < %(count)d; ++jj) {
5370 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5373 expected.cmd.Init(%(cmd_args)s, &data[0][0]);
5374 gl_->%(name)s(%(args)s, &data[0][0]);
5375 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5379 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
5383 for arg
in func
.GetOriginalArgs()[0:-1]:
5384 valid_value
= arg
.GetValidClientSideArg(func
)
5385 gl_arg_strings
.append(valid_value
)
5386 if arg
.name
== "count":
5387 count_param
= int(valid_value
)
5390 'type': self
.GetArrayType(func
),
5391 'count': self
.GetArrayCount(func
),
5392 'args': ", ".join(gl_arg_strings
),
5393 'cmd_args': ", ".join(cmd_arg_strings
),
5394 'count_param': count_param
,
5397 # Test constants for invalid values, as they are not tested by the
5400 arg
for arg
in func
.GetOriginalArgs()[0:-1] if arg
.IsConstant()
5406 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
5407 %(type)s data[%(count_param)d][%(count)d] = {{0}};
5408 for (int ii = 0; ii < %(count_param)d; ++ii) {
5409 for (int jj = 0; jj < %(count)d; ++jj) {
5410 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
5413 gl_->%(name)s(%(args)s, &data[0][0]);
5414 EXPECT_TRUE(NoCommandsWritten());
5415 EXPECT_EQ(%(gl_error)s, CheckError());
5418 for invalid_arg
in constants
:
5420 invalid
= invalid_arg
.GetInvalidArg(func
)
5421 for arg
in func
.GetOriginalArgs()[0:-1]:
5422 if arg
is invalid_arg
:
5423 gl_arg_strings
.append(invalid
[0])
5425 valid_value
= arg
.GetValidClientSideArg(func
)
5426 gl_arg_strings
.append(valid_value
)
5427 if arg
.name
== "count":
5428 count_param
= int(valid_value
)
5432 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
5433 'type': self
.GetArrayType(func
),
5434 'count': self
.GetArrayCount(func
),
5435 'args': ", ".join(gl_arg_strings
),
5436 'gl_error': invalid
[2],
5437 'count_param': count_param
,
5441 def WriteImmediateCmdComputeSize(self
, func
, file):
5442 """Overrriden from TypeHandler."""
5443 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
5444 file.Write(" return static_cast<uint32_t>(\n")
5445 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
5446 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
5449 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
5450 file.Write(" return static_cast<uint32_t>(\n")
5452 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
5456 def WriteImmediateCmdSetHeader(self
, func
, file):
5457 """Overrriden from TypeHandler."""
5458 file.Write(" void SetHeader(GLsizei count) {\n")
5460 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
5464 def WriteImmediateCmdInit(self
, func
, file):
5465 """Overrriden from TypeHandler."""
5466 last_arg
= func
.GetLastOriginalArg()
5467 file.Write(" void Init(%s, %s _%s) {\n" %
5468 (func
.MakeTypedCmdArgString("_"),
5469 last_arg
.type, last_arg
.name
))
5470 file.Write(" SetHeader(_count);\n")
5471 args
= func
.GetCmdArgs()
5473 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5474 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5475 file.Write(" _%s, ComputeDataSize(_count));\n" % last_arg
.name
)
5479 def WriteImmediateCmdSet(self
, func
, file):
5480 """Overrriden from TypeHandler."""
5481 last_arg
= func
.GetLastOriginalArg()
5482 copy_args
= func
.MakeCmdArgString("_", False)
5483 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5484 (func
.MakeTypedCmdArgString("_", True),
5485 last_arg
.type, last_arg
.name
))
5486 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5487 (copy_args
, last_arg
.name
))
5488 file.Write(" const uint32_t size = ComputeSize(_count);\n")
5489 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5494 def WriteImmediateCmdHelper(self
, func
, file):
5495 """Overrriden from TypeHandler."""
5496 code
= """ void %(name)s(%(typed_args)s) {
5497 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
5498 gles2::cmds::%(name)s* c =
5499 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5508 "typed_args": func
.MakeTypedInitString(""),
5509 "args": func
.MakeInitString("")
5512 def WriteImmediateFormatTest(self
, func
, file):
5513 """Overrriden from TypeHandler."""
5514 args
= func
.GetCmdArgs()
5517 if arg
.name
== "count":
5518 count_param
= int(arg
.GetValidClientSideCmdArg(func
))
5519 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5520 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5521 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
5522 for v
in range(0, self
.GetArrayCount(func
) * count_param
):
5523 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5524 (self
.GetArrayType(func
), v
))
5526 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5527 (func
.name
, func
.name
))
5528 file.Write(" const GLsizei kNumElements = %d;\n" % count_param
)
5529 file.Write(" const size_t kExpectedCmdSize =\n")
5530 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
5531 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
5532 file.Write(" void* next_cmd = cmd.Set(\n")
5534 for value
, arg
in enumerate(args
):
5535 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
5536 file.Write(",\n data);\n")
5537 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5539 file.Write(" cmd.header.command);\n")
5540 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
5541 for value
, arg
in enumerate(args
):
5542 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
5543 (arg
.type, value
+ 1, arg
.name
))
5544 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5545 file.Write(" next_cmd, sizeof(cmd) +\n")
5546 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
5547 file.Write(" // TODO(gman): Check that data was inserted;\n")
5552 class PUTXnHandler(ArrayArgTypeHandler
):
5553 """Handler for glUniform?f functions."""
5555 ArrayArgTypeHandler
.__init
__(self
)
5557 def WriteHandlerImplementation(self
, func
, file):
5558 """Overrriden from TypeHandler."""
5559 code
= """ %(type)s temp[%(count)s] = { %(values)s};
5560 Do%(name)sv(%(location)s, 1, &temp[0]);
5563 args
= func
.GetOriginalArgs()
5564 count
= int(self
.GetArrayCount(func
))
5565 num_args
= len(args
)
5566 for ii
in range(count
):
5567 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
5571 'count': self
.GetArrayCount(func
),
5572 'type': self
.GetArrayType(func
),
5573 'location': args
[0].name
,
5574 'args': func
.MakeOriginalArgString(""),
5578 def WriteServiceUnitTest(self
, func
, file, *extras
):
5579 """Overrriden from TypeHandler."""
5581 TEST_P(%(test_name)s, %(name)sValidArgs) {
5582 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
5583 SpecializedSetup<cmds::%(name)s, 0>(true);
5586 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5587 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5590 args
= func
.GetOriginalArgs()
5591 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
)
5592 self
.WriteValidUnitTest(func
, file, valid_test
, {
5594 'count': self
.GetArrayCount(func
),
5595 'local_args': local_args
,
5599 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5600 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
5601 SpecializedSetup<cmds::%(name)s, 0>(false);
5604 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5607 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5608 'name': func
.GetInfo('name'),
5609 'count': self
.GetArrayCount(func
),
5613 class GLcharHandler(CustomHandler
):
5614 """Handler for functions that pass a single string ."""
5617 CustomHandler
.__init
__(self
)
5619 def WriteImmediateCmdComputeSize(self
, func
, file):
5620 """Overrriden from TypeHandler."""
5621 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
5622 file.Write(" return static_cast<uint32_t>(\n")
5623 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
5626 def WriteImmediateCmdSetHeader(self
, func
, file):
5627 """Overrriden from TypeHandler."""
5629 void SetHeader(uint32_t data_size) {
5630 header.SetCmdBySize<ValueType>(data_size);
5635 def WriteImmediateCmdInit(self
, func
, file):
5636 """Overrriden from TypeHandler."""
5637 last_arg
= func
.GetLastOriginalArg()
5638 args
= func
.GetCmdArgs()
5641 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
5643 void Init(%(typed_args)s, uint32_t _data_size) {
5644 SetHeader(_data_size);
5646 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
5651 "typed_args": func
.MakeTypedArgString("_"),
5652 "set_code": "\n".join(set_code
),
5653 "last_arg": last_arg
.name
5656 def WriteImmediateCmdSet(self
, func
, file):
5657 """Overrriden from TypeHandler."""
5658 last_arg
= func
.GetLastOriginalArg()
5659 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
5660 func
.MakeTypedCmdArgString("_", True))
5661 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
5662 func
.MakeCmdArgString("_"))
5663 file.Write(" return NextImmediateCmdAddress<ValueType>("
5664 "cmd, _data_size);\n")
5668 def WriteImmediateCmdHelper(self
, func
, file):
5669 """Overrriden from TypeHandler."""
5670 code
= """ void %(name)s(%(typed_args)s) {
5671 const uint32_t data_size = strlen(name);
5672 gles2::cmds::%(name)s* c =
5673 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
5675 c->Init(%(args)s, data_size);
5682 "typed_args": func
.MakeTypedOriginalArgString(""),
5683 "args": func
.MakeOriginalArgString(""),
5687 def WriteImmediateFormatTest(self
, func
, file):
5688 """Overrriden from TypeHandler."""
5691 all_but_last_arg
= func
.GetCmdArgs()[:-1]
5692 for value
, arg
in enumerate(all_but_last_arg
):
5693 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
5694 for value
, arg
in enumerate(all_but_last_arg
):
5695 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
5696 (arg
.type, value
+ 11, arg
.name
))
5698 TEST_F(GLES2FormatTest, %(func_name)s) {
5699 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
5700 static const char* const test_str = \"test string\";
5701 void* next_cmd = cmd.Set(
5706 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
5707 cmd.header.command);
5708 EXPECT_EQ(sizeof(cmd) +
5709 RoundSizeToMultipleOfEntries(strlen(test_str)),
5710 cmd.header.size * 4u);
5711 EXPECT_EQ(static_cast<char*>(next_cmd),
5712 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
5713 RoundSizeToMultipleOfEntries(strlen(test_str)));
5715 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
5716 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
5719 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
5720 sizeof(cmd) + strlen(test_str));
5725 'func_name': func
.name
,
5726 'init_code': "\n".join(init_code
),
5727 'check_code': "\n".join(check_code
),
5731 class GLcharNHandler(CustomHandler
):
5732 """Handler for functions that pass a single string with an optional len."""
5735 CustomHandler
.__init
__(self
)
5737 def InitFunction(self
, func
):
5738 """Overrriden from TypeHandler."""
5740 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5742 def NeedsDataTransferFunction(self
, func
):
5743 """Overriden from TypeHandler."""
5746 def AddBucketFunction(self
, generator
, func
):
5747 """Overrriden from TypeHandler."""
5750 def WriteServiceImplementation(self
, func
, file):
5751 """Overrriden from TypeHandler."""
5752 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
5753 uint32_t immediate_data_size, const gles2::cmds::%(name)s& c) {
5754 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
5755 Bucket* bucket = GetBucket(bucket_id);
5756 if (!bucket || bucket->size() == 0) {
5757 return error::kInvalidArguments;
5760 if (!bucket->GetAsString(&str)) {
5761 return error::kInvalidArguments;
5763 %(gl_func_name)s(0, str.c_str());
5764 return error::kNoError;
5769 'gl_func_name': func
.GetGLFunctionName(),
5770 'bucket_id': func
.cmd_args
[0].name
,
5774 class IsHandler(TypeHandler
):
5775 """Handler for glIs____ type and glGetError functions."""
5778 TypeHandler
.__init
__(self
)
5780 def InitFunction(self
, func
):
5781 """Overrriden from TypeHandler."""
5782 func
.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
5783 func
.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
5784 if func
.GetInfo('result') == None:
5785 func
.AddInfo('result', ['uint32_t'])
5787 def WriteServiceUnitTest(self
, func
, file, *extras
):
5788 """Overrriden from TypeHandler."""
5790 TEST_P(%(test_name)s, %(name)sValidArgs) {
5791 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5792 SpecializedSetup<cmds::%(name)s, 0>(true);
5794 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5795 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5796 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5800 if len(func
.GetOriginalArgs()):
5802 self
.WriteValidUnitTest(func
, file, valid_test
, {
5807 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5808 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5809 SpecializedSetup<cmds::%(name)s, 0>(false);
5811 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
5812 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5815 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5820 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
5821 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5822 SpecializedSetup<cmds::%(name)s, 0>(false);
5824 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
5825 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5826 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
5827 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
5830 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5834 def WriteServiceImplementation(self
, func
, file):
5835 """Overrriden from TypeHandler."""
5837 "error::Error GLES2DecoderImpl::Handle%s(\n" % func
.name
)
5839 " uint32_t immediate_data_size, const gles2::cmds::%s& c) {\n" %
5841 args
= func
.GetOriginalArgs()
5843 arg
.WriteGetCode(file)
5845 code
= """ typedef cmds::%(func_name)s::Result Result;
5846 Result* result_dst = GetSharedMemoryAs<Result*>(
5847 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
5849 return error::kOutOfBounds;
5852 file.Write(code
% {'func_name': func
.name
})
5853 func
.WriteHandlerValidation(file)
5854 file.Write(" *result_dst = %s(%s);\n" %
5855 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5856 file.Write(" return error::kNoError;\n")
5860 def WriteGLES2Implementation(self
, func
, file):
5861 """Overrriden from TypeHandler."""
5862 impl_func
= func
.GetInfo('impl_func')
5863 if impl_func
== None or impl_func
== True:
5864 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
5865 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5866 (func
.return_type
, func
.original_name
,
5867 func
.MakeTypedOriginalArgString("")))
5868 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5869 self
.WriteTraceEvent(func
, file)
5870 func
.WriteDestinationInitalizationValidation(file)
5871 self
.WriteClientGLCallLog(func
, file)
5872 file.Write(" typedef cmds::%s::Result Result;\n" % func
.name
)
5873 file.Write(" Result* result = GetResultAs<Result*>();\n")
5874 file.Write(" if (!result) {\n")
5875 file.Write(" return %s;\n" % error_value
)
5877 file.Write(" *result = 0;\n")
5878 arg_string
= func
.MakeOriginalArgString("")
5880 if len(arg_string
) > 0:
5883 " helper_->%s(%s%sGetResultShmId(), GetResultShmOffset());\n" %
5884 (func
.name
, arg_string
, comma
))
5885 file.Write(" WaitForCmd();\n")
5886 file.Write(" %s result_value = *result;\n" % func
.return_type
)
5887 file.Write(' GPU_CLIENT_LOG("returned " << result_value);\n')
5888 file.Write(" CheckGLError();\n")
5889 file.Write(" return result_value;\n")
5893 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5894 """Overrriden from TypeHandler."""
5895 client_test
= func
.GetInfo('client_test')
5896 if client_test
== None or client_test
== True:
5898 TEST_F(GLES2ImplementationTest, %(name)s) {
5904 ExpectedMemoryInfo result1 =
5905 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
5906 expected.cmd.Init(1, result1.id, result1.offset);
5908 EXPECT_CALL(*command_buffer(), OnFlush())
5909 .WillOnce(SetMemory(result1.ptr, uint32_t(1)))
5910 .RetiresOnSaturation();
5912 GLboolean result = gl_->%(name)s(1);
5913 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5914 EXPECT_TRUE(result);
5922 class STRnHandler(TypeHandler
):
5923 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
5924 GetTranslatedShaderSourceANGLE."""
5927 TypeHandler
.__init
__(self
)
5929 def InitFunction(self
, func
):
5930 """Overrriden from TypeHandler."""
5931 # remove all but the first cmd args.
5932 cmd_args
= func
.GetCmdArgs()
5934 func
.AddCmdArg(cmd_args
[0])
5935 # add on a bucket id.
5936 func
.AddCmdArg(Argument('bucket_id', 'uint32_t'))
5938 def WriteGLES2Implementation(self
, func
, file):
5939 """Overrriden from TypeHandler."""
5940 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
5941 GPU_CLIENT_SINGLE_THREAD_CHECK();
5943 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
5944 << "] gl%(func_name)s" << "("
5947 << static_cast<void*>(%(arg2)s) << ", "
5948 << static_cast<void*>(%(arg3)s) << ")");
5949 helper_->SetBucketSize(kResultBucketId, 0);
5950 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
5952 GLsizei max_size = 0;
5953 if (GetBucketAsString(kResultBucketId, &str)) {
5956 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
5957 memcpy(%(dest_name)s, str.c_str(), max_size);
5958 %(dest_name)s[max_size] = '\\0';
5959 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
5962 if (%(length_name)s != NULL) {
5963 *%(length_name)s = max_size;
5968 args
= func
.GetOriginalArgs()
5970 'return_type': func
.return_type
,
5971 'func_name': func
.original_name
,
5972 'args': func
.MakeTypedOriginalArgString(""),
5973 'id_name': args
[0].name
,
5974 'bufsize_name': args
[1].name
,
5975 'length_name': args
[2].name
,
5976 'dest_name': args
[3].name
,
5977 'arg0': args
[0].name
,
5978 'arg1': args
[1].name
,
5979 'arg2': args
[2].name
,
5980 'arg3': args
[3].name
,
5982 file.Write(code_1
% str_args
)
5983 func
.WriteDestinationInitalizationValidation(file)
5984 file.Write(code_2
% str_args
)
5986 def WriteServiceUnitTest(self
, func
, file, *extras
):
5987 """Overrriden from TypeHandler."""
5989 TEST_P(%(test_name)s, %(name)sValidArgs) {
5990 const char* kInfo = "hello";
5991 const uint32_t kBucketId = 123;
5992 SpecializedSetup<cmds::%(name)s, 0>(true);
5994 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5995 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
5996 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
5999 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6000 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
6001 ASSERT_TRUE(bucket != NULL);
6002 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
6003 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
6005 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6008 args
= func
.GetOriginalArgs()
6009 id_name
= args
[0].GetValidGLArg(func
)
6010 get_len_func
= func
.GetInfo('get_len_func')
6011 get_len_enum
= func
.GetInfo('get_len_enum')
6014 'get_len_func': get_len_func
,
6015 'get_len_enum': get_len_enum
,
6016 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
6017 args
[0].GetValidGLArg(func
),
6018 'args': '%s, kBucketId' % args
[0].GetValidArg(func
),
6019 'expect_len_code': '',
6021 if get_len_func
and get_len_func
[0:2] == 'gl':
6022 sub
['expect_len_code'] = (
6023 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
6024 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
6025 get_len_func
[2:], id_name
, get_len_enum
)
6026 self
.WriteValidUnitTest(func
, file, valid_test
, sub
, *extras
)
6029 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6030 const uint32_t kBucketId = 123;
6031 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
6034 cmd.Init(kInvalidClientId, kBucketId);
6035 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6036 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
6039 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
6041 def WriteServiceImplementation(self
, func
, file):
6042 """Overrriden from TypeHandler."""
6045 class NamedType(object):
6046 """A class that represents a type of an argument in a client function.
6048 A type of an argument that is to be passed through in the command buffer
6049 command. Currently used only for the arguments that are specificly named in
6050 the 'cmd_buffer_functions.txt' file, mostly enums.
6053 def __init__(self
, info
):
6054 assert not 'is_complete' in info
or info
['is_complete'] == True
6056 self
.valid
= info
['valid']
6057 if 'invalid' in info
:
6058 self
.invalid
= info
['invalid']
6063 return self
.info
['type']
6065 def GetInvalidValues(self
):
6068 def GetValidValues(self
):
6071 def IsConstant(self
):
6072 if not 'is_complete' in self
.info
:
6075 return len(self
.GetValidValues()) == 1
6077 def GetConstantValue(self
):
6078 return self
.GetValidValues()[0]
6080 class Argument(object):
6081 """A class that represents a function argument."""
6084 'GLenum': 'uint32_t',
6086 'GLintptr': 'int32_t',
6087 'GLsizei': 'int32_t',
6088 'GLsizeiptr': 'int32_t',
6090 'GLclampf': 'float',
6092 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
6094 def __init__(self
, name
, type):
6096 self
.optional
= type.endswith("Optional*")
6098 type = type[:-9] + "*"
6101 if type in self
.cmd_type_map_
:
6102 self
.cmd_type
= self
.cmd_type_map_
[type]
6104 self
.cmd_type
= 'uint32_t'
6106 def IsPointer(self
):
6107 """Returns true if argument is a pointer."""
6110 def IsConstant(self
):
6111 """Returns true if the argument has only one valid value."""
6114 def AddCmdArgs(self
, args
):
6115 """Adds command arguments for this argument to the given list."""
6116 if not self
.IsConstant():
6117 return args
.append(self
)
6119 def AddInitArgs(self
, args
):
6120 """Adds init arguments for this argument to the given list."""
6121 if not self
.IsConstant():
6122 return args
.append(self
)
6124 def GetValidArg(self
, func
):
6125 """Gets a valid value for this argument."""
6126 valid_arg
= func
.GetValidArg(self
)
6127 if valid_arg
!= None:
6130 index
= func
.GetOriginalArgs().index(self
)
6131 return str(index
+ 1)
6133 def GetValidClientSideArg(self
, func
):
6134 """Gets a valid value for this argument."""
6135 valid_arg
= func
.GetValidArg(self
)
6136 if valid_arg
!= None:
6139 index
= func
.GetOriginalArgs().index(self
)
6140 return str(index
+ 1)
6142 def GetValidClientSideCmdArg(self
, func
):
6143 """Gets a valid value for this argument."""
6144 valid_arg
= func
.GetValidArg(self
)
6145 if valid_arg
!= None:
6148 index
= func
.GetOriginalArgs().index(self
)
6149 return str(index
+ 1)
6152 index
= func
.GetCmdArgs().index(self
)
6153 return str(index
+ 1)
6155 def GetValidGLArg(self
, func
):
6156 """Gets a valid GL value for this argument."""
6157 return self
.GetValidArg(func
)
6159 def GetValidNonCachedClientSideArg(self
, func
):
6160 """Returns a valid value for this argument in a GL call.
6161 Using the value will produce a command buffer service invocation.
6162 Returns None if there is no such value."""
6165 def GetValidNonCachedClientSideCmdArg(self
, func
):
6166 """Returns a valid value for this argument in a command buffer command.
6167 Calling the GL function with the value returned by
6168 GetValidNonCachedClientSideArg will result in a command buffer command
6169 that contains the value returned by this function. """
6172 def GetNumInvalidValues(self
, func
):
6173 """returns the number of invalid values to be tested."""
6176 def GetInvalidArg(self
, index
):
6177 """returns an invalid value and expected parse result by index."""
6178 return ("---ERROR0---", "---ERROR2---", None)
6180 def GetLogArg(self
):
6181 """Get argument appropriate for LOG macro."""
6182 if self
.type == 'GLboolean':
6183 return 'GLES2Util::GetStringBool(%s)' % self
.name
6184 if self
.type == 'GLenum':
6185 return 'GLES2Util::GetStringEnum(%s)' % self
.name
6188 def WriteGetCode(self
, file):
6189 """Writes the code to get an argument from a command structure."""
6190 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
6191 (self
.type, self
.name
, self
.type, self
.name
))
6193 def WriteValidationCode(self
, file, func
):
6194 """Writes the validation code for an argument."""
6197 def WriteClientSideValidationCode(self
, file, func
):
6198 """Writes the validation code for an argument."""
6201 def WriteDestinationInitalizationValidation(self
, file, func
):
6202 """Writes the client side destintion initialization validation."""
6205 def WriteDestinationInitalizationValidatationIfNeeded(self
, file, func
):
6206 """Writes the client side destintion initialization validation if needed."""
6207 parts
= self
.type.split(" ")
6210 if parts
[0] in self
.need_validation_
:
6212 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
6213 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
6216 def WriteGetAddress(self
, file):
6217 """Writes the code to get the address this argument refers to."""
6220 def GetImmediateVersion(self
):
6221 """Gets the immediate version of this argument."""
6224 def GetBucketVersion(self
):
6225 """Gets the bucket version of this argument."""
6229 class BoolArgument(Argument
):
6230 """class for GLboolean"""
6232 def __init__(self
, name
, type):
6233 Argument
.__init
__(self
, name
, 'GLboolean')
6235 def GetValidArg(self
, func
):
6236 """Gets a valid value for this argument."""
6239 def GetValidClientSideArg(self
, func
):
6240 """Gets a valid value for this argument."""
6243 def GetValidClientSideCmdArg(self
, func
):
6244 """Gets a valid value for this argument."""
6247 def GetValidGLArg(self
, func
):
6248 """Gets a valid GL value for this argument."""
6252 class UniformLocationArgument(Argument
):
6253 """class for uniform locations."""
6255 def __init__(self
, name
):
6256 Argument
.__init
__(self
, name
, "GLint")
6258 def WriteGetCode(self
, file):
6259 """Writes the code to get an argument from a command structure."""
6260 code
= """ %s %s = static_cast<%s>(c.%s);
6262 file.Write(code
% (self
.type, self
.name
, self
.type, self
.name
))
6264 class DataSizeArgument(Argument
):
6265 """class for data_size which Bucket commands do not need."""
6267 def __init__(self
, name
):
6268 Argument
.__init
__(self
, name
, "uint32_t")
6270 def GetBucketVersion(self
):
6274 class SizeArgument(Argument
):
6275 """class for GLsizei and GLsizeiptr."""
6277 def __init__(self
, name
, type):
6278 Argument
.__init
__(self
, name
, type)
6280 def GetNumInvalidValues(self
, func
):
6281 """overridden from Argument."""
6282 if func
.IsImmediate():
6286 def GetInvalidArg(self
, index
):
6287 """overridden from Argument."""
6288 return ("-1", "kNoError", "GL_INVALID_VALUE")
6290 def WriteValidationCode(self
, file, func
):
6291 """overridden from Argument."""
6292 file.Write(" if (%s < 0) {\n" % self
.name
)
6294 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
6295 (func
.original_name
, self
.name
))
6296 file.Write(" return error::kNoError;\n")
6299 def WriteClientSideValidationCode(self
, file, func
):
6300 """overridden from Argument."""
6301 file.Write(" if (%s < 0) {\n" % self
.name
)
6303 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
6304 (func
.original_name
, self
.name
))
6305 file.Write(" return;\n")
6309 class SizeNotNegativeArgument(SizeArgument
):
6310 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
6312 def __init__(self
, name
, type, gl_type
):
6313 SizeArgument
.__init
__(self
, name
, gl_type
)
6315 def GetInvalidArg(self
, index
):
6316 """overridden from SizeArgument."""
6317 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
6319 def WriteValidationCode(self
, file, func
):
6320 """overridden from SizeArgument."""
6324 class EnumBaseArgument(Argument
):
6325 """Base class for EnumArgument, IntArgument and ValidatedBoolArgument"""
6327 def __init__(self
, name
, gl_type
, type, gl_error
):
6328 Argument
.__init
__(self
, name
, gl_type
)
6330 self
.local_type
= type
6331 self
.gl_error
= gl_error
6332 name
= type[len(gl_type
):]
6333 self
.type_name
= name
6334 self
.named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
6336 def IsConstant(self
):
6337 return self
.named_type
.IsConstant()
6339 def GetConstantValue(self
):
6340 return self
.named_type
.GetConstantValue()
6342 def WriteValidationCode(self
, file, func
):
6343 if self
.named_type
.IsConstant():
6345 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
6346 (ToUnderscore(self
.type_name
), self
.name
))
6347 if self
.gl_error
== "GL_INVALID_ENUM":
6349 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
6350 (func
.original_name
, self
.name
, self
.name
))
6353 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
6354 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
6355 file.Write(" return error::kNoError;\n")
6358 def WriteClientSideValidationCode(self
, file, func
):
6359 if not self
.named_type
.IsConstant():
6361 file.Write(" if (%s != %s) {" % (self
.name
,
6362 self
.GetConstantValue()))
6364 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
6365 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
6366 if func
.return_type
== "void":
6367 file.Write(" return;\n")
6369 file.Write(" return %s;\n" % func
.GetErrorReturnString())
6372 def GetValidArg(self
, func
):
6373 valid_arg
= func
.GetValidArg(self
)
6374 if valid_arg
!= None:
6376 valid
= self
.named_type
.GetValidValues()
6378 num_valid
= len(valid
)
6381 index
= func
.GetOriginalArgs().index(self
)
6382 return str(index
+ 1)
6384 def GetValidClientSideArg(self
, func
):
6385 """Gets a valid value for this argument."""
6386 return self
.GetValidArg(func
)
6388 def GetValidClientSideCmdArg(self
, func
):
6389 """Gets a valid value for this argument."""
6390 valid_arg
= func
.GetValidArg(self
)
6391 if valid_arg
!= None:
6394 valid
= self
.named_type
.GetValidValues()
6396 num_valid
= len(valid
)
6400 index
= func
.GetOriginalArgs().index(self
)
6401 return str(index
+ 1)
6404 index
= func
.GetCmdArgs().index(self
)
6405 return str(index
+ 1)
6407 def GetValidGLArg(self
, func
):
6408 """Gets a valid value for this argument."""
6409 return self
.GetValidArg(func
)
6411 def GetNumInvalidValues(self
, func
):
6412 """returns the number of invalid values to be tested."""
6413 return len(self
.named_type
.GetInvalidValues())
6415 def GetInvalidArg(self
, index
):
6416 """returns an invalid value by index."""
6417 invalid
= self
.named_type
.GetInvalidValues()
6419 num_invalid
= len(invalid
)
6420 if index
>= num_invalid
:
6421 index
= num_invalid
- 1
6422 return (invalid
[index
], "kNoError", self
.gl_error
)
6423 return ("---ERROR1---", "kNoError", self
.gl_error
)
6426 class EnumArgument(EnumBaseArgument
):
6427 """A class that represents a GLenum argument"""
6429 def __init__(self
, name
, type):
6430 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
6432 def GetLogArg(self
):
6433 """Overridden from Argument."""
6434 return ("GLES2Util::GetString%s(%s)" %
6435 (self
.type_name
, self
.name
))
6438 class IntArgument(EnumBaseArgument
):
6439 """A class for a GLint argument that can only except specific values.
6441 For example glTexImage2D takes a GLint for its internalformat
6442 argument instead of a GLenum.
6445 def __init__(self
, name
, type):
6446 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
6449 class ValidatedBoolArgument(EnumBaseArgument
):
6450 """A class for a GLboolean argument that can only except specific values.
6452 For example glUniformMatrix takes a GLboolean for it's transpose but it
6456 def __init__(self
, name
, type):
6457 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
6459 def GetLogArg(self
):
6460 """Overridden from Argument."""
6461 return 'GLES2Util::GetStringBool(%s)' % self
.name
6464 class ImmediatePointerArgument(Argument
):
6465 """A class that represents an immediate argument to a function.
6467 An immediate argument is one where the data follows the command.
6470 def __init__(self
, name
, type):
6471 Argument
.__init
__(self
, name
, type)
6473 def IsPointer(self
):
6476 def GetPointedType(self
):
6477 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
6479 return match
.groupdict()['element_type']
6481 def AddCmdArgs(self
, args
):
6482 """Overridden from Argument."""
6485 def WriteGetCode(self
, file):
6486 """Overridden from Argument."""
6488 " %s %s = GetImmediateDataAs<%s>(\n" %
6489 (self
.type, self
.name
, self
.type))
6490 file.Write(" c, data_size, immediate_data_size);\n")
6492 def WriteValidationCode(self
, file, func
):
6493 """Overridden from Argument."""
6494 file.Write(" if (%s == NULL) {\n" % self
.name
)
6495 file.Write(" return error::kOutOfBounds;\n")
6498 def GetImmediateVersion(self
):
6499 """Overridden from Argument."""
6502 def WriteDestinationInitalizationValidation(self
, file, func
):
6503 """Overridden from Argument."""
6504 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6506 def GetLogArg(self
):
6507 """Overridden from Argument."""
6508 return "static_cast<const void*>(%s)" % self
.name
6511 class BucketPointerArgument(Argument
):
6512 """A class that represents an bucket argument to a function."""
6514 def __init__(self
, name
, type):
6515 Argument
.__init
__(self
, name
, type)
6517 def AddCmdArgs(self
, args
):
6518 """Overridden from Argument."""
6521 def WriteGetCode(self
, file):
6522 """Overridden from Argument."""
6524 " %s %s = bucket->GetData(0, data_size);\n" %
6525 (self
.type, self
.name
))
6527 def WriteValidationCode(self
, file, func
):
6528 """Overridden from Argument."""
6531 def GetImmediateVersion(self
):
6532 """Overridden from Argument."""
6535 def WriteDestinationInitalizationValidation(self
, file, func
):
6536 """Overridden from Argument."""
6537 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6539 def GetLogArg(self
):
6540 """Overridden from Argument."""
6541 return "static_cast<const void*>(%s)" % self
.name
6544 class PointerArgument(Argument
):
6545 """A class that represents a pointer argument to a function."""
6547 def __init__(self
, name
, type):
6548 Argument
.__init
__(self
, name
, type)
6550 def IsPointer(self
):
6551 """Returns true if argument is a pointer."""
6554 def GetPointedType(self
):
6555 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
6557 return match
.groupdict()['element_type']
6559 def GetValidArg(self
, func
):
6560 """Overridden from Argument."""
6561 return "shared_memory_id_, shared_memory_offset_"
6563 def GetValidGLArg(self
, func
):
6564 """Overridden from Argument."""
6565 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
6567 def GetNumInvalidValues(self
, func
):
6568 """Overridden from Argument."""
6571 def GetInvalidArg(self
, index
):
6572 """Overridden from Argument."""
6574 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
6576 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
6577 "kOutOfBounds", None)
6579 def GetLogArg(self
):
6580 """Overridden from Argument."""
6581 return "static_cast<const void*>(%s)" % self
.name
6583 def AddCmdArgs(self
, args
):
6584 """Overridden from Argument."""
6585 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32_t'))
6586 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32_t'))
6588 def WriteGetCode(self
, file):
6589 """Overridden from Argument."""
6591 " %s %s = GetSharedMemoryAs<%s>(\n" %
6592 (self
.type, self
.name
, self
.type))
6594 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
6595 (self
.name
, self
.name
))
6597 def WriteGetAddress(self
, file):
6598 """Overridden from Argument."""
6600 " %s %s = GetSharedMemoryAs<%s>(\n" %
6601 (self
.type, self
.name
, self
.type))
6603 " %s_shm_id, %s_shm_offset, %s_size);\n" %
6604 (self
.name
, self
.name
, self
.name
))
6606 def WriteValidationCode(self
, file, func
):
6607 """Overridden from Argument."""
6608 file.Write(" if (%s == NULL) {\n" % self
.name
)
6609 file.Write(" return error::kOutOfBounds;\n")
6612 def GetImmediateVersion(self
):
6613 """Overridden from Argument."""
6614 return ImmediatePointerArgument(self
.name
, self
.type)
6616 def GetBucketVersion(self
):
6617 """Overridden from Argument."""
6618 if self
.type == "const char*":
6619 return InputStringBucketArgument(self
.name
, self
.type)
6620 return BucketPointerArgument(self
.name
, self
.type)
6622 def WriteDestinationInitalizationValidation(self
, file, func
):
6623 """Overridden from Argument."""
6624 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
6627 class InputStringBucketArgument(Argument
):
6628 """An string input argument where the string is passed in a bucket."""
6630 def __init__(self
, name
, type):
6631 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
6633 def WriteGetCode(self
, file):
6634 """Overridden from Argument."""
6636 Bucket* %(name)s_bucket = GetBucket(c.%(name)s);
6637 if (!%(name)s_bucket) {
6638 return error::kInvalidArguments;
6640 std::string %(name)s_str;
6641 if (!%(name)s_bucket->GetAsString(&%(name)s_str)) {
6642 return error::kInvalidArguments;
6644 const char* %(name)s = %(name)s_str.c_str();
6650 def GetValidArg(self
, func
):
6651 return "kNameBucketId"
6653 def GetValidGLArg(self
, func
):
6657 class ResourceIdArgument(Argument
):
6658 """A class that represents a resource id argument to a function."""
6660 def __init__(self
, name
, type):
6661 match
= re
.match("(GLid\w+)", type)
6662 self
.resource_type
= match
.group(1)[4:]
6663 type = type.replace(match
.group(1), "GLuint")
6664 Argument
.__init
__(self
, name
, type)
6666 def WriteGetCode(self
, file):
6667 """Overridden from Argument."""
6668 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
6670 def GetValidArg(self
, func
):
6671 return "client_%s_id_" % self
.resource_type
.lower()
6673 def GetValidGLArg(self
, func
):
6674 return "kService%sId" % self
.resource_type
6677 class ResourceIdBindArgument(Argument
):
6678 """Represents a resource id argument to a bind function."""
6680 def __init__(self
, name
, type):
6681 match
= re
.match("(GLidBind\w+)", type)
6682 self
.resource_type
= match
.group(1)[8:]
6683 type = type.replace(match
.group(1), "GLuint")
6684 Argument
.__init
__(self
, name
, type)
6686 def WriteGetCode(self
, file):
6687 """Overridden from Argument."""
6688 code
= """ %(type)s %(name)s = c.%(name)s;
6690 file.Write(code
% {'type': self
.type, 'name': self
.name
})
6692 def GetValidArg(self
, func
):
6693 return "client_%s_id_" % self
.resource_type
.lower()
6695 def GetValidGLArg(self
, func
):
6696 return "kService%sId" % self
.resource_type
6699 class ResourceIdZeroArgument(Argument
):
6700 """Represents a resource id argument to a function that can be zero."""
6702 def __init__(self
, name
, type):
6703 match
= re
.match("(GLidZero\w+)", type)
6704 self
.resource_type
= match
.group(1)[8:]
6705 type = type.replace(match
.group(1), "GLuint")
6706 Argument
.__init
__(self
, name
, type)
6708 def WriteGetCode(self
, file):
6709 """Overridden from Argument."""
6710 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
6712 def GetValidArg(self
, func
):
6713 return "client_%s_id_" % self
.resource_type
.lower()
6715 def GetValidGLArg(self
, func
):
6716 return "kService%sId" % self
.resource_type
6718 def GetNumInvalidValues(self
, func
):
6719 """returns the number of invalid values to be tested."""
6722 def GetInvalidArg(self
, index
):
6723 """returns an invalid value by index."""
6724 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
6727 class Function(object):
6728 """A class that represents a function."""
6732 'Bind': BindHandler(),
6733 'Create': CreateHandler(),
6734 'Custom': CustomHandler(),
6735 'Data': DataHandler(),
6736 'Delete': DeleteHandler(),
6737 'DELn': DELnHandler(),
6738 'GENn': GENnHandler(),
6739 'GETn': GETnHandler(),
6740 'GLchar': GLcharHandler(),
6741 'GLcharN': GLcharNHandler(),
6742 'HandWritten': HandWrittenHandler(),
6744 'Manual': ManualHandler(),
6745 'PUT': PUTHandler(),
6746 'PUTn': PUTnHandler(),
6747 'PUTXn': PUTXnHandler(),
6748 'StateSet': StateSetHandler(),
6749 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
6750 'StateSetFrontBack': StateSetFrontBackHandler(),
6751 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
6752 'StateSetNamedParameter': StateSetNamedParameter(),
6753 'STRn': STRnHandler(),
6754 'Todo': TodoHandler(),
6757 def __init__(self
, name
, info
):
6759 self
.original_name
= info
['original_name']
6761 self
.original_args
= self
.ParseArgs(info
['original_args'])
6763 if 'cmd_args' in info
:
6764 self
.args_for_cmds
= self
.ParseArgs(info
['cmd_args'])
6766 self
.args_for_cmds
= self
.original_args
[:]
6768 self
.return_type
= info
['return_type']
6769 if self
.return_type
!= 'void':
6770 self
.return_arg
= CreateArg(info
['return_type'] + " result")
6772 self
.return_arg
= None
6774 self
.num_pointer_args
= sum(
6775 [1 for arg
in self
.args_for_cmds
if arg
.IsPointer()])
6777 self
.type_handler
= self
.type_handlers
[info
['type']]
6778 self
.can_auto_generate
= (self
.num_pointer_args
== 0 and
6779 info
['return_type'] == "void")
6782 def ParseArgs(self
, arg_string
):
6783 """Parses a function arg string."""
6785 parts
= arg_string
.split(',')
6786 for arg_string
in parts
:
6787 arg
= CreateArg(arg_string
)
6792 def IsType(self
, type_name
):
6793 """Returns true if function is a certain type."""
6794 return self
.info
['type'] == type_name
6796 def InitFunction(self
):
6797 """Creates command args and calls the init function for the type handler.
6799 Creates argument lists for command buffer commands, eg. self.cmd_args and
6801 Calls the type function initialization.
6802 Override to create different kind of command buffer command argument lists.
6805 for arg
in self
.args_for_cmds
:
6806 arg
.AddCmdArgs(self
.cmd_args
)
6809 for arg
in self
.args_for_cmds
:
6810 arg
.AddInitArgs(self
.init_args
)
6813 self
.init_args
.append(self
.return_arg
)
6815 self
.type_handler
.InitFunction(self
)
6817 def IsImmediate(self
):
6818 """Returns whether the function is immediate data function or not."""
6821 def GetInfo(self
, name
, default
= None):
6822 """Returns a value from the function info for this function."""
6823 if name
in self
.info
:
6824 return self
.info
[name
]
6827 def GetValidArg(self
, arg
):
6828 """Gets a valid argument value for the parameter arg from the function info
6831 index
= self
.GetOriginalArgs().index(arg
)
6835 valid_args
= self
.GetInfo('valid_args')
6836 if valid_args
and str(index
) in valid_args
:
6837 return valid_args
[str(index
)]
6840 def AddInfo(self
, name
, value
):
6842 self
.info
[name
] = value
6844 def IsExtension(self
):
6845 return self
.GetInfo('extension') or self
.GetInfo('extension_flag')
6847 def IsCoreGLFunction(self
):
6848 return (not self
.IsExtension() and
6849 not self
.GetInfo('pepper_interface'))
6851 def InPepperInterface(self
, interface
):
6852 ext
= self
.GetInfo('pepper_interface')
6853 if not interface
.GetName():
6854 return self
.IsCoreGLFunction()
6855 return ext
== interface
.GetName()
6857 def InAnyPepperExtension(self
):
6858 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
6860 def GetErrorReturnString(self
):
6861 if self
.GetInfo("error_return"):
6862 return self
.GetInfo("error_return")
6863 elif self
.return_type
== "GLboolean":
6865 elif "*" in self
.return_type
:
6869 def GetGLFunctionName(self
):
6870 """Gets the function to call to execute GL for this command."""
6871 if self
.GetInfo('decoder_func'):
6872 return self
.GetInfo('decoder_func')
6873 return "gl%s" % self
.original_name
6875 def GetGLTestFunctionName(self
):
6876 gl_func_name
= self
.GetInfo('gl_test_func')
6877 if gl_func_name
== None:
6878 gl_func_name
= self
.GetGLFunctionName()
6879 if gl_func_name
.startswith("gl"):
6880 gl_func_name
= gl_func_name
[2:]
6882 gl_func_name
= self
.original_name
6885 def GetDataTransferMethods(self
):
6886 return self
.GetInfo('data_transfer_methods',
6887 ['immediate' if self
.num_pointer_args
== 1 else 'shm'])
6889 def AddCmdArg(self
, arg
):
6890 """Adds a cmd argument to this function."""
6891 self
.cmd_args
.append(arg
)
6893 def GetCmdArgs(self
):
6894 """Gets the command args for this function."""
6895 return self
.cmd_args
6897 def ClearCmdArgs(self
):
6898 """Clears the command args for this function."""
6901 def GetCmdConstants(self
):
6902 """Gets the constants for this function."""
6903 return [arg
for arg
in self
.args_for_cmds
if arg
.IsConstant()]
6905 def GetInitArgs(self
):
6906 """Gets the init args for this function."""
6907 return self
.init_args
6909 def GetOriginalArgs(self
):
6910 """Gets the original arguments to this function."""
6911 return self
.original_args
6913 def GetLastOriginalArg(self
):
6914 """Gets the last original argument to this function."""
6915 return self
.original_args
[len(self
.original_args
) - 1]
6917 def __MaybePrependComma(self
, arg_string
, add_comma
):
6918 """Adds a comma if arg_string is not empty and add_comma is true."""
6920 if add_comma
and len(arg_string
):
6922 return "%s%s" % (comma
, arg_string
)
6924 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
6925 """Gets a list of arguments as they are in GL."""
6926 args
= self
.GetOriginalArgs()
6927 arg_string
= ", ".join(
6928 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6929 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6931 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
6932 """Gets the list of arguments as they are in GL."""
6933 args
= self
.GetOriginalArgs()
6934 arg_string
= separator
.join(
6935 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6936 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6938 def MakeTypedHelperArgString(self
, prefix
, add_comma
= False):
6939 """Gets a list of typed GL arguments after removing unneeded arguments."""
6940 args
= self
.GetOriginalArgs()
6941 arg_string
= ", ".join(
6946 ) for arg
in args
if not arg
.IsConstant()])
6947 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6949 def MakeHelperArgString(self
, prefix
, add_comma
= False, separator
= ", "):
6950 """Gets a list of GL arguments after removing unneeded arguments."""
6951 args
= self
.GetOriginalArgs()
6952 arg_string
= separator
.join(
6953 ["%s%s" % (prefix
, arg
.name
)
6954 for arg
in args
if not arg
.IsConstant()])
6955 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6957 def MakeTypedPepperArgString(self
, prefix
):
6958 """Gets a list of arguments as they need to be for Pepper."""
6959 if self
.GetInfo("pepper_args"):
6960 return self
.GetInfo("pepper_args")
6962 return self
.MakeTypedOriginalArgString(prefix
, False)
6964 def GetPepperName(self
):
6965 if self
.GetInfo("pepper_name"):
6966 return self
.GetInfo("pepper_name")
6969 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
6970 """Gets a typed list of arguments as they need to be for command buffers."""
6971 args
= self
.GetCmdArgs()
6972 arg_string
= ", ".join(
6973 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6974 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6976 def MakeCmdArgString(self
, prefix
, add_comma
= False):
6977 """Gets the list of arguments as they need to be for command buffers."""
6978 args
= self
.GetCmdArgs()
6979 arg_string
= ", ".join(
6980 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6981 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6983 def MakeTypedInitString(self
, prefix
, add_comma
= False):
6984 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
6985 args
= self
.GetInitArgs()
6986 arg_string
= ", ".join(
6987 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
6988 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6990 def MakeInitString(self
, prefix
, add_comma
= False):
6991 """Gets the list of arguments as they need to be for cmd Init/Set."""
6992 args
= self
.GetInitArgs()
6993 arg_string
= ", ".join(
6994 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
6995 return self
.__MaybePrependComma
(arg_string
, add_comma
)
6997 def MakeLogArgString(self
):
6998 """Makes a string of the arguments for the LOG macros"""
6999 args
= self
.GetOriginalArgs()
7000 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
7002 def WriteCommandDescription(self
, file):
7003 """Writes a description of the command."""
7004 file.Write("//! Command that corresponds to gl%s.\n" % self
.original_name
)
7006 def WriteHandlerValidation(self
, file):
7007 """Writes validation code for the function."""
7008 for arg
in self
.GetOriginalArgs():
7009 arg
.WriteValidationCode(file, self
)
7010 self
.WriteValidationCode(file)
7012 def WriteHandlerImplementation(self
, file):
7013 """Writes the handler implementation for this command."""
7014 self
.type_handler
.WriteHandlerImplementation(self
, file)
7016 def WriteValidationCode(self
, file):
7017 """Writes the validation code for a command."""
7020 def WriteCmdFlag(self
, file):
7021 """Writes the cmd cmd_flags constant."""
7023 # By default trace only at the highest level 3.
7024 trace_level
= int(self
.GetInfo('trace_level', default
= 3))
7025 if trace_level
not in xrange(0, 4):
7026 raise KeyError("Unhandled trace_level: %d" % trace_level
)
7028 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
7031 cmd_flags
= ' | '.join(flags
)
7035 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
7038 def WriteCmdArgFlag(self
, file):
7039 """Writes the cmd kArgFlags constant."""
7040 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
7042 def WriteCmdComputeSize(self
, file):
7043 """Writes the ComputeSize function for the command."""
7044 file.Write(" static uint32_t ComputeSize() {\n")
7046 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
7050 def WriteCmdSetHeader(self
, file):
7051 """Writes the cmd's SetHeader function."""
7052 file.Write(" void SetHeader() {\n")
7053 file.Write(" header.SetCmd<ValueType>();\n")
7057 def WriteCmdInit(self
, file):
7058 """Writes the cmd's Init function."""
7059 file.Write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
7060 file.Write(" SetHeader();\n")
7061 args
= self
.GetCmdArgs()
7063 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
7067 def WriteCmdSet(self
, file):
7068 """Writes the cmd's Set function."""
7069 copy_args
= self
.MakeCmdArgString("_", False)
7070 file.Write(" void* Set(void* cmd%s) {\n" %
7071 self
.MakeTypedCmdArgString("_", True))
7072 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
7073 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
7077 def WriteStruct(self
, file):
7078 self
.type_handler
.WriteStruct(self
, file)
7080 def WriteDocs(self
, file):
7081 self
.type_handler
.WriteDocs(self
, file)
7083 def WriteCmdHelper(self
, file):
7084 """Writes the cmd's helper."""
7085 self
.type_handler
.WriteCmdHelper(self
, file)
7087 def WriteServiceImplementation(self
, file):
7088 """Writes the service implementation for a command."""
7089 self
.type_handler
.WriteServiceImplementation(self
, file)
7091 def WriteServiceUnitTest(self
, file, *extras
):
7092 """Writes the service implementation for a command."""
7093 self
.type_handler
.WriteServiceUnitTest(self
, file, *extras
)
7095 def WriteGLES2CLibImplementation(self
, file):
7096 """Writes the GLES2 C Lib Implemention."""
7097 self
.type_handler
.WriteGLES2CLibImplementation(self
, file)
7099 def WriteGLES2InterfaceHeader(self
, file):
7100 """Writes the GLES2 Interface declaration."""
7101 self
.type_handler
.WriteGLES2InterfaceHeader(self
, file)
7103 def WriteGLES2InterfaceStub(self
, file):
7104 """Writes the GLES2 Interface Stub declaration."""
7105 self
.type_handler
.WriteGLES2InterfaceStub(self
, file)
7107 def WriteGLES2InterfaceStubImpl(self
, file):
7108 """Writes the GLES2 Interface Stub declaration."""
7109 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, file)
7111 def WriteGLES2ImplementationHeader(self
, file):
7112 """Writes the GLES2 Implemention declaration."""
7113 self
.type_handler
.WriteGLES2ImplementationHeader(self
, file)
7115 def WriteGLES2Implementation(self
, file):
7116 """Writes the GLES2 Implemention definition."""
7117 self
.type_handler
.WriteGLES2Implementation(self
, file)
7119 def WriteGLES2TraceImplementationHeader(self
, file):
7120 """Writes the GLES2 Trace Implemention declaration."""
7121 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, file)
7123 def WriteGLES2TraceImplementation(self
, file):
7124 """Writes the GLES2 Trace Implemention definition."""
7125 self
.type_handler
.WriteGLES2TraceImplementation(self
, file)
7127 def WriteGLES2Header(self
, file):
7128 """Writes the GLES2 Implemention unit test."""
7129 self
.type_handler
.WriteGLES2Header(self
, file)
7131 def WriteGLES2ImplementationUnitTest(self
, file):
7132 """Writes the GLES2 Implemention unit test."""
7133 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, file)
7135 def WriteDestinationInitalizationValidation(self
, file):
7136 """Writes the client side destintion initialization validation."""
7137 self
.type_handler
.WriteDestinationInitalizationValidation(self
, file)
7139 def WriteFormatTest(self
, file):
7140 """Writes the cmd's format test."""
7141 self
.type_handler
.WriteFormatTest(self
, file)
7144 class PepperInterface(object):
7145 """A class that represents a function."""
7147 def __init__(self
, info
):
7148 self
.name
= info
["name"]
7149 self
.dev
= info
["dev"]
7154 def GetInterfaceName(self
):
7158 upperint
= "_" + self
.name
.upper()
7161 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
7163 def GetInterfaceString(self
):
7167 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
7169 def GetStructName(self
):
7173 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
7176 class ImmediateFunction(Function
):
7177 """A class that represnets an immediate function command."""
7179 def __init__(self
, func
):
7182 "%sImmediate" % func
.name
,
7185 def InitFunction(self
):
7186 # Override args in original_args and args_for_cmds with immediate versions
7189 new_original_args
= []
7190 for arg
in self
.original_args
:
7191 new_arg
= arg
.GetImmediateVersion()
7193 new_original_args
.append(new_arg
)
7194 self
.original_args
= new_original_args
7196 new_args_for_cmds
= []
7197 for arg
in self
.args_for_cmds
:
7198 new_arg
= arg
.GetImmediateVersion()
7200 new_args_for_cmds
.append(new_arg
)
7202 self
.args_for_cmds
= new_args_for_cmds
7204 Function
.InitFunction(self
)
7206 def IsImmediate(self
):
7209 def WriteCommandDescription(self
, file):
7210 """Overridden from Function"""
7211 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
7214 def WriteServiceImplementation(self
, file):
7215 """Overridden from Function"""
7216 self
.type_handler
.WriteImmediateServiceImplementation(self
, file)
7218 def WriteHandlerImplementation(self
, file):
7219 """Overridden from Function"""
7220 self
.type_handler
.WriteImmediateHandlerImplementation(self
, file)
7222 def WriteServiceUnitTest(self
, file, *extras
):
7223 """Writes the service implementation for a command."""
7224 self
.type_handler
.WriteImmediateServiceUnitTest(self
, file, *extras
)
7226 def WriteValidationCode(self
, file):
7227 """Overridden from Function"""
7228 self
.type_handler
.WriteImmediateValidationCode(self
, file)
7230 def WriteCmdArgFlag(self
, file):
7231 """Overridden from Function"""
7232 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
7234 def WriteCmdComputeSize(self
, file):
7235 """Overridden from Function"""
7236 self
.type_handler
.WriteImmediateCmdComputeSize(self
, file)
7238 def WriteCmdSetHeader(self
, file):
7239 """Overridden from Function"""
7240 self
.type_handler
.WriteImmediateCmdSetHeader(self
, file)
7242 def WriteCmdInit(self
, file):
7243 """Overridden from Function"""
7244 self
.type_handler
.WriteImmediateCmdInit(self
, file)
7246 def WriteCmdSet(self
, file):
7247 """Overridden from Function"""
7248 self
.type_handler
.WriteImmediateCmdSet(self
, file)
7250 def WriteCmdHelper(self
, file):
7251 """Overridden from Function"""
7252 self
.type_handler
.WriteImmediateCmdHelper(self
, file)
7254 def WriteFormatTest(self
, file):
7255 """Overridden from Function"""
7256 self
.type_handler
.WriteImmediateFormatTest(self
, file)
7259 class BucketFunction(Function
):
7260 """A class that represnets a bucket version of a function command."""
7262 def __init__(self
, func
):
7265 "%sBucket" % func
.name
,
7268 def InitFunction(self
):
7269 # Override args in original_args and args_for_cmds with bucket versions
7272 new_original_args
= []
7273 for arg
in self
.original_args
:
7274 new_arg
= arg
.GetBucketVersion()
7276 new_original_args
.append(new_arg
)
7277 self
.original_args
= new_original_args
7279 new_args_for_cmds
= []
7280 for arg
in self
.args_for_cmds
:
7281 new_arg
= arg
.GetBucketVersion()
7283 new_args_for_cmds
.append(new_arg
)
7285 self
.args_for_cmds
= new_args_for_cmds
7287 Function
.InitFunction(self
)
7289 def WriteCommandDescription(self
, file):
7290 """Overridden from Function"""
7291 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
7294 def WriteServiceImplementation(self
, file):
7295 """Overridden from Function"""
7296 self
.type_handler
.WriteBucketServiceImplementation(self
, file)
7298 def WriteHandlerImplementation(self
, file):
7299 """Overridden from Function"""
7300 self
.type_handler
.WriteBucketHandlerImplementation(self
, file)
7302 def WriteServiceUnitTest(self
, file, *extras
):
7303 """Writes the service implementation for a command."""
7304 self
.type_handler
.WriteBucketServiceUnitTest(self
, file, *extras
)
7307 def CreateArg(arg_string
):
7308 """Creates an Argument."""
7309 arg_parts
= arg_string
.split()
7310 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
7312 # Is this a pointer argument?
7313 elif arg_string
.find('*') >= 0:
7314 return PointerArgument(
7316 " ".join(arg_parts
[0:-1]))
7317 # Is this a resource argument? Must come after pointer check.
7318 elif arg_parts
[0].startswith('GLidBind'):
7319 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7320 elif arg_parts
[0].startswith('GLidZero'):
7321 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7322 elif arg_parts
[0].startswith('GLid'):
7323 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7324 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
7325 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7326 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
7327 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7328 elif arg_parts
[0].startswith('GLboolean'):
7329 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7330 elif arg_parts
[0].startswith('GLintUniformLocation'):
7331 return UniformLocationArgument(arg_parts
[-1])
7332 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
7333 not arg_parts
[0].startswith('GLintptr')):
7334 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7335 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
7336 arg_parts
[0].startswith('GLintptrNotNegative')):
7337 return SizeNotNegativeArgument(arg_parts
[-1],
7338 " ".join(arg_parts
[0:-1]),
7339 arg_parts
[0][0:-11])
7340 elif arg_parts
[0].startswith('GLsize'):
7341 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7343 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
7346 class GLGenerator(object):
7347 """A class to generate GL command buffers."""
7349 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
7351 def __init__(self
, verbose
):
7352 self
.original_functions
= []
7354 self
.verbose
= verbose
7356 self
.pepper_interfaces
= []
7357 self
.interface_info
= {}
7359 for interface
in _PEPPER_INTERFACES
:
7360 interface
= PepperInterface(interface
)
7361 self
.pepper_interfaces
.append(interface
)
7362 self
.interface_info
[interface
.GetName()] = interface
7364 def AddFunction(self
, func
):
7365 """Adds a function."""
7366 self
.functions
.append(func
)
7368 def GetFunctionInfo(self
, name
):
7369 """Gets a type info for the given function name."""
7370 if name
in _FUNCTION_INFO
:
7371 func_info
= _FUNCTION_INFO
[name
].copy()
7375 if not 'type' in func_info
:
7376 func_info
['type'] = ''
7381 """Prints something if verbose is true."""
7385 def Error(self
, msg
):
7386 """Prints an error."""
7387 print "Error: %s" % msg
7390 def WriteLicense(self
, file):
7391 """Writes the license."""
7392 file.Write(_LICENSE
)
7394 def WriteNamespaceOpen(self
, file):
7395 """Writes the code for the namespace."""
7396 file.Write("namespace gpu {\n")
7397 file.Write("namespace gles2 {\n")
7400 def WriteNamespaceClose(self
, file):
7401 """Writes the code to close the namespace."""
7402 file.Write("} // namespace gles2\n")
7403 file.Write("} // namespace gpu\n")
7406 def ParseGLH(self
, filename
):
7407 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
7408 f
= open(filename
, "r")
7409 functions
= f
.read()
7411 for line
in functions
.splitlines():
7412 match
= self
._function
_re
.match(line
)
7414 func_name
= match
.group(2)[2:]
7415 func_info
= self
.GetFunctionInfo(func_name
)
7416 if func_info
['type'] == 'Noop':
7419 parsed_func_info
= {
7420 'original_name': func_name
,
7421 'original_args': match
.group(3),
7422 'return_type': match
.group(1).strip(),
7425 for k
in parsed_func_info
.keys():
7426 if not k
in func_info
:
7427 func_info
[k
] = parsed_func_info
[k
]
7429 f
= Function(func_name
, func_info
)
7430 self
.original_functions
.append(f
)
7432 #for arg in f.GetOriginalArgs():
7433 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
7434 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
7436 gen_cmd
= f
.GetInfo('gen_cmd')
7437 if gen_cmd
== True or gen_cmd
== None:
7438 if f
.type_handler
.NeedsDataTransferFunction(f
):
7439 methods
= f
.GetDataTransferMethods()
7440 if 'immediate' in methods
:
7441 self
.AddFunction(ImmediateFunction(f
))
7442 if 'bucket' in methods
:
7443 self
.AddFunction(BucketFunction(f
))
7444 if 'shm' in methods
:
7449 self
.Log("Auto Generated Functions : %d" %
7450 len([f
for f
in self
.functions
if f
.can_auto_generate
or
7451 (not f
.IsType('') and not f
.IsType('Custom') and
7452 not f
.IsType('Todo'))]))
7454 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
7455 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
7456 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
7459 self
.Log(" %-10s %-20s gl%s" % (f
.info
['type'], f
.return_type
, f
.name
))
7461 def WriteCommandIds(self
, filename
):
7462 """Writes the command buffer format"""
7463 file = CHeaderWriter(filename
)
7464 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
7466 for func
in self
.functions
:
7467 file.Write(" %-60s /* %d */ \\\n" %
7468 ("OP(%s)" % func
.name
, id))
7472 file.Write("enum CommandId {\n")
7473 file.Write(" kStartPoint = cmd::kLastCommonId, "
7474 "// All GLES2 commands start after this.\n")
7475 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
7476 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
7477 file.Write("#undef GLES2_CMD_OP\n")
7478 file.Write(" kNumCommands\n")
7483 def WriteFormat(self
, filename
):
7484 """Writes the command buffer format"""
7485 file = CHeaderWriter(filename
)
7486 for func
in self
.functions
:
7488 #gen_cmd = func.GetInfo('gen_cmd')
7489 #if gen_cmd == True or gen_cmd == None:
7490 func
.WriteStruct(file)
7494 def WriteDocs(self
, filename
):
7495 """Writes the command buffer doc version of the commands"""
7496 file = CWriter(filename
)
7497 for func
in self
.functions
:
7499 #gen_cmd = func.GetInfo('gen_cmd')
7500 #if gen_cmd == True or gen_cmd == None:
7501 func
.WriteDocs(file)
7505 def WriteFormatTest(self
, filename
):
7506 """Writes the command buffer format test."""
7507 file = CHeaderWriter(
7509 "// This file contains unit tests for gles2 commmands\n"
7510 "// It is included by gles2_cmd_format_test.cc\n"
7513 for func
in self
.functions
:
7515 #gen_cmd = func.GetInfo('gen_cmd')
7516 #if gen_cmd == True or gen_cmd == None:
7517 func
.WriteFormatTest(file)
7521 def WriteCmdHelperHeader(self
, filename
):
7522 """Writes the gles2 command helper."""
7523 file = CHeaderWriter(filename
)
7525 for func
in self
.functions
:
7527 #gen_cmd = func.GetInfo('gen_cmd')
7528 #if gen_cmd == True or gen_cmd == None:
7529 func
.WriteCmdHelper(file)
7533 def WriteServiceContextStateHeader(self
, filename
):
7534 """Writes the service context state header."""
7535 file = CHeaderWriter(
7537 "// It is included by context_state.h\n")
7538 file.Write("struct EnableFlags {\n")
7539 file.Write(" EnableFlags();\n")
7540 for capability
in _CAPABILITY_FLAGS
:
7541 file.Write(" bool %s;\n" % capability
['name'])
7542 file.Write(" bool cached_%s;\n" % capability
['name'])
7543 file.Write("};\n\n")
7545 for state_name
in sorted(_STATES
.keys()):
7546 state
= _STATES
[state_name
]
7547 for item
in state
['states']:
7548 if isinstance(item
['default'], list):
7549 file.Write("%s %s[%d];\n" % (item
['type'], item
['name'],
7550 len(item
['default'])))
7552 file.Write("%s %s;\n" % (item
['type'], item
['name']))
7554 if item
.get('cached', False):
7555 if isinstance(item
['default'], list):
7556 file.Write("%s cached_%s[%d];\n" % (item
['type'], item
['name'],
7557 len(item
['default'])))
7559 file.Write("%s cached_%s;\n" % (item
['type'], item
['name']))
7564 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
7567 for capability
in _CAPABILITY_FLAGS
:
7570 """ % capability
['name'].upper())
7572 if (enable_flags.cached_%(name)s == enable &&
7573 !ignore_cached_state)
7575 enable_flags.cached_%(name)s = enable;
7593 def WriteClientContextStateHeader(self
, filename
):
7594 """Writes the client context state header."""
7595 file = CHeaderWriter(
7597 "// It is included by client_context_state.h\n")
7598 file.Write("struct EnableFlags {\n")
7599 file.Write(" EnableFlags();\n")
7600 for capability
in _CAPABILITY_FLAGS
:
7601 file.Write(" bool %s;\n" % capability
['name'])
7602 file.Write("};\n\n")
7606 def WriteContextStateGetters(self
, file, class_name
):
7607 """Writes the state getters."""
7608 for gl_type
in ["GLint", "GLfloat"]:
7610 bool %s::GetStateAs%s(
7611 GLenum pname, %s* params, GLsizei* num_written) const {
7613 """ % (class_name
, gl_type
, gl_type
))
7614 for state_name
in sorted(_STATES
.keys()):
7615 state
= _STATES
[state_name
]
7617 file.Write(" case %s:\n" % state
['enum'])
7618 file.Write(" *num_written = %d;\n" % len(state
['states']))
7619 file.Write(" if (params) {\n")
7620 for ndx
,item
in enumerate(state
['states']):
7621 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
7622 (ndx
, gl_type
, item
['name']))
7624 file.Write(" return true;\n")
7626 for item
in state
['states']:
7627 file.Write(" case %s:\n" % item
['enum'])
7628 if isinstance(item
['default'], list):
7629 item_len
= len(item
['default'])
7630 file.Write(" *num_written = %d;\n" % item_len
)
7631 file.Write(" if (params) {\n")
7632 if item
['type'] == gl_type
:
7633 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
7634 (item
['name'], item
['type'], item_len
))
7636 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
7638 file.Write(" params[i] = %s;\n" %
7639 (GetGLGetTypeConversion(gl_type
, item
['type'],
7640 "%s[i]" % item
['name'])))
7643 file.Write(" *num_written = 1;\n")
7644 file.Write(" if (params) {\n")
7645 file.Write(" params[0] = %s;\n" %
7646 (GetGLGetTypeConversion(gl_type
, item
['type'],
7649 file.Write(" return true;\n")
7650 for capability
in _CAPABILITY_FLAGS
:
7651 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7652 file.Write(" *num_written = 1;\n")
7653 file.Write(" if (params) {\n")
7655 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
7656 (gl_type
, capability
['name']))
7658 file.Write(" return true;\n")
7659 file.Write(""" default:
7665 def WriteServiceContextStateImpl(self
, filename
):
7666 """Writes the context state service implementation."""
7667 file = CHeaderWriter(
7669 "// It is included by context_state.cc\n")
7671 for capability
in _CAPABILITY_FLAGS
:
7672 code
.append("%s(%s)" %
7673 (capability
['name'],
7674 ('false', 'true')['default' in capability
]))
7675 code
.append("cached_%s(%s)" %
7676 (capability
['name'],
7677 ('false', 'true')['default' in capability
]))
7678 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7682 file.Write("void ContextState::Initialize() {\n")
7683 for state_name
in sorted(_STATES
.keys()):
7684 state
= _STATES
[state_name
]
7685 for item
in state
['states']:
7686 if isinstance(item
['default'], list):
7687 for ndx
, value
in enumerate(item
['default']):
7688 file.Write(" %s[%d] = %s;\n" % (item
['name'], ndx
, value
))
7690 file.Write(" %s = %s;\n" % (item
['name'], item
['default']))
7691 if item
.get('cached', False):
7692 if isinstance(item
['default'], list):
7693 for ndx
, value
in enumerate(item
['default']):
7694 file.Write(" cached_%s[%d] = %s;\n" % (item
['name'], ndx
, value
))
7696 file.Write(" cached_%s = %s;\n" % (item
['name'], item
['default']))
7700 void ContextState::InitCapabilities(const ContextState* prev_state) const {
7702 def WriteCapabilities(test_prev
):
7703 for capability
in _CAPABILITY_FLAGS
:
7704 capability_name
= capability
['name']
7706 file.Write(""" if (prev_state->enable_flags.cached_%s !=
7707 enable_flags.cached_%s)\n""" %
7708 (capability_name
, capability_name
))
7709 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
7710 (capability_name
.upper(), capability_name
))
7712 file.Write(" if (prev_state) {")
7713 WriteCapabilities(True)
7714 file.Write(" } else {")
7715 WriteCapabilities(False)
7720 void ContextState::InitState(const ContextState *prev_state) const {
7723 def WriteStates(test_prev
):
7724 # We need to sort the keys so the expectations match
7725 for state_name
in sorted(_STATES
.keys()):
7726 state
= _STATES
[state_name
]
7727 if state
['type'] == 'FrontBack':
7728 num_states
= len(state
['states'])
7729 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
7733 for place
, item
in enumerate(group
):
7734 item_name
= CachedStateName(item
)
7735 args
.append('%s' % item_name
)
7739 file.Write("(%s != prev_state->%s)" % (item_name
, item_name
))
7743 " gl%s(%s, %s);\n" %
7744 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
7745 elif state
['type'] == 'NamedParameter':
7746 for item
in state
['states']:
7747 item_name
= CachedStateName(item
)
7749 if 'extension_flag' in item
:
7750 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
7751 item
['extension_flag'])
7753 if isinstance(item
['default'], list):
7754 file.Write(" if (memcmp(prev_state->%s, %s, "
7755 "sizeof(%s) * %d)) {\n" %
7756 (item_name
, item_name
, item
['type'],
7757 len(item
['default'])))
7759 file.Write(" if (prev_state->%s != %s) {\n " %
7760 (item_name
, item_name
))
7761 file.Write(" gl%s(%s, %s);\n" %
7764 if 'enum_set' in item
else item
['enum']),
7767 if 'extension_flag' in item
:
7770 if 'extension_flag' in item
:
7773 if 'extension_flag' in state
:
7774 file.Write(" if (feature_info_->feature_flags().%s)\n " %
7775 state
['extension_flag'])
7779 for place
, item
in enumerate(state
['states']):
7780 item_name
= CachedStateName(item
)
7781 args
.append('%s' % item_name
)
7785 file.Write("(%s != prev_state->%s)" %
7786 (item_name
, item_name
))
7789 file.Write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
7791 file.Write(" if (prev_state) {")
7793 file.Write(" } else {")
7798 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
7801 for capability
in _CAPABILITY_FLAGS
:
7802 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7803 file.Write(" return enable_flags.%s;\n" % capability
['name'])
7804 file.Write(""" default:
7811 self
.WriteContextStateGetters(file, "ContextState")
7814 def WriteClientContextStateImpl(self
, filename
):
7815 """Writes the context state client side implementation."""
7816 file = CHeaderWriter(
7818 "// It is included by client_context_state.cc\n")
7820 for capability
in _CAPABILITY_FLAGS
:
7821 code
.append("%s(%s)" %
7822 (capability
['name'],
7823 ('false', 'true')['default' in capability
]))
7825 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
7830 bool ClientContextState::SetCapabilityState(
7831 GLenum cap, bool enabled, bool* changed) {
7835 for capability
in _CAPABILITY_FLAGS
:
7836 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7837 file.Write(""" if (enable_flags.%(name)s != enabled) {
7839 enable_flags.%(name)s = enabled;
7843 file.Write(""" default:
7848 file.Write("""bool ClientContextState::GetEnabled(
7849 GLenum cap, bool* enabled) const {
7852 for capability
in _CAPABILITY_FLAGS
:
7853 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7854 file.Write(" *enabled = enable_flags.%s;\n" % capability
['name'])
7855 file.Write(" return true;\n")
7856 file.Write(""" default:
7863 def WriteServiceImplementation(self
, filename
):
7864 """Writes the service decorder implementation."""
7865 file = CHeaderWriter(
7867 "// It is included by gles2_cmd_decoder.cc\n")
7869 for func
in self
.functions
:
7871 #gen_cmd = func.GetInfo('gen_cmd')
7872 #if gen_cmd == True or gen_cmd == None:
7873 func
.WriteServiceImplementation(file)
7876 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
7879 for capability
in _CAPABILITY_FLAGS
:
7880 file.Write(" case GL_%s:\n" % capability
['name'].upper())
7881 if 'state_flag' in capability
:
7884 state_.enable_flags.%(name)s = enabled;
7885 if (state_.enable_flags.cached_%(name)s != enabled
7886 || state_.ignore_cached_state) {
7887 %(state_flag)s = true;
7893 state_.enable_flags.%(name)s = enabled;
7894 if (state_.enable_flags.cached_%(name)s != enabled
7895 || state_.ignore_cached_state) {
7896 state_.enable_flags.cached_%(name)s = enabled;
7901 file.Write(""" default:
7909 def WriteServiceUnitTests(self
, filename
):
7910 """Writes the service decorder unit tests."""
7911 num_tests
= len(self
.functions
)
7912 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
7914 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
7916 name
= filename
% count
7917 file = CHeaderWriter(
7919 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count
)
7920 test_name
= 'GLES2DecoderTest%d' % count
7921 end
= test_num
+ FUNCTIONS_PER_FILE
7924 for idx
in range(test_num
, end
):
7925 func
= self
.functions
[idx
]
7927 # Do any filtering of the functions here, so that the functions
7928 # will not move between the numbered files if filtering properties
7930 if func
.GetInfo('extension_flag'):
7934 #gen_cmd = func.GetInfo('gen_cmd')
7935 #if gen_cmd == True or gen_cmd == None:
7936 if func
.GetInfo('unit_test') == False:
7937 file.Write("// TODO(gman): %s\n" % func
.name
)
7939 func
.WriteServiceUnitTest(file, {
7940 'test_name': test_name
7944 file = CHeaderWriter(
7946 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
7948 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
7950 for capability
in _CAPABILITY_FLAGS
:
7951 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
7952 (capability
['name'].upper(),
7953 ('false', 'true')['default' in capability
]))
7956 void GLES2DecoderTestBase::SetupInitStateExpectations() {
7959 # We need to sort the keys so the expectations match
7960 for state_name
in sorted(_STATES
.keys()):
7961 state
= _STATES
[state_name
]
7962 if state
['type'] == 'FrontBack':
7963 num_states
= len(state
['states'])
7964 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
7967 if 'expected' in item
:
7968 args
.append(item
['expected'])
7970 args
.append(item
['default'])
7972 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7973 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
7974 file.Write(" .Times(1)\n")
7975 file.Write(" .RetiresOnSaturation();\n")
7976 elif state
['type'] == 'NamedParameter':
7977 for item
in state
['states']:
7978 if 'extension_flag' in item
:
7979 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
7980 item
['extension_flag'])
7982 expect_value
= item
['default']
7983 if isinstance(expect_value
, list):
7984 # TODO: Currently we do not check array values.
7988 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
7991 if 'enum_set' in item
else item
['enum']),
7993 file.Write(" .Times(1)\n")
7994 file.Write(" .RetiresOnSaturation();\n")
7995 if 'extension_flag' in item
:
7998 if 'extension_flag' in state
:
7999 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
8000 state
['extension_flag'])
8003 for item
in state
['states']:
8004 if 'expected' in item
:
8005 args
.append(item
['expected'])
8007 args
.append(item
['default'])
8008 # TODO: Currently we do not check array values.
8009 args
= ["_" if isinstance(arg
, list) else arg
for arg
in args
]
8010 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
8011 (state
['func'], ", ".join(args
)))
8012 file.Write(" .Times(1)\n")
8013 file.Write(" .RetiresOnSaturation();\n")
8014 if 'extension_flag' in state
:
8020 def WriteServiceUnitTestsForExtensions(self
, filename
):
8021 """Writes the service decorder unit tests for functions with extension_flag.
8023 The functions are special in that they need a specific unit test
8024 baseclass to turn on the extension.
8026 functions
= [f
for f
in self
.functions
if f
.GetInfo('extension_flag')]
8027 file = CHeaderWriter(
8029 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
8030 for func
in functions
:
8032 if func
.GetInfo('unit_test') == False:
8033 file.Write("// TODO(gman): %s\n" % func
.name
)
8035 extension
= ToCamelCase(
8036 ToGLExtensionString(func
.GetInfo('extension_flag')))
8037 func
.WriteServiceUnitTest(file, {
8038 'test_name': 'GLES2DecoderTestWith%s' % extension
8043 def WriteGLES2Header(self
, filename
):
8044 """Writes the GLES2 header."""
8045 file = CHeaderWriter(
8047 "// This file contains Chromium-specific GLES2 declarations.\n\n")
8049 for func
in self
.original_functions
:
8050 func
.WriteGLES2Header(file)
8055 def WriteGLES2CLibImplementation(self
, filename
):
8056 """Writes the GLES2 c lib implementation."""
8057 file = CHeaderWriter(
8059 "// These functions emulate GLES2 over command buffers.\n")
8061 for func
in self
.original_functions
:
8062 func
.WriteGLES2CLibImplementation(file)
8067 extern const NameToFunc g_gles2_function_table[] = {
8069 for func
in self
.original_functions
:
8071 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
8072 (func
.name
, func
.name
))
8073 file.Write(""" { NULL, NULL, },
8076 } // namespace gles2
8080 def WriteGLES2InterfaceHeader(self
, filename
):
8081 """Writes the GLES2 interface header."""
8082 file = CHeaderWriter(
8084 "// This file is included by gles2_interface.h to declare the\n"
8085 "// GL api functions.\n")
8086 for func
in self
.original_functions
:
8087 func
.WriteGLES2InterfaceHeader(file)
8090 def WriteGLES2InterfaceStub(self
, filename
):
8091 """Writes the GLES2 interface stub header."""
8092 file = CHeaderWriter(
8094 "// This file is included by gles2_interface_stub.h.\n")
8095 for func
in self
.original_functions
:
8096 func
.WriteGLES2InterfaceStub(file)
8099 def WriteGLES2InterfaceStubImpl(self
, filename
):
8100 """Writes the GLES2 interface header."""
8101 file = CHeaderWriter(
8103 "// This file is included by gles2_interface_stub.cc.\n")
8104 for func
in self
.original_functions
:
8105 func
.WriteGLES2InterfaceStubImpl(file)
8108 def WriteGLES2ImplementationHeader(self
, filename
):
8109 """Writes the GLES2 Implementation header."""
8110 file = CHeaderWriter(
8112 "// This file is included by gles2_implementation.h to declare the\n"
8113 "// GL api functions.\n")
8114 for func
in self
.original_functions
:
8115 func
.WriteGLES2ImplementationHeader(file)
8118 def WriteGLES2Implementation(self
, filename
):
8119 """Writes the GLES2 Implementation."""
8120 file = CHeaderWriter(
8122 "// This file is included by gles2_implementation.cc to define the\n"
8123 "// GL api functions.\n")
8124 for func
in self
.original_functions
:
8125 func
.WriteGLES2Implementation(file)
8128 def WriteGLES2TraceImplementationHeader(self
, filename
):
8129 """Writes the GLES2 Trace Implementation header."""
8130 file = CHeaderWriter(
8132 "// This file is included by gles2_trace_implementation.h\n")
8133 for func
in self
.original_functions
:
8134 func
.WriteGLES2TraceImplementationHeader(file)
8137 def WriteGLES2TraceImplementation(self
, filename
):
8138 """Writes the GLES2 Trace Implementation."""
8139 file = CHeaderWriter(
8141 "// This file is included by gles2_trace_implementation.cc\n")
8142 for func
in self
.original_functions
:
8143 func
.WriteGLES2TraceImplementation(file)
8146 def WriteGLES2ImplementationUnitTests(self
, filename
):
8147 """Writes the GLES2 helper header."""
8148 file = CHeaderWriter(
8150 "// This file is included by gles2_implementation.h to declare the\n"
8151 "// GL api functions.\n")
8152 for func
in self
.original_functions
:
8153 func
.WriteGLES2ImplementationUnitTest(file)
8156 def WriteServiceUtilsHeader(self
, filename
):
8157 """Writes the gles2 auto generated utility header."""
8158 file = CHeaderWriter(filename
)
8159 for name
in sorted(_NAMED_TYPE_INFO
.keys()):
8160 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8161 if named_type
.IsConstant():
8163 file.Write("ValueValidator<%s> %s;\n" %
8164 (named_type
.GetType(), ToUnderscore(name
)))
8168 def WriteServiceUtilsImplementation(self
, filename
):
8169 """Writes the gles2 auto generated utility implementation."""
8170 file = CHeaderWriter(filename
)
8171 names
= sorted(_NAMED_TYPE_INFO
.keys())
8173 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8174 if named_type
.IsConstant():
8176 if named_type
.GetValidValues():
8177 file.Write("static const %s valid_%s_table[] = {\n" %
8178 (named_type
.GetType(), ToUnderscore(name
)))
8179 for value
in named_type
.GetValidValues():
8180 file.Write(" %s,\n" % value
)
8183 file.Write("Validators::Validators()")
8185 for count
, name
in enumerate(names
):
8186 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8187 if named_type
.IsConstant():
8189 if named_type
.GetValidValues():
8190 code
= """%(pre)s%(name)s(
8191 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
8193 code
= "%(pre)s%(name)s()"
8195 'name': ToUnderscore(name
),
8200 file.Write("}\n\n");
8203 def WriteCommonUtilsHeader(self
, filename
):
8204 """Writes the gles2 common utility header."""
8205 file = CHeaderWriter(filename
)
8206 type_infos
= sorted(_NAMED_TYPE_INFO
.keys())
8207 for type_info
in type_infos
:
8208 if _NAMED_TYPE_INFO
[type_info
]['type'] == 'GLenum':
8209 file.Write("static std::string GetString%s(uint32_t value);\n" %
8214 def WriteCommonUtilsImpl(self
, filename
):
8215 """Writes the gles2 common utility header."""
8216 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
8218 for fname
in ['../../third_party/khronos/GLES2/gl2.h',
8219 '../../third_party/khronos/GLES2/gl2ext.h',
8220 '../../gpu/GLES2/gl2chromium.h',
8221 '../../gpu/GLES2/gl2extchromium.h']:
8222 lines
= open(fname
).readlines()
8224 m
= enum_re
.match(line
)
8228 if len(value
) <= 10 and not value
in dict:
8231 file = CHeaderWriter(filename
)
8232 file.Write("static const GLES2Util::EnumToString "
8233 "enum_to_string_table[] = {\n")
8235 file.Write(' { %s, "%s", },\n' % (value
, dict[value
]))
8238 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
8239 enum_to_string_table;
8240 const size_t GLES2Util::enum_to_string_table_len_ =
8241 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
8245 enums
= sorted(_NAMED_TYPE_INFO
.keys())
8247 if _NAMED_TYPE_INFO
[enum
]['type'] == 'GLenum':
8248 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
8250 if len(_NAMED_TYPE_INFO
[enum
]['valid']) > 0:
8251 file.Write(" static const EnumToString string_table[] = {\n")
8252 for value
in _NAMED_TYPE_INFO
[enum
]['valid']:
8253 file.Write(' { %s, "%s" },\n' % (value
, value
))
8255 return GLES2Util::GetQualifiedEnumString(
8256 string_table, arraysize(string_table), value);
8261 file.Write(""" return GLES2Util::GetQualifiedEnumString(
8268 def WritePepperGLES2Interface(self
, filename
, dev
):
8269 """Writes the Pepper OpenGLES interface definition."""
8270 file = CHeaderWriter(
8272 "// OpenGL ES interface.\n")
8274 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
8276 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
8278 file.Write("\n#ifndef __gl2_h_\n")
8279 for (k
, v
) in _GL_TYPES
.iteritems():
8280 file.Write("typedef %s %s;\n" % (v
, k
))
8281 file.Write("#ifdef _WIN64\n")
8282 for (k
, v
) in _GL_TYPES_64
.iteritems():
8283 file.Write("typedef %s %s;\n" % (v
, k
))
8284 file.Write("#else\n")
8285 for (k
, v
) in _GL_TYPES_32
.iteritems():
8286 file.Write("typedef %s %s;\n" % (v
, k
))
8287 file.Write("#endif // _WIN64\n")
8288 file.Write("#endif // __gl2_h_\n\n")
8290 for interface
in self
.pepper_interfaces
:
8291 if interface
.dev
!= dev
:
8293 file.Write("#define %s_1_0 \"%s;1.0\"\n" %
8294 (interface
.GetInterfaceName(), interface
.GetInterfaceString()))
8295 file.Write("#define %s %s_1_0\n" %
8296 (interface
.GetInterfaceName(), interface
.GetInterfaceName()))
8298 file.Write("\nstruct %s {\n" % interface
.GetStructName())
8299 for func
in self
.original_functions
:
8300 if not func
.InPepperInterface(interface
):
8303 original_arg
= func
.MakeTypedPepperArgString("")
8304 context_arg
= "PP_Resource context"
8305 if len(original_arg
):
8306 arg
= context_arg
+ ", " + original_arg
8309 file.Write(" %s (*%s)(%s);\n" %
8310 (func
.return_type
, func
.GetPepperName(), arg
))
8311 file.Write("};\n\n")
8316 def WritePepperGLES2Implementation(self
, filename
):
8317 """Writes the Pepper OpenGLES interface implementation."""
8319 file = CWriter(filename
)
8320 file.Write(_LICENSE
)
8321 file.Write(_DO_NOT_EDIT_WARNING
)
8323 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
8324 file.Write("#include \"base/logging.h\"\n")
8325 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
8326 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
8327 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
8329 file.Write("namespace ppapi {\n\n")
8330 file.Write("namespace {\n\n")
8332 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
8335 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
8337 file.Write(" DCHECK(enter);\n")
8338 file.Write(" DCHECK(enter->succeeded());\n")
8339 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
8341 file.Write("}\n\n");
8343 for func
in self
.original_functions
:
8344 if not func
.InAnyPepperExtension():
8347 original_arg
= func
.MakeTypedPepperArgString("")
8348 context_arg
= "PP_Resource context_id"
8349 if len(original_arg
):
8350 arg
= context_arg
+ ", " + original_arg
8353 file.Write("%s %s(%s) {\n" %
8354 (func
.return_type
, func
.GetPepperName(), arg
))
8355 file.Write(" Enter3D enter(context_id, true);\n")
8356 file.Write(" if (enter.succeeded()) {\n")
8358 return_str
= "" if func
.return_type
== "void" else "return "
8359 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
8360 (return_str
, func
.original_name
,
8361 func
.MakeOriginalArgString("")))
8363 if func
.return_type
== "void":
8366 file.Write(" else {\n")
8367 file.Write(" return %s;\n" % func
.GetErrorReturnString())
8371 file.Write("} // namespace\n")
8373 for interface
in self
.pepper_interfaces
:
8374 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
8375 (interface
.GetStructName(), interface
.GetName()))
8376 file.Write(" static const struct %s "
8377 "ppb_opengles2 = {\n" % interface
.GetStructName())
8379 file.Write(",\n &".join(
8380 f
.GetPepperName() for f
in self
.original_functions
8381 if f
.InPepperInterface(interface
)))
8385 file.Write(" return &ppb_opengles2;\n")
8388 file.Write("} // namespace ppapi\n")
8391 def WriteGLES2ToPPAPIBridge(self
, filename
):
8392 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
8394 file = CWriter(filename
)
8395 file.Write(_LICENSE
)
8396 file.Write(_DO_NOT_EDIT_WARNING
)
8398 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
8399 file.Write("#define GL_GLEXT_PROTOTYPES\n")
8400 file.Write("#endif\n")
8401 file.Write("#include <GLES2/gl2.h>\n")
8402 file.Write("#include <GLES2/gl2ext.h>\n")
8403 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
8405 for func
in self
.original_functions
:
8406 if not func
.InAnyPepperExtension():
8409 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
8411 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
8412 (func
.return_type
, func
.GetPepperName(),
8413 func
.MakeTypedPepperArgString("")))
8414 return_str
= "" if func
.return_type
== "void" else "return "
8415 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
8416 original_arg
= func
.MakeOriginalArgString("")
8417 context_arg
= "glGetCurrentContextPPAPI()"
8418 if len(original_arg
):
8419 arg
= context_arg
+ ", " + original_arg
8422 if interface
.GetName():
8423 file.Write(" const struct %s* ext = %s;\n" %
8424 (interface
.GetStructName(), interface_str
))
8425 file.Write(" if (ext)\n")
8426 file.Write(" %sext->%s(%s);\n" %
8427 (return_str
, func
.GetPepperName(), arg
))
8429 file.Write(" %s0;\n" % return_str
)
8431 file.Write(" %s%s->%s(%s);\n" %
8432 (return_str
, interface_str
, func
.GetPepperName(), arg
))
8436 def WriteMojoGLCallVisitor(self
, filename
):
8437 """Provides the GL implementation for mojo"""
8438 file = CWriter(filename
)
8439 file.Write(_LICENSE
)
8440 file.Write(_DO_NOT_EDIT_WARNING
)
8442 for func
in self
.original_functions
:
8443 if not func
.IsCoreGLFunction():
8445 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
8446 (func
.name
, func
.return_type
,
8447 func
.MakeTypedOriginalArgString(""),
8448 func
.MakeOriginalArgString("")))
8452 def WriteMojoGLCallVisitorForExtension(self
, filename
, extension
):
8453 """Provides the GL implementation for mojo for a particular extension"""
8454 file = CWriter(filename
)
8455 file.Write(_LICENSE
)
8456 file.Write(_DO_NOT_EDIT_WARNING
)
8458 for func
in self
.original_functions
:
8459 if func
.GetInfo("extension") != extension
:
8461 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
8462 (func
.name
, func
.return_type
,
8463 func
.MakeTypedOriginalArgString(""),
8464 func
.MakeOriginalArgString("")))
8468 def Format(generated_files
):
8469 for filename
in generated_files
:
8470 call(["clang-format", "-i", "-style=chromium", filename
])
8473 """This is the main function."""
8474 parser
= OptionParser()
8477 help="base directory for resulting files, under chrome/src. default is "
8478 "empty. Use this if you want the result stored under gen.")
8480 "-v", "--verbose", action
="store_true",
8481 help="prints more output.")
8483 (options
, args
) = parser
.parse_args(args
=argv
)
8485 # Add in states and capabilites to GLState
8486 gl_state_valid
= _NAMED_TYPE_INFO
['GLState']['valid']
8487 for state_name
in sorted(_STATES
.keys()):
8488 state
= _STATES
[state_name
]
8489 if 'extension_flag' in state
:
8492 if not state
['enum'] in gl_state_valid
:
8493 gl_state_valid
.append(state
['enum'])
8495 for item
in state
['states']:
8496 if 'extension_flag' in item
:
8498 if not item
['enum'] in gl_state_valid
:
8499 gl_state_valid
.append(item
['enum'])
8500 for capability
in _CAPABILITY_FLAGS
:
8501 valid_value
= "GL_%s" % capability
['name'].upper()
8502 if not valid_value
in gl_state_valid
:
8503 gl_state_valid
.append(valid_value
)
8505 # This script lives under gpu/command_buffer, cd to base directory.
8506 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
8508 gen
= GLGenerator(options
.verbose
)
8509 gen
.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
8511 # Support generating files under gen/
8512 if options
.output_dir
!= None:
8513 os
.chdir(options
.output_dir
)
8515 gen
.WritePepperGLES2Interface("ppapi/c/ppb_opengles2.h", False)
8516 gen
.WritePepperGLES2Interface("ppapi/c/dev/ppb_opengles2ext_dev.h", True)
8517 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
8518 gen
.WritePepperGLES2Implementation(
8519 "ppapi/shared_impl/ppb_opengles2_shared.cc")
8520 os
.chdir("gpu/command_buffer")
8521 gen
.WriteCommandIds("common/gles2_cmd_ids_autogen.h")
8522 gen
.WriteFormat("common/gles2_cmd_format_autogen.h")
8523 gen
.WriteFormatTest("common/gles2_cmd_format_test_autogen.h")
8524 gen
.WriteGLES2InterfaceHeader("client/gles2_interface_autogen.h")
8525 gen
.WriteGLES2InterfaceStub("client/gles2_interface_stub_autogen.h")
8526 gen
.WriteGLES2InterfaceStubImpl(
8527 "client/gles2_interface_stub_impl_autogen.h")
8528 gen
.WriteGLES2ImplementationHeader("client/gles2_implementation_autogen.h")
8529 gen
.WriteGLES2Implementation("client/gles2_implementation_impl_autogen.h")
8530 gen
.WriteGLES2ImplementationUnitTests(
8531 "client/gles2_implementation_unittest_autogen.h")
8532 gen
.WriteGLES2TraceImplementationHeader(
8533 "client/gles2_trace_implementation_autogen.h")
8534 gen
.WriteGLES2TraceImplementation(
8535 "client/gles2_trace_implementation_impl_autogen.h")
8536 gen
.WriteGLES2CLibImplementation("client/gles2_c_lib_autogen.h")
8537 gen
.WriteCmdHelperHeader("client/gles2_cmd_helper_autogen.h")
8538 gen
.WriteServiceImplementation("service/gles2_cmd_decoder_autogen.h")
8539 gen
.WriteServiceContextStateHeader("service/context_state_autogen.h")
8540 gen
.WriteServiceContextStateImpl("service/context_state_impl_autogen.h")
8541 gen
.WriteClientContextStateHeader("client/client_context_state_autogen.h")
8542 gen
.WriteClientContextStateImpl(
8543 "client/client_context_state_impl_autogen.h")
8544 gen
.WriteServiceUnitTests("service/gles2_cmd_decoder_unittest_%d_autogen.h")
8545 gen
.WriteServiceUnitTestsForExtensions(
8546 "service/gles2_cmd_decoder_unittest_extensions_autogen.h")
8547 gen
.WriteServiceUtilsHeader("service/gles2_cmd_validation_autogen.h")
8548 gen
.WriteServiceUtilsImplementation(
8549 "service/gles2_cmd_validation_implementation_autogen.h")
8550 gen
.WriteCommonUtilsHeader("common/gles2_cmd_utils_autogen.h")
8551 gen
.WriteCommonUtilsImpl("common/gles2_cmd_utils_implementation_autogen.h")
8552 gen
.WriteGLES2Header("../GLES2/gl2chromium_autogen.h")
8553 mojo_gles2_prefix
= "../../mojo/public/c/gles2/gles2_call_visitor"
8554 gen
.WriteMojoGLCallVisitor(mojo_gles2_prefix
+ "_autogen.h")
8555 gen
.WriteMojoGLCallVisitorForExtension(
8556 mojo_gles2_prefix
+ "_chromium_texture_mailbox_autogen.h",
8557 "CHROMIUM_texture_mailbox")
8558 gen
.WriteMojoGLCallVisitorForExtension(
8559 mojo_gles2_prefix
+ "_chromium_sync_point_autogen.h",
8560 "CHROMIUM_sync_point")
8563 "common/gles2_cmd_format_autogen.h",
8564 "common/gles2_cmd_format_test_autogen.h",
8565 "common/gles2_cmd_ids_autogen.h",
8566 "common/gles2_cmd_utils_autogen.h",
8567 "common/gles2_cmd_utils_implementation_autogen.h",
8568 "client/client_context_state_autogen.h",
8569 "client/client_context_state_impl_autogen.h",
8570 "client/gles2_cmd_helper_autogen.h",
8571 "client/gles2_c_lib_autogen.h",
8572 "client/gles2_implementation_autogen.h",
8573 "client/gles2_implementation_impl_autogen.h",
8574 "client/gles2_implementation_unittest_autogen.h",
8575 "client/gles2_interface_autogen.h",
8576 "client/gles2_interface_stub_autogen.h",
8577 "client/gles2_interface_stub_impl_autogen.h",
8578 "client/gles2_trace_implementation_autogen.h",
8579 "client/gles2_trace_implementation_impl_autogen.h",
8580 "service/context_state_autogen.h",
8581 "service/context_state_impl_autogen.h",
8582 "service/gles2_cmd_decoder_autogen.h",
8583 "service/gles2_cmd_decoder_unittest_0_autogen.h",
8584 "service/gles2_cmd_decoder_unittest_1_autogen.h",
8585 "service/gles2_cmd_decoder_unittest_2_autogen.h",
8586 "service/gles2_cmd_decoder_unittest_3_autogen.h",
8587 "service/gles2_cmd_validation_autogen.h",
8588 "service/gles2_cmd_validation_implementation_autogen.h"])
8590 mojo_gles2_prefix
= "mojo/public/c/gles2/gles2_call_visitor"
8592 "gpu/GLES2/gl2chromium_autogen.h",
8593 mojo_gles2_prefix
+ "_autogen.h",
8594 mojo_gles2_prefix
+ "_chromium_texture_mailbox_autogen.h",
8595 mojo_gles2_prefix
+ "_chromium_sync_point_autogen.h",
8596 "ppapi/c/dev/ppb_opengles2ext_dev.h",
8597 "ppapi/c/ppb_opengles2.h",
8598 "ppapi/lib/gl/gles2/gles2.c",
8599 "ppapi/shared_impl/ppb_opengles2_shared.cc"])
8602 print "%d errors" % gen
.errors
8607 if __name__
== '__main__':
8608 sys
.exit(main(sys
.argv
[1:]))