2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """code generator for GLES2 command buffers."""
14 from optparse
import OptionParser
15 from subprocess
import call
18 _SIZE_OF_COMMAND_HEADER
= 4
19 _FIRST_SPECIFIC_COMMAND_ID
= 256
21 _LICENSE
= """// Copyright 2014 The Chromium Authors. All rights reserved.
22 // Use of this source code is governed by a BSD-style license that can be
23 // found in the LICENSE file.
27 _DO_NOT_EDIT_WARNING
= """// This file is auto-generated from
28 // gpu/command_buffer/build_gles2_cmd_buffer.py
29 // It's formatted by clang-format using chromium coding style:
30 // clang-format -i -style=chromium filename
35 # This string is copied directly out of the gl2.h file from GLES2.0
39 # *) Any argument that is a resourceID has been changed to GLid<Type>.
40 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
41 # If it's allowed to not exist it's GLidBind<Type>
43 # *) All GLenums have been changed to GLenumTypeOfEnum
46 'GLenum': 'unsigned int',
47 'GLboolean': 'unsigned char',
48 'GLbitfield': 'unsigned int',
49 'GLbyte': 'signed char',
53 'GLubyte': 'unsigned char',
54 'GLushort': 'unsigned short',
55 'GLuint': 'unsigned int',
64 'GLintptr': 'long int',
65 'GLsizeiptr': 'long int'
69 'GLintptr': 'long long int',
70 'GLsizeiptr': 'long long int'
73 # Capabilites selected with glEnable
76 {'name': 'cull_face'},
77 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
78 {'name': 'dither', 'default': True},
79 {'name': 'polygon_offset_fill'},
80 {'name': 'sample_alpha_to_coverage'},
81 {'name': 'sample_coverage'},
82 {'name': 'scissor_test'},
83 {'name': 'stencil_test',
84 'state_flag': 'framebuffer_state_.clear_state_dirty'},
91 'enum': 'GL_COLOR_CLEAR_VALUE',
93 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
94 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
95 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
101 'func': 'ClearDepth',
102 'enum': 'GL_DEPTH_CLEAR_VALUE',
104 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
110 'enum': 'GL_COLOR_WRITEMASK',
113 'name': 'color_mask_red',
119 'name': 'color_mask_green',
125 'name': 'color_mask_blue',
131 'name': 'color_mask_alpha',
137 'state_flag': 'framebuffer_state_.clear_state_dirty',
141 'func': 'ClearStencil',
142 'enum': 'GL_STENCIL_CLEAR_VALUE',
144 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
149 'func': 'BlendColor',
150 'enum': 'GL_BLEND_COLOR',
152 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
153 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
154 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
155 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
160 'func': 'BlendEquationSeparate',
163 'name': 'blend_equation_rgb',
165 'enum': 'GL_BLEND_EQUATION_RGB',
166 'default': 'GL_FUNC_ADD',
169 'name': 'blend_equation_alpha',
171 'enum': 'GL_BLEND_EQUATION_ALPHA',
172 'default': 'GL_FUNC_ADD',
178 'func': 'BlendFuncSeparate',
181 'name': 'blend_source_rgb',
183 'enum': 'GL_BLEND_SRC_RGB',
187 'name': 'blend_dest_rgb',
189 'enum': 'GL_BLEND_DST_RGB',
190 'default': 'GL_ZERO',
193 'name': 'blend_source_alpha',
195 'enum': 'GL_BLEND_SRC_ALPHA',
199 'name': 'blend_dest_alpha',
201 'enum': 'GL_BLEND_DST_ALPHA',
202 'default': 'GL_ZERO',
208 'func': 'PolygonOffset',
211 'name': 'polygon_offset_factor',
213 'enum': 'GL_POLYGON_OFFSET_FACTOR',
217 'name': 'polygon_offset_units',
219 'enum': 'GL_POLYGON_OFFSET_UNITS',
227 'enum': 'GL_CULL_FACE_MODE',
232 'default': 'GL_BACK',
239 'enum': 'GL_FRONT_FACE',
240 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
245 'enum': 'GL_DEPTH_FUNC',
246 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
250 'func': 'DepthRange',
251 'enum': 'GL_DEPTH_RANGE',
253 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
254 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
259 'func': 'SampleCoverage',
262 'name': 'sample_coverage_value',
264 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
268 'name': 'sample_coverage_invert',
270 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
277 'func': 'StencilMaskSeparate',
278 'state_flag': 'framebuffer_state_.clear_state_dirty',
281 'name': 'stencil_front_writemask',
283 'enum': 'GL_STENCIL_WRITEMASK',
284 'default': '0xFFFFFFFFU',
288 'name': 'stencil_back_writemask',
290 'enum': 'GL_STENCIL_BACK_WRITEMASK',
291 'default': '0xFFFFFFFFU',
298 'func': 'StencilOpSeparate',
301 'name': 'stencil_front_fail_op',
303 'enum': 'GL_STENCIL_FAIL',
304 'default': 'GL_KEEP',
307 'name': 'stencil_front_z_fail_op',
309 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
310 'default': 'GL_KEEP',
313 'name': 'stencil_front_z_pass_op',
315 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
316 'default': 'GL_KEEP',
319 'name': 'stencil_back_fail_op',
321 'enum': 'GL_STENCIL_BACK_FAIL',
322 'default': 'GL_KEEP',
325 'name': 'stencil_back_z_fail_op',
327 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
328 'default': 'GL_KEEP',
331 'name': 'stencil_back_z_pass_op',
333 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
334 'default': 'GL_KEEP',
340 'func': 'StencilFuncSeparate',
343 'name': 'stencil_front_func',
345 'enum': 'GL_STENCIL_FUNC',
346 'default': 'GL_ALWAYS',
349 'name': 'stencil_front_ref',
351 'enum': 'GL_STENCIL_REF',
355 'name': 'stencil_front_mask',
357 'enum': 'GL_STENCIL_VALUE_MASK',
358 'default': '0xFFFFFFFFU',
361 'name': 'stencil_back_func',
363 'enum': 'GL_STENCIL_BACK_FUNC',
364 'default': 'GL_ALWAYS',
367 'name': 'stencil_back_ref',
369 'enum': 'GL_STENCIL_BACK_REF',
373 'name': 'stencil_back_mask',
375 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
376 'default': '0xFFFFFFFFU',
381 'type': 'NamedParameter',
385 'name': 'hint_generate_mipmap',
387 'enum': 'GL_GENERATE_MIPMAP_HINT',
388 'default': 'GL_DONT_CARE'
391 'name': 'hint_fragment_shader_derivative',
393 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
394 'default': 'GL_DONT_CARE',
395 'extension_flag': 'oes_standard_derivatives'
400 'type': 'NamedParameter',
401 'func': 'PixelStorei',
404 'name': 'pack_alignment',
406 'enum': 'GL_PACK_ALIGNMENT',
410 'name': 'unpack_alignment',
412 'enum': 'GL_UNPACK_ALIGNMENT',
417 # TODO: Consider implemenenting these states
422 'enum': 'GL_LINE_WIDTH',
425 'name': 'line_width',
428 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
435 'enum': 'GL_DEPTH_WRITEMASK',
438 'name': 'depth_mask',
444 'state_flag': 'framebuffer_state_.clear_state_dirty',
449 'enum': 'GL_SCISSOR_BOX',
451 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
456 'expected': 'kViewportX',
462 'expected': 'kViewportY',
465 'name': 'scissor_width',
468 'expected': 'kViewportWidth',
471 'name': 'scissor_height',
474 'expected': 'kViewportHeight',
481 'enum': 'GL_VIEWPORT',
483 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
485 'name': 'viewport_x',
488 'expected': 'kViewportX',
491 'name': 'viewport_y',
494 'expected': 'kViewportY',
497 'name': 'viewport_width',
500 'expected': 'kViewportWidth',
503 'name': 'viewport_height',
506 'expected': 'kViewportHeight',
510 'MatrixValuesCHROMIUM': {
511 'type': 'NamedParameter',
512 'func': 'MatrixLoadfEXT',
514 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
515 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
516 'name': 'modelview_matrix',
519 '1.0f', '0.0f','0.0f','0.0f',
520 '0.0f', '1.0f','0.0f','0.0f',
521 '0.0f', '0.0f','1.0f','0.0f',
522 '0.0f', '0.0f','0.0f','1.0f',
524 'extension_flag': 'chromium_path_rendering',
526 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
527 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
528 'name': 'projection_matrix',
531 '1.0f', '0.0f','0.0f','0.0f',
532 '0.0f', '1.0f','0.0f','0.0f',
533 '0.0f', '0.0f','1.0f','0.0f',
534 '0.0f', '0.0f','0.0f','1.0f',
536 'extension_flag': 'chromium_path_rendering',
542 # Named type info object represents a named type that is used in OpenGL call
543 # arguments. Each named type defines a set of valid OpenGL call arguments. The
544 # named types are used in 'cmd_buffer_functions.txt'.
545 # type: The actual GL type of the named type.
546 # valid: The list of values that are valid for both the client and the service.
547 # valid_es3: The list of values that are valid in OpenGL ES 3, but not ES 2.
548 # invalid: Examples of invalid values for the type. At least these values
549 # should be tested to be invalid.
550 # deprecated_es3: The list of values that are valid in OpenGL ES 2, but
551 # deprecated in ES 3.
552 # is_complete: The list of valid values of type are final and will not be
553 # modified during runtime.
562 'GL_LINEAR_MIPMAP_LINEAR',
565 'FrameBufferTarget': {
571 'GL_DRAW_FRAMEBUFFER' ,
572 'GL_READ_FRAMEBUFFER' ,
575 'RenderBufferTarget': {
588 'GL_ELEMENT_ARRAY_BUFFER',
591 'GL_COPY_READ_BUFFER',
592 'GL_COPY_WRITE_BUFFER',
593 'GL_PIXEL_PACK_BUFFER',
594 'GL_PIXEL_UNPACK_BUFFER',
595 'GL_TRANSFORM_FEEDBACK_BUFFER',
602 'IndexedBufferTarget': {
605 'GL_TRANSFORM_FEEDBACK_BUFFER',
617 'GL_MAP_INVALIDATE_RANGE_BIT',
618 'GL_MAP_INVALIDATE_BUFFER_BIT',
619 'GL_MAP_FLUSH_EXPLICIT_BIT',
620 'GL_MAP_UNSYNCHRONIZED_BIT',
623 'GL_SYNC_FLUSH_COMMANDS_BIT',
675 'CompressedTextureFormat': {
683 # NOTE: State an Capability entries added later.
685 'GL_ALIASED_LINE_WIDTH_RANGE',
686 'GL_ALIASED_POINT_SIZE_RANGE',
688 'GL_ARRAY_BUFFER_BINDING',
690 'GL_COMPRESSED_TEXTURE_FORMATS',
691 'GL_CURRENT_PROGRAM',
694 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
695 'GL_FRAMEBUFFER_BINDING',
696 'GL_GENERATE_MIPMAP_HINT',
698 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
699 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
700 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
701 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
702 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
703 'GL_MAX_RENDERBUFFER_SIZE',
704 'GL_MAX_TEXTURE_IMAGE_UNITS',
705 'GL_MAX_TEXTURE_SIZE',
706 'GL_MAX_VARYING_VECTORS',
707 'GL_MAX_VERTEX_ATTRIBS',
708 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
709 'GL_MAX_VERTEX_UNIFORM_VECTORS',
710 'GL_MAX_VIEWPORT_DIMS',
711 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
712 'GL_NUM_SHADER_BINARY_FORMATS',
715 'GL_RENDERBUFFER_BINDING',
717 'GL_SAMPLE_COVERAGE_INVERT',
718 'GL_SAMPLE_COVERAGE_VALUE',
721 'GL_SHADER_BINARY_FORMATS',
722 'GL_SHADER_COMPILER',
725 'GL_TEXTURE_BINDING_2D',
726 'GL_TEXTURE_BINDING_CUBE_MAP',
727 'GL_UNPACK_ALIGNMENT',
728 'GL_UNPACK_FLIP_Y_CHROMIUM',
729 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
730 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
731 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
732 # we can add this because we emulate it if the driver does not support it.
733 'GL_VERTEX_ARRAY_BINDING_OES',
740 'GetTexParamTarget': {
744 'GL_TEXTURE_CUBE_MAP',
747 'GL_PROXY_TEXTURE_CUBE_MAP',
754 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
755 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
756 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
757 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
758 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
759 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
762 'GL_PROXY_TEXTURE_CUBE_MAP',
769 'GL_TEXTURE_2D_ARRAY',
775 'TextureBindTarget': {
779 'GL_TEXTURE_CUBE_MAP',
783 'GL_TEXTURE_2D_ARRAY',
790 'TransformFeedbackBindTarget': {
793 'GL_TRANSFORM_FEEDBACK',
799 'TransformFeedbackPrimitiveMode': {
814 'GL_FRAGMENT_SHADER',
817 'GL_GEOMETRY_SHADER',
853 'GL_FUNC_REVERSE_SUBTRACT',
866 'GL_ONE_MINUS_SRC_COLOR',
868 'GL_ONE_MINUS_DST_COLOR',
870 'GL_ONE_MINUS_SRC_ALPHA',
872 'GL_ONE_MINUS_DST_ALPHA',
874 'GL_ONE_MINUS_CONSTANT_COLOR',
876 'GL_ONE_MINUS_CONSTANT_ALPHA',
877 'GL_SRC_ALPHA_SATURATE',
886 'GL_ONE_MINUS_SRC_COLOR',
888 'GL_ONE_MINUS_DST_COLOR',
890 'GL_ONE_MINUS_SRC_ALPHA',
892 'GL_ONE_MINUS_DST_ALPHA',
894 'GL_ONE_MINUS_CONSTANT_COLOR',
896 'GL_ONE_MINUS_CONSTANT_ALPHA',
901 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
],
948 'GL_COLOR_ATTACHMENT0',
949 'GL_DEPTH_ATTACHMENT',
950 'GL_STENCIL_ATTACHMENT',
953 'BackbufferAttachment': {
968 'GL_PIXEL_PACK_BUFFER',
974 'GL_INTERLEAVED_ATTRIBS',
975 'GL_SEPARATE_ATTRIBS',
978 'GL_PIXEL_PACK_BUFFER',
981 'FrameBufferParameter': {
984 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
985 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
986 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
987 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
993 'GL_PATH_PROJECTION_CHROMIUM',
994 'GL_PATH_MODELVIEW_CHROMIUM',
997 'ProgramParameter': {
1002 'GL_VALIDATE_STATUS',
1003 'GL_INFO_LOG_LENGTH',
1004 'GL_ATTACHED_SHADERS',
1005 'GL_ACTIVE_ATTRIBUTES',
1006 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1007 'GL_ACTIVE_UNIFORMS',
1008 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1011 'QueryObjectParameter': {
1014 'GL_QUERY_RESULT_EXT',
1015 'GL_QUERY_RESULT_AVAILABLE_EXT',
1021 'GL_CURRENT_QUERY_EXT',
1027 'GL_ANY_SAMPLES_PASSED_EXT',
1028 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1029 'GL_COMMANDS_ISSUED_CHROMIUM',
1030 'GL_LATENCY_QUERY_CHROMIUM',
1031 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1032 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1033 'GL_COMMANDS_COMPLETED_CHROMIUM',
1036 'RenderBufferParameter': {
1039 'GL_RENDERBUFFER_RED_SIZE',
1040 'GL_RENDERBUFFER_GREEN_SIZE',
1041 'GL_RENDERBUFFER_BLUE_SIZE',
1042 'GL_RENDERBUFFER_ALPHA_SIZE',
1043 'GL_RENDERBUFFER_DEPTH_SIZE',
1044 'GL_RENDERBUFFER_STENCIL_SIZE',
1045 'GL_RENDERBUFFER_WIDTH',
1046 'GL_RENDERBUFFER_HEIGHT',
1047 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1050 'SamplerParameter': {
1053 'GL_TEXTURE_MAG_FILTER',
1054 'GL_TEXTURE_MIN_FILTER',
1055 'GL_TEXTURE_MIN_LOD',
1056 'GL_TEXTURE_MAX_LOD',
1057 'GL_TEXTURE_WRAP_S',
1058 'GL_TEXTURE_WRAP_T',
1059 'GL_TEXTURE_WRAP_R',
1060 'GL_TEXTURE_COMPARE_MODE',
1061 'GL_TEXTURE_COMPARE_FUNC',
1064 'GL_GENERATE_MIPMAP',
1067 'ShaderParameter': {
1072 'GL_COMPILE_STATUS',
1073 'GL_INFO_LOG_LENGTH',
1074 'GL_SHADER_SOURCE_LENGTH',
1075 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1078 'ShaderPrecision': {
1095 'GL_SHADING_LANGUAGE_VERSION',
1099 'TextureParameter': {
1102 'GL_TEXTURE_MAG_FILTER',
1103 'GL_TEXTURE_MIN_FILTER',
1104 'GL_TEXTURE_POOL_CHROMIUM',
1105 'GL_TEXTURE_WRAP_S',
1106 'GL_TEXTURE_WRAP_T',
1109 'GL_GENERATE_MIPMAP',
1115 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1116 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1119 'TextureWrapMode': {
1123 'GL_MIRRORED_REPEAT',
1127 'TextureMinFilterMode': {
1132 'GL_NEAREST_MIPMAP_NEAREST',
1133 'GL_LINEAR_MIPMAP_NEAREST',
1134 'GL_NEAREST_MIPMAP_LINEAR',
1135 'GL_LINEAR_MIPMAP_LINEAR',
1138 'TextureMagFilterMode': {
1149 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1152 'VertexAttribute': {
1155 # some enum that the decoder actually passes through to GL needs
1156 # to be the first listed here since it's used in unit tests.
1157 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1158 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1159 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1160 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1161 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1162 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1163 'GL_CURRENT_VERTEX_ATTRIB',
1169 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1175 'GL_GENERATE_MIPMAP_HINT',
1178 'GL_PERSPECTIVE_CORRECTION_HINT',
1192 'GL_PACK_ALIGNMENT',
1193 'GL_UNPACK_ALIGNMENT',
1194 'GL_UNPACK_FLIP_Y_CHROMIUM',
1195 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
1196 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
1199 'GL_PACK_SWAP_BYTES',
1200 'GL_UNPACK_SWAP_BYTES',
1203 'PixelStoreAlignment': {
1216 'ReadPixelFormat': {
1228 'GL_UNSIGNED_SHORT_5_6_5',
1229 'GL_UNSIGNED_SHORT_4_4_4_4',
1230 'GL_UNSIGNED_SHORT_5_5_5_1',
1234 'GL_UNSIGNED_SHORT',
1240 'GL_UNSIGNED_INT_2_10_10_10_REV',
1241 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1242 'GL_UNSIGNED_INT_5_9_9_9_REV',
1243 'GL_UNSIGNED_INT_24_8',
1244 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1247 'GL_UNSIGNED_BYTE_3_3_2',
1254 'GL_UNSIGNED_SHORT_5_6_5',
1255 'GL_UNSIGNED_SHORT_4_4_4_4',
1256 'GL_UNSIGNED_SHORT_5_5_5_1',
1263 'RenderBufferFormat': {
1269 'GL_DEPTH_COMPONENT16',
1270 'GL_STENCIL_INDEX8',
1273 'ShaderBinaryFormat': {
1296 'GL_LUMINANCE_ALPHA',
1307 'GL_DEPTH_COMPONENT',
1315 'TextureInternalFormat': {
1320 'GL_LUMINANCE_ALPHA',
1349 'GL_R11F_G11F_B10F',
1374 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1375 # We will reject them dynamically in GPU command buffer.
1376 'GL_DEPTH_COMPONENT16',
1377 'GL_DEPTH_COMPONENT24',
1378 'GL_DEPTH_COMPONENT32F',
1379 'GL_DEPTH24_STENCIL8',
1380 'GL_DEPTH32F_STENCIL8',
1387 'TextureInternalFormatStorage': {
1394 'GL_LUMINANCE8_EXT',
1395 'GL_LUMINANCE8_ALPHA8_EXT',
1422 'GL_R11F_G11F_B10F',
1444 'GL_DEPTH_COMPONENT16',
1445 'GL_DEPTH_COMPONENT24',
1446 'GL_DEPTH_COMPONENT32F',
1447 'GL_DEPTH24_STENCIL8',
1448 'GL_DEPTH32F_STENCIL8',
1449 'GL_COMPRESSED_R11_EAC',
1450 'GL_COMPRESSED_SIGNED_R11_EAC',
1451 'GL_COMPRESSED_RG11_EAC',
1452 'GL_COMPRESSED_SIGNED_RG11_EAC',
1453 'GL_COMPRESSED_RGB8_ETC2',
1454 'GL_COMPRESSED_SRGB8_ETC2',
1455 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1456 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1457 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1458 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1462 'GL_LUMINANCE8_EXT',
1463 'GL_LUMINANCE8_ALPHA8_EXT',
1465 'GL_LUMINANCE16F_EXT',
1466 'GL_LUMINANCE_ALPHA16F_EXT',
1468 'GL_LUMINANCE32F_EXT',
1469 'GL_LUMINANCE_ALPHA32F_EXT',
1472 'ImageInternalFormat': {
1483 'GL_SCANOUT_CHROMIUM'
1486 'ValueBufferTarget': {
1489 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1492 'SubscriptionTarget': {
1495 'GL_MOUSE_POSITION_CHROMIUM',
1498 'UniformParameter': {
1503 'GL_UNIFORM_NAME_LENGTH',
1504 'GL_UNIFORM_BLOCK_INDEX',
1505 'GL_UNIFORM_OFFSET',
1506 'GL_UNIFORM_ARRAY_STRIDE',
1507 'GL_UNIFORM_MATRIX_STRIDE',
1508 'GL_UNIFORM_IS_ROW_MAJOR',
1511 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1514 'UniformBlockParameter': {
1517 'GL_UNIFORM_BLOCK_BINDING',
1518 'GL_UNIFORM_BLOCK_DATA_SIZE',
1519 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1520 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1521 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1522 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1523 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1529 'VertexAttribType': {
1535 'GL_UNSIGNED_SHORT',
1536 # 'GL_FIXED', // This is not available on Desktop GL.
1545 'is_complete': True,
1553 'VertexAttribSize': {
1568 'is_complete': True,
1577 'type': 'GLboolean',
1578 'is_complete': True,
1589 'GL_GUILTY_CONTEXT_RESET_ARB',
1590 'GL_INNOCENT_CONTEXT_RESET_ARB',
1591 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1596 'is_complete': True,
1598 'GL_SYNC_GPU_COMMANDS_COMPLETE',
1605 'type': 'GLbitfield',
1606 'is_complete': True,
1615 'type': 'GLbitfield',
1617 'GL_SYNC_FLUSH_COMMANDS_BIT',
1627 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
1629 'GL_SYNC_CONDITION',
1638 # This table specifies the different pepper interfaces that are supported for
1639 # GL commands. 'dev' is true if it's a dev interface.
1640 _PEPPER_INTERFACES
= [
1641 {'name': '', 'dev': False},
1642 {'name': 'InstancedArrays', 'dev': False},
1643 {'name': 'FramebufferBlit', 'dev': False},
1644 {'name': 'FramebufferMultisample', 'dev': False},
1645 {'name': 'ChromiumEnableFeature', 'dev': False},
1646 {'name': 'ChromiumMapSub', 'dev': False},
1647 {'name': 'Query', 'dev': False},
1648 {'name': 'VertexArrayObject', 'dev': False},
1649 {'name': 'DrawBuffers', 'dev': True},
1652 # A function info object specifies the type and other special data for the
1653 # command that will be generated. A base function info object is generated by
1654 # parsing the "cmd_buffer_functions.txt", one for each function in the
1655 # file. These function info objects can be augmented and their values can be
1656 # overridden by adding an object to the table below.
1658 # Must match function names specified in "cmd_buffer_functions.txt".
1660 # cmd_comment: A comment added to the cmd format.
1661 # type: defines which handler will be used to generate code.
1662 # decoder_func: defines which function to call in the decoder to execute the
1663 # corresponding GL command. If not specified the GL command will
1664 # be called directly.
1665 # gl_test_func: GL function that is expected to be called when testing.
1666 # cmd_args: The arguments to use for the command. This overrides generating
1667 # them based on the GL function arguments.
1668 # gen_cmd: Whether or not this function geneates a command. Default = True.
1669 # data_transfer_methods: Array of methods that are used for transfering the
1670 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1671 # The default is 'immediate' if the command has one pointer
1672 # argument, otherwise 'shm'. One command is generated for each
1673 # transfer method. Affects only commands which are not of type
1674 # 'HandWritten', 'GETn' or 'GLcharN'.
1675 # Note: the command arguments that affect this are the final args,
1676 # taking cmd_args override into consideration.
1677 # impl_func: Whether or not to generate the GLES2Implementation part of this
1679 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1681 # needs_size: If True a data_size field is added to the command.
1682 # count: The number of units per element. For PUTn or PUT types.
1683 # use_count_func: If True the actual data count needs to be computed; the count
1684 # argument specifies the maximum count.
1685 # unit_test: If False no service side unit test will be generated.
1686 # client_test: If False no client side unit test will be generated.
1687 # expectation: If False the unit test will have no expected calls.
1688 # gen_func: Name of function that generates GL resource for corresponding
1690 # states: array of states that get set by this function corresponding to
1691 # the given arguments
1692 # state_flag: name of flag that is set to true when function is called.
1693 # no_gl: no GL function is called.
1694 # valid_args: A dictionary of argument indices to args to use in unit tests
1695 # when they can not be automatically determined.
1696 # pepper_interface: The pepper interface that is used for this extension
1697 # pepper_name: The name of the function as exposed to pepper.
1698 # pepper_args: A string representing the argument list (what would appear in
1699 # C/C++ between the parentheses for the function declaration)
1700 # that the Pepper API expects for this function. Use this only if
1701 # the stable Pepper API differs from the GLES2 argument list.
1702 # invalid_test: False if no invalid test needed.
1703 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1704 # first_element_only: For PUT types, True if only the first element of an
1705 # array is used and we end up calling the single value
1706 # corresponding function. eg. TexParameteriv -> TexParameteri
1707 # extension: Function is an extension to GL and should not be exposed to
1708 # pepper unless pepper_interface is defined.
1709 # extension_flag: Function is an extension and should be enabled only when
1710 # the corresponding feature info flag is enabled. Implies
1711 # 'extension': True.
1712 # not_shared: For GENn types, True if objects can't be shared between contexts
1713 # unsafe: True = no validation is implemented on the service side and the
1714 # command is only available with --enable-unsafe-es3-apis.
1715 # id_mapping: A list of resource type names whose client side IDs need to be
1716 # mapped to service side IDs. This is only used for unsafe APIs.
1720 'decoder_func': 'DoActiveTexture',
1723 'client_test': False,
1725 'AttachShader': {'decoder_func': 'DoAttachShader'},
1726 'BindAttribLocation': {
1728 'data_transfer_methods': ['bucket'],
1733 'decoder_func': 'DoBindBuffer',
1734 'gen_func': 'GenBuffersARB',
1738 'id_mapping': [ 'Buffer' ],
1739 'gen_func': 'GenBuffersARB',
1742 'BindBufferRange': {
1744 'id_mapping': [ 'Buffer' ],
1745 'gen_func': 'GenBuffersARB',
1752 'BindFramebuffer': {
1754 'decoder_func': 'DoBindFramebuffer',
1755 'gl_test_func': 'glBindFramebufferEXT',
1756 'gen_func': 'GenFramebuffersEXT',
1759 'BindRenderbuffer': {
1761 'decoder_func': 'DoBindRenderbuffer',
1762 'gl_test_func': 'glBindRenderbufferEXT',
1763 'gen_func': 'GenRenderbuffersEXT',
1767 'id_mapping': [ 'Sampler' ],
1772 'decoder_func': 'DoBindTexture',
1773 'gen_func': 'GenTextures',
1774 # TODO(gman): remove this once client side caching works.
1775 'client_test': False,
1778 'BindTransformFeedback': {
1780 'id_mapping': [ 'TransformFeedback' ],
1783 'BlitFramebufferCHROMIUM': {
1784 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1786 'extension_flag': 'chromium_framebuffer_multisample',
1787 'pepper_interface': 'FramebufferBlit',
1788 'pepper_name': 'BlitFramebufferEXT',
1789 'defer_reads': True,
1790 'defer_draws': True,
1795 'data_transfer_methods': ['shm'],
1796 'client_test': False,
1800 'client_test': False,
1801 'decoder_func': 'DoBufferSubData',
1802 'data_transfer_methods': ['shm'],
1804 'CheckFramebufferStatus': {
1806 'decoder_func': 'DoCheckFramebufferStatus',
1807 'gl_test_func': 'glCheckFramebufferStatusEXT',
1808 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1809 'result': ['GLenum'],
1812 'decoder_func': 'DoClear',
1813 'defer_draws': True,
1818 'use_count_func': True,
1829 'use_count_func': True,
1838 'state': 'ClearColor',
1842 'state': 'ClearDepthf',
1843 'decoder_func': 'glClearDepth',
1844 'gl_test_func': 'glClearDepth',
1851 'data_transfer_methods': ['shm'],
1852 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
1853 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
1855 'result': ['GLenum'],
1859 'state': 'ColorMask',
1861 'expectation': False,
1863 'ConsumeTextureCHROMIUM': {
1864 'decoder_func': 'DoConsumeTextureCHROMIUM',
1867 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1869 'client_test': False,
1870 'extension': "CHROMIUM_texture_mailbox",
1874 'CopyBufferSubData': {
1877 'CreateAndConsumeTextureCHROMIUM': {
1878 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
1880 'type': 'HandWritten',
1881 'data_transfer_methods': ['immediate'],
1883 'client_test': False,
1884 'extension': "CHROMIUM_texture_mailbox",
1887 'GenValuebuffersCHROMIUM': {
1889 'gl_test_func': 'glGenValuebuffersCHROMIUM',
1890 'resource_type': 'Valuebuffer',
1891 'resource_types': 'Valuebuffers',
1896 'DeleteValuebuffersCHROMIUM': {
1898 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
1899 'resource_type': 'Valuebuffer',
1900 'resource_types': 'Valuebuffers',
1905 'IsValuebufferCHROMIUM': {
1907 'decoder_func': 'DoIsValuebufferCHROMIUM',
1908 'expectation': False,
1912 'BindValuebufferCHROMIUM': {
1914 'decoder_func': 'DoBindValueBufferCHROMIUM',
1915 'gen_func': 'GenValueBuffersCHROMIUM',
1920 'SubscribeValueCHROMIUM': {
1921 'decoder_func': 'DoSubscribeValueCHROMIUM',
1926 'PopulateSubscribedValuesCHROMIUM': {
1927 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
1932 'UniformValuebufferCHROMIUM': {
1933 'decoder_func': 'DoUniformValueBufferCHROMIUM',
1940 'state': 'ClearStencil',
1942 'EnableFeatureCHROMIUM': {
1944 'data_transfer_methods': ['shm'],
1945 'decoder_func': 'DoEnableFeatureCHROMIUM',
1946 'expectation': False,
1947 'cmd_args': 'GLuint bucket_id, GLint* result',
1948 'result': ['GLint'],
1951 'pepper_interface': 'ChromiumEnableFeature',
1953 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1954 'CompressedTexImage2D': {
1956 'data_transfer_methods': ['bucket', 'shm'],
1958 'CompressedTexSubImage2D': {
1960 'data_transfer_methods': ['bucket', 'shm'],
1961 'decoder_func': 'DoCompressedTexSubImage2D',
1964 'decoder_func': 'DoCopyTexImage2D',
1966 'defer_reads': True,
1968 'CopyTexSubImage2D': {
1969 'decoder_func': 'DoCopyTexSubImage2D',
1970 'defer_reads': True,
1972 'CopyTexSubImage3D': {
1973 'defer_reads': True,
1976 'CreateImageCHROMIUM': {
1979 'ClientBuffer buffer, GLsizei width, GLsizei height, '
1980 'GLenum internalformat',
1981 'result': ['GLuint'],
1982 'client_test': False,
1984 'expectation': False,
1988 'DestroyImageCHROMIUM': {
1990 'client_test': False,
1995 'CreateGpuMemoryBufferImageCHROMIUM': {
1998 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
1999 'result': ['GLuint'],
2000 'client_test': False,
2002 'expectation': False,
2008 'client_test': False,
2012 'client_test': False,
2016 'state': 'BlendColor',
2019 'type': 'StateSetRGBAlpha',
2020 'state': 'BlendEquation',
2022 '0': 'GL_FUNC_SUBTRACT'
2025 'BlendEquationSeparate': {
2027 'state': 'BlendEquation',
2029 '0': 'GL_FUNC_SUBTRACT'
2033 'type': 'StateSetRGBAlpha',
2034 'state': 'BlendFunc',
2036 'BlendFuncSeparate': {
2038 'state': 'BlendFunc',
2040 'BlendBarrierKHR': {
2041 'gl_test_func': 'glBlendBarrierKHR',
2043 'extension_flag': 'blend_equation_advanced',
2044 'client_test': False,
2046 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2048 'type': 'StateSetFrontBack',
2049 'state': 'StencilFunc',
2051 'StencilFuncSeparate': {
2052 'type': 'StateSetFrontBackSeparate',
2053 'state': 'StencilFunc',
2056 'type': 'StateSetFrontBack',
2057 'state': 'StencilOp',
2062 'StencilOpSeparate': {
2063 'type': 'StateSetFrontBackSeparate',
2064 'state': 'StencilOp',
2070 'type': 'StateSetNamedParameter',
2073 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2074 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2075 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2078 'state': 'LineWidth',
2085 'state': 'PolygonOffset',
2089 'gl_test_func': 'glDeleteBuffersARB',
2090 'resource_type': 'Buffer',
2091 'resource_types': 'Buffers',
2093 'DeleteFramebuffers': {
2095 'gl_test_func': 'glDeleteFramebuffersEXT',
2096 'resource_type': 'Framebuffer',
2097 'resource_types': 'Framebuffers',
2099 'DeleteProgram': { 'type': 'Delete' },
2100 'DeleteRenderbuffers': {
2102 'gl_test_func': 'glDeleteRenderbuffersEXT',
2103 'resource_type': 'Renderbuffer',
2104 'resource_types': 'Renderbuffers',
2108 'resource_type': 'Sampler',
2109 'resource_types': 'Samplers',
2112 'DeleteShader': { 'type': 'Delete' },
2115 'cmd_args': 'GLuint sync',
2116 'resource_type': 'Sync',
2121 'resource_type': 'Texture',
2122 'resource_types': 'Textures',
2124 'DeleteTransformFeedbacks': {
2126 'resource_type': 'TransformFeedback',
2127 'resource_types': 'TransformFeedbacks',
2131 'decoder_func': 'DoDepthRangef',
2132 'gl_test_func': 'glDepthRange',
2136 'state': 'DepthMask',
2138 'expectation': False,
2140 'DetachShader': {'decoder_func': 'DoDetachShader'},
2142 'decoder_func': 'DoDisable',
2144 'client_test': False,
2146 'DisableVertexAttribArray': {
2147 'decoder_func': 'DoDisableVertexAttribArray',
2152 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2153 'defer_draws': True,
2158 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2159 'GLenumIndexType type, GLuint index_offset',
2160 'client_test': False,
2161 'defer_draws': True,
2164 'DrawRangeElements': {
2170 'decoder_func': 'DoEnable',
2172 'client_test': False,
2174 'EnableVertexAttribArray': {
2175 'decoder_func': 'DoEnableVertexAttribArray',
2180 'client_test': False,
2185 'client_test': False,
2186 'decoder_func': 'DoFinish',
2187 'defer_reads': True,
2191 'decoder_func': 'DoFlush',
2193 'FramebufferRenderbuffer': {
2194 'decoder_func': 'DoFramebufferRenderbuffer',
2195 'gl_test_func': 'glFramebufferRenderbufferEXT',
2197 'FramebufferTexture2D': {
2198 'decoder_func': 'DoFramebufferTexture2D',
2199 'gl_test_func': 'glFramebufferTexture2DEXT',
2202 'FramebufferTexture2DMultisampleEXT': {
2203 'decoder_func': 'DoFramebufferTexture2DMultisample',
2204 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2205 'expectation': False,
2207 'extension_flag': 'multisampled_render_to_texture',
2210 'FramebufferTextureLayer': {
2211 'decoder_func': 'DoFramebufferTextureLayer',
2215 'decoder_func': 'DoGenerateMipmap',
2216 'gl_test_func': 'glGenerateMipmapEXT',
2220 'gl_test_func': 'glGenBuffersARB',
2221 'resource_type': 'Buffer',
2222 'resource_types': 'Buffers',
2224 'GenMailboxCHROMIUM': {
2225 'type': 'HandWritten',
2227 'extension': "CHROMIUM_texture_mailbox",
2230 'GenFramebuffers': {
2232 'gl_test_func': 'glGenFramebuffersEXT',
2233 'resource_type': 'Framebuffer',
2234 'resource_types': 'Framebuffers',
2236 'GenRenderbuffers': {
2237 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2238 'resource_type': 'Renderbuffer',
2239 'resource_types': 'Renderbuffers',
2243 'gl_test_func': 'glGenSamplers',
2244 'resource_type': 'Sampler',
2245 'resource_types': 'Samplers',
2250 'gl_test_func': 'glGenTextures',
2251 'resource_type': 'Texture',
2252 'resource_types': 'Textures',
2254 'GenTransformFeedbacks': {
2256 'gl_test_func': 'glGenTransformFeedbacks',
2257 'resource_type': 'TransformFeedback',
2258 'resource_types': 'TransformFeedbacks',
2261 'GetActiveAttrib': {
2263 'data_transfer_methods': ['shm'],
2265 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2273 'GetActiveUniform': {
2275 'data_transfer_methods': ['shm'],
2277 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2285 'GetActiveUniformBlockiv': {
2287 'data_transfer_methods': ['shm'],
2288 'result': ['SizedResult<GLint>'],
2291 'GetActiveUniformBlockName': {
2293 'data_transfer_methods': ['shm'],
2295 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2297 'result': ['int32_t'],
2300 'GetActiveUniformsiv': {
2302 'data_transfer_methods': ['shm'],
2304 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2306 'result': ['SizedResult<GLint>'],
2309 'GetAttachedShaders': {
2311 'data_transfer_methods': ['shm'],
2312 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2313 'result': ['SizedResult<GLuint>'],
2315 'GetAttribLocation': {
2317 'data_transfer_methods': ['shm'],
2319 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2320 'result': ['GLint'],
2323 'GetFragDataLocation': {
2325 'data_transfer_methods': ['shm'],
2327 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2328 'result': ['GLint'],
2334 'result': ['SizedResult<GLboolean>'],
2335 'decoder_func': 'DoGetBooleanv',
2336 'gl_test_func': 'glGetBooleanv',
2338 'GetBufferParameteriv': {
2340 'result': ['SizedResult<GLint>'],
2341 'decoder_func': 'DoGetBufferParameteriv',
2342 'expectation': False,
2347 'decoder_func': 'GetErrorState()->GetGLError',
2349 'result': ['GLenum'],
2350 'client_test': False,
2354 'result': ['SizedResult<GLfloat>'],
2355 'decoder_func': 'DoGetFloatv',
2356 'gl_test_func': 'glGetFloatv',
2358 'GetFramebufferAttachmentParameteriv': {
2360 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2361 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2362 'result': ['SizedResult<GLint>'],
2366 'result': ['SizedResult<GLint>'],
2367 'decoder_func': 'DoGetIntegerv',
2368 'client_test': False,
2370 'GetInternalformativ': {
2372 'result': ['SizedResult<GLint>'],
2375 'GetMaxValueInBufferCHROMIUM': {
2377 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2378 'result': ['GLuint'],
2380 'client_test': False,
2387 'decoder_func': 'DoGetProgramiv',
2388 'result': ['SizedResult<GLint>'],
2389 'expectation': False,
2391 'GetProgramInfoCHROMIUM': {
2393 'expectation': False,
2397 'client_test': False,
2398 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2400 'uint32_t link_status',
2401 'uint32_t num_attribs',
2402 'uint32_t num_uniforms',
2405 'GetProgramInfoLog': {
2407 'expectation': False,
2409 'GetRenderbufferParameteriv': {
2411 'decoder_func': 'DoGetRenderbufferParameteriv',
2412 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2413 'result': ['SizedResult<GLint>'],
2415 'GetSamplerParameterfv': {
2417 'result': ['SizedResult<GLfloat>'],
2418 'id_mapping': [ 'Sampler' ],
2421 'GetSamplerParameteriv': {
2423 'result': ['SizedResult<GLint>'],
2424 'id_mapping': [ 'Sampler' ],
2429 'decoder_func': 'DoGetShaderiv',
2430 'result': ['SizedResult<GLint>'],
2432 'GetShaderInfoLog': {
2434 'get_len_func': 'glGetShaderiv',
2435 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2438 'GetShaderPrecisionFormat': {
2440 'data_transfer_methods': ['shm'],
2442 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2446 'int32_t min_range',
2447 'int32_t max_range',
2448 'int32_t precision',
2451 'GetShaderSource': {
2453 'get_len_func': 'DoGetShaderiv',
2454 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2456 'client_test': False,
2460 'client_test': False,
2461 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2465 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2466 'result': ['SizedResult<GLint>'],
2467 'id_mapping': ['Sync'],
2470 'GetTexParameterfv': {
2472 'decoder_func': 'DoGetTexParameterfv',
2473 'result': ['SizedResult<GLfloat>']
2475 'GetTexParameteriv': {
2477 'decoder_func': 'DoGetTexParameteriv',
2478 'result': ['SizedResult<GLint>']
2480 'GetTranslatedShaderSourceANGLE': {
2482 'get_len_func': 'DoGetShaderiv',
2483 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2487 'GetUniformBlockIndex': {
2489 'data_transfer_methods': ['shm'],
2491 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2492 'result': ['GLuint'],
2493 'error_return': 'GL_INVALID_INDEX',
2496 'GetUniformBlocksCHROMIUM': {
2498 'expectation': False,
2502 'client_test': False,
2503 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2504 'result': ['uint32_t'],
2507 'GetUniformsES3CHROMIUM': {
2509 'expectation': False,
2513 'client_test': False,
2514 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2515 'result': ['uint32_t'],
2518 'GetTransformFeedbackVarying': {
2520 'data_transfer_methods': ['shm'],
2522 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2531 'GetTransformFeedbackVaryingsCHROMIUM': {
2533 'expectation': False,
2537 'client_test': False,
2538 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2539 'result': ['uint32_t'],
2544 'data_transfer_methods': ['shm'],
2545 'result': ['SizedResult<GLfloat>'],
2549 'data_transfer_methods': ['shm'],
2550 'result': ['SizedResult<GLint>'],
2552 'GetUniformIndices': {
2554 'data_transfer_methods': ['shm'],
2555 'result': ['SizedResult<GLuint>'],
2556 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
2560 'GetUniformLocation': {
2562 'data_transfer_methods': ['shm'],
2564 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2565 'result': ['GLint'],
2566 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
2568 'GetVertexAttribfv': {
2570 'result': ['SizedResult<GLfloat>'],
2572 'decoder_func': 'DoGetVertexAttribfv',
2573 'expectation': False,
2574 'client_test': False,
2576 'GetVertexAttribiv': {
2578 'result': ['SizedResult<GLint>'],
2580 'decoder_func': 'DoGetVertexAttribiv',
2581 'expectation': False,
2582 'client_test': False,
2584 'GetVertexAttribPointerv': {
2586 'data_transfer_methods': ['shm'],
2587 'result': ['SizedResult<GLuint>'],
2588 'client_test': False,
2590 'InvalidateFramebuffer': {
2593 'client_test': False,
2597 'InvalidateSubFramebuffer': {
2600 'client_test': False,
2606 'decoder_func': 'DoIsBuffer',
2607 'expectation': False,
2611 'decoder_func': 'DoIsEnabled',
2612 'client_test': False,
2614 'expectation': False,
2618 'decoder_func': 'DoIsFramebuffer',
2619 'expectation': False,
2623 'decoder_func': 'DoIsProgram',
2624 'expectation': False,
2628 'decoder_func': 'DoIsRenderbuffer',
2629 'expectation': False,
2633 'decoder_func': 'DoIsShader',
2634 'expectation': False,
2638 'id_mapping': [ 'Sampler' ],
2639 'expectation': False,
2644 'id_mapping': [ 'Sync' ],
2645 'cmd_args': 'GLuint sync',
2646 'expectation': False,
2651 'decoder_func': 'DoIsTexture',
2652 'expectation': False,
2654 'IsTransformFeedback': {
2656 'id_mapping': [ 'TransformFeedback' ],
2657 'expectation': False,
2661 'decoder_func': 'DoLinkProgram',
2664 'MapBufferCHROMIUM': {
2668 'client_test': False,
2670 'MapBufferSubDataCHROMIUM': {
2674 'client_test': False,
2675 'pepper_interface': 'ChromiumMapSub',
2677 'MapTexSubImage2DCHROMIUM': {
2681 'client_test': False,
2682 'pepper_interface': 'ChromiumMapSub',
2686 'data_transfer_methods': ['shm'],
2687 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
2688 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
2689 'uint32_t data_shm_id, uint32_t data_shm_offset, '
2690 'uint32_t result_shm_id, uint32_t result_shm_offset',
2692 'result': ['uint32_t'],
2694 'PauseTransformFeedback': {
2697 'PixelStorei': {'type': 'Manual'},
2698 'PostSubBufferCHROMIUM': {
2702 'client_test': False,
2706 'ProduceTextureCHROMIUM': {
2707 'decoder_func': 'DoProduceTextureCHROMIUM',
2710 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2712 'client_test': False,
2713 'extension': "CHROMIUM_texture_mailbox",
2717 'ProduceTextureDirectCHROMIUM': {
2718 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
2721 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2723 'client_test': False,
2724 'extension': "CHROMIUM_texture_mailbox",
2728 'RenderbufferStorage': {
2729 'decoder_func': 'DoRenderbufferStorage',
2730 'gl_test_func': 'glRenderbufferStorageEXT',
2731 'expectation': False,
2733 'RenderbufferStorageMultisampleCHROMIUM': {
2735 '// GL_CHROMIUM_framebuffer_multisample\n',
2736 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
2737 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
2738 'expectation': False,
2740 'extension_flag': 'chromium_framebuffer_multisample',
2741 'pepper_interface': 'FramebufferMultisample',
2742 'pepper_name': 'RenderbufferStorageMultisampleEXT',
2744 'RenderbufferStorageMultisampleEXT': {
2746 '// GL_EXT_multisampled_render_to_texture\n',
2747 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
2748 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
2749 'expectation': False,
2751 'extension_flag': 'multisampled_render_to_texture',
2758 '// ReadPixels has the result separated from the pixel buffer so that\n'
2759 '// it is easier to specify the result going to some specific place\n'
2760 '// that exactly fits the rectangle of pixels.\n',
2762 'data_transfer_methods': ['shm'],
2764 'client_test': False,
2766 'GLint x, GLint y, GLsizei width, GLsizei height, '
2767 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
2768 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
2769 'uint32_t result_shm_id, uint32_t result_shm_offset, '
2771 'result': ['uint32_t'],
2772 'defer_reads': True,
2774 'ReleaseShaderCompiler': {
2775 'decoder_func': 'DoReleaseShaderCompiler',
2778 'ResumeTransformFeedback': {
2781 'SamplerParameterf': {
2785 'id_mapping': [ 'Sampler' ],
2788 'SamplerParameterfv': {
2790 'data_value': 'GL_NEAREST',
2792 'gl_test_func': 'glSamplerParameterf',
2793 'decoder_func': 'DoSamplerParameterfv',
2794 'first_element_only': True,
2795 'id_mapping': [ 'Sampler' ],
2798 'SamplerParameteri': {
2802 'id_mapping': [ 'Sampler' ],
2805 'SamplerParameteriv': {
2807 'data_value': 'GL_NEAREST',
2809 'gl_test_func': 'glSamplerParameteri',
2810 'decoder_func': 'DoSamplerParameteriv',
2811 'first_element_only': True,
2816 'client_test': False,
2820 'decoder_func': 'DoShaderSource',
2821 'expectation': False,
2822 'data_transfer_methods': ['bucket'],
2824 'GLuint shader, const char** str',
2826 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2829 'type': 'StateSetFrontBack',
2830 'state': 'StencilMask',
2832 'expectation': False,
2834 'StencilMaskSeparate': {
2835 'type': 'StateSetFrontBackSeparate',
2836 'state': 'StencilMask',
2838 'expectation': False,
2842 'decoder_func': 'DoSwapBuffers',
2844 'client_test': False,
2850 'decoder_func': 'DoSwapInterval',
2852 'client_test': False,
2858 'data_transfer_methods': ['shm'],
2859 'client_test': False,
2863 'data_transfer_methods': ['shm'],
2864 'client_test': False,
2868 'decoder_func': 'DoTexParameterf',
2874 'decoder_func': 'DoTexParameteri',
2881 'data_value': 'GL_NEAREST',
2883 'decoder_func': 'DoTexParameterfv',
2884 'gl_test_func': 'glTexParameterf',
2885 'first_element_only': True,
2889 'data_value': 'GL_NEAREST',
2891 'decoder_func': 'DoTexParameteriv',
2892 'gl_test_func': 'glTexParameteri',
2893 'first_element_only': True,
2900 'data_transfer_methods': ['shm'],
2901 'client_test': False,
2902 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2903 'GLint xoffset, GLint yoffset, '
2904 'GLsizei width, GLsizei height, '
2905 'GLenumTextureFormat format, GLenumPixelType type, '
2906 'const void* pixels, GLboolean internal'
2910 'data_transfer_methods': ['shm'],
2911 'client_test': False,
2912 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2913 'GLint xoffset, GLint yoffset, GLint zoffset, '
2914 'GLsizei width, GLsizei height, GLsizei depth, '
2915 'GLenumTextureFormat format, GLenumPixelType type, '
2916 'const void* pixels, GLboolean internal',
2919 'TransformFeedbackVaryings': {
2921 'data_transfer_methods': ['bucket'],
2922 'decoder_func': 'DoTransformFeedbackVaryings',
2924 'GLuint program, const char** varyings, GLenum buffermode',
2927 'Uniform1f': {'type': 'PUTXn', 'count': 1},
2931 'decoder_func': 'DoUniform1fv',
2933 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2937 'decoder_func': 'DoUniform1iv',
2950 'Uniform2i': {'type': 'PUTXn', 'count': 2},
2951 'Uniform2f': {'type': 'PUTXn', 'count': 2},
2955 'decoder_func': 'DoUniform2fv',
2960 'decoder_func': 'DoUniform2iv',
2972 'Uniform3i': {'type': 'PUTXn', 'count': 3},
2973 'Uniform3f': {'type': 'PUTXn', 'count': 3},
2977 'decoder_func': 'DoUniform3fv',
2982 'decoder_func': 'DoUniform3iv',
2994 'Uniform4i': {'type': 'PUTXn', 'count': 4},
2995 'Uniform4f': {'type': 'PUTXn', 'count': 4},
2999 'decoder_func': 'DoUniform4fv',
3004 'decoder_func': 'DoUniform4iv',
3016 'UniformMatrix2fv': {
3019 'decoder_func': 'DoUniformMatrix2fv',
3021 'UniformMatrix2x3fv': {
3026 'UniformMatrix2x4fv': {
3031 'UniformMatrix3fv': {
3034 'decoder_func': 'DoUniformMatrix3fv',
3036 'UniformMatrix3x2fv': {
3041 'UniformMatrix3x4fv': {
3046 'UniformMatrix4fv': {
3049 'decoder_func': 'DoUniformMatrix4fv',
3051 'UniformMatrix4x2fv': {
3056 'UniformMatrix4x3fv': {
3061 'UniformBlockBinding': {
3066 'UnmapBufferCHROMIUM': {
3070 'client_test': False,
3072 'UnmapBufferSubDataCHROMIUM': {
3076 'client_test': False,
3077 'pepper_interface': 'ChromiumMapSub',
3083 'UnmapTexSubImage2DCHROMIUM': {
3087 'client_test': False,
3088 'pepper_interface': 'ChromiumMapSub',
3092 'decoder_func': 'DoUseProgram',
3094 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3095 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3096 'VertexAttrib1fv': {
3099 'decoder_func': 'DoVertexAttrib1fv',
3101 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3102 'VertexAttrib2fv': {
3105 'decoder_func': 'DoVertexAttrib2fv',
3107 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3108 'VertexAttrib3fv': {
3111 'decoder_func': 'DoVertexAttrib3fv',
3113 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3114 'VertexAttrib4fv': {
3117 'decoder_func': 'DoVertexAttrib4fv',
3119 'VertexAttribI4i': {
3122 'VertexAttribI4iv': {
3127 'VertexAttribI4ui': {
3130 'VertexAttribI4uiv': {
3135 'VertexAttribIPointer': {
3137 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3138 'GLenumVertexAttribType type, GLsizei stride, '
3140 'client_test': False,
3143 'VertexAttribPointer': {
3145 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3146 'GLenumVertexAttribType type, GLboolean normalized, '
3147 'GLsizei stride, GLuint offset',
3148 'client_test': False,
3152 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3153 'GLuint timeout_0, GLuint timeout_1',
3155 'client_test': False,
3163 'decoder_func': 'DoViewport',
3172 'GetRequestableExtensionsCHROMIUM': {
3175 'cmd_args': 'uint32_t bucket_id',
3179 'RequestExtensionCHROMIUM': {
3182 'client_test': False,
3183 'cmd_args': 'uint32_t bucket_id',
3187 'RateLimitOffscreenContextCHROMIUM': {
3191 'client_test': False,
3193 'CreateStreamTextureCHROMIUM': {
3194 'type': 'HandWritten',
3200 'TexImageIOSurface2DCHROMIUM': {
3201 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3206 'CopyTextureCHROMIUM': {
3207 'decoder_func': 'DoCopyTextureCHROMIUM',
3212 'CopySubTextureCHROMIUM': {
3213 'decoder_func': 'DoCopySubTextureCHROMIUM',
3218 'TexStorage2DEXT': {
3221 'decoder_func': 'DoTexStorage2DEXT',
3223 'DrawArraysInstancedANGLE': {
3225 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3226 'GLsizei primcount',
3229 'pepper_interface': 'InstancedArrays',
3230 'defer_draws': True,
3234 'decoder_func': 'DoDrawBuffersEXT',
3236 'client_test': False,
3238 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3241 'pepper_interface': 'DrawBuffers',
3243 'DrawElementsInstancedANGLE': {
3245 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3246 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3249 'client_test': False,
3250 'pepper_interface': 'InstancedArrays',
3251 'defer_draws': True,
3253 'VertexAttribDivisorANGLE': {
3255 'cmd_args': 'GLuint index, GLuint divisor',
3258 'pepper_interface': 'InstancedArrays',
3262 'gl_test_func': 'glGenQueriesARB',
3263 'resource_type': 'Query',
3264 'resource_types': 'Queries',
3266 'pepper_interface': 'Query',
3267 'not_shared': 'True',
3269 'DeleteQueriesEXT': {
3271 'gl_test_func': 'glDeleteQueriesARB',
3272 'resource_type': 'Query',
3273 'resource_types': 'Queries',
3275 'pepper_interface': 'Query',
3279 'client_test': False,
3280 'pepper_interface': 'Query',
3284 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3285 'data_transfer_methods': ['shm'],
3286 'gl_test_func': 'glBeginQuery',
3287 'pepper_interface': 'Query',
3289 'BeginTransformFeedback': {
3294 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3295 'gl_test_func': 'glEndnQuery',
3296 'client_test': False,
3297 'pepper_interface': 'Query',
3299 'EndTransformFeedback': {
3304 'client_test': False,
3305 'gl_test_func': 'glGetQueryiv',
3306 'pepper_interface': 'Query',
3308 'GetQueryObjectuivEXT': {
3310 'client_test': False,
3311 'gl_test_func': 'glGetQueryObjectuiv',
3312 'pepper_interface': 'Query',
3314 'BindUniformLocationCHROMIUM': {
3317 'data_transfer_methods': ['bucket'],
3319 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3321 'InsertEventMarkerEXT': {
3323 'decoder_func': 'DoInsertEventMarkerEXT',
3324 'expectation': False,
3327 'PushGroupMarkerEXT': {
3329 'decoder_func': 'DoPushGroupMarkerEXT',
3330 'expectation': False,
3333 'PopGroupMarkerEXT': {
3334 'decoder_func': 'DoPopGroupMarkerEXT',
3335 'expectation': False,
3340 'GenVertexArraysOES': {
3343 'gl_test_func': 'glGenVertexArraysOES',
3344 'resource_type': 'VertexArray',
3345 'resource_types': 'VertexArrays',
3347 'pepper_interface': 'VertexArrayObject',
3349 'BindVertexArrayOES': {
3352 'gl_test_func': 'glBindVertexArrayOES',
3353 'decoder_func': 'DoBindVertexArrayOES',
3354 'gen_func': 'GenVertexArraysOES',
3356 'client_test': False,
3357 'pepper_interface': 'VertexArrayObject',
3359 'DeleteVertexArraysOES': {
3362 'gl_test_func': 'glDeleteVertexArraysOES',
3363 'resource_type': 'VertexArray',
3364 'resource_types': 'VertexArrays',
3366 'pepper_interface': 'VertexArrayObject',
3368 'IsVertexArrayOES': {
3371 'gl_test_func': 'glIsVertexArrayOES',
3372 'decoder_func': 'DoIsVertexArrayOES',
3373 'expectation': False,
3375 'pepper_interface': 'VertexArrayObject',
3377 'BindTexImage2DCHROMIUM': {
3378 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3383 'ReleaseTexImage2DCHROMIUM': {
3384 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3389 'ShallowFinishCHROMIUM': {
3394 'client_test': False,
3396 'ShallowFlushCHROMIUM': {
3401 'client_test': False,
3403 'OrderingBarrierCHROMIUM': {
3408 'client_test': False,
3410 'TraceBeginCHROMIUM': {
3413 'client_test': False,
3414 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3418 'TraceEndCHROMIUM': {
3420 'client_test': False,
3421 'decoder_func': 'DoTraceEndCHROMIUM',
3426 'AsyncTexImage2DCHROMIUM': {
3428 'data_transfer_methods': ['shm'],
3429 'client_test': False,
3430 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3431 'GLintTextureInternalFormat internalformat, '
3432 'GLsizei width, GLsizei height, '
3433 'GLintTextureBorder border, '
3434 'GLenumTextureFormat format, GLenumPixelType type, '
3435 'const void* pixels, '
3436 'uint32_t async_upload_token, '
3441 'AsyncTexSubImage2DCHROMIUM': {
3443 'data_transfer_methods': ['shm'],
3444 'client_test': False,
3445 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3446 'GLint xoffset, GLint yoffset, '
3447 'GLsizei width, GLsizei height, '
3448 'GLenumTextureFormat format, GLenumPixelType type, '
3449 'const void* data, '
3450 'uint32_t async_upload_token, '
3455 'WaitAsyncTexImage2DCHROMIUM': {
3457 'client_test': False,
3461 'WaitAllAsyncTexImage2DCHROMIUM': {
3463 'client_test': False,
3467 'DiscardFramebufferEXT': {
3470 'decoder_func': 'DoDiscardFramebufferEXT',
3472 'client_test': False,
3473 'extension_flag': 'ext_discard_framebuffer',
3475 'LoseContextCHROMIUM': {
3476 'decoder_func': 'DoLoseContextCHROMIUM',
3481 'InsertSyncPointCHROMIUM': {
3482 'type': 'HandWritten',
3484 'extension': "CHROMIUM_sync_point",
3487 'WaitSyncPointCHROMIUM': {
3490 'extension': "CHROMIUM_sync_point",
3494 'DiscardBackbufferCHROMIUM': {
3500 'ScheduleOverlayPlaneCHROMIUM': {
3504 'client_test': False,
3508 'MatrixLoadfCHROMIUM': {
3511 'data_type': 'GLfloat',
3512 'decoder_func': 'DoMatrixLoadfCHROMIUM',
3513 'gl_test_func': 'glMatrixLoadfEXT',
3516 'extension_flag': 'chromium_path_rendering',
3518 'MatrixLoadIdentityCHROMIUM': {
3519 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
3520 'gl_test_func': 'glMatrixLoadIdentityEXT',
3523 'extension_flag': 'chromium_path_rendering',
3528 def Grouper(n
, iterable
, fillvalue
=None):
3529 """Collect data into fixed-length chunks or blocks"""
3530 args
= [iter(iterable
)] * n
3531 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
3534 def SplitWords(input_string
):
3535 """Transforms a input_string into a list of lower-case components.
3538 input_string: the input string.
3541 a list of lower-case words.
3543 if input_string
.find('_') > -1:
3544 # 'some_TEXT_' -> 'some text'
3545 return input_string
.replace('_', ' ').strip().lower().split()
3547 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
3549 # look for capitalization to cut input_strings
3550 # 'SomeText' -> 'Some Text'
3551 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
3552 # 'Vector3' -> 'Vector 3'
3553 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
3554 return input_string
.lower().split()
3558 """Makes a lower-case identifier from words.
3561 words: a list of lower-case words.
3564 the lower-case identifier.
3566 return '_'.join(words
)
3569 def ToUnderscore(input_string
):
3570 """converts CamelCase to camel_case."""
3571 words
= SplitWords(input_string
)
3574 def CachedStateName(item
):
3575 if item
.get('cached', False):
3576 return 'cached_' + item
['name']
3579 def ToGLExtensionString(extension_flag
):
3580 """Returns GL-type extension string of a extension flag."""
3581 if extension_flag
== "oes_compressed_etc1_rgb8_texture":
3582 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
3584 uppercase_words
= [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
3585 'egl', 'atc', 'etc1', 'angle']
3586 parts
= extension_flag
.split('_')
3588 [part
.upper() if part
in uppercase_words
else part
for part
in parts
])
3590 def ToCamelCase(input_string
):
3591 """converts ABC_underscore_case to ABCUnderscoreCase."""
3592 return ''.join(w
[0].upper() + w
[1:] for w
in input_string
.split('_'))
3594 def GetGLGetTypeConversion(result_type
, value_type
, value
):
3595 """Makes a gl compatible type conversion string for accessing state variables.
3597 Useful when accessing state variables through glGetXXX calls.
3598 glGet documetation (for example, the manual pages):
3599 [...] If glGetIntegerv is called, [...] most floating-point values are
3600 rounded to the nearest integer value. [...]
3603 result_type: the gl type to be obtained
3604 value_type: the GL type of the state variable
3605 value: the name of the state variable
3608 String that converts the state variable to desired GL type according to GL
3612 if result_type
== 'GLint':
3613 if value_type
== 'GLfloat':
3614 return 'static_cast<GLint>(round(%s))' % value
3615 return 'static_cast<%s>(%s)' % (result_type
, value
)
3617 class CWriter(object):
3618 """Writes to a file formatting it for Google's style guidelines."""
3620 def __init__(self
, filename
):
3621 self
.filename
= filename
3624 def Write(self
, string
):
3625 """Writes a string to a file spliting if it's > 80 characters."""
3626 lines
= string
.splitlines()
3627 num_lines
= len(lines
)
3628 for ii
in range(0, num_lines
):
3629 self
.content
.append(lines
[ii
])
3630 if ii
< (num_lines
- 1) or string
[-1] == '\n':
3631 self
.content
.append('\n')
3634 """Close the file."""
3635 content
= "".join(self
.content
)
3637 if os
.path
.exists(self
.filename
):
3638 old_file
= open(self
.filename
, "rb");
3639 old_content
= old_file
.read()
3641 if content
== old_content
:
3644 file = open(self
.filename
, "wb")
3649 class CHeaderWriter(CWriter
):
3650 """Writes a C Header file."""
3652 _non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
3654 def __init__(self
, filename
, file_comment
= None):
3655 CWriter
.__init
__(self
, filename
)
3657 base
= os
.path
.abspath(filename
)
3658 while os
.path
.basename(base
) != 'src':
3659 new_base
= os
.path
.dirname(base
)
3660 assert new_base
!= base
# Prevent infinite loop.
3663 hpath
= os
.path
.relpath(filename
, base
)
3664 self
.guard
= self
._non
_alnum
_re
.sub('_', hpath
).upper() + '_'
3666 self
.Write(_LICENSE
)
3667 self
.Write(_DO_NOT_EDIT_WARNING
)
3668 if not file_comment
== None:
3669 self
.Write(file_comment
)
3670 self
.Write("#ifndef %s\n" % self
.guard
)
3671 self
.Write("#define %s\n\n" % self
.guard
)
3674 self
.Write("#endif // %s\n\n" % self
.guard
)
3677 class TypeHandler(object):
3678 """This class emits code for a particular type of function."""
3680 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
3685 def InitFunction(self
, func
):
3686 """Add or adjust anything type specific for this function."""
3687 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
3688 func
.AddCmdArg(DataSizeArgument('data_size'))
3690 def NeedsDataTransferFunction(self
, func
):
3691 """Overriden from TypeHandler."""
3692 return func
.num_pointer_args
>= 1
3694 def WriteStruct(self
, func
, file):
3695 """Writes a structure that matches the arguments to a function."""
3696 comment
= func
.GetInfo('cmd_comment')
3697 if not comment
== None:
3699 file.Write("struct %s {\n" % func
.name
)
3700 file.Write(" typedef %s ValueType;\n" % func
.name
)
3701 file.Write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
3702 func
.WriteCmdArgFlag(file)
3703 func
.WriteCmdFlag(file)
3705 result
= func
.GetInfo('result')
3706 if not result
== None:
3707 if len(result
) == 1:
3708 file.Write(" typedef %s Result;\n\n" % result
[0])
3710 file.Write(" struct Result {\n")
3712 file.Write(" %s;\n" % line
)
3713 file.Write(" };\n\n")
3715 func
.WriteCmdComputeSize(file)
3716 func
.WriteCmdSetHeader(file)
3717 func
.WriteCmdInit(file)
3718 func
.WriteCmdSet(file)
3720 file.Write(" gpu::CommandHeader header;\n")
3721 args
= func
.GetCmdArgs()
3723 file.Write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
3725 consts
= func
.GetCmdConstants()
3726 for const
in consts
:
3727 file.Write(" static const %s %s = %s;\n" %
3728 (const
.cmd_type
, const
.name
, const
.GetConstantValue()))
3733 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
3734 file.Write("static_assert(sizeof(%s) == %d,\n" % (func
.name
, size
))
3735 file.Write(" \"size of %s should be %d\");\n" %
3737 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func
.name
)
3738 file.Write(" \"offset of %s header should be 0\");\n" %
3740 offset
= _SIZE_OF_COMMAND_HEADER
3742 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
3743 (func
.name
, arg
.name
, offset
))
3744 file.Write(" \"offset of %s %s should be %d\");\n" %
3745 (func
.name
, arg
.name
, offset
))
3746 offset
+= _SIZE_OF_UINT32
3747 if not result
== None and len(result
) > 1:
3750 parts
= line
.split()
3753 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
3754 "offset of %(cmd_name)s Result %(field_name)s should be "
3757 file.Write((check
.strip() + "\n") % {
3758 'cmd_name': func
.name
,
3762 offset
+= _SIZE_OF_UINT32
3765 def WriteHandlerImplementation(self
, func
, file):
3766 """Writes the handler implementation for this command."""
3767 if func
.IsUnsafe() and func
.GetInfo('id_mapping'):
3768 code_no_gen
= """ if (!group_->Get%(type)sServiceId(
3769 %(var)s, &%(service_var)s)) {
3770 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3771 return error::kNoError;
3774 code_gen
= """ if (!group_->Get%(type)sServiceId(
3775 %(var)s, &%(service_var)s)) {
3776 if (!group_->bind_generates_resource()) {
3778 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3779 return error::kNoError;
3781 GLuint client_id = %(var)s;
3782 gl%(gen_func)s(1, &%(service_var)s);
3783 Create%(type)s(client_id, %(service_var)s);
3786 gen_func
= func
.GetInfo('gen_func')
3787 for id_type
in func
.GetInfo('id_mapping'):
3788 service_var
= id_type
.lower()
3789 if id_type
== 'Sync':
3790 service_var
= "service_%s" % service_var
3791 file.Write(" GLsync %s = 0;\n" % service_var
)
3792 if gen_func
and id_type
in gen_func
:
3793 file.Write(code_gen
% { 'type': id_type
,
3794 'var': id_type
.lower(),
3795 'service_var': service_var
,
3796 'func': func
.GetGLFunctionName(),
3797 'gen_func': gen_func
})
3799 file.Write(code_no_gen
% { 'type': id_type
,
3800 'var': id_type
.lower(),
3801 'service_var': service_var
,
3802 'func': func
.GetGLFunctionName() })
3804 for arg
in func
.GetOriginalArgs():
3805 if arg
.type == "GLsync":
3806 args
.append("service_%s" % arg
.name
)
3807 elif arg
.name
.endswith("size") and arg
.type == "GLsizei":
3808 args
.append("num_%s" % func
.GetLastOriginalArg().name
)
3809 elif arg
.name
== "length":
3810 args
.append("nullptr")
3812 args
.append(arg
.name
)
3813 file.Write(" %s(%s);\n" %
3814 (func
.GetGLFunctionName(), ", ".join(args
)))
3816 def WriteCmdSizeTest(self
, func
, file):
3817 """Writes the size test for a command."""
3818 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3820 def WriteFormatTest(self
, func
, file):
3821 """Writes a format test for a command."""
3822 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
3823 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
3824 (func
.name
, func
.name
))
3825 file.Write(" void* next_cmd = cmd.Set(\n")
3827 args
= func
.GetCmdArgs()
3828 for value
, arg
in enumerate(args
):
3829 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
3831 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
3833 file.Write(" cmd.header.command);\n")
3834 func
.type_handler
.WriteCmdSizeTest(func
, file)
3835 for value
, arg
in enumerate(args
):
3836 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
3837 (arg
.type, value
+ 11, arg
.name
))
3838 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
3839 file.Write(" next_cmd, sizeof(cmd));\n")
3843 def WriteImmediateFormatTest(self
, func
, file):
3844 """Writes a format test for an immediate version of a command."""
3847 def WriteBucketFormatTest(self
, func
, file):
3848 """Writes a format test for a bucket version of a command."""
3851 def WriteGetDataSizeCode(self
, func
, file):
3852 """Writes the code to set data_size used in validation"""
3855 def WriteImmediateCmdSizeTest(self
, func
, file):
3856 """Writes a size test for an immediate version of a command."""
3857 file.Write(" // TODO(gman): Compute correct size.\n")
3858 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3860 def __WriteIdMapping(self
, func
, file):
3861 """Writes client side / service side ID mapping."""
3862 if not func
.IsUnsafe() or not func
.GetInfo('id_mapping'):
3864 for id_type
in func
.GetInfo('id_mapping'):
3865 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
3866 (id_type
, id_type
.lower(), id_type
.lower()))
3868 def WriteImmediateHandlerImplementation (self
, func
, file):
3869 """Writes the handler impl for the immediate version of a command."""
3870 self
.__WriteIdMapping
(func
, file)
3871 file.Write(" %s(%s);\n" %
3872 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3874 def WriteBucketHandlerImplementation (self
, func
, file):
3875 """Writes the handler impl for the bucket version of a command."""
3876 self
.__WriteIdMapping
(func
, file)
3877 file.Write(" %s(%s);\n" %
3878 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
3880 def WriteServiceHandlerFunctionHeader(self
, func
, file):
3881 """Writes function header for service implementation handlers."""
3882 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
3883 uint32_t immediate_data_size, const void* cmd_data) {
3884 """ % {'name': func
.name
})
3886 file.Write("""if (!unsafe_es3_apis_enabled())
3887 return error::kUnknownCommand;
3889 file.Write("""const gles2::cmds::%(name)s& c =
3890 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
3892 """ % {'name': func
.name
})
3894 def WriteServiceImplementation(self
, func
, file):
3895 """Writes the service implementation for a command."""
3896 self
.WriteServiceHandlerFunctionHeader(func
, file)
3897 self
.WriteHandlerExtensionCheck(func
, file)
3898 self
.WriteHandlerDeferReadWrite(func
, file);
3899 if len(func
.GetOriginalArgs()) > 0:
3900 last_arg
= func
.GetLastOriginalArg()
3901 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
3902 for arg
in all_but_last_arg
:
3903 arg
.WriteGetCode(file)
3904 self
.WriteGetDataSizeCode(func
, file)
3905 last_arg
.WriteGetCode(file)
3906 func
.WriteHandlerValidation(file)
3907 func
.WriteHandlerImplementation(file)
3908 file.Write(" return error::kNoError;\n")
3912 def WriteImmediateServiceImplementation(self
, func
, file):
3913 """Writes the service implementation for an immediate version of command."""
3914 self
.WriteServiceHandlerFunctionHeader(func
, file)
3915 self
.WriteHandlerExtensionCheck(func
, file)
3916 self
.WriteHandlerDeferReadWrite(func
, file);
3917 for arg
in func
.GetOriginalArgs():
3919 self
.WriteGetDataSizeCode(func
, file)
3920 arg
.WriteGetCode(file)
3921 func
.WriteHandlerValidation(file)
3922 func
.WriteHandlerImplementation(file)
3923 file.Write(" return error::kNoError;\n")
3927 def WriteBucketServiceImplementation(self
, func
, file):
3928 """Writes the service implementation for a bucket version of command."""
3929 self
.WriteServiceHandlerFunctionHeader(func
, file)
3930 self
.WriteHandlerExtensionCheck(func
, file)
3931 self
.WriteHandlerDeferReadWrite(func
, file);
3932 for arg
in func
.GetCmdArgs():
3933 arg
.WriteGetCode(file)
3934 func
.WriteHandlerValidation(file)
3935 func
.WriteHandlerImplementation(file)
3936 file.Write(" return error::kNoError;\n")
3940 def WriteHandlerExtensionCheck(self
, func
, file):
3941 if func
.GetInfo('extension_flag'):
3942 file.Write(" if (!features().%s) {\n" % func
.GetInfo('extension_flag'))
3943 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
3944 " \"function not available\");\n" % func
.original_name
)
3945 file.Write(" return error::kNoError;")
3946 file.Write(" }\n\n")
3948 def WriteHandlerDeferReadWrite(self
, func
, file):
3949 """Writes the code to handle deferring reads or writes."""
3950 defer_draws
= func
.GetInfo('defer_draws')
3951 defer_reads
= func
.GetInfo('defer_reads')
3952 if defer_draws
or defer_reads
:
3953 file.Write(" error::Error error;\n")
3955 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
3956 file.Write(" if (error != error::kNoError)\n")
3957 file.Write(" return error;\n")
3959 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
3960 file.Write(" if (error != error::kNoError)\n")
3961 file.Write(" return error;\n")
3963 def WriteValidUnitTest(self
, func
, file, test
, *extras
):
3964 """Writes a valid unit test for the service implementation."""
3965 if func
.GetInfo('expectation') == False:
3966 test
= self
._remove
_expected
_call
_re
.sub('', test
)
3969 arg
.GetValidArg(func
) \
3970 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
3973 arg
.GetValidGLArg(func
) \
3974 for arg
in func
.GetOriginalArgs()
3976 gl_func_name
= func
.GetGLTestFunctionName()
3979 'gl_func_name': gl_func_name
,
3980 'args': ", ".join(arg_strings
),
3981 'gl_args': ", ".join(gl_arg_strings
),
3983 for extra
in extras
:
3986 while (old_test
!= test
):
3989 file.Write(test
% vars)
3991 def WriteInvalidUnitTest(self
, func
, file, test
, *extras
):
3992 """Writes an invalid unit test for the service implementation."""
3995 for invalid_arg_index
, invalid_arg
in enumerate(func
.GetOriginalArgs()):
3996 # Service implementation does not test constants, as they are not part of
3997 # the call in the service side.
3998 if invalid_arg
.IsConstant():
4001 num_invalid_values
= invalid_arg
.GetNumInvalidValues(func
)
4002 for value_index
in range(0, num_invalid_values
):
4004 parse_result
= "kNoError"
4006 for arg
in func
.GetOriginalArgs():
4007 if arg
.IsConstant():
4009 if invalid_arg
is arg
:
4010 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
4013 arg_string
= arg
.GetValidArg(func
)
4014 arg_strings
.append(arg_string
)
4016 for arg
in func
.GetOriginalArgs():
4017 gl_arg_strings
.append("_")
4018 gl_func_name
= func
.GetGLTestFunctionName()
4020 if not gl_error
== None:
4021 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4025 'arg_index': invalid_arg_index
,
4026 'value_index': value_index
,
4027 'gl_func_name': gl_func_name
,
4028 'args': ", ".join(arg_strings
),
4029 'all_but_last_args': ", ".join(arg_strings
[:-1]),
4030 'gl_args': ", ".join(gl_arg_strings
),
4031 'parse_result': parse_result
,
4032 'gl_error_test': gl_error_test
,
4034 for extra
in extras
:
4036 file.Write(test
% vars)
4038 def WriteServiceUnitTest(self
, func
, file, *extras
):
4039 """Writes the service unit test for a command."""
4041 if func
.name
== 'Enable':
4043 TEST_P(%(test_name)s, %(name)sValidArgs) {
4044 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4045 SpecializedSetup<cmds::%(name)s, 0>(true);
4047 cmd.Init(%(args)s);"""
4048 elif func
.name
== 'Disable':
4050 TEST_P(%(test_name)s, %(name)sValidArgs) {
4051 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4052 SpecializedSetup<cmds::%(name)s, 0>(true);
4054 cmd.Init(%(args)s);"""
4057 TEST_P(%(test_name)s, %(name)sValidArgs) {
4058 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4059 SpecializedSetup<cmds::%(name)s, 0>(true);
4061 cmd.Init(%(args)s);"""
4064 decoder_->set_unsafe_es3_apis_enabled(true);
4065 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4066 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4067 decoder_->set_unsafe_es3_apis_enabled(false);
4068 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4073 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4074 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4077 self
.WriteValidUnitTest(func
, file, valid_test
, *extras
)
4079 if not func
.IsUnsafe():
4081 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4082 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4083 SpecializedSetup<cmds::%(name)s, 0>(false);
4086 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4089 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
4091 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4092 """Writes the service unit test for an immediate command."""
4093 file.Write("// TODO(gman): %s\n" % func
.name
)
4095 def WriteImmediateValidationCode(self
, func
, file):
4096 """Writes the validation code for an immediate version of a command."""
4099 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
4100 """Writes the service unit test for a bucket command."""
4101 file.Write("// TODO(gman): %s\n" % func
.name
)
4103 def WriteBucketValidationCode(self
, func
, file):
4104 """Writes the validation code for a bucket version of a command."""
4105 file.Write("// TODO(gman): %s\n" % func
.name
)
4107 def WriteGLES2ImplementationDeclaration(self
, func
, file):
4108 """Writes the GLES2 Implemention declaration."""
4109 impl_decl
= func
.GetInfo('impl_decl')
4110 if impl_decl
== None or impl_decl
== True:
4111 file.Write("%s %s(%s) override;\n" %
4112 (func
.return_type
, func
.original_name
,
4113 func
.MakeTypedOriginalArgString("")))
4116 def WriteGLES2CLibImplementation(self
, func
, file):
4117 file.Write("%s GLES2%s(%s) {\n" %
4118 (func
.return_type
, func
.name
,
4119 func
.MakeTypedOriginalArgString("")))
4120 result_string
= "return "
4121 if func
.return_type
== "void":
4123 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
4124 (result_string
, func
.original_name
,
4125 func
.MakeOriginalArgString("")))
4128 def WriteGLES2Header(self
, func
, file):
4129 """Writes a re-write macro for GLES"""
4130 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
4132 def WriteClientGLCallLog(self
, func
, file):
4133 """Writes a logging macro for the client side code."""
4135 if len(func
.GetOriginalArgs()):
4138 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4139 (func
.original_name
, comma
, func
.MakeLogArgString()))
4141 def WriteClientGLReturnLog(self
, func
, file):
4142 """Writes the return value logging code."""
4143 if func
.return_type
!= "void":
4144 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
4146 def WriteGLES2ImplementationHeader(self
, func
, file):
4147 """Writes the GLES2 Implemention."""
4148 self
.WriteGLES2ImplementationDeclaration(func
, file)
4150 def WriteGLES2TraceImplementationHeader(self
, func
, file):
4151 """Writes the GLES2 Trace Implemention header."""
4152 file.Write("%s %s(%s) override;\n" %
4153 (func
.return_type
, func
.original_name
,
4154 func
.MakeTypedOriginalArgString("")))
4156 def WriteGLES2TraceImplementation(self
, func
, file):
4157 """Writes the GLES2 Trace Implemention."""
4158 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
4159 (func
.return_type
, func
.original_name
,
4160 func
.MakeTypedOriginalArgString("")))
4161 result_string
= "return "
4162 if func
.return_type
== "void":
4164 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4166 file.Write(" %sgl_->%s(%s);\n" %
4167 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
4171 def WriteGLES2Implementation(self
, func
, file):
4172 """Writes the GLES2 Implemention."""
4173 impl_func
= func
.GetInfo('impl_func')
4174 impl_decl
= func
.GetInfo('impl_decl')
4175 gen_cmd
= func
.GetInfo('gen_cmd')
4176 if (func
.can_auto_generate
and
4177 (impl_func
== None or impl_func
== True) and
4178 (impl_decl
== None or impl_decl
== True) and
4179 (gen_cmd
== None or gen_cmd
== True)):
4180 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4181 (func
.return_type
, func
.original_name
,
4182 func
.MakeTypedOriginalArgString("")))
4183 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4184 self
.WriteClientGLCallLog(func
, file)
4185 func
.WriteDestinationInitalizationValidation(file)
4186 for arg
in func
.GetOriginalArgs():
4187 arg
.WriteClientSideValidationCode(file, func
)
4188 file.Write(" helper_->%s(%s);\n" %
4189 (func
.name
, func
.MakeHelperArgString("")))
4190 file.Write(" CheckGLError();\n")
4191 self
.WriteClientGLReturnLog(func
, file)
4195 def WriteGLES2InterfaceHeader(self
, func
, file):
4196 """Writes the GLES2 Interface."""
4197 file.Write("virtual %s %s(%s) = 0;\n" %
4198 (func
.return_type
, func
.original_name
,
4199 func
.MakeTypedOriginalArgString("")))
4201 def WriteGLES2InterfaceStub(self
, func
, file):
4202 """Writes the GLES2 Interface stub declaration."""
4203 file.Write("%s %s(%s) override;\n" %
4204 (func
.return_type
, func
.original_name
,
4205 func
.MakeTypedOriginalArgString("")))
4207 def WriteGLES2InterfaceStubImpl(self
, func
, file):
4208 """Writes the GLES2 Interface stub declaration."""
4209 args
= func
.GetOriginalArgs()
4210 arg_string
= ", ".join(
4211 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
4212 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
4213 (func
.return_type
, func
.original_name
, arg_string
))
4214 if func
.return_type
!= "void":
4215 file.Write(" return 0;\n")
4218 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4219 """Writes the GLES2 Implemention unit test."""
4220 client_test
= func
.GetInfo('client_test')
4221 if (func
.can_auto_generate
and
4222 (client_test
== None or client_test
== True)):
4224 TEST_F(GLES2ImplementationTest, %(name)s) {
4229 expected.cmd.Init(%(cmd_args)s);
4231 gl_->%(name)s(%(args)s);
4232 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4236 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
4240 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
4245 'args': ", ".join(gl_arg_strings
),
4246 'cmd_args': ", ".join(cmd_arg_strings
),
4249 # Test constants for invalid values, as they are not tested by the
4251 constants
= [arg
for arg
in func
.GetOriginalArgs() if arg
.IsConstant()]
4254 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4255 gl_->%(name)s(%(args)s);
4256 EXPECT_TRUE(NoCommandsWritten());
4257 EXPECT_EQ(%(gl_error)s, CheckError());
4260 for invalid_arg
in constants
:
4262 invalid
= invalid_arg
.GetInvalidArg(func
)
4263 for arg
in func
.GetOriginalArgs():
4264 if arg
is invalid_arg
:
4265 gl_arg_strings
.append(invalid
[0])
4267 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
4271 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
4272 'args': ", ".join(gl_arg_strings
),
4273 'gl_error': invalid
[2],
4276 if client_test
!= False:
4277 file.Write("// TODO(zmo): Implement unit test for %s\n" % func
.name
)
4279 def WriteDestinationInitalizationValidation(self
, func
, file):
4280 """Writes the client side destintion initialization validation."""
4281 for arg
in func
.GetOriginalArgs():
4282 arg
.WriteDestinationInitalizationValidation(file, func
)
4284 def WriteTraceEvent(self
, func
, file):
4285 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4288 def WriteImmediateCmdComputeSize(self
, func
, file):
4289 """Writes the size computation code for the immediate version of a cmd."""
4290 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4291 file.Write(" return static_cast<uint32_t>(\n")
4292 file.Write(" sizeof(ValueType) + // NOLINT\n")
4293 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4297 def WriteImmediateCmdSetHeader(self
, func
, file):
4298 """Writes the SetHeader function for the immediate version of a cmd."""
4299 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
4300 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4304 def WriteImmediateCmdInit(self
, func
, file):
4305 """Writes the Init function for the immediate version of a command."""
4306 raise NotImplementedError(func
.name
)
4308 def WriteImmediateCmdSet(self
, func
, file):
4309 """Writes the Set function for the immediate version of a command."""
4310 raise NotImplementedError(func
.name
)
4312 def WriteCmdHelper(self
, func
, file):
4313 """Writes the cmd helper definition for a cmd."""
4314 code
= """ void %(name)s(%(typed_args)s) {
4315 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4324 "typed_args": func
.MakeTypedCmdArgString(""),
4325 "args": func
.MakeCmdArgString(""),
4328 def WriteImmediateCmdHelper(self
, func
, file):
4329 """Writes the cmd helper definition for the immediate version of a cmd."""
4330 code
= """ void %(name)s(%(typed_args)s) {
4331 const uint32_t s = 0; // TODO(gman): compute correct size
4332 gles2::cmds::%(name)s* c =
4333 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4342 "typed_args": func
.MakeTypedCmdArgString(""),
4343 "args": func
.MakeCmdArgString(""),
4347 class StateSetHandler(TypeHandler
):
4348 """Handler for commands that simply set state."""
4351 TypeHandler
.__init
__(self
)
4353 def WriteHandlerImplementation(self
, func
, file):
4354 """Overrriden from TypeHandler."""
4355 state_name
= func
.GetInfo('state')
4356 state
= _STATES
[state_name
]
4357 states
= state
['states']
4358 args
= func
.GetOriginalArgs()
4359 for ndx
,item
in enumerate(states
):
4361 if 'range_checks' in item
:
4362 for range_check
in item
['range_checks']:
4363 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
4364 if 'nan_check' in item
:
4365 # Drivers might generate an INVALID_VALUE error when a value is set
4366 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
4367 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
4368 # Make this behavior consistent within Chromium, and avoid leaking GL
4369 # errors by generating the error in the command buffer instead of
4370 # letting the GL driver generate it.
4371 code
.append("base::IsNaN(%s)" % args
[ndx
].name
)
4373 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4375 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
4376 ' "%s", "%s out of range");\n' %
4377 (func
.name
, args
[ndx
].name
))
4378 file.Write(" return error::kNoError;\n")
4381 for ndx
,item
in enumerate(states
):
4382 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
4383 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4384 for ndx
,item
in enumerate(states
):
4385 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
4386 if 'state_flag' in state
:
4387 file.Write(" %s = true;\n" % state
['state_flag'])
4388 if not func
.GetInfo("no_gl"):
4389 for ndx
,item
in enumerate(states
):
4390 if item
.get('cached', False):
4391 file.Write(" state_.%s = %s;\n" %
4392 (CachedStateName(item
), args
[ndx
].name
))
4393 file.Write(" %s(%s);\n" %
4394 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4397 def WriteServiceUnitTest(self
, func
, file, *extras
):
4398 """Overrriden from TypeHandler."""
4399 TypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
4400 state_name
= func
.GetInfo('state')
4401 state
= _STATES
[state_name
]
4402 states
= state
['states']
4403 for ndx
,item
in enumerate(states
):
4404 if 'range_checks' in item
:
4405 for check_ndx
, range_check
in enumerate(item
['range_checks']):
4407 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
4408 SpecializedSetup<cmds::%(name)s, 0>(false);
4411 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4412 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4417 arg
.GetValidArg(func
) \
4418 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4421 arg_strings
[ndx
] = range_check
['test_value']
4425 'check_ndx': check_ndx
,
4426 'args': ", ".join(arg_strings
),
4428 for extra
in extras
:
4430 file.Write(valid_test
% vars)
4431 if 'nan_check' in item
:
4433 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
4434 SpecializedSetup<cmds::%(name)s, 0>(false);
4437 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4438 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4443 arg
.GetValidArg(func
) \
4444 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4447 arg_strings
[ndx
] = 'nanf("")'
4451 'args': ", ".join(arg_strings
),
4453 for extra
in extras
:
4455 file.Write(valid_test
% vars)
4458 class StateSetRGBAlphaHandler(TypeHandler
):
4459 """Handler for commands that simply set state that have rgb/alpha."""
4462 TypeHandler
.__init
__(self
)
4464 def WriteHandlerImplementation(self
, func
, file):
4465 """Overrriden from TypeHandler."""
4466 state_name
= func
.GetInfo('state')
4467 state
= _STATES
[state_name
]
4468 states
= state
['states']
4469 args
= func
.GetOriginalArgs()
4470 num_args
= len(args
)
4472 for ndx
,item
in enumerate(states
):
4473 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
4474 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4475 for ndx
, item
in enumerate(states
):
4476 file.Write(" state_.%s = %s;\n" %
4477 (item
['name'], args
[ndx
% num_args
].name
))
4478 if 'state_flag' in state
:
4479 file.Write(" %s = true;\n" % state
['state_flag'])
4480 if not func
.GetInfo("no_gl"):
4481 file.Write(" %s(%s);\n" %
4482 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4486 class StateSetFrontBackSeparateHandler(TypeHandler
):
4487 """Handler for commands that simply set state that have front/back."""
4490 TypeHandler
.__init
__(self
)
4492 def WriteHandlerImplementation(self
, func
, file):
4493 """Overrriden from TypeHandler."""
4494 state_name
= func
.GetInfo('state')
4495 state
= _STATES
[state_name
]
4496 states
= state
['states']
4497 args
= func
.GetOriginalArgs()
4499 num_args
= len(args
)
4500 file.Write(" bool changed = false;\n")
4501 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
4502 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4503 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
4505 for ndx
, item
in enumerate(group
):
4506 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
4507 file.Write(" changed |= %s;\n" % " ||\n ".join(code
))
4509 file.Write(" if (changed) {\n")
4510 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
4511 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4512 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
4513 for ndx
, item
in enumerate(group
):
4514 file.Write(" state_.%s = %s;\n" %
4515 (item
['name'], args
[ndx
+ 1].name
))
4517 if 'state_flag' in state
:
4518 file.Write(" %s = true;\n" % state
['state_flag'])
4519 if not func
.GetInfo("no_gl"):
4520 file.Write(" %s(%s);\n" %
4521 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4525 class StateSetFrontBackHandler(TypeHandler
):
4526 """Handler for commands that simply set state that set both front/back."""
4529 TypeHandler
.__init
__(self
)
4531 def WriteHandlerImplementation(self
, func
, file):
4532 """Overrriden from TypeHandler."""
4533 state_name
= func
.GetInfo('state')
4534 state
= _STATES
[state_name
]
4535 states
= state
['states']
4536 args
= func
.GetOriginalArgs()
4537 num_args
= len(args
)
4539 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
4540 for ndx
, item
in enumerate(group
):
4541 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
4542 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4543 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
4544 for ndx
, item
in enumerate(group
):
4545 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
4546 if 'state_flag' in state
:
4547 file.Write(" %s = true;\n" % state
['state_flag'])
4548 if not func
.GetInfo("no_gl"):
4549 file.Write(" %s(%s);\n" %
4550 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4554 class StateSetNamedParameter(TypeHandler
):
4555 """Handler for commands that set a state chosen with an enum parameter."""
4558 TypeHandler
.__init
__(self
)
4560 def WriteHandlerImplementation(self
, func
, file):
4561 """Overridden from TypeHandler."""
4562 state_name
= func
.GetInfo('state')
4563 state
= _STATES
[state_name
]
4564 states
= state
['states']
4565 args
= func
.GetOriginalArgs()
4566 num_args
= len(args
)
4567 assert num_args
== 2
4568 file.Write(" switch (%s) {\n" % args
[0].name
)
4569 for state
in states
:
4570 file.Write(" case %s:\n" % state
['enum'])
4571 file.Write(" if (state_.%s != %s) {\n" %
4572 (state
['name'], args
[1].name
))
4573 file.Write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
4574 if not func
.GetInfo("no_gl"):
4575 file.Write(" %s(%s);\n" %
4576 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4578 file.Write(" break;\n")
4579 file.Write(" default:\n")
4580 file.Write(" NOTREACHED();\n")
4584 class CustomHandler(TypeHandler
):
4585 """Handler for commands that are auto-generated but require minor tweaks."""
4588 TypeHandler
.__init
__(self
)
4590 def WriteServiceImplementation(self
, func
, file):
4591 """Overrriden from TypeHandler."""
4594 def WriteImmediateServiceImplementation(self
, func
, file):
4595 """Overrriden from TypeHandler."""
4598 def WriteBucketServiceImplementation(self
, func
, file):
4599 """Overrriden from TypeHandler."""
4602 def WriteServiceUnitTest(self
, func
, file, *extras
):
4603 """Overrriden from TypeHandler."""
4604 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4606 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4607 """Overrriden from TypeHandler."""
4608 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4610 def WriteImmediateCmdGetTotalSize(self
, func
, file):
4611 """Overrriden from TypeHandler."""
4613 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
4615 def WriteImmediateCmdInit(self
, func
, file):
4616 """Overrriden from TypeHandler."""
4617 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
4618 self
.WriteImmediateCmdGetTotalSize(func
, file)
4619 file.Write(" SetHeader(total_size);\n")
4620 args
= func
.GetCmdArgs()
4622 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4626 def WriteImmediateCmdSet(self
, func
, file):
4627 """Overrriden from TypeHandler."""
4628 copy_args
= func
.MakeCmdArgString("_", False)
4629 file.Write(" void* Set(void* cmd%s) {\n" %
4630 func
.MakeTypedCmdArgString("_", True))
4631 self
.WriteImmediateCmdGetTotalSize(func
, file)
4632 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
4633 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4634 "cmd, total_size);\n")
4639 class TodoHandler(CustomHandler
):
4640 """Handle for commands that are not yet implemented."""
4642 def NeedsDataTransferFunction(self
, func
):
4643 """Overriden from TypeHandler."""
4646 def WriteImmediateFormatTest(self
, func
, file):
4647 """Overrriden from TypeHandler."""
4650 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4651 """Overrriden from TypeHandler."""
4654 def WriteGLES2Implementation(self
, func
, file):
4655 """Overrriden from TypeHandler."""
4656 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4657 (func
.return_type
, func
.original_name
,
4658 func
.MakeTypedOriginalArgString("")))
4659 file.Write(" // TODO: for now this is a no-op\n")
4662 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4664 if func
.return_type
!= "void":
4665 file.Write(" return 0;\n")
4669 def WriteServiceImplementation(self
, func
, file):
4670 """Overrriden from TypeHandler."""
4671 self
.WriteServiceHandlerFunctionHeader(func
, file)
4672 file.Write(" // TODO: for now this is a no-op\n")
4674 " LOCAL_SET_GL_ERROR("
4675 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4677 file.Write(" return error::kNoError;\n")
4682 class HandWrittenHandler(CustomHandler
):
4683 """Handler for comands where everything must be written by hand."""
4685 def InitFunction(self
, func
):
4686 """Add or adjust anything type specific for this function."""
4687 CustomHandler
.InitFunction(self
, func
)
4688 func
.can_auto_generate
= False
4690 def NeedsDataTransferFunction(self
, func
):
4691 """Overriden from TypeHandler."""
4692 # If specified explicitly, force the data transfer method.
4693 if func
.GetInfo('data_transfer_methods'):
4697 def WriteStruct(self
, func
, file):
4698 """Overrriden from TypeHandler."""
4701 def WriteDocs(self
, func
, file):
4702 """Overrriden from TypeHandler."""
4705 def WriteServiceUnitTest(self
, func
, file, *extras
):
4706 """Overrriden from TypeHandler."""
4707 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4709 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4710 """Overrriden from TypeHandler."""
4711 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4713 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
4714 """Overrriden from TypeHandler."""
4715 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4717 def WriteServiceImplementation(self
, func
, file):
4718 """Overrriden from TypeHandler."""
4721 def WriteImmediateServiceImplementation(self
, func
, file):
4722 """Overrriden from TypeHandler."""
4725 def WriteBucketServiceImplementation(self
, func
, file):
4726 """Overrriden from TypeHandler."""
4729 def WriteImmediateCmdHelper(self
, func
, file):
4730 """Overrriden from TypeHandler."""
4733 def WriteCmdHelper(self
, func
, file):
4734 """Overrriden from TypeHandler."""
4737 def WriteFormatTest(self
, func
, file):
4738 """Overrriden from TypeHandler."""
4739 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
4741 def WriteImmediateFormatTest(self
, func
, file):
4742 """Overrriden from TypeHandler."""
4743 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
4745 def WriteBucketFormatTest(self
, func
, file):
4746 """Overrriden from TypeHandler."""
4747 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
4751 class ManualHandler(CustomHandler
):
4752 """Handler for commands who's handlers must be written by hand."""
4755 CustomHandler
.__init
__(self
)
4757 def InitFunction(self
, func
):
4758 """Overrriden from TypeHandler."""
4759 if (func
.name
== 'CompressedTexImage2DBucket'):
4760 func
.cmd_args
= func
.cmd_args
[:-1]
4761 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
4763 CustomHandler
.InitFunction(self
, func
)
4765 def WriteServiceImplementation(self
, func
, file):
4766 """Overrriden from TypeHandler."""
4769 def WriteBucketServiceImplementation(self
, func
, file):
4770 """Overrriden from TypeHandler."""
4773 def WriteServiceUnitTest(self
, func
, file, *extras
):
4774 """Overrriden from TypeHandler."""
4775 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4777 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4778 """Overrriden from TypeHandler."""
4779 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4781 def WriteImmediateServiceImplementation(self
, func
, file):
4782 """Overrriden from TypeHandler."""
4785 def WriteImmediateFormatTest(self
, func
, file):
4786 """Overrriden from TypeHandler."""
4787 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
4789 def WriteGLES2Implementation(self
, func
, file):
4790 """Overrriden from TypeHandler."""
4791 if func
.GetInfo('impl_func'):
4792 super(ManualHandler
, self
).WriteGLES2Implementation(func
, file)
4794 def WriteGLES2ImplementationHeader(self
, func
, file):
4795 """Overrriden from TypeHandler."""
4796 file.Write("%s %s(%s) override;\n" %
4797 (func
.return_type
, func
.original_name
,
4798 func
.MakeTypedOriginalArgString("")))
4801 def WriteImmediateCmdGetTotalSize(self
, func
, file):
4802 """Overrriden from TypeHandler."""
4803 # TODO(gman): Move this data to _FUNCTION_INFO?
4804 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, file)
4807 class DataHandler(TypeHandler
):
4808 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
4809 glCompressedTexImage2D, glCompressedTexImageSub2D."""
4811 TypeHandler
.__init
__(self
)
4813 def InitFunction(self
, func
):
4814 """Overrriden from TypeHandler."""
4815 if func
.name
== 'CompressedTexSubImage2DBucket':
4816 func
.cmd_args
= func
.cmd_args
[:-1]
4817 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
4819 def WriteGetDataSizeCode(self
, func
, file):
4820 """Overrriden from TypeHandler."""
4821 # TODO(gman): Move this data to _FUNCTION_INFO?
4823 if name
.endswith("Immediate"):
4825 if name
== 'BufferData' or name
== 'BufferSubData':
4826 file.Write(" uint32_t data_size = size;\n")
4827 elif (name
== 'CompressedTexImage2D' or
4828 name
== 'CompressedTexSubImage2D'):
4829 file.Write(" uint32_t data_size = imageSize;\n")
4830 elif (name
== 'CompressedTexSubImage2DBucket'):
4831 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
4832 file.Write(" uint32_t data_size = bucket->size();\n")
4833 file.Write(" GLsizei imageSize = data_size;\n")
4834 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
4835 code
= """ uint32_t data_size;
4836 if (!GLES2Util::ComputeImageDataSize(
4837 width, height, format, type, unpack_alignment_, &data_size)) {
4838 return error::kOutOfBounds;
4844 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
4846 def WriteImmediateCmdGetTotalSize(self
, func
, file):
4847 """Overrriden from TypeHandler."""
4850 def WriteImmediateCmdSizeTest(self
, func
, file):
4851 """Overrriden from TypeHandler."""
4852 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
4854 def WriteImmediateCmdInit(self
, func
, file):
4855 """Overrriden from TypeHandler."""
4856 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
4857 self
.WriteImmediateCmdGetTotalSize(func
, file)
4858 file.Write(" SetHeader(total_size);\n")
4859 args
= func
.GetCmdArgs()
4861 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
4865 def WriteImmediateCmdSet(self
, func
, file):
4866 """Overrriden from TypeHandler."""
4867 copy_args
= func
.MakeCmdArgString("_", False)
4868 file.Write(" void* Set(void* cmd%s) {\n" %
4869 func
.MakeTypedCmdArgString("_", True))
4870 self
.WriteImmediateCmdGetTotalSize(func
, file)
4871 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
4872 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4873 "cmd, total_size);\n")
4877 def WriteImmediateFormatTest(self
, func
, file):
4878 """Overrriden from TypeHandler."""
4879 # TODO(gman): Remove this exception.
4880 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
4883 def WriteServiceUnitTest(self
, func
, file, *extras
):
4884 """Overrriden from TypeHandler."""
4885 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4887 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4888 """Overrriden from TypeHandler."""
4889 file.Write("// TODO(gman): %s\n\n" % func
.name
)
4891 def WriteBucketServiceImplementation(self
, func
, file):
4892 """Overrriden from TypeHandler."""
4893 if not func
.name
== 'CompressedTexSubImage2DBucket':
4894 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, file)
4897 class BindHandler(TypeHandler
):
4898 """Handler for glBind___ type functions."""
4901 TypeHandler
.__init
__(self
)
4903 def WriteServiceUnitTest(self
, func
, file, *extras
):
4904 """Overrriden from TypeHandler."""
4906 if len(func
.GetOriginalArgs()) == 1:
4908 TEST_P(%(test_name)s, %(name)sValidArgs) {
4909 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4910 SpecializedSetup<cmds::%(name)s, 0>(true);
4912 cmd.Init(%(args)s);"""
4915 decoder_->set_unsafe_es3_apis_enabled(true);
4916 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4917 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4918 decoder_->set_unsafe_es3_apis_enabled(false);
4919 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4924 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4925 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4928 if func
.GetInfo("gen_func"):
4930 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
4931 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
4932 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
4933 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4934 SpecializedSetup<cmds::%(name)s, 0>(true);
4936 cmd.Init(kNewClientId);
4937 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4938 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4939 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4942 self
.WriteValidUnitTest(func
, file, valid_test
, {
4943 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
4944 'gl_gen_func_name': func
.GetInfo("gen_func"),
4948 TEST_P(%(test_name)s, %(name)sValidArgs) {
4949 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4950 SpecializedSetup<cmds::%(name)s, 0>(true);
4952 cmd.Init(%(args)s);"""
4955 decoder_->set_unsafe_es3_apis_enabled(true);
4956 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4957 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4958 decoder_->set_unsafe_es3_apis_enabled(false);
4959 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4964 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4965 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4968 if func
.GetInfo("gen_func"):
4970 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
4972 %(gl_func_name)s(%(gl_args_with_new_id)s));
4973 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
4974 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4975 SpecializedSetup<cmds::%(name)s, 0>(true);
4977 cmd.Init(%(args_with_new_id)s);"""
4980 decoder_->set_unsafe_es3_apis_enabled(true);
4981 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4982 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4983 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4984 decoder_->set_unsafe_es3_apis_enabled(false);
4985 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4990 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4991 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4992 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4996 gl_args_with_new_id
= []
4997 args_with_new_id
= []
4998 for arg
in func
.GetOriginalArgs():
4999 if hasattr(arg
, 'resource_type'):
5000 gl_args_with_new_id
.append('kNewServiceId')
5001 args_with_new_id
.append('kNewClientId')
5003 gl_args_with_new_id
.append(arg
.GetValidGLArg(func
))
5004 args_with_new_id
.append(arg
.GetValidArg(func
))
5005 self
.WriteValidUnitTest(func
, file, valid_test
, {
5006 'args_with_new_id': ", ".join(args_with_new_id
),
5007 'gl_args_with_new_id': ", ".join(gl_args_with_new_id
),
5008 'resource_type': func
.GetResourceIdArg().resource_type
,
5009 'gl_gen_func_name': func
.GetInfo("gen_func"),
5013 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5014 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5015 SpecializedSetup<cmds::%(name)s, 0>(false);
5018 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5021 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
5023 def WriteGLES2Implementation(self
, func
, file):
5024 """Writes the GLES2 Implemention."""
5026 impl_func
= func
.GetInfo('impl_func')
5027 impl_decl
= func
.GetInfo('impl_decl')
5029 if (func
.can_auto_generate
and
5030 (impl_func
== None or impl_func
== True) and
5031 (impl_decl
== None or impl_decl
== True)):
5033 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5034 (func
.return_type
, func
.original_name
,
5035 func
.MakeTypedOriginalArgString("")))
5036 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5037 func
.WriteDestinationInitalizationValidation(file)
5038 self
.WriteClientGLCallLog(func
, file)
5039 for arg
in func
.GetOriginalArgs():
5040 arg
.WriteClientSideValidationCode(file, func
)
5042 code
= """ if (Is%(type)sReservedId(%(id)s)) {
5043 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5046 %(name)sHelper(%(arg_string)s);
5051 name_arg
= func
.GetResourceIdArg()
5054 'arg_string': func
.MakeOriginalArgString(""),
5055 'id': name_arg
.name
,
5056 'type': name_arg
.resource_type
,
5057 'lc_type': name_arg
.resource_type
.lower(),
5060 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5061 """Overrriden from TypeHandler."""
5062 client_test
= func
.GetInfo('client_test')
5063 if client_test
== False:
5066 TEST_F(GLES2ImplementationTest, %(name)s) {
5071 expected.cmd.Init(%(cmd_args)s);
5073 gl_->%(name)s(%(args)s);
5074 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5075 if not func
.IsUnsafe():
5078 gl_->%(name)s(%(args)s);
5079 EXPECT_TRUE(NoCommandsWritten());"""
5084 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
5087 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
5092 'args': ", ".join(gl_arg_strings
),
5093 'cmd_args': ", ".join(cmd_arg_strings
),
5097 class GENnHandler(TypeHandler
):
5098 """Handler for glGen___ type functions."""
5101 TypeHandler
.__init
__(self
)
5103 def InitFunction(self
, func
):
5104 """Overrriden from TypeHandler."""
5107 def WriteGetDataSizeCode(self
, func
, file):
5108 """Overrriden from TypeHandler."""
5109 code
= """ uint32_t data_size;
5110 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5111 return error::kOutOfBounds;
5116 def WriteHandlerImplementation (self
, func
, file):
5117 """Overrriden from TypeHandler."""
5118 file.Write(" if (!%sHelper(n, %s)) {\n"
5119 " return error::kInvalidArguments;\n"
5121 (func
.name
, func
.GetLastOriginalArg().name
))
5123 def WriteImmediateHandlerImplementation(self
, func
, file):
5124 """Overrriden from TypeHandler."""
5126 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5127 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5128 return error::kInvalidArguments;
5131 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5132 gl%(func_name)s(n, service_ids.get());
5133 for (GLsizei ii = 0; ii < n; ++ii) {
5134 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5136 """ % { 'func_name': func
.original_name
,
5137 'last_arg_name': func
.GetLastOriginalArg().name
,
5138 'resource_name': func
.GetInfo('resource_type') })
5140 file.Write(" if (!%sHelper(n, %s)) {\n"
5141 " return error::kInvalidArguments;\n"
5143 (func
.original_name
, func
.GetLastOriginalArg().name
))
5145 def WriteGLES2Implementation(self
, func
, file):
5146 """Overrriden from TypeHandler."""
5147 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
5148 for (GLsizei i = 0; i < n; ++i) {
5149 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5151 });""" % func
.GetOriginalArgs()[1].name
)
5153 'log_code': log_code
,
5154 'return_type': func
.return_type
,
5155 'name': func
.original_name
,
5156 'typed_args': func
.MakeTypedOriginalArgString(""),
5157 'args': func
.MakeOriginalArgString(""),
5158 'resource_types': func
.GetInfo('resource_types'),
5159 'count_name': func
.GetOriginalArgs()[0].name
,
5162 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5164 func
.WriteDestinationInitalizationValidation(file)
5165 self
.WriteClientGLCallLog(func
, file)
5166 for arg
in func
.GetOriginalArgs():
5167 arg
.WriteClientSideValidationCode(file, func
)
5168 not_shared
= func
.GetInfo('not_shared')
5172 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5173 for (GLsizei ii = 0; ii < n; ++ii)
5174 %s[ii] = id_allocator->AllocateID();""" %
5175 (func
.GetInfo('resource_types'), func
.GetOriginalArgs()[1].name
))
5177 alloc_code
= (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5178 MakeIds(this, 0, %(args)s);""" % args
)
5179 args
['alloc_code'] = alloc_code
5181 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5183 %(name)sHelper(%(args)s);
5184 helper_->%(name)sImmediate(%(args)s);
5185 if (share_group_->bind_generates_resource())
5186 helper_->CommandBufferHelper::Flush();
5192 file.Write(code
% args
)
5194 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5195 """Overrriden from TypeHandler."""
5197 TEST_F(GLES2ImplementationTest, %(name)s) {
5198 GLuint ids[2] = { 0, };
5200 cmds::%(name)sImmediate gen;
5204 expected.gen.Init(arraysize(ids), &ids[0]);
5205 expected.data[0] = k%(types)sStartId;
5206 expected.data[1] = k%(types)sStartId + 1;
5207 gl_->%(name)s(arraysize(ids), &ids[0]);
5208 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5209 EXPECT_EQ(k%(types)sStartId, ids[0]);
5210 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5215 'types': func
.GetInfo('resource_types'),
5218 def WriteServiceUnitTest(self
, func
, file, *extras
):
5219 """Overrriden from TypeHandler."""
5221 TEST_P(%(test_name)s, %(name)sValidArgs) {
5222 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5223 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5224 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5225 SpecializedSetup<cmds::%(name)s, 0>(true);
5228 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5229 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5233 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5234 EXPECT_EQ(kNewServiceId, service_id)
5239 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5242 self
.WriteValidUnitTest(func
, file, valid_test
, {
5243 'resource_name': func
.GetInfo('resource_type'),
5246 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5247 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5248 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5249 SpecializedSetup<cmds::%(name)s, 0>(false);
5252 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5255 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5256 'resource_name': func
.GetInfo('resource_type').lower(),
5259 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5260 """Overrriden from TypeHandler."""
5262 TEST_P(%(test_name)s, %(name)sValidArgs) {
5263 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5264 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5265 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5266 GLuint temp = kNewClientId;
5267 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5270 decoder_->set_unsafe_es3_apis_enabled(true);"""
5272 cmd->Init(1, &temp);
5273 EXPECT_EQ(error::kNoError,
5274 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5275 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5279 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5280 EXPECT_EQ(kNewServiceId, service_id);
5281 decoder_->set_unsafe_es3_apis_enabled(false);
5282 EXPECT_EQ(error::kUnknownCommand,
5283 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5288 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5291 self
.WriteValidUnitTest(func
, file, valid_test
, {
5292 'resource_name': func
.GetInfo('resource_type'),
5295 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5296 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5297 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5298 SpecializedSetup<cmds::%(name)s, 0>(false);
5299 cmd->Init(1, &client_%(resource_name)s_id_);"""
5302 decoder_->set_unsafe_es3_apis_enabled(true);
5303 EXPECT_EQ(error::kInvalidArguments,
5304 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5305 decoder_->set_unsafe_es3_apis_enabled(false);
5310 EXPECT_EQ(error::kInvalidArguments,
5311 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5314 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5315 'resource_name': func
.GetInfo('resource_type').lower(),
5318 def WriteImmediateCmdComputeSize(self
, func
, file):
5319 """Overrriden from TypeHandler."""
5320 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5322 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5325 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5326 file.Write(" return static_cast<uint32_t>(\n")
5327 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5331 def WriteImmediateCmdSetHeader(self
, func
, file):
5332 """Overrriden from TypeHandler."""
5333 file.Write(" void SetHeader(GLsizei n) {\n")
5334 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5338 def WriteImmediateCmdInit(self
, func
, file):
5339 """Overrriden from TypeHandler."""
5340 last_arg
= func
.GetLastOriginalArg()
5341 file.Write(" void Init(%s, %s _%s) {\n" %
5342 (func
.MakeTypedCmdArgString("_"),
5343 last_arg
.type, last_arg
.name
))
5344 file.Write(" SetHeader(_n);\n")
5345 args
= func
.GetCmdArgs()
5347 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5348 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5349 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
5353 def WriteImmediateCmdSet(self
, func
, file):
5354 """Overrriden from TypeHandler."""
5355 last_arg
= func
.GetLastOriginalArg()
5356 copy_args
= func
.MakeCmdArgString("_", False)
5357 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5358 (func
.MakeTypedCmdArgString("_", True),
5359 last_arg
.type, last_arg
.name
))
5360 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5361 (copy_args
, last_arg
.name
))
5362 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5363 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5368 def WriteImmediateCmdHelper(self
, func
, file):
5369 """Overrriden from TypeHandler."""
5370 code
= """ void %(name)s(%(typed_args)s) {
5371 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5372 gles2::cmds::%(name)s* c =
5373 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5382 "typed_args": func
.MakeTypedOriginalArgString(""),
5383 "args": func
.MakeOriginalArgString(""),
5386 def WriteImmediateFormatTest(self
, func
, file):
5387 """Overrriden from TypeHandler."""
5388 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5389 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5390 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5391 (func
.name
, func
.name
))
5392 file.Write(" void* next_cmd = cmd.Set(\n")
5393 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5394 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5396 file.Write(" cmd.header.command);\n")
5397 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5398 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5399 file.Write(" cmd.header.size * 4u);\n")
5400 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5401 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5402 file.Write(" next_cmd, sizeof(cmd) +\n")
5403 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5404 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5409 class CreateHandler(TypeHandler
):
5410 """Handler for glCreate___ type functions."""
5413 TypeHandler
.__init
__(self
)
5415 def InitFunction(self
, func
):
5416 """Overrriden from TypeHandler."""
5417 func
.AddCmdArg(Argument("client_id", 'uint32_t'))
5419 def __GetResourceType(self
, func
):
5420 if func
.return_type
== "GLsync":
5423 return func
.name
[6:] # Create*
5425 def WriteServiceUnitTest(self
, func
, file, *extras
):
5426 """Overrriden from TypeHandler."""
5428 TEST_P(%(test_name)s, %(name)sValidArgs) {
5429 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5430 .WillOnce(Return(%(const_service_id)s));
5431 SpecializedSetup<cmds::%(name)s, 0>(true);
5433 cmd.Init(%(args)s%(comma)skNewClientId);"""
5436 decoder_->set_unsafe_es3_apis_enabled(true);"""
5438 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5439 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5442 %(return_type)s service_id = 0;
5443 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
5444 EXPECT_EQ(%(const_service_id)s, service_id);
5445 decoder_->set_unsafe_es3_apis_enabled(false);
5446 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5451 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
5456 for arg
in func
.GetOriginalArgs():
5457 if not arg
.IsConstant():
5461 if func
.return_type
== 'GLsync':
5462 id_type_cast
= ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
5463 "<GLsync>(kNewServiceId);\n ")
5464 const_service_id
= "kNewServiceIdGLuint"
5467 const_service_id
= "kNewServiceId"
5468 self
.WriteValidUnitTest(func
, file, valid_test
, {
5470 'resource_type': self
.__GetResourceType
(func
),
5471 'return_type': func
.return_type
,
5472 'id_type_cast': id_type_cast
,
5473 'const_service_id': const_service_id
,
5476 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5477 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5478 SpecializedSetup<cmds::%(name)s, 0>(false);
5480 cmd.Init(%(args)s%(comma)skNewClientId);
5481 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
5484 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5488 def WriteHandlerImplementation (self
, func
, file):
5489 """Overrriden from TypeHandler."""
5491 code
= """ uint32_t client_id = c.client_id;
5492 %(return_type)s service_id = 0;
5493 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
5494 return error::kInvalidArguments;
5496 service_id = %(gl_func_name)s(%(gl_args)s);
5498 group_->Add%(resource_name)sId(client_id, service_id);
5502 code
= """ uint32_t client_id = c.client_id;
5503 if (Get%(resource_name)s(client_id)) {
5504 return error::kInvalidArguments;
5506 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
5508 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
5512 'resource_name': self
.__GetResourceType
(func
),
5513 'return_type': func
.return_type
,
5514 'gl_func_name': func
.GetGLFunctionName(),
5515 'gl_args': func
.MakeOriginalArgString(""),
5516 'gl_args_with_comma': func
.MakeOriginalArgString("", True) })
5518 def WriteGLES2Implementation(self
, func
, file):
5519 """Overrriden from TypeHandler."""
5520 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5521 (func
.return_type
, func
.original_name
,
5522 func
.MakeTypedOriginalArgString("")))
5523 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5524 func
.WriteDestinationInitalizationValidation(file)
5525 self
.WriteClientGLCallLog(func
, file)
5526 for arg
in func
.GetOriginalArgs():
5527 arg
.WriteClientSideValidationCode(file, func
)
5528 file.Write(" GLuint client_id;\n")
5529 if func
.return_type
== "GLsync":
5531 " GetIdHandler(id_namespaces::kSyncs)->\n")
5534 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
5535 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
5536 file.Write(" helper_->%s(%s);\n" %
5537 (func
.name
, func
.MakeCmdArgString("")))
5538 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
5539 file.Write(" CheckGLError();\n")
5540 if func
.return_type
== "GLsync":
5541 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
5543 file.Write(" return client_id;\n")
5548 class DeleteHandler(TypeHandler
):
5549 """Handler for glDelete___ single resource type functions."""
5552 TypeHandler
.__init
__(self
)
5554 def WriteServiceImplementation(self
, func
, file):
5555 """Overrriden from TypeHandler."""
5557 TypeHandler
.WriteServiceImplementation(self
, func
, file)
5558 # HandleDeleteShader and HandleDeleteProgram are manually written.
5561 def WriteGLES2Implementation(self
, func
, file):
5562 """Overrriden from TypeHandler."""
5563 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5564 (func
.return_type
, func
.original_name
,
5565 func
.MakeTypedOriginalArgString("")))
5566 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5567 func
.WriteDestinationInitalizationValidation(file)
5568 self
.WriteClientGLCallLog(func
, file)
5569 for arg
in func
.GetOriginalArgs():
5570 arg
.WriteClientSideValidationCode(file, func
)
5572 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
5573 file.Write(" %sHelper(%s);\n" %
5574 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
5575 file.Write(" CheckGLError();\n")
5579 def WriteHandlerImplementation (self
, func
, file):
5580 """Overrriden from TypeHandler."""
5581 assert len(func
.GetOriginalArgs()) == 1
5582 arg
= func
.GetOriginalArgs()[0]
5584 file.Write(""" %(arg_type)s service_id = 0;
5585 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
5586 glDelete%(resource_type)s(service_id);
5587 group_->Remove%(resource_type)sId(%(arg_name)s);
5590 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
5592 """ % { 'resource_type': func
.GetInfo('resource_type'),
5593 'arg_name': arg
.name
,
5594 'arg_type': arg
.type,
5595 'func_name': func
.original_name
})
5597 file.Write(" %sHelper(%s);\n" % (func
.original_name
, arg
.name
))
5599 class DELnHandler(TypeHandler
):
5600 """Handler for glDelete___ type functions."""
5603 TypeHandler
.__init
__(self
)
5605 def WriteGetDataSizeCode(self
, func
, file):
5606 """Overrriden from TypeHandler."""
5607 code
= """ uint32_t data_size;
5608 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5609 return error::kOutOfBounds;
5614 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5615 """Overrriden from TypeHandler."""
5617 TEST_F(GLES2ImplementationTest, %(name)s) {
5618 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
5620 cmds::%(name)sImmediate del;
5624 expected.del.Init(arraysize(ids), &ids[0]);
5625 expected.data[0] = k%(types)sStartId;
5626 expected.data[1] = k%(types)sStartId + 1;
5627 gl_->%(name)s(arraysize(ids), &ids[0]);
5628 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5633 'types': func
.GetInfo('resource_types'),
5636 def WriteServiceUnitTest(self
, func
, file, *extras
):
5637 """Overrriden from TypeHandler."""
5639 TEST_P(%(test_name)s, %(name)sValidArgs) {
5642 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5644 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5645 SpecializedSetup<cmds::%(name)s, 0>(true);
5648 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5649 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5651 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5654 self
.WriteValidUnitTest(func
, file, valid_test
, {
5655 'resource_name': func
.GetInfo('resource_type').lower(),
5656 'upper_resource_name': func
.GetInfo('resource_type'),
5659 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5660 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
5661 SpecializedSetup<cmds::%(name)s, 0>(false);
5664 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5667 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
5669 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5670 """Overrriden from TypeHandler."""
5672 TEST_P(%(test_name)s, %(name)sValidArgs) {
5675 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5677 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5678 SpecializedSetup<cmds::%(name)s, 0>(true);
5679 cmd.Init(1, &client_%(resource_name)s_id_);"""
5682 decoder_->set_unsafe_es3_apis_enabled(true);"""
5684 EXPECT_EQ(error::kNoError,
5685 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5686 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5689 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
5690 client_%(resource_name)s_id_, NULL));
5691 decoder_->set_unsafe_es3_apis_enabled(false);
5692 EXPECT_EQ(error::kUnknownCommand,
5693 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5699 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5702 self
.WriteValidUnitTest(func
, file, valid_test
, {
5703 'resource_name': func
.GetInfo('resource_type').lower(),
5704 'upper_resource_name': func
.GetInfo('resource_type'),
5707 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5708 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5709 SpecializedSetup<cmds::%(name)s, 0>(false);
5710 GLuint temp = kInvalidClientId;
5711 cmd.Init(1, &temp);"""
5714 decoder_->set_unsafe_es3_apis_enabled(true);
5715 EXPECT_EQ(error::kNoError,
5716 ExecuteImmediateCmd(cmd, sizeof(temp)));
5717 decoder_->set_unsafe_es3_apis_enabled(false);
5718 EXPECT_EQ(error::kUnknownCommand,
5719 ExecuteImmediateCmd(cmd, sizeof(temp)));
5724 EXPECT_EQ(error::kNoError,
5725 ExecuteImmediateCmd(cmd, sizeof(temp)));
5728 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
5730 def WriteHandlerImplementation (self
, func
, file):
5731 """Overrriden from TypeHandler."""
5732 file.Write(" %sHelper(n, %s);\n" %
5733 (func
.name
, func
.GetLastOriginalArg().name
))
5735 def WriteImmediateHandlerImplementation (self
, func
, file):
5736 """Overrriden from TypeHandler."""
5738 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5739 GLuint service_id = 0;
5740 if (group_->Get%(resource_type)sServiceId(
5741 %(last_arg_name)s[ii], &service_id)) {
5742 glDelete%(resource_type)ss(1, &service_id);
5743 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
5746 """ % { 'resource_type': func
.GetInfo('resource_type'),
5747 'last_arg_name': func
.GetLastOriginalArg().name
})
5749 file.Write(" %sHelper(n, %s);\n" %
5750 (func
.original_name
, func
.GetLastOriginalArg().name
))
5752 def WriteGLES2Implementation(self
, func
, file):
5753 """Overrriden from TypeHandler."""
5754 impl_decl
= func
.GetInfo('impl_decl')
5755 if impl_decl
== None or impl_decl
== True:
5757 'return_type': func
.return_type
,
5758 'name': func
.original_name
,
5759 'typed_args': func
.MakeTypedOriginalArgString(""),
5760 'args': func
.MakeOriginalArgString(""),
5761 'resource_type': func
.GetInfo('resource_type').lower(),
5762 'count_name': func
.GetOriginalArgs()[0].name
,
5765 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5767 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5768 func
.WriteDestinationInitalizationValidation(file)
5769 self
.WriteClientGLCallLog(func
, file)
5770 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5771 for (GLsizei i = 0; i < n; ++i) {
5772 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5775 """ % func
.GetOriginalArgs()[1].name
)
5776 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
5777 for (GLsizei i = 0; i < n; ++i) {
5781 """ % func
.GetOriginalArgs()[1].name
)
5782 for arg
in func
.GetOriginalArgs():
5783 arg
.WriteClientSideValidationCode(file, func
)
5784 code
= """ %(name)sHelper(%(args)s);
5789 file.Write(code
% args
)
5791 def WriteImmediateCmdComputeSize(self
, func
, file):
5792 """Overrriden from TypeHandler."""
5793 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5795 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5798 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5799 file.Write(" return static_cast<uint32_t>(\n")
5800 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5804 def WriteImmediateCmdSetHeader(self
, func
, file):
5805 """Overrriden from TypeHandler."""
5806 file.Write(" void SetHeader(GLsizei n) {\n")
5807 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5811 def WriteImmediateCmdInit(self
, func
, file):
5812 """Overrriden from TypeHandler."""
5813 last_arg
= func
.GetLastOriginalArg()
5814 file.Write(" void Init(%s, %s _%s) {\n" %
5815 (func
.MakeTypedCmdArgString("_"),
5816 last_arg
.type, last_arg
.name
))
5817 file.Write(" SetHeader(_n);\n")
5818 args
= func
.GetCmdArgs()
5820 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5821 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5822 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
5826 def WriteImmediateCmdSet(self
, func
, file):
5827 """Overrriden from TypeHandler."""
5828 last_arg
= func
.GetLastOriginalArg()
5829 copy_args
= func
.MakeCmdArgString("_", False)
5830 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5831 (func
.MakeTypedCmdArgString("_", True),
5832 last_arg
.type, last_arg
.name
))
5833 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5834 (copy_args
, last_arg
.name
))
5835 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5836 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5841 def WriteImmediateCmdHelper(self
, func
, file):
5842 """Overrriden from TypeHandler."""
5843 code
= """ void %(name)s(%(typed_args)s) {
5844 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5845 gles2::cmds::%(name)s* c =
5846 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5855 "typed_args": func
.MakeTypedOriginalArgString(""),
5856 "args": func
.MakeOriginalArgString(""),
5859 def WriteImmediateFormatTest(self
, func
, file):
5860 """Overrriden from TypeHandler."""
5861 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5862 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5863 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5864 (func
.name
, func
.name
))
5865 file.Write(" void* next_cmd = cmd.Set(\n")
5866 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5867 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5869 file.Write(" cmd.header.command);\n")
5870 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5871 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5872 file.Write(" cmd.header.size * 4u);\n")
5873 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5874 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5875 file.Write(" next_cmd, sizeof(cmd) +\n")
5876 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5877 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5882 class GETnHandler(TypeHandler
):
5883 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
5886 TypeHandler
.__init
__(self
)
5888 def NeedsDataTransferFunction(self
, func
):
5889 """Overriden from TypeHandler."""
5892 def WriteServiceImplementation(self
, func
, file):
5893 """Overrriden from TypeHandler."""
5894 self
.WriteServiceHandlerFunctionHeader(func
, file)
5895 last_arg
= func
.GetLastOriginalArg()
5896 # All except shm_id and shm_offset.
5897 all_but_last_args
= func
.GetCmdArgs()[:-2]
5898 for arg
in all_but_last_args
:
5899 arg
.WriteGetCode(file)
5901 code
= """ typedef cmds::%(func_name)s::Result Result;
5902 GLsizei num_values = 0;
5903 GetNumValuesReturnedForGLGet(pname, &num_values);
5904 Result* result = GetSharedMemoryAs<Result*>(
5905 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
5906 Result::ComputeSize(num_values));
5907 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
5910 'last_arg_type': last_arg
.type,
5911 'last_arg_name': last_arg
.name
,
5912 'func_name': func
.name
,
5914 func
.WriteHandlerValidation(file)
5915 code
= """ // Check that the client initialized the result.
5916 if (result->size != 0) {
5917 return error::kInvalidArguments;
5920 shadowed
= func
.GetInfo('shadowed')
5922 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
5924 func
.WriteHandlerImplementation(file)
5926 code
= """ result->SetNumResults(num_values);
5927 return error::kNoError;
5931 code
= """ GLenum error = glGetError();
5932 if (error == GL_NO_ERROR) {
5933 result->SetNumResults(num_values);
5935 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
5937 return error::kNoError;
5941 file.Write(code
% {'func_name': func
.name
})
5943 def WriteGLES2Implementation(self
, func
, file):
5944 """Overrriden from TypeHandler."""
5945 impl_decl
= func
.GetInfo('impl_decl')
5946 if impl_decl
== None or impl_decl
== True:
5947 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5948 (func
.return_type
, func
.original_name
,
5949 func
.MakeTypedOriginalArgString("")))
5950 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5951 func
.WriteDestinationInitalizationValidation(file)
5952 self
.WriteClientGLCallLog(func
, file)
5953 for arg
in func
.GetOriginalArgs():
5954 arg
.WriteClientSideValidationCode(file, func
)
5955 all_but_last_args
= func
.GetOriginalArgs()[:-1]
5957 has_length_arg
= False
5958 for arg
in all_but_last_args
:
5959 if arg
.type == 'GLsync':
5960 args
.append('ToGLuint(%s)' % arg
.name
)
5961 elif arg
.name
.endswith('size') and arg
.type == 'GLsizei':
5963 elif arg
.name
== 'length':
5964 has_length_arg
= True
5967 args
.append(arg
.name
)
5968 arg_string
= ", ".join(args
)
5972 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()]))
5973 self
.WriteTraceEvent(func
, file)
5974 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
5977 typedef cmds::%(func_name)s::Result Result;
5978 Result* result = GetResultAs<Result*>();
5982 result->SetNumResults(0);
5983 helper_->%(func_name)s(%(arg_string)s,
5984 GetResultShmId(), GetResultShmOffset());
5986 result->CopyResult(%(last_arg_name)s);
5987 GPU_CLIENT_LOG_CODE_BLOCK({
5988 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
5989 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
5995 *length = result->GetNumResults();
6002 'func_name': func
.name
,
6003 'arg_string': arg_string
,
6004 'all_arg_string': all_arg_string
,
6005 'last_arg_name': func
.GetLastOriginalArg().name
,
6008 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6009 """Writes the GLES2 Implemention unit test."""
6011 TEST_F(GLES2ImplementationTest, %(name)s) {
6015 typedef cmds::%(name)s::Result Result;
6016 Result::Type result = 0;
6018 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
6019 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6020 EXPECT_CALL(*command_buffer(), OnFlush())
6021 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
6022 .RetiresOnSaturation();
6023 gl_->%(name)s(%(args)s, &result);
6024 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6025 EXPECT_EQ(static_cast<Result::Type>(1), result);
6028 first_cmd_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func
)
6029 if not first_cmd_arg
:
6032 first_gl_arg
= func
.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6035 cmd_arg_strings
= [first_cmd_arg
]
6036 for arg
in func
.GetCmdArgs()[1:-2]:
6037 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
6038 gl_arg_strings
= [first_gl_arg
]
6039 for arg
in func
.GetOriginalArgs()[1:-1]:
6040 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
6044 'args': ", ".join(gl_arg_strings
),
6045 'cmd_args': ", ".join(cmd_arg_strings
),
6048 def WriteServiceUnitTest(self
, func
, file, *extras
):
6049 """Overrriden from TypeHandler."""
6051 TEST_P(%(test_name)s, %(name)sValidArgs) {
6052 EXPECT_CALL(*gl_, GetError())
6053 .WillOnce(Return(GL_NO_ERROR))
6054 .WillOnce(Return(GL_NO_ERROR))
6055 .RetiresOnSaturation();
6056 SpecializedSetup<cmds::%(name)s, 0>(true);
6057 typedef cmds::%(name)s::Result Result;
6058 Result* result = static_cast<Result*>(shared_memory_address_);
6059 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6062 cmd.Init(%(cmd_args)s);"""
6065 decoder_->set_unsafe_es3_apis_enabled(true);"""
6067 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6068 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6070 result->GetNumResults());
6071 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6074 decoder_->set_unsafe_es3_apis_enabled(false);
6075 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6080 cmd_arg_strings
= []
6082 for arg
in func
.GetOriginalArgs()[:-1]:
6083 if arg
.name
== 'length':
6084 gl_arg_value
= 'nullptr'
6085 elif arg
.name
.endswith('size'):
6086 gl_arg_value
= ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6088 elif arg
.type == 'GLsync':
6089 gl_arg_value
= 'reinterpret_cast<GLsync>(kServiceSyncId)'
6091 gl_arg_value
= arg
.GetValidGLArg(func
)
6092 gl_arg_strings
.append(gl_arg_value
)
6093 if arg
.name
== 'pname':
6094 valid_pname
= gl_arg_value
6095 if arg
.name
.endswith('size') or arg
.name
== 'length':
6097 if arg
.type == 'GLsync':
6098 arg_value
= 'client_sync_id_'
6100 arg_value
= arg
.GetValidArg(func
)
6101 cmd_arg_strings
.append(arg_value
)
6102 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
6103 gl_arg_strings
.append("_")
6105 gl_arg_strings
.append("result->GetData()")
6106 cmd_arg_strings
.append("shared_memory_id_")
6107 cmd_arg_strings
.append("shared_memory_offset_")
6109 self
.WriteValidUnitTest(func
, file, valid_test
, {
6110 'local_gl_args': ", ".join(gl_arg_strings
),
6111 'cmd_args': ", ".join(cmd_arg_strings
),
6112 'valid_pname': valid_pname
,
6115 if not func
.IsUnsafe():
6117 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6118 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6119 SpecializedSetup<cmds::%(name)s, 0>(false);
6120 cmds::%(name)s::Result* result =
6121 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6125 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6126 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6129 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
6131 class ArrayArgTypeHandler(TypeHandler
):
6132 """Base class for type handlers that handle args that are arrays"""
6135 TypeHandler
.__init
__(self
)
6137 def GetArrayType(self
, func
):
6138 """Returns the type of the element in the element array being PUT to."""
6139 for arg
in func
.GetOriginalArgs():
6141 element_type
= arg
.GetPointedType()
6144 # Special case: array type handler is used for a function that is forwarded
6145 # to the actual array type implementation
6146 element_type
= func
.GetOriginalArgs()[-1].type
6147 assert all(arg
.type == element_type \
6148 for arg
in func
.GetOriginalArgs()[-self
.GetArrayCount(func
):])
6151 def GetArrayCount(self
, func
):
6152 """Returns the count of the elements in the array being PUT to."""
6153 return func
.GetInfo('count')
6155 class PUTHandler(ArrayArgTypeHandler
):
6156 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6159 ArrayArgTypeHandler
.__init
__(self
)
6161 def WriteServiceUnitTest(self
, func
, file, *extras
):
6162 """Writes the service unit test for a command."""
6163 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6164 if func
.GetInfo("first_element_only"):
6166 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()
6168 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
6169 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6170 ", ".join(gl_arg_strings
))
6172 TEST_P(%(test_name)s, %(name)sValidArgs) {
6173 SpecializedSetup<cmds::%(name)s, 0>(true);
6176 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6178 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6179 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6183 'data_type': self
.GetArrayType(func
),
6184 'data_value': func
.GetInfo('data_value') or '0',
6185 'expected_call': expected_call
,
6187 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6190 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6191 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6192 SpecializedSetup<cmds::%(name)s, 0>(false);
6195 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6196 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6199 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6201 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6202 """Writes the service unit test for a command."""
6204 TEST_P(%(test_name)s, %(name)sValidArgs) {
6205 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6206 SpecializedSetup<cmds::%(name)s, 0>(true);
6207 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6208 cmd.Init(%(gl_args)s, &temp[0]);
6211 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6212 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6215 decoder_->set_unsafe_es3_apis_enabled(true);"""
6217 EXPECT_EQ(error::kNoError,
6218 ExecuteImmediateCmd(cmd, sizeof(temp)));
6219 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6222 decoder_->set_unsafe_es3_apis_enabled(false);
6223 EXPECT_EQ(error::kUnknownCommand,
6224 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6229 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6231 gl_any_strings
= ["_"] * len(gl_arg_strings
)
6234 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
6235 'data_type': self
.GetArrayType(func
),
6236 'data_count': self
.GetArrayCount(func
),
6237 'data_value': func
.GetInfo('data_value') or '0',
6238 'gl_args': ", ".join(gl_arg_strings
),
6239 'gl_any_args': ", ".join(gl_any_strings
),
6241 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6244 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6245 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6248 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6252 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6255 SpecializedSetup<cmds::%(name)s, 0>(false);
6256 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6257 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6260 decoder_->set_unsafe_es3_apis_enabled(true);
6261 EXPECT_EQ(error::%(parse_result)s,
6262 ExecuteImmediateCmd(cmd, sizeof(temp)));
6263 decoder_->set_unsafe_es3_apis_enabled(false);
6268 EXPECT_EQ(error::%(parse_result)s,
6269 ExecuteImmediateCmd(cmd, sizeof(temp)));
6273 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6275 def WriteGetDataSizeCode(self
, func
, file):
6276 """Overrriden from TypeHandler."""
6277 code
= """ uint32_t data_size;
6278 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6279 return error::kOutOfBounds;
6282 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6283 if func
.IsImmediate():
6284 file.Write(" if (data_size > immediate_data_size) {\n")
6285 file.Write(" return error::kOutOfBounds;\n")
6288 def __NeedsToCalcDataCount(self
, func
):
6289 use_count_func
= func
.GetInfo('use_count_func')
6290 return use_count_func
!= None and use_count_func
!= False
6292 def WriteGLES2Implementation(self
, func
, file):
6293 """Overrriden from TypeHandler."""
6294 impl_func
= func
.GetInfo('impl_func')
6295 if (impl_func
!= None and impl_func
!= True):
6297 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6298 (func
.return_type
, func
.original_name
,
6299 func
.MakeTypedOriginalArgString("")))
6300 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6301 func
.WriteDestinationInitalizationValidation(file)
6302 self
.WriteClientGLCallLog(func
, file)
6304 if self
.__NeedsToCalcDataCount
(func
):
6305 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6306 (func
.name
, func
.GetOriginalArgs()[0].name
))
6307 file.Write(" DCHECK_LE(count, %du);\n" % self
.GetArrayCount(func
))
6309 file.Write(" size_t count = %d;" % self
.GetArrayCount(func
))
6310 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
6311 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6312 func
.GetLastOriginalArg().name
)
6313 for arg
in func
.GetOriginalArgs():
6314 arg
.WriteClientSideValidationCode(file, func
)
6315 file.Write(" helper_->%sImmediate(%s);\n" %
6316 (func
.name
, func
.MakeOriginalArgString("")))
6317 file.Write(" CheckGLError();\n")
6321 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6322 """Writes the GLES2 Implemention unit test."""
6323 client_test
= func
.GetInfo('client_test')
6324 if (client_test
!= None and client_test
!= True):
6327 TEST_F(GLES2ImplementationTest, %(name)s) {
6328 %(type)s data[%(count)d] = {0};
6330 cmds::%(name)sImmediate cmd;
6331 %(type)s data[%(count)d];
6334 for (int jj = 0; jj < %(count)d; ++jj) {
6335 data[jj] = static_cast<%(type)s>(jj);
6338 expected.cmd.Init(%(cmd_args)s, &data[0]);
6339 gl_->%(name)s(%(args)s, &data[0]);
6340 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6344 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
6347 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6352 'type': self
.GetArrayType(func
),
6353 'count': self
.GetArrayCount(func
),
6354 'args': ", ".join(gl_arg_strings
),
6355 'cmd_args': ", ".join(cmd_arg_strings
),
6358 def WriteImmediateCmdComputeSize(self
, func
, file):
6359 """Overrriden from TypeHandler."""
6360 file.Write(" static uint32_t ComputeDataSize() {\n")
6361 file.Write(" return static_cast<uint32_t>(\n")
6362 file.Write(" sizeof(%s) * %d);\n" %
6363 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6366 if self
.__NeedsToCalcDataCount
(func
):
6367 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6368 (func
.GetOriginalArgs()[0].type,
6369 func
.GetOriginalArgs()[0].name
))
6370 file.Write(" return static_cast<uint32_t>(\n")
6371 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6372 (self
.GetArrayType(func
), func
.original_name
,
6373 func
.GetOriginalArgs()[0].name
))
6376 file.Write(" static uint32_t ComputeSize() {\n")
6377 file.Write(" return static_cast<uint32_t>(\n")
6379 " sizeof(ValueType) + ComputeDataSize());\n")
6383 def WriteImmediateCmdSetHeader(self
, func
, file):
6384 """Overrriden from TypeHandler."""
6385 file.Write(" void SetHeader() {\n")
6387 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6391 def WriteImmediateCmdInit(self
, func
, file):
6392 """Overrriden from TypeHandler."""
6393 last_arg
= func
.GetLastOriginalArg()
6394 file.Write(" void Init(%s, %s _%s) {\n" %
6395 (func
.MakeTypedCmdArgString("_"),
6396 last_arg
.type, last_arg
.name
))
6397 file.Write(" SetHeader();\n")
6398 args
= func
.GetCmdArgs()
6400 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6401 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6402 if self
.__NeedsToCalcDataCount
(func
):
6403 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
6404 (last_arg
.name
, func
.GetOriginalArgs()[0].name
))
6406 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6407 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6408 ComputeEffectiveDataSize(%(arg)s);
6409 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6410 """ % { 'arg': func
.GetOriginalArgs()[0].name
, })
6412 file.Write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
6416 def WriteImmediateCmdSet(self
, func
, file):
6417 """Overrriden from TypeHandler."""
6418 last_arg
= func
.GetLastOriginalArg()
6419 copy_args
= func
.MakeCmdArgString("_", False)
6420 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6421 (func
.MakeTypedCmdArgString("_", True),
6422 last_arg
.type, last_arg
.name
))
6423 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6424 (copy_args
, last_arg
.name
))
6425 file.Write(" const uint32_t size = ComputeSize();\n")
6426 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6431 def WriteImmediateCmdHelper(self
, func
, file):
6432 """Overrriden from TypeHandler."""
6433 code
= """ void %(name)s(%(typed_args)s) {
6434 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
6435 gles2::cmds::%(name)s* c =
6436 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6445 "typed_args": func
.MakeTypedOriginalArgString(""),
6446 "args": func
.MakeOriginalArgString(""),
6449 def WriteImmediateFormatTest(self
, func
, file):
6450 """Overrriden from TypeHandler."""
6451 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6452 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6453 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
6454 for v
in range(0, self
.GetArrayCount(func
)):
6455 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6456 (self
.GetArrayType(func
), v
))
6458 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6459 (func
.name
, func
.name
))
6460 file.Write(" void* next_cmd = cmd.Set(\n")
6462 args
= func
.GetCmdArgs()
6463 for value
, arg
in enumerate(args
):
6464 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
6465 file.Write(",\n data);\n")
6466 args
= func
.GetCmdArgs()
6467 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
6469 file.Write(" cmd.header.command);\n")
6470 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6471 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
6472 file.Write(" cmd.header.size * 4u);\n")
6473 for value
, arg
in enumerate(args
):
6474 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6475 (arg
.type, value
+ 11, arg
.name
))
6476 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6477 file.Write(" next_cmd, sizeof(cmd) +\n")
6478 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6479 file.Write(" // TODO(gman): Check that data was inserted;\n")
6484 class PUTnHandler(ArrayArgTypeHandler
):
6485 """Handler for PUTn 'glUniform__v' type functions."""
6488 ArrayArgTypeHandler
.__init
__(self
)
6490 def WriteServiceUnitTest(self
, func
, file, *extras
):
6491 """Overridden from TypeHandler."""
6492 ArrayArgTypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
6495 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
6496 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6497 SpecializedSetup<cmds::%(name)s, 0>(true);
6500 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6501 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6506 for count
, arg
in enumerate(func
.GetOriginalArgs()):
6507 # hardcoded to match unit tests.
6509 # the location of the second element of the 2nd uniform.
6510 # defined in GLES2DecoderBase::SetupShaderForUniform
6511 gl_arg_strings
.append("3")
6512 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
6514 # the number of elements that gl will be called with.
6515 gl_arg_strings
.append("3")
6516 # the number of elements requested in the command.
6517 arg_strings
.append("5")
6519 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
6520 if not arg
.IsConstant():
6521 arg_strings
.append(arg
.GetValidArg(func
))
6523 'gl_args': ", ".join(gl_arg_strings
),
6524 'args': ", ".join(arg_strings
),
6526 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6528 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6529 """Overridden from TypeHandler."""
6531 TEST_P(%(test_name)s, %(name)sValidArgs) {
6532 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6535 %(gl_func_name)s(%(gl_args)s,
6536 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
6537 SpecializedSetup<cmds::%(name)s, 0>(true);
6538 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6539 cmd.Init(%(args)s, &temp[0]);"""
6542 decoder_->set_unsafe_es3_apis_enabled(true);"""
6544 EXPECT_EQ(error::kNoError,
6545 ExecuteImmediateCmd(cmd, sizeof(temp)));
6546 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6549 decoder_->set_unsafe_es3_apis_enabled(false);
6550 EXPECT_EQ(error::kUnknownCommand,
6551 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6558 for arg
in func
.GetOriginalArgs()[0:-1]:
6559 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
6560 gl_any_strings
.append("_")
6561 if not arg
.IsConstant():
6562 arg_strings
.append(arg
.GetValidArg(func
))
6564 'data_type': self
.GetArrayType(func
),
6565 'data_count': self
.GetArrayCount(func
),
6566 'args': ", ".join(arg_strings
),
6567 'gl_args': ", ".join(gl_arg_strings
),
6568 'gl_any_args': ", ".join(gl_any_strings
),
6570 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6573 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6574 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6575 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6576 SpecializedSetup<cmds::%(name)s, 0>(false);
6577 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6578 cmd.Init(%(all_but_last_args)s, &temp[0]);
6579 EXPECT_EQ(error::%(parse_result)s,
6580 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
6583 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6585 def WriteGetDataSizeCode(self
, func
, file):
6586 """Overrriden from TypeHandler."""
6587 code
= """ uint32_t data_size;
6588 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
6589 return error::kOutOfBounds;
6592 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6593 if func
.IsImmediate():
6594 file.Write(" if (data_size > immediate_data_size) {\n")
6595 file.Write(" return error::kOutOfBounds;\n")
6598 def WriteGLES2Implementation(self
, func
, file):
6599 """Overrriden from TypeHandler."""
6600 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6601 (func
.return_type
, func
.original_name
,
6602 func
.MakeTypedOriginalArgString("")))
6603 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6604 func
.WriteDestinationInitalizationValidation(file)
6605 self
.WriteClientGLCallLog(func
, file)
6606 last_pointer_name
= func
.GetLastOriginalPointerArg().name
6607 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6608 for (GLsizei i = 0; i < count; ++i) {
6610 values_str
= ' << ", " << '.join(
6611 ["%s[%d + i * %d]" % (
6612 last_pointer_name
, ndx
, self
.GetArrayCount(func
)) for ndx
in range(
6613 0, self
.GetArrayCount(func
))])
6614 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
6615 file.Write(" }\n });\n")
6616 for arg
in func
.GetOriginalArgs():
6617 arg
.WriteClientSideValidationCode(file, func
)
6618 file.Write(" helper_->%sImmediate(%s);\n" %
6619 (func
.name
, func
.MakeInitString("")))
6620 file.Write(" CheckGLError();\n")
6624 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6625 """Writes the GLES2 Implemention unit test."""
6627 TEST_F(GLES2ImplementationTest, %(name)s) {
6628 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6630 cmds::%(name)sImmediate cmd;
6631 %(type)s data[%(count_param)d][%(count)d];
6635 for (int ii = 0; ii < %(count_param)d; ++ii) {
6636 for (int jj = 0; jj < %(count)d; ++jj) {
6637 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6640 expected.cmd.Init(%(cmd_args)s);
6641 gl_->%(name)s(%(args)s);
6642 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6645 cmd_arg_strings
= []
6646 for arg
in func
.GetCmdArgs():
6647 if arg
.name
.endswith("_shm_id"):
6648 cmd_arg_strings
.append("&data[0][0]")
6649 elif arg
.name
.endswith("_shm_offset"):
6652 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
6655 for arg
in func
.GetOriginalArgs():
6657 valid_value
= "&data[0][0]"
6659 valid_value
= arg
.GetValidClientSideArg(func
)
6660 gl_arg_strings
.append(valid_value
)
6661 if arg
.name
== "count":
6662 count_param
= int(valid_value
)
6665 'type': self
.GetArrayType(func
),
6666 'count': self
.GetArrayCount(func
),
6667 'args': ", ".join(gl_arg_strings
),
6668 'cmd_args': ", ".join(cmd_arg_strings
),
6669 'count_param': count_param
,
6672 # Test constants for invalid values, as they are not tested by the
6675 arg
for arg
in func
.GetOriginalArgs()[0:-1] if arg
.IsConstant()
6681 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
6682 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6683 for (int ii = 0; ii < %(count_param)d; ++ii) {
6684 for (int jj = 0; jj < %(count)d; ++jj) {
6685 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6688 gl_->%(name)s(%(args)s);
6689 EXPECT_TRUE(NoCommandsWritten());
6690 EXPECT_EQ(%(gl_error)s, CheckError());
6693 for invalid_arg
in constants
:
6695 invalid
= invalid_arg
.GetInvalidArg(func
)
6696 for arg
in func
.GetOriginalArgs():
6697 if arg
is invalid_arg
:
6698 gl_arg_strings
.append(invalid
[0])
6699 elif arg
.IsPointer():
6700 gl_arg_strings
.append("&data[0][0]")
6702 valid_value
= arg
.GetValidClientSideArg(func
)
6703 gl_arg_strings
.append(valid_value
)
6704 if arg
.name
== "count":
6705 count_param
= int(valid_value
)
6709 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
6710 'type': self
.GetArrayType(func
),
6711 'count': self
.GetArrayCount(func
),
6712 'args': ", ".join(gl_arg_strings
),
6713 'gl_error': invalid
[2],
6714 'count_param': count_param
,
6718 def WriteImmediateCmdComputeSize(self
, func
, file):
6719 """Overrriden from TypeHandler."""
6720 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
6721 file.Write(" return static_cast<uint32_t>(\n")
6722 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
6723 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6726 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
6727 file.Write(" return static_cast<uint32_t>(\n")
6729 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
6733 def WriteImmediateCmdSetHeader(self
, func
, file):
6734 """Overrriden from TypeHandler."""
6735 file.Write(" void SetHeader(GLsizei count) {\n")
6737 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
6741 def WriteImmediateCmdInit(self
, func
, file):
6742 """Overrriden from TypeHandler."""
6743 file.Write(" void Init(%s) {\n" %
6744 func
.MakeTypedInitString("_"))
6745 file.Write(" SetHeader(_count);\n")
6746 args
= func
.GetCmdArgs()
6748 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6749 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6750 pointer_arg
= func
.GetLastOriginalPointerArg()
6751 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg
.name
)
6755 def WriteImmediateCmdSet(self
, func
, file):
6756 """Overrriden from TypeHandler."""
6757 file.Write(" void* Set(void* cmd%s) {\n" %
6758 func
.MakeTypedInitString("_", True))
6759 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
6760 func
.MakeInitString("_"))
6761 file.Write(" const uint32_t size = ComputeSize(_count);\n")
6762 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6767 def WriteImmediateCmdHelper(self
, func
, file):
6768 """Overrriden from TypeHandler."""
6769 code
= """ void %(name)s(%(typed_args)s) {
6770 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
6771 gles2::cmds::%(name)s* c =
6772 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6781 "typed_args": func
.MakeTypedInitString(""),
6782 "args": func
.MakeInitString("")
6785 def WriteImmediateFormatTest(self
, func
, file):
6786 """Overrriden from TypeHandler."""
6787 args
= func
.GetOriginalArgs()
6790 if arg
.name
== "count":
6791 count_param
= int(arg
.GetValidClientSideCmdArg(func
))
6792 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6793 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6794 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
6795 for v
in range(0, self
.GetArrayCount(func
) * count_param
):
6796 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6797 (self
.GetArrayType(func
), v
))
6799 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6800 (func
.name
, func
.name
))
6801 file.Write(" const GLsizei kNumElements = %d;\n" % count_param
)
6802 file.Write(" const size_t kExpectedCmdSize =\n")
6803 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
6804 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6805 file.Write(" void* next_cmd = cmd.Set(\n")
6807 for value
, arg
in enumerate(args
):
6809 file.Write(",\n data")
6810 elif arg
.IsConstant():
6813 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
6815 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6817 file.Write(" cmd.header.command);\n")
6818 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
6819 for value
, arg
in enumerate(args
):
6820 if arg
.IsPointer() or arg
.IsConstant():
6822 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6823 (arg
.type, value
+ 1, arg
.name
))
6824 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6825 file.Write(" next_cmd, sizeof(cmd) +\n")
6826 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6827 file.Write(" // TODO(gman): Check that data was inserted;\n")
6831 class PUTSTRHandler(ArrayArgTypeHandler
):
6832 """Handler for functions that pass a string array."""
6835 ArrayArgTypeHandler
.__init
__(self
)
6837 def __GetDataArg(self
, func
):
6838 """Return the argument that points to the 2D char arrays"""
6839 for arg
in func
.GetOriginalArgs():
6840 if arg
.IsPointer2D():
6844 def __GetLengthArg(self
, func
):
6845 """Return the argument that holds length for each char array"""
6846 for arg
in func
.GetOriginalArgs():
6847 if arg
.IsPointer() and not arg
.IsPointer2D():
6851 def WriteGLES2Implementation(self
, func
, file):
6852 """Overrriden from TypeHandler."""
6853 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6854 (func
.return_type
, func
.original_name
,
6855 func
.MakeTypedOriginalArgString("")))
6856 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6857 func
.WriteDestinationInitalizationValidation(file)
6858 self
.WriteClientGLCallLog(func
, file)
6859 data_arg
= self
.__GetDataArg
(func
)
6860 length_arg
= self
.__GetLengthArg
(func
)
6861 log_code_block
= """ GPU_CLIENT_LOG_CODE_BLOCK({
6862 for (GLsizei ii = 0; ii < count; ++ii) {
6863 if (%(data)s[ii]) {"""
6864 if length_arg
== None:
6865 log_code_block
+= """
6866 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
6868 log_code_block
+= """
6869 if (%(length)s && %(length)s[ii] >= 0) {
6870 const std::string my_str(%(data)s[ii], %(length)s[ii]);
6871 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
6873 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
6875 log_code_block
+= """
6877 GPU_CLIENT_LOG(" " << ii << ": NULL");
6882 file.Write(log_code_block
% {
6883 'data': data_arg
.name
,
6884 'length': length_arg
.name
if not length_arg
== None else ''
6886 for arg
in func
.GetOriginalArgs():
6887 arg
.WriteClientSideValidationCode(file, func
)
6890 for arg
in func
.GetOriginalArgs():
6891 if arg
.name
== 'count' or arg
== self
.__GetLengthArg
(func
):
6893 if arg
== self
.__GetDataArg
(func
):
6894 bucket_args
.append('kResultBucketId')
6896 bucket_args
.append(arg
.name
)
6898 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
6901 helper_->%(func_name)sBucket(%(bucket_args)s);
6902 helper_->SetBucketSize(kResultBucketId, 0);
6907 file.Write(code_block
% {
6908 'data': data_arg
.name
,
6909 'length': length_arg
.name
if not length_arg
== None else 'NULL',
6910 'func_name': func
.name
,
6911 'bucket_args': ', '.join(bucket_args
),
6914 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6915 """Overrriden from TypeHandler."""
6917 TEST_F(GLES2ImplementationTest, %(name)s) {
6918 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
6919 const char* kString1 = "happy";
6920 const char* kString2 = "ending";
6921 const size_t kString1Size = ::strlen(kString1) + 1;
6922 const size_t kString2Size = ::strlen(kString2) + 1;
6923 const size_t kHeaderSize = sizeof(GLint) * 3;
6924 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
6925 const size_t kPaddedHeaderSize =
6926 transfer_buffer_->RoundToAlignment(kHeaderSize);
6927 const size_t kPaddedString1Size =
6928 transfer_buffer_->RoundToAlignment(kString1Size);
6929 const size_t kPaddedString2Size =
6930 transfer_buffer_->RoundToAlignment(kString2Size);
6932 cmd::SetBucketSize set_bucket_size;
6933 cmd::SetBucketData set_bucket_header;
6934 cmd::SetToken set_token1;
6935 cmd::SetBucketData set_bucket_data1;
6936 cmd::SetToken set_token2;
6937 cmd::SetBucketData set_bucket_data2;
6938 cmd::SetToken set_token3;
6939 cmds::%(name)sBucket cmd_bucket;
6940 cmd::SetBucketSize clear_bucket_size;
6943 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
6944 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
6945 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
6948 expected.set_bucket_size.Init(kBucketId, kSourceSize);
6949 expected.set_bucket_header.Init(
6950 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
6951 expected.set_token1.Init(GetNextToken());
6952 expected.set_bucket_data1.Init(
6953 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
6954 expected.set_token2.Init(GetNextToken());
6955 expected.set_bucket_data2.Init(
6956 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
6958 expected.set_token3.Init(GetNextToken());
6959 expected.cmd_bucket.Init(%(bucket_args)s);
6960 expected.clear_bucket_size.Init(kBucketId, 0);
6961 const char* kStrings[] = { kString1, kString2 };
6962 gl_->%(name)s(%(gl_args)s);
6963 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6968 for arg
in func
.GetOriginalArgs():
6969 if arg
== self
.__GetDataArg
(func
):
6970 gl_args
.append('kStrings')
6971 bucket_args
.append('kBucketId')
6972 elif arg
== self
.__GetLengthArg
(func
):
6973 gl_args
.append('NULL')
6974 elif arg
.name
== 'count':
6977 gl_args
.append(arg
.GetValidClientSideArg(func
))
6978 bucket_args
.append(arg
.GetValidClientSideArg(func
))
6981 'gl_args': ", ".join(gl_args
),
6982 'bucket_args': ", ".join(bucket_args
),
6985 if self
.__GetLengthArg
(func
) == None:
6988 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
6989 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
6990 const char* kString = "foobar******";
6991 const size_t kStringSize = 6; // We only need "foobar".
6992 const size_t kHeaderSize = sizeof(GLint) * 2;
6993 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
6994 const size_t kPaddedHeaderSize =
6995 transfer_buffer_->RoundToAlignment(kHeaderSize);
6996 const size_t kPaddedStringSize =
6997 transfer_buffer_->RoundToAlignment(kStringSize + 1);
6999 cmd::SetBucketSize set_bucket_size;
7000 cmd::SetBucketData set_bucket_header;
7001 cmd::SetToken set_token1;
7002 cmd::SetBucketData set_bucket_data;
7003 cmd::SetToken set_token2;
7004 cmds::ShaderSourceBucket shader_source_bucket;
7005 cmd::SetBucketSize clear_bucket_size;
7008 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7009 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7012 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7013 expected.set_bucket_header.Init(
7014 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7015 expected.set_token1.Init(GetNextToken());
7016 expected.set_bucket_data.Init(
7017 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7018 expected.set_token2.Init(GetNextToken());
7019 expected.shader_source_bucket.Init(%(bucket_args)s);
7020 expected.clear_bucket_size.Init(kBucketId, 0);
7021 const char* kStrings[] = { kString };
7022 const GLint kLength[] = { kStringSize };
7023 gl_->%(name)s(%(gl_args)s);
7024 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7028 for arg
in func
.GetOriginalArgs():
7029 if arg
== self
.__GetDataArg
(func
):
7030 gl_args
.append('kStrings')
7031 elif arg
== self
.__GetLengthArg
(func
):
7032 gl_args
.append('kLength')
7033 elif arg
.name
== 'count':
7036 gl_args
.append(arg
.GetValidClientSideArg(func
))
7039 'gl_args': ", ".join(gl_args
),
7040 'bucket_args': ", ".join(bucket_args
),
7043 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
7044 """Overrriden from TypeHandler."""
7046 cmd_args_with_invalid_id
= []
7048 for index
, arg
in enumerate(func
.GetOriginalArgs()):
7049 if arg
== self
.__GetLengthArg
(func
):
7051 elif arg
.name
== 'count':
7053 elif arg
== self
.__GetDataArg
(func
):
7054 cmd_args
.append('kBucketId')
7055 cmd_args_with_invalid_id
.append('kBucketId')
7057 elif index
== 0: # Resource ID arg
7058 cmd_args
.append(arg
.GetValidArg(func
))
7059 cmd_args_with_invalid_id
.append('kInvalidClientId')
7060 gl_args
.append(arg
.GetValidGLArg(func
))
7062 cmd_args
.append(arg
.GetValidArg(func
))
7063 cmd_args_with_invalid_id
.append(arg
.GetValidArg(func
))
7064 gl_args
.append(arg
.GetValidGLArg(func
))
7067 TEST_P(%(test_name)s, %(name)sValidArgs) {
7068 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7069 const uint32 kBucketId = 123;
7070 const char kSource0[] = "hello";
7071 const char* kSource[] = { kSource0 };
7072 const char kValidStrEnd = 0;
7073 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7075 cmd.Init(%(cmd_args)s);
7076 decoder_->set_unsafe_es3_apis_enabled(true);
7077 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7080 decoder_->set_unsafe_es3_apis_enabled(false);
7081 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7086 self
.WriteValidUnitTest(func
, file, test
, {
7087 'cmd_args': ", ".join(cmd_args
),
7088 'gl_args': ", ".join(gl_args
),
7092 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7093 const uint32 kBucketId = 123;
7094 const char kSource0[] = "hello";
7095 const char* kSource[] = { kSource0 };
7096 const char kValidStrEnd = 0;
7097 decoder_->set_unsafe_es3_apis_enabled(true);
7100 cmd.Init(%(cmd_args)s);
7101 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7102 // Test invalid client.
7103 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7104 cmd.Init(%(cmd_args_with_invalid_id)s);
7105 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7106 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7109 self
.WriteValidUnitTest(func
, file, test
, {
7110 'cmd_args': ", ".join(cmd_args
),
7111 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id
),
7115 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7116 const uint32 kBucketId = 123;
7117 const char kSource0[] = "hello";
7118 const char* kSource[] = { kSource0 };
7119 const char kValidStrEnd = 0;
7120 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7121 const GLsizei kTests[] = {
7124 std::numeric_limits<GLsizei>::max(),
7127 decoder_->set_unsafe_es3_apis_enabled(true);
7128 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7129 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7131 cmd.Init(%(cmd_args)s);
7132 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7136 self
.WriteValidUnitTest(func
, file, test
, {
7137 'cmd_args': ", ".join(cmd_args
),
7141 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7142 const uint32 kBucketId = 123;
7143 const char kSource0[] = "hello";
7144 const char* kSource[] = { kSource0 };
7145 const char kInvalidStrEnd = '*';
7146 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7148 cmd.Init(%(cmd_args)s);
7149 decoder_->set_unsafe_es3_apis_enabled(true);
7150 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7153 self
.WriteValidUnitTest(func
, file, test
, {
7154 'cmd_args': ", ".join(cmd_args
),
7158 class PUTXnHandler(ArrayArgTypeHandler
):
7159 """Handler for glUniform?f functions."""
7161 ArrayArgTypeHandler
.__init
__(self
)
7163 def WriteHandlerImplementation(self
, func
, file):
7164 """Overrriden from TypeHandler."""
7165 code
= """ %(type)s temp[%(count)s] = { %(values)s};"""
7168 gl%(name)sv(%(location)s, 1, &temp[0]);
7172 Do%(name)sv(%(location)s, 1, &temp[0]);
7175 args
= func
.GetOriginalArgs()
7176 count
= int(self
.GetArrayCount(func
))
7177 num_args
= len(args
)
7178 for ii
in range(count
):
7179 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
7183 'count': self
.GetArrayCount(func
),
7184 'type': self
.GetArrayType(func
),
7185 'location': args
[0].name
,
7186 'args': func
.MakeOriginalArgString(""),
7190 def WriteServiceUnitTest(self
, func
, file, *extras
):
7191 """Overrriden from TypeHandler."""
7193 TEST_P(%(test_name)s, %(name)sValidArgs) {
7194 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7195 SpecializedSetup<cmds::%(name)s, 0>(true);
7197 cmd.Init(%(args)s);"""
7200 decoder_->set_unsafe_es3_apis_enabled(true);"""
7202 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7203 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7206 decoder_->set_unsafe_es3_apis_enabled(false);
7207 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7211 args
= func
.GetOriginalArgs()
7212 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
)
7213 self
.WriteValidUnitTest(func
, file, valid_test
, {
7215 'count': self
.GetArrayCount(func
),
7216 'local_args': local_args
,
7220 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7221 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7222 SpecializedSetup<cmds::%(name)s, 0>(false);
7225 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7228 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
7229 'name': func
.GetInfo('name'),
7230 'count': self
.GetArrayCount(func
),
7234 class GLcharHandler(CustomHandler
):
7235 """Handler for functions that pass a single string ."""
7238 CustomHandler
.__init
__(self
)
7240 def WriteImmediateCmdComputeSize(self
, func
, file):
7241 """Overrriden from TypeHandler."""
7242 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7243 file.Write(" return static_cast<uint32_t>(\n")
7244 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
7247 def WriteImmediateCmdSetHeader(self
, func
, file):
7248 """Overrriden from TypeHandler."""
7250 void SetHeader(uint32_t data_size) {
7251 header.SetCmdBySize<ValueType>(data_size);
7256 def WriteImmediateCmdInit(self
, func
, file):
7257 """Overrriden from TypeHandler."""
7258 last_arg
= func
.GetLastOriginalArg()
7259 args
= func
.GetCmdArgs()
7262 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
7264 void Init(%(typed_args)s, uint32_t _data_size) {
7265 SetHeader(_data_size);
7267 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7272 "typed_args": func
.MakeTypedArgString("_"),
7273 "set_code": "\n".join(set_code
),
7274 "last_arg": last_arg
.name
7277 def WriteImmediateCmdSet(self
, func
, file):
7278 """Overrriden from TypeHandler."""
7279 last_arg
= func
.GetLastOriginalArg()
7280 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7281 func
.MakeTypedCmdArgString("_", True))
7282 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7283 func
.MakeCmdArgString("_"))
7284 file.Write(" return NextImmediateCmdAddress<ValueType>("
7285 "cmd, _data_size);\n")
7289 def WriteImmediateCmdHelper(self
, func
, file):
7290 """Overrriden from TypeHandler."""
7291 code
= """ void %(name)s(%(typed_args)s) {
7292 const uint32_t data_size = strlen(name);
7293 gles2::cmds::%(name)s* c =
7294 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7296 c->Init(%(args)s, data_size);
7303 "typed_args": func
.MakeTypedOriginalArgString(""),
7304 "args": func
.MakeOriginalArgString(""),
7308 def WriteImmediateFormatTest(self
, func
, file):
7309 """Overrriden from TypeHandler."""
7312 all_but_last_arg
= func
.GetCmdArgs()[:-1]
7313 for value
, arg
in enumerate(all_but_last_arg
):
7314 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
7315 for value
, arg
in enumerate(all_but_last_arg
):
7316 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7317 (arg
.type, value
+ 11, arg
.name
))
7319 TEST_F(GLES2FormatTest, %(func_name)s) {
7320 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7321 static const char* const test_str = \"test string\";
7322 void* next_cmd = cmd.Set(
7327 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7328 cmd.header.command);
7329 EXPECT_EQ(sizeof(cmd) +
7330 RoundSizeToMultipleOfEntries(strlen(test_str)),
7331 cmd.header.size * 4u);
7332 EXPECT_EQ(static_cast<char*>(next_cmd),
7333 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7334 RoundSizeToMultipleOfEntries(strlen(test_str)));
7336 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7337 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7340 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7341 sizeof(cmd) + strlen(test_str));
7346 'func_name': func
.name
,
7347 'init_code': "\n".join(init_code
),
7348 'check_code': "\n".join(check_code
),
7352 class GLcharNHandler(CustomHandler
):
7353 """Handler for functions that pass a single string with an optional len."""
7356 CustomHandler
.__init
__(self
)
7358 def InitFunction(self
, func
):
7359 """Overrriden from TypeHandler."""
7361 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
7363 def NeedsDataTransferFunction(self
, func
):
7364 """Overriden from TypeHandler."""
7367 def AddBucketFunction(self
, generator
, func
):
7368 """Overrriden from TypeHandler."""
7371 def WriteServiceImplementation(self
, func
, file):
7372 """Overrriden from TypeHandler."""
7373 self
.WriteServiceHandlerFunctionHeader(func
, file)
7375 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7376 Bucket* bucket = GetBucket(bucket_id);
7377 if (!bucket || bucket->size() == 0) {
7378 return error::kInvalidArguments;
7381 if (!bucket->GetAsString(&str)) {
7382 return error::kInvalidArguments;
7384 %(gl_func_name)s(0, str.c_str());
7385 return error::kNoError;
7390 'gl_func_name': func
.GetGLFunctionName(),
7391 'bucket_id': func
.cmd_args
[0].name
,
7395 class IsHandler(TypeHandler
):
7396 """Handler for glIs____ type and glGetError functions."""
7399 TypeHandler
.__init
__(self
)
7401 def InitFunction(self
, func
):
7402 """Overrriden from TypeHandler."""
7403 func
.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7404 func
.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7405 if func
.GetInfo('result') == None:
7406 func
.AddInfo('result', ['uint32_t'])
7408 def WriteServiceUnitTest(self
, func
, file, *extras
):
7409 """Overrriden from TypeHandler."""
7411 TEST_P(%(test_name)s, %(name)sValidArgs) {
7412 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7413 SpecializedSetup<cmds::%(name)s, 0>(true);
7415 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7418 decoder_->set_unsafe_es3_apis_enabled(true);"""
7420 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7421 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7424 decoder_->set_unsafe_es3_apis_enabled(false);
7425 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7430 if len(func
.GetOriginalArgs()):
7432 self
.WriteValidUnitTest(func
, file, valid_test
, {
7437 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7438 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7439 SpecializedSetup<cmds::%(name)s, 0>(false);
7441 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7442 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7445 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
7450 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
7451 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7452 SpecializedSetup<cmds::%(name)s, 0>(false);"""
7455 decoder_->set_unsafe_es3_apis_enabled(true);"""
7458 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
7459 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
7460 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
7461 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
7464 decoder_->set_unsafe_es3_apis_enabled(true);"""
7468 self
.WriteValidUnitTest(func
, file, invalid_test
, {
7472 def WriteServiceImplementation(self
, func
, file):
7473 """Overrriden from TypeHandler."""
7474 self
.WriteServiceHandlerFunctionHeader(func
, file)
7475 args
= func
.GetOriginalArgs()
7477 arg
.WriteGetCode(file)
7479 code
= """ typedef cmds::%(func_name)s::Result Result;
7480 Result* result_dst = GetSharedMemoryAs<Result*>(
7481 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
7483 return error::kOutOfBounds;
7486 file.Write(code
% {'func_name': func
.name
})
7487 func
.WriteHandlerValidation(file)
7489 assert func
.GetInfo('id_mapping')
7490 assert len(func
.GetInfo('id_mapping')) == 1
7491 assert len(args
) == 1
7492 id_type
= func
.GetInfo('id_mapping')[0]
7493 file.Write(" %s service_%s = 0;\n" % (args
[0].type, id_type
.lower()))
7494 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
7495 (id_type
, id_type
.lower(), id_type
.lower()))
7497 file.Write(" *result_dst = %s(%s);\n" %
7498 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
7499 file.Write(" return error::kNoError;\n")
7503 def WriteGLES2Implementation(self
, func
, file):
7504 """Overrriden from TypeHandler."""
7505 impl_func
= func
.GetInfo('impl_func')
7506 if impl_func
== None or impl_func
== True:
7507 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
7508 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7509 (func
.return_type
, func
.original_name
,
7510 func
.MakeTypedOriginalArgString("")))
7511 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7512 self
.WriteTraceEvent(func
, file)
7513 func
.WriteDestinationInitalizationValidation(file)
7514 self
.WriteClientGLCallLog(func
, file)
7515 file.Write(" typedef cmds::%s::Result Result;\n" % func
.name
)
7516 file.Write(" Result* result = GetResultAs<Result*>();\n")
7517 file.Write(" if (!result) {\n")
7518 file.Write(" return %s;\n" % error_value
)
7520 file.Write(" *result = 0;\n")
7521 assert len(func
.GetOriginalArgs()) == 1
7522 id_arg
= func
.GetOriginalArgs()[0]
7523 if id_arg
.type == 'GLsync':
7524 arg_string
= "ToGLuint(%s)" % func
.MakeOriginalArgString("")
7526 arg_string
= func
.MakeOriginalArgString("")
7528 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
7529 (func
.name
, arg_string
))
7530 file.Write(" WaitForCmd();\n")
7531 file.Write(" %s result_value = *result" % func
.return_type
)
7532 if func
.return_type
== "GLboolean":
7534 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
7535 file.Write(" CheckGLError();\n")
7536 file.Write(" return result_value;\n")
7540 def WriteGLES2ImplementationUnitTest(self
, func
, file):
7541 """Overrriden from TypeHandler."""
7542 client_test
= func
.GetInfo('client_test')
7543 if client_test
== None or client_test
== True:
7545 TEST_F(GLES2ImplementationTest, %(name)s) {
7551 ExpectedMemoryInfo result1 =
7552 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
7553 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
7555 EXPECT_CALL(*command_buffer(), OnFlush())
7556 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
7557 .RetiresOnSaturation();
7559 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
7560 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7561 EXPECT_TRUE(result);
7564 args
= func
.GetOriginalArgs()
7565 assert len(args
) == 1
7568 'cmd_id_value': args
[0].GetValidClientSideCmdArg(func
),
7569 'gl_id_value': args
[0].GetValidClientSideArg(func
) })
7572 class STRnHandler(TypeHandler
):
7573 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
7574 GetTranslatedShaderSourceANGLE."""
7577 TypeHandler
.__init
__(self
)
7579 def InitFunction(self
, func
):
7580 """Overrriden from TypeHandler."""
7581 # remove all but the first cmd args.
7582 cmd_args
= func
.GetCmdArgs()
7584 func
.AddCmdArg(cmd_args
[0])
7585 # add on a bucket id.
7586 func
.AddCmdArg(Argument('bucket_id', 'uint32_t'))
7588 def WriteGLES2Implementation(self
, func
, file):
7589 """Overrriden from TypeHandler."""
7590 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
7591 GPU_CLIENT_SINGLE_THREAD_CHECK();
7593 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
7594 << "] gl%(func_name)s" << "("
7597 << static_cast<void*>(%(arg2)s) << ", "
7598 << static_cast<void*>(%(arg3)s) << ")");
7599 helper_->SetBucketSize(kResultBucketId, 0);
7600 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
7602 GLsizei max_size = 0;
7603 if (GetBucketAsString(kResultBucketId, &str)) {
7606 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
7607 memcpy(%(dest_name)s, str.c_str(), max_size);
7608 %(dest_name)s[max_size] = '\\0';
7609 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
7612 if (%(length_name)s != NULL) {
7613 *%(length_name)s = max_size;
7618 args
= func
.GetOriginalArgs()
7620 'return_type': func
.return_type
,
7621 'func_name': func
.original_name
,
7622 'args': func
.MakeTypedOriginalArgString(""),
7623 'id_name': args
[0].name
,
7624 'bufsize_name': args
[1].name
,
7625 'length_name': args
[2].name
,
7626 'dest_name': args
[3].name
,
7627 'arg0': args
[0].name
,
7628 'arg1': args
[1].name
,
7629 'arg2': args
[2].name
,
7630 'arg3': args
[3].name
,
7632 file.Write(code_1
% str_args
)
7633 func
.WriteDestinationInitalizationValidation(file)
7634 file.Write(code_2
% str_args
)
7636 def WriteServiceUnitTest(self
, func
, file, *extras
):
7637 """Overrriden from TypeHandler."""
7639 TEST_P(%(test_name)s, %(name)sValidArgs) {
7640 const char* kInfo = "hello";
7641 const uint32_t kBucketId = 123;
7642 SpecializedSetup<cmds::%(name)s, 0>(true);
7644 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
7645 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
7646 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
7649 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7650 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
7651 ASSERT_TRUE(bucket != NULL);
7652 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
7653 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
7655 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7658 args
= func
.GetOriginalArgs()
7659 id_name
= args
[0].GetValidGLArg(func
)
7660 get_len_func
= func
.GetInfo('get_len_func')
7661 get_len_enum
= func
.GetInfo('get_len_enum')
7664 'get_len_func': get_len_func
,
7665 'get_len_enum': get_len_enum
,
7666 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
7667 args
[0].GetValidGLArg(func
),
7668 'args': '%s, kBucketId' % args
[0].GetValidArg(func
),
7669 'expect_len_code': '',
7671 if get_len_func
and get_len_func
[0:2] == 'gl':
7672 sub
['expect_len_code'] = (
7673 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
7674 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
7675 get_len_func
[2:], id_name
, get_len_enum
)
7676 self
.WriteValidUnitTest(func
, file, valid_test
, sub
, *extras
)
7679 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7680 const uint32_t kBucketId = 123;
7681 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
7684 cmd.Init(kInvalidClientId, kBucketId);
7685 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7686 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7689 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
7691 def WriteServiceImplementation(self
, func
, file):
7692 """Overrriden from TypeHandler."""
7695 class NamedType(object):
7696 """A class that represents a type of an argument in a client function.
7698 A type of an argument that is to be passed through in the command buffer
7699 command. Currently used only for the arguments that are specificly named in
7700 the 'cmd_buffer_functions.txt' file, mostly enums.
7703 def __init__(self
, info
):
7704 assert not 'is_complete' in info
or info
['is_complete'] == True
7706 self
.valid
= info
['valid']
7707 if 'invalid' in info
:
7708 self
.invalid
= info
['invalid']
7711 if 'valid_es3' in info
:
7712 self
.valid_es3
= info
['valid_es3']
7715 if 'deprecated_es3' in info
:
7716 self
.deprecated_es3
= info
['deprecated_es3']
7718 self
.deprecated_es3
= []
7721 return self
.info
['type']
7723 def GetInvalidValues(self
):
7726 def GetValidValues(self
):
7729 def GetValidValuesES3(self
):
7730 return self
.valid_es3
7732 def GetDeprecatedValuesES3(self
):
7733 return self
.deprecated_es3
7735 def IsConstant(self
):
7736 if not 'is_complete' in self
.info
:
7739 return len(self
.GetValidValues()) == 1
7741 def GetConstantValue(self
):
7742 return self
.GetValidValues()[0]
7744 class Argument(object):
7745 """A class that represents a function argument."""
7748 'GLenum': 'uint32_t',
7750 'GLintptr': 'int32_t',
7751 'GLsizei': 'int32_t',
7752 'GLsizeiptr': 'int32_t',
7754 'GLclampf': 'float',
7756 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
7758 def __init__(self
, name
, type):
7760 self
.optional
= type.endswith("Optional*")
7762 type = type[:-9] + "*"
7765 if type in self
.cmd_type_map_
:
7766 self
.cmd_type
= self
.cmd_type_map_
[type]
7768 self
.cmd_type
= 'uint32_t'
7770 def IsPointer(self
):
7771 """Returns true if argument is a pointer."""
7774 def IsPointer2D(self
):
7775 """Returns true if argument is a 2D pointer."""
7778 def IsConstant(self
):
7779 """Returns true if the argument has only one valid value."""
7782 def AddCmdArgs(self
, args
):
7783 """Adds command arguments for this argument to the given list."""
7784 if not self
.IsConstant():
7785 return args
.append(self
)
7787 def AddInitArgs(self
, args
):
7788 """Adds init arguments for this argument to the given list."""
7789 if not self
.IsConstant():
7790 return args
.append(self
)
7792 def GetValidArg(self
, func
):
7793 """Gets a valid value for this argument."""
7794 valid_arg
= func
.GetValidArg(self
)
7795 if valid_arg
!= None:
7798 index
= func
.GetOriginalArgs().index(self
)
7799 return str(index
+ 1)
7801 def GetValidClientSideArg(self
, func
):
7802 """Gets a valid value for this argument."""
7803 valid_arg
= func
.GetValidArg(self
)
7804 if valid_arg
!= None:
7807 if self
.IsPointer():
7809 index
= func
.GetOriginalArgs().index(self
)
7810 if self
.type == 'GLsync':
7811 return ("reinterpret_cast<GLsync>(%d)" % (index
+ 1))
7812 return str(index
+ 1)
7814 def GetValidClientSideCmdArg(self
, func
):
7815 """Gets a valid value for this argument."""
7816 valid_arg
= func
.GetValidArg(self
)
7817 if valid_arg
!= None:
7820 index
= func
.GetOriginalArgs().index(self
)
7821 return str(index
+ 1)
7824 index
= func
.GetCmdArgs().index(self
)
7825 return str(index
+ 1)
7827 def GetValidGLArg(self
, func
):
7828 """Gets a valid GL value for this argument."""
7829 value
= self
.GetValidArg(func
)
7830 if self
.type == 'GLsync':
7831 return ("reinterpret_cast<GLsync>(%s)" % value
)
7834 def GetValidNonCachedClientSideArg(self
, func
):
7835 """Returns a valid value for this argument in a GL call.
7836 Using the value will produce a command buffer service invocation.
7837 Returns None if there is no such value."""
7839 if self
.type == 'GLsync':
7840 return ("reinterpret_cast<GLsync>(%s)" % value
)
7843 def GetValidNonCachedClientSideCmdArg(self
, func
):
7844 """Returns a valid value for this argument in a command buffer command.
7845 Calling the GL function with the value returned by
7846 GetValidNonCachedClientSideArg will result in a command buffer command
7847 that contains the value returned by this function. """
7850 def GetNumInvalidValues(self
, func
):
7851 """returns the number of invalid values to be tested."""
7854 def GetInvalidArg(self
, index
):
7855 """returns an invalid value and expected parse result by index."""
7856 return ("---ERROR0---", "---ERROR2---", None)
7858 def GetLogArg(self
):
7859 """Get argument appropriate for LOG macro."""
7860 if self
.type == 'GLboolean':
7861 return 'GLES2Util::GetStringBool(%s)' % self
.name
7862 if self
.type == 'GLenum':
7863 return 'GLES2Util::GetStringEnum(%s)' % self
.name
7866 def WriteGetCode(self
, file):
7867 """Writes the code to get an argument from a command structure."""
7868 if self
.type == 'GLsync':
7872 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
7873 (my_type
, self
.name
, my_type
, self
.name
))
7875 def WriteValidationCode(self
, file, func
):
7876 """Writes the validation code for an argument."""
7879 def WriteClientSideValidationCode(self
, file, func
):
7880 """Writes the validation code for an argument."""
7883 def WriteDestinationInitalizationValidation(self
, file, func
):
7884 """Writes the client side destintion initialization validation."""
7887 def WriteDestinationInitalizationValidatationIfNeeded(self
, file, func
):
7888 """Writes the client side destintion initialization validation if needed."""
7889 parts
= self
.type.split(" ")
7892 if parts
[0] in self
.need_validation_
:
7894 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
7895 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
7898 def WriteGetAddress(self
, file):
7899 """Writes the code to get the address this argument refers to."""
7902 def GetImmediateVersion(self
):
7903 """Gets the immediate version of this argument."""
7906 def GetBucketVersion(self
):
7907 """Gets the bucket version of this argument."""
7911 class BoolArgument(Argument
):
7912 """class for GLboolean"""
7914 def __init__(self
, name
, type):
7915 Argument
.__init
__(self
, name
, 'GLboolean')
7917 def GetValidArg(self
, func
):
7918 """Gets a valid value for this argument."""
7921 def GetValidClientSideArg(self
, func
):
7922 """Gets a valid value for this argument."""
7925 def GetValidClientSideCmdArg(self
, func
):
7926 """Gets a valid value for this argument."""
7929 def GetValidGLArg(self
, func
):
7930 """Gets a valid GL value for this argument."""
7934 class UniformLocationArgument(Argument
):
7935 """class for uniform locations."""
7937 def __init__(self
, name
):
7938 Argument
.__init
__(self
, name
, "GLint")
7940 def WriteGetCode(self
, file):
7941 """Writes the code to get an argument from a command structure."""
7942 code
= """ %s %s = static_cast<%s>(c.%s);
7944 file.Write(code
% (self
.type, self
.name
, self
.type, self
.name
))
7946 class DataSizeArgument(Argument
):
7947 """class for data_size which Bucket commands do not need."""
7949 def __init__(self
, name
):
7950 Argument
.__init
__(self
, name
, "uint32_t")
7952 def GetBucketVersion(self
):
7956 class SizeArgument(Argument
):
7957 """class for GLsizei and GLsizeiptr."""
7959 def __init__(self
, name
, type):
7960 Argument
.__init
__(self
, name
, type)
7962 def GetNumInvalidValues(self
, func
):
7963 """overridden from Argument."""
7964 if func
.IsImmediate():
7968 def GetInvalidArg(self
, index
):
7969 """overridden from Argument."""
7970 return ("-1", "kNoError", "GL_INVALID_VALUE")
7972 def WriteValidationCode(self
, file, func
):
7973 """overridden from Argument."""
7976 code
= """ if (%(var_name)s < 0) {
7977 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
7978 return error::kNoError;
7982 "var_name": self
.name
,
7983 "func_name": func
.original_name
,
7986 def WriteClientSideValidationCode(self
, file, func
):
7987 """overridden from Argument."""
7988 code
= """ if (%(var_name)s < 0) {
7989 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
7994 "var_name": self
.name
,
7995 "func_name": func
.original_name
,
7999 class SizeNotNegativeArgument(SizeArgument
):
8000 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8002 def __init__(self
, name
, type, gl_type
):
8003 SizeArgument
.__init
__(self
, name
, gl_type
)
8005 def GetInvalidArg(self
, index
):
8006 """overridden from SizeArgument."""
8007 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8009 def WriteValidationCode(self
, file, func
):
8010 """overridden from SizeArgument."""
8014 class EnumBaseArgument(Argument
):
8015 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8016 ValidatedBoolArgument."""
8018 def __init__(self
, name
, gl_type
, type, gl_error
):
8019 Argument
.__init
__(self
, name
, gl_type
)
8021 self
.local_type
= type
8022 self
.gl_error
= gl_error
8023 name
= type[len(gl_type
):]
8024 self
.type_name
= name
8025 self
.named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8027 def IsConstant(self
):
8028 return self
.named_type
.IsConstant()
8030 def GetConstantValue(self
):
8031 return self
.named_type
.GetConstantValue()
8033 def WriteValidationCode(self
, file, func
):
8036 if self
.named_type
.IsConstant():
8038 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
8039 (ToUnderscore(self
.type_name
), self
.name
))
8040 if self
.gl_error
== "GL_INVALID_ENUM":
8042 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8043 (func
.original_name
, self
.name
, self
.name
))
8046 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8047 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8048 file.Write(" return error::kNoError;\n")
8051 def WriteClientSideValidationCode(self
, file, func
):
8052 if not self
.named_type
.IsConstant():
8054 file.Write(" if (%s != %s) {" % (self
.name
,
8055 self
.GetConstantValue()))
8057 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8058 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8059 if func
.return_type
== "void":
8060 file.Write(" return;\n")
8062 file.Write(" return %s;\n" % func
.GetErrorReturnString())
8065 def GetValidArg(self
, func
):
8066 valid_arg
= func
.GetValidArg(self
)
8067 if valid_arg
!= None:
8069 valid
= self
.named_type
.GetValidValues()
8071 num_valid
= len(valid
)
8074 index
= func
.GetOriginalArgs().index(self
)
8075 return str(index
+ 1)
8077 def GetValidClientSideArg(self
, func
):
8078 """Gets a valid value for this argument."""
8079 return self
.GetValidArg(func
)
8081 def GetValidClientSideCmdArg(self
, func
):
8082 """Gets a valid value for this argument."""
8083 valid_arg
= func
.GetValidArg(self
)
8084 if valid_arg
!= None:
8087 valid
= self
.named_type
.GetValidValues()
8089 num_valid
= len(valid
)
8093 index
= func
.GetOriginalArgs().index(self
)
8094 return str(index
+ 1)
8097 index
= func
.GetCmdArgs().index(self
)
8098 return str(index
+ 1)
8100 def GetValidGLArg(self
, func
):
8101 """Gets a valid value for this argument."""
8102 return self
.GetValidArg(func
)
8104 def GetNumInvalidValues(self
, func
):
8105 """returns the number of invalid values to be tested."""
8106 return len(self
.named_type
.GetInvalidValues())
8108 def GetInvalidArg(self
, index
):
8109 """returns an invalid value by index."""
8110 invalid
= self
.named_type
.GetInvalidValues()
8112 num_invalid
= len(invalid
)
8113 if index
>= num_invalid
:
8114 index
= num_invalid
- 1
8115 return (invalid
[index
], "kNoError", self
.gl_error
)
8116 return ("---ERROR1---", "kNoError", self
.gl_error
)
8119 class EnumArgument(EnumBaseArgument
):
8120 """A class that represents a GLenum argument"""
8122 def __init__(self
, name
, type):
8123 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
8125 def GetLogArg(self
):
8126 """Overridden from Argument."""
8127 return ("GLES2Util::GetString%s(%s)" %
8128 (self
.type_name
, self
.name
))
8131 class IntArgument(EnumBaseArgument
):
8132 """A class for a GLint argument that can only accept specific values.
8134 For example glTexImage2D takes a GLint for its internalformat
8135 argument instead of a GLenum.
8138 def __init__(self
, name
, type):
8139 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
8142 class ValidatedBoolArgument(EnumBaseArgument
):
8143 """A class for a GLboolean argument that can only accept specific values.
8145 For example glUniformMatrix takes a GLboolean for it's transpose but it
8149 def __init__(self
, name
, type):
8150 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
8152 def GetLogArg(self
):
8153 """Overridden from Argument."""
8154 return 'GLES2Util::GetStringBool(%s)' % self
.name
8157 class BitFieldArgument(EnumBaseArgument
):
8158 """A class for a GLbitfield argument that can only accept specific values.
8160 For example glFenceSync takes a GLbitfield for its flags argument bit it
8164 def __init__(self
, name
, type):
8165 EnumBaseArgument
.__init
__(self
, name
, "GLbitfield", type,
8169 class ImmediatePointerArgument(Argument
):
8170 """A class that represents an immediate argument to a function.
8172 An immediate argument is one where the data follows the command.
8175 def __init__(self
, name
, type):
8176 Argument
.__init
__(self
, name
, type)
8178 def IsPointer(self
):
8181 def GetPointedType(self
):
8182 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8184 return match
.groupdict()['element_type']
8186 def AddCmdArgs(self
, args
):
8187 """Overridden from Argument."""
8190 def WriteGetCode(self
, file):
8191 """Overridden from Argument."""
8193 " %s %s = GetImmediateDataAs<%s>(\n" %
8194 (self
.type, self
.name
, self
.type))
8195 file.Write(" c, data_size, immediate_data_size);\n")
8197 def WriteValidationCode(self
, file, func
):
8198 """Overridden from Argument."""
8201 file.Write(" if (%s == NULL) {\n" % self
.name
)
8202 file.Write(" return error::kOutOfBounds;\n")
8205 def GetImmediateVersion(self
):
8206 """Overridden from Argument."""
8209 def WriteDestinationInitalizationValidation(self
, file, func
):
8210 """Overridden from Argument."""
8211 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8213 def GetLogArg(self
):
8214 """Overridden from Argument."""
8215 return "static_cast<const void*>(%s)" % self
.name
8218 class PointerArgument(Argument
):
8219 """A class that represents a pointer argument to a function."""
8221 def __init__(self
, name
, type):
8222 Argument
.__init
__(self
, name
, type)
8224 def IsPointer(self
):
8225 """Overridden from Argument."""
8228 def IsPointer2D(self
):
8229 """Overridden from Argument."""
8230 return self
.type.count('*') == 2
8232 def GetPointedType(self
):
8233 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8235 return match
.groupdict()['element_type']
8237 def GetValidArg(self
, func
):
8238 """Overridden from Argument."""
8239 return "shared_memory_id_, shared_memory_offset_"
8241 def GetValidGLArg(self
, func
):
8242 """Overridden from Argument."""
8243 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
8245 def GetNumInvalidValues(self
, func
):
8246 """Overridden from Argument."""
8249 def GetInvalidArg(self
, index
):
8250 """Overridden from Argument."""
8252 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8254 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8255 "kOutOfBounds", None)
8257 def GetLogArg(self
):
8258 """Overridden from Argument."""
8259 return "static_cast<const void*>(%s)" % self
.name
8261 def AddCmdArgs(self
, args
):
8262 """Overridden from Argument."""
8263 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32_t'))
8264 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32_t'))
8266 def WriteGetCode(self
, file):
8267 """Overridden from Argument."""
8269 " %s %s = GetSharedMemoryAs<%s>(\n" %
8270 (self
.type, self
.name
, self
.type))
8272 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8273 (self
.name
, self
.name
))
8275 def WriteGetAddress(self
, file):
8276 """Overridden from Argument."""
8278 " %s %s = GetSharedMemoryAs<%s>(\n" %
8279 (self
.type, self
.name
, self
.type))
8281 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8282 (self
.name
, self
.name
, self
.name
))
8284 def WriteValidationCode(self
, file, func
):
8285 """Overridden from Argument."""
8288 file.Write(" if (%s == NULL) {\n" % self
.name
)
8289 file.Write(" return error::kOutOfBounds;\n")
8292 def GetImmediateVersion(self
):
8293 """Overridden from Argument."""
8294 return ImmediatePointerArgument(self
.name
, self
.type)
8296 def GetBucketVersion(self
):
8297 """Overridden from Argument."""
8298 if self
.type.find('char') >= 0:
8299 if self
.IsPointer2D():
8300 return InputStringArrayBucketArgument(self
.name
, self
.type)
8301 return InputStringBucketArgument(self
.name
, self
.type)
8302 return BucketPointerArgument(self
.name
, self
.type)
8304 def WriteDestinationInitalizationValidation(self
, file, func
):
8305 """Overridden from Argument."""
8306 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8309 class BucketPointerArgument(PointerArgument
):
8310 """A class that represents an bucket argument to a function."""
8312 def __init__(self
, name
, type):
8313 Argument
.__init
__(self
, name
, type)
8315 def AddCmdArgs(self
, args
):
8316 """Overridden from Argument."""
8319 def WriteGetCode(self
, file):
8320 """Overridden from Argument."""
8322 " %s %s = bucket->GetData(0, data_size);\n" %
8323 (self
.type, self
.name
))
8325 def WriteValidationCode(self
, file, func
):
8326 """Overridden from Argument."""
8329 def GetImmediateVersion(self
):
8330 """Overridden from Argument."""
8333 def WriteDestinationInitalizationValidation(self
, file, func
):
8334 """Overridden from Argument."""
8335 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8337 def GetLogArg(self
):
8338 """Overridden from Argument."""
8339 return "static_cast<const void*>(%s)" % self
.name
8342 class InputStringBucketArgument(Argument
):
8343 """A string input argument where the string is passed in a bucket."""
8345 def __init__(self
, name
, type):
8346 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8348 def IsPointer(self
):
8349 """Overridden from Argument."""
8352 def IsPointer2D(self
):
8353 """Overridden from Argument."""
8357 class InputStringArrayBucketArgument(Argument
):
8358 """A string array input argument where the strings are passed in a bucket."""
8360 def __init__(self
, name
, type):
8361 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8362 self
._original
_name
= name
8364 def WriteGetCode(self
, file):
8365 """Overridden from Argument."""
8367 Bucket* bucket = GetBucket(c.%(name)s);
8369 return error::kInvalidArguments;
8372 std::vector<char*> strs;
8373 std::vector<GLint> len;
8374 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8375 return error::kInvalidArguments;
8377 const char** %(original_name)s =
8378 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8379 const GLint* length =
8380 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8385 'original_name': self
._original
_name
,
8388 def GetValidArg(self
, func
):
8389 return "kNameBucketId"
8391 def GetValidGLArg(self
, func
):
8394 def IsPointer(self
):
8395 """Overridden from Argument."""
8398 def IsPointer2D(self
):
8399 """Overridden from Argument."""
8403 class ResourceIdArgument(Argument
):
8404 """A class that represents a resource id argument to a function."""
8406 def __init__(self
, name
, type):
8407 match
= re
.match("(GLid\w+)", type)
8408 self
.resource_type
= match
.group(1)[4:]
8409 if self
.resource_type
== "Sync":
8410 type = type.replace(match
.group(1), "GLsync")
8412 type = type.replace(match
.group(1), "GLuint")
8413 Argument
.__init
__(self
, name
, type)
8415 def WriteGetCode(self
, file):
8416 """Overridden from Argument."""
8417 if self
.type == "GLsync":
8421 file.Write(" %s %s = c.%s;\n" % (my_type
, self
.name
, self
.name
))
8423 def GetValidArg(self
, func
):
8424 return "client_%s_id_" % self
.resource_type
.lower()
8426 def GetValidGLArg(self
, func
):
8427 if self
.resource_type
== "Sync":
8428 return "reinterpret_cast<GLsync>(kService%sId)" % self
.resource_type
8429 return "kService%sId" % self
.resource_type
8432 class ResourceIdBindArgument(Argument
):
8433 """Represents a resource id argument to a bind function."""
8435 def __init__(self
, name
, type):
8436 match
= re
.match("(GLidBind\w+)", type)
8437 self
.resource_type
= match
.group(1)[8:]
8438 type = type.replace(match
.group(1), "GLuint")
8439 Argument
.__init
__(self
, name
, type)
8441 def WriteGetCode(self
, file):
8442 """Overridden from Argument."""
8443 code
= """ %(type)s %(name)s = c.%(name)s;
8445 file.Write(code
% {'type': self
.type, 'name': self
.name
})
8447 def GetValidArg(self
, func
):
8448 return "client_%s_id_" % self
.resource_type
.lower()
8450 def GetValidGLArg(self
, func
):
8451 return "kService%sId" % self
.resource_type
8454 class ResourceIdZeroArgument(Argument
):
8455 """Represents a resource id argument to a function that can be zero."""
8457 def __init__(self
, name
, type):
8458 match
= re
.match("(GLidZero\w+)", type)
8459 self
.resource_type
= match
.group(1)[8:]
8460 type = type.replace(match
.group(1), "GLuint")
8461 Argument
.__init
__(self
, name
, type)
8463 def WriteGetCode(self
, file):
8464 """Overridden from Argument."""
8465 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
8467 def GetValidArg(self
, func
):
8468 return "client_%s_id_" % self
.resource_type
.lower()
8470 def GetValidGLArg(self
, func
):
8471 return "kService%sId" % self
.resource_type
8473 def GetNumInvalidValues(self
, func
):
8474 """returns the number of invalid values to be tested."""
8477 def GetInvalidArg(self
, index
):
8478 """returns an invalid value by index."""
8479 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
8482 class Function(object):
8483 """A class that represents a function."""
8487 'Bind': BindHandler(),
8488 'Create': CreateHandler(),
8489 'Custom': CustomHandler(),
8490 'Data': DataHandler(),
8491 'Delete': DeleteHandler(),
8492 'DELn': DELnHandler(),
8493 'GENn': GENnHandler(),
8494 'GETn': GETnHandler(),
8495 'GLchar': GLcharHandler(),
8496 'GLcharN': GLcharNHandler(),
8497 'HandWritten': HandWrittenHandler(),
8499 'Manual': ManualHandler(),
8500 'PUT': PUTHandler(),
8501 'PUTn': PUTnHandler(),
8502 'PUTSTR': PUTSTRHandler(),
8503 'PUTXn': PUTXnHandler(),
8504 'StateSet': StateSetHandler(),
8505 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
8506 'StateSetFrontBack': StateSetFrontBackHandler(),
8507 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
8508 'StateSetNamedParameter': StateSetNamedParameter(),
8509 'STRn': STRnHandler(),
8510 'Todo': TodoHandler(),
8513 def __init__(self
, name
, info
):
8515 self
.original_name
= info
['original_name']
8517 self
.original_args
= self
.ParseArgs(info
['original_args'])
8519 if 'cmd_args' in info
:
8520 self
.args_for_cmds
= self
.ParseArgs(info
['cmd_args'])
8522 self
.args_for_cmds
= self
.original_args
[:]
8524 self
.return_type
= info
['return_type']
8525 if self
.return_type
!= 'void':
8526 self
.return_arg
= CreateArg(info
['return_type'] + " result")
8528 self
.return_arg
= None
8530 self
.num_pointer_args
= sum(
8531 [1 for arg
in self
.args_for_cmds
if arg
.IsPointer()])
8532 if self
.num_pointer_args
> 0:
8533 for arg
in reversed(self
.original_args
):
8535 self
.last_original_pointer_arg
= arg
8538 self
.last_original_pointer_arg
= None
8540 self
.type_handler
= self
.type_handlers
[info
['type']]
8541 self
.can_auto_generate
= (self
.num_pointer_args
== 0 and
8542 info
['return_type'] == "void")
8545 def ParseArgs(self
, arg_string
):
8546 """Parses a function arg string."""
8548 parts
= arg_string
.split(',')
8549 for arg_string
in parts
:
8550 arg
= CreateArg(arg_string
)
8555 def IsType(self
, type_name
):
8556 """Returns true if function is a certain type."""
8557 return self
.info
['type'] == type_name
8559 def InitFunction(self
):
8560 """Creates command args and calls the init function for the type handler.
8562 Creates argument lists for command buffer commands, eg. self.cmd_args and
8564 Calls the type function initialization.
8565 Override to create different kind of command buffer command argument lists.
8568 for arg
in self
.args_for_cmds
:
8569 arg
.AddCmdArgs(self
.cmd_args
)
8572 for arg
in self
.args_for_cmds
:
8573 arg
.AddInitArgs(self
.init_args
)
8576 self
.init_args
.append(self
.return_arg
)
8578 self
.type_handler
.InitFunction(self
)
8580 def IsImmediate(self
):
8581 """Returns whether the function is immediate data function or not."""
8585 """Returns whether the function has service side validation or not."""
8586 return self
.GetInfo('unsafe', False)
8588 def GetInfo(self
, name
, default
= None):
8589 """Returns a value from the function info for this function."""
8590 if name
in self
.info
:
8591 return self
.info
[name
]
8594 def GetValidArg(self
, arg
):
8595 """Gets a valid argument value for the parameter arg from the function info
8598 index
= self
.GetOriginalArgs().index(arg
)
8602 valid_args
= self
.GetInfo('valid_args')
8603 if valid_args
and str(index
) in valid_args
:
8604 return valid_args
[str(index
)]
8607 def AddInfo(self
, name
, value
):
8609 self
.info
[name
] = value
8611 def IsExtension(self
):
8612 return self
.GetInfo('extension') or self
.GetInfo('extension_flag')
8614 def IsCoreGLFunction(self
):
8615 return (not self
.IsExtension() and
8616 not self
.GetInfo('pepper_interface') and
8617 not self
.IsUnsafe())
8619 def InPepperInterface(self
, interface
):
8620 ext
= self
.GetInfo('pepper_interface')
8621 if not interface
.GetName():
8622 return self
.IsCoreGLFunction()
8623 return ext
== interface
.GetName()
8625 def InAnyPepperExtension(self
):
8626 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
8628 def GetErrorReturnString(self
):
8629 if self
.GetInfo("error_return"):
8630 return self
.GetInfo("error_return")
8631 elif self
.return_type
== "GLboolean":
8633 elif "*" in self
.return_type
:
8637 def GetGLFunctionName(self
):
8638 """Gets the function to call to execute GL for this command."""
8639 if self
.GetInfo('decoder_func'):
8640 return self
.GetInfo('decoder_func')
8641 return "gl%s" % self
.original_name
8643 def GetGLTestFunctionName(self
):
8644 gl_func_name
= self
.GetInfo('gl_test_func')
8645 if gl_func_name
== None:
8646 gl_func_name
= self
.GetGLFunctionName()
8647 if gl_func_name
.startswith("gl"):
8648 gl_func_name
= gl_func_name
[2:]
8650 gl_func_name
= self
.original_name
8653 def GetDataTransferMethods(self
):
8654 return self
.GetInfo('data_transfer_methods',
8655 ['immediate' if self
.num_pointer_args
== 1 else 'shm'])
8657 def AddCmdArg(self
, arg
):
8658 """Adds a cmd argument to this function."""
8659 self
.cmd_args
.append(arg
)
8661 def GetCmdArgs(self
):
8662 """Gets the command args for this function."""
8663 return self
.cmd_args
8665 def ClearCmdArgs(self
):
8666 """Clears the command args for this function."""
8669 def GetCmdConstants(self
):
8670 """Gets the constants for this function."""
8671 return [arg
for arg
in self
.args_for_cmds
if arg
.IsConstant()]
8673 def GetInitArgs(self
):
8674 """Gets the init args for this function."""
8675 return self
.init_args
8677 def GetOriginalArgs(self
):
8678 """Gets the original arguments to this function."""
8679 return self
.original_args
8681 def GetLastOriginalArg(self
):
8682 """Gets the last original argument to this function."""
8683 return self
.original_args
[len(self
.original_args
) - 1]
8685 def GetLastOriginalPointerArg(self
):
8686 return self
.last_original_pointer_arg
8688 def GetResourceIdArg(self
):
8689 for arg
in self
.original_args
:
8690 if hasattr(arg
, 'resource_type'):
8694 def _MaybePrependComma(self
, arg_string
, add_comma
):
8695 """Adds a comma if arg_string is not empty and add_comma is true."""
8697 if add_comma
and len(arg_string
):
8699 return "%s%s" % (comma
, arg_string
)
8701 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
8702 """Gets a list of arguments as they are in GL."""
8703 args
= self
.GetOriginalArgs()
8704 arg_string
= ", ".join(
8705 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
8706 return self
._MaybePrependComma
(arg_string
, add_comma
)
8708 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
8709 """Gets the list of arguments as they are in GL."""
8710 args
= self
.GetOriginalArgs()
8711 arg_string
= separator
.join(
8712 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
8713 return self
._MaybePrependComma
(arg_string
, add_comma
)
8715 def MakeTypedHelperArgString(self
, prefix
, add_comma
= False):
8716 """Gets a list of typed GL arguments after removing unneeded arguments."""
8717 args
= self
.GetOriginalArgs()
8718 arg_string
= ", ".join(
8723 ) for arg
in args
if not arg
.IsConstant()])
8724 return self
._MaybePrependComma
(arg_string
, add_comma
)
8726 def MakeHelperArgString(self
, prefix
, add_comma
= False, separator
= ", "):
8727 """Gets a list of GL arguments after removing unneeded arguments."""
8728 args
= self
.GetOriginalArgs()
8729 arg_string
= separator
.join(
8730 ["%s%s" % (prefix
, arg
.name
)
8731 for arg
in args
if not arg
.IsConstant()])
8732 return self
._MaybePrependComma
(arg_string
, add_comma
)
8734 def MakeTypedPepperArgString(self
, prefix
):
8735 """Gets a list of arguments as they need to be for Pepper."""
8736 if self
.GetInfo("pepper_args"):
8737 return self
.GetInfo("pepper_args")
8739 return self
.MakeTypedOriginalArgString(prefix
, False)
8741 def MapCTypeToPepperIdlType(self
, ctype
, is_for_return_type
=False):
8742 """Converts a C type name to the corresponding Pepper IDL type."""
8744 'char*': '[out] str_t',
8745 'const GLchar* const*': '[out] cstr_t',
8746 'const char*': 'cstr_t',
8747 'const void*': 'mem_t',
8748 'void*': '[out] mem_t',
8749 'void**': '[out] mem_ptr_t',
8751 # We use "GLxxx_ptr_t" for "GLxxx*".
8752 matched
= re
.match(r
'(const )?(GL\w+)\*$', ctype
)
8754 idltype
= matched
.group(2) + '_ptr_t'
8755 if not matched
.group(1):
8756 idltype
= '[out] ' + idltype
8757 # If an in/out specifier is not specified yet, prepend [in].
8758 if idltype
[0] != '[':
8759 idltype
= '[in] ' + idltype
8760 # Strip the in/out specifier for a return type.
8761 if is_for_return_type
:
8762 idltype
= re
.sub(r
'\[\w+\] ', '', idltype
)
8765 def MakeTypedPepperIdlArgStrings(self
):
8766 """Gets a list of arguments as they need to be for Pepper IDL."""
8767 args
= self
.GetOriginalArgs()
8768 return ["%s %s" % (self
.MapCTypeToPepperIdlType(arg
.type), arg
.name
)
8771 def GetPepperName(self
):
8772 if self
.GetInfo("pepper_name"):
8773 return self
.GetInfo("pepper_name")
8776 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
8777 """Gets a typed list of arguments as they need to be for command buffers."""
8778 args
= self
.GetCmdArgs()
8779 arg_string
= ", ".join(
8780 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
8781 return self
._MaybePrependComma
(arg_string
, add_comma
)
8783 def MakeCmdArgString(self
, prefix
, add_comma
= False):
8784 """Gets the list of arguments as they need to be for command buffers."""
8785 args
= self
.GetCmdArgs()
8786 arg_string
= ", ".join(
8787 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
8788 return self
._MaybePrependComma
(arg_string
, add_comma
)
8790 def MakeTypedInitString(self
, prefix
, add_comma
= False):
8791 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
8792 args
= self
.GetInitArgs()
8793 arg_string
= ", ".join(
8794 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
8795 return self
._MaybePrependComma
(arg_string
, add_comma
)
8797 def MakeInitString(self
, prefix
, add_comma
= False):
8798 """Gets the list of arguments as they need to be for cmd Init/Set."""
8799 args
= self
.GetInitArgs()
8800 arg_string
= ", ".join(
8801 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
8802 return self
._MaybePrependComma
(arg_string
, add_comma
)
8804 def MakeLogArgString(self
):
8805 """Makes a string of the arguments for the LOG macros"""
8806 args
= self
.GetOriginalArgs()
8807 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
8809 def WriteCommandDescription(self
, file):
8810 """Writes a description of the command."""
8811 file.Write("//! Command that corresponds to gl%s.\n" % self
.original_name
)
8813 def WriteHandlerValidation(self
, file):
8814 """Writes validation code for the function."""
8815 for arg
in self
.GetOriginalArgs():
8816 arg
.WriteValidationCode(file, self
)
8817 self
.WriteValidationCode(file)
8819 def WriteHandlerImplementation(self
, file):
8820 """Writes the handler implementation for this command."""
8821 self
.type_handler
.WriteHandlerImplementation(self
, file)
8823 def WriteValidationCode(self
, file):
8824 """Writes the validation code for a command."""
8827 def WriteCmdFlag(self
, file):
8828 """Writes the cmd cmd_flags constant."""
8830 # By default trace only at the highest level 3.
8831 trace_level
= int(self
.GetInfo('trace_level', default
= 3))
8832 if trace_level
not in xrange(0, 4):
8833 raise KeyError("Unhandled trace_level: %d" % trace_level
)
8835 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
8838 cmd_flags
= ' | '.join(flags
)
8842 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
8845 def WriteCmdArgFlag(self
, file):
8846 """Writes the cmd kArgFlags constant."""
8847 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
8849 def WriteCmdComputeSize(self
, file):
8850 """Writes the ComputeSize function for the command."""
8851 file.Write(" static uint32_t ComputeSize() {\n")
8853 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
8857 def WriteCmdSetHeader(self
, file):
8858 """Writes the cmd's SetHeader function."""
8859 file.Write(" void SetHeader() {\n")
8860 file.Write(" header.SetCmd<ValueType>();\n")
8864 def WriteCmdInit(self
, file):
8865 """Writes the cmd's Init function."""
8866 file.Write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
8867 file.Write(" SetHeader();\n")
8868 args
= self
.GetCmdArgs()
8870 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
8874 def WriteCmdSet(self
, file):
8875 """Writes the cmd's Set function."""
8876 copy_args
= self
.MakeCmdArgString("_", False)
8877 file.Write(" void* Set(void* cmd%s) {\n" %
8878 self
.MakeTypedCmdArgString("_", True))
8879 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
8880 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
8884 def WriteStruct(self
, file):
8885 self
.type_handler
.WriteStruct(self
, file)
8887 def WriteDocs(self
, file):
8888 self
.type_handler
.WriteDocs(self
, file)
8890 def WriteCmdHelper(self
, file):
8891 """Writes the cmd's helper."""
8892 self
.type_handler
.WriteCmdHelper(self
, file)
8894 def WriteServiceImplementation(self
, file):
8895 """Writes the service implementation for a command."""
8896 self
.type_handler
.WriteServiceImplementation(self
, file)
8898 def WriteServiceUnitTest(self
, file, *extras
):
8899 """Writes the service implementation for a command."""
8900 self
.type_handler
.WriteServiceUnitTest(self
, file, *extras
)
8902 def WriteGLES2CLibImplementation(self
, file):
8903 """Writes the GLES2 C Lib Implemention."""
8904 self
.type_handler
.WriteGLES2CLibImplementation(self
, file)
8906 def WriteGLES2InterfaceHeader(self
, file):
8907 """Writes the GLES2 Interface declaration."""
8908 self
.type_handler
.WriteGLES2InterfaceHeader(self
, file)
8910 def WriteGLES2InterfaceStub(self
, file):
8911 """Writes the GLES2 Interface Stub declaration."""
8912 self
.type_handler
.WriteGLES2InterfaceStub(self
, file)
8914 def WriteGLES2InterfaceStubImpl(self
, file):
8915 """Writes the GLES2 Interface Stub declaration."""
8916 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, file)
8918 def WriteGLES2ImplementationHeader(self
, file):
8919 """Writes the GLES2 Implemention declaration."""
8920 self
.type_handler
.WriteGLES2ImplementationHeader(self
, file)
8922 def WriteGLES2Implementation(self
, file):
8923 """Writes the GLES2 Implemention definition."""
8924 self
.type_handler
.WriteGLES2Implementation(self
, file)
8926 def WriteGLES2TraceImplementationHeader(self
, file):
8927 """Writes the GLES2 Trace Implemention declaration."""
8928 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, file)
8930 def WriteGLES2TraceImplementation(self
, file):
8931 """Writes the GLES2 Trace Implemention definition."""
8932 self
.type_handler
.WriteGLES2TraceImplementation(self
, file)
8934 def WriteGLES2Header(self
, file):
8935 """Writes the GLES2 Implemention unit test."""
8936 self
.type_handler
.WriteGLES2Header(self
, file)
8938 def WriteGLES2ImplementationUnitTest(self
, file):
8939 """Writes the GLES2 Implemention unit test."""
8940 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, file)
8942 def WriteDestinationInitalizationValidation(self
, file):
8943 """Writes the client side destintion initialization validation."""
8944 self
.type_handler
.WriteDestinationInitalizationValidation(self
, file)
8946 def WriteFormatTest(self
, file):
8947 """Writes the cmd's format test."""
8948 self
.type_handler
.WriteFormatTest(self
, file)
8951 class PepperInterface(object):
8952 """A class that represents a function."""
8954 def __init__(self
, info
):
8955 self
.name
= info
["name"]
8956 self
.dev
= info
["dev"]
8961 def GetInterfaceName(self
):
8965 upperint
= "_" + self
.name
.upper()
8968 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
8970 def GetInterfaceString(self
):
8974 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
8976 def GetStructName(self
):
8980 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
8983 class ImmediateFunction(Function
):
8984 """A class that represnets an immediate function command."""
8986 def __init__(self
, func
):
8989 "%sImmediate" % func
.name
,
8992 def InitFunction(self
):
8993 # Override args in original_args and args_for_cmds with immediate versions
8996 new_original_args
= []
8997 for arg
in self
.original_args
:
8998 new_arg
= arg
.GetImmediateVersion()
9000 new_original_args
.append(new_arg
)
9001 self
.original_args
= new_original_args
9003 new_args_for_cmds
= []
9004 for arg
in self
.args_for_cmds
:
9005 new_arg
= arg
.GetImmediateVersion()
9007 new_args_for_cmds
.append(new_arg
)
9009 self
.args_for_cmds
= new_args_for_cmds
9011 Function
.InitFunction(self
)
9013 def IsImmediate(self
):
9016 def WriteCommandDescription(self
, file):
9017 """Overridden from Function"""
9018 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
9021 def WriteServiceImplementation(self
, file):
9022 """Overridden from Function"""
9023 self
.type_handler
.WriteImmediateServiceImplementation(self
, file)
9025 def WriteHandlerImplementation(self
, file):
9026 """Overridden from Function"""
9027 self
.type_handler
.WriteImmediateHandlerImplementation(self
, file)
9029 def WriteServiceUnitTest(self
, file, *extras
):
9030 """Writes the service implementation for a command."""
9031 self
.type_handler
.WriteImmediateServiceUnitTest(self
, file, *extras
)
9033 def WriteValidationCode(self
, file):
9034 """Overridden from Function"""
9035 self
.type_handler
.WriteImmediateValidationCode(self
, file)
9037 def WriteCmdArgFlag(self
, file):
9038 """Overridden from Function"""
9039 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9041 def WriteCmdComputeSize(self
, file):
9042 """Overridden from Function"""
9043 self
.type_handler
.WriteImmediateCmdComputeSize(self
, file)
9045 def WriteCmdSetHeader(self
, file):
9046 """Overridden from Function"""
9047 self
.type_handler
.WriteImmediateCmdSetHeader(self
, file)
9049 def WriteCmdInit(self
, file):
9050 """Overridden from Function"""
9051 self
.type_handler
.WriteImmediateCmdInit(self
, file)
9053 def WriteCmdSet(self
, file):
9054 """Overridden from Function"""
9055 self
.type_handler
.WriteImmediateCmdSet(self
, file)
9057 def WriteCmdHelper(self
, file):
9058 """Overridden from Function"""
9059 self
.type_handler
.WriteImmediateCmdHelper(self
, file)
9061 def WriteFormatTest(self
, file):
9062 """Overridden from Function"""
9063 self
.type_handler
.WriteImmediateFormatTest(self
, file)
9066 class BucketFunction(Function
):
9067 """A class that represnets a bucket version of a function command."""
9069 def __init__(self
, func
):
9072 "%sBucket" % func
.name
,
9075 def InitFunction(self
):
9076 # Override args in original_args and args_for_cmds with bucket versions
9079 new_original_args
= []
9080 for arg
in self
.original_args
:
9081 new_arg
= arg
.GetBucketVersion()
9083 new_original_args
.append(new_arg
)
9084 self
.original_args
= new_original_args
9086 new_args_for_cmds
= []
9087 for arg
in self
.args_for_cmds
:
9088 new_arg
= arg
.GetBucketVersion()
9090 new_args_for_cmds
.append(new_arg
)
9092 self
.args_for_cmds
= new_args_for_cmds
9094 Function
.InitFunction(self
)
9096 def WriteCommandDescription(self
, file):
9097 """Overridden from Function"""
9098 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
9101 def WriteServiceImplementation(self
, file):
9102 """Overridden from Function"""
9103 self
.type_handler
.WriteBucketServiceImplementation(self
, file)
9105 def WriteHandlerImplementation(self
, file):
9106 """Overridden from Function"""
9107 self
.type_handler
.WriteBucketHandlerImplementation(self
, file)
9109 def WriteServiceUnitTest(self
, file, *extras
):
9110 """Overridden from Function"""
9111 self
.type_handler
.WriteBucketServiceUnitTest(self
, file, *extras
)
9113 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9114 """Overridden from Function"""
9115 args
= self
.GetOriginalArgs()
9116 arg_string
= separator
.join(
9117 ["%s%s" % (prefix
, arg
.name
[0:-10] if arg
.name
.endswith("_bucket_id")
9118 else arg
.name
) for arg
in args
])
9119 return super(BucketFunction
, self
)._MaybePrependComma
(arg_string
, add_comma
)
9122 def CreateArg(arg_string
):
9123 """Creates an Argument."""
9124 arg_parts
= arg_string
.split()
9125 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
9127 # Is this a pointer argument?
9128 elif arg_string
.find('*') >= 0:
9129 return PointerArgument(
9131 " ".join(arg_parts
[0:-1]))
9132 # Is this a resource argument? Must come after pointer check.
9133 elif arg_parts
[0].startswith('GLidBind'):
9134 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9135 elif arg_parts
[0].startswith('GLidZero'):
9136 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9137 elif arg_parts
[0].startswith('GLid'):
9138 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9139 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
9140 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9141 elif arg_parts
[0].startswith('GLbitfield') and len(arg_parts
[0]) > 10:
9142 return BitFieldArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9143 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
9144 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9145 elif arg_parts
[0].startswith('GLboolean'):
9146 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9147 elif arg_parts
[0].startswith('GLintUniformLocation'):
9148 return UniformLocationArgument(arg_parts
[-1])
9149 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
9150 not arg_parts
[0].startswith('GLintptr')):
9151 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9152 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
9153 arg_parts
[0].startswith('GLintptrNotNegative')):
9154 return SizeNotNegativeArgument(arg_parts
[-1],
9155 " ".join(arg_parts
[0:-1]),
9156 arg_parts
[0][0:-11])
9157 elif arg_parts
[0].startswith('GLsize'):
9158 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9160 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9163 class GLGenerator(object):
9164 """A class to generate GL command buffers."""
9166 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9168 def __init__(self
, verbose
):
9169 self
.original_functions
= []
9171 self
.verbose
= verbose
9173 self
.pepper_interfaces
= []
9174 self
.interface_info
= {}
9175 self
.generated_cpp_filenames
= []
9177 for interface
in _PEPPER_INTERFACES
:
9178 interface
= PepperInterface(interface
)
9179 self
.pepper_interfaces
.append(interface
)
9180 self
.interface_info
[interface
.GetName()] = interface
9182 def AddFunction(self
, func
):
9183 """Adds a function."""
9184 self
.functions
.append(func
)
9186 def GetFunctionInfo(self
, name
):
9187 """Gets a type info for the given function name."""
9188 if name
in _FUNCTION_INFO
:
9189 func_info
= _FUNCTION_INFO
[name
].copy()
9193 if not 'type' in func_info
:
9194 func_info
['type'] = ''
9199 """Prints something if verbose is true."""
9203 def Error(self
, msg
):
9204 """Prints an error."""
9205 print "Error: %s" % msg
9208 def WriteLicense(self
, file):
9209 """Writes the license."""
9210 file.Write(_LICENSE
)
9212 def WriteNamespaceOpen(self
, file):
9213 """Writes the code for the namespace."""
9214 file.Write("namespace gpu {\n")
9215 file.Write("namespace gles2 {\n")
9218 def WriteNamespaceClose(self
, file):
9219 """Writes the code to close the namespace."""
9220 file.Write("} // namespace gles2\n")
9221 file.Write("} // namespace gpu\n")
9224 def ParseGLH(self
, filename
):
9225 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9226 f
= open(filename
, "r")
9227 functions
= f
.read()
9229 for line
in functions
.splitlines():
9230 match
= self
._function
_re
.match(line
)
9232 func_name
= match
.group(2)[2:]
9233 func_info
= self
.GetFunctionInfo(func_name
)
9234 if func_info
['type'] == 'Noop':
9237 parsed_func_info
= {
9238 'original_name': func_name
,
9239 'original_args': match
.group(3),
9240 'return_type': match
.group(1).strip(),
9243 for k
in parsed_func_info
.keys():
9244 if not k
in func_info
:
9245 func_info
[k
] = parsed_func_info
[k
]
9247 f
= Function(func_name
, func_info
)
9248 self
.original_functions
.append(f
)
9250 #for arg in f.GetOriginalArgs():
9251 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9252 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9254 gen_cmd
= f
.GetInfo('gen_cmd')
9255 if gen_cmd
== True or gen_cmd
== None:
9256 if f
.type_handler
.NeedsDataTransferFunction(f
):
9257 methods
= f
.GetDataTransferMethods()
9258 if 'immediate' in methods
:
9259 self
.AddFunction(ImmediateFunction(f
))
9260 if 'bucket' in methods
:
9261 self
.AddFunction(BucketFunction(f
))
9262 if 'shm' in methods
:
9267 self
.Log("Auto Generated Functions : %d" %
9268 len([f
for f
in self
.functions
if f
.can_auto_generate
or
9269 (not f
.IsType('') and not f
.IsType('Custom') and
9270 not f
.IsType('Todo'))]))
9272 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
9273 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
9274 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
9277 self
.Log(" %-10s %-20s gl%s" % (f
.info
['type'], f
.return_type
, f
.name
))
9279 def WriteCommandIds(self
, filename
):
9280 """Writes the command buffer format"""
9281 file = CHeaderWriter(filename
)
9282 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
9284 for func
in self
.functions
:
9285 file.Write(" %-60s /* %d */ \\\n" %
9286 ("OP(%s)" % func
.name
, id))
9290 file.Write("enum CommandId {\n")
9291 file.Write(" kStartPoint = cmd::kLastCommonId, "
9292 "// All GLES2 commands start after this.\n")
9293 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
9294 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9295 file.Write("#undef GLES2_CMD_OP\n")
9296 file.Write(" kNumCommands\n")
9300 self
.generated_cpp_filenames
.append(file.filename
)
9302 def WriteFormat(self
, filename
):
9303 """Writes the command buffer format"""
9304 file = CHeaderWriter(filename
)
9305 # Forward declaration of a few enums used in constant argument
9306 # to avoid including GL header files.
9308 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9309 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9312 for enum
in enum_defines
:
9313 file.Write("#define %s %s\n" % (enum
, enum_defines
[enum
]))
9315 for func
in self
.functions
:
9317 #gen_cmd = func.GetInfo('gen_cmd')
9318 #if gen_cmd == True or gen_cmd == None:
9319 func
.WriteStruct(file)
9322 self
.generated_cpp_filenames
.append(file.filename
)
9324 def WriteDocs(self
, filename
):
9325 """Writes the command buffer doc version of the commands"""
9326 file = CWriter(filename
)
9327 for func
in self
.functions
:
9329 #gen_cmd = func.GetInfo('gen_cmd')
9330 #if gen_cmd == True or gen_cmd == None:
9331 func
.WriteDocs(file)
9334 self
.generated_cpp_filenames
.append(file.filename
)
9336 def WriteFormatTest(self
, filename
):
9337 """Writes the command buffer format test."""
9338 file = CHeaderWriter(
9340 "// This file contains unit tests for gles2 commmands\n"
9341 "// It is included by gles2_cmd_format_test.cc\n"
9344 for func
in self
.functions
:
9346 #gen_cmd = func.GetInfo('gen_cmd')
9347 #if gen_cmd == True or gen_cmd == None:
9348 func
.WriteFormatTest(file)
9351 self
.generated_cpp_filenames
.append(file.filename
)
9353 def WriteCmdHelperHeader(self
, filename
):
9354 """Writes the gles2 command helper."""
9355 file = CHeaderWriter(filename
)
9357 for func
in self
.functions
:
9359 #gen_cmd = func.GetInfo('gen_cmd')
9360 #if gen_cmd == True or gen_cmd == None:
9361 func
.WriteCmdHelper(file)
9364 self
.generated_cpp_filenames
.append(file.filename
)
9366 def WriteServiceContextStateHeader(self
, filename
):
9367 """Writes the service context state header."""
9368 file = CHeaderWriter(
9370 "// It is included by context_state.h\n")
9371 file.Write("struct EnableFlags {\n")
9372 file.Write(" EnableFlags();\n")
9373 for capability
in _CAPABILITY_FLAGS
:
9374 file.Write(" bool %s;\n" % capability
['name'])
9375 file.Write(" bool cached_%s;\n" % capability
['name'])
9376 file.Write("};\n\n")
9378 for state_name
in sorted(_STATES
.keys()):
9379 state
= _STATES
[state_name
]
9380 for item
in state
['states']:
9381 if isinstance(item
['default'], list):
9382 file.Write("%s %s[%d];\n" % (item
['type'], item
['name'],
9383 len(item
['default'])))
9385 file.Write("%s %s;\n" % (item
['type'], item
['name']))
9387 if item
.get('cached', False):
9388 if isinstance(item
['default'], list):
9389 file.Write("%s cached_%s[%d];\n" % (item
['type'], item
['name'],
9390 len(item
['default'])))
9392 file.Write("%s cached_%s;\n" % (item
['type'], item
['name']))
9397 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9400 for capability
in _CAPABILITY_FLAGS
:
9403 """ % capability
['name'].upper())
9405 if (enable_flags.cached_%(name)s == enable &&
9406 !ignore_cached_state)
9408 enable_flags.cached_%(name)s = enable;
9425 self
.generated_cpp_filenames
.append(file.filename
)
9427 def WriteClientContextStateHeader(self
, filename
):
9428 """Writes the client context state header."""
9429 file = CHeaderWriter(
9431 "// It is included by client_context_state.h\n")
9432 file.Write("struct EnableFlags {\n")
9433 file.Write(" EnableFlags();\n")
9434 for capability
in _CAPABILITY_FLAGS
:
9435 file.Write(" bool %s;\n" % capability
['name'])
9436 file.Write("};\n\n")
9439 self
.generated_cpp_filenames
.append(file.filename
)
9441 def WriteContextStateGetters(self
, file, class_name
):
9442 """Writes the state getters."""
9443 for gl_type
in ["GLint", "GLfloat"]:
9445 bool %s::GetStateAs%s(
9446 GLenum pname, %s* params, GLsizei* num_written) const {
9448 """ % (class_name
, gl_type
, gl_type
))
9449 for state_name
in sorted(_STATES
.keys()):
9450 state
= _STATES
[state_name
]
9452 file.Write(" case %s:\n" % state
['enum'])
9453 file.Write(" *num_written = %d;\n" % len(state
['states']))
9454 file.Write(" if (params) {\n")
9455 for ndx
,item
in enumerate(state
['states']):
9456 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
9457 (ndx
, gl_type
, item
['name']))
9459 file.Write(" return true;\n")
9461 for item
in state
['states']:
9462 file.Write(" case %s:\n" % item
['enum'])
9463 if isinstance(item
['default'], list):
9464 item_len
= len(item
['default'])
9465 file.Write(" *num_written = %d;\n" % item_len
)
9466 file.Write(" if (params) {\n")
9467 if item
['type'] == gl_type
:
9468 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9469 (item
['name'], item
['type'], item_len
))
9471 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
9473 file.Write(" params[i] = %s;\n" %
9474 (GetGLGetTypeConversion(gl_type
, item
['type'],
9475 "%s[i]" % item
['name'])))
9478 file.Write(" *num_written = 1;\n")
9479 file.Write(" if (params) {\n")
9480 file.Write(" params[0] = %s;\n" %
9481 (GetGLGetTypeConversion(gl_type
, item
['type'],
9484 file.Write(" return true;\n")
9485 for capability
in _CAPABILITY_FLAGS
:
9486 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9487 file.Write(" *num_written = 1;\n")
9488 file.Write(" if (params) {\n")
9490 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9491 (gl_type
, capability
['name']))
9493 file.Write(" return true;\n")
9494 file.Write(""" default:
9500 def WriteServiceContextStateImpl(self
, filename
):
9501 """Writes the context state service implementation."""
9502 file = CHeaderWriter(
9504 "// It is included by context_state.cc\n")
9506 for capability
in _CAPABILITY_FLAGS
:
9507 code
.append("%s(%s)" %
9508 (capability
['name'],
9509 ('false', 'true')['default' in capability
]))
9510 code
.append("cached_%s(%s)" %
9511 (capability
['name'],
9512 ('false', 'true')['default' in capability
]))
9513 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9517 file.Write("void ContextState::Initialize() {\n")
9518 for state_name
in sorted(_STATES
.keys()):
9519 state
= _STATES
[state_name
]
9520 for item
in state
['states']:
9521 if isinstance(item
['default'], list):
9522 for ndx
, value
in enumerate(item
['default']):
9523 file.Write(" %s[%d] = %s;\n" % (item
['name'], ndx
, value
))
9525 file.Write(" %s = %s;\n" % (item
['name'], item
['default']))
9526 if item
.get('cached', False):
9527 if isinstance(item
['default'], list):
9528 for ndx
, value
in enumerate(item
['default']):
9529 file.Write(" cached_%s[%d] = %s;\n" % (item
['name'], ndx
, value
))
9531 file.Write(" cached_%s = %s;\n" % (item
['name'], item
['default']))
9535 void ContextState::InitCapabilities(const ContextState* prev_state) const {
9537 def WriteCapabilities(test_prev
):
9538 for capability
in _CAPABILITY_FLAGS
:
9539 capability_name
= capability
['name']
9541 file.Write(""" if (prev_state->enable_flags.cached_%s !=
9542 enable_flags.cached_%s)\n""" %
9543 (capability_name
, capability_name
))
9544 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
9545 (capability_name
.upper(), capability_name
))
9547 file.Write(" if (prev_state) {")
9548 WriteCapabilities(True)
9549 file.Write(" } else {")
9550 WriteCapabilities(False)
9555 void ContextState::InitState(const ContextState *prev_state) const {
9558 def WriteStates(test_prev
):
9559 # We need to sort the keys so the expectations match
9560 for state_name
in sorted(_STATES
.keys()):
9561 state
= _STATES
[state_name
]
9562 if state
['type'] == 'FrontBack':
9563 num_states
= len(state
['states'])
9564 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
9568 for place
, item
in enumerate(group
):
9569 item_name
= CachedStateName(item
)
9570 args
.append('%s' % item_name
)
9574 file.Write("(%s != prev_state->%s)" % (item_name
, item_name
))
9578 " gl%s(%s, %s);\n" %
9579 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
9580 elif state
['type'] == 'NamedParameter':
9581 for item
in state
['states']:
9582 item_name
= CachedStateName(item
)
9584 if 'extension_flag' in item
:
9585 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
9586 item
['extension_flag'])
9588 if isinstance(item
['default'], list):
9589 file.Write(" if (memcmp(prev_state->%s, %s, "
9590 "sizeof(%s) * %d)) {\n" %
9591 (item_name
, item_name
, item
['type'],
9592 len(item
['default'])))
9594 file.Write(" if (prev_state->%s != %s) {\n " %
9595 (item_name
, item_name
))
9596 file.Write(" gl%s(%s, %s);\n" %
9599 if 'enum_set' in item
else item
['enum']),
9602 if 'extension_flag' in item
:
9605 if 'extension_flag' in item
:
9608 if 'extension_flag' in state
:
9609 file.Write(" if (feature_info_->feature_flags().%s)\n " %
9610 state
['extension_flag'])
9614 for place
, item
in enumerate(state
['states']):
9615 item_name
= CachedStateName(item
)
9616 args
.append('%s' % item_name
)
9620 file.Write("(%s != prev_state->%s)" %
9621 (item_name
, item_name
))
9624 file.Write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
9626 file.Write(" if (prev_state) {")
9628 file.Write(" } else {")
9633 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
9636 for capability
in _CAPABILITY_FLAGS
:
9637 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9638 file.Write(" return enable_flags.%s;\n" % capability
['name'])
9639 file.Write(""" default:
9646 self
.WriteContextStateGetters(file, "ContextState")
9648 self
.generated_cpp_filenames
.append(file.filename
)
9650 def WriteClientContextStateImpl(self
, filename
):
9651 """Writes the context state client side implementation."""
9652 file = CHeaderWriter(
9654 "// It is included by client_context_state.cc\n")
9656 for capability
in _CAPABILITY_FLAGS
:
9657 code
.append("%s(%s)" %
9658 (capability
['name'],
9659 ('false', 'true')['default' in capability
]))
9661 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9666 bool ClientContextState::SetCapabilityState(
9667 GLenum cap, bool enabled, bool* changed) {
9671 for capability
in _CAPABILITY_FLAGS
:
9672 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9673 file.Write(""" if (enable_flags.%(name)s != enabled) {
9675 enable_flags.%(name)s = enabled;
9679 file.Write(""" default:
9684 file.Write("""bool ClientContextState::GetEnabled(
9685 GLenum cap, bool* enabled) const {
9688 for capability
in _CAPABILITY_FLAGS
:
9689 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9690 file.Write(" *enabled = enable_flags.%s;\n" % capability
['name'])
9691 file.Write(" return true;\n")
9692 file.Write(""" default:
9698 self
.generated_cpp_filenames
.append(file.filename
)
9700 def WriteServiceImplementation(self
, filename
):
9701 """Writes the service decorder implementation."""
9702 file = CHeaderWriter(
9704 "// It is included by gles2_cmd_decoder.cc\n")
9706 for func
in self
.functions
:
9708 #gen_cmd = func.GetInfo('gen_cmd')
9709 #if gen_cmd == True or gen_cmd == None:
9710 func
.WriteServiceImplementation(file)
9713 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
9716 for capability
in _CAPABILITY_FLAGS
:
9717 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9718 if 'state_flag' in capability
:
9721 state_.enable_flags.%(name)s = enabled;
9722 if (state_.enable_flags.cached_%(name)s != enabled
9723 || state_.ignore_cached_state) {
9724 %(state_flag)s = true;
9730 state_.enable_flags.%(name)s = enabled;
9731 if (state_.enable_flags.cached_%(name)s != enabled
9732 || state_.ignore_cached_state) {
9733 state_.enable_flags.cached_%(name)s = enabled;
9738 file.Write(""" default:
9745 self
.generated_cpp_filenames
.append(file.filename
)
9747 def WriteServiceUnitTests(self
, filename
):
9748 """Writes the service decorder unit tests."""
9749 num_tests
= len(self
.functions
)
9750 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
9752 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
9754 name
= filename
% count
9755 file = CHeaderWriter(
9757 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count
)
9758 test_name
= 'GLES2DecoderTest%d' % count
9759 end
= test_num
+ FUNCTIONS_PER_FILE
9762 for idx
in range(test_num
, end
):
9763 func
= self
.functions
[idx
]
9765 # Do any filtering of the functions here, so that the functions
9766 # will not move between the numbered files if filtering properties
9768 if func
.GetInfo('extension_flag'):
9772 #gen_cmd = func.GetInfo('gen_cmd')
9773 #if gen_cmd == True or gen_cmd == None:
9774 if func
.GetInfo('unit_test') == False:
9775 file.Write("// TODO(gman): %s\n" % func
.name
)
9777 func
.WriteServiceUnitTest(file, {
9778 'test_name': test_name
9781 self
.generated_cpp_filenames
.append(file.filename
)
9782 file = CHeaderWriter(
9784 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
9786 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
9788 for capability
in _CAPABILITY_FLAGS
:
9789 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
9790 (capability
['name'].upper(),
9791 ('false', 'true')['default' in capability
]))
9794 void GLES2DecoderTestBase::SetupInitStateExpectations() {
9797 # We need to sort the keys so the expectations match
9798 for state_name
in sorted(_STATES
.keys()):
9799 state
= _STATES
[state_name
]
9800 if state
['type'] == 'FrontBack':
9801 num_states
= len(state
['states'])
9802 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
9805 if 'expected' in item
:
9806 args
.append(item
['expected'])
9808 args
.append(item
['default'])
9810 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
9811 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
9812 file.Write(" .Times(1)\n")
9813 file.Write(" .RetiresOnSaturation();\n")
9814 elif state
['type'] == 'NamedParameter':
9815 for item
in state
['states']:
9816 if 'extension_flag' in item
:
9817 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
9818 item
['extension_flag'])
9820 expect_value
= item
['default']
9821 if isinstance(expect_value
, list):
9822 # TODO: Currently we do not check array values.
9826 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
9829 if 'enum_set' in item
else item
['enum']),
9831 file.Write(" .Times(1)\n")
9832 file.Write(" .RetiresOnSaturation();\n")
9833 if 'extension_flag' in item
:
9836 if 'extension_flag' in state
:
9837 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
9838 state
['extension_flag'])
9841 for item
in state
['states']:
9842 if 'expected' in item
:
9843 args
.append(item
['expected'])
9845 args
.append(item
['default'])
9846 # TODO: Currently we do not check array values.
9847 args
= ["_" if isinstance(arg
, list) else arg
for arg
in args
]
9848 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
9849 (state
['func'], ", ".join(args
)))
9850 file.Write(" .Times(1)\n")
9851 file.Write(" .RetiresOnSaturation();\n")
9852 if 'extension_flag' in state
:
9857 self
.generated_cpp_filenames
.append(file.filename
)
9859 def WriteServiceUnitTestsForExtensions(self
, filename
):
9860 """Writes the service decorder unit tests for functions with extension_flag.
9862 The functions are special in that they need a specific unit test
9863 baseclass to turn on the extension.
9865 functions
= [f
for f
in self
.functions
if f
.GetInfo('extension_flag')]
9866 file = CHeaderWriter(
9868 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
9869 for func
in functions
:
9871 if func
.GetInfo('unit_test') == False:
9872 file.Write("// TODO(gman): %s\n" % func
.name
)
9874 extension
= ToCamelCase(
9875 ToGLExtensionString(func
.GetInfo('extension_flag')))
9876 func
.WriteServiceUnitTest(file, {
9877 'test_name': 'GLES2DecoderTestWith%s' % extension
9881 self
.generated_cpp_filenames
.append(file.filename
)
9883 def WriteGLES2Header(self
, filename
):
9884 """Writes the GLES2 header."""
9885 file = CHeaderWriter(
9887 "// This file contains Chromium-specific GLES2 declarations.\n\n")
9889 for func
in self
.original_functions
:
9890 func
.WriteGLES2Header(file)
9894 self
.generated_cpp_filenames
.append(file.filename
)
9896 def WriteGLES2CLibImplementation(self
, filename
):
9897 """Writes the GLES2 c lib implementation."""
9898 file = CHeaderWriter(
9900 "// These functions emulate GLES2 over command buffers.\n")
9902 for func
in self
.original_functions
:
9903 func
.WriteGLES2CLibImplementation(file)
9908 extern const NameToFunc g_gles2_function_table[] = {
9910 for func
in self
.original_functions
:
9912 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
9913 (func
.name
, func
.name
))
9914 file.Write(""" { NULL, NULL, },
9917 } // namespace gles2
9920 self
.generated_cpp_filenames
.append(file.filename
)
9922 def WriteGLES2InterfaceHeader(self
, filename
):
9923 """Writes the GLES2 interface header."""
9924 file = CHeaderWriter(
9926 "// This file is included by gles2_interface.h to declare the\n"
9927 "// GL api functions.\n")
9928 for func
in self
.original_functions
:
9929 func
.WriteGLES2InterfaceHeader(file)
9931 self
.generated_cpp_filenames
.append(file.filename
)
9933 def WriteGLES2InterfaceStub(self
, filename
):
9934 """Writes the GLES2 interface stub header."""
9935 file = CHeaderWriter(
9937 "// This file is included by gles2_interface_stub.h.\n")
9938 for func
in self
.original_functions
:
9939 func
.WriteGLES2InterfaceStub(file)
9941 self
.generated_cpp_filenames
.append(file.filename
)
9943 def WriteGLES2InterfaceStubImpl(self
, filename
):
9944 """Writes the GLES2 interface header."""
9945 file = CHeaderWriter(
9947 "// This file is included by gles2_interface_stub.cc.\n")
9948 for func
in self
.original_functions
:
9949 func
.WriteGLES2InterfaceStubImpl(file)
9951 self
.generated_cpp_filenames
.append(file.filename
)
9953 def WriteGLES2ImplementationHeader(self
, filename
):
9954 """Writes the GLES2 Implementation header."""
9955 file = CHeaderWriter(
9957 "// This file is included by gles2_implementation.h to declare the\n"
9958 "// GL api functions.\n")
9959 for func
in self
.original_functions
:
9960 func
.WriteGLES2ImplementationHeader(file)
9962 self
.generated_cpp_filenames
.append(file.filename
)
9964 def WriteGLES2Implementation(self
, filename
):
9965 """Writes the GLES2 Implementation."""
9966 file = CHeaderWriter(
9968 "// This file is included by gles2_implementation.cc to define the\n"
9969 "// GL api functions.\n")
9970 for func
in self
.original_functions
:
9971 func
.WriteGLES2Implementation(file)
9973 self
.generated_cpp_filenames
.append(file.filename
)
9975 def WriteGLES2TraceImplementationHeader(self
, filename
):
9976 """Writes the GLES2 Trace Implementation header."""
9977 file = CHeaderWriter(
9979 "// This file is included by gles2_trace_implementation.h\n")
9980 for func
in self
.original_functions
:
9981 func
.WriteGLES2TraceImplementationHeader(file)
9983 self
.generated_cpp_filenames
.append(file.filename
)
9985 def WriteGLES2TraceImplementation(self
, filename
):
9986 """Writes the GLES2 Trace Implementation."""
9987 file = CHeaderWriter(
9989 "// This file is included by gles2_trace_implementation.cc\n")
9990 for func
in self
.original_functions
:
9991 func
.WriteGLES2TraceImplementation(file)
9993 self
.generated_cpp_filenames
.append(file.filename
)
9995 def WriteGLES2ImplementationUnitTests(self
, filename
):
9996 """Writes the GLES2 helper header."""
9997 file = CHeaderWriter(
9999 "// This file is included by gles2_implementation.h to declare the\n"
10000 "// GL api functions.\n")
10001 for func
in self
.original_functions
:
10002 func
.WriteGLES2ImplementationUnitTest(file)
10004 self
.generated_cpp_filenames
.append(file.filename
)
10006 def WriteServiceUtilsHeader(self
, filename
):
10007 """Writes the gles2 auto generated utility header."""
10008 file = CHeaderWriter(filename
)
10009 for name
in sorted(_NAMED_TYPE_INFO
.keys()):
10010 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10011 if named_type
.IsConstant():
10013 file.Write("ValueValidator<%s> %s;\n" %
10014 (named_type
.GetType(), ToUnderscore(name
)))
10017 self
.generated_cpp_filenames
.append(file.filename
)
10019 def WriteServiceUtilsImplementation(self
, filename
):
10020 """Writes the gles2 auto generated utility implementation."""
10021 file = CHeaderWriter(filename
)
10022 names
= sorted(_NAMED_TYPE_INFO
.keys())
10024 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10025 if named_type
.IsConstant():
10027 if named_type
.GetValidValues():
10028 file.Write("static const %s valid_%s_table[] = {\n" %
10029 (named_type
.GetType(), ToUnderscore(name
)))
10030 for value
in named_type
.GetValidValues():
10031 file.Write(" %s,\n" % value
)
10034 if named_type
.GetValidValuesES3():
10035 file.Write("static const %s valid_%s_table_es3[] = {\n" %
10036 (named_type
.GetType(), ToUnderscore(name
)))
10037 for value
in named_type
.GetValidValuesES3():
10038 file.Write(" %s,\n" % value
)
10041 if named_type
.GetDeprecatedValuesES3():
10042 file.Write("static const %s deprecated_%s_table_es3[] = {\n" %
10043 (named_type
.GetType(), ToUnderscore(name
)))
10044 for value
in named_type
.GetDeprecatedValuesES3():
10045 file.Write(" %s,\n" % value
)
10048 file.Write("Validators::Validators()")
10050 for count
, name
in enumerate(names
):
10051 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10052 if named_type
.IsConstant():
10054 if named_type
.GetValidValues():
10055 code
= """%(pre)s%(name)s(
10056 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10058 code
= "%(pre)s%(name)s()"
10059 file.Write(code
% {
10060 'name': ToUnderscore(name
),
10064 file.Write(" {\n");
10065 file.Write("}\n\n");
10067 file.Write("void Validators::UpdateValuesES3() {\n")
10069 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10070 if named_type
.GetDeprecatedValuesES3():
10071 code
= """ %(name)s.RemoveValues(
10072 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10074 file.Write(code
% {
10075 'name': ToUnderscore(name
),
10077 if named_type
.GetValidValuesES3():
10078 code
= """ %(name)s.AddValues(
10079 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10081 file.Write(code
% {
10082 'name': ToUnderscore(name
),
10084 file.Write("}\n\n");
10086 self
.generated_cpp_filenames
.append(file.filename
)
10088 def WriteCommonUtilsHeader(self
, filename
):
10089 """Writes the gles2 common utility header."""
10090 file = CHeaderWriter(filename
)
10091 type_infos
= sorted(_NAMED_TYPE_INFO
.keys())
10092 for type_info
in type_infos
:
10093 if _NAMED_TYPE_INFO
[type_info
]['type'] == 'GLenum':
10094 file.Write("static std::string GetString%s(uint32_t value);\n" %
10098 self
.generated_cpp_filenames
.append(file.filename
)
10100 def WriteCommonUtilsImpl(self
, filename
):
10101 """Writes the gles2 common utility header."""
10102 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10104 for fname
in ['third_party/khronos/GLES2/gl2.h',
10105 'third_party/khronos/GLES2/gl2ext.h',
10106 'third_party/khronos/GLES3/gl3.h',
10107 'gpu/GLES2/gl2chromium.h',
10108 'gpu/GLES2/gl2extchromium.h']:
10109 lines
= open(fname
).readlines()
10111 m
= enum_re
.match(line
)
10115 if len(value
) <= 10:
10116 if not value
in dict:
10118 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10119 elif dict[value
] != name
and (name
.endswith('_CHROMIUM') or
10120 dict[value
].endswith('_CHROMIUM')):
10121 self
.Error("code collision: %s and %s have the same code %s" %
10122 (dict[value
], name
, value
))
10124 file = CHeaderWriter(filename
)
10125 file.Write("static const GLES2Util::EnumToString "
10126 "enum_to_string_table[] = {\n")
10128 file.Write(' { %s, "%s", },\n' % (value
, dict[value
]))
10131 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10132 enum_to_string_table;
10133 const size_t GLES2Util::enum_to_string_table_len_ =
10134 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10138 enums
= sorted(_NAMED_TYPE_INFO
.keys())
10140 if _NAMED_TYPE_INFO
[enum
]['type'] == 'GLenum':
10141 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10143 valid_list
= _NAMED_TYPE_INFO
[enum
]['valid']
10144 if 'valid_es3' in _NAMED_TYPE_INFO
[enum
]:
10145 valid_list
= valid_list
+ _NAMED_TYPE_INFO
[enum
]['valid_es3']
10146 assert len(valid_list
) == len(set(valid_list
))
10147 if len(valid_list
) > 0:
10148 file.Write(" static const EnumToString string_table[] = {\n")
10149 for value
in valid_list
:
10150 file.Write(' { %s, "%s" },\n' % (value
, value
))
10152 return GLES2Util::GetQualifiedEnumString(
10153 string_table, arraysize(string_table), value);
10158 file.Write(""" return GLES2Util::GetQualifiedEnumString(
10164 self
.generated_cpp_filenames
.append(file.filename
)
10166 def WritePepperGLES2Interface(self
, filename
, dev
):
10167 """Writes the Pepper OpenGLES interface definition."""
10168 file = CWriter(filename
)
10169 file.Write(_LICENSE
)
10170 file.Write(_DO_NOT_EDIT_WARNING
)
10172 file.Write("label Chrome {\n")
10173 file.Write(" M39 = 1.0\n")
10174 file.Write("};\n\n")
10177 # Declare GL types.
10178 file.Write("[version=1.0]\n")
10179 file.Write("describe {\n")
10180 for gltype
in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10181 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10182 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10183 'GLubyte', 'GLuint', 'GLushort']:
10184 file.Write(" %s;\n" % gltype
)
10185 file.Write(" %s_ptr_t;\n" % gltype
)
10186 file.Write("};\n\n")
10188 # C level typedefs.
10189 file.Write("#inline c\n")
10190 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
10192 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10194 file.Write("\n#ifndef __gl2_h_\n")
10195 for (k
, v
) in _GL_TYPES
.iteritems():
10196 file.Write("typedef %s %s;\n" % (v
, k
))
10197 file.Write("#ifdef _WIN64\n")
10198 for (k
, v
) in _GL_TYPES_64
.iteritems():
10199 file.Write("typedef %s %s;\n" % (v
, k
))
10200 file.Write("#else\n")
10201 for (k
, v
) in _GL_TYPES_32
.iteritems():
10202 file.Write("typedef %s %s;\n" % (v
, k
))
10203 file.Write("#endif // _WIN64\n")
10204 file.Write("#endif // __gl2_h_\n\n")
10205 file.Write("#endinl\n")
10207 for interface
in self
.pepper_interfaces
:
10208 if interface
.dev
!= dev
:
10210 # Historically, we provide OpenGLES2 interfaces with struct
10211 # namespace. Not to break code which uses the interface as
10212 # "struct OpenGLES2", we put it in struct namespace.
10213 file.Write('\n[macro="%s", force_struct_namespace]\n' %
10214 interface
.GetInterfaceName())
10215 file.Write("interface %s {\n" % interface
.GetStructName())
10216 for func
in self
.original_functions
:
10217 if not func
.InPepperInterface(interface
):
10220 ret_type
= func
.MapCTypeToPepperIdlType(func
.return_type
,
10221 is_for_return_type
=True)
10222 func_prefix
= " %s %s(" % (ret_type
, func
.GetPepperName())
10223 file.Write(func_prefix
)
10224 file.Write("[in] PP_Resource context")
10225 for arg
in func
.MakeTypedPepperIdlArgStrings():
10226 file.Write(",\n" + " " * len(func_prefix
) + arg
)
10228 file.Write("};\n\n")
10233 def WritePepperGLES2Implementation(self
, filename
):
10234 """Writes the Pepper OpenGLES interface implementation."""
10236 file = CWriter(filename
)
10237 file.Write(_LICENSE
)
10238 file.Write(_DO_NOT_EDIT_WARNING
)
10240 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10241 file.Write("#include \"base/logging.h\"\n")
10242 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10243 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10244 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
10246 file.Write("namespace ppapi {\n\n")
10247 file.Write("namespace {\n\n")
10249 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10252 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10254 file.Write(" DCHECK(enter);\n")
10255 file.Write(" DCHECK(enter->succeeded());\n")
10256 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10257 "gles2_impl();\n");
10258 file.Write("}\n\n");
10260 for func
in self
.original_functions
:
10261 if not func
.InAnyPepperExtension():
10264 original_arg
= func
.MakeTypedPepperArgString("")
10265 context_arg
= "PP_Resource context_id"
10266 if len(original_arg
):
10267 arg
= context_arg
+ ", " + original_arg
10270 file.Write("%s %s(%s) {\n" %
10271 (func
.return_type
, func
.GetPepperName(), arg
))
10272 file.Write(" Enter3D enter(context_id, true);\n")
10273 file.Write(" if (enter.succeeded()) {\n")
10275 return_str
= "" if func
.return_type
== "void" else "return "
10276 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10277 (return_str
, func
.original_name
,
10278 func
.MakeOriginalArgString("")))
10280 if func
.return_type
== "void":
10283 file.Write(" else {\n")
10284 file.Write(" return %s;\n" % func
.GetErrorReturnString())
10286 file.Write("}\n\n")
10288 file.Write("} // namespace\n")
10290 for interface
in self
.pepper_interfaces
:
10291 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10292 (interface
.GetStructName(), interface
.GetName()))
10293 file.Write(" static const struct %s "
10294 "ppb_opengles2 = {\n" % interface
.GetStructName())
10296 file.Write(",\n &".join(
10297 f
.GetPepperName() for f
in self
.original_functions
10298 if f
.InPepperInterface(interface
)))
10301 file.Write(" };\n")
10302 file.Write(" return &ppb_opengles2;\n")
10305 file.Write("} // namespace ppapi\n")
10307 self
.generated_cpp_filenames
.append(file.filename
)
10309 def WriteGLES2ToPPAPIBridge(self
, filename
):
10310 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10312 file = CWriter(filename
)
10313 file.Write(_LICENSE
)
10314 file.Write(_DO_NOT_EDIT_WARNING
)
10316 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
10317 file.Write("#define GL_GLEXT_PROTOTYPES\n")
10318 file.Write("#endif\n")
10319 file.Write("#include <GLES2/gl2.h>\n")
10320 file.Write("#include <GLES2/gl2ext.h>\n")
10321 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10323 for func
in self
.original_functions
:
10324 if not func
.InAnyPepperExtension():
10327 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
10329 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
10330 (func
.return_type
, func
.GetPepperName(),
10331 func
.MakeTypedPepperArgString("")))
10332 return_str
= "" if func
.return_type
== "void" else "return "
10333 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
10334 original_arg
= func
.MakeOriginalArgString("")
10335 context_arg
= "glGetCurrentContextPPAPI()"
10336 if len(original_arg
):
10337 arg
= context_arg
+ ", " + original_arg
10340 if interface
.GetName():
10341 file.Write(" const struct %s* ext = %s;\n" %
10342 (interface
.GetStructName(), interface_str
))
10343 file.Write(" if (ext)\n")
10344 file.Write(" %sext->%s(%s);\n" %
10345 (return_str
, func
.GetPepperName(), arg
))
10347 file.Write(" %s0;\n" % return_str
)
10349 file.Write(" %s%s->%s(%s);\n" %
10350 (return_str
, interface_str
, func
.GetPepperName(), arg
))
10351 file.Write("}\n\n")
10353 self
.generated_cpp_filenames
.append(file.filename
)
10355 def WriteMojoGLCallVisitor(self
, filename
):
10356 """Provides the GL implementation for mojo"""
10357 file = CWriter(filename
)
10358 file.Write(_LICENSE
)
10359 file.Write(_DO_NOT_EDIT_WARNING
)
10361 for func
in self
.original_functions
:
10362 if not func
.IsCoreGLFunction():
10364 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10365 (func
.name
, func
.return_type
,
10366 func
.MakeTypedOriginalArgString(""),
10367 func
.MakeOriginalArgString("")))
10370 self
.generated_cpp_filenames
.append(file.filename
)
10372 def WriteMojoGLCallVisitorForExtension(self
, filename
, extension
):
10373 """Provides the GL implementation for mojo for a particular extension"""
10374 file = CWriter(filename
)
10375 file.Write(_LICENSE
)
10376 file.Write(_DO_NOT_EDIT_WARNING
)
10378 for func
in self
.original_functions
:
10379 if func
.GetInfo("extension") != extension
:
10381 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10382 (func
.name
, func
.return_type
,
10383 func
.MakeTypedOriginalArgString(""),
10384 func
.MakeOriginalArgString("")))
10387 self
.generated_cpp_filenames
.append(file.filename
)
10389 def Format(generated_files
):
10390 formatter
= "clang-format"
10391 if platform
.system() == "Windows":
10392 formatter
+= ".bat"
10393 for filename
in generated_files
:
10394 call([formatter
, "-i", "-style=chromium", filename
])
10397 """This is the main function."""
10398 parser
= OptionParser()
10401 help="base directory for resulting files, under chrome/src. default is "
10402 "empty. Use this if you want the result stored under gen.")
10404 "-v", "--verbose", action
="store_true",
10405 help="prints more output.")
10407 (options
, args
) = parser
.parse_args(args
=argv
)
10409 # Add in states and capabilites to GLState
10410 gl_state_valid
= _NAMED_TYPE_INFO
['GLState']['valid']
10411 for state_name
in sorted(_STATES
.keys()):
10412 state
= _STATES
[state_name
]
10413 if 'extension_flag' in state
:
10415 if 'enum' in state
:
10416 if not state
['enum'] in gl_state_valid
:
10417 gl_state_valid
.append(state
['enum'])
10419 for item
in state
['states']:
10420 if 'extension_flag' in item
:
10422 if not item
['enum'] in gl_state_valid
:
10423 gl_state_valid
.append(item
['enum'])
10424 for capability
in _CAPABILITY_FLAGS
:
10425 valid_value
= "GL_%s" % capability
['name'].upper()
10426 if not valid_value
in gl_state_valid
:
10427 gl_state_valid
.append(valid_value
)
10429 # This script lives under gpu/command_buffer, cd to base directory.
10430 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
10431 base_dir
= os
.getcwd()
10432 gen
= GLGenerator(options
.verbose
)
10433 gen
.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10435 # Support generating files under gen/
10436 if options
.output_dir
!= None:
10437 os
.chdir(options
.output_dir
)
10439 gen
.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10440 gen
.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10441 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10442 gen
.WritePepperGLES2Implementation(
10443 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10445 gen
.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10446 gen
.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10447 gen
.WriteFormatTest(
10448 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10449 gen
.WriteGLES2InterfaceHeader(
10450 "gpu/command_buffer/client/gles2_interface_autogen.h")
10451 gen
.WriteGLES2InterfaceStub(
10452 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10453 gen
.WriteGLES2InterfaceStubImpl(
10454 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10455 gen
.WriteGLES2ImplementationHeader(
10456 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10457 gen
.WriteGLES2Implementation(
10458 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10459 gen
.WriteGLES2ImplementationUnitTests(
10460 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10461 gen
.WriteGLES2TraceImplementationHeader(
10462 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10463 gen
.WriteGLES2TraceImplementation(
10464 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10465 gen
.WriteGLES2CLibImplementation(
10466 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10467 gen
.WriteCmdHelperHeader(
10468 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
10469 gen
.WriteServiceImplementation(
10470 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
10471 gen
.WriteServiceContextStateHeader(
10472 "gpu/command_buffer/service/context_state_autogen.h")
10473 gen
.WriteServiceContextStateImpl(
10474 "gpu/command_buffer/service/context_state_impl_autogen.h")
10475 gen
.WriteClientContextStateHeader(
10476 "gpu/command_buffer/client/client_context_state_autogen.h")
10477 gen
.WriteClientContextStateImpl(
10478 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
10479 gen
.WriteServiceUnitTests(
10480 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
10481 gen
.WriteServiceUnitTestsForExtensions(
10482 "gpu/command_buffer/service/"
10483 "gles2_cmd_decoder_unittest_extensions_autogen.h")
10484 gen
.WriteServiceUtilsHeader(
10485 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
10486 gen
.WriteServiceUtilsImplementation(
10487 "gpu/command_buffer/service/"
10488 "gles2_cmd_validation_implementation_autogen.h")
10489 gen
.WriteCommonUtilsHeader(
10490 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
10491 gen
.WriteCommonUtilsImpl(
10492 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
10493 gen
.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
10494 mojo_gles2_prefix
= ("third_party/mojo/src/mojo/public/c/gles2/"
10495 "gles2_call_visitor")
10496 gen
.WriteMojoGLCallVisitor(mojo_gles2_prefix
+ "_autogen.h")
10497 gen
.WriteMojoGLCallVisitorForExtension(
10498 mojo_gles2_prefix
+ "_chromium_texture_mailbox_autogen.h",
10499 "CHROMIUM_texture_mailbox")
10500 gen
.WriteMojoGLCallVisitorForExtension(
10501 mojo_gles2_prefix
+ "_chromium_sync_point_autogen.h",
10502 "CHROMIUM_sync_point")
10504 Format(gen
.generated_cpp_filenames
)
10507 print "%d errors" % gen
.errors
10512 if __name__
== '__main__':
10513 sys
.exit(main(sys
.argv
[1:]))