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'},
85 {'name': 'rasterizer_discard', 'es3': True},
86 {'name': 'primitive_restart_fixed_index', 'es3': True},
93 'enum': 'GL_COLOR_CLEAR_VALUE',
95 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
97 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
98 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
103 'func': 'ClearDepth',
104 'enum': 'GL_DEPTH_CLEAR_VALUE',
106 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
112 'enum': 'GL_COLOR_WRITEMASK',
115 'name': 'color_mask_red',
121 'name': 'color_mask_green',
127 'name': 'color_mask_blue',
133 'name': 'color_mask_alpha',
139 'state_flag': 'framebuffer_state_.clear_state_dirty',
143 'func': 'ClearStencil',
144 'enum': 'GL_STENCIL_CLEAR_VALUE',
146 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
151 'func': 'BlendColor',
152 'enum': 'GL_BLEND_COLOR',
154 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
155 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
156 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
157 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
162 'func': 'BlendEquationSeparate',
165 'name': 'blend_equation_rgb',
167 'enum': 'GL_BLEND_EQUATION_RGB',
168 'default': 'GL_FUNC_ADD',
171 'name': 'blend_equation_alpha',
173 'enum': 'GL_BLEND_EQUATION_ALPHA',
174 'default': 'GL_FUNC_ADD',
180 'func': 'BlendFuncSeparate',
183 'name': 'blend_source_rgb',
185 'enum': 'GL_BLEND_SRC_RGB',
189 'name': 'blend_dest_rgb',
191 'enum': 'GL_BLEND_DST_RGB',
192 'default': 'GL_ZERO',
195 'name': 'blend_source_alpha',
197 'enum': 'GL_BLEND_SRC_ALPHA',
201 'name': 'blend_dest_alpha',
203 'enum': 'GL_BLEND_DST_ALPHA',
204 'default': 'GL_ZERO',
210 'func': 'PolygonOffset',
213 'name': 'polygon_offset_factor',
215 'enum': 'GL_POLYGON_OFFSET_FACTOR',
219 'name': 'polygon_offset_units',
221 'enum': 'GL_POLYGON_OFFSET_UNITS',
229 'enum': 'GL_CULL_FACE_MODE',
234 'default': 'GL_BACK',
241 'enum': 'GL_FRONT_FACE',
242 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
247 'enum': 'GL_DEPTH_FUNC',
248 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
252 'func': 'DepthRange',
253 'enum': 'GL_DEPTH_RANGE',
255 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
256 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
261 'func': 'SampleCoverage',
264 'name': 'sample_coverage_value',
266 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
270 'name': 'sample_coverage_invert',
272 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
279 'func': 'StencilMaskSeparate',
280 'state_flag': 'framebuffer_state_.clear_state_dirty',
283 'name': 'stencil_front_writemask',
285 'enum': 'GL_STENCIL_WRITEMASK',
286 'default': '0xFFFFFFFFU',
290 'name': 'stencil_back_writemask',
292 'enum': 'GL_STENCIL_BACK_WRITEMASK',
293 'default': '0xFFFFFFFFU',
300 'func': 'StencilOpSeparate',
303 'name': 'stencil_front_fail_op',
305 'enum': 'GL_STENCIL_FAIL',
306 'default': 'GL_KEEP',
309 'name': 'stencil_front_z_fail_op',
311 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
312 'default': 'GL_KEEP',
315 'name': 'stencil_front_z_pass_op',
317 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
318 'default': 'GL_KEEP',
321 'name': 'stencil_back_fail_op',
323 'enum': 'GL_STENCIL_BACK_FAIL',
324 'default': 'GL_KEEP',
327 'name': 'stencil_back_z_fail_op',
329 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
330 'default': 'GL_KEEP',
333 'name': 'stencil_back_z_pass_op',
335 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
336 'default': 'GL_KEEP',
342 'func': 'StencilFuncSeparate',
345 'name': 'stencil_front_func',
347 'enum': 'GL_STENCIL_FUNC',
348 'default': 'GL_ALWAYS',
351 'name': 'stencil_front_ref',
353 'enum': 'GL_STENCIL_REF',
357 'name': 'stencil_front_mask',
359 'enum': 'GL_STENCIL_VALUE_MASK',
360 'default': '0xFFFFFFFFU',
363 'name': 'stencil_back_func',
365 'enum': 'GL_STENCIL_BACK_FUNC',
366 'default': 'GL_ALWAYS',
369 'name': 'stencil_back_ref',
371 'enum': 'GL_STENCIL_BACK_REF',
375 'name': 'stencil_back_mask',
377 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
378 'default': '0xFFFFFFFFU',
383 'type': 'NamedParameter',
387 'name': 'hint_generate_mipmap',
389 'enum': 'GL_GENERATE_MIPMAP_HINT',
390 'default': 'GL_DONT_CARE',
391 'gl_version_flag': '!is_desktop_core_profile'
394 'name': 'hint_fragment_shader_derivative',
396 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
397 'default': 'GL_DONT_CARE',
398 'extension_flag': 'oes_standard_derivatives'
403 'type': 'NamedParameter',
404 'func': 'PixelStorei',
407 'name': 'pack_alignment',
409 'enum': 'GL_PACK_ALIGNMENT',
413 'name': 'unpack_alignment',
415 'enum': 'GL_UNPACK_ALIGNMENT',
420 # TODO: Consider implemenenting these states
425 'enum': 'GL_LINE_WIDTH',
428 'name': 'line_width',
431 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
438 'enum': 'GL_DEPTH_WRITEMASK',
441 'name': 'depth_mask',
447 'state_flag': 'framebuffer_state_.clear_state_dirty',
452 'enum': 'GL_SCISSOR_BOX',
454 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
459 'expected': 'kViewportX',
465 'expected': 'kViewportY',
468 'name': 'scissor_width',
471 'expected': 'kViewportWidth',
474 'name': 'scissor_height',
477 'expected': 'kViewportHeight',
484 'enum': 'GL_VIEWPORT',
486 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
488 'name': 'viewport_x',
491 'expected': 'kViewportX',
494 'name': 'viewport_y',
497 'expected': 'kViewportY',
500 'name': 'viewport_width',
503 'expected': 'kViewportWidth',
506 'name': 'viewport_height',
509 'expected': 'kViewportHeight',
513 'MatrixValuesCHROMIUM': {
514 'type': 'NamedParameter',
515 'func': 'MatrixLoadfEXT',
517 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
518 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
519 'name': 'modelview_matrix',
522 '1.0f', '0.0f','0.0f','0.0f',
523 '0.0f', '1.0f','0.0f','0.0f',
524 '0.0f', '0.0f','1.0f','0.0f',
525 '0.0f', '0.0f','0.0f','1.0f',
527 'extension_flag': 'chromium_path_rendering',
529 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
530 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
531 'name': 'projection_matrix',
534 '1.0f', '0.0f','0.0f','0.0f',
535 '0.0f', '1.0f','0.0f','0.0f',
536 '0.0f', '0.0f','1.0f','0.0f',
537 '0.0f', '0.0f','0.0f','1.0f',
539 'extension_flag': 'chromium_path_rendering',
545 # Named type info object represents a named type that is used in OpenGL call
546 # arguments. Each named type defines a set of valid OpenGL call arguments. The
547 # named types are used in 'cmd_buffer_functions.txt'.
548 # type: The actual GL type of the named type.
549 # valid: The list of values that are valid for both the client and the service.
550 # valid_es3: The list of values that are valid in OpenGL ES 3, but not ES 2.
551 # invalid: Examples of invalid values for the type. At least these values
552 # should be tested to be invalid.
553 # deprecated_es3: The list of values that are valid in OpenGL ES 2, but
554 # deprecated in ES 3.
555 # is_complete: The list of valid values of type are final and will not be
556 # modified during runtime.
565 'GL_LINEAR_MIPMAP_LINEAR',
568 'FrameBufferTarget': {
574 'GL_DRAW_FRAMEBUFFER' ,
575 'GL_READ_FRAMEBUFFER' ,
581 'InvalidateFrameBufferTarget': {
587 'GL_DRAW_FRAMEBUFFER' ,
588 'GL_READ_FRAMEBUFFER' ,
591 'RenderBufferTarget': {
604 'GL_ELEMENT_ARRAY_BUFFER',
607 'GL_COPY_READ_BUFFER',
608 'GL_COPY_WRITE_BUFFER',
609 'GL_PIXEL_PACK_BUFFER',
610 'GL_PIXEL_UNPACK_BUFFER',
611 'GL_TRANSFORM_FEEDBACK_BUFFER',
618 'IndexedBufferTarget': {
621 'GL_TRANSFORM_FEEDBACK_BUFFER',
633 'GL_MAP_INVALIDATE_RANGE_BIT',
634 'GL_MAP_INVALIDATE_BUFFER_BIT',
635 'GL_MAP_FLUSH_EXPLICIT_BIT',
636 'GL_MAP_UNSYNCHRONIZED_BIT',
639 'GL_SYNC_FLUSH_COMMANDS_BIT',
699 'CompressedTextureFormat': {
704 'GL_COMPRESSED_R11_EAC',
705 'GL_COMPRESSED_SIGNED_R11_EAC',
706 'GL_COMPRESSED_RG11_EAC',
707 'GL_COMPRESSED_SIGNED_RG11_EAC',
708 'GL_COMPRESSED_RGB8_ETC2',
709 'GL_COMPRESSED_SRGB8_ETC2',
710 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
711 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
712 'GL_COMPRESSED_RGBA8_ETC2_EAC',
713 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
719 # NOTE: State an Capability entries added later.
721 'GL_ALIASED_LINE_WIDTH_RANGE',
722 'GL_ALIASED_POINT_SIZE_RANGE',
724 'GL_ARRAY_BUFFER_BINDING',
726 'GL_COMPRESSED_TEXTURE_FORMATS',
727 'GL_CURRENT_PROGRAM',
730 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
731 'GL_FRAMEBUFFER_BINDING',
732 'GL_GENERATE_MIPMAP_HINT',
734 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
735 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
736 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
737 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
738 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
739 'GL_MAX_RENDERBUFFER_SIZE',
740 'GL_MAX_TEXTURE_IMAGE_UNITS',
741 'GL_MAX_TEXTURE_SIZE',
742 'GL_MAX_VARYING_VECTORS',
743 'GL_MAX_VERTEX_ATTRIBS',
744 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
745 'GL_MAX_VERTEX_UNIFORM_VECTORS',
746 'GL_MAX_VIEWPORT_DIMS',
747 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
748 'GL_NUM_SHADER_BINARY_FORMATS',
751 'GL_RENDERBUFFER_BINDING',
753 'GL_SAMPLE_COVERAGE_INVERT',
754 'GL_SAMPLE_COVERAGE_VALUE',
757 'GL_SHADER_BINARY_FORMATS',
758 'GL_SHADER_COMPILER',
761 'GL_TEXTURE_BINDING_2D',
762 'GL_TEXTURE_BINDING_CUBE_MAP',
763 'GL_UNPACK_ALIGNMENT',
764 'GL_UNPACK_FLIP_Y_CHROMIUM',
765 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
766 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
767 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
768 # we can add this because we emulate it if the driver does not support it.
769 'GL_VERTEX_ARRAY_BINDING_OES',
773 'GL_COPY_READ_BUFFER_BINDING',
774 'GL_COPY_WRITE_BUFFER_BINDING',
791 'GL_DRAW_FRAMEBUFFER_BINDING',
792 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
794 'GL_MAX_3D_TEXTURE_SIZE',
795 'GL_MAX_ARRAY_TEXTURE_LAYERS',
796 'GL_MAX_COLOR_ATTACHMENTS',
797 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
798 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
799 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
800 'GL_MAX_DRAW_BUFFERS',
801 'GL_MAX_ELEMENT_INDEX',
802 'GL_MAX_ELEMENTS_INDICES',
803 'GL_MAX_ELEMENTS_VERTICES',
804 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
805 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
806 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
807 'GL_MAX_PROGRAM_TEXEL_OFFSET',
809 'GL_MAX_SERVER_WAIT_TIMEOUT',
810 'GL_MAX_TEXTURE_LOD_BIAS',
811 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
812 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
813 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
814 'GL_MAX_UNIFORM_BLOCK_SIZE',
815 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
816 'GL_MAX_VARYING_COMPONENTS',
817 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
818 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
819 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
820 'GL_MIN_PROGRAM_TEXEL_OFFSET',
823 'GL_NUM_PROGRAM_BINARY_FORMATS',
824 'GL_PACK_ROW_LENGTH',
825 'GL_PACK_SKIP_PIXELS',
827 'GL_PIXEL_PACK_BUFFER_BINDING',
828 'GL_PIXEL_UNPACK_BUFFER_BINDING',
829 'GL_PROGRAM_BINARY_FORMATS',
831 'GL_READ_FRAMEBUFFER_BINDING',
832 'GL_SAMPLER_BINDING',
833 'GL_TEXTURE_BINDING_2D_ARRAY',
834 'GL_TEXTURE_BINDING_3D',
835 'GL_TRANSFORM_FEEDBACK_BINDING',
836 'GL_TRANSFORM_FEEDBACK_ACTIVE',
837 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
838 'GL_TRANSFORM_FEEDBACK_PAUSED',
839 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
840 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
841 'GL_UNIFORM_BUFFER_BINDING',
842 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
843 'GL_UNIFORM_BUFFER_SIZE',
844 'GL_UNIFORM_BUFFER_START',
845 'GL_UNPACK_IMAGE_HEIGHT',
846 'GL_UNPACK_ROW_LENGTH',
847 'GL_UNPACK_SKIP_IMAGES',
848 'GL_UNPACK_SKIP_PIXELS',
849 'GL_UNPACK_SKIP_ROWS',
850 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
851 # 'GL_VERTEX_ARRAY_BINDING',
860 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
861 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
862 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
863 'GL_UNIFORM_BUFFER_BINDING',
864 'GL_UNIFORM_BUFFER_SIZE',
865 'GL_UNIFORM_BUFFER_START',
871 'GetTexParamTarget': {
875 'GL_TEXTURE_CUBE_MAP',
878 'GL_TEXTURE_2D_ARRAY',
882 'GL_PROXY_TEXTURE_CUBE_MAP',
889 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
890 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
891 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
892 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
893 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
894 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
897 'GL_PROXY_TEXTURE_CUBE_MAP',
904 'GL_TEXTURE_2D_ARRAY',
910 'TextureBindTarget': {
914 'GL_TEXTURE_CUBE_MAP',
918 'GL_TEXTURE_2D_ARRAY',
925 'TransformFeedbackBindTarget': {
928 'GL_TRANSFORM_FEEDBACK',
934 'TransformFeedbackPrimitiveMode': {
949 'GL_FRAGMENT_SHADER',
952 'GL_GEOMETRY_SHADER',
988 'GL_FUNC_REVERSE_SUBTRACT',
1004 'GL_ONE_MINUS_SRC_COLOR',
1006 'GL_ONE_MINUS_DST_COLOR',
1008 'GL_ONE_MINUS_SRC_ALPHA',
1010 'GL_ONE_MINUS_DST_ALPHA',
1011 'GL_CONSTANT_COLOR',
1012 'GL_ONE_MINUS_CONSTANT_COLOR',
1013 'GL_CONSTANT_ALPHA',
1014 'GL_ONE_MINUS_CONSTANT_ALPHA',
1015 'GL_SRC_ALPHA_SATURATE',
1024 'GL_ONE_MINUS_SRC_COLOR',
1026 'GL_ONE_MINUS_DST_COLOR',
1028 'GL_ONE_MINUS_SRC_ALPHA',
1030 'GL_ONE_MINUS_DST_ALPHA',
1031 'GL_CONSTANT_COLOR',
1032 'GL_ONE_MINUS_CONSTANT_COLOR',
1033 'GL_CONSTANT_ALPHA',
1034 'GL_ONE_MINUS_CONSTANT_ALPHA',
1039 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1040 if 'es3' not in cap
or cap
['es3'] != True],
1041 'valid_es3': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1042 if 'es3' in cap
and cap
['es3'] == True],
1055 'GL_TRIANGLE_STRIP',
1068 'GL_UNSIGNED_SHORT',
1077 'GetMaxIndexType': {
1081 'GL_UNSIGNED_SHORT',
1091 'GL_COLOR_ATTACHMENT0',
1092 'GL_DEPTH_ATTACHMENT',
1093 'GL_STENCIL_ATTACHMENT',
1096 'GL_DEPTH_STENCIL_ATTACHMENT',
1099 'BackbufferAttachment': {
1107 'BufferParameter': {
1114 'GL_BUFFER_ACCESS_FLAGS',
1116 'GL_BUFFER_MAP_LENGTH',
1117 'GL_BUFFER_MAP_OFFSET',
1120 'GL_PIXEL_PACK_BUFFER',
1126 'GL_INTERLEAVED_ATTRIBS',
1127 'GL_SEPARATE_ATTRIBS',
1130 'GL_PIXEL_PACK_BUFFER',
1133 'FrameBufferParameter': {
1136 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1137 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1138 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1139 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1142 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1143 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1144 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1145 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1146 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1147 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1148 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1149 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1150 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1156 'GL_PATH_PROJECTION_CHROMIUM',
1157 'GL_PATH_MODELVIEW_CHROMIUM',
1160 'ProgramParameter': {
1165 'GL_VALIDATE_STATUS',
1166 'GL_INFO_LOG_LENGTH',
1167 'GL_ATTACHED_SHADERS',
1168 'GL_ACTIVE_ATTRIBUTES',
1169 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1170 'GL_ACTIVE_UNIFORMS',
1171 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1174 'GL_ACTIVE_UNIFORM_BLOCKS',
1175 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1176 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1177 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1178 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1181 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1184 'QueryObjectParameter': {
1187 'GL_QUERY_RESULT_EXT',
1188 'GL_QUERY_RESULT_AVAILABLE_EXT',
1194 'GL_CURRENT_QUERY_EXT',
1200 'GL_ANY_SAMPLES_PASSED_EXT',
1201 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1202 'GL_COMMANDS_ISSUED_CHROMIUM',
1203 'GL_LATENCY_QUERY_CHROMIUM',
1204 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1205 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1206 'GL_COMMANDS_COMPLETED_CHROMIUM',
1209 'RenderBufferParameter': {
1212 'GL_RENDERBUFFER_RED_SIZE',
1213 'GL_RENDERBUFFER_GREEN_SIZE',
1214 'GL_RENDERBUFFER_BLUE_SIZE',
1215 'GL_RENDERBUFFER_ALPHA_SIZE',
1216 'GL_RENDERBUFFER_DEPTH_SIZE',
1217 'GL_RENDERBUFFER_STENCIL_SIZE',
1218 'GL_RENDERBUFFER_WIDTH',
1219 'GL_RENDERBUFFER_HEIGHT',
1220 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1223 'GL_RENDERBUFFER_SAMPLES',
1226 'InternalFormatParameter': {
1229 'GL_NUM_SAMPLE_COUNTS',
1233 'SamplerParameter': {
1236 'GL_TEXTURE_MAG_FILTER',
1237 'GL_TEXTURE_MIN_FILTER',
1238 'GL_TEXTURE_MIN_LOD',
1239 'GL_TEXTURE_MAX_LOD',
1240 'GL_TEXTURE_WRAP_S',
1241 'GL_TEXTURE_WRAP_T',
1242 'GL_TEXTURE_WRAP_R',
1243 'GL_TEXTURE_COMPARE_MODE',
1244 'GL_TEXTURE_COMPARE_FUNC',
1247 'GL_GENERATE_MIPMAP',
1250 'ShaderParameter': {
1255 'GL_COMPILE_STATUS',
1256 'GL_INFO_LOG_LENGTH',
1257 'GL_SHADER_SOURCE_LENGTH',
1258 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1261 'ShaderPrecision': {
1278 'GL_SHADING_LANGUAGE_VERSION',
1282 'TextureParameter': {
1285 'GL_TEXTURE_MAG_FILTER',
1286 'GL_TEXTURE_MIN_FILTER',
1287 'GL_TEXTURE_POOL_CHROMIUM',
1288 'GL_TEXTURE_WRAP_S',
1289 'GL_TEXTURE_WRAP_T',
1292 'GL_TEXTURE_BASE_LEVEL',
1293 'GL_TEXTURE_COMPARE_FUNC',
1294 'GL_TEXTURE_COMPARE_MODE',
1295 'GL_TEXTURE_IMMUTABLE_FORMAT',
1296 'GL_TEXTURE_IMMUTABLE_LEVELS',
1297 'GL_TEXTURE_MAX_LEVEL',
1298 'GL_TEXTURE_MAX_LOD',
1299 'GL_TEXTURE_MIN_LOD',
1300 'GL_TEXTURE_WRAP_R',
1303 'GL_GENERATE_MIPMAP',
1309 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1310 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1313 'TextureWrapMode': {
1317 'GL_MIRRORED_REPEAT',
1321 'TextureMinFilterMode': {
1326 'GL_NEAREST_MIPMAP_NEAREST',
1327 'GL_LINEAR_MIPMAP_NEAREST',
1328 'GL_NEAREST_MIPMAP_LINEAR',
1329 'GL_LINEAR_MIPMAP_LINEAR',
1332 'TextureMagFilterMode': {
1339 'TextureCompareFunc': {
1352 'TextureCompareMode': {
1356 'GL_COMPARE_REF_TO_TEXTURE',
1363 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1366 'VertexAttribute': {
1369 # some enum that the decoder actually passes through to GL needs
1370 # to be the first listed here since it's used in unit tests.
1371 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1372 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1373 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1374 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1375 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1376 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1377 'GL_CURRENT_VERTEX_ATTRIB',
1380 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1381 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1387 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1393 'GL_GENERATE_MIPMAP_HINT',
1396 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1399 'GL_PERSPECTIVE_CORRECTION_HINT',
1413 'GL_PACK_ALIGNMENT',
1414 'GL_UNPACK_ALIGNMENT',
1415 'GL_UNPACK_FLIP_Y_CHROMIUM',
1416 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
1417 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
1420 'GL_PACK_ROW_LENGTH',
1421 'GL_PACK_SKIP_PIXELS',
1422 'GL_PACK_SKIP_ROWS',
1423 'GL_UNPACK_ROW_LENGTH',
1424 'GL_UNPACK_IMAGE_HEIGHT',
1425 'GL_UNPACK_SKIP_PIXELS',
1426 'GL_UNPACK_SKIP_ROWS',
1427 'GL_UNPACK_SKIP_IMAGES',
1430 'GL_PACK_SWAP_BYTES',
1431 'GL_UNPACK_SWAP_BYTES',
1434 'PixelStoreAlignment': {
1447 'ReadPixelFormat': {
1466 'GL_UNSIGNED_SHORT_5_6_5',
1467 'GL_UNSIGNED_SHORT_4_4_4_4',
1468 'GL_UNSIGNED_SHORT_5_5_5_1',
1472 'GL_UNSIGNED_SHORT',
1478 'GL_UNSIGNED_INT_2_10_10_10_REV',
1479 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1480 'GL_UNSIGNED_INT_5_9_9_9_REV',
1481 'GL_UNSIGNED_INT_24_8',
1482 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1485 'GL_UNSIGNED_BYTE_3_3_2',
1492 'GL_UNSIGNED_SHORT_5_6_5',
1493 'GL_UNSIGNED_SHORT_4_4_4_4',
1494 'GL_UNSIGNED_SHORT_5_5_5_1',
1505 'GL_UNSIGNED_SHORT_5_6_5',
1506 'GL_UNSIGNED_SHORT_4_4_4_4',
1507 'GL_UNSIGNED_SHORT_5_5_5_1',
1510 'RenderBufferFormat': {
1516 'GL_DEPTH_COMPONENT16',
1517 'GL_STENCIL_INDEX8',
1545 'GL_DEPTH_COMPONENT24',
1546 'GL_DEPTH_COMPONENT32F',
1547 'GL_DEPTH24_STENCIL8',
1548 'GL_DEPTH32F_STENCIL8',
1551 'ShaderBinaryFormat': {
1574 'GL_LUMINANCE_ALPHA',
1585 'GL_DEPTH_COMPONENT',
1593 'TextureInternalFormat': {
1598 'GL_LUMINANCE_ALPHA',
1627 'GL_R11F_G11F_B10F',
1652 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1653 # We will reject them dynamically in GPU command buffer.
1654 'GL_DEPTH_COMPONENT16',
1655 'GL_DEPTH_COMPONENT24',
1656 'GL_DEPTH_COMPONENT32F',
1657 'GL_DEPTH24_STENCIL8',
1658 'GL_DEPTH32F_STENCIL8',
1665 'TextureInternalFormatStorage': {
1672 'GL_LUMINANCE8_EXT',
1673 'GL_LUMINANCE8_ALPHA8_EXT',
1700 'GL_R11F_G11F_B10F',
1722 'GL_DEPTH_COMPONENT16',
1723 'GL_DEPTH_COMPONENT24',
1724 'GL_DEPTH_COMPONENT32F',
1725 'GL_DEPTH24_STENCIL8',
1726 'GL_DEPTH32F_STENCIL8',
1727 'GL_COMPRESSED_R11_EAC',
1728 'GL_COMPRESSED_SIGNED_R11_EAC',
1729 'GL_COMPRESSED_RG11_EAC',
1730 'GL_COMPRESSED_SIGNED_RG11_EAC',
1731 'GL_COMPRESSED_RGB8_ETC2',
1732 'GL_COMPRESSED_SRGB8_ETC2',
1733 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1734 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1735 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1736 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1740 'GL_LUMINANCE8_EXT',
1741 'GL_LUMINANCE8_ALPHA8_EXT',
1743 'GL_LUMINANCE16F_EXT',
1744 'GL_LUMINANCE_ALPHA16F_EXT',
1746 'GL_LUMINANCE32F_EXT',
1747 'GL_LUMINANCE_ALPHA32F_EXT',
1750 'ImageInternalFormat': {
1754 'GL_RGB_YUV_420_CHROMIUM',
1762 'GL_SCANOUT_CHROMIUM'
1765 'ValueBufferTarget': {
1768 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1771 'SubscriptionTarget': {
1774 'GL_MOUSE_POSITION_CHROMIUM',
1777 'UniformParameter': {
1782 'GL_UNIFORM_NAME_LENGTH',
1783 'GL_UNIFORM_BLOCK_INDEX',
1784 'GL_UNIFORM_OFFSET',
1785 'GL_UNIFORM_ARRAY_STRIDE',
1786 'GL_UNIFORM_MATRIX_STRIDE',
1787 'GL_UNIFORM_IS_ROW_MAJOR',
1790 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1793 'UniformBlockParameter': {
1796 'GL_UNIFORM_BLOCK_BINDING',
1797 'GL_UNIFORM_BLOCK_DATA_SIZE',
1798 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1799 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1800 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1801 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1802 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1808 'VertexAttribType': {
1814 'GL_UNSIGNED_SHORT',
1815 # 'GL_FIXED', // This is not available on Desktop GL.
1822 'GL_INT_2_10_10_10_REV',
1823 'GL_UNSIGNED_INT_2_10_10_10_REV',
1829 'VertexAttribIType': {
1835 'GL_UNSIGNED_SHORT',
1846 'is_complete': True,
1854 'VertexAttribSize': {
1869 'is_complete': True,
1878 'type': 'GLboolean',
1879 'is_complete': True,
1890 'GL_GUILTY_CONTEXT_RESET_ARB',
1891 'GL_INNOCENT_CONTEXT_RESET_ARB',
1892 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1897 'is_complete': True,
1899 'GL_SYNC_GPU_COMMANDS_COMPLETE',
1906 'type': 'GLbitfield',
1907 'is_complete': True,
1916 'type': 'GLbitfield',
1918 'GL_SYNC_FLUSH_COMMANDS_BIT',
1928 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
1930 'GL_SYNC_CONDITION',
1939 # This table specifies the different pepper interfaces that are supported for
1940 # GL commands. 'dev' is true if it's a dev interface.
1941 _PEPPER_INTERFACES
= [
1942 {'name': '', 'dev': False},
1943 {'name': 'InstancedArrays', 'dev': False},
1944 {'name': 'FramebufferBlit', 'dev': False},
1945 {'name': 'FramebufferMultisample', 'dev': False},
1946 {'name': 'ChromiumEnableFeature', 'dev': False},
1947 {'name': 'ChromiumMapSub', 'dev': False},
1948 {'name': 'Query', 'dev': False},
1949 {'name': 'VertexArrayObject', 'dev': False},
1950 {'name': 'DrawBuffers', 'dev': True},
1953 # A function info object specifies the type and other special data for the
1954 # command that will be generated. A base function info object is generated by
1955 # parsing the "cmd_buffer_functions.txt", one for each function in the
1956 # file. These function info objects can be augmented and their values can be
1957 # overridden by adding an object to the table below.
1959 # Must match function names specified in "cmd_buffer_functions.txt".
1961 # cmd_comment: A comment added to the cmd format.
1962 # type: defines which handler will be used to generate code.
1963 # decoder_func: defines which function to call in the decoder to execute the
1964 # corresponding GL command. If not specified the GL command will
1965 # be called directly.
1966 # gl_test_func: GL function that is expected to be called when testing.
1967 # cmd_args: The arguments to use for the command. This overrides generating
1968 # them based on the GL function arguments.
1969 # gen_cmd: Whether or not this function geneates a command. Default = True.
1970 # data_transfer_methods: Array of methods that are used for transfering the
1971 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1972 # The default is 'immediate' if the command has one pointer
1973 # argument, otherwise 'shm'. One command is generated for each
1974 # transfer method. Affects only commands which are not of type
1975 # 'HandWritten', 'GETn' or 'GLcharN'.
1976 # Note: the command arguments that affect this are the final args,
1977 # taking cmd_args override into consideration.
1978 # impl_func: Whether or not to generate the GLES2Implementation part of this
1980 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1982 # needs_size: If True a data_size field is added to the command.
1983 # count: The number of units per element. For PUTn or PUT types.
1984 # use_count_func: If True the actual data count needs to be computed; the count
1985 # argument specifies the maximum count.
1986 # unit_test: If False no service side unit test will be generated.
1987 # client_test: If False no client side unit test will be generated.
1988 # expectation: If False the unit test will have no expected calls.
1989 # gen_func: Name of function that generates GL resource for corresponding
1991 # states: array of states that get set by this function corresponding to
1992 # the given arguments
1993 # state_flag: name of flag that is set to true when function is called.
1994 # no_gl: no GL function is called.
1995 # valid_args: A dictionary of argument indices to args to use in unit tests
1996 # when they can not be automatically determined.
1997 # pepper_interface: The pepper interface that is used for this extension
1998 # pepper_name: The name of the function as exposed to pepper.
1999 # pepper_args: A string representing the argument list (what would appear in
2000 # C/C++ between the parentheses for the function declaration)
2001 # that the Pepper API expects for this function. Use this only if
2002 # the stable Pepper API differs from the GLES2 argument list.
2003 # invalid_test: False if no invalid test needed.
2004 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2005 # first_element_only: For PUT types, True if only the first element of an
2006 # array is used and we end up calling the single value
2007 # corresponding function. eg. TexParameteriv -> TexParameteri
2008 # extension: Function is an extension to GL and should not be exposed to
2009 # pepper unless pepper_interface is defined.
2010 # extension_flag: Function is an extension and should be enabled only when
2011 # the corresponding feature info flag is enabled. Implies
2012 # 'extension': True.
2013 # not_shared: For GENn types, True if objects can't be shared between contexts
2014 # unsafe: True = no validation is implemented on the service side and the
2015 # command is only available with --enable-unsafe-es3-apis.
2016 # id_mapping: A list of resource type names whose client side IDs need to be
2017 # mapped to service side IDs. This is only used for unsafe APIs.
2021 'decoder_func': 'DoActiveTexture',
2024 'client_test': False,
2026 'AttachShader': {'decoder_func': 'DoAttachShader'},
2027 'BindAttribLocation': {
2029 'data_transfer_methods': ['bucket'],
2034 'decoder_func': 'DoBindBuffer',
2035 'gen_func': 'GenBuffersARB',
2039 'id_mapping': [ 'Buffer' ],
2040 'gen_func': 'GenBuffersARB',
2043 'BindBufferRange': {
2045 'id_mapping': [ 'Buffer' ],
2046 'gen_func': 'GenBuffersARB',
2053 'BindFramebuffer': {
2055 'decoder_func': 'DoBindFramebuffer',
2056 'gl_test_func': 'glBindFramebufferEXT',
2057 'gen_func': 'GenFramebuffersEXT',
2060 'BindRenderbuffer': {
2062 'decoder_func': 'DoBindRenderbuffer',
2063 'gl_test_func': 'glBindRenderbufferEXT',
2064 'gen_func': 'GenRenderbuffersEXT',
2068 'id_mapping': [ 'Sampler' ],
2073 'decoder_func': 'DoBindTexture',
2074 'gen_func': 'GenTextures',
2075 # TODO(gman): remove this once client side caching works.
2076 'client_test': False,
2079 'BindTransformFeedback': {
2081 'id_mapping': [ 'TransformFeedback' ],
2084 'BlitFramebufferCHROMIUM': {
2085 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2087 'extension_flag': 'chromium_framebuffer_multisample',
2088 'pepper_interface': 'FramebufferBlit',
2089 'pepper_name': 'BlitFramebufferEXT',
2090 'defer_reads': True,
2091 'defer_draws': True,
2096 'data_transfer_methods': ['shm'],
2097 'client_test': False,
2102 'client_test': False,
2103 'decoder_func': 'DoBufferSubData',
2104 'data_transfer_methods': ['shm'],
2107 'CheckFramebufferStatus': {
2109 'decoder_func': 'DoCheckFramebufferStatus',
2110 'gl_test_func': 'glCheckFramebufferStatusEXT',
2111 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2112 'result': ['GLenum'],
2115 'decoder_func': 'DoClear',
2116 'defer_draws': True,
2121 'use_count_func': True,
2134 'use_count_func': True,
2145 'state': 'ClearColor',
2149 'state': 'ClearDepthf',
2150 'decoder_func': 'glClearDepth',
2151 'gl_test_func': 'glClearDepth',
2158 'data_transfer_methods': ['shm'],
2159 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2160 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2162 'result': ['GLenum'],
2167 'state': 'ColorMask',
2169 'expectation': False,
2171 'ConsumeTextureCHROMIUM': {
2172 'decoder_func': 'DoConsumeTextureCHROMIUM',
2175 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2177 'client_test': False,
2178 'extension': "CHROMIUM_texture_mailbox",
2182 'CopyBufferSubData': {
2185 'CreateAndConsumeTextureCHROMIUM': {
2186 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2188 'type': 'HandWritten',
2189 'data_transfer_methods': ['immediate'],
2191 'client_test': False,
2192 'extension': "CHROMIUM_texture_mailbox",
2196 'GenValuebuffersCHROMIUM': {
2198 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2199 'resource_type': 'Valuebuffer',
2200 'resource_types': 'Valuebuffers',
2205 'DeleteValuebuffersCHROMIUM': {
2207 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2208 'resource_type': 'Valuebuffer',
2209 'resource_types': 'Valuebuffers',
2214 'IsValuebufferCHROMIUM': {
2216 'decoder_func': 'DoIsValuebufferCHROMIUM',
2217 'expectation': False,
2221 'BindValuebufferCHROMIUM': {
2223 'decoder_func': 'DoBindValueBufferCHROMIUM',
2224 'gen_func': 'GenValueBuffersCHROMIUM',
2229 'SubscribeValueCHROMIUM': {
2230 'decoder_func': 'DoSubscribeValueCHROMIUM',
2235 'PopulateSubscribedValuesCHROMIUM': {
2236 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2241 'UniformValuebufferCHROMIUM': {
2242 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2249 'state': 'ClearStencil',
2251 'EnableFeatureCHROMIUM': {
2253 'data_transfer_methods': ['shm'],
2254 'decoder_func': 'DoEnableFeatureCHROMIUM',
2255 'expectation': False,
2256 'cmd_args': 'GLuint bucket_id, GLint* result',
2257 'result': ['GLint'],
2260 'pepper_interface': 'ChromiumEnableFeature',
2262 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2263 'CompressedTexImage2D': {
2265 'data_transfer_methods': ['bucket', 'shm'],
2268 'CompressedTexSubImage2D': {
2270 'data_transfer_methods': ['bucket', 'shm'],
2271 'decoder_func': 'DoCompressedTexSubImage2D',
2275 'decoder_func': 'DoCopyTexImage2D',
2277 'defer_reads': True,
2280 'CopyTexSubImage2D': {
2281 'decoder_func': 'DoCopyTexSubImage2D',
2282 'defer_reads': True,
2285 'CompressedTexImage3D': {
2287 'data_transfer_methods': ['bucket', 'shm'],
2291 'CompressedTexSubImage3D': {
2293 'data_transfer_methods': ['bucket', 'shm'],
2294 'decoder_func': 'DoCompressedTexSubImage3D',
2298 'CopyTexSubImage3D': {
2299 'defer_reads': True,
2303 'CreateImageCHROMIUM': {
2306 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2307 'GLenum internalformat',
2308 'result': ['GLuint'],
2309 'client_test': False,
2311 'expectation': False,
2312 'extension': "CHROMIUM_image",
2316 'DestroyImageCHROMIUM': {
2318 'client_test': False,
2320 'extension': "CHROMIUM_image",
2324 'CreateGpuMemoryBufferImageCHROMIUM': {
2327 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2328 'result': ['GLuint'],
2329 'client_test': False,
2331 'expectation': False,
2332 'extension': "CHROMIUM_image",
2338 'client_test': False,
2342 'client_test': False,
2346 'state': 'BlendColor',
2349 'type': 'StateSetRGBAlpha',
2350 'state': 'BlendEquation',
2352 '0': 'GL_FUNC_SUBTRACT'
2355 'BlendEquationSeparate': {
2357 'state': 'BlendEquation',
2359 '0': 'GL_FUNC_SUBTRACT'
2363 'type': 'StateSetRGBAlpha',
2364 'state': 'BlendFunc',
2366 'BlendFuncSeparate': {
2368 'state': 'BlendFunc',
2370 'BlendBarrierKHR': {
2371 'gl_test_func': 'glBlendBarrierKHR',
2373 'extension_flag': 'blend_equation_advanced',
2374 'client_test': False,
2376 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2378 'type': 'StateSetFrontBack',
2379 'state': 'StencilFunc',
2381 'StencilFuncSeparate': {
2382 'type': 'StateSetFrontBackSeparate',
2383 'state': 'StencilFunc',
2386 'type': 'StateSetFrontBack',
2387 'state': 'StencilOp',
2392 'StencilOpSeparate': {
2393 'type': 'StateSetFrontBackSeparate',
2394 'state': 'StencilOp',
2400 'type': 'StateSetNamedParameter',
2403 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2404 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2405 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2408 'state': 'LineWidth',
2415 'state': 'PolygonOffset',
2419 'gl_test_func': 'glDeleteBuffersARB',
2420 'resource_type': 'Buffer',
2421 'resource_types': 'Buffers',
2423 'DeleteFramebuffers': {
2425 'gl_test_func': 'glDeleteFramebuffersEXT',
2426 'resource_type': 'Framebuffer',
2427 'resource_types': 'Framebuffers',
2430 'DeleteProgram': { 'type': 'Delete' },
2431 'DeleteRenderbuffers': {
2433 'gl_test_func': 'glDeleteRenderbuffersEXT',
2434 'resource_type': 'Renderbuffer',
2435 'resource_types': 'Renderbuffers',
2440 'resource_type': 'Sampler',
2441 'resource_types': 'Samplers',
2444 'DeleteShader': { 'type': 'Delete' },
2447 'cmd_args': 'GLuint sync',
2448 'resource_type': 'Sync',
2453 'resource_type': 'Texture',
2454 'resource_types': 'Textures',
2456 'DeleteTransformFeedbacks': {
2458 'resource_type': 'TransformFeedback',
2459 'resource_types': 'TransformFeedbacks',
2463 'decoder_func': 'DoDepthRangef',
2464 'gl_test_func': 'glDepthRange',
2468 'state': 'DepthMask',
2470 'expectation': False,
2472 'DetachShader': {'decoder_func': 'DoDetachShader'},
2474 'decoder_func': 'DoDisable',
2476 'client_test': False,
2478 'DisableVertexAttribArray': {
2479 'decoder_func': 'DoDisableVertexAttribArray',
2484 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2485 'defer_draws': True,
2490 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2491 'GLenumIndexType type, GLuint index_offset',
2492 'client_test': False,
2493 'defer_draws': True,
2496 'DrawRangeElements': {
2502 'decoder_func': 'DoEnable',
2504 'client_test': False,
2506 'EnableVertexAttribArray': {
2507 'decoder_func': 'DoEnableVertexAttribArray',
2512 'client_test': False,
2518 'client_test': False,
2519 'decoder_func': 'DoFinish',
2520 'defer_reads': True,
2525 'decoder_func': 'DoFlush',
2528 'FramebufferRenderbuffer': {
2529 'decoder_func': 'DoFramebufferRenderbuffer',
2530 'gl_test_func': 'glFramebufferRenderbufferEXT',
2533 'FramebufferTexture2D': {
2534 'decoder_func': 'DoFramebufferTexture2D',
2535 'gl_test_func': 'glFramebufferTexture2DEXT',
2538 'FramebufferTexture2DMultisampleEXT': {
2539 'decoder_func': 'DoFramebufferTexture2DMultisample',
2540 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2541 'expectation': False,
2543 'extension_flag': 'multisampled_render_to_texture',
2546 'FramebufferTextureLayer': {
2547 'decoder_func': 'DoFramebufferTextureLayer',
2552 'decoder_func': 'DoGenerateMipmap',
2553 'gl_test_func': 'glGenerateMipmapEXT',
2558 'gl_test_func': 'glGenBuffersARB',
2559 'resource_type': 'Buffer',
2560 'resource_types': 'Buffers',
2562 'GenMailboxCHROMIUM': {
2563 'type': 'HandWritten',
2565 'extension': "CHROMIUM_texture_mailbox",
2568 'GenFramebuffers': {
2570 'gl_test_func': 'glGenFramebuffersEXT',
2571 'resource_type': 'Framebuffer',
2572 'resource_types': 'Framebuffers',
2574 'GenRenderbuffers': {
2575 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2576 'resource_type': 'Renderbuffer',
2577 'resource_types': 'Renderbuffers',
2581 'gl_test_func': 'glGenSamplers',
2582 'resource_type': 'Sampler',
2583 'resource_types': 'Samplers',
2588 'gl_test_func': 'glGenTextures',
2589 'resource_type': 'Texture',
2590 'resource_types': 'Textures',
2592 'GenTransformFeedbacks': {
2594 'gl_test_func': 'glGenTransformFeedbacks',
2595 'resource_type': 'TransformFeedback',
2596 'resource_types': 'TransformFeedbacks',
2599 'GetActiveAttrib': {
2601 'data_transfer_methods': ['shm'],
2603 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2611 'GetActiveUniform': {
2613 'data_transfer_methods': ['shm'],
2615 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2623 'GetActiveUniformBlockiv': {
2625 'data_transfer_methods': ['shm'],
2626 'result': ['SizedResult<GLint>'],
2629 'GetActiveUniformBlockName': {
2631 'data_transfer_methods': ['shm'],
2633 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2635 'result': ['int32_t'],
2638 'GetActiveUniformsiv': {
2640 'data_transfer_methods': ['shm'],
2642 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2644 'result': ['SizedResult<GLint>'],
2647 'GetAttachedShaders': {
2649 'data_transfer_methods': ['shm'],
2650 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2651 'result': ['SizedResult<GLuint>'],
2653 'GetAttribLocation': {
2655 'data_transfer_methods': ['shm'],
2657 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2658 'result': ['GLint'],
2661 'GetFragDataLocation': {
2663 'data_transfer_methods': ['shm'],
2665 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2666 'result': ['GLint'],
2672 'result': ['SizedResult<GLboolean>'],
2673 'decoder_func': 'DoGetBooleanv',
2674 'gl_test_func': 'glGetBooleanv',
2676 'GetBufferParameteriv': {
2678 'result': ['SizedResult<GLint>'],
2679 'decoder_func': 'DoGetBufferParameteriv',
2680 'expectation': False,
2685 'decoder_func': 'GetErrorState()->GetGLError',
2687 'result': ['GLenum'],
2688 'client_test': False,
2692 'result': ['SizedResult<GLfloat>'],
2693 'decoder_func': 'DoGetFloatv',
2694 'gl_test_func': 'glGetFloatv',
2696 'GetFramebufferAttachmentParameteriv': {
2698 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2699 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2700 'result': ['SizedResult<GLint>'],
2702 'GetGraphicsResetStatusKHR': {
2704 'client_test': False,
2710 'result': ['SizedResult<GLint64>'],
2711 'client_test': False,
2712 'decoder_func': 'DoGetInteger64v',
2717 'result': ['SizedResult<GLint>'],
2718 'decoder_func': 'DoGetIntegerv',
2719 'client_test': False,
2721 'GetInteger64i_v': {
2723 'result': ['SizedResult<GLint64>'],
2724 'client_test': False,
2729 'result': ['SizedResult<GLint>'],
2730 'client_test': False,
2733 'GetInternalformativ': {
2735 'data_transfer_methods': ['shm'],
2736 'result': ['SizedResult<GLint>'],
2738 'GLenumRenderBufferTarget target, GLenumRenderBufferFormat format, '
2739 'GLenumInternalFormatParameter pname, GLint* params',
2742 'GetMaxValueInBufferCHROMIUM': {
2744 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2745 'result': ['GLuint'],
2747 'client_test': False,
2754 'decoder_func': 'DoGetProgramiv',
2755 'result': ['SizedResult<GLint>'],
2756 'expectation': False,
2758 'GetProgramInfoCHROMIUM': {
2760 'expectation': False,
2764 'client_test': False,
2765 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2767 'uint32_t link_status',
2768 'uint32_t num_attribs',
2769 'uint32_t num_uniforms',
2772 'GetProgramInfoLog': {
2774 'expectation': False,
2776 'GetRenderbufferParameteriv': {
2778 'decoder_func': 'DoGetRenderbufferParameteriv',
2779 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2780 'result': ['SizedResult<GLint>'],
2782 'GetSamplerParameterfv': {
2784 'result': ['SizedResult<GLfloat>'],
2785 'id_mapping': [ 'Sampler' ],
2788 'GetSamplerParameteriv': {
2790 'result': ['SizedResult<GLint>'],
2791 'id_mapping': [ 'Sampler' ],
2796 'decoder_func': 'DoGetShaderiv',
2797 'result': ['SizedResult<GLint>'],
2799 'GetShaderInfoLog': {
2801 'get_len_func': 'glGetShaderiv',
2802 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2805 'GetShaderPrecisionFormat': {
2807 'data_transfer_methods': ['shm'],
2809 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2813 'int32_t min_range',
2814 'int32_t max_range',
2815 'int32_t precision',
2818 'GetShaderSource': {
2820 'get_len_func': 'DoGetShaderiv',
2821 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2823 'client_test': False,
2827 'client_test': False,
2828 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2832 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2833 'result': ['SizedResult<GLint>'],
2834 'id_mapping': ['Sync'],
2837 'GetTexParameterfv': {
2839 'decoder_func': 'DoGetTexParameterfv',
2840 'result': ['SizedResult<GLfloat>']
2842 'GetTexParameteriv': {
2844 'decoder_func': 'DoGetTexParameteriv',
2845 'result': ['SizedResult<GLint>']
2847 'GetTranslatedShaderSourceANGLE': {
2849 'get_len_func': 'DoGetShaderiv',
2850 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2854 'GetUniformBlockIndex': {
2856 'data_transfer_methods': ['shm'],
2858 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2859 'result': ['GLuint'],
2860 'error_return': 'GL_INVALID_INDEX',
2863 'GetUniformBlocksCHROMIUM': {
2865 'expectation': False,
2869 'client_test': False,
2870 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2871 'result': ['uint32_t'],
2874 'GetUniformsES3CHROMIUM': {
2876 'expectation': False,
2880 'client_test': False,
2881 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2882 'result': ['uint32_t'],
2885 'GetTransformFeedbackVarying': {
2887 'data_transfer_methods': ['shm'],
2889 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2898 'GetTransformFeedbackVaryingsCHROMIUM': {
2900 'expectation': False,
2904 'client_test': False,
2905 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2906 'result': ['uint32_t'],
2911 'data_transfer_methods': ['shm'],
2912 'result': ['SizedResult<GLfloat>'],
2916 'data_transfer_methods': ['shm'],
2917 'result': ['SizedResult<GLint>'],
2921 'data_transfer_methods': ['shm'],
2922 'result': ['SizedResult<GLuint>'],
2925 'GetUniformIndices': {
2927 'data_transfer_methods': ['shm'],
2928 'result': ['SizedResult<GLuint>'],
2929 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
2933 'GetUniformLocation': {
2935 'data_transfer_methods': ['shm'],
2937 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2938 'result': ['GLint'],
2939 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
2941 'GetVertexAttribfv': {
2943 'result': ['SizedResult<GLfloat>'],
2945 'decoder_func': 'DoGetVertexAttribfv',
2946 'expectation': False,
2947 'client_test': False,
2949 'GetVertexAttribiv': {
2951 'result': ['SizedResult<GLint>'],
2953 'decoder_func': 'DoGetVertexAttribiv',
2954 'expectation': False,
2955 'client_test': False,
2957 'GetVertexAttribIiv': {
2959 'result': ['SizedResult<GLint>'],
2961 'decoder_func': 'DoGetVertexAttribIiv',
2962 'expectation': False,
2963 'client_test': False,
2966 'GetVertexAttribIuiv': {
2968 'result': ['SizedResult<GLuint>'],
2970 'decoder_func': 'DoGetVertexAttribIuiv',
2971 'expectation': False,
2972 'client_test': False,
2975 'GetVertexAttribPointerv': {
2977 'data_transfer_methods': ['shm'],
2978 'result': ['SizedResult<GLuint>'],
2979 'client_test': False,
2981 'InvalidateFramebuffer': {
2984 'client_test': False,
2988 'InvalidateSubFramebuffer': {
2991 'client_test': False,
2997 'decoder_func': 'DoIsBuffer',
2998 'expectation': False,
3002 'decoder_func': 'DoIsEnabled',
3003 'client_test': False,
3005 'expectation': False,
3009 'decoder_func': 'DoIsFramebuffer',
3010 'expectation': False,
3014 'decoder_func': 'DoIsProgram',
3015 'expectation': False,
3019 'decoder_func': 'DoIsRenderbuffer',
3020 'expectation': False,
3024 'decoder_func': 'DoIsShader',
3025 'expectation': False,
3029 'id_mapping': [ 'Sampler' ],
3030 'expectation': False,
3035 'id_mapping': [ 'Sync' ],
3036 'cmd_args': 'GLuint sync',
3037 'expectation': False,
3042 'decoder_func': 'DoIsTexture',
3043 'expectation': False,
3045 'IsTransformFeedback': {
3047 'id_mapping': [ 'TransformFeedback' ],
3048 'expectation': False,
3052 'decoder_func': 'DoLinkProgram',
3056 'MapBufferCHROMIUM': {
3058 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3060 'client_test': False,
3063 'MapBufferSubDataCHROMIUM': {
3067 'client_test': False,
3068 'pepper_interface': 'ChromiumMapSub',
3071 'MapTexSubImage2DCHROMIUM': {
3073 'extension': "CHROMIUM_sub_image",
3075 'client_test': False,
3076 'pepper_interface': 'ChromiumMapSub',
3081 'data_transfer_methods': ['shm'],
3082 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3083 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3084 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3085 'uint32_t result_shm_id, uint32_t result_shm_offset',
3087 'result': ['uint32_t'],
3090 'PauseTransformFeedback': {
3093 'PixelStorei': {'type': 'Manual'},
3094 'PostSubBufferCHROMIUM': {
3098 'client_test': False,
3102 'ProduceTextureCHROMIUM': {
3103 'decoder_func': 'DoProduceTextureCHROMIUM',
3106 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3108 'client_test': False,
3109 'extension': "CHROMIUM_texture_mailbox",
3113 'ProduceTextureDirectCHROMIUM': {
3114 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3117 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3119 'client_test': False,
3120 'extension': "CHROMIUM_texture_mailbox",
3124 'RenderbufferStorage': {
3125 'decoder_func': 'DoRenderbufferStorage',
3126 'gl_test_func': 'glRenderbufferStorageEXT',
3127 'expectation': False,
3130 'RenderbufferStorageMultisampleCHROMIUM': {
3132 '// GL_CHROMIUM_framebuffer_multisample\n',
3133 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3134 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3135 'expectation': False,
3137 'extension_flag': 'chromium_framebuffer_multisample',
3138 'pepper_interface': 'FramebufferMultisample',
3139 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3142 'RenderbufferStorageMultisampleEXT': {
3144 '// GL_EXT_multisampled_render_to_texture\n',
3145 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3146 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3147 'expectation': False,
3149 'extension_flag': 'multisampled_render_to_texture',
3158 '// ReadPixels has the result separated from the pixel buffer so that\n'
3159 '// it is easier to specify the result going to some specific place\n'
3160 '// that exactly fits the rectangle of pixels.\n',
3162 'data_transfer_methods': ['shm'],
3164 'client_test': False,
3166 'GLint x, GLint y, GLsizei width, GLsizei height, '
3167 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3168 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3169 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3171 'result': ['uint32_t'],
3172 'defer_reads': True,
3175 'ReleaseShaderCompiler': {
3176 'decoder_func': 'DoReleaseShaderCompiler',
3179 'ResumeTransformFeedback': {
3182 'SamplerParameterf': {
3186 'id_mapping': [ 'Sampler' ],
3189 'SamplerParameterfv': {
3191 'data_value': 'GL_NEAREST',
3193 'gl_test_func': 'glSamplerParameterf',
3194 'decoder_func': 'DoSamplerParameterfv',
3195 'first_element_only': True,
3196 'id_mapping': [ 'Sampler' ],
3199 'SamplerParameteri': {
3203 'id_mapping': [ 'Sampler' ],
3206 'SamplerParameteriv': {
3208 'data_value': 'GL_NEAREST',
3210 'gl_test_func': 'glSamplerParameteri',
3211 'decoder_func': 'DoSamplerParameteriv',
3212 'first_element_only': True,
3217 'client_test': False,
3221 'decoder_func': 'DoShaderSource',
3222 'expectation': False,
3223 'data_transfer_methods': ['bucket'],
3225 'GLuint shader, const char** str',
3227 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3230 'type': 'StateSetFrontBack',
3231 'state': 'StencilMask',
3233 'expectation': False,
3235 'StencilMaskSeparate': {
3236 'type': 'StateSetFrontBackSeparate',
3237 'state': 'StencilMask',
3239 'expectation': False,
3243 'decoder_func': 'DoSwapBuffers',
3245 'client_test': False,
3251 'decoder_func': 'DoSwapInterval',
3253 'client_test': False,
3259 'data_transfer_methods': ['shm'],
3260 'client_test': False,
3265 'data_transfer_methods': ['shm'],
3266 'client_test': False,
3271 'decoder_func': 'DoTexParameterf',
3277 'decoder_func': 'DoTexParameteri',
3284 'data_value': 'GL_NEAREST',
3286 'decoder_func': 'DoTexParameterfv',
3287 'gl_test_func': 'glTexParameterf',
3288 'first_element_only': True,
3292 'data_value': 'GL_NEAREST',
3294 'decoder_func': 'DoTexParameteriv',
3295 'gl_test_func': 'glTexParameteri',
3296 'first_element_only': True,
3304 'data_transfer_methods': ['shm'],
3305 'client_test': False,
3307 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3308 'GLint xoffset, GLint yoffset, '
3309 'GLsizei width, GLsizei height, '
3310 'GLenumTextureFormat format, GLenumPixelType type, '
3311 'const void* pixels, GLboolean internal'
3315 'data_transfer_methods': ['shm'],
3316 'client_test': False,
3318 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3319 'GLint xoffset, GLint yoffset, GLint zoffset, '
3320 'GLsizei width, GLsizei height, GLsizei depth, '
3321 'GLenumTextureFormat format, GLenumPixelType type, '
3322 'const void* pixels, GLboolean internal',
3325 'TransformFeedbackVaryings': {
3327 'data_transfer_methods': ['bucket'],
3328 'decoder_func': 'DoTransformFeedbackVaryings',
3330 'GLuint program, const char** varyings, GLenum buffermode',
3333 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3337 'decoder_func': 'DoUniform1fv',
3339 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3343 'decoder_func': 'DoUniform1iv',
3356 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3357 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3361 'decoder_func': 'DoUniform2fv',
3366 'decoder_func': 'DoUniform2iv',
3378 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3379 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3383 'decoder_func': 'DoUniform3fv',
3388 'decoder_func': 'DoUniform3iv',
3400 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3401 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3405 'decoder_func': 'DoUniform4fv',
3410 'decoder_func': 'DoUniform4iv',
3422 'UniformMatrix2fv': {
3425 'decoder_func': 'DoUniformMatrix2fv',
3427 'UniformMatrix2x3fv': {
3432 'UniformMatrix2x4fv': {
3437 'UniformMatrix3fv': {
3440 'decoder_func': 'DoUniformMatrix3fv',
3442 'UniformMatrix3x2fv': {
3447 'UniformMatrix3x4fv': {
3452 'UniformMatrix4fv': {
3455 'decoder_func': 'DoUniformMatrix4fv',
3457 'UniformMatrix4x2fv': {
3462 'UniformMatrix4x3fv': {
3467 'UniformBlockBinding': {
3472 'UnmapBufferCHROMIUM': {
3474 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3476 'client_test': False,
3479 'UnmapBufferSubDataCHROMIUM': {
3483 'client_test': False,
3484 'pepper_interface': 'ChromiumMapSub',
3492 'UnmapTexSubImage2DCHROMIUM': {
3494 'extension': "CHROMIUM_sub_image",
3496 'client_test': False,
3497 'pepper_interface': 'ChromiumMapSub',
3502 'decoder_func': 'DoUseProgram',
3504 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3505 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3506 'VertexAttrib1fv': {
3509 'decoder_func': 'DoVertexAttrib1fv',
3511 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3512 'VertexAttrib2fv': {
3515 'decoder_func': 'DoVertexAttrib2fv',
3517 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3518 'VertexAttrib3fv': {
3521 'decoder_func': 'DoVertexAttrib3fv',
3523 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3524 'VertexAttrib4fv': {
3527 'decoder_func': 'DoVertexAttrib4fv',
3529 'VertexAttribI4i': {
3531 'decoder_func': 'DoVertexAttribI4i',
3533 'VertexAttribI4iv': {
3537 'decoder_func': 'DoVertexAttribI4iv',
3539 'VertexAttribI4ui': {
3541 'decoder_func': 'DoVertexAttribI4ui',
3543 'VertexAttribI4uiv': {
3547 'decoder_func': 'DoVertexAttribI4uiv',
3549 'VertexAttribIPointer': {
3551 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3552 'GLenumVertexAttribIType type, GLsizei stride, '
3554 'client_test': False,
3557 'VertexAttribPointer': {
3559 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3560 'GLenumVertexAttribType type, GLboolean normalized, '
3561 'GLsizei stride, GLuint offset',
3562 'client_test': False,
3566 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3567 'GLuint timeout_0, GLuint timeout_1',
3569 'client_test': False,
3578 'decoder_func': 'DoViewport',
3588 'GetRequestableExtensionsCHROMIUM': {
3591 'cmd_args': 'uint32_t bucket_id',
3595 'RequestExtensionCHROMIUM': {
3598 'client_test': False,
3599 'cmd_args': 'uint32_t bucket_id',
3603 'RateLimitOffscreenContextCHROMIUM': {
3607 'client_test': False,
3609 'CreateStreamTextureCHROMIUM': {
3610 'type': 'HandWritten',
3617 'TexImageIOSurface2DCHROMIUM': {
3618 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3624 'CopyTextureCHROMIUM': {
3625 'decoder_func': 'DoCopyTextureCHROMIUM',
3627 'extension': "CHROMIUM_copy_texture",
3631 'CopySubTextureCHROMIUM': {
3632 'decoder_func': 'DoCopySubTextureCHROMIUM',
3634 'extension': "CHROMIUM_copy_texture",
3638 'CompressedCopyTextureCHROMIUM': {
3639 'decoder_func': 'DoCompressedCopyTextureCHROMIUM',
3644 'TexStorage2DEXT': {
3647 'decoder_func': 'DoTexStorage2DEXT',
3650 'DrawArraysInstancedANGLE': {
3652 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3653 'GLsizei primcount',
3656 'pepper_interface': 'InstancedArrays',
3657 'defer_draws': True,
3662 'decoder_func': 'DoDrawBuffersEXT',
3664 'client_test': False,
3666 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3669 'pepper_interface': 'DrawBuffers',
3672 'DrawElementsInstancedANGLE': {
3674 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3675 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3678 'client_test': False,
3679 'pepper_interface': 'InstancedArrays',
3680 'defer_draws': True,
3683 'VertexAttribDivisorANGLE': {
3685 'cmd_args': 'GLuint index, GLuint divisor',
3688 'pepper_interface': 'InstancedArrays',
3692 'gl_test_func': 'glGenQueriesARB',
3693 'resource_type': 'Query',
3694 'resource_types': 'Queries',
3696 'pepper_interface': 'Query',
3697 'not_shared': 'True',
3698 'extension': "occlusion_query_EXT",
3700 'DeleteQueriesEXT': {
3702 'gl_test_func': 'glDeleteQueriesARB',
3703 'resource_type': 'Query',
3704 'resource_types': 'Queries',
3706 'pepper_interface': 'Query',
3707 'extension': "occlusion_query_EXT",
3711 'client_test': False,
3712 'pepper_interface': 'Query',
3713 'extension': "occlusion_query_EXT",
3717 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3718 'data_transfer_methods': ['shm'],
3719 'gl_test_func': 'glBeginQuery',
3720 'pepper_interface': 'Query',
3721 'extension': "occlusion_query_EXT",
3723 'BeginTransformFeedback': {
3728 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3729 'gl_test_func': 'glEndnQuery',
3730 'client_test': False,
3731 'pepper_interface': 'Query',
3732 'extension': "occlusion_query_EXT",
3734 'EndTransformFeedback': {
3739 'client_test': False,
3740 'gl_test_func': 'glGetQueryiv',
3741 'pepper_interface': 'Query',
3742 'extension': "occlusion_query_EXT",
3744 'GetQueryObjectuivEXT': {
3746 'client_test': False,
3747 'gl_test_func': 'glGetQueryObjectuiv',
3748 'pepper_interface': 'Query',
3749 'extension': "occlusion_query_EXT",
3751 'BindUniformLocationCHROMIUM': {
3754 'data_transfer_methods': ['bucket'],
3756 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3758 'InsertEventMarkerEXT': {
3760 'decoder_func': 'DoInsertEventMarkerEXT',
3761 'expectation': False,
3764 'PushGroupMarkerEXT': {
3766 'decoder_func': 'DoPushGroupMarkerEXT',
3767 'expectation': False,
3770 'PopGroupMarkerEXT': {
3771 'decoder_func': 'DoPopGroupMarkerEXT',
3772 'expectation': False,
3777 'GenVertexArraysOES': {
3780 'gl_test_func': 'glGenVertexArraysOES',
3781 'resource_type': 'VertexArray',
3782 'resource_types': 'VertexArrays',
3784 'pepper_interface': 'VertexArrayObject',
3786 'BindVertexArrayOES': {
3789 'gl_test_func': 'glBindVertexArrayOES',
3790 'decoder_func': 'DoBindVertexArrayOES',
3791 'gen_func': 'GenVertexArraysOES',
3793 'client_test': False,
3794 'pepper_interface': 'VertexArrayObject',
3796 'DeleteVertexArraysOES': {
3799 'gl_test_func': 'glDeleteVertexArraysOES',
3800 'resource_type': 'VertexArray',
3801 'resource_types': 'VertexArrays',
3803 'pepper_interface': 'VertexArrayObject',
3805 'IsVertexArrayOES': {
3808 'gl_test_func': 'glIsVertexArrayOES',
3809 'decoder_func': 'DoIsVertexArrayOES',
3810 'expectation': False,
3812 'pepper_interface': 'VertexArrayObject',
3814 'BindTexImage2DCHROMIUM': {
3815 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3817 'extension': "CHROMIUM_image",
3820 'ReleaseTexImage2DCHROMIUM': {
3821 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3823 'extension': "CHROMIUM_image",
3826 'ShallowFinishCHROMIUM': {
3831 'client_test': False,
3833 'ShallowFlushCHROMIUM': {
3836 'extension': "CHROMIUM_miscellaneous",
3838 'client_test': False,
3840 'OrderingBarrierCHROMIUM': {
3845 'client_test': False,
3847 'TraceBeginCHROMIUM': {
3850 'client_test': False,
3851 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3855 'TraceEndCHROMIUM': {
3857 'client_test': False,
3858 'decoder_func': 'DoTraceEndCHROMIUM',
3863 'AsyncTexImage2DCHROMIUM': {
3865 'data_transfer_methods': ['shm'],
3866 'client_test': False,
3867 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3868 'GLintTextureInternalFormat internalformat, '
3869 'GLsizei width, GLsizei height, '
3870 'GLintTextureBorder border, '
3871 'GLenumTextureFormat format, GLenumPixelType type, '
3872 'const void* pixels, '
3873 'uint32_t async_upload_token, '
3879 'AsyncTexSubImage2DCHROMIUM': {
3881 'data_transfer_methods': ['shm'],
3882 'client_test': False,
3883 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3884 'GLint xoffset, GLint yoffset, '
3885 'GLsizei width, GLsizei height, '
3886 'GLenumTextureFormat format, GLenumPixelType type, '
3887 'const void* data, '
3888 'uint32_t async_upload_token, '
3894 'WaitAsyncTexImage2DCHROMIUM': {
3896 'client_test': False,
3901 'WaitAllAsyncTexImage2DCHROMIUM': {
3903 'client_test': False,
3908 'DiscardFramebufferEXT': {
3911 'decoder_func': 'DoDiscardFramebufferEXT',
3913 'client_test': False,
3914 'extension_flag': 'ext_discard_framebuffer',
3917 'LoseContextCHROMIUM': {
3918 'decoder_func': 'DoLoseContextCHROMIUM',
3924 'InsertSyncPointCHROMIUM': {
3925 'type': 'HandWritten',
3927 'extension': "CHROMIUM_sync_point",
3931 'WaitSyncPointCHROMIUM': {
3934 'extension': "CHROMIUM_sync_point",
3938 'DiscardBackbufferCHROMIUM': {
3945 'ScheduleOverlayPlaneCHROMIUM': {
3949 'client_test': False,
3953 'MatrixLoadfCHROMIUM': {
3956 'data_type': 'GLfloat',
3957 'decoder_func': 'DoMatrixLoadfCHROMIUM',
3958 'gl_test_func': 'glMatrixLoadfEXT',
3961 'extension_flag': 'chromium_path_rendering',
3963 'MatrixLoadIdentityCHROMIUM': {
3964 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
3965 'gl_test_func': 'glMatrixLoadIdentityEXT',
3968 'extension_flag': 'chromium_path_rendering',
3973 def Grouper(n
, iterable
, fillvalue
=None):
3974 """Collect data into fixed-length chunks or blocks"""
3975 args
= [iter(iterable
)] * n
3976 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
3979 def SplitWords(input_string
):
3980 """Split by '_' if found, otherwise split at uppercase/numeric chars.
3982 Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
3983 "Case"], and "Vector3" into ["Vector", "3"].
3985 if input_string
.find('_') > -1:
3986 # 'some_TEXT_' -> 'some TEXT'
3987 return input_string
.replace('_', ' ').strip().split()
3989 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
3991 # look for capitalization to cut input_strings
3992 # 'SomeText' -> 'Some Text'
3993 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
3994 # 'Vector3' -> 'Vector 3'
3995 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
3996 return input_string
.split()
3998 def ToUnderscore(input_string
):
3999 """converts CamelCase to camel_case."""
4000 words
= SplitWords(input_string
)
4001 return '_'.join([word
.lower() for word
in words
])
4003 def CachedStateName(item
):
4004 if item
.get('cached', False):
4005 return 'cached_' + item
['name']
4008 def ToGLExtensionString(extension_flag
):
4009 """Returns GL-type extension string of a extension flag."""
4010 if extension_flag
== "oes_compressed_etc1_rgb8_texture":
4011 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
4013 uppercase_words
= [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
4014 'egl', 'atc', 'etc1', 'angle']
4015 parts
= extension_flag
.split('_')
4017 [part
.upper() if part
in uppercase_words
else part
for part
in parts
])
4019 def ToCamelCase(input_string
):
4020 """converts ABC_underscore_case to ABCUnderscoreCase."""
4021 return ''.join(w
[0].upper() + w
[1:] for w
in input_string
.split('_'))
4023 def GetGLGetTypeConversion(result_type
, value_type
, value
):
4024 """Makes a gl compatible type conversion string for accessing state variables.
4026 Useful when accessing state variables through glGetXXX calls.
4027 glGet documetation (for example, the manual pages):
4028 [...] If glGetIntegerv is called, [...] most floating-point values are
4029 rounded to the nearest integer value. [...]
4032 result_type: the gl type to be obtained
4033 value_type: the GL type of the state variable
4034 value: the name of the state variable
4037 String that converts the state variable to desired GL type according to GL
4041 if result_type
== 'GLint':
4042 if value_type
== 'GLfloat':
4043 return 'static_cast<GLint>(round(%s))' % value
4044 return 'static_cast<%s>(%s)' % (result_type
, value
)
4046 class CWriter(object):
4047 """Writes to a file formatting it for Google's style guidelines."""
4049 def __init__(self
, filename
):
4050 self
.filename
= filename
4053 def Write(self
, string
):
4054 """Writes a string to a file spliting if it's > 80 characters."""
4055 lines
= string
.splitlines()
4056 num_lines
= len(lines
)
4057 for ii
in range(0, num_lines
):
4058 self
.content
.append(lines
[ii
])
4059 if ii
< (num_lines
- 1) or string
[-1] == '\n':
4060 self
.content
.append('\n')
4063 """Close the file."""
4064 content
= "".join(self
.content
)
4066 if os
.path
.exists(self
.filename
):
4067 old_file
= open(self
.filename
, "rb");
4068 old_content
= old_file
.read()
4070 if content
== old_content
:
4073 file = open(self
.filename
, "wb")
4078 class CHeaderWriter(CWriter
):
4079 """Writes a C Header file."""
4081 _non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
4083 def __init__(self
, filename
, file_comment
= None):
4084 CWriter
.__init
__(self
, filename
)
4086 base
= os
.path
.abspath(filename
)
4087 while os
.path
.basename(base
) != 'src':
4088 new_base
= os
.path
.dirname(base
)
4089 assert new_base
!= base
# Prevent infinite loop.
4092 hpath
= os
.path
.relpath(filename
, base
)
4093 self
.guard
= self
._non
_alnum
_re
.sub('_', hpath
).upper() + '_'
4095 self
.Write(_LICENSE
)
4096 self
.Write(_DO_NOT_EDIT_WARNING
)
4097 if not file_comment
== None:
4098 self
.Write(file_comment
)
4099 self
.Write("#ifndef %s\n" % self
.guard
)
4100 self
.Write("#define %s\n\n" % self
.guard
)
4103 self
.Write("#endif // %s\n\n" % self
.guard
)
4106 class TypeHandler(object):
4107 """This class emits code for a particular type of function."""
4109 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
4114 def InitFunction(self
, func
):
4115 """Add or adjust anything type specific for this function."""
4116 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
4117 func
.AddCmdArg(DataSizeArgument('data_size'))
4119 def NeedsDataTransferFunction(self
, func
):
4120 """Overriden from TypeHandler."""
4121 return func
.num_pointer_args
>= 1
4123 def WriteStruct(self
, func
, file):
4124 """Writes a structure that matches the arguments to a function."""
4125 comment
= func
.GetInfo('cmd_comment')
4126 if not comment
== None:
4128 file.Write("struct %s {\n" % func
.name
)
4129 file.Write(" typedef %s ValueType;\n" % func
.name
)
4130 file.Write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
4131 func
.WriteCmdArgFlag(file)
4132 func
.WriteCmdFlag(file)
4134 result
= func
.GetInfo('result')
4135 if not result
== None:
4136 if len(result
) == 1:
4137 file.Write(" typedef %s Result;\n\n" % result
[0])
4139 file.Write(" struct Result {\n")
4141 file.Write(" %s;\n" % line
)
4142 file.Write(" };\n\n")
4144 func
.WriteCmdComputeSize(file)
4145 func
.WriteCmdSetHeader(file)
4146 func
.WriteCmdInit(file)
4147 func
.WriteCmdSet(file)
4149 file.Write(" gpu::CommandHeader header;\n")
4150 args
= func
.GetCmdArgs()
4152 file.Write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
4154 consts
= func
.GetCmdConstants()
4155 for const
in consts
:
4156 file.Write(" static const %s %s = %s;\n" %
4157 (const
.cmd_type
, const
.name
, const
.GetConstantValue()))
4162 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
4163 file.Write("static_assert(sizeof(%s) == %d,\n" % (func
.name
, size
))
4164 file.Write(" \"size of %s should be %d\");\n" %
4166 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func
.name
)
4167 file.Write(" \"offset of %s header should be 0\");\n" %
4169 offset
= _SIZE_OF_COMMAND_HEADER
4171 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
4172 (func
.name
, arg
.name
, offset
))
4173 file.Write(" \"offset of %s %s should be %d\");\n" %
4174 (func
.name
, arg
.name
, offset
))
4175 offset
+= _SIZE_OF_UINT32
4176 if not result
== None and len(result
) > 1:
4179 parts
= line
.split()
4182 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4183 "offset of %(cmd_name)s Result %(field_name)s should be "
4186 file.Write((check
.strip() + "\n") % {
4187 'cmd_name': func
.name
,
4191 offset
+= _SIZE_OF_UINT32
4194 def WriteHandlerImplementation(self
, func
, file):
4195 """Writes the handler implementation for this command."""
4196 if func
.IsUnsafe() and func
.GetInfo('id_mapping'):
4197 code_no_gen
= """ if (!group_->Get%(type)sServiceId(
4198 %(var)s, &%(service_var)s)) {
4199 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4200 return error::kNoError;
4203 code_gen
= """ if (!group_->Get%(type)sServiceId(
4204 %(var)s, &%(service_var)s)) {
4205 if (!group_->bind_generates_resource()) {
4207 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4208 return error::kNoError;
4210 GLuint client_id = %(var)s;
4211 gl%(gen_func)s(1, &%(service_var)s);
4212 Create%(type)s(client_id, %(service_var)s);
4215 gen_func
= func
.GetInfo('gen_func')
4216 for id_type
in func
.GetInfo('id_mapping'):
4217 service_var
= id_type
.lower()
4218 if id_type
== 'Sync':
4219 service_var
= "service_%s" % service_var
4220 file.Write(" GLsync %s = 0;\n" % service_var
)
4221 if gen_func
and id_type
in gen_func
:
4222 file.Write(code_gen
% { 'type': id_type
,
4223 'var': id_type
.lower(),
4224 'service_var': service_var
,
4225 'func': func
.GetGLFunctionName(),
4226 'gen_func': gen_func
})
4228 file.Write(code_no_gen
% { 'type': id_type
,
4229 'var': id_type
.lower(),
4230 'service_var': service_var
,
4231 'func': func
.GetGLFunctionName() })
4233 for arg
in func
.GetOriginalArgs():
4234 if arg
.type == "GLsync":
4235 args
.append("service_%s" % arg
.name
)
4236 elif arg
.name
.endswith("size") and arg
.type == "GLsizei":
4237 args
.append("num_%s" % func
.GetLastOriginalArg().name
)
4238 elif arg
.name
== "length":
4239 args
.append("nullptr")
4241 args
.append(arg
.name
)
4242 file.Write(" %s(%s);\n" %
4243 (func
.GetGLFunctionName(), ", ".join(args
)))
4245 def WriteCmdSizeTest(self
, func
, file):
4246 """Writes the size test for a command."""
4247 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4249 def WriteFormatTest(self
, func
, file):
4250 """Writes a format test for a command."""
4251 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4252 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4253 (func
.name
, func
.name
))
4254 file.Write(" void* next_cmd = cmd.Set(\n")
4256 args
= func
.GetCmdArgs()
4257 for value
, arg
in enumerate(args
):
4258 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
4260 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4262 file.Write(" cmd.header.command);\n")
4263 func
.type_handler
.WriteCmdSizeTest(func
, file)
4264 for value
, arg
in enumerate(args
):
4265 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4266 (arg
.type, value
+ 11, arg
.name
))
4267 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4268 file.Write(" next_cmd, sizeof(cmd));\n")
4272 def WriteImmediateFormatTest(self
, func
, file):
4273 """Writes a format test for an immediate version of a command."""
4276 def WriteBucketFormatTest(self
, func
, file):
4277 """Writes a format test for a bucket version of a command."""
4280 def WriteGetDataSizeCode(self
, func
, file):
4281 """Writes the code to set data_size used in validation"""
4284 def WriteImmediateCmdSizeTest(self
, func
, file):
4285 """Writes a size test for an immediate version of a command."""
4286 file.Write(" // TODO(gman): Compute correct size.\n")
4287 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4289 def __WriteIdMapping(self
, func
, file):
4290 """Writes client side / service side ID mapping."""
4291 if not func
.IsUnsafe() or not func
.GetInfo('id_mapping'):
4293 for id_type
in func
.GetInfo('id_mapping'):
4294 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
4295 (id_type
, id_type
.lower(), id_type
.lower()))
4297 def WriteImmediateHandlerImplementation (self
, func
, file):
4298 """Writes the handler impl for the immediate version of a command."""
4299 self
.__WriteIdMapping
(func
, file)
4300 file.Write(" %s(%s);\n" %
4301 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4303 def WriteBucketHandlerImplementation (self
, func
, file):
4304 """Writes the handler impl for the bucket version of a command."""
4305 self
.__WriteIdMapping
(func
, file)
4306 file.Write(" %s(%s);\n" %
4307 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4309 def WriteServiceHandlerFunctionHeader(self
, func
, file):
4310 """Writes function header for service implementation handlers."""
4311 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4312 uint32_t immediate_data_size, const void* cmd_data) {
4313 """ % {'name': func
.name
})
4315 file.Write("""if (!unsafe_es3_apis_enabled())
4316 return error::kUnknownCommand;
4318 file.Write("""const gles2::cmds::%(name)s& c =
4319 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4321 """ % {'name': func
.name
})
4323 def WriteServiceImplementation(self
, func
, file):
4324 """Writes the service implementation for a command."""
4325 self
.WriteServiceHandlerFunctionHeader(func
, file)
4326 self
.WriteHandlerExtensionCheck(func
, file)
4327 self
.WriteHandlerDeferReadWrite(func
, file);
4328 if len(func
.GetOriginalArgs()) > 0:
4329 last_arg
= func
.GetLastOriginalArg()
4330 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
4331 for arg
in all_but_last_arg
:
4332 arg
.WriteGetCode(file)
4333 self
.WriteGetDataSizeCode(func
, file)
4334 last_arg
.WriteGetCode(file)
4335 func
.WriteHandlerValidation(file)
4336 func
.WriteHandlerImplementation(file)
4337 file.Write(" return error::kNoError;\n")
4341 def WriteImmediateServiceImplementation(self
, func
, file):
4342 """Writes the service implementation for an immediate version of command."""
4343 self
.WriteServiceHandlerFunctionHeader(func
, file)
4344 self
.WriteHandlerExtensionCheck(func
, file)
4345 self
.WriteHandlerDeferReadWrite(func
, file);
4346 for arg
in func
.GetOriginalArgs():
4348 self
.WriteGetDataSizeCode(func
, file)
4349 arg
.WriteGetCode(file)
4350 func
.WriteHandlerValidation(file)
4351 func
.WriteHandlerImplementation(file)
4352 file.Write(" return error::kNoError;\n")
4356 def WriteBucketServiceImplementation(self
, func
, file):
4357 """Writes the service implementation for a bucket version of command."""
4358 self
.WriteServiceHandlerFunctionHeader(func
, file)
4359 self
.WriteHandlerExtensionCheck(func
, file)
4360 self
.WriteHandlerDeferReadWrite(func
, file);
4361 for arg
in func
.GetCmdArgs():
4362 arg
.WriteGetCode(file)
4363 func
.WriteHandlerValidation(file)
4364 func
.WriteHandlerImplementation(file)
4365 file.Write(" return error::kNoError;\n")
4369 def WriteHandlerExtensionCheck(self
, func
, file):
4370 if func
.GetInfo('extension_flag'):
4371 file.Write(" if (!features().%s) {\n" % func
.GetInfo('extension_flag'))
4372 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4373 " \"function not available\");\n" % func
.original_name
)
4374 file.Write(" return error::kNoError;")
4375 file.Write(" }\n\n")
4377 def WriteHandlerDeferReadWrite(self
, func
, file):
4378 """Writes the code to handle deferring reads or writes."""
4379 defer_draws
= func
.GetInfo('defer_draws')
4380 defer_reads
= func
.GetInfo('defer_reads')
4381 if defer_draws
or defer_reads
:
4382 file.Write(" error::Error error;\n")
4384 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
4385 file.Write(" if (error != error::kNoError)\n")
4386 file.Write(" return error;\n")
4388 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
4389 file.Write(" if (error != error::kNoError)\n")
4390 file.Write(" return error;\n")
4392 def WriteValidUnitTest(self
, func
, file, test
, *extras
):
4393 """Writes a valid unit test for the service implementation."""
4394 if func
.GetInfo('expectation') == False:
4395 test
= self
._remove
_expected
_call
_re
.sub('', test
)
4398 arg
.GetValidArg(func
) \
4399 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4402 arg
.GetValidGLArg(func
) \
4403 for arg
in func
.GetOriginalArgs()
4405 gl_func_name
= func
.GetGLTestFunctionName()
4408 'gl_func_name': gl_func_name
,
4409 'args': ", ".join(arg_strings
),
4410 'gl_args': ", ".join(gl_arg_strings
),
4412 for extra
in extras
:
4415 while (old_test
!= test
):
4418 file.Write(test
% vars)
4420 def WriteInvalidUnitTest(self
, func
, file, test
, *extras
):
4421 """Writes an invalid unit test for the service implementation."""
4424 for invalid_arg_index
, invalid_arg
in enumerate(func
.GetOriginalArgs()):
4425 # Service implementation does not test constants, as they are not part of
4426 # the call in the service side.
4427 if invalid_arg
.IsConstant():
4430 num_invalid_values
= invalid_arg
.GetNumInvalidValues(func
)
4431 for value_index
in range(0, num_invalid_values
):
4433 parse_result
= "kNoError"
4435 for arg
in func
.GetOriginalArgs():
4436 if arg
.IsConstant():
4438 if invalid_arg
is arg
:
4439 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
4442 arg_string
= arg
.GetValidArg(func
)
4443 arg_strings
.append(arg_string
)
4445 for arg
in func
.GetOriginalArgs():
4446 gl_arg_strings
.append("_")
4447 gl_func_name
= func
.GetGLTestFunctionName()
4449 if not gl_error
== None:
4450 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4454 'arg_index': invalid_arg_index
,
4455 'value_index': value_index
,
4456 'gl_func_name': gl_func_name
,
4457 'args': ", ".join(arg_strings
),
4458 'all_but_last_args': ", ".join(arg_strings
[:-1]),
4459 'gl_args': ", ".join(gl_arg_strings
),
4460 'parse_result': parse_result
,
4461 'gl_error_test': gl_error_test
,
4463 for extra
in extras
:
4465 file.Write(test
% vars)
4467 def WriteServiceUnitTest(self
, func
, file, *extras
):
4468 """Writes the service unit test for a command."""
4470 if func
.name
== 'Enable':
4472 TEST_P(%(test_name)s, %(name)sValidArgs) {
4473 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4474 SpecializedSetup<cmds::%(name)s, 0>(true);
4476 cmd.Init(%(args)s);"""
4477 elif func
.name
== 'Disable':
4479 TEST_P(%(test_name)s, %(name)sValidArgs) {
4480 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4481 SpecializedSetup<cmds::%(name)s, 0>(true);
4483 cmd.Init(%(args)s);"""
4486 TEST_P(%(test_name)s, %(name)sValidArgs) {
4487 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4488 SpecializedSetup<cmds::%(name)s, 0>(true);
4490 cmd.Init(%(args)s);"""
4493 decoder_->set_unsafe_es3_apis_enabled(true);
4494 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4495 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4496 decoder_->set_unsafe_es3_apis_enabled(false);
4497 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4502 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4503 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4506 self
.WriteValidUnitTest(func
, file, valid_test
, *extras
)
4508 if not func
.IsUnsafe():
4510 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4511 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4512 SpecializedSetup<cmds::%(name)s, 0>(false);
4515 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4518 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
4520 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
4521 """Writes the service unit test for an immediate command."""
4522 file.Write("// TODO(gman): %s\n" % func
.name
)
4524 def WriteImmediateValidationCode(self
, func
, file):
4525 """Writes the validation code for an immediate version of a command."""
4528 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
4529 """Writes the service unit test for a bucket command."""
4530 file.Write("// TODO(gman): %s\n" % func
.name
)
4532 def WriteBucketValidationCode(self
, func
, file):
4533 """Writes the validation code for a bucket version of a command."""
4534 file.Write("// TODO(gman): %s\n" % func
.name
)
4536 def WriteGLES2ImplementationDeclaration(self
, func
, file):
4537 """Writes the GLES2 Implemention declaration."""
4538 impl_decl
= func
.GetInfo('impl_decl')
4539 if impl_decl
== None or impl_decl
== True:
4540 file.Write("%s %s(%s) override;\n" %
4541 (func
.return_type
, func
.original_name
,
4542 func
.MakeTypedOriginalArgString("")))
4545 def WriteGLES2CLibImplementation(self
, func
, file):
4546 file.Write("%s GLES2%s(%s) {\n" %
4547 (func
.return_type
, func
.name
,
4548 func
.MakeTypedOriginalArgString("")))
4549 result_string
= "return "
4550 if func
.return_type
== "void":
4552 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
4553 (result_string
, func
.original_name
,
4554 func
.MakeOriginalArgString("")))
4557 def WriteGLES2Header(self
, func
, file):
4558 """Writes a re-write macro for GLES"""
4559 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
4561 def WriteClientGLCallLog(self
, func
, file):
4562 """Writes a logging macro for the client side code."""
4564 if len(func
.GetOriginalArgs()):
4567 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4568 (func
.original_name
, comma
, func
.MakeLogArgString()))
4570 def WriteClientGLReturnLog(self
, func
, file):
4571 """Writes the return value logging code."""
4572 if func
.return_type
!= "void":
4573 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
4575 def WriteGLES2ImplementationHeader(self
, func
, file):
4576 """Writes the GLES2 Implemention."""
4577 self
.WriteGLES2ImplementationDeclaration(func
, file)
4579 def WriteGLES2TraceImplementationHeader(self
, func
, file):
4580 """Writes the GLES2 Trace Implemention header."""
4581 file.Write("%s %s(%s) override;\n" %
4582 (func
.return_type
, func
.original_name
,
4583 func
.MakeTypedOriginalArgString("")))
4585 def WriteGLES2TraceImplementation(self
, func
, file):
4586 """Writes the GLES2 Trace Implemention."""
4587 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
4588 (func
.return_type
, func
.original_name
,
4589 func
.MakeTypedOriginalArgString("")))
4590 result_string
= "return "
4591 if func
.return_type
== "void":
4593 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4595 file.Write(" %sgl_->%s(%s);\n" %
4596 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
4600 def WriteGLES2Implementation(self
, func
, file):
4601 """Writes the GLES2 Implemention."""
4602 impl_func
= func
.GetInfo('impl_func')
4603 impl_decl
= func
.GetInfo('impl_decl')
4604 gen_cmd
= func
.GetInfo('gen_cmd')
4605 if (func
.can_auto_generate
and
4606 (impl_func
== None or impl_func
== True) and
4607 (impl_decl
== None or impl_decl
== True) and
4608 (gen_cmd
== None or gen_cmd
== True)):
4609 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4610 (func
.return_type
, func
.original_name
,
4611 func
.MakeTypedOriginalArgString("")))
4612 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4613 self
.WriteClientGLCallLog(func
, file)
4614 func
.WriteDestinationInitalizationValidation(file)
4615 for arg
in func
.GetOriginalArgs():
4616 arg
.WriteClientSideValidationCode(file, func
)
4617 file.Write(" helper_->%s(%s);\n" %
4618 (func
.name
, func
.MakeHelperArgString("")))
4619 file.Write(" CheckGLError();\n")
4620 self
.WriteClientGLReturnLog(func
, file)
4624 def WriteGLES2InterfaceHeader(self
, func
, file):
4625 """Writes the GLES2 Interface."""
4626 file.Write("virtual %s %s(%s) = 0;\n" %
4627 (func
.return_type
, func
.original_name
,
4628 func
.MakeTypedOriginalArgString("")))
4630 def WriteMojoGLES2ImplHeader(self
, func
, file):
4631 """Writes the Mojo GLES2 implementation header."""
4632 file.Write("%s %s(%s) override;\n" %
4633 (func
.return_type
, func
.original_name
,
4634 func
.MakeTypedOriginalArgString("")))
4636 def WriteMojoGLES2Impl(self
, func
, file):
4637 """Writes the Mojo GLES2 implementation."""
4638 file.Write("%s MojoGLES2Impl::%s(%s) {\n" %
4639 (func
.return_type
, func
.original_name
,
4640 func
.MakeTypedOriginalArgString("")))
4641 extensions
= ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4642 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4643 "occlusion_query_EXT", "CHROMIUM_image",
4644 "CHROMIUM_copy_texture",
4645 "CHROMIUM_pixel_transfer_buffer_object"]
4646 if func
.IsCoreGLFunction() or func
.GetInfo("extension") in extensions
:
4647 file.Write("MojoGLES2MakeCurrent(context_);");
4648 func_return
= "gl" + func
.original_name
+ "(" + \
4649 func
.MakeOriginalArgString("") + ");"
4650 if func
.return_type
== "void":
4651 file.Write(func_return
);
4653 file.Write("return " + func_return
);
4655 file.Write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4656 func
.original_name
);
4657 if func
.return_type
!= "void":
4658 file.Write("return 0;")
4661 def WriteGLES2InterfaceStub(self
, func
, file):
4662 """Writes the GLES2 Interface stub declaration."""
4663 file.Write("%s %s(%s) override;\n" %
4664 (func
.return_type
, func
.original_name
,
4665 func
.MakeTypedOriginalArgString("")))
4667 def WriteGLES2InterfaceStubImpl(self
, func
, file):
4668 """Writes the GLES2 Interface stub declaration."""
4669 args
= func
.GetOriginalArgs()
4670 arg_string
= ", ".join(
4671 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
4672 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
4673 (func
.return_type
, func
.original_name
, arg_string
))
4674 if func
.return_type
!= "void":
4675 file.Write(" return 0;\n")
4678 def WriteGLES2ImplementationUnitTest(self
, func
, file):
4679 """Writes the GLES2 Implemention unit test."""
4680 client_test
= func
.GetInfo('client_test')
4681 if (func
.can_auto_generate
and
4682 (client_test
== None or client_test
== True)):
4684 TEST_F(GLES2ImplementationTest, %(name)s) {
4689 expected.cmd.Init(%(cmd_args)s);
4691 gl_->%(name)s(%(args)s);
4692 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4696 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
4700 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
4705 'args': ", ".join(gl_arg_strings
),
4706 'cmd_args': ", ".join(cmd_arg_strings
),
4709 # Test constants for invalid values, as they are not tested by the
4711 constants
= [arg
for arg
in func
.GetOriginalArgs() if arg
.IsConstant()]
4714 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4715 gl_->%(name)s(%(args)s);
4716 EXPECT_TRUE(NoCommandsWritten());
4717 EXPECT_EQ(%(gl_error)s, CheckError());
4720 for invalid_arg
in constants
:
4722 invalid
= invalid_arg
.GetInvalidArg(func
)
4723 for arg
in func
.GetOriginalArgs():
4724 if arg
is invalid_arg
:
4725 gl_arg_strings
.append(invalid
[0])
4727 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
4731 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
4732 'args': ", ".join(gl_arg_strings
),
4733 'gl_error': invalid
[2],
4736 if client_test
!= False:
4737 file.Write("// TODO(zmo): Implement unit test for %s\n" % func
.name
)
4739 def WriteDestinationInitalizationValidation(self
, func
, file):
4740 """Writes the client side destintion initialization validation."""
4741 for arg
in func
.GetOriginalArgs():
4742 arg
.WriteDestinationInitalizationValidation(file, func
)
4744 def WriteTraceEvent(self
, func
, file):
4745 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4748 def WriteImmediateCmdComputeSize(self
, func
, file):
4749 """Writes the size computation code for the immediate version of a cmd."""
4750 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4751 file.Write(" return static_cast<uint32_t>(\n")
4752 file.Write(" sizeof(ValueType) + // NOLINT\n")
4753 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4757 def WriteImmediateCmdSetHeader(self
, func
, file):
4758 """Writes the SetHeader function for the immediate version of a cmd."""
4759 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
4760 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4764 def WriteImmediateCmdInit(self
, func
, file):
4765 """Writes the Init function for the immediate version of a command."""
4766 raise NotImplementedError(func
.name
)
4768 def WriteImmediateCmdSet(self
, func
, file):
4769 """Writes the Set function for the immediate version of a command."""
4770 raise NotImplementedError(func
.name
)
4772 def WriteCmdHelper(self
, func
, file):
4773 """Writes the cmd helper definition for a cmd."""
4774 code
= """ void %(name)s(%(typed_args)s) {
4775 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4784 "typed_args": func
.MakeTypedCmdArgString(""),
4785 "args": func
.MakeCmdArgString(""),
4788 def WriteImmediateCmdHelper(self
, func
, file):
4789 """Writes the cmd helper definition for the immediate version of a cmd."""
4790 code
= """ void %(name)s(%(typed_args)s) {
4791 const uint32_t s = 0; // TODO(gman): compute correct size
4792 gles2::cmds::%(name)s* c =
4793 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4802 "typed_args": func
.MakeTypedCmdArgString(""),
4803 "args": func
.MakeCmdArgString(""),
4807 class StateSetHandler(TypeHandler
):
4808 """Handler for commands that simply set state."""
4811 TypeHandler
.__init
__(self
)
4813 def WriteHandlerImplementation(self
, func
, file):
4814 """Overrriden from TypeHandler."""
4815 state_name
= func
.GetInfo('state')
4816 state
= _STATES
[state_name
]
4817 states
= state
['states']
4818 args
= func
.GetOriginalArgs()
4819 for ndx
,item
in enumerate(states
):
4821 if 'range_checks' in item
:
4822 for range_check
in item
['range_checks']:
4823 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
4824 if 'nan_check' in item
:
4825 # Drivers might generate an INVALID_VALUE error when a value is set
4826 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
4827 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
4828 # Make this behavior consistent within Chromium, and avoid leaking GL
4829 # errors by generating the error in the command buffer instead of
4830 # letting the GL driver generate it.
4831 code
.append("std::isnan(%s)" % args
[ndx
].name
)
4833 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4835 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
4836 ' "%s", "%s out of range");\n' %
4837 (func
.name
, args
[ndx
].name
))
4838 file.Write(" return error::kNoError;\n")
4841 for ndx
,item
in enumerate(states
):
4842 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
4843 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4844 for ndx
,item
in enumerate(states
):
4845 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
4846 if 'state_flag' in state
:
4847 file.Write(" %s = true;\n" % state
['state_flag'])
4848 if not func
.GetInfo("no_gl"):
4849 for ndx
,item
in enumerate(states
):
4850 if item
.get('cached', False):
4851 file.Write(" state_.%s = %s;\n" %
4852 (CachedStateName(item
), args
[ndx
].name
))
4853 file.Write(" %s(%s);\n" %
4854 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4857 def WriteServiceUnitTest(self
, func
, file, *extras
):
4858 """Overrriden from TypeHandler."""
4859 TypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
4860 state_name
= func
.GetInfo('state')
4861 state
= _STATES
[state_name
]
4862 states
= state
['states']
4863 for ndx
,item
in enumerate(states
):
4864 if 'range_checks' in item
:
4865 for check_ndx
, range_check
in enumerate(item
['range_checks']):
4867 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
4868 SpecializedSetup<cmds::%(name)s, 0>(false);
4871 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4872 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4877 arg
.GetValidArg(func
) \
4878 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4881 arg_strings
[ndx
] = range_check
['test_value']
4885 'check_ndx': check_ndx
,
4886 'args': ", ".join(arg_strings
),
4888 for extra
in extras
:
4890 file.Write(valid_test
% vars)
4891 if 'nan_check' in item
:
4893 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
4894 SpecializedSetup<cmds::%(name)s, 0>(false);
4897 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4898 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4903 arg
.GetValidArg(func
) \
4904 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4907 arg_strings
[ndx
] = 'nanf("")'
4911 'args': ", ".join(arg_strings
),
4913 for extra
in extras
:
4915 file.Write(valid_test
% vars)
4918 class StateSetRGBAlphaHandler(TypeHandler
):
4919 """Handler for commands that simply set state that have rgb/alpha."""
4922 TypeHandler
.__init
__(self
)
4924 def WriteHandlerImplementation(self
, func
, file):
4925 """Overrriden from TypeHandler."""
4926 state_name
= func
.GetInfo('state')
4927 state
= _STATES
[state_name
]
4928 states
= state
['states']
4929 args
= func
.GetOriginalArgs()
4930 num_args
= len(args
)
4932 for ndx
,item
in enumerate(states
):
4933 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
4934 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
4935 for ndx
, item
in enumerate(states
):
4936 file.Write(" state_.%s = %s;\n" %
4937 (item
['name'], args
[ndx
% num_args
].name
))
4938 if 'state_flag' in state
:
4939 file.Write(" %s = true;\n" % state
['state_flag'])
4940 if not func
.GetInfo("no_gl"):
4941 file.Write(" %s(%s);\n" %
4942 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4946 class StateSetFrontBackSeparateHandler(TypeHandler
):
4947 """Handler for commands that simply set state that have front/back."""
4950 TypeHandler
.__init
__(self
)
4952 def WriteHandlerImplementation(self
, func
, file):
4953 """Overrriden from TypeHandler."""
4954 state_name
= func
.GetInfo('state')
4955 state
= _STATES
[state_name
]
4956 states
= state
['states']
4957 args
= func
.GetOriginalArgs()
4959 num_args
= len(args
)
4960 file.Write(" bool changed = false;\n")
4961 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
4962 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4963 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
4965 for ndx
, item
in enumerate(group
):
4966 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
4967 file.Write(" changed |= %s;\n" % " ||\n ".join(code
))
4969 file.Write(" if (changed) {\n")
4970 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
4971 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4972 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
4973 for ndx
, item
in enumerate(group
):
4974 file.Write(" state_.%s = %s;\n" %
4975 (item
['name'], args
[ndx
+ 1].name
))
4977 if 'state_flag' in state
:
4978 file.Write(" %s = true;\n" % state
['state_flag'])
4979 if not func
.GetInfo("no_gl"):
4980 file.Write(" %s(%s);\n" %
4981 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4985 class StateSetFrontBackHandler(TypeHandler
):
4986 """Handler for commands that simply set state that set both front/back."""
4989 TypeHandler
.__init
__(self
)
4991 def WriteHandlerImplementation(self
, func
, file):
4992 """Overrriden from TypeHandler."""
4993 state_name
= func
.GetInfo('state')
4994 state
= _STATES
[state_name
]
4995 states
= state
['states']
4996 args
= func
.GetOriginalArgs()
4997 num_args
= len(args
)
4999 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
5000 for ndx
, item
in enumerate(group
):
5001 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
5002 file.Write(" if (%s) {\n" % " ||\n ".join(code
))
5003 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
5004 for ndx
, item
in enumerate(group
):
5005 file.Write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
5006 if 'state_flag' in state
:
5007 file.Write(" %s = true;\n" % state
['state_flag'])
5008 if not func
.GetInfo("no_gl"):
5009 file.Write(" %s(%s);\n" %
5010 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5014 class StateSetNamedParameter(TypeHandler
):
5015 """Handler for commands that set a state chosen with an enum parameter."""
5018 TypeHandler
.__init
__(self
)
5020 def WriteHandlerImplementation(self
, func
, file):
5021 """Overridden from TypeHandler."""
5022 state_name
= func
.GetInfo('state')
5023 state
= _STATES
[state_name
]
5024 states
= state
['states']
5025 args
= func
.GetOriginalArgs()
5026 num_args
= len(args
)
5027 assert num_args
== 2
5028 file.Write(" switch (%s) {\n" % args
[0].name
)
5029 for state
in states
:
5030 file.Write(" case %s:\n" % state
['enum'])
5031 file.Write(" if (state_.%s != %s) {\n" %
5032 (state
['name'], args
[1].name
))
5033 file.Write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
5034 if not func
.GetInfo("no_gl"):
5035 file.Write(" %s(%s);\n" %
5036 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5038 file.Write(" break;\n")
5039 file.Write(" default:\n")
5040 file.Write(" NOTREACHED();\n")
5044 class CustomHandler(TypeHandler
):
5045 """Handler for commands that are auto-generated but require minor tweaks."""
5048 TypeHandler
.__init
__(self
)
5050 def WriteServiceImplementation(self
, func
, file):
5051 """Overrriden from TypeHandler."""
5054 def WriteImmediateServiceImplementation(self
, func
, file):
5055 """Overrriden from TypeHandler."""
5058 def WriteBucketServiceImplementation(self
, func
, file):
5059 """Overrriden from TypeHandler."""
5062 def WriteServiceUnitTest(self
, func
, file, *extras
):
5063 """Overrriden from TypeHandler."""
5064 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5066 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5067 """Overrriden from TypeHandler."""
5068 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5070 def WriteImmediateCmdGetTotalSize(self
, func
, file):
5071 """Overrriden from TypeHandler."""
5073 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5075 def WriteImmediateCmdInit(self
, func
, file):
5076 """Overrriden from TypeHandler."""
5077 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5078 self
.WriteImmediateCmdGetTotalSize(func
, file)
5079 file.Write(" SetHeader(total_size);\n")
5080 args
= func
.GetCmdArgs()
5082 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5086 def WriteImmediateCmdSet(self
, func
, file):
5087 """Overrriden from TypeHandler."""
5088 copy_args
= func
.MakeCmdArgString("_", False)
5089 file.Write(" void* Set(void* cmd%s) {\n" %
5090 func
.MakeTypedCmdArgString("_", True))
5091 self
.WriteImmediateCmdGetTotalSize(func
, file)
5092 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5093 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5094 "cmd, total_size);\n")
5099 class TodoHandler(CustomHandler
):
5100 """Handle for commands that are not yet implemented."""
5102 def NeedsDataTransferFunction(self
, func
):
5103 """Overriden from TypeHandler."""
5106 def WriteImmediateFormatTest(self
, func
, file):
5107 """Overrriden from TypeHandler."""
5110 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5111 """Overrriden from TypeHandler."""
5114 def WriteGLES2Implementation(self
, func
, file):
5115 """Overrriden from TypeHandler."""
5116 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5117 (func
.return_type
, func
.original_name
,
5118 func
.MakeTypedOriginalArgString("")))
5119 file.Write(" // TODO: for now this is a no-op\n")
5122 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5124 if func
.return_type
!= "void":
5125 file.Write(" return 0;\n")
5129 def WriteServiceImplementation(self
, func
, file):
5130 """Overrriden from TypeHandler."""
5131 self
.WriteServiceHandlerFunctionHeader(func
, file)
5132 file.Write(" // TODO: for now this is a no-op\n")
5134 " LOCAL_SET_GL_ERROR("
5135 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
5137 file.Write(" return error::kNoError;\n")
5142 class HandWrittenHandler(CustomHandler
):
5143 """Handler for comands where everything must be written by hand."""
5145 def InitFunction(self
, func
):
5146 """Add or adjust anything type specific for this function."""
5147 CustomHandler
.InitFunction(self
, func
)
5148 func
.can_auto_generate
= False
5150 def NeedsDataTransferFunction(self
, func
):
5151 """Overriden from TypeHandler."""
5152 # If specified explicitly, force the data transfer method.
5153 if func
.GetInfo('data_transfer_methods'):
5157 def WriteStruct(self
, func
, file):
5158 """Overrriden from TypeHandler."""
5161 def WriteDocs(self
, func
, file):
5162 """Overrriden from TypeHandler."""
5165 def WriteServiceUnitTest(self
, func
, file, *extras
):
5166 """Overrriden from TypeHandler."""
5167 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5169 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5170 """Overrriden from TypeHandler."""
5171 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5173 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
5174 """Overrriden from TypeHandler."""
5175 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5177 def WriteServiceImplementation(self
, func
, file):
5178 """Overrriden from TypeHandler."""
5181 def WriteImmediateServiceImplementation(self
, func
, file):
5182 """Overrriden from TypeHandler."""
5185 def WriteBucketServiceImplementation(self
, func
, file):
5186 """Overrriden from TypeHandler."""
5189 def WriteImmediateCmdHelper(self
, func
, file):
5190 """Overrriden from TypeHandler."""
5193 def WriteCmdHelper(self
, func
, file):
5194 """Overrriden from TypeHandler."""
5197 def WriteFormatTest(self
, func
, file):
5198 """Overrriden from TypeHandler."""
5199 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
5201 def WriteImmediateFormatTest(self
, func
, file):
5202 """Overrriden from TypeHandler."""
5203 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
5205 def WriteBucketFormatTest(self
, func
, file):
5206 """Overrriden from TypeHandler."""
5207 file.Write("// TODO(gman): Write test for %s\n" % func
.name
)
5211 class ManualHandler(CustomHandler
):
5212 """Handler for commands who's handlers must be written by hand."""
5215 CustomHandler
.__init
__(self
)
5217 def InitFunction(self
, func
):
5218 """Overrriden from TypeHandler."""
5219 if (func
.name
== 'CompressedTexImage2DBucket' or
5220 func
.name
== 'CompressedTexImage3DBucket'):
5221 func
.cmd_args
= func
.cmd_args
[:-1]
5222 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5224 CustomHandler
.InitFunction(self
, func
)
5226 def WriteServiceImplementation(self
, func
, file):
5227 """Overrriden from TypeHandler."""
5230 def WriteBucketServiceImplementation(self
, func
, file):
5231 """Overrriden from TypeHandler."""
5234 def WriteServiceUnitTest(self
, func
, file, *extras
):
5235 """Overrriden from TypeHandler."""
5236 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5238 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5239 """Overrriden from TypeHandler."""
5240 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5242 def WriteImmediateServiceImplementation(self
, func
, file):
5243 """Overrriden from TypeHandler."""
5246 def WriteImmediateFormatTest(self
, func
, file):
5247 """Overrriden from TypeHandler."""
5248 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
5250 def WriteGLES2Implementation(self
, func
, file):
5251 """Overrriden from TypeHandler."""
5252 if func
.GetInfo('impl_func'):
5253 super(ManualHandler
, self
).WriteGLES2Implementation(func
, file)
5255 def WriteGLES2ImplementationHeader(self
, func
, file):
5256 """Overrriden from TypeHandler."""
5257 file.Write("%s %s(%s) override;\n" %
5258 (func
.return_type
, func
.original_name
,
5259 func
.MakeTypedOriginalArgString("")))
5262 def WriteImmediateCmdGetTotalSize(self
, func
, file):
5263 """Overrriden from TypeHandler."""
5264 # TODO(gman): Move this data to _FUNCTION_INFO?
5265 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, file)
5268 class DataHandler(TypeHandler
):
5269 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5270 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5272 TypeHandler
.__init
__(self
)
5274 def InitFunction(self
, func
):
5275 """Overrriden from TypeHandler."""
5276 if (func
.name
== 'CompressedTexSubImage2DBucket' or
5277 func
.name
== 'CompressedTexSubImage3DBucket'):
5278 func
.cmd_args
= func
.cmd_args
[:-1]
5279 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5281 def WriteGetDataSizeCode(self
, func
, file):
5282 """Overrriden from TypeHandler."""
5283 # TODO(gman): Move this data to _FUNCTION_INFO?
5285 if name
.endswith("Immediate"):
5287 if name
== 'BufferData' or name
== 'BufferSubData':
5288 file.Write(" uint32_t data_size = size;\n")
5289 elif (name
== 'CompressedTexImage2D' or
5290 name
== 'CompressedTexSubImage2D' or
5291 name
== 'CompressedTexImage3D' or
5292 name
== 'CompressedTexSubImage3D'):
5293 file.Write(" uint32_t data_size = imageSize;\n")
5294 elif (name
== 'CompressedTexSubImage2DBucket' or
5295 name
== 'CompressedTexSubImage3DBucket'):
5296 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5297 file.Write(" uint32_t data_size = bucket->size();\n")
5298 file.Write(" GLsizei imageSize = data_size;\n")
5299 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
5300 code
= """ uint32_t data_size;
5301 if (!GLES2Util::ComputeImageDataSize(
5302 width, height, format, type, unpack_alignment_, &data_size)) {
5303 return error::kOutOfBounds;
5309 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5311 def WriteImmediateCmdGetTotalSize(self
, func
, file):
5312 """Overrriden from TypeHandler."""
5315 def WriteImmediateCmdSizeTest(self
, func
, file):
5316 """Overrriden from TypeHandler."""
5317 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
5319 def WriteImmediateCmdInit(self
, func
, file):
5320 """Overrriden from TypeHandler."""
5321 file.Write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5322 self
.WriteImmediateCmdGetTotalSize(func
, file)
5323 file.Write(" SetHeader(total_size);\n")
5324 args
= func
.GetCmdArgs()
5326 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5330 def WriteImmediateCmdSet(self
, func
, file):
5331 """Overrriden from TypeHandler."""
5332 copy_args
= func
.MakeCmdArgString("_", False)
5333 file.Write(" void* Set(void* cmd%s) {\n" %
5334 func
.MakeTypedCmdArgString("_", True))
5335 self
.WriteImmediateCmdGetTotalSize(func
, file)
5336 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5337 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5338 "cmd, total_size);\n")
5342 def WriteImmediateFormatTest(self
, func
, file):
5343 """Overrriden from TypeHandler."""
5344 # TODO(gman): Remove this exception.
5345 file.Write("// TODO(gman): Implement test for %s\n" % func
.name
)
5348 def WriteServiceUnitTest(self
, func
, file, *extras
):
5349 """Overrriden from TypeHandler."""
5350 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5352 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5353 """Overrriden from TypeHandler."""
5354 file.Write("// TODO(gman): %s\n\n" % func
.name
)
5356 def WriteBucketServiceImplementation(self
, func
, file):
5357 """Overrriden from TypeHandler."""
5358 if ((not func
.name
== 'CompressedTexSubImage2DBucket') and
5359 (not func
.name
== 'CompressedTexSubImage3DBucket')):
5360 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, file)
5363 class BindHandler(TypeHandler
):
5364 """Handler for glBind___ type functions."""
5367 TypeHandler
.__init
__(self
)
5369 def WriteServiceUnitTest(self
, func
, file, *extras
):
5370 """Overrriden from TypeHandler."""
5372 if len(func
.GetOriginalArgs()) == 1:
5374 TEST_P(%(test_name)s, %(name)sValidArgs) {
5375 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5376 SpecializedSetup<cmds::%(name)s, 0>(true);
5378 cmd.Init(%(args)s);"""
5381 decoder_->set_unsafe_es3_apis_enabled(true);
5382 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5383 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5384 decoder_->set_unsafe_es3_apis_enabled(false);
5385 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5390 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5391 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5394 if func
.GetInfo("gen_func"):
5396 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5397 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5398 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5399 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5400 SpecializedSetup<cmds::%(name)s, 0>(true);
5402 cmd.Init(kNewClientId);
5403 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5404 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5405 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5408 self
.WriteValidUnitTest(func
, file, valid_test
, {
5409 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
5410 'gl_gen_func_name': func
.GetInfo("gen_func"),
5414 TEST_P(%(test_name)s, %(name)sValidArgs) {
5415 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5416 SpecializedSetup<cmds::%(name)s, 0>(true);
5418 cmd.Init(%(args)s);"""
5421 decoder_->set_unsafe_es3_apis_enabled(true);
5422 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5423 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5424 decoder_->set_unsafe_es3_apis_enabled(false);
5425 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5430 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5431 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5434 if func
.GetInfo("gen_func"):
5436 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5438 %(gl_func_name)s(%(gl_args_with_new_id)s));
5439 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5440 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5441 SpecializedSetup<cmds::%(name)s, 0>(true);
5443 cmd.Init(%(args_with_new_id)s);"""
5446 decoder_->set_unsafe_es3_apis_enabled(true);
5447 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5448 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5449 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5450 decoder_->set_unsafe_es3_apis_enabled(false);
5451 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5456 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5457 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5458 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5462 gl_args_with_new_id
= []
5463 args_with_new_id
= []
5464 for arg
in func
.GetOriginalArgs():
5465 if hasattr(arg
, 'resource_type'):
5466 gl_args_with_new_id
.append('kNewServiceId')
5467 args_with_new_id
.append('kNewClientId')
5469 gl_args_with_new_id
.append(arg
.GetValidGLArg(func
))
5470 args_with_new_id
.append(arg
.GetValidArg(func
))
5471 self
.WriteValidUnitTest(func
, file, valid_test
, {
5472 'args_with_new_id': ", ".join(args_with_new_id
),
5473 'gl_args_with_new_id': ", ".join(gl_args_with_new_id
),
5474 'resource_type': func
.GetResourceIdArg().resource_type
,
5475 'gl_gen_func_name': func
.GetInfo("gen_func"),
5479 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5480 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5481 SpecializedSetup<cmds::%(name)s, 0>(false);
5484 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5487 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
5489 def WriteGLES2Implementation(self
, func
, file):
5490 """Writes the GLES2 Implemention."""
5492 impl_func
= func
.GetInfo('impl_func')
5493 impl_decl
= func
.GetInfo('impl_decl')
5495 if (func
.can_auto_generate
and
5496 (impl_func
== None or impl_func
== True) and
5497 (impl_decl
== None or impl_decl
== True)):
5499 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5500 (func
.return_type
, func
.original_name
,
5501 func
.MakeTypedOriginalArgString("")))
5502 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5503 func
.WriteDestinationInitalizationValidation(file)
5504 self
.WriteClientGLCallLog(func
, file)
5505 for arg
in func
.GetOriginalArgs():
5506 arg
.WriteClientSideValidationCode(file, func
)
5508 code
= """ if (Is%(type)sReservedId(%(id)s)) {
5509 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5512 %(name)sHelper(%(arg_string)s);
5517 name_arg
= func
.GetResourceIdArg()
5520 'arg_string': func
.MakeOriginalArgString(""),
5521 'id': name_arg
.name
,
5522 'type': name_arg
.resource_type
,
5523 'lc_type': name_arg
.resource_type
.lower(),
5526 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5527 """Overrriden from TypeHandler."""
5528 client_test
= func
.GetInfo('client_test')
5529 if client_test
== False:
5532 TEST_F(GLES2ImplementationTest, %(name)s) {
5537 expected.cmd.Init(%(cmd_args)s);
5539 gl_->%(name)s(%(args)s);
5540 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5541 if not func
.IsUnsafe():
5544 gl_->%(name)s(%(args)s);
5545 EXPECT_TRUE(NoCommandsWritten());"""
5550 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
5553 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
5558 'args': ", ".join(gl_arg_strings
),
5559 'cmd_args': ", ".join(cmd_arg_strings
),
5563 class GENnHandler(TypeHandler
):
5564 """Handler for glGen___ type functions."""
5567 TypeHandler
.__init
__(self
)
5569 def InitFunction(self
, func
):
5570 """Overrriden from TypeHandler."""
5573 def WriteGetDataSizeCode(self
, func
, file):
5574 """Overrriden from TypeHandler."""
5575 code
= """ uint32_t data_size;
5576 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5577 return error::kOutOfBounds;
5582 def WriteHandlerImplementation (self
, func
, file):
5583 """Overrriden from TypeHandler."""
5584 file.Write(" if (!%sHelper(n, %s)) {\n"
5585 " return error::kInvalidArguments;\n"
5587 (func
.name
, func
.GetLastOriginalArg().name
))
5589 def WriteImmediateHandlerImplementation(self
, func
, file):
5590 """Overrriden from TypeHandler."""
5592 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5593 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5594 return error::kInvalidArguments;
5597 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5598 gl%(func_name)s(n, service_ids.get());
5599 for (GLsizei ii = 0; ii < n; ++ii) {
5600 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5602 """ % { 'func_name': func
.original_name
,
5603 'last_arg_name': func
.GetLastOriginalArg().name
,
5604 'resource_name': func
.GetInfo('resource_type') })
5606 file.Write(" if (!%sHelper(n, %s)) {\n"
5607 " return error::kInvalidArguments;\n"
5609 (func
.original_name
, func
.GetLastOriginalArg().name
))
5611 def WriteGLES2Implementation(self
, func
, file):
5612 """Overrriden from TypeHandler."""
5613 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
5614 for (GLsizei i = 0; i < n; ++i) {
5615 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5617 });""" % func
.GetOriginalArgs()[1].name
)
5619 'log_code': log_code
,
5620 'return_type': func
.return_type
,
5621 'name': func
.original_name
,
5622 'typed_args': func
.MakeTypedOriginalArgString(""),
5623 'args': func
.MakeOriginalArgString(""),
5624 'resource_types': func
.GetInfo('resource_types'),
5625 'count_name': func
.GetOriginalArgs()[0].name
,
5628 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5630 func
.WriteDestinationInitalizationValidation(file)
5631 self
.WriteClientGLCallLog(func
, file)
5632 for arg
in func
.GetOriginalArgs():
5633 arg
.WriteClientSideValidationCode(file, func
)
5634 not_shared
= func
.GetInfo('not_shared')
5638 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5639 for (GLsizei ii = 0; ii < n; ++ii)
5640 %s[ii] = id_allocator->AllocateID();""" %
5641 (func
.GetInfo('resource_types'), func
.GetOriginalArgs()[1].name
))
5643 alloc_code
= (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5644 MakeIds(this, 0, %(args)s);""" % args
)
5645 args
['alloc_code'] = alloc_code
5647 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5649 %(name)sHelper(%(args)s);
5650 helper_->%(name)sImmediate(%(args)s);
5651 if (share_group_->bind_generates_resource())
5652 helper_->CommandBufferHelper::Flush();
5658 file.Write(code
% args
)
5660 def WriteGLES2ImplementationUnitTest(self
, func
, file):
5661 """Overrriden from TypeHandler."""
5663 TEST_F(GLES2ImplementationTest, %(name)s) {
5664 GLuint ids[2] = { 0, };
5666 cmds::%(name)sImmediate gen;
5670 expected.gen.Init(arraysize(ids), &ids[0]);
5671 expected.data[0] = k%(types)sStartId;
5672 expected.data[1] = k%(types)sStartId + 1;
5673 gl_->%(name)s(arraysize(ids), &ids[0]);
5674 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5675 EXPECT_EQ(k%(types)sStartId, ids[0]);
5676 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5681 'types': func
.GetInfo('resource_types'),
5684 def WriteServiceUnitTest(self
, func
, file, *extras
):
5685 """Overrriden from TypeHandler."""
5687 TEST_P(%(test_name)s, %(name)sValidArgs) {
5688 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5689 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5690 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5691 SpecializedSetup<cmds::%(name)s, 0>(true);
5694 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5695 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5699 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5700 EXPECT_EQ(kNewServiceId, service_id)
5705 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5708 self
.WriteValidUnitTest(func
, file, valid_test
, {
5709 'resource_name': func
.GetInfo('resource_type'),
5712 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5713 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5714 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5715 SpecializedSetup<cmds::%(name)s, 0>(false);
5718 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5721 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5722 'resource_name': func
.GetInfo('resource_type').lower(),
5725 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
5726 """Overrriden from TypeHandler."""
5728 TEST_P(%(test_name)s, %(name)sValidArgs) {
5729 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5730 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5731 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5732 GLuint temp = kNewClientId;
5733 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5736 decoder_->set_unsafe_es3_apis_enabled(true);"""
5738 cmd->Init(1, &temp);
5739 EXPECT_EQ(error::kNoError,
5740 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5741 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5745 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5746 EXPECT_EQ(kNewServiceId, service_id);
5747 decoder_->set_unsafe_es3_apis_enabled(false);
5748 EXPECT_EQ(error::kUnknownCommand,
5749 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5754 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5757 self
.WriteValidUnitTest(func
, file, valid_test
, {
5758 'resource_name': func
.GetInfo('resource_type'),
5761 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5762 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5763 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5764 SpecializedSetup<cmds::%(name)s, 0>(false);
5765 cmd->Init(1, &client_%(resource_name)s_id_);"""
5768 decoder_->set_unsafe_es3_apis_enabled(true);
5769 EXPECT_EQ(error::kInvalidArguments,
5770 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5771 decoder_->set_unsafe_es3_apis_enabled(false);
5776 EXPECT_EQ(error::kInvalidArguments,
5777 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5780 self
.WriteValidUnitTest(func
, file, invalid_test
, {
5781 'resource_name': func
.GetInfo('resource_type').lower(),
5784 def WriteImmediateCmdComputeSize(self
, func
, file):
5785 """Overrriden from TypeHandler."""
5786 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5788 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5791 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5792 file.Write(" return static_cast<uint32_t>(\n")
5793 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5797 def WriteImmediateCmdSetHeader(self
, func
, file):
5798 """Overrriden from TypeHandler."""
5799 file.Write(" void SetHeader(GLsizei n) {\n")
5800 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5804 def WriteImmediateCmdInit(self
, func
, file):
5805 """Overrriden from TypeHandler."""
5806 last_arg
= func
.GetLastOriginalArg()
5807 file.Write(" void Init(%s, %s _%s) {\n" %
5808 (func
.MakeTypedCmdArgString("_"),
5809 last_arg
.type, last_arg
.name
))
5810 file.Write(" SetHeader(_n);\n")
5811 args
= func
.GetCmdArgs()
5813 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5814 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5815 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
5819 def WriteImmediateCmdSet(self
, func
, file):
5820 """Overrriden from TypeHandler."""
5821 last_arg
= func
.GetLastOriginalArg()
5822 copy_args
= func
.MakeCmdArgString("_", False)
5823 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5824 (func
.MakeTypedCmdArgString("_", True),
5825 last_arg
.type, last_arg
.name
))
5826 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5827 (copy_args
, last_arg
.name
))
5828 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5829 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5834 def WriteImmediateCmdHelper(self
, func
, file):
5835 """Overrriden from TypeHandler."""
5836 code
= """ void %(name)s(%(typed_args)s) {
5837 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5838 gles2::cmds::%(name)s* c =
5839 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5848 "typed_args": func
.MakeTypedOriginalArgString(""),
5849 "args": func
.MakeOriginalArgString(""),
5852 def WriteImmediateFormatTest(self
, func
, file):
5853 """Overrriden from TypeHandler."""
5854 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5855 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5856 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5857 (func
.name
, func
.name
))
5858 file.Write(" void* next_cmd = cmd.Set(\n")
5859 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5860 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5862 file.Write(" cmd.header.command);\n")
5863 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5864 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5865 file.Write(" cmd.header.size * 4u);\n")
5866 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5867 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5868 file.Write(" next_cmd, sizeof(cmd) +\n")
5869 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5870 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5875 class CreateHandler(TypeHandler
):
5876 """Handler for glCreate___ type functions."""
5879 TypeHandler
.__init
__(self
)
5881 def InitFunction(self
, func
):
5882 """Overrriden from TypeHandler."""
5883 func
.AddCmdArg(Argument("client_id", 'uint32_t'))
5885 def __GetResourceType(self
, func
):
5886 if func
.return_type
== "GLsync":
5889 return func
.name
[6:] # Create*
5891 def WriteServiceUnitTest(self
, func
, file, *extras
):
5892 """Overrriden from TypeHandler."""
5894 TEST_P(%(test_name)s, %(name)sValidArgs) {
5895 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5896 .WillOnce(Return(%(const_service_id)s));
5897 SpecializedSetup<cmds::%(name)s, 0>(true);
5899 cmd.Init(%(args)s%(comma)skNewClientId);"""
5902 decoder_->set_unsafe_es3_apis_enabled(true);"""
5904 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5905 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5908 %(return_type)s service_id = 0;
5909 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
5910 EXPECT_EQ(%(const_service_id)s, service_id);
5911 decoder_->set_unsafe_es3_apis_enabled(false);
5912 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5917 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
5922 for arg
in func
.GetOriginalArgs():
5923 if not arg
.IsConstant():
5927 if func
.return_type
== 'GLsync':
5928 id_type_cast
= ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
5929 "<GLsync>(kNewServiceId);\n ")
5930 const_service_id
= "kNewServiceIdGLuint"
5933 const_service_id
= "kNewServiceId"
5934 self
.WriteValidUnitTest(func
, file, valid_test
, {
5936 'resource_type': self
.__GetResourceType
(func
),
5937 'return_type': func
.return_type
,
5938 'id_type_cast': id_type_cast
,
5939 'const_service_id': const_service_id
,
5942 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5943 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5944 SpecializedSetup<cmds::%(name)s, 0>(false);
5946 cmd.Init(%(args)s%(comma)skNewClientId);
5947 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
5950 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
5954 def WriteHandlerImplementation (self
, func
, file):
5955 """Overrriden from TypeHandler."""
5957 code
= """ uint32_t client_id = c.client_id;
5958 %(return_type)s service_id = 0;
5959 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
5960 return error::kInvalidArguments;
5962 service_id = %(gl_func_name)s(%(gl_args)s);
5964 group_->Add%(resource_name)sId(client_id, service_id);
5968 code
= """ uint32_t client_id = c.client_id;
5969 if (Get%(resource_name)s(client_id)) {
5970 return error::kInvalidArguments;
5972 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
5974 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
5978 'resource_name': self
.__GetResourceType
(func
),
5979 'return_type': func
.return_type
,
5980 'gl_func_name': func
.GetGLFunctionName(),
5981 'gl_args': func
.MakeOriginalArgString(""),
5982 'gl_args_with_comma': func
.MakeOriginalArgString("", True) })
5984 def WriteGLES2Implementation(self
, func
, file):
5985 """Overrriden from TypeHandler."""
5986 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5987 (func
.return_type
, func
.original_name
,
5988 func
.MakeTypedOriginalArgString("")))
5989 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5990 func
.WriteDestinationInitalizationValidation(file)
5991 self
.WriteClientGLCallLog(func
, file)
5992 for arg
in func
.GetOriginalArgs():
5993 arg
.WriteClientSideValidationCode(file, func
)
5994 file.Write(" GLuint client_id;\n")
5995 if func
.return_type
== "GLsync":
5997 " GetIdHandler(id_namespaces::kSyncs)->\n")
6000 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
6001 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
6002 file.Write(" helper_->%s(%s);\n" %
6003 (func
.name
, func
.MakeCmdArgString("")))
6004 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
6005 file.Write(" CheckGLError();\n")
6006 if func
.return_type
== "GLsync":
6007 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
6009 file.Write(" return client_id;\n")
6014 class DeleteHandler(TypeHandler
):
6015 """Handler for glDelete___ single resource type functions."""
6018 TypeHandler
.__init
__(self
)
6020 def WriteServiceImplementation(self
, func
, file):
6021 """Overrriden from TypeHandler."""
6023 TypeHandler
.WriteServiceImplementation(self
, func
, file)
6024 # HandleDeleteShader and HandleDeleteProgram are manually written.
6027 def WriteGLES2Implementation(self
, func
, file):
6028 """Overrriden from TypeHandler."""
6029 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6030 (func
.return_type
, func
.original_name
,
6031 func
.MakeTypedOriginalArgString("")))
6032 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6033 func
.WriteDestinationInitalizationValidation(file)
6034 self
.WriteClientGLCallLog(func
, file)
6035 for arg
in func
.GetOriginalArgs():
6036 arg
.WriteClientSideValidationCode(file, func
)
6038 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
6039 file.Write(" %sHelper(%s);\n" %
6040 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
6041 file.Write(" CheckGLError();\n")
6045 def WriteHandlerImplementation (self
, func
, file):
6046 """Overrriden from TypeHandler."""
6047 assert len(func
.GetOriginalArgs()) == 1
6048 arg
= func
.GetOriginalArgs()[0]
6050 file.Write(""" %(arg_type)s service_id = 0;
6051 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
6052 glDelete%(resource_type)s(service_id);
6053 group_->Remove%(resource_type)sId(%(arg_name)s);
6056 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
6058 """ % { 'resource_type': func
.GetInfo('resource_type'),
6059 'arg_name': arg
.name
,
6060 'arg_type': arg
.type,
6061 'func_name': func
.original_name
})
6063 file.Write(" %sHelper(%s);\n" % (func
.original_name
, arg
.name
))
6065 class DELnHandler(TypeHandler
):
6066 """Handler for glDelete___ type functions."""
6069 TypeHandler
.__init
__(self
)
6071 def WriteGetDataSizeCode(self
, func
, file):
6072 """Overrriden from TypeHandler."""
6073 code
= """ uint32_t data_size;
6074 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6075 return error::kOutOfBounds;
6080 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6081 """Overrriden from TypeHandler."""
6083 TEST_F(GLES2ImplementationTest, %(name)s) {
6084 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6086 cmds::%(name)sImmediate del;
6090 expected.del.Init(arraysize(ids), &ids[0]);
6091 expected.data[0] = k%(types)sStartId;
6092 expected.data[1] = k%(types)sStartId + 1;
6093 gl_->%(name)s(arraysize(ids), &ids[0]);
6094 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6099 'types': func
.GetInfo('resource_types'),
6102 def WriteServiceUnitTest(self
, func
, file, *extras
):
6103 """Overrriden from TypeHandler."""
6105 TEST_P(%(test_name)s, %(name)sValidArgs) {
6108 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6110 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6111 SpecializedSetup<cmds::%(name)s, 0>(true);
6114 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6115 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6117 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6120 self
.WriteValidUnitTest(func
, file, valid_test
, {
6121 'resource_name': func
.GetInfo('resource_type').lower(),
6122 'upper_resource_name': func
.GetInfo('resource_type'),
6125 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6126 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6127 SpecializedSetup<cmds::%(name)s, 0>(false);
6130 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6133 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
6135 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6136 """Overrriden from TypeHandler."""
6138 TEST_P(%(test_name)s, %(name)sValidArgs) {
6141 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6143 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6144 SpecializedSetup<cmds::%(name)s, 0>(true);
6145 cmd.Init(1, &client_%(resource_name)s_id_);"""
6148 decoder_->set_unsafe_es3_apis_enabled(true);"""
6150 EXPECT_EQ(error::kNoError,
6151 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6152 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6155 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6156 client_%(resource_name)s_id_, NULL));
6157 decoder_->set_unsafe_es3_apis_enabled(false);
6158 EXPECT_EQ(error::kUnknownCommand,
6159 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6165 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6168 self
.WriteValidUnitTest(func
, file, valid_test
, {
6169 'resource_name': func
.GetInfo('resource_type').lower(),
6170 'upper_resource_name': func
.GetInfo('resource_type'),
6173 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6174 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6175 SpecializedSetup<cmds::%(name)s, 0>(false);
6176 GLuint temp = kInvalidClientId;
6177 cmd.Init(1, &temp);"""
6180 decoder_->set_unsafe_es3_apis_enabled(true);
6181 EXPECT_EQ(error::kNoError,
6182 ExecuteImmediateCmd(cmd, sizeof(temp)));
6183 decoder_->set_unsafe_es3_apis_enabled(false);
6184 EXPECT_EQ(error::kUnknownCommand,
6185 ExecuteImmediateCmd(cmd, sizeof(temp)));
6190 EXPECT_EQ(error::kNoError,
6191 ExecuteImmediateCmd(cmd, sizeof(temp)));
6194 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
6196 def WriteHandlerImplementation (self
, func
, file):
6197 """Overrriden from TypeHandler."""
6198 file.Write(" %sHelper(n, %s);\n" %
6199 (func
.name
, func
.GetLastOriginalArg().name
))
6201 def WriteImmediateHandlerImplementation (self
, func
, file):
6202 """Overrriden from TypeHandler."""
6204 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6205 GLuint service_id = 0;
6206 if (group_->Get%(resource_type)sServiceId(
6207 %(last_arg_name)s[ii], &service_id)) {
6208 glDelete%(resource_type)ss(1, &service_id);
6209 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6212 """ % { 'resource_type': func
.GetInfo('resource_type'),
6213 'last_arg_name': func
.GetLastOriginalArg().name
})
6215 file.Write(" %sHelper(n, %s);\n" %
6216 (func
.original_name
, func
.GetLastOriginalArg().name
))
6218 def WriteGLES2Implementation(self
, func
, file):
6219 """Overrriden from TypeHandler."""
6220 impl_decl
= func
.GetInfo('impl_decl')
6221 if impl_decl
== None or impl_decl
== True:
6223 'return_type': func
.return_type
,
6224 'name': func
.original_name
,
6225 'typed_args': func
.MakeTypedOriginalArgString(""),
6226 'args': func
.MakeOriginalArgString(""),
6227 'resource_type': func
.GetInfo('resource_type').lower(),
6228 'count_name': func
.GetOriginalArgs()[0].name
,
6231 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6233 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6234 func
.WriteDestinationInitalizationValidation(file)
6235 self
.WriteClientGLCallLog(func
, file)
6236 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6237 for (GLsizei i = 0; i < n; ++i) {
6238 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6241 """ % func
.GetOriginalArgs()[1].name
)
6242 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6243 for (GLsizei i = 0; i < n; ++i) {
6247 """ % func
.GetOriginalArgs()[1].name
)
6248 for arg
in func
.GetOriginalArgs():
6249 arg
.WriteClientSideValidationCode(file, func
)
6250 code
= """ %(name)sHelper(%(args)s);
6255 file.Write(code
% args
)
6257 def WriteImmediateCmdComputeSize(self
, func
, file):
6258 """Overrriden from TypeHandler."""
6259 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6261 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6264 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
6265 file.Write(" return static_cast<uint32_t>(\n")
6266 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6270 def WriteImmediateCmdSetHeader(self
, func
, file):
6271 """Overrriden from TypeHandler."""
6272 file.Write(" void SetHeader(GLsizei n) {\n")
6273 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6277 def WriteImmediateCmdInit(self
, func
, file):
6278 """Overrriden from TypeHandler."""
6279 last_arg
= func
.GetLastOriginalArg()
6280 file.Write(" void Init(%s, %s _%s) {\n" %
6281 (func
.MakeTypedCmdArgString("_"),
6282 last_arg
.type, last_arg
.name
))
6283 file.Write(" SetHeader(_n);\n")
6284 args
= func
.GetCmdArgs()
6286 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6287 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6288 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
6292 def WriteImmediateCmdSet(self
, func
, file):
6293 """Overrriden from TypeHandler."""
6294 last_arg
= func
.GetLastOriginalArg()
6295 copy_args
= func
.MakeCmdArgString("_", False)
6296 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6297 (func
.MakeTypedCmdArgString("_", True),
6298 last_arg
.type, last_arg
.name
))
6299 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6300 (copy_args
, last_arg
.name
))
6301 file.Write(" const uint32_t size = ComputeSize(_n);\n")
6302 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6307 def WriteImmediateCmdHelper(self
, func
, file):
6308 """Overrriden from TypeHandler."""
6309 code
= """ void %(name)s(%(typed_args)s) {
6310 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6311 gles2::cmds::%(name)s* c =
6312 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6321 "typed_args": func
.MakeTypedOriginalArgString(""),
6322 "args": func
.MakeOriginalArgString(""),
6325 def WriteImmediateFormatTest(self
, func
, file):
6326 """Overrriden from TypeHandler."""
6327 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6328 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
6329 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6330 (func
.name
, func
.name
))
6331 file.Write(" void* next_cmd = cmd.Set(\n")
6332 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6333 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6335 file.Write(" cmd.header.command);\n")
6336 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6337 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6338 file.Write(" cmd.header.size * 4u);\n")
6339 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6340 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6341 file.Write(" next_cmd, sizeof(cmd) +\n")
6342 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6343 file.Write(" // TODO(gman): Check that ids were inserted;\n")
6348 class GETnHandler(TypeHandler
):
6349 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6352 TypeHandler
.__init
__(self
)
6354 def NeedsDataTransferFunction(self
, func
):
6355 """Overriden from TypeHandler."""
6358 def WriteServiceImplementation(self
, func
, file):
6359 """Overrriden from TypeHandler."""
6360 self
.WriteServiceHandlerFunctionHeader(func
, file)
6361 last_arg
= func
.GetLastOriginalArg()
6362 # All except shm_id and shm_offset.
6363 all_but_last_args
= func
.GetCmdArgs()[:-2]
6364 for arg
in all_but_last_args
:
6365 arg
.WriteGetCode(file)
6367 code
= """ typedef cmds::%(func_name)s::Result Result;
6368 GLsizei num_values = 0;
6369 GetNumValuesReturnedForGLGet(pname, &num_values);
6370 Result* result = GetSharedMemoryAs<Result*>(
6371 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6372 Result::ComputeSize(num_values));
6373 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6376 'last_arg_type': last_arg
.type,
6377 'last_arg_name': last_arg
.name
,
6378 'func_name': func
.name
,
6380 func
.WriteHandlerValidation(file)
6381 code
= """ // Check that the client initialized the result.
6382 if (result->size != 0) {
6383 return error::kInvalidArguments;
6386 shadowed
= func
.GetInfo('shadowed')
6388 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
6390 func
.WriteHandlerImplementation(file)
6392 code
= """ result->SetNumResults(num_values);
6393 return error::kNoError;
6397 code
= """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
6398 if (error == GL_NO_ERROR) {
6399 result->SetNumResults(num_values);
6401 return error::kNoError;
6405 file.Write(code
% {'func_name': func
.name
})
6407 def WriteGLES2Implementation(self
, func
, file):
6408 """Overrriden from TypeHandler."""
6409 impl_decl
= func
.GetInfo('impl_decl')
6410 if impl_decl
== None or impl_decl
== True:
6411 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6412 (func
.return_type
, func
.original_name
,
6413 func
.MakeTypedOriginalArgString("")))
6414 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6415 func
.WriteDestinationInitalizationValidation(file)
6416 self
.WriteClientGLCallLog(func
, file)
6417 for arg
in func
.GetOriginalArgs():
6418 arg
.WriteClientSideValidationCode(file, func
)
6419 all_but_last_args
= func
.GetOriginalArgs()[:-1]
6421 has_length_arg
= False
6422 for arg
in all_but_last_args
:
6423 if arg
.type == 'GLsync':
6424 args
.append('ToGLuint(%s)' % arg
.name
)
6425 elif arg
.name
.endswith('size') and arg
.type == 'GLsizei':
6427 elif arg
.name
== 'length':
6428 has_length_arg
= True
6431 args
.append(arg
.name
)
6432 arg_string
= ", ".join(args
)
6436 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()]))
6437 self
.WriteTraceEvent(func
, file)
6438 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6441 typedef cmds::%(func_name)s::Result Result;
6442 Result* result = GetResultAs<Result*>();
6446 result->SetNumResults(0);
6447 helper_->%(func_name)s(%(arg_string)s,
6448 GetResultShmId(), GetResultShmOffset());
6450 result->CopyResult(%(last_arg_name)s);
6451 GPU_CLIENT_LOG_CODE_BLOCK({
6452 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6453 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6459 *length = result->GetNumResults();
6466 'func_name': func
.name
,
6467 'arg_string': arg_string
,
6468 'all_arg_string': all_arg_string
,
6469 'last_arg_name': func
.GetLastOriginalArg().name
,
6472 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6473 """Writes the GLES2 Implemention unit test."""
6475 TEST_F(GLES2ImplementationTest, %(name)s) {
6479 typedef cmds::%(name)s::Result::Type ResultType;
6480 ResultType result = 0;
6482 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6483 sizeof(uint32_t) + sizeof(ResultType));
6484 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6485 EXPECT_CALL(*command_buffer(), OnFlush())
6486 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6487 .RetiresOnSaturation();
6488 gl_->%(name)s(%(args)s, &result);
6489 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6490 EXPECT_EQ(static_cast<ResultType>(1), result);
6493 first_cmd_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func
)
6494 if not first_cmd_arg
:
6497 first_gl_arg
= func
.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6500 cmd_arg_strings
= [first_cmd_arg
]
6501 for arg
in func
.GetCmdArgs()[1:-2]:
6502 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
6503 gl_arg_strings
= [first_gl_arg
]
6504 for arg
in func
.GetOriginalArgs()[1:-1]:
6505 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
6509 'args': ", ".join(gl_arg_strings
),
6510 'cmd_args': ", ".join(cmd_arg_strings
),
6513 def WriteServiceUnitTest(self
, func
, file, *extras
):
6514 """Overrriden from TypeHandler."""
6516 TEST_P(%(test_name)s, %(name)sValidArgs) {
6517 EXPECT_CALL(*gl_, GetError())
6518 .WillOnce(Return(GL_NO_ERROR))
6519 .WillOnce(Return(GL_NO_ERROR))
6520 .RetiresOnSaturation();
6521 SpecializedSetup<cmds::%(name)s, 0>(true);
6522 typedef cmds::%(name)s::Result Result;
6523 Result* result = static_cast<Result*>(shared_memory_address_);
6524 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6527 cmd.Init(%(cmd_args)s);"""
6530 decoder_->set_unsafe_es3_apis_enabled(true);"""
6532 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6533 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6535 result->GetNumResults());
6536 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6539 decoder_->set_unsafe_es3_apis_enabled(false);
6540 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6545 cmd_arg_strings
= []
6547 for arg
in func
.GetOriginalArgs()[:-1]:
6548 if arg
.name
== 'length':
6549 gl_arg_value
= 'nullptr'
6550 elif arg
.name
.endswith('size'):
6551 gl_arg_value
= ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6553 elif arg
.type == 'GLsync':
6554 gl_arg_value
= 'reinterpret_cast<GLsync>(kServiceSyncId)'
6556 gl_arg_value
= arg
.GetValidGLArg(func
)
6557 gl_arg_strings
.append(gl_arg_value
)
6558 if arg
.name
== 'pname':
6559 valid_pname
= gl_arg_value
6560 if arg
.name
.endswith('size') or arg
.name
== 'length':
6562 if arg
.type == 'GLsync':
6563 arg_value
= 'client_sync_id_'
6565 arg_value
= arg
.GetValidArg(func
)
6566 cmd_arg_strings
.append(arg_value
)
6567 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
6568 gl_arg_strings
.append("_")
6570 gl_arg_strings
.append("result->GetData()")
6571 cmd_arg_strings
.append("shared_memory_id_")
6572 cmd_arg_strings
.append("shared_memory_offset_")
6574 self
.WriteValidUnitTest(func
, file, valid_test
, {
6575 'local_gl_args': ", ".join(gl_arg_strings
),
6576 'cmd_args': ", ".join(cmd_arg_strings
),
6577 'valid_pname': valid_pname
,
6580 if not func
.IsUnsafe():
6582 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6583 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6584 SpecializedSetup<cmds::%(name)s, 0>(false);
6585 cmds::%(name)s::Result* result =
6586 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6590 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6591 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6594 self
.WriteInvalidUnitTest(func
, file, invalid_test
, *extras
)
6596 class ArrayArgTypeHandler(TypeHandler
):
6597 """Base class for type handlers that handle args that are arrays"""
6600 TypeHandler
.__init
__(self
)
6602 def GetArrayType(self
, func
):
6603 """Returns the type of the element in the element array being PUT to."""
6604 for arg
in func
.GetOriginalArgs():
6606 element_type
= arg
.GetPointedType()
6609 # Special case: array type handler is used for a function that is forwarded
6610 # to the actual array type implementation
6611 element_type
= func
.GetOriginalArgs()[-1].type
6612 assert all(arg
.type == element_type \
6613 for arg
in func
.GetOriginalArgs()[-self
.GetArrayCount(func
):])
6616 def GetArrayCount(self
, func
):
6617 """Returns the count of the elements in the array being PUT to."""
6618 return func
.GetInfo('count')
6620 class PUTHandler(ArrayArgTypeHandler
):
6621 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6624 ArrayArgTypeHandler
.__init
__(self
)
6626 def WriteServiceUnitTest(self
, func
, file, *extras
):
6627 """Writes the service unit test for a command."""
6628 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6629 if func
.GetInfo("first_element_only"):
6631 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()
6633 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
6634 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6635 ", ".join(gl_arg_strings
))
6637 TEST_P(%(test_name)s, %(name)sValidArgs) {
6638 SpecializedSetup<cmds::%(name)s, 0>(true);
6641 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6643 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6644 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6648 'data_type': self
.GetArrayType(func
),
6649 'data_value': func
.GetInfo('data_value') or '0',
6650 'expected_call': expected_call
,
6652 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6655 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6656 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6657 SpecializedSetup<cmds::%(name)s, 0>(false);
6660 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6661 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6664 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6666 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6667 """Writes the service unit test for a command."""
6669 TEST_P(%(test_name)s, %(name)sValidArgs) {
6670 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6671 SpecializedSetup<cmds::%(name)s, 0>(true);
6672 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6673 cmd.Init(%(gl_args)s, &temp[0]);
6676 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6677 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6680 decoder_->set_unsafe_es3_apis_enabled(true);"""
6682 EXPECT_EQ(error::kNoError,
6683 ExecuteImmediateCmd(cmd, sizeof(temp)));
6684 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6687 decoder_->set_unsafe_es3_apis_enabled(false);
6688 EXPECT_EQ(error::kUnknownCommand,
6689 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6694 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6696 gl_any_strings
= ["_"] * len(gl_arg_strings
)
6699 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
6700 'data_type': self
.GetArrayType(func
),
6701 'data_count': self
.GetArrayCount(func
),
6702 'data_value': func
.GetInfo('data_value') or '0',
6703 'gl_args': ", ".join(gl_arg_strings
),
6704 'gl_any_args': ", ".join(gl_any_strings
),
6706 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6709 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6710 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6713 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6717 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6720 SpecializedSetup<cmds::%(name)s, 0>(false);
6721 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6722 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6725 decoder_->set_unsafe_es3_apis_enabled(true);
6726 EXPECT_EQ(error::%(parse_result)s,
6727 ExecuteImmediateCmd(cmd, sizeof(temp)));
6728 decoder_->set_unsafe_es3_apis_enabled(false);
6733 EXPECT_EQ(error::%(parse_result)s,
6734 ExecuteImmediateCmd(cmd, sizeof(temp)));
6738 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
6740 def WriteGetDataSizeCode(self
, func
, file):
6741 """Overrriden from TypeHandler."""
6742 code
= """ uint32_t data_size;
6743 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6744 return error::kOutOfBounds;
6747 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6748 if func
.IsImmediate():
6749 file.Write(" if (data_size > immediate_data_size) {\n")
6750 file.Write(" return error::kOutOfBounds;\n")
6753 def __NeedsToCalcDataCount(self
, func
):
6754 use_count_func
= func
.GetInfo('use_count_func')
6755 return use_count_func
!= None and use_count_func
!= False
6757 def WriteGLES2Implementation(self
, func
, file):
6758 """Overrriden from TypeHandler."""
6759 impl_func
= func
.GetInfo('impl_func')
6760 if (impl_func
!= None and impl_func
!= True):
6762 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6763 (func
.return_type
, func
.original_name
,
6764 func
.MakeTypedOriginalArgString("")))
6765 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6766 func
.WriteDestinationInitalizationValidation(file)
6767 self
.WriteClientGLCallLog(func
, file)
6769 if self
.__NeedsToCalcDataCount
(func
):
6770 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6771 (func
.name
, func
.GetOriginalArgs()[0].name
))
6772 file.Write(" DCHECK_LE(count, %du);\n" % self
.GetArrayCount(func
))
6774 file.Write(" size_t count = %d;" % self
.GetArrayCount(func
))
6775 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
6776 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6777 func
.GetLastOriginalArg().name
)
6778 for arg
in func
.GetOriginalArgs():
6779 arg
.WriteClientSideValidationCode(file, func
)
6780 file.Write(" helper_->%sImmediate(%s);\n" %
6781 (func
.name
, func
.MakeOriginalArgString("")))
6782 file.Write(" CheckGLError();\n")
6786 def WriteGLES2ImplementationUnitTest(self
, func
, file):
6787 """Writes the GLES2 Implemention unit test."""
6788 client_test
= func
.GetInfo('client_test')
6789 if (client_test
!= None and client_test
!= True):
6792 TEST_F(GLES2ImplementationTest, %(name)s) {
6793 %(type)s data[%(count)d] = {0};
6795 cmds::%(name)sImmediate cmd;
6796 %(type)s data[%(count)d];
6799 for (int jj = 0; jj < %(count)d; ++jj) {
6800 data[jj] = static_cast<%(type)s>(jj);
6803 expected.cmd.Init(%(cmd_args)s, &data[0]);
6804 gl_->%(name)s(%(args)s, &data[0]);
6805 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6809 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
6812 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6817 'type': self
.GetArrayType(func
),
6818 'count': self
.GetArrayCount(func
),
6819 'args': ", ".join(gl_arg_strings
),
6820 'cmd_args': ", ".join(cmd_arg_strings
),
6823 def WriteImmediateCmdComputeSize(self
, func
, file):
6824 """Overrriden from TypeHandler."""
6825 file.Write(" static uint32_t ComputeDataSize() {\n")
6826 file.Write(" return static_cast<uint32_t>(\n")
6827 file.Write(" sizeof(%s) * %d);\n" %
6828 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6831 if self
.__NeedsToCalcDataCount
(func
):
6832 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6833 (func
.GetOriginalArgs()[0].type,
6834 func
.GetOriginalArgs()[0].name
))
6835 file.Write(" return static_cast<uint32_t>(\n")
6836 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6837 (self
.GetArrayType(func
), func
.original_name
,
6838 func
.GetOriginalArgs()[0].name
))
6841 file.Write(" static uint32_t ComputeSize() {\n")
6842 file.Write(" return static_cast<uint32_t>(\n")
6844 " sizeof(ValueType) + ComputeDataSize());\n")
6848 def WriteImmediateCmdSetHeader(self
, func
, file):
6849 """Overrriden from TypeHandler."""
6850 file.Write(" void SetHeader() {\n")
6852 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6856 def WriteImmediateCmdInit(self
, func
, file):
6857 """Overrriden from TypeHandler."""
6858 last_arg
= func
.GetLastOriginalArg()
6859 file.Write(" void Init(%s, %s _%s) {\n" %
6860 (func
.MakeTypedCmdArgString("_"),
6861 last_arg
.type, last_arg
.name
))
6862 file.Write(" SetHeader();\n")
6863 args
= func
.GetCmdArgs()
6865 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6866 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6867 if self
.__NeedsToCalcDataCount
(func
):
6868 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
6869 (last_arg
.name
, func
.GetOriginalArgs()[0].name
))
6871 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6872 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6873 ComputeEffectiveDataSize(%(arg)s);
6874 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6875 """ % { 'arg': func
.GetOriginalArgs()[0].name
, })
6877 file.Write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
6881 def WriteImmediateCmdSet(self
, func
, file):
6882 """Overrriden from TypeHandler."""
6883 last_arg
= func
.GetLastOriginalArg()
6884 copy_args
= func
.MakeCmdArgString("_", False)
6885 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6886 (func
.MakeTypedCmdArgString("_", True),
6887 last_arg
.type, last_arg
.name
))
6888 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6889 (copy_args
, last_arg
.name
))
6890 file.Write(" const uint32_t size = ComputeSize();\n")
6891 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6896 def WriteImmediateCmdHelper(self
, func
, file):
6897 """Overrriden from TypeHandler."""
6898 code
= """ void %(name)s(%(typed_args)s) {
6899 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
6900 gles2::cmds::%(name)s* c =
6901 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6910 "typed_args": func
.MakeTypedOriginalArgString(""),
6911 "args": func
.MakeOriginalArgString(""),
6914 def WriteImmediateFormatTest(self
, func
, file):
6915 """Overrriden from TypeHandler."""
6916 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6917 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6918 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
6919 for v
in range(0, self
.GetArrayCount(func
)):
6920 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6921 (self
.GetArrayType(func
), v
))
6923 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6924 (func
.name
, func
.name
))
6925 file.Write(" void* next_cmd = cmd.Set(\n")
6927 args
= func
.GetCmdArgs()
6928 for value
, arg
in enumerate(args
):
6929 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
6930 file.Write(",\n data);\n")
6931 args
= func
.GetCmdArgs()
6932 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
6934 file.Write(" cmd.header.command);\n")
6935 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6936 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
6937 file.Write(" cmd.header.size * 4u);\n")
6938 for value
, arg
in enumerate(args
):
6939 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6940 (arg
.type, value
+ 11, arg
.name
))
6941 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6942 file.Write(" next_cmd, sizeof(cmd) +\n")
6943 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6944 file.Write(" // TODO(gman): Check that data was inserted;\n")
6949 class PUTnHandler(ArrayArgTypeHandler
):
6950 """Handler for PUTn 'glUniform__v' type functions."""
6953 ArrayArgTypeHandler
.__init
__(self
)
6955 def WriteServiceUnitTest(self
, func
, file, *extras
):
6956 """Overridden from TypeHandler."""
6957 ArrayArgTypeHandler
.WriteServiceUnitTest(self
, func
, file, *extras
)
6960 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
6961 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6962 SpecializedSetup<cmds::%(name)s, 0>(true);
6965 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6966 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6971 for count
, arg
in enumerate(func
.GetOriginalArgs()):
6972 # hardcoded to match unit tests.
6974 # the location of the second element of the 2nd uniform.
6975 # defined in GLES2DecoderBase::SetupShaderForUniform
6976 gl_arg_strings
.append("3")
6977 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
6979 # the number of elements that gl will be called with.
6980 gl_arg_strings
.append("3")
6981 # the number of elements requested in the command.
6982 arg_strings
.append("5")
6984 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
6985 if not arg
.IsConstant():
6986 arg_strings
.append(arg
.GetValidArg(func
))
6988 'gl_args': ", ".join(gl_arg_strings
),
6989 'args': ", ".join(arg_strings
),
6991 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
6993 def WriteImmediateServiceUnitTest(self
, func
, file, *extras
):
6994 """Overridden from TypeHandler."""
6996 TEST_P(%(test_name)s, %(name)sValidArgs) {
6997 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7000 %(gl_func_name)s(%(gl_args)s,
7001 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
7002 SpecializedSetup<cmds::%(name)s, 0>(true);
7003 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7004 cmd.Init(%(args)s, &temp[0]);"""
7007 decoder_->set_unsafe_es3_apis_enabled(true);"""
7009 EXPECT_EQ(error::kNoError,
7010 ExecuteImmediateCmd(cmd, sizeof(temp)));
7011 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7014 decoder_->set_unsafe_es3_apis_enabled(false);
7015 EXPECT_EQ(error::kUnknownCommand,
7016 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
7023 for arg
in func
.GetOriginalArgs()[0:-1]:
7024 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
7025 gl_any_strings
.append("_")
7026 if not arg
.IsConstant():
7027 arg_strings
.append(arg
.GetValidArg(func
))
7029 'data_type': self
.GetArrayType(func
),
7030 'data_count': self
.GetArrayCount(func
),
7031 'args': ", ".join(arg_strings
),
7032 'gl_args': ", ".join(gl_arg_strings
),
7033 'gl_any_args': ", ".join(gl_any_strings
),
7035 self
.WriteValidUnitTest(func
, file, valid_test
, extra
, *extras
)
7038 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7039 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7040 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
7041 SpecializedSetup<cmds::%(name)s, 0>(false);
7042 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7043 cmd.Init(%(all_but_last_args)s, &temp[0]);
7044 EXPECT_EQ(error::%(parse_result)s,
7045 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
7048 self
.WriteInvalidUnitTest(func
, file, invalid_test
, extra
, *extras
)
7050 def WriteGetDataSizeCode(self
, func
, file):
7051 """Overrriden from TypeHandler."""
7052 code
= """ uint32_t data_size;
7053 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
7054 return error::kOutOfBounds;
7057 file.Write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7058 if func
.IsImmediate():
7059 file.Write(" if (data_size > immediate_data_size) {\n")
7060 file.Write(" return error::kOutOfBounds;\n")
7063 def WriteGLES2Implementation(self
, func
, file):
7064 """Overrriden from TypeHandler."""
7065 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7066 (func
.return_type
, func
.original_name
,
7067 func
.MakeTypedOriginalArgString("")))
7068 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7069 func
.WriteDestinationInitalizationValidation(file)
7070 self
.WriteClientGLCallLog(func
, file)
7071 last_pointer_name
= func
.GetLastOriginalPointerArg().name
7072 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7073 for (GLsizei i = 0; i < count; ++i) {
7075 values_str
= ' << ", " << '.join(
7076 ["%s[%d + i * %d]" % (
7077 last_pointer_name
, ndx
, self
.GetArrayCount(func
)) for ndx
in range(
7078 0, self
.GetArrayCount(func
))])
7079 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
7080 file.Write(" }\n });\n")
7081 for arg
in func
.GetOriginalArgs():
7082 arg
.WriteClientSideValidationCode(file, func
)
7083 file.Write(" helper_->%sImmediate(%s);\n" %
7084 (func
.name
, func
.MakeInitString("")))
7085 file.Write(" CheckGLError();\n")
7089 def WriteGLES2ImplementationUnitTest(self
, func
, file):
7090 """Writes the GLES2 Implemention unit test."""
7092 TEST_F(GLES2ImplementationTest, %(name)s) {
7093 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7095 cmds::%(name)sImmediate cmd;
7096 %(type)s data[%(count_param)d][%(count)d];
7100 for (int ii = 0; ii < %(count_param)d; ++ii) {
7101 for (int jj = 0; jj < %(count)d; ++jj) {
7102 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7105 expected.cmd.Init(%(cmd_args)s);
7106 gl_->%(name)s(%(args)s);
7107 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7110 cmd_arg_strings
= []
7111 for arg
in func
.GetCmdArgs():
7112 if arg
.name
.endswith("_shm_id"):
7113 cmd_arg_strings
.append("&data[0][0]")
7114 elif arg
.name
.endswith("_shm_offset"):
7117 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
7120 for arg
in func
.GetOriginalArgs():
7122 valid_value
= "&data[0][0]"
7124 valid_value
= arg
.GetValidClientSideArg(func
)
7125 gl_arg_strings
.append(valid_value
)
7126 if arg
.name
== "count":
7127 count_param
= int(valid_value
)
7130 'type': self
.GetArrayType(func
),
7131 'count': self
.GetArrayCount(func
),
7132 'args': ", ".join(gl_arg_strings
),
7133 'cmd_args': ", ".join(cmd_arg_strings
),
7134 'count_param': count_param
,
7137 # Test constants for invalid values, as they are not tested by the
7140 arg
for arg
in func
.GetOriginalArgs()[0:-1] if arg
.IsConstant()
7146 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7147 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7148 for (int ii = 0; ii < %(count_param)d; ++ii) {
7149 for (int jj = 0; jj < %(count)d; ++jj) {
7150 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7153 gl_->%(name)s(%(args)s);
7154 EXPECT_TRUE(NoCommandsWritten());
7155 EXPECT_EQ(%(gl_error)s, CheckError());
7158 for invalid_arg
in constants
:
7160 invalid
= invalid_arg
.GetInvalidArg(func
)
7161 for arg
in func
.GetOriginalArgs():
7162 if arg
is invalid_arg
:
7163 gl_arg_strings
.append(invalid
[0])
7164 elif arg
.IsPointer():
7165 gl_arg_strings
.append("&data[0][0]")
7167 valid_value
= arg
.GetValidClientSideArg(func
)
7168 gl_arg_strings
.append(valid_value
)
7169 if arg
.name
== "count":
7170 count_param
= int(valid_value
)
7174 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
7175 'type': self
.GetArrayType(func
),
7176 'count': self
.GetArrayCount(func
),
7177 'args': ", ".join(gl_arg_strings
),
7178 'gl_error': invalid
[2],
7179 'count_param': count_param
,
7183 def WriteImmediateCmdComputeSize(self
, func
, file):
7184 """Overrriden from TypeHandler."""
7185 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7186 file.Write(" return static_cast<uint32_t>(\n")
7187 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
7188 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7191 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
7192 file.Write(" return static_cast<uint32_t>(\n")
7194 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7198 def WriteImmediateCmdSetHeader(self
, func
, file):
7199 """Overrriden from TypeHandler."""
7200 file.Write(" void SetHeader(GLsizei count) {\n")
7202 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7206 def WriteImmediateCmdInit(self
, func
, file):
7207 """Overrriden from TypeHandler."""
7208 file.Write(" void Init(%s) {\n" %
7209 func
.MakeTypedInitString("_"))
7210 file.Write(" SetHeader(_count);\n")
7211 args
= func
.GetCmdArgs()
7213 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
7214 file.Write(" memcpy(ImmediateDataAddress(this),\n")
7215 pointer_arg
= func
.GetLastOriginalPointerArg()
7216 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg
.name
)
7220 def WriteImmediateCmdSet(self
, func
, file):
7221 """Overrriden from TypeHandler."""
7222 file.Write(" void* Set(void* cmd%s) {\n" %
7223 func
.MakeTypedInitString("_", True))
7224 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7225 func
.MakeInitString("_"))
7226 file.Write(" const uint32_t size = ComputeSize(_count);\n")
7227 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7232 def WriteImmediateCmdHelper(self
, func
, file):
7233 """Overrriden from TypeHandler."""
7234 code
= """ void %(name)s(%(typed_args)s) {
7235 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7236 gles2::cmds::%(name)s* c =
7237 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7246 "typed_args": func
.MakeTypedInitString(""),
7247 "args": func
.MakeInitString("")
7250 def WriteImmediateFormatTest(self
, func
, file):
7251 """Overrriden from TypeHandler."""
7252 args
= func
.GetOriginalArgs()
7255 if arg
.name
== "count":
7256 count_param
= int(arg
.GetValidClientSideCmdArg(func
))
7257 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
7258 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
7259 file.Write(" static %s data[] = {\n" % self
.GetArrayType(func
))
7260 for v
in range(0, self
.GetArrayCount(func
) * count_param
):
7261 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7262 (self
.GetArrayType(func
), v
))
7264 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7265 (func
.name
, func
.name
))
7266 file.Write(" const GLsizei kNumElements = %d;\n" % count_param
)
7267 file.Write(" const size_t kExpectedCmdSize =\n")
7268 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7269 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7270 file.Write(" void* next_cmd = cmd.Set(\n")
7272 for value
, arg
in enumerate(args
):
7274 file.Write(",\n data")
7275 elif arg
.IsConstant():
7278 file.Write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
7280 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7282 file.Write(" cmd.header.command);\n")
7283 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7284 for value
, arg
in enumerate(args
):
7285 if arg
.IsPointer() or arg
.IsConstant():
7287 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7288 (arg
.type, value
+ 1, arg
.name
))
7289 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
7290 file.Write(" next_cmd, sizeof(cmd) +\n")
7291 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7292 file.Write(" // TODO(gman): Check that data was inserted;\n")
7296 class PUTSTRHandler(ArrayArgTypeHandler
):
7297 """Handler for functions that pass a string array."""
7300 ArrayArgTypeHandler
.__init
__(self
)
7302 def __GetDataArg(self
, func
):
7303 """Return the argument that points to the 2D char arrays"""
7304 for arg
in func
.GetOriginalArgs():
7305 if arg
.IsPointer2D():
7309 def __GetLengthArg(self
, func
):
7310 """Return the argument that holds length for each char array"""
7311 for arg
in func
.GetOriginalArgs():
7312 if arg
.IsPointer() and not arg
.IsPointer2D():
7316 def WriteGLES2Implementation(self
, func
, file):
7317 """Overrriden from TypeHandler."""
7318 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7319 (func
.return_type
, func
.original_name
,
7320 func
.MakeTypedOriginalArgString("")))
7321 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7322 func
.WriteDestinationInitalizationValidation(file)
7323 self
.WriteClientGLCallLog(func
, file)
7324 data_arg
= self
.__GetDataArg
(func
)
7325 length_arg
= self
.__GetLengthArg
(func
)
7326 log_code_block
= """ GPU_CLIENT_LOG_CODE_BLOCK({
7327 for (GLsizei ii = 0; ii < count; ++ii) {
7328 if (%(data)s[ii]) {"""
7329 if length_arg
== None:
7330 log_code_block
+= """
7331 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7333 log_code_block
+= """
7334 if (%(length)s && %(length)s[ii] >= 0) {
7335 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7336 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7338 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7340 log_code_block
+= """
7342 GPU_CLIENT_LOG(" " << ii << ": NULL");
7347 file.Write(log_code_block
% {
7348 'data': data_arg
.name
,
7349 'length': length_arg
.name
if not length_arg
== None else ''
7351 for arg
in func
.GetOriginalArgs():
7352 arg
.WriteClientSideValidationCode(file, func
)
7355 for arg
in func
.GetOriginalArgs():
7356 if arg
.name
== 'count' or arg
== self
.__GetLengthArg
(func
):
7358 if arg
== self
.__GetDataArg
(func
):
7359 bucket_args
.append('kResultBucketId')
7361 bucket_args
.append(arg
.name
)
7363 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7366 helper_->%(func_name)sBucket(%(bucket_args)s);
7367 helper_->SetBucketSize(kResultBucketId, 0);
7372 file.Write(code_block
% {
7373 'data': data_arg
.name
,
7374 'length': length_arg
.name
if not length_arg
== None else 'NULL',
7375 'func_name': func
.name
,
7376 'bucket_args': ', '.join(bucket_args
),
7379 def WriteGLES2ImplementationUnitTest(self
, func
, file):
7380 """Overrriden from TypeHandler."""
7382 TEST_F(GLES2ImplementationTest, %(name)s) {
7383 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7384 const char* kString1 = "happy";
7385 const char* kString2 = "ending";
7386 const size_t kString1Size = ::strlen(kString1) + 1;
7387 const size_t kString2Size = ::strlen(kString2) + 1;
7388 const size_t kHeaderSize = sizeof(GLint) * 3;
7389 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7390 const size_t kPaddedHeaderSize =
7391 transfer_buffer_->RoundToAlignment(kHeaderSize);
7392 const size_t kPaddedString1Size =
7393 transfer_buffer_->RoundToAlignment(kString1Size);
7394 const size_t kPaddedString2Size =
7395 transfer_buffer_->RoundToAlignment(kString2Size);
7397 cmd::SetBucketSize set_bucket_size;
7398 cmd::SetBucketData set_bucket_header;
7399 cmd::SetToken set_token1;
7400 cmd::SetBucketData set_bucket_data1;
7401 cmd::SetToken set_token2;
7402 cmd::SetBucketData set_bucket_data2;
7403 cmd::SetToken set_token3;
7404 cmds::%(name)sBucket cmd_bucket;
7405 cmd::SetBucketSize clear_bucket_size;
7408 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7409 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7410 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7413 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7414 expected.set_bucket_header.Init(
7415 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7416 expected.set_token1.Init(GetNextToken());
7417 expected.set_bucket_data1.Init(
7418 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7419 expected.set_token2.Init(GetNextToken());
7420 expected.set_bucket_data2.Init(
7421 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7423 expected.set_token3.Init(GetNextToken());
7424 expected.cmd_bucket.Init(%(bucket_args)s);
7425 expected.clear_bucket_size.Init(kBucketId, 0);
7426 const char* kStrings[] = { kString1, kString2 };
7427 gl_->%(name)s(%(gl_args)s);
7428 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7433 for arg
in func
.GetOriginalArgs():
7434 if arg
== self
.__GetDataArg
(func
):
7435 gl_args
.append('kStrings')
7436 bucket_args
.append('kBucketId')
7437 elif arg
== self
.__GetLengthArg
(func
):
7438 gl_args
.append('NULL')
7439 elif arg
.name
== 'count':
7442 gl_args
.append(arg
.GetValidClientSideArg(func
))
7443 bucket_args
.append(arg
.GetValidClientSideArg(func
))
7446 'gl_args': ", ".join(gl_args
),
7447 'bucket_args': ", ".join(bucket_args
),
7450 if self
.__GetLengthArg
(func
) == None:
7453 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7454 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7455 const char* kString = "foobar******";
7456 const size_t kStringSize = 6; // We only need "foobar".
7457 const size_t kHeaderSize = sizeof(GLint) * 2;
7458 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7459 const size_t kPaddedHeaderSize =
7460 transfer_buffer_->RoundToAlignment(kHeaderSize);
7461 const size_t kPaddedStringSize =
7462 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7464 cmd::SetBucketSize set_bucket_size;
7465 cmd::SetBucketData set_bucket_header;
7466 cmd::SetToken set_token1;
7467 cmd::SetBucketData set_bucket_data;
7468 cmd::SetToken set_token2;
7469 cmds::ShaderSourceBucket shader_source_bucket;
7470 cmd::SetBucketSize clear_bucket_size;
7473 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7474 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7477 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7478 expected.set_bucket_header.Init(
7479 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7480 expected.set_token1.Init(GetNextToken());
7481 expected.set_bucket_data.Init(
7482 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7483 expected.set_token2.Init(GetNextToken());
7484 expected.shader_source_bucket.Init(%(bucket_args)s);
7485 expected.clear_bucket_size.Init(kBucketId, 0);
7486 const char* kStrings[] = { kString };
7487 const GLint kLength[] = { kStringSize };
7488 gl_->%(name)s(%(gl_args)s);
7489 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7493 for arg
in func
.GetOriginalArgs():
7494 if arg
== self
.__GetDataArg
(func
):
7495 gl_args
.append('kStrings')
7496 elif arg
== self
.__GetLengthArg
(func
):
7497 gl_args
.append('kLength')
7498 elif arg
.name
== 'count':
7501 gl_args
.append(arg
.GetValidClientSideArg(func
))
7504 'gl_args': ", ".join(gl_args
),
7505 'bucket_args': ", ".join(bucket_args
),
7508 def WriteBucketServiceUnitTest(self
, func
, file, *extras
):
7509 """Overrriden from TypeHandler."""
7511 cmd_args_with_invalid_id
= []
7513 for index
, arg
in enumerate(func
.GetOriginalArgs()):
7514 if arg
== self
.__GetLengthArg
(func
):
7516 elif arg
.name
== 'count':
7518 elif arg
== self
.__GetDataArg
(func
):
7519 cmd_args
.append('kBucketId')
7520 cmd_args_with_invalid_id
.append('kBucketId')
7522 elif index
== 0: # Resource ID arg
7523 cmd_args
.append(arg
.GetValidArg(func
))
7524 cmd_args_with_invalid_id
.append('kInvalidClientId')
7525 gl_args
.append(arg
.GetValidGLArg(func
))
7527 cmd_args
.append(arg
.GetValidArg(func
))
7528 cmd_args_with_invalid_id
.append(arg
.GetValidArg(func
))
7529 gl_args
.append(arg
.GetValidGLArg(func
))
7532 TEST_P(%(test_name)s, %(name)sValidArgs) {
7533 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7534 const uint32 kBucketId = 123;
7535 const char kSource0[] = "hello";
7536 const char* kSource[] = { kSource0 };
7537 const char kValidStrEnd = 0;
7538 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7540 cmd.Init(%(cmd_args)s);
7541 decoder_->set_unsafe_es3_apis_enabled(true);
7542 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7545 decoder_->set_unsafe_es3_apis_enabled(false);
7546 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7551 self
.WriteValidUnitTest(func
, file, test
, {
7552 'cmd_args': ", ".join(cmd_args
),
7553 'gl_args': ", ".join(gl_args
),
7557 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7558 const uint32 kBucketId = 123;
7559 const char kSource0[] = "hello";
7560 const char* kSource[] = { kSource0 };
7561 const char kValidStrEnd = 0;
7562 decoder_->set_unsafe_es3_apis_enabled(true);
7565 cmd.Init(%(cmd_args)s);
7566 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7567 // Test invalid client.
7568 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7569 cmd.Init(%(cmd_args_with_invalid_id)s);
7570 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7571 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7574 self
.WriteValidUnitTest(func
, file, test
, {
7575 'cmd_args': ", ".join(cmd_args
),
7576 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id
),
7580 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7581 const uint32 kBucketId = 123;
7582 const char kSource0[] = "hello";
7583 const char* kSource[] = { kSource0 };
7584 const char kValidStrEnd = 0;
7585 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7586 const GLsizei kTests[] = {
7589 std::numeric_limits<GLsizei>::max(),
7592 decoder_->set_unsafe_es3_apis_enabled(true);
7593 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7594 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7596 cmd.Init(%(cmd_args)s);
7597 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7601 self
.WriteValidUnitTest(func
, file, test
, {
7602 'cmd_args': ", ".join(cmd_args
),
7606 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7607 const uint32 kBucketId = 123;
7608 const char kSource0[] = "hello";
7609 const char* kSource[] = { kSource0 };
7610 const char kInvalidStrEnd = '*';
7611 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7613 cmd.Init(%(cmd_args)s);
7614 decoder_->set_unsafe_es3_apis_enabled(true);
7615 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7618 self
.WriteValidUnitTest(func
, file, test
, {
7619 'cmd_args': ", ".join(cmd_args
),
7623 class PUTXnHandler(ArrayArgTypeHandler
):
7624 """Handler for glUniform?f functions."""
7626 ArrayArgTypeHandler
.__init
__(self
)
7628 def WriteHandlerImplementation(self
, func
, file):
7629 """Overrriden from TypeHandler."""
7630 code
= """ %(type)s temp[%(count)s] = { %(values)s};"""
7633 gl%(name)sv(%(location)s, 1, &temp[0]);
7637 Do%(name)sv(%(location)s, 1, &temp[0]);
7640 args
= func
.GetOriginalArgs()
7641 count
= int(self
.GetArrayCount(func
))
7642 num_args
= len(args
)
7643 for ii
in range(count
):
7644 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
7648 'count': self
.GetArrayCount(func
),
7649 'type': self
.GetArrayType(func
),
7650 'location': args
[0].name
,
7651 'args': func
.MakeOriginalArgString(""),
7655 def WriteServiceUnitTest(self
, func
, file, *extras
):
7656 """Overrriden from TypeHandler."""
7658 TEST_P(%(test_name)s, %(name)sValidArgs) {
7659 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7660 SpecializedSetup<cmds::%(name)s, 0>(true);
7662 cmd.Init(%(args)s);"""
7665 decoder_->set_unsafe_es3_apis_enabled(true);"""
7667 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7668 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7671 decoder_->set_unsafe_es3_apis_enabled(false);
7672 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7676 args
= func
.GetOriginalArgs()
7677 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
)
7678 self
.WriteValidUnitTest(func
, file, valid_test
, {
7680 'count': self
.GetArrayCount(func
),
7681 'local_args': local_args
,
7685 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7686 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7687 SpecializedSetup<cmds::%(name)s, 0>(false);
7690 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7693 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
7694 'name': func
.GetInfo('name'),
7695 'count': self
.GetArrayCount(func
),
7699 class GLcharHandler(CustomHandler
):
7700 """Handler for functions that pass a single string ."""
7703 CustomHandler
.__init
__(self
)
7705 def WriteImmediateCmdComputeSize(self
, func
, file):
7706 """Overrriden from TypeHandler."""
7707 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7708 file.Write(" return static_cast<uint32_t>(\n")
7709 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
7712 def WriteImmediateCmdSetHeader(self
, func
, file):
7713 """Overrriden from TypeHandler."""
7715 void SetHeader(uint32_t data_size) {
7716 header.SetCmdBySize<ValueType>(data_size);
7721 def WriteImmediateCmdInit(self
, func
, file):
7722 """Overrriden from TypeHandler."""
7723 last_arg
= func
.GetLastOriginalArg()
7724 args
= func
.GetCmdArgs()
7727 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
7729 void Init(%(typed_args)s, uint32_t _data_size) {
7730 SetHeader(_data_size);
7732 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7737 "typed_args": func
.MakeTypedArgString("_"),
7738 "set_code": "\n".join(set_code
),
7739 "last_arg": last_arg
.name
7742 def WriteImmediateCmdSet(self
, func
, file):
7743 """Overrriden from TypeHandler."""
7744 last_arg
= func
.GetLastOriginalArg()
7745 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7746 func
.MakeTypedCmdArgString("_", True))
7747 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7748 func
.MakeCmdArgString("_"))
7749 file.Write(" return NextImmediateCmdAddress<ValueType>("
7750 "cmd, _data_size);\n")
7754 def WriteImmediateCmdHelper(self
, func
, file):
7755 """Overrriden from TypeHandler."""
7756 code
= """ void %(name)s(%(typed_args)s) {
7757 const uint32_t data_size = strlen(name);
7758 gles2::cmds::%(name)s* c =
7759 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7761 c->Init(%(args)s, data_size);
7768 "typed_args": func
.MakeTypedOriginalArgString(""),
7769 "args": func
.MakeOriginalArgString(""),
7773 def WriteImmediateFormatTest(self
, func
, file):
7774 """Overrriden from TypeHandler."""
7777 all_but_last_arg
= func
.GetCmdArgs()[:-1]
7778 for value
, arg
in enumerate(all_but_last_arg
):
7779 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
7780 for value
, arg
in enumerate(all_but_last_arg
):
7781 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7782 (arg
.type, value
+ 11, arg
.name
))
7784 TEST_F(GLES2FormatTest, %(func_name)s) {
7785 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7786 static const char* const test_str = \"test string\";
7787 void* next_cmd = cmd.Set(
7792 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7793 cmd.header.command);
7794 EXPECT_EQ(sizeof(cmd) +
7795 RoundSizeToMultipleOfEntries(strlen(test_str)),
7796 cmd.header.size * 4u);
7797 EXPECT_EQ(static_cast<char*>(next_cmd),
7798 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7799 RoundSizeToMultipleOfEntries(strlen(test_str)));
7801 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7802 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7805 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7806 sizeof(cmd) + strlen(test_str));
7811 'func_name': func
.name
,
7812 'init_code': "\n".join(init_code
),
7813 'check_code': "\n".join(check_code
),
7817 class GLcharNHandler(CustomHandler
):
7818 """Handler for functions that pass a single string with an optional len."""
7821 CustomHandler
.__init
__(self
)
7823 def InitFunction(self
, func
):
7824 """Overrriden from TypeHandler."""
7826 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
7828 def NeedsDataTransferFunction(self
, func
):
7829 """Overriden from TypeHandler."""
7832 def AddBucketFunction(self
, generator
, func
):
7833 """Overrriden from TypeHandler."""
7836 def WriteServiceImplementation(self
, func
, file):
7837 """Overrriden from TypeHandler."""
7838 self
.WriteServiceHandlerFunctionHeader(func
, file)
7840 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7841 Bucket* bucket = GetBucket(bucket_id);
7842 if (!bucket || bucket->size() == 0) {
7843 return error::kInvalidArguments;
7846 if (!bucket->GetAsString(&str)) {
7847 return error::kInvalidArguments;
7849 %(gl_func_name)s(0, str.c_str());
7850 return error::kNoError;
7855 'gl_func_name': func
.GetGLFunctionName(),
7856 'bucket_id': func
.cmd_args
[0].name
,
7860 class IsHandler(TypeHandler
):
7861 """Handler for glIs____ type and glGetError functions."""
7864 TypeHandler
.__init
__(self
)
7866 def InitFunction(self
, func
):
7867 """Overrriden from TypeHandler."""
7868 func
.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7869 func
.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7870 if func
.GetInfo('result') == None:
7871 func
.AddInfo('result', ['uint32_t'])
7873 def WriteServiceUnitTest(self
, func
, file, *extras
):
7874 """Overrriden from TypeHandler."""
7876 TEST_P(%(test_name)s, %(name)sValidArgs) {
7877 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7878 SpecializedSetup<cmds::%(name)s, 0>(true);
7880 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7883 decoder_->set_unsafe_es3_apis_enabled(true);"""
7885 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7886 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7889 decoder_->set_unsafe_es3_apis_enabled(false);
7890 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7895 if len(func
.GetOriginalArgs()):
7897 self
.WriteValidUnitTest(func
, file, valid_test
, {
7902 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7903 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7904 SpecializedSetup<cmds::%(name)s, 0>(false);
7906 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7907 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7910 self
.WriteInvalidUnitTest(func
, file, invalid_test
, {
7915 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
7916 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7917 SpecializedSetup<cmds::%(name)s, 0>(false);"""
7920 decoder_->set_unsafe_es3_apis_enabled(true);"""
7923 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
7924 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
7925 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
7926 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
7929 decoder_->set_unsafe_es3_apis_enabled(true);"""
7933 self
.WriteValidUnitTest(func
, file, invalid_test
, {
7937 def WriteServiceImplementation(self
, func
, file):
7938 """Overrriden from TypeHandler."""
7939 self
.WriteServiceHandlerFunctionHeader(func
, file)
7940 args
= func
.GetOriginalArgs()
7942 arg
.WriteGetCode(file)
7944 code
= """ typedef cmds::%(func_name)s::Result Result;
7945 Result* result_dst = GetSharedMemoryAs<Result*>(
7946 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
7948 return error::kOutOfBounds;
7951 file.Write(code
% {'func_name': func
.name
})
7952 func
.WriteHandlerValidation(file)
7954 assert func
.GetInfo('id_mapping')
7955 assert len(func
.GetInfo('id_mapping')) == 1
7956 assert len(args
) == 1
7957 id_type
= func
.GetInfo('id_mapping')[0]
7958 file.Write(" %s service_%s = 0;\n" % (args
[0].type, id_type
.lower()))
7959 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
7960 (id_type
, id_type
.lower(), id_type
.lower()))
7962 file.Write(" *result_dst = %s(%s);\n" %
7963 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
7964 file.Write(" return error::kNoError;\n")
7968 def WriteGLES2Implementation(self
, func
, file):
7969 """Overrriden from TypeHandler."""
7970 impl_func
= func
.GetInfo('impl_func')
7971 if impl_func
== None or impl_func
== True:
7972 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
7973 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7974 (func
.return_type
, func
.original_name
,
7975 func
.MakeTypedOriginalArgString("")))
7976 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7977 self
.WriteTraceEvent(func
, file)
7978 func
.WriteDestinationInitalizationValidation(file)
7979 self
.WriteClientGLCallLog(func
, file)
7980 file.Write(" typedef cmds::%s::Result Result;\n" % func
.name
)
7981 file.Write(" Result* result = GetResultAs<Result*>();\n")
7982 file.Write(" if (!result) {\n")
7983 file.Write(" return %s;\n" % error_value
)
7985 file.Write(" *result = 0;\n")
7986 assert len(func
.GetOriginalArgs()) == 1
7987 id_arg
= func
.GetOriginalArgs()[0]
7988 if id_arg
.type == 'GLsync':
7989 arg_string
= "ToGLuint(%s)" % func
.MakeOriginalArgString("")
7991 arg_string
= func
.MakeOriginalArgString("")
7993 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
7994 (func
.name
, arg_string
))
7995 file.Write(" WaitForCmd();\n")
7996 file.Write(" %s result_value = *result" % func
.return_type
)
7997 if func
.return_type
== "GLboolean":
7999 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
8000 file.Write(" CheckGLError();\n")
8001 file.Write(" return result_value;\n")
8005 def WriteGLES2ImplementationUnitTest(self
, func
, file):
8006 """Overrriden from TypeHandler."""
8007 client_test
= func
.GetInfo('client_test')
8008 if client_test
== None or client_test
== True:
8010 TEST_F(GLES2ImplementationTest, %(name)s) {
8016 ExpectedMemoryInfo result1 =
8017 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
8018 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
8020 EXPECT_CALL(*command_buffer(), OnFlush())
8021 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
8022 .RetiresOnSaturation();
8024 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
8025 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
8026 EXPECT_TRUE(result);
8029 args
= func
.GetOriginalArgs()
8030 assert len(args
) == 1
8033 'cmd_id_value': args
[0].GetValidClientSideCmdArg(func
),
8034 'gl_id_value': args
[0].GetValidClientSideArg(func
) })
8037 class STRnHandler(TypeHandler
):
8038 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
8039 GetTranslatedShaderSourceANGLE."""
8042 TypeHandler
.__init
__(self
)
8044 def InitFunction(self
, func
):
8045 """Overrriden from TypeHandler."""
8046 # remove all but the first cmd args.
8047 cmd_args
= func
.GetCmdArgs()
8049 func
.AddCmdArg(cmd_args
[0])
8050 # add on a bucket id.
8051 func
.AddCmdArg(Argument('bucket_id', 'uint32_t'))
8053 def WriteGLES2Implementation(self
, func
, file):
8054 """Overrriden from TypeHandler."""
8055 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
8056 GPU_CLIENT_SINGLE_THREAD_CHECK();
8058 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
8059 << "] gl%(func_name)s" << "("
8062 << static_cast<void*>(%(arg2)s) << ", "
8063 << static_cast<void*>(%(arg3)s) << ")");
8064 helper_->SetBucketSize(kResultBucketId, 0);
8065 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8067 GLsizei max_size = 0;
8068 if (GetBucketAsString(kResultBucketId, &str)) {
8071 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8072 memcpy(%(dest_name)s, str.c_str(), max_size);
8073 %(dest_name)s[max_size] = '\\0';
8074 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8077 if (%(length_name)s != NULL) {
8078 *%(length_name)s = max_size;
8083 args
= func
.GetOriginalArgs()
8085 'return_type': func
.return_type
,
8086 'func_name': func
.original_name
,
8087 'args': func
.MakeTypedOriginalArgString(""),
8088 'id_name': args
[0].name
,
8089 'bufsize_name': args
[1].name
,
8090 'length_name': args
[2].name
,
8091 'dest_name': args
[3].name
,
8092 'arg0': args
[0].name
,
8093 'arg1': args
[1].name
,
8094 'arg2': args
[2].name
,
8095 'arg3': args
[3].name
,
8097 file.Write(code_1
% str_args
)
8098 func
.WriteDestinationInitalizationValidation(file)
8099 file.Write(code_2
% str_args
)
8101 def WriteServiceUnitTest(self
, func
, file, *extras
):
8102 """Overrriden from TypeHandler."""
8104 TEST_P(%(test_name)s, %(name)sValidArgs) {
8105 const char* kInfo = "hello";
8106 const uint32_t kBucketId = 123;
8107 SpecializedSetup<cmds::%(name)s, 0>(true);
8109 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8110 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8111 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8114 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8115 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8116 ASSERT_TRUE(bucket != NULL);
8117 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8118 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8120 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8123 args
= func
.GetOriginalArgs()
8124 id_name
= args
[0].GetValidGLArg(func
)
8125 get_len_func
= func
.GetInfo('get_len_func')
8126 get_len_enum
= func
.GetInfo('get_len_enum')
8129 'get_len_func': get_len_func
,
8130 'get_len_enum': get_len_enum
,
8131 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8132 args
[0].GetValidGLArg(func
),
8133 'args': '%s, kBucketId' % args
[0].GetValidArg(func
),
8134 'expect_len_code': '',
8136 if get_len_func
and get_len_func
[0:2] == 'gl':
8137 sub
['expect_len_code'] = (
8138 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8139 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8140 get_len_func
[2:], id_name
, get_len_enum
)
8141 self
.WriteValidUnitTest(func
, file, valid_test
, sub
, *extras
)
8144 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8145 const uint32_t kBucketId = 123;
8146 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8149 cmd.Init(kInvalidClientId, kBucketId);
8150 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8151 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8154 self
.WriteValidUnitTest(func
, file, invalid_test
, *extras
)
8156 def WriteServiceImplementation(self
, func
, file):
8157 """Overrriden from TypeHandler."""
8160 class NamedType(object):
8161 """A class that represents a type of an argument in a client function.
8163 A type of an argument that is to be passed through in the command buffer
8164 command. Currently used only for the arguments that are specificly named in
8165 the 'cmd_buffer_functions.txt' file, mostly enums.
8168 def __init__(self
, info
):
8169 assert not 'is_complete' in info
or info
['is_complete'] == True
8171 self
.valid
= info
['valid']
8172 if 'invalid' in info
:
8173 self
.invalid
= info
['invalid']
8176 if 'valid_es3' in info
:
8177 self
.valid_es3
= info
['valid_es3']
8180 if 'deprecated_es3' in info
:
8181 self
.deprecated_es3
= info
['deprecated_es3']
8183 self
.deprecated_es3
= []
8186 return self
.info
['type']
8188 def GetInvalidValues(self
):
8191 def GetValidValues(self
):
8194 def GetValidValuesES3(self
):
8195 return self
.valid_es3
8197 def GetDeprecatedValuesES3(self
):
8198 return self
.deprecated_es3
8200 def IsConstant(self
):
8201 if not 'is_complete' in self
.info
:
8204 return len(self
.GetValidValues()) == 1
8206 def GetConstantValue(self
):
8207 return self
.GetValidValues()[0]
8209 class Argument(object):
8210 """A class that represents a function argument."""
8213 'GLenum': 'uint32_t',
8215 'GLintptr': 'int32_t',
8216 'GLsizei': 'int32_t',
8217 'GLsizeiptr': 'int32_t',
8219 'GLclampf': 'float',
8221 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8223 def __init__(self
, name
, type):
8225 self
.optional
= type.endswith("Optional*")
8227 type = type[:-9] + "*"
8230 if type in self
.cmd_type_map_
:
8231 self
.cmd_type
= self
.cmd_type_map_
[type]
8233 self
.cmd_type
= 'uint32_t'
8235 def IsPointer(self
):
8236 """Returns true if argument is a pointer."""
8239 def IsPointer2D(self
):
8240 """Returns true if argument is a 2D pointer."""
8243 def IsConstant(self
):
8244 """Returns true if the argument has only one valid value."""
8247 def AddCmdArgs(self
, args
):
8248 """Adds command arguments for this argument to the given list."""
8249 if not self
.IsConstant():
8250 return args
.append(self
)
8252 def AddInitArgs(self
, args
):
8253 """Adds init arguments for this argument to the given list."""
8254 if not self
.IsConstant():
8255 return args
.append(self
)
8257 def GetValidArg(self
, func
):
8258 """Gets a valid value for this argument."""
8259 valid_arg
= func
.GetValidArg(self
)
8260 if valid_arg
!= None:
8263 index
= func
.GetOriginalArgs().index(self
)
8264 return str(index
+ 1)
8266 def GetValidClientSideArg(self
, func
):
8267 """Gets a valid value for this argument."""
8268 valid_arg
= func
.GetValidArg(self
)
8269 if valid_arg
!= None:
8272 if self
.IsPointer():
8274 index
= func
.GetOriginalArgs().index(self
)
8275 if self
.type == 'GLsync':
8276 return ("reinterpret_cast<GLsync>(%d)" % (index
+ 1))
8277 return str(index
+ 1)
8279 def GetValidClientSideCmdArg(self
, func
):
8280 """Gets a valid value for this argument."""
8281 valid_arg
= func
.GetValidArg(self
)
8282 if valid_arg
!= None:
8285 index
= func
.GetOriginalArgs().index(self
)
8286 return str(index
+ 1)
8289 index
= func
.GetCmdArgs().index(self
)
8290 return str(index
+ 1)
8292 def GetValidGLArg(self
, func
):
8293 """Gets a valid GL value for this argument."""
8294 value
= self
.GetValidArg(func
)
8295 if self
.type == 'GLsync':
8296 return ("reinterpret_cast<GLsync>(%s)" % value
)
8299 def GetValidNonCachedClientSideArg(self
, func
):
8300 """Returns a valid value for this argument in a GL call.
8301 Using the value will produce a command buffer service invocation.
8302 Returns None if there is no such value."""
8304 if self
.type == 'GLsync':
8305 return ("reinterpret_cast<GLsync>(%s)" % value
)
8308 def GetValidNonCachedClientSideCmdArg(self
, func
):
8309 """Returns a valid value for this argument in a command buffer command.
8310 Calling the GL function with the value returned by
8311 GetValidNonCachedClientSideArg will result in a command buffer command
8312 that contains the value returned by this function. """
8315 def GetNumInvalidValues(self
, func
):
8316 """returns the number of invalid values to be tested."""
8319 def GetInvalidArg(self
, index
):
8320 """returns an invalid value and expected parse result by index."""
8321 return ("---ERROR0---", "---ERROR2---", None)
8323 def GetLogArg(self
):
8324 """Get argument appropriate for LOG macro."""
8325 if self
.type == 'GLboolean':
8326 return 'GLES2Util::GetStringBool(%s)' % self
.name
8327 if self
.type == 'GLenum':
8328 return 'GLES2Util::GetStringEnum(%s)' % self
.name
8331 def WriteGetCode(self
, file):
8332 """Writes the code to get an argument from a command structure."""
8333 if self
.type == 'GLsync':
8337 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
8338 (my_type
, self
.name
, my_type
, self
.name
))
8340 def WriteValidationCode(self
, file, func
):
8341 """Writes the validation code for an argument."""
8344 def WriteClientSideValidationCode(self
, file, func
):
8345 """Writes the validation code for an argument."""
8348 def WriteDestinationInitalizationValidation(self
, file, func
):
8349 """Writes the client side destintion initialization validation."""
8352 def WriteDestinationInitalizationValidatationIfNeeded(self
, file, func
):
8353 """Writes the client side destintion initialization validation if needed."""
8354 parts
= self
.type.split(" ")
8357 if parts
[0] in self
.need_validation_
:
8359 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8360 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
8363 def WriteGetAddress(self
, file):
8364 """Writes the code to get the address this argument refers to."""
8367 def GetImmediateVersion(self
):
8368 """Gets the immediate version of this argument."""
8371 def GetBucketVersion(self
):
8372 """Gets the bucket version of this argument."""
8376 class BoolArgument(Argument
):
8377 """class for GLboolean"""
8379 def __init__(self
, name
, type):
8380 Argument
.__init
__(self
, name
, 'GLboolean')
8382 def GetValidArg(self
, func
):
8383 """Gets a valid value for this argument."""
8386 def GetValidClientSideArg(self
, func
):
8387 """Gets a valid value for this argument."""
8390 def GetValidClientSideCmdArg(self
, func
):
8391 """Gets a valid value for this argument."""
8394 def GetValidGLArg(self
, func
):
8395 """Gets a valid GL value for this argument."""
8399 class UniformLocationArgument(Argument
):
8400 """class for uniform locations."""
8402 def __init__(self
, name
):
8403 Argument
.__init
__(self
, name
, "GLint")
8405 def WriteGetCode(self
, file):
8406 """Writes the code to get an argument from a command structure."""
8407 code
= """ %s %s = static_cast<%s>(c.%s);
8409 file.Write(code
% (self
.type, self
.name
, self
.type, self
.name
))
8411 class DataSizeArgument(Argument
):
8412 """class for data_size which Bucket commands do not need."""
8414 def __init__(self
, name
):
8415 Argument
.__init
__(self
, name
, "uint32_t")
8417 def GetBucketVersion(self
):
8421 class SizeArgument(Argument
):
8422 """class for GLsizei and GLsizeiptr."""
8424 def __init__(self
, name
, type):
8425 Argument
.__init
__(self
, name
, type)
8427 def GetNumInvalidValues(self
, func
):
8428 """overridden from Argument."""
8429 if func
.IsImmediate():
8433 def GetInvalidArg(self
, index
):
8434 """overridden from Argument."""
8435 return ("-1", "kNoError", "GL_INVALID_VALUE")
8437 def WriteValidationCode(self
, file, func
):
8438 """overridden from Argument."""
8441 code
= """ if (%(var_name)s < 0) {
8442 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8443 return error::kNoError;
8447 "var_name": self
.name
,
8448 "func_name": func
.original_name
,
8451 def WriteClientSideValidationCode(self
, file, func
):
8452 """overridden from Argument."""
8453 code
= """ if (%(var_name)s < 0) {
8454 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8459 "var_name": self
.name
,
8460 "func_name": func
.original_name
,
8464 class SizeNotNegativeArgument(SizeArgument
):
8465 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8467 def __init__(self
, name
, type, gl_type
):
8468 SizeArgument
.__init
__(self
, name
, gl_type
)
8470 def GetInvalidArg(self
, index
):
8471 """overridden from SizeArgument."""
8472 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8474 def WriteValidationCode(self
, file, func
):
8475 """overridden from SizeArgument."""
8479 class EnumBaseArgument(Argument
):
8480 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8481 ValidatedBoolArgument."""
8483 def __init__(self
, name
, gl_type
, type, gl_error
):
8484 Argument
.__init
__(self
, name
, gl_type
)
8486 self
.local_type
= type
8487 self
.gl_error
= gl_error
8488 name
= type[len(gl_type
):]
8489 self
.type_name
= name
8490 self
.named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8492 def IsConstant(self
):
8493 return self
.named_type
.IsConstant()
8495 def GetConstantValue(self
):
8496 return self
.named_type
.GetConstantValue()
8498 def WriteValidationCode(self
, file, func
):
8501 if self
.named_type
.IsConstant():
8503 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
8504 (ToUnderscore(self
.type_name
), self
.name
))
8505 if self
.gl_error
== "GL_INVALID_ENUM":
8507 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8508 (func
.original_name
, self
.name
, self
.name
))
8511 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8512 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8513 file.Write(" return error::kNoError;\n")
8516 def WriteClientSideValidationCode(self
, file, func
):
8517 if not self
.named_type
.IsConstant():
8519 file.Write(" if (%s != %s) {" % (self
.name
,
8520 self
.GetConstantValue()))
8522 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8523 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8524 if func
.return_type
== "void":
8525 file.Write(" return;\n")
8527 file.Write(" return %s;\n" % func
.GetErrorReturnString())
8530 def GetValidArg(self
, func
):
8531 valid_arg
= func
.GetValidArg(self
)
8532 if valid_arg
!= None:
8534 valid
= self
.named_type
.GetValidValues()
8536 num_valid
= len(valid
)
8539 index
= func
.GetOriginalArgs().index(self
)
8540 return str(index
+ 1)
8542 def GetValidClientSideArg(self
, func
):
8543 """Gets a valid value for this argument."""
8544 return self
.GetValidArg(func
)
8546 def GetValidClientSideCmdArg(self
, func
):
8547 """Gets a valid value for this argument."""
8548 valid_arg
= func
.GetValidArg(self
)
8549 if valid_arg
!= None:
8552 valid
= self
.named_type
.GetValidValues()
8554 num_valid
= len(valid
)
8558 index
= func
.GetOriginalArgs().index(self
)
8559 return str(index
+ 1)
8562 index
= func
.GetCmdArgs().index(self
)
8563 return str(index
+ 1)
8565 def GetValidGLArg(self
, func
):
8566 """Gets a valid value for this argument."""
8567 return self
.GetValidArg(func
)
8569 def GetNumInvalidValues(self
, func
):
8570 """returns the number of invalid values to be tested."""
8571 return len(self
.named_type
.GetInvalidValues())
8573 def GetInvalidArg(self
, index
):
8574 """returns an invalid value by index."""
8575 invalid
= self
.named_type
.GetInvalidValues()
8577 num_invalid
= len(invalid
)
8578 if index
>= num_invalid
:
8579 index
= num_invalid
- 1
8580 return (invalid
[index
], "kNoError", self
.gl_error
)
8581 return ("---ERROR1---", "kNoError", self
.gl_error
)
8584 class EnumArgument(EnumBaseArgument
):
8585 """A class that represents a GLenum argument"""
8587 def __init__(self
, name
, type):
8588 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
8590 def GetLogArg(self
):
8591 """Overridden from Argument."""
8592 return ("GLES2Util::GetString%s(%s)" %
8593 (self
.type_name
, self
.name
))
8596 class IntArgument(EnumBaseArgument
):
8597 """A class for a GLint argument that can only accept specific values.
8599 For example glTexImage2D takes a GLint for its internalformat
8600 argument instead of a GLenum.
8603 def __init__(self
, name
, type):
8604 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
8607 class ValidatedBoolArgument(EnumBaseArgument
):
8608 """A class for a GLboolean argument that can only accept specific values.
8610 For example glUniformMatrix takes a GLboolean for it's transpose but it
8614 def __init__(self
, name
, type):
8615 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
8617 def GetLogArg(self
):
8618 """Overridden from Argument."""
8619 return 'GLES2Util::GetStringBool(%s)' % self
.name
8622 class BitFieldArgument(EnumBaseArgument
):
8623 """A class for a GLbitfield argument that can only accept specific values.
8625 For example glFenceSync takes a GLbitfield for its flags argument bit it
8629 def __init__(self
, name
, type):
8630 EnumBaseArgument
.__init
__(self
, name
, "GLbitfield", type,
8634 class ImmediatePointerArgument(Argument
):
8635 """A class that represents an immediate argument to a function.
8637 An immediate argument is one where the data follows the command.
8640 def __init__(self
, name
, type):
8641 Argument
.__init
__(self
, name
, type)
8643 def IsPointer(self
):
8646 def GetPointedType(self
):
8647 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8649 return match
.groupdict()['element_type']
8651 def AddCmdArgs(self
, args
):
8652 """Overridden from Argument."""
8655 def WriteGetCode(self
, file):
8656 """Overridden from Argument."""
8658 " %s %s = GetImmediateDataAs<%s>(\n" %
8659 (self
.type, self
.name
, self
.type))
8660 file.Write(" c, data_size, immediate_data_size);\n")
8662 def WriteValidationCode(self
, file, func
):
8663 """Overridden from Argument."""
8666 file.Write(" if (%s == NULL) {\n" % self
.name
)
8667 file.Write(" return error::kOutOfBounds;\n")
8670 def GetImmediateVersion(self
):
8671 """Overridden from Argument."""
8674 def WriteDestinationInitalizationValidation(self
, file, func
):
8675 """Overridden from Argument."""
8676 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8678 def GetLogArg(self
):
8679 """Overridden from Argument."""
8680 return "static_cast<const void*>(%s)" % self
.name
8683 class PointerArgument(Argument
):
8684 """A class that represents a pointer argument to a function."""
8686 def __init__(self
, name
, type):
8687 Argument
.__init
__(self
, name
, type)
8689 def IsPointer(self
):
8690 """Overridden from Argument."""
8693 def IsPointer2D(self
):
8694 """Overridden from Argument."""
8695 return self
.type.count('*') == 2
8697 def GetPointedType(self
):
8698 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8700 return match
.groupdict()['element_type']
8702 def GetValidArg(self
, func
):
8703 """Overridden from Argument."""
8704 return "shared_memory_id_, shared_memory_offset_"
8706 def GetValidGLArg(self
, func
):
8707 """Overridden from Argument."""
8708 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
8710 def GetNumInvalidValues(self
, func
):
8711 """Overridden from Argument."""
8714 def GetInvalidArg(self
, index
):
8715 """Overridden from Argument."""
8717 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8719 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8720 "kOutOfBounds", None)
8722 def GetLogArg(self
):
8723 """Overridden from Argument."""
8724 return "static_cast<const void*>(%s)" % self
.name
8726 def AddCmdArgs(self
, args
):
8727 """Overridden from Argument."""
8728 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32_t'))
8729 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32_t'))
8731 def WriteGetCode(self
, file):
8732 """Overridden from Argument."""
8734 " %s %s = GetSharedMemoryAs<%s>(\n" %
8735 (self
.type, self
.name
, self
.type))
8737 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8738 (self
.name
, self
.name
))
8740 def WriteGetAddress(self
, file):
8741 """Overridden from Argument."""
8743 " %s %s = GetSharedMemoryAs<%s>(\n" %
8744 (self
.type, self
.name
, self
.type))
8746 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8747 (self
.name
, self
.name
, self
.name
))
8749 def WriteValidationCode(self
, file, func
):
8750 """Overridden from Argument."""
8753 file.Write(" if (%s == NULL) {\n" % self
.name
)
8754 file.Write(" return error::kOutOfBounds;\n")
8757 def GetImmediateVersion(self
):
8758 """Overridden from Argument."""
8759 return ImmediatePointerArgument(self
.name
, self
.type)
8761 def GetBucketVersion(self
):
8762 """Overridden from Argument."""
8763 if self
.type.find('char') >= 0:
8764 if self
.IsPointer2D():
8765 return InputStringArrayBucketArgument(self
.name
, self
.type)
8766 return InputStringBucketArgument(self
.name
, self
.type)
8767 return BucketPointerArgument(self
.name
, self
.type)
8769 def WriteDestinationInitalizationValidation(self
, file, func
):
8770 """Overridden from Argument."""
8771 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8774 class BucketPointerArgument(PointerArgument
):
8775 """A class that represents an bucket argument to a function."""
8777 def __init__(self
, name
, type):
8778 Argument
.__init
__(self
, name
, type)
8780 def AddCmdArgs(self
, args
):
8781 """Overridden from Argument."""
8784 def WriteGetCode(self
, file):
8785 """Overridden from Argument."""
8787 " %s %s = bucket->GetData(0, data_size);\n" %
8788 (self
.type, self
.name
))
8790 def WriteValidationCode(self
, file, func
):
8791 """Overridden from Argument."""
8794 def GetImmediateVersion(self
):
8795 """Overridden from Argument."""
8798 def WriteDestinationInitalizationValidation(self
, file, func
):
8799 """Overridden from Argument."""
8800 self
.WriteDestinationInitalizationValidatationIfNeeded(file, func
)
8802 def GetLogArg(self
):
8803 """Overridden from Argument."""
8804 return "static_cast<const void*>(%s)" % self
.name
8807 class InputStringBucketArgument(Argument
):
8808 """A string input argument where the string is passed in a bucket."""
8810 def __init__(self
, name
, type):
8811 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8813 def IsPointer(self
):
8814 """Overridden from Argument."""
8817 def IsPointer2D(self
):
8818 """Overridden from Argument."""
8822 class InputStringArrayBucketArgument(Argument
):
8823 """A string array input argument where the strings are passed in a bucket."""
8825 def __init__(self
, name
, type):
8826 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8827 self
._original
_name
= name
8829 def WriteGetCode(self
, file):
8830 """Overridden from Argument."""
8832 Bucket* bucket = GetBucket(c.%(name)s);
8834 return error::kInvalidArguments;
8837 std::vector<char*> strs;
8838 std::vector<GLint> len;
8839 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8840 return error::kInvalidArguments;
8842 const char** %(original_name)s =
8843 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8844 const GLint* length =
8845 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8850 'original_name': self
._original
_name
,
8853 def GetValidArg(self
, func
):
8854 return "kNameBucketId"
8856 def GetValidGLArg(self
, func
):
8859 def IsPointer(self
):
8860 """Overridden from Argument."""
8863 def IsPointer2D(self
):
8864 """Overridden from Argument."""
8868 class ResourceIdArgument(Argument
):
8869 """A class that represents a resource id argument to a function."""
8871 def __init__(self
, name
, type):
8872 match
= re
.match("(GLid\w+)", type)
8873 self
.resource_type
= match
.group(1)[4:]
8874 if self
.resource_type
== "Sync":
8875 type = type.replace(match
.group(1), "GLsync")
8877 type = type.replace(match
.group(1), "GLuint")
8878 Argument
.__init
__(self
, name
, type)
8880 def WriteGetCode(self
, file):
8881 """Overridden from Argument."""
8882 if self
.type == "GLsync":
8886 file.Write(" %s %s = c.%s;\n" % (my_type
, self
.name
, self
.name
))
8888 def GetValidArg(self
, func
):
8889 return "client_%s_id_" % self
.resource_type
.lower()
8891 def GetValidGLArg(self
, func
):
8892 if self
.resource_type
== "Sync":
8893 return "reinterpret_cast<GLsync>(kService%sId)" % self
.resource_type
8894 return "kService%sId" % self
.resource_type
8897 class ResourceIdBindArgument(Argument
):
8898 """Represents a resource id argument to a bind function."""
8900 def __init__(self
, name
, type):
8901 match
= re
.match("(GLidBind\w+)", type)
8902 self
.resource_type
= match
.group(1)[8:]
8903 type = type.replace(match
.group(1), "GLuint")
8904 Argument
.__init
__(self
, name
, type)
8906 def WriteGetCode(self
, file):
8907 """Overridden from Argument."""
8908 code
= """ %(type)s %(name)s = c.%(name)s;
8910 file.Write(code
% {'type': self
.type, 'name': self
.name
})
8912 def GetValidArg(self
, func
):
8913 return "client_%s_id_" % self
.resource_type
.lower()
8915 def GetValidGLArg(self
, func
):
8916 return "kService%sId" % self
.resource_type
8919 class ResourceIdZeroArgument(Argument
):
8920 """Represents a resource id argument to a function that can be zero."""
8922 def __init__(self
, name
, type):
8923 match
= re
.match("(GLidZero\w+)", type)
8924 self
.resource_type
= match
.group(1)[8:]
8925 type = type.replace(match
.group(1), "GLuint")
8926 Argument
.__init
__(self
, name
, type)
8928 def WriteGetCode(self
, file):
8929 """Overridden from Argument."""
8930 file.Write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
8932 def GetValidArg(self
, func
):
8933 return "client_%s_id_" % self
.resource_type
.lower()
8935 def GetValidGLArg(self
, func
):
8936 return "kService%sId" % self
.resource_type
8938 def GetNumInvalidValues(self
, func
):
8939 """returns the number of invalid values to be tested."""
8942 def GetInvalidArg(self
, index
):
8943 """returns an invalid value by index."""
8944 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
8947 class Function(object):
8948 """A class that represents a function."""
8952 'Bind': BindHandler(),
8953 'Create': CreateHandler(),
8954 'Custom': CustomHandler(),
8955 'Data': DataHandler(),
8956 'Delete': DeleteHandler(),
8957 'DELn': DELnHandler(),
8958 'GENn': GENnHandler(),
8959 'GETn': GETnHandler(),
8960 'GLchar': GLcharHandler(),
8961 'GLcharN': GLcharNHandler(),
8962 'HandWritten': HandWrittenHandler(),
8964 'Manual': ManualHandler(),
8965 'PUT': PUTHandler(),
8966 'PUTn': PUTnHandler(),
8967 'PUTSTR': PUTSTRHandler(),
8968 'PUTXn': PUTXnHandler(),
8969 'StateSet': StateSetHandler(),
8970 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
8971 'StateSetFrontBack': StateSetFrontBackHandler(),
8972 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
8973 'StateSetNamedParameter': StateSetNamedParameter(),
8974 'STRn': STRnHandler(),
8975 'Todo': TodoHandler(),
8978 def __init__(self
, name
, info
):
8980 self
.original_name
= info
['original_name']
8982 self
.original_args
= self
.ParseArgs(info
['original_args'])
8984 if 'cmd_args' in info
:
8985 self
.args_for_cmds
= self
.ParseArgs(info
['cmd_args'])
8987 self
.args_for_cmds
= self
.original_args
[:]
8989 self
.return_type
= info
['return_type']
8990 if self
.return_type
!= 'void':
8991 self
.return_arg
= CreateArg(info
['return_type'] + " result")
8993 self
.return_arg
= None
8995 self
.num_pointer_args
= sum(
8996 [1 for arg
in self
.args_for_cmds
if arg
.IsPointer()])
8997 if self
.num_pointer_args
> 0:
8998 for arg
in reversed(self
.original_args
):
9000 self
.last_original_pointer_arg
= arg
9003 self
.last_original_pointer_arg
= None
9005 self
.type_handler
= self
.type_handlers
[info
['type']]
9006 self
.can_auto_generate
= (self
.num_pointer_args
== 0 and
9007 info
['return_type'] == "void")
9010 def ParseArgs(self
, arg_string
):
9011 """Parses a function arg string."""
9013 parts
= arg_string
.split(',')
9014 for arg_string
in parts
:
9015 arg
= CreateArg(arg_string
)
9020 def IsType(self
, type_name
):
9021 """Returns true if function is a certain type."""
9022 return self
.info
['type'] == type_name
9024 def InitFunction(self
):
9025 """Creates command args and calls the init function for the type handler.
9027 Creates argument lists for command buffer commands, eg. self.cmd_args and
9029 Calls the type function initialization.
9030 Override to create different kind of command buffer command argument lists.
9033 for arg
in self
.args_for_cmds
:
9034 arg
.AddCmdArgs(self
.cmd_args
)
9037 for arg
in self
.args_for_cmds
:
9038 arg
.AddInitArgs(self
.init_args
)
9041 self
.init_args
.append(self
.return_arg
)
9043 self
.type_handler
.InitFunction(self
)
9045 def IsImmediate(self
):
9046 """Returns whether the function is immediate data function or not."""
9050 """Returns whether the function has service side validation or not."""
9051 return self
.GetInfo('unsafe', False)
9053 def GetInfo(self
, name
, default
= None):
9054 """Returns a value from the function info for this function."""
9055 if name
in self
.info
:
9056 return self
.info
[name
]
9059 def GetValidArg(self
, arg
):
9060 """Gets a valid argument value for the parameter arg from the function info
9063 index
= self
.GetOriginalArgs().index(arg
)
9067 valid_args
= self
.GetInfo('valid_args')
9068 if valid_args
and str(index
) in valid_args
:
9069 return valid_args
[str(index
)]
9072 def AddInfo(self
, name
, value
):
9074 self
.info
[name
] = value
9076 def IsExtension(self
):
9077 return self
.GetInfo('extension') or self
.GetInfo('extension_flag')
9079 def IsCoreGLFunction(self
):
9080 return (not self
.IsExtension() and
9081 not self
.GetInfo('pepper_interface') and
9082 not self
.IsUnsafe())
9084 def InPepperInterface(self
, interface
):
9085 ext
= self
.GetInfo('pepper_interface')
9086 if not interface
.GetName():
9087 return self
.IsCoreGLFunction()
9088 return ext
== interface
.GetName()
9090 def InAnyPepperExtension(self
):
9091 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
9093 def GetErrorReturnString(self
):
9094 if self
.GetInfo("error_return"):
9095 return self
.GetInfo("error_return")
9096 elif self
.return_type
== "GLboolean":
9098 elif "*" in self
.return_type
:
9102 def GetGLFunctionName(self
):
9103 """Gets the function to call to execute GL for this command."""
9104 if self
.GetInfo('decoder_func'):
9105 return self
.GetInfo('decoder_func')
9106 return "gl%s" % self
.original_name
9108 def GetGLTestFunctionName(self
):
9109 gl_func_name
= self
.GetInfo('gl_test_func')
9110 if gl_func_name
== None:
9111 gl_func_name
= self
.GetGLFunctionName()
9112 if gl_func_name
.startswith("gl"):
9113 gl_func_name
= gl_func_name
[2:]
9115 gl_func_name
= self
.original_name
9118 def GetDataTransferMethods(self
):
9119 return self
.GetInfo('data_transfer_methods',
9120 ['immediate' if self
.num_pointer_args
== 1 else 'shm'])
9122 def AddCmdArg(self
, arg
):
9123 """Adds a cmd argument to this function."""
9124 self
.cmd_args
.append(arg
)
9126 def GetCmdArgs(self
):
9127 """Gets the command args for this function."""
9128 return self
.cmd_args
9130 def ClearCmdArgs(self
):
9131 """Clears the command args for this function."""
9134 def GetCmdConstants(self
):
9135 """Gets the constants for this function."""
9136 return [arg
for arg
in self
.args_for_cmds
if arg
.IsConstant()]
9138 def GetInitArgs(self
):
9139 """Gets the init args for this function."""
9140 return self
.init_args
9142 def GetOriginalArgs(self
):
9143 """Gets the original arguments to this function."""
9144 return self
.original_args
9146 def GetLastOriginalArg(self
):
9147 """Gets the last original argument to this function."""
9148 return self
.original_args
[len(self
.original_args
) - 1]
9150 def GetLastOriginalPointerArg(self
):
9151 return self
.last_original_pointer_arg
9153 def GetResourceIdArg(self
):
9154 for arg
in self
.original_args
:
9155 if hasattr(arg
, 'resource_type'):
9159 def _MaybePrependComma(self
, arg_string
, add_comma
):
9160 """Adds a comma if arg_string is not empty and add_comma is true."""
9162 if add_comma
and len(arg_string
):
9164 return "%s%s" % (comma
, arg_string
)
9166 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
9167 """Gets a list of arguments as they are in GL."""
9168 args
= self
.GetOriginalArgs()
9169 arg_string
= ", ".join(
9170 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9171 return self
._MaybePrependComma
(arg_string
, add_comma
)
9173 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9174 """Gets the list of arguments as they are in GL."""
9175 args
= self
.GetOriginalArgs()
9176 arg_string
= separator
.join(
9177 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9178 return self
._MaybePrependComma
(arg_string
, add_comma
)
9180 def MakeTypedHelperArgString(self
, prefix
, add_comma
= False):
9181 """Gets a list of typed GL arguments after removing unneeded arguments."""
9182 args
= self
.GetOriginalArgs()
9183 arg_string
= ", ".join(
9188 ) for arg
in args
if not arg
.IsConstant()])
9189 return self
._MaybePrependComma
(arg_string
, add_comma
)
9191 def MakeHelperArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9192 """Gets a list of GL arguments after removing unneeded arguments."""
9193 args
= self
.GetOriginalArgs()
9194 arg_string
= separator
.join(
9195 ["%s%s" % (prefix
, arg
.name
)
9196 for arg
in args
if not arg
.IsConstant()])
9197 return self
._MaybePrependComma
(arg_string
, add_comma
)
9199 def MakeTypedPepperArgString(self
, prefix
):
9200 """Gets a list of arguments as they need to be for Pepper."""
9201 if self
.GetInfo("pepper_args"):
9202 return self
.GetInfo("pepper_args")
9204 return self
.MakeTypedOriginalArgString(prefix
, False)
9206 def MapCTypeToPepperIdlType(self
, ctype
, is_for_return_type
=False):
9207 """Converts a C type name to the corresponding Pepper IDL type."""
9209 'char*': '[out] str_t',
9210 'const GLchar* const*': '[out] cstr_t',
9211 'const char*': 'cstr_t',
9212 'const void*': 'mem_t',
9213 'void*': '[out] mem_t',
9214 'void**': '[out] mem_ptr_t',
9216 # We use "GLxxx_ptr_t" for "GLxxx*".
9217 matched
= re
.match(r
'(const )?(GL\w+)\*$', ctype
)
9219 idltype
= matched
.group(2) + '_ptr_t'
9220 if not matched
.group(1):
9221 idltype
= '[out] ' + idltype
9222 # If an in/out specifier is not specified yet, prepend [in].
9223 if idltype
[0] != '[':
9224 idltype
= '[in] ' + idltype
9225 # Strip the in/out specifier for a return type.
9226 if is_for_return_type
:
9227 idltype
= re
.sub(r
'\[\w+\] ', '', idltype
)
9230 def MakeTypedPepperIdlArgStrings(self
):
9231 """Gets a list of arguments as they need to be for Pepper IDL."""
9232 args
= self
.GetOriginalArgs()
9233 return ["%s %s" % (self
.MapCTypeToPepperIdlType(arg
.type), arg
.name
)
9236 def GetPepperName(self
):
9237 if self
.GetInfo("pepper_name"):
9238 return self
.GetInfo("pepper_name")
9241 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
9242 """Gets a typed list of arguments as they need to be for command buffers."""
9243 args
= self
.GetCmdArgs()
9244 arg_string
= ", ".join(
9245 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9246 return self
._MaybePrependComma
(arg_string
, add_comma
)
9248 def MakeCmdArgString(self
, prefix
, add_comma
= False):
9249 """Gets the list of arguments as they need to be for command buffers."""
9250 args
= self
.GetCmdArgs()
9251 arg_string
= ", ".join(
9252 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9253 return self
._MaybePrependComma
(arg_string
, add_comma
)
9255 def MakeTypedInitString(self
, prefix
, add_comma
= False):
9256 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9257 args
= self
.GetInitArgs()
9258 arg_string
= ", ".join(
9259 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9260 return self
._MaybePrependComma
(arg_string
, add_comma
)
9262 def MakeInitString(self
, prefix
, add_comma
= False):
9263 """Gets the list of arguments as they need to be for cmd Init/Set."""
9264 args
= self
.GetInitArgs()
9265 arg_string
= ", ".join(
9266 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9267 return self
._MaybePrependComma
(arg_string
, add_comma
)
9269 def MakeLogArgString(self
):
9270 """Makes a string of the arguments for the LOG macros"""
9271 args
= self
.GetOriginalArgs()
9272 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
9274 def WriteCommandDescription(self
, file):
9275 """Writes a description of the command."""
9276 file.Write("//! Command that corresponds to gl%s.\n" % self
.original_name
)
9278 def WriteHandlerValidation(self
, file):
9279 """Writes validation code for the function."""
9280 for arg
in self
.GetOriginalArgs():
9281 arg
.WriteValidationCode(file, self
)
9282 self
.WriteValidationCode(file)
9284 def WriteHandlerImplementation(self
, file):
9285 """Writes the handler implementation for this command."""
9286 self
.type_handler
.WriteHandlerImplementation(self
, file)
9288 def WriteValidationCode(self
, file):
9289 """Writes the validation code for a command."""
9292 def WriteCmdFlag(self
, file):
9293 """Writes the cmd cmd_flags constant."""
9295 # By default trace only at the highest level 3.
9296 trace_level
= int(self
.GetInfo('trace_level', default
= 3))
9297 if trace_level
not in xrange(0, 4):
9298 raise KeyError("Unhandled trace_level: %d" % trace_level
)
9300 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
9303 cmd_flags
= ' | '.join(flags
)
9307 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
9310 def WriteCmdArgFlag(self
, file):
9311 """Writes the cmd kArgFlags constant."""
9312 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9314 def WriteCmdComputeSize(self
, file):
9315 """Writes the ComputeSize function for the command."""
9316 file.Write(" static uint32_t ComputeSize() {\n")
9318 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9322 def WriteCmdSetHeader(self
, file):
9323 """Writes the cmd's SetHeader function."""
9324 file.Write(" void SetHeader() {\n")
9325 file.Write(" header.SetCmd<ValueType>();\n")
9329 def WriteCmdInit(self
, file):
9330 """Writes the cmd's Init function."""
9331 file.Write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
9332 file.Write(" SetHeader();\n")
9333 args
= self
.GetCmdArgs()
9335 file.Write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
9339 def WriteCmdSet(self
, file):
9340 """Writes the cmd's Set function."""
9341 copy_args
= self
.MakeCmdArgString("_", False)
9342 file.Write(" void* Set(void* cmd%s) {\n" %
9343 self
.MakeTypedCmdArgString("_", True))
9344 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
9345 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
9349 def WriteStruct(self
, file):
9350 self
.type_handler
.WriteStruct(self
, file)
9352 def WriteDocs(self
, file):
9353 self
.type_handler
.WriteDocs(self
, file)
9355 def WriteCmdHelper(self
, file):
9356 """Writes the cmd's helper."""
9357 self
.type_handler
.WriteCmdHelper(self
, file)
9359 def WriteServiceImplementation(self
, file):
9360 """Writes the service implementation for a command."""
9361 self
.type_handler
.WriteServiceImplementation(self
, file)
9363 def WriteServiceUnitTest(self
, file, *extras
):
9364 """Writes the service implementation for a command."""
9365 self
.type_handler
.WriteServiceUnitTest(self
, file, *extras
)
9367 def WriteGLES2CLibImplementation(self
, file):
9368 """Writes the GLES2 C Lib Implemention."""
9369 self
.type_handler
.WriteGLES2CLibImplementation(self
, file)
9371 def WriteGLES2InterfaceHeader(self
, file):
9372 """Writes the GLES2 Interface declaration."""
9373 self
.type_handler
.WriteGLES2InterfaceHeader(self
, file)
9375 def WriteMojoGLES2ImplHeader(self
, file):
9376 """Writes the Mojo GLES2 implementation header declaration."""
9377 self
.type_handler
.WriteMojoGLES2ImplHeader(self
, file)
9379 def WriteMojoGLES2Impl(self
, file):
9380 """Writes the Mojo GLES2 implementation declaration."""
9381 self
.type_handler
.WriteMojoGLES2Impl(self
, file)
9383 def WriteGLES2InterfaceStub(self
, file):
9384 """Writes the GLES2 Interface Stub declaration."""
9385 self
.type_handler
.WriteGLES2InterfaceStub(self
, file)
9387 def WriteGLES2InterfaceStubImpl(self
, file):
9388 """Writes the GLES2 Interface Stub declaration."""
9389 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, file)
9391 def WriteGLES2ImplementationHeader(self
, file):
9392 """Writes the GLES2 Implemention declaration."""
9393 self
.type_handler
.WriteGLES2ImplementationHeader(self
, file)
9395 def WriteGLES2Implementation(self
, file):
9396 """Writes the GLES2 Implemention definition."""
9397 self
.type_handler
.WriteGLES2Implementation(self
, file)
9399 def WriteGLES2TraceImplementationHeader(self
, file):
9400 """Writes the GLES2 Trace Implemention declaration."""
9401 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, file)
9403 def WriteGLES2TraceImplementation(self
, file):
9404 """Writes the GLES2 Trace Implemention definition."""
9405 self
.type_handler
.WriteGLES2TraceImplementation(self
, file)
9407 def WriteGLES2Header(self
, file):
9408 """Writes the GLES2 Implemention unit test."""
9409 self
.type_handler
.WriteGLES2Header(self
, file)
9411 def WriteGLES2ImplementationUnitTest(self
, file):
9412 """Writes the GLES2 Implemention unit test."""
9413 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, file)
9415 def WriteDestinationInitalizationValidation(self
, file):
9416 """Writes the client side destintion initialization validation."""
9417 self
.type_handler
.WriteDestinationInitalizationValidation(self
, file)
9419 def WriteFormatTest(self
, file):
9420 """Writes the cmd's format test."""
9421 self
.type_handler
.WriteFormatTest(self
, file)
9424 class PepperInterface(object):
9425 """A class that represents a function."""
9427 def __init__(self
, info
):
9428 self
.name
= info
["name"]
9429 self
.dev
= info
["dev"]
9434 def GetInterfaceName(self
):
9438 upperint
= "_" + self
.name
.upper()
9441 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
9443 def GetInterfaceString(self
):
9447 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
9449 def GetStructName(self
):
9453 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
9456 class ImmediateFunction(Function
):
9457 """A class that represnets an immediate function command."""
9459 def __init__(self
, func
):
9462 "%sImmediate" % func
.name
,
9465 def InitFunction(self
):
9466 # Override args in original_args and args_for_cmds with immediate versions
9469 new_original_args
= []
9470 for arg
in self
.original_args
:
9471 new_arg
= arg
.GetImmediateVersion()
9473 new_original_args
.append(new_arg
)
9474 self
.original_args
= new_original_args
9476 new_args_for_cmds
= []
9477 for arg
in self
.args_for_cmds
:
9478 new_arg
= arg
.GetImmediateVersion()
9480 new_args_for_cmds
.append(new_arg
)
9482 self
.args_for_cmds
= new_args_for_cmds
9484 Function
.InitFunction(self
)
9486 def IsImmediate(self
):
9489 def WriteCommandDescription(self
, file):
9490 """Overridden from Function"""
9491 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
9494 def WriteServiceImplementation(self
, file):
9495 """Overridden from Function"""
9496 self
.type_handler
.WriteImmediateServiceImplementation(self
, file)
9498 def WriteHandlerImplementation(self
, file):
9499 """Overridden from Function"""
9500 self
.type_handler
.WriteImmediateHandlerImplementation(self
, file)
9502 def WriteServiceUnitTest(self
, file, *extras
):
9503 """Writes the service implementation for a command."""
9504 self
.type_handler
.WriteImmediateServiceUnitTest(self
, file, *extras
)
9506 def WriteValidationCode(self
, file):
9507 """Overridden from Function"""
9508 self
.type_handler
.WriteImmediateValidationCode(self
, file)
9510 def WriteCmdArgFlag(self
, file):
9511 """Overridden from Function"""
9512 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9514 def WriteCmdComputeSize(self
, file):
9515 """Overridden from Function"""
9516 self
.type_handler
.WriteImmediateCmdComputeSize(self
, file)
9518 def WriteCmdSetHeader(self
, file):
9519 """Overridden from Function"""
9520 self
.type_handler
.WriteImmediateCmdSetHeader(self
, file)
9522 def WriteCmdInit(self
, file):
9523 """Overridden from Function"""
9524 self
.type_handler
.WriteImmediateCmdInit(self
, file)
9526 def WriteCmdSet(self
, file):
9527 """Overridden from Function"""
9528 self
.type_handler
.WriteImmediateCmdSet(self
, file)
9530 def WriteCmdHelper(self
, file):
9531 """Overridden from Function"""
9532 self
.type_handler
.WriteImmediateCmdHelper(self
, file)
9534 def WriteFormatTest(self
, file):
9535 """Overridden from Function"""
9536 self
.type_handler
.WriteImmediateFormatTest(self
, file)
9539 class BucketFunction(Function
):
9540 """A class that represnets a bucket version of a function command."""
9542 def __init__(self
, func
):
9545 "%sBucket" % func
.name
,
9548 def InitFunction(self
):
9549 # Override args in original_args and args_for_cmds with bucket versions
9552 new_original_args
= []
9553 for arg
in self
.original_args
:
9554 new_arg
= arg
.GetBucketVersion()
9556 new_original_args
.append(new_arg
)
9557 self
.original_args
= new_original_args
9559 new_args_for_cmds
= []
9560 for arg
in self
.args_for_cmds
:
9561 new_arg
= arg
.GetBucketVersion()
9563 new_args_for_cmds
.append(new_arg
)
9565 self
.args_for_cmds
= new_args_for_cmds
9567 Function
.InitFunction(self
)
9569 def WriteCommandDescription(self
, file):
9570 """Overridden from Function"""
9571 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
9574 def WriteServiceImplementation(self
, file):
9575 """Overridden from Function"""
9576 self
.type_handler
.WriteBucketServiceImplementation(self
, file)
9578 def WriteHandlerImplementation(self
, file):
9579 """Overridden from Function"""
9580 self
.type_handler
.WriteBucketHandlerImplementation(self
, file)
9582 def WriteServiceUnitTest(self
, file, *extras
):
9583 """Overridden from Function"""
9584 self
.type_handler
.WriteBucketServiceUnitTest(self
, file, *extras
)
9586 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9587 """Overridden from Function"""
9588 args
= self
.GetOriginalArgs()
9589 arg_string
= separator
.join(
9590 ["%s%s" % (prefix
, arg
.name
[0:-10] if arg
.name
.endswith("_bucket_id")
9591 else arg
.name
) for arg
in args
])
9592 return super(BucketFunction
, self
)._MaybePrependComma
(arg_string
, add_comma
)
9595 def CreateArg(arg_string
):
9596 """Creates an Argument."""
9597 arg_parts
= arg_string
.split()
9598 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
9600 # Is this a pointer argument?
9601 elif arg_string
.find('*') >= 0:
9602 return PointerArgument(
9604 " ".join(arg_parts
[0:-1]))
9605 # Is this a resource argument? Must come after pointer check.
9606 elif arg_parts
[0].startswith('GLidBind'):
9607 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9608 elif arg_parts
[0].startswith('GLidZero'):
9609 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9610 elif arg_parts
[0].startswith('GLid'):
9611 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9612 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
9613 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9614 elif arg_parts
[0].startswith('GLbitfield') and len(arg_parts
[0]) > 10:
9615 return BitFieldArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9616 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
9617 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9618 elif arg_parts
[0].startswith('GLboolean'):
9619 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9620 elif arg_parts
[0].startswith('GLintUniformLocation'):
9621 return UniformLocationArgument(arg_parts
[-1])
9622 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
9623 not arg_parts
[0].startswith('GLintptr')):
9624 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9625 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
9626 arg_parts
[0].startswith('GLintptrNotNegative')):
9627 return SizeNotNegativeArgument(arg_parts
[-1],
9628 " ".join(arg_parts
[0:-1]),
9629 arg_parts
[0][0:-11])
9630 elif arg_parts
[0].startswith('GLsize'):
9631 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9633 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9636 class GLGenerator(object):
9637 """A class to generate GL command buffers."""
9639 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9641 def __init__(self
, verbose
):
9642 self
.original_functions
= []
9644 self
.verbose
= verbose
9646 self
.pepper_interfaces
= []
9647 self
.interface_info
= {}
9648 self
.generated_cpp_filenames
= []
9650 for interface
in _PEPPER_INTERFACES
:
9651 interface
= PepperInterface(interface
)
9652 self
.pepper_interfaces
.append(interface
)
9653 self
.interface_info
[interface
.GetName()] = interface
9655 def AddFunction(self
, func
):
9656 """Adds a function."""
9657 self
.functions
.append(func
)
9659 def GetFunctionInfo(self
, name
):
9660 """Gets a type info for the given function name."""
9661 if name
in _FUNCTION_INFO
:
9662 func_info
= _FUNCTION_INFO
[name
].copy()
9666 if not 'type' in func_info
:
9667 func_info
['type'] = ''
9672 """Prints something if verbose is true."""
9676 def Error(self
, msg
):
9677 """Prints an error."""
9678 print "Error: %s" % msg
9681 def WriteLicense(self
, file):
9682 """Writes the license."""
9683 file.Write(_LICENSE
)
9685 def WriteNamespaceOpen(self
, file):
9686 """Writes the code for the namespace."""
9687 file.Write("namespace gpu {\n")
9688 file.Write("namespace gles2 {\n")
9691 def WriteNamespaceClose(self
, file):
9692 """Writes the code to close the namespace."""
9693 file.Write("} // namespace gles2\n")
9694 file.Write("} // namespace gpu\n")
9697 def ParseGLH(self
, filename
):
9698 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9699 f
= open(filename
, "r")
9700 functions
= f
.read()
9702 for line
in functions
.splitlines():
9703 match
= self
._function
_re
.match(line
)
9705 func_name
= match
.group(2)[2:]
9706 func_info
= self
.GetFunctionInfo(func_name
)
9707 if func_info
['type'] == 'Noop':
9710 parsed_func_info
= {
9711 'original_name': func_name
,
9712 'original_args': match
.group(3),
9713 'return_type': match
.group(1).strip(),
9716 for k
in parsed_func_info
.keys():
9717 if not k
in func_info
:
9718 func_info
[k
] = parsed_func_info
[k
]
9720 f
= Function(func_name
, func_info
)
9721 self
.original_functions
.append(f
)
9723 #for arg in f.GetOriginalArgs():
9724 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9725 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9727 gen_cmd
= f
.GetInfo('gen_cmd')
9728 if gen_cmd
== True or gen_cmd
== None:
9729 if f
.type_handler
.NeedsDataTransferFunction(f
):
9730 methods
= f
.GetDataTransferMethods()
9731 if 'immediate' in methods
:
9732 self
.AddFunction(ImmediateFunction(f
))
9733 if 'bucket' in methods
:
9734 self
.AddFunction(BucketFunction(f
))
9735 if 'shm' in methods
:
9740 self
.Log("Auto Generated Functions : %d" %
9741 len([f
for f
in self
.functions
if f
.can_auto_generate
or
9742 (not f
.IsType('') and not f
.IsType('Custom') and
9743 not f
.IsType('Todo'))]))
9745 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
9746 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
9747 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
9750 self
.Log(" %-10s %-20s gl%s" % (f
.info
['type'], f
.return_type
, f
.name
))
9752 def WriteCommandIds(self
, filename
):
9753 """Writes the command buffer format"""
9754 file = CHeaderWriter(filename
)
9755 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
9757 for func
in self
.functions
:
9758 file.Write(" %-60s /* %d */ \\\n" %
9759 ("OP(%s)" % func
.name
, id))
9763 file.Write("enum CommandId {\n")
9764 file.Write(" kStartPoint = cmd::kLastCommonId, "
9765 "// All GLES2 commands start after this.\n")
9766 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
9767 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9768 file.Write("#undef GLES2_CMD_OP\n")
9769 file.Write(" kNumCommands\n")
9773 self
.generated_cpp_filenames
.append(file.filename
)
9775 def WriteFormat(self
, filename
):
9776 """Writes the command buffer format"""
9777 file = CHeaderWriter(filename
)
9778 # Forward declaration of a few enums used in constant argument
9779 # to avoid including GL header files.
9781 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9782 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9785 for enum
in enum_defines
:
9786 file.Write("#define %s %s\n" % (enum
, enum_defines
[enum
]))
9788 for func
in self
.functions
:
9790 #gen_cmd = func.GetInfo('gen_cmd')
9791 #if gen_cmd == True or gen_cmd == None:
9792 func
.WriteStruct(file)
9795 self
.generated_cpp_filenames
.append(file.filename
)
9797 def WriteDocs(self
, filename
):
9798 """Writes the command buffer doc version of the commands"""
9799 file = CWriter(filename
)
9800 for func
in self
.functions
:
9802 #gen_cmd = func.GetInfo('gen_cmd')
9803 #if gen_cmd == True or gen_cmd == None:
9804 func
.WriteDocs(file)
9807 self
.generated_cpp_filenames
.append(file.filename
)
9809 def WriteFormatTest(self
, filename
):
9810 """Writes the command buffer format test."""
9811 file = CHeaderWriter(
9813 "// This file contains unit tests for gles2 commmands\n"
9814 "// It is included by gles2_cmd_format_test.cc\n"
9817 for func
in self
.functions
:
9819 #gen_cmd = func.GetInfo('gen_cmd')
9820 #if gen_cmd == True or gen_cmd == None:
9821 func
.WriteFormatTest(file)
9824 self
.generated_cpp_filenames
.append(file.filename
)
9826 def WriteCmdHelperHeader(self
, filename
):
9827 """Writes the gles2 command helper."""
9828 file = CHeaderWriter(filename
)
9830 for func
in self
.functions
:
9832 #gen_cmd = func.GetInfo('gen_cmd')
9833 #if gen_cmd == True or gen_cmd == None:
9834 func
.WriteCmdHelper(file)
9837 self
.generated_cpp_filenames
.append(file.filename
)
9839 def WriteServiceContextStateHeader(self
, filename
):
9840 """Writes the service context state header."""
9841 file = CHeaderWriter(
9843 "// It is included by context_state.h\n")
9844 file.Write("struct EnableFlags {\n")
9845 file.Write(" EnableFlags();\n")
9846 for capability
in _CAPABILITY_FLAGS
:
9847 file.Write(" bool %s;\n" % capability
['name'])
9848 file.Write(" bool cached_%s;\n" % capability
['name'])
9849 file.Write("};\n\n")
9851 for state_name
in sorted(_STATES
.keys()):
9852 state
= _STATES
[state_name
]
9853 for item
in state
['states']:
9854 if isinstance(item
['default'], list):
9855 file.Write("%s %s[%d];\n" % (item
['type'], item
['name'],
9856 len(item
['default'])))
9858 file.Write("%s %s;\n" % (item
['type'], item
['name']))
9860 if item
.get('cached', False):
9861 if isinstance(item
['default'], list):
9862 file.Write("%s cached_%s[%d];\n" % (item
['type'], item
['name'],
9863 len(item
['default'])))
9865 file.Write("%s cached_%s;\n" % (item
['type'], item
['name']))
9870 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9873 for capability
in _CAPABILITY_FLAGS
:
9876 """ % capability
['name'].upper())
9878 if (enable_flags.cached_%(name)s == enable &&
9879 !ignore_cached_state)
9881 enable_flags.cached_%(name)s = enable;
9898 self
.generated_cpp_filenames
.append(file.filename
)
9900 def WriteClientContextStateHeader(self
, filename
):
9901 """Writes the client context state header."""
9902 file = CHeaderWriter(
9904 "// It is included by client_context_state.h\n")
9905 file.Write("struct EnableFlags {\n")
9906 file.Write(" EnableFlags();\n")
9907 for capability
in _CAPABILITY_FLAGS
:
9908 file.Write(" bool %s;\n" % capability
['name'])
9909 file.Write("};\n\n")
9912 self
.generated_cpp_filenames
.append(file.filename
)
9914 def WriteContextStateGetters(self
, file, class_name
):
9915 """Writes the state getters."""
9916 for gl_type
in ["GLint", "GLfloat"]:
9918 bool %s::GetStateAs%s(
9919 GLenum pname, %s* params, GLsizei* num_written) const {
9921 """ % (class_name
, gl_type
, gl_type
))
9922 for state_name
in sorted(_STATES
.keys()):
9923 state
= _STATES
[state_name
]
9925 file.Write(" case %s:\n" % state
['enum'])
9926 file.Write(" *num_written = %d;\n" % len(state
['states']))
9927 file.Write(" if (params) {\n")
9928 for ndx
,item
in enumerate(state
['states']):
9929 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
9930 (ndx
, gl_type
, item
['name']))
9932 file.Write(" return true;\n")
9934 for item
in state
['states']:
9935 file.Write(" case %s:\n" % item
['enum'])
9936 if isinstance(item
['default'], list):
9937 item_len
= len(item
['default'])
9938 file.Write(" *num_written = %d;\n" % item_len
)
9939 file.Write(" if (params) {\n")
9940 if item
['type'] == gl_type
:
9941 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9942 (item
['name'], item
['type'], item_len
))
9944 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
9946 file.Write(" params[i] = %s;\n" %
9947 (GetGLGetTypeConversion(gl_type
, item
['type'],
9948 "%s[i]" % item
['name'])))
9951 file.Write(" *num_written = 1;\n")
9952 file.Write(" if (params) {\n")
9953 file.Write(" params[0] = %s;\n" %
9954 (GetGLGetTypeConversion(gl_type
, item
['type'],
9957 file.Write(" return true;\n")
9958 for capability
in _CAPABILITY_FLAGS
:
9959 file.Write(" case GL_%s:\n" % capability
['name'].upper())
9960 file.Write(" *num_written = 1;\n")
9961 file.Write(" if (params) {\n")
9963 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9964 (gl_type
, capability
['name']))
9966 file.Write(" return true;\n")
9967 file.Write(""" default:
9973 def WriteServiceContextStateImpl(self
, filename
):
9974 """Writes the context state service implementation."""
9975 file = CHeaderWriter(
9977 "// It is included by context_state.cc\n")
9979 for capability
in _CAPABILITY_FLAGS
:
9980 code
.append("%s(%s)" %
9981 (capability
['name'],
9982 ('false', 'true')['default' in capability
]))
9983 code
.append("cached_%s(%s)" %
9984 (capability
['name'],
9985 ('false', 'true')['default' in capability
]))
9986 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9990 file.Write("void ContextState::Initialize() {\n")
9991 for state_name
in sorted(_STATES
.keys()):
9992 state
= _STATES
[state_name
]
9993 for item
in state
['states']:
9994 if isinstance(item
['default'], list):
9995 for ndx
, value
in enumerate(item
['default']):
9996 file.Write(" %s[%d] = %s;\n" % (item
['name'], ndx
, value
))
9998 file.Write(" %s = %s;\n" % (item
['name'], item
['default']))
9999 if item
.get('cached', False):
10000 if isinstance(item
['default'], list):
10001 for ndx
, value
in enumerate(item
['default']):
10002 file.Write(" cached_%s[%d] = %s;\n" % (item
['name'], ndx
, value
))
10004 file.Write(" cached_%s = %s;\n" % (item
['name'], item
['default']))
10008 void ContextState::InitCapabilities(const ContextState* prev_state) const {
10010 def WriteCapabilities(test_prev
, es3_caps
):
10011 for capability
in _CAPABILITY_FLAGS
:
10012 capability_name
= capability
['name']
10013 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10014 if capability_es3
and not es3_caps
or not capability_es3
and es3_caps
:
10017 file.Write(""" if (prev_state->enable_flags.cached_%s !=
10018 enable_flags.cached_%s) {\n""" %
10019 (capability_name
, capability_name
))
10020 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
10021 (capability_name
.upper(), capability_name
))
10025 file.Write(" if (prev_state) {")
10026 WriteCapabilities(True, False)
10027 file.Write(" if (feature_info_->IsES3Capable()) {\n")
10028 WriteCapabilities(True, True)
10030 file.Write(" } else {")
10031 WriteCapabilities(False, False)
10032 file.Write(" if (feature_info_->IsES3Capable()) {\n")
10033 WriteCapabilities(False, True)
10039 void ContextState::InitState(const ContextState *prev_state) const {
10042 def WriteStates(test_prev
):
10043 # We need to sort the keys so the expectations match
10044 for state_name
in sorted(_STATES
.keys()):
10045 state
= _STATES
[state_name
]
10046 if state
['type'] == 'FrontBack':
10047 num_states
= len(state
['states'])
10048 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
10050 file.Write(" if (")
10052 for place
, item
in enumerate(group
):
10053 item_name
= CachedStateName(item
)
10054 args
.append('%s' % item_name
)
10057 file.Write(' ||\n')
10058 file.Write("(%s != prev_state->%s)" % (item_name
, item_name
))
10062 " gl%s(%s, %s);\n" %
10063 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
10064 elif state
['type'] == 'NamedParameter':
10065 for item
in state
['states']:
10066 item_name
= CachedStateName(item
)
10068 if 'extension_flag' in item
:
10069 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
10070 item
['extension_flag'])
10072 if isinstance(item
['default'], list):
10073 file.Write(" if (memcmp(prev_state->%s, %s, "
10074 "sizeof(%s) * %d)) {\n" %
10075 (item_name
, item_name
, item
['type'],
10076 len(item
['default'])))
10078 file.Write(" if (prev_state->%s != %s) {\n " %
10079 (item_name
, item_name
))
10080 if 'gl_version_flag' in item
:
10081 item_name
= item
['gl_version_flag']
10083 if item_name
[0] == '!':
10085 item_name
= item_name
[1:]
10086 file.Write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10087 (inverted
, item_name
))
10088 file.Write(" gl%s(%s, %s);\n" %
10091 if 'enum_set' in item
else item
['enum']),
10093 if 'gl_version_flag' in item
:
10096 if 'extension_flag' in item
:
10099 if 'extension_flag' in item
:
10102 if 'extension_flag' in state
:
10103 file.Write(" if (feature_info_->feature_flags().%s)\n " %
10104 state
['extension_flag'])
10106 file.Write(" if (")
10108 for place
, item
in enumerate(state
['states']):
10109 item_name
= CachedStateName(item
)
10110 args
.append('%s' % item_name
)
10113 file.Write(' ||\n')
10114 file.Write("(%s != prev_state->%s)" %
10115 (item_name
, item_name
))
10118 file.Write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
10120 file.Write(" if (prev_state) {")
10122 file.Write(" } else {")
10127 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
10130 for capability
in _CAPABILITY_FLAGS
:
10131 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10132 file.Write(" return enable_flags.%s;\n" % capability
['name'])
10133 file.Write(""" default:
10140 self
.WriteContextStateGetters(file, "ContextState")
10142 self
.generated_cpp_filenames
.append(file.filename
)
10144 def WriteClientContextStateImpl(self
, filename
):
10145 """Writes the context state client side implementation."""
10146 file = CHeaderWriter(
10148 "// It is included by client_context_state.cc\n")
10150 for capability
in _CAPABILITY_FLAGS
:
10151 code
.append("%s(%s)" %
10152 (capability
['name'],
10153 ('false', 'true')['default' in capability
]))
10155 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10160 bool ClientContextState::SetCapabilityState(
10161 GLenum cap, bool enabled, bool* changed) {
10165 for capability
in _CAPABILITY_FLAGS
:
10166 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10167 file.Write(""" if (enable_flags.%(name)s != enabled) {
10169 enable_flags.%(name)s = enabled;
10173 file.Write(""" default:
10178 file.Write("""bool ClientContextState::GetEnabled(
10179 GLenum cap, bool* enabled) const {
10182 for capability
in _CAPABILITY_FLAGS
:
10183 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10184 file.Write(" *enabled = enable_flags.%s;\n" % capability
['name'])
10185 file.Write(" return true;\n")
10186 file.Write(""" default:
10192 self
.generated_cpp_filenames
.append(file.filename
)
10194 def WriteServiceImplementation(self
, filename
):
10195 """Writes the service decorder implementation."""
10196 file = CHeaderWriter(
10198 "// It is included by gles2_cmd_decoder.cc\n")
10200 for func
in self
.functions
:
10202 #gen_cmd = func.GetInfo('gen_cmd')
10203 #if gen_cmd == True or gen_cmd == None:
10204 func
.WriteServiceImplementation(file)
10207 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10210 for capability
in _CAPABILITY_FLAGS
:
10211 file.Write(" case GL_%s:\n" % capability
['name'].upper())
10212 if 'state_flag' in capability
:
10215 state_.enable_flags.%(name)s = enabled;
10216 if (state_.enable_flags.cached_%(name)s != enabled
10217 || state_.ignore_cached_state) {
10218 %(state_flag)s = true;
10224 state_.enable_flags.%(name)s = enabled;
10225 if (state_.enable_flags.cached_%(name)s != enabled
10226 || state_.ignore_cached_state) {
10227 state_.enable_flags.cached_%(name)s = enabled;
10232 file.Write(""" default:
10239 self
.generated_cpp_filenames
.append(file.filename
)
10241 def WriteServiceUnitTests(self
, filename
):
10242 """Writes the service decorder unit tests."""
10243 num_tests
= len(self
.functions
)
10244 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
10246 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
10248 name
= filename
% count
10249 file = CHeaderWriter(
10251 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count
)
10252 test_name
= 'GLES2DecoderTest%d' % count
10253 end
= test_num
+ FUNCTIONS_PER_FILE
10254 if end
> num_tests
:
10256 for idx
in range(test_num
, end
):
10257 func
= self
.functions
[idx
]
10259 # Do any filtering of the functions here, so that the functions
10260 # will not move between the numbered files if filtering properties
10262 if func
.GetInfo('extension_flag'):
10266 #gen_cmd = func.GetInfo('gen_cmd')
10267 #if gen_cmd == True or gen_cmd == None:
10268 if func
.GetInfo('unit_test') == False:
10269 file.Write("// TODO(gman): %s\n" % func
.name
)
10271 func
.WriteServiceUnitTest(file, {
10272 'test_name': test_name
10275 self
.generated_cpp_filenames
.append(file.filename
)
10276 file = CHeaderWriter(
10278 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
10280 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10281 bool es3_capable) {""")
10282 for capability
in _CAPABILITY_FLAGS
:
10283 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10284 if not capability_es3
:
10285 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10286 (capability
['name'].upper(),
10287 ('false', 'true')['default' in capability
]))
10289 file.Write(" if (es3_capable) {")
10290 for capability
in _CAPABILITY_FLAGS
:
10291 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10293 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
10294 (capability
['name'].upper(),
10295 ('false', 'true')['default' in capability
]))
10299 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10302 # We need to sort the keys so the expectations match
10303 for state_name
in sorted(_STATES
.keys()):
10304 state
= _STATES
[state_name
]
10305 if state
['type'] == 'FrontBack':
10306 num_states
= len(state
['states'])
10307 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
10310 if 'expected' in item
:
10311 args
.append(item
['expected'])
10313 args
.append(item
['default'])
10315 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10316 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
10317 file.Write(" .Times(1)\n")
10318 file.Write(" .RetiresOnSaturation();\n")
10319 elif state
['type'] == 'NamedParameter':
10320 for item
in state
['states']:
10321 if 'extension_flag' in item
:
10322 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10323 item
['extension_flag'])
10325 expect_value
= item
['default']
10326 if isinstance(expect_value
, list):
10327 # TODO: Currently we do not check array values.
10331 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10334 if 'enum_set' in item
else item
['enum']),
10336 file.Write(" .Times(1)\n")
10337 file.Write(" .RetiresOnSaturation();\n")
10338 if 'extension_flag' in item
:
10341 if 'extension_flag' in state
:
10342 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10343 state
['extension_flag'])
10346 for item
in state
['states']:
10347 if 'expected' in item
:
10348 args
.append(item
['expected'])
10350 args
.append(item
['default'])
10351 # TODO: Currently we do not check array values.
10352 args
= ["_" if isinstance(arg
, list) else arg
for arg
in args
]
10353 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10354 (state
['func'], ", ".join(args
)))
10355 file.Write(" .Times(1)\n")
10356 file.Write(" .RetiresOnSaturation();\n")
10357 if 'extension_flag' in state
:
10362 self
.generated_cpp_filenames
.append(file.filename
)
10364 def WriteServiceUnitTestsForExtensions(self
, filename
):
10365 """Writes the service decorder unit tests for functions with extension_flag.
10367 The functions are special in that they need a specific unit test
10368 baseclass to turn on the extension.
10370 functions
= [f
for f
in self
.functions
if f
.GetInfo('extension_flag')]
10371 file = CHeaderWriter(
10373 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
10374 for func
in functions
:
10376 if func
.GetInfo('unit_test') == False:
10377 file.Write("// TODO(gman): %s\n" % func
.name
)
10379 extension
= ToCamelCase(
10380 ToGLExtensionString(func
.GetInfo('extension_flag')))
10381 func
.WriteServiceUnitTest(file, {
10382 'test_name': 'GLES2DecoderTestWith%s' % extension
10386 self
.generated_cpp_filenames
.append(file.filename
)
10388 def WriteGLES2Header(self
, filename
):
10389 """Writes the GLES2 header."""
10390 file = CHeaderWriter(
10392 "// This file contains Chromium-specific GLES2 declarations.\n\n")
10394 for func
in self
.original_functions
:
10395 func
.WriteGLES2Header(file)
10399 self
.generated_cpp_filenames
.append(file.filename
)
10401 def WriteGLES2CLibImplementation(self
, filename
):
10402 """Writes the GLES2 c lib implementation."""
10403 file = CHeaderWriter(
10405 "// These functions emulate GLES2 over command buffers.\n")
10407 for func
in self
.original_functions
:
10408 func
.WriteGLES2CLibImplementation(file)
10413 extern const NameToFunc g_gles2_function_table[] = {
10415 for func
in self
.original_functions
:
10417 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10418 (func
.name
, func
.name
))
10419 file.Write(""" { NULL, NULL, },
10422 } // namespace gles2
10425 self
.generated_cpp_filenames
.append(file.filename
)
10427 def WriteGLES2InterfaceHeader(self
, filename
):
10428 """Writes the GLES2 interface header."""
10429 file = CHeaderWriter(
10431 "// This file is included by gles2_interface.h to declare the\n"
10432 "// GL api functions.\n")
10433 for func
in self
.original_functions
:
10434 func
.WriteGLES2InterfaceHeader(file)
10436 self
.generated_cpp_filenames
.append(file.filename
)
10438 def WriteMojoGLES2ImplHeader(self
, filename
):
10439 """Writes the Mojo GLES2 implementation header."""
10440 file = CHeaderWriter(
10442 "// This file is included by gles2_interface.h to declare the\n"
10443 "// GL api functions.\n")
10446 #include "gpu/command_buffer/client/gles2_interface.h"
10447 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10451 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10453 explicit MojoGLES2Impl(MojoGLES2Context context) {
10454 context_ = context;
10456 ~MojoGLES2Impl() override {}
10459 for func
in self
.original_functions
:
10460 func
.WriteMojoGLES2ImplHeader(file)
10463 MojoGLES2Context context_;
10466 } // namespace mojo
10470 self
.generated_cpp_filenames
.append(file.filename
)
10472 def WriteMojoGLES2Impl(self
, filename
):
10473 """Writes the Mojo GLES2 implementation."""
10474 file = CWriter(filename
)
10475 file.Write(_LICENSE
)
10476 file.Write(_DO_NOT_EDIT_WARNING
)
10479 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10481 #include "base/logging.h"
10482 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_copy_texture.h"
10483 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_image.h"
10484 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10485 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_pixel_transfer_buffer_object.h"
10486 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10487 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10488 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10489 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10490 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10496 for func
in self
.original_functions
:
10497 func
.WriteMojoGLES2Impl(file)
10500 } // namespace mojo
10504 self
.generated_cpp_filenames
.append(file.filename
)
10506 def WriteGLES2InterfaceStub(self
, filename
):
10507 """Writes the GLES2 interface stub header."""
10508 file = CHeaderWriter(
10510 "// This file is included by gles2_interface_stub.h.\n")
10511 for func
in self
.original_functions
:
10512 func
.WriteGLES2InterfaceStub(file)
10514 self
.generated_cpp_filenames
.append(file.filename
)
10516 def WriteGLES2InterfaceStubImpl(self
, filename
):
10517 """Writes the GLES2 interface header."""
10518 file = CHeaderWriter(
10520 "// This file is included by gles2_interface_stub.cc.\n")
10521 for func
in self
.original_functions
:
10522 func
.WriteGLES2InterfaceStubImpl(file)
10524 self
.generated_cpp_filenames
.append(file.filename
)
10526 def WriteGLES2ImplementationHeader(self
, filename
):
10527 """Writes the GLES2 Implementation header."""
10528 file = CHeaderWriter(
10530 "// This file is included by gles2_implementation.h to declare the\n"
10531 "// GL api functions.\n")
10532 for func
in self
.original_functions
:
10533 func
.WriteGLES2ImplementationHeader(file)
10535 self
.generated_cpp_filenames
.append(file.filename
)
10537 def WriteGLES2Implementation(self
, filename
):
10538 """Writes the GLES2 Implementation."""
10539 file = CHeaderWriter(
10541 "// This file is included by gles2_implementation.cc to define the\n"
10542 "// GL api functions.\n")
10543 for func
in self
.original_functions
:
10544 func
.WriteGLES2Implementation(file)
10546 self
.generated_cpp_filenames
.append(file.filename
)
10548 def WriteGLES2TraceImplementationHeader(self
, filename
):
10549 """Writes the GLES2 Trace Implementation header."""
10550 file = CHeaderWriter(
10552 "// This file is included by gles2_trace_implementation.h\n")
10553 for func
in self
.original_functions
:
10554 func
.WriteGLES2TraceImplementationHeader(file)
10556 self
.generated_cpp_filenames
.append(file.filename
)
10558 def WriteGLES2TraceImplementation(self
, filename
):
10559 """Writes the GLES2 Trace Implementation."""
10560 file = CHeaderWriter(
10562 "// This file is included by gles2_trace_implementation.cc\n")
10563 for func
in self
.original_functions
:
10564 func
.WriteGLES2TraceImplementation(file)
10566 self
.generated_cpp_filenames
.append(file.filename
)
10568 def WriteGLES2ImplementationUnitTests(self
, filename
):
10569 """Writes the GLES2 helper header."""
10570 file = CHeaderWriter(
10572 "// This file is included by gles2_implementation.h to declare the\n"
10573 "// GL api functions.\n")
10574 for func
in self
.original_functions
:
10575 func
.WriteGLES2ImplementationUnitTest(file)
10577 self
.generated_cpp_filenames
.append(file.filename
)
10579 def WriteServiceUtilsHeader(self
, filename
):
10580 """Writes the gles2 auto generated utility header."""
10581 file = CHeaderWriter(filename
)
10582 for name
in sorted(_NAMED_TYPE_INFO
.keys()):
10583 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10584 if named_type
.IsConstant():
10586 file.Write("ValueValidator<%s> %s;\n" %
10587 (named_type
.GetType(), ToUnderscore(name
)))
10590 self
.generated_cpp_filenames
.append(file.filename
)
10592 def WriteServiceUtilsImplementation(self
, filename
):
10593 """Writes the gles2 auto generated utility implementation."""
10594 file = CHeaderWriter(filename
)
10595 names
= sorted(_NAMED_TYPE_INFO
.keys())
10597 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10598 if named_type
.IsConstant():
10600 if named_type
.GetValidValues():
10601 file.Write("static const %s valid_%s_table[] = {\n" %
10602 (named_type
.GetType(), ToUnderscore(name
)))
10603 for value
in named_type
.GetValidValues():
10604 file.Write(" %s,\n" % value
)
10607 if named_type
.GetValidValuesES3():
10608 file.Write("static const %s valid_%s_table_es3[] = {\n" %
10609 (named_type
.GetType(), ToUnderscore(name
)))
10610 for value
in named_type
.GetValidValuesES3():
10611 file.Write(" %s,\n" % value
)
10614 if named_type
.GetDeprecatedValuesES3():
10615 file.Write("static const %s deprecated_%s_table_es3[] = {\n" %
10616 (named_type
.GetType(), ToUnderscore(name
)))
10617 for value
in named_type
.GetDeprecatedValuesES3():
10618 file.Write(" %s,\n" % value
)
10621 file.Write("Validators::Validators()")
10623 for count
, name
in enumerate(names
):
10624 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10625 if named_type
.IsConstant():
10627 if named_type
.GetValidValues():
10628 code
= """%(pre)s%(name)s(
10629 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10631 code
= "%(pre)s%(name)s()"
10632 file.Write(code
% {
10633 'name': ToUnderscore(name
),
10637 file.Write(" {\n");
10638 file.Write("}\n\n");
10640 file.Write("void Validators::UpdateValuesES3() {\n")
10642 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10643 if named_type
.GetDeprecatedValuesES3():
10644 code
= """ %(name)s.RemoveValues(
10645 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10647 file.Write(code
% {
10648 'name': ToUnderscore(name
),
10650 if named_type
.GetValidValuesES3():
10651 code
= """ %(name)s.AddValues(
10652 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10654 file.Write(code
% {
10655 'name': ToUnderscore(name
),
10657 file.Write("}\n\n");
10659 self
.generated_cpp_filenames
.append(file.filename
)
10661 def WriteCommonUtilsHeader(self
, filename
):
10662 """Writes the gles2 common utility header."""
10663 file = CHeaderWriter(filename
)
10664 type_infos
= sorted(_NAMED_TYPE_INFO
.keys())
10665 for type_info
in type_infos
:
10666 if _NAMED_TYPE_INFO
[type_info
]['type'] == 'GLenum':
10667 file.Write("static std::string GetString%s(uint32_t value);\n" %
10671 self
.generated_cpp_filenames
.append(file.filename
)
10673 def WriteCommonUtilsImpl(self
, filename
):
10674 """Writes the gles2 common utility header."""
10675 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10677 for fname
in ['third_party/khronos/GLES2/gl2.h',
10678 'third_party/khronos/GLES2/gl2ext.h',
10679 'third_party/khronos/GLES3/gl3.h',
10680 'gpu/GLES2/gl2chromium.h',
10681 'gpu/GLES2/gl2extchromium.h']:
10682 lines
= open(fname
).readlines()
10684 m
= enum_re
.match(line
)
10688 if len(value
) <= 10:
10689 if not value
in dict:
10691 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10692 elif dict[value
] != name
and (name
.endswith('_CHROMIUM') or
10693 dict[value
].endswith('_CHROMIUM')):
10694 self
.Error("code collision: %s and %s have the same code %s" %
10695 (dict[value
], name
, value
))
10697 file = CHeaderWriter(filename
)
10698 file.Write("static const GLES2Util::EnumToString "
10699 "enum_to_string_table[] = {\n")
10701 file.Write(' { %s, "%s", },\n' % (value
, dict[value
]))
10704 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10705 enum_to_string_table;
10706 const size_t GLES2Util::enum_to_string_table_len_ =
10707 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10711 enums
= sorted(_NAMED_TYPE_INFO
.keys())
10713 if _NAMED_TYPE_INFO
[enum
]['type'] == 'GLenum':
10714 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10716 valid_list
= _NAMED_TYPE_INFO
[enum
]['valid']
10717 if 'valid_es3' in _NAMED_TYPE_INFO
[enum
]:
10718 valid_list
= valid_list
+ _NAMED_TYPE_INFO
[enum
]['valid_es3']
10719 assert len(valid_list
) == len(set(valid_list
))
10720 if len(valid_list
) > 0:
10721 file.Write(" static const EnumToString string_table[] = {\n")
10722 for value
in valid_list
:
10723 file.Write(' { %s, "%s" },\n' % (value
, value
))
10725 return GLES2Util::GetQualifiedEnumString(
10726 string_table, arraysize(string_table), value);
10731 file.Write(""" return GLES2Util::GetQualifiedEnumString(
10737 self
.generated_cpp_filenames
.append(file.filename
)
10739 def WritePepperGLES2Interface(self
, filename
, dev
):
10740 """Writes the Pepper OpenGLES interface definition."""
10741 file = CWriter(filename
)
10742 file.Write(_LICENSE
)
10743 file.Write(_DO_NOT_EDIT_WARNING
)
10745 file.Write("label Chrome {\n")
10746 file.Write(" M39 = 1.0\n")
10747 file.Write("};\n\n")
10750 # Declare GL types.
10751 file.Write("[version=1.0]\n")
10752 file.Write("describe {\n")
10753 for gltype
in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10754 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10755 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10756 'GLubyte', 'GLuint', 'GLushort']:
10757 file.Write(" %s;\n" % gltype
)
10758 file.Write(" %s_ptr_t;\n" % gltype
)
10759 file.Write("};\n\n")
10761 # C level typedefs.
10762 file.Write("#inline c\n")
10763 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
10765 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10767 file.Write("\n#ifndef __gl2_h_\n")
10768 for (k
, v
) in _GL_TYPES
.iteritems():
10769 file.Write("typedef %s %s;\n" % (v
, k
))
10770 file.Write("#ifdef _WIN64\n")
10771 for (k
, v
) in _GL_TYPES_64
.iteritems():
10772 file.Write("typedef %s %s;\n" % (v
, k
))
10773 file.Write("#else\n")
10774 for (k
, v
) in _GL_TYPES_32
.iteritems():
10775 file.Write("typedef %s %s;\n" % (v
, k
))
10776 file.Write("#endif // _WIN64\n")
10777 file.Write("#endif // __gl2_h_\n\n")
10778 file.Write("#endinl\n")
10780 for interface
in self
.pepper_interfaces
:
10781 if interface
.dev
!= dev
:
10783 # Historically, we provide OpenGLES2 interfaces with struct
10784 # namespace. Not to break code which uses the interface as
10785 # "struct OpenGLES2", we put it in struct namespace.
10786 file.Write('\n[macro="%s", force_struct_namespace]\n' %
10787 interface
.GetInterfaceName())
10788 file.Write("interface %s {\n" % interface
.GetStructName())
10789 for func
in self
.original_functions
:
10790 if not func
.InPepperInterface(interface
):
10793 ret_type
= func
.MapCTypeToPepperIdlType(func
.return_type
,
10794 is_for_return_type
=True)
10795 func_prefix
= " %s %s(" % (ret_type
, func
.GetPepperName())
10796 file.Write(func_prefix
)
10797 file.Write("[in] PP_Resource context")
10798 for arg
in func
.MakeTypedPepperIdlArgStrings():
10799 file.Write(",\n" + " " * len(func_prefix
) + arg
)
10801 file.Write("};\n\n")
10806 def WritePepperGLES2Implementation(self
, filename
):
10807 """Writes the Pepper OpenGLES interface implementation."""
10809 file = CWriter(filename
)
10810 file.Write(_LICENSE
)
10811 file.Write(_DO_NOT_EDIT_WARNING
)
10813 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10814 file.Write("#include \"base/logging.h\"\n")
10815 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10816 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10817 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
10819 file.Write("namespace ppapi {\n\n")
10820 file.Write("namespace {\n\n")
10822 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10825 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10827 file.Write(" DCHECK(enter);\n")
10828 file.Write(" DCHECK(enter->succeeded());\n")
10829 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10830 "gles2_impl();\n");
10831 file.Write("}\n\n");
10833 for func
in self
.original_functions
:
10834 if not func
.InAnyPepperExtension():
10837 original_arg
= func
.MakeTypedPepperArgString("")
10838 context_arg
= "PP_Resource context_id"
10839 if len(original_arg
):
10840 arg
= context_arg
+ ", " + original_arg
10843 file.Write("%s %s(%s) {\n" %
10844 (func
.return_type
, func
.GetPepperName(), arg
))
10845 file.Write(" Enter3D enter(context_id, true);\n")
10846 file.Write(" if (enter.succeeded()) {\n")
10848 return_str
= "" if func
.return_type
== "void" else "return "
10849 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10850 (return_str
, func
.original_name
,
10851 func
.MakeOriginalArgString("")))
10853 if func
.return_type
== "void":
10856 file.Write(" else {\n")
10857 file.Write(" return %s;\n" % func
.GetErrorReturnString())
10859 file.Write("}\n\n")
10861 file.Write("} // namespace\n")
10863 for interface
in self
.pepper_interfaces
:
10864 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10865 (interface
.GetStructName(), interface
.GetName()))
10866 file.Write(" static const struct %s "
10867 "ppb_opengles2 = {\n" % interface
.GetStructName())
10869 file.Write(",\n &".join(
10870 f
.GetPepperName() for f
in self
.original_functions
10871 if f
.InPepperInterface(interface
)))
10874 file.Write(" };\n")
10875 file.Write(" return &ppb_opengles2;\n")
10878 file.Write("} // namespace ppapi\n")
10880 self
.generated_cpp_filenames
.append(file.filename
)
10882 def WriteGLES2ToPPAPIBridge(self
, filename
):
10883 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10885 file = CWriter(filename
)
10886 file.Write(_LICENSE
)
10887 file.Write(_DO_NOT_EDIT_WARNING
)
10889 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
10890 file.Write("#define GL_GLEXT_PROTOTYPES\n")
10891 file.Write("#endif\n")
10892 file.Write("#include <GLES2/gl2.h>\n")
10893 file.Write("#include <GLES2/gl2ext.h>\n")
10894 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10896 for func
in self
.original_functions
:
10897 if not func
.InAnyPepperExtension():
10900 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
10902 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
10903 (func
.return_type
, func
.GetPepperName(),
10904 func
.MakeTypedPepperArgString("")))
10905 return_str
= "" if func
.return_type
== "void" else "return "
10906 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
10907 original_arg
= func
.MakeOriginalArgString("")
10908 context_arg
= "glGetCurrentContextPPAPI()"
10909 if len(original_arg
):
10910 arg
= context_arg
+ ", " + original_arg
10913 if interface
.GetName():
10914 file.Write(" const struct %s* ext = %s;\n" %
10915 (interface
.GetStructName(), interface_str
))
10916 file.Write(" if (ext)\n")
10917 file.Write(" %sext->%s(%s);\n" %
10918 (return_str
, func
.GetPepperName(), arg
))
10920 file.Write(" %s0;\n" % return_str
)
10922 file.Write(" %s%s->%s(%s);\n" %
10923 (return_str
, interface_str
, func
.GetPepperName(), arg
))
10924 file.Write("}\n\n")
10926 self
.generated_cpp_filenames
.append(file.filename
)
10928 def WriteMojoGLCallVisitor(self
, filename
):
10929 """Provides the GL implementation for mojo"""
10930 file = CWriter(filename
)
10931 file.Write(_LICENSE
)
10932 file.Write(_DO_NOT_EDIT_WARNING
)
10934 for func
in self
.original_functions
:
10935 if not func
.IsCoreGLFunction():
10937 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10938 (func
.name
, func
.return_type
,
10939 func
.MakeTypedOriginalArgString(""),
10940 func
.MakeOriginalArgString("")))
10943 self
.generated_cpp_filenames
.append(file.filename
)
10945 def WriteMojoGLCallVisitorForExtension(self
, filename
, extension
):
10946 """Provides the GL implementation for mojo for a particular extension"""
10947 file = CWriter(filename
)
10948 file.Write(_LICENSE
)
10949 file.Write(_DO_NOT_EDIT_WARNING
)
10951 for func
in self
.original_functions
:
10952 if func
.GetInfo("extension") != extension
:
10954 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10955 (func
.name
, func
.return_type
,
10956 func
.MakeTypedOriginalArgString(""),
10957 func
.MakeOriginalArgString("")))
10960 self
.generated_cpp_filenames
.append(file.filename
)
10962 def Format(generated_files
):
10963 formatter
= "clang-format"
10964 if platform
.system() == "Windows":
10965 formatter
+= ".bat"
10966 for filename
in generated_files
:
10967 call([formatter
, "-i", "-style=chromium", filename
])
10970 """This is the main function."""
10971 parser
= OptionParser()
10974 help="base directory for resulting files, under chrome/src. default is "
10975 "empty. Use this if you want the result stored under gen.")
10977 "-v", "--verbose", action
="store_true",
10978 help="prints more output.")
10980 (options
, args
) = parser
.parse_args(args
=argv
)
10982 # Add in states and capabilites to GLState
10983 gl_state_valid
= _NAMED_TYPE_INFO
['GLState']['valid']
10984 for state_name
in sorted(_STATES
.keys()):
10985 state
= _STATES
[state_name
]
10986 if 'extension_flag' in state
:
10988 if 'enum' in state
:
10989 if not state
['enum'] in gl_state_valid
:
10990 gl_state_valid
.append(state
['enum'])
10992 for item
in state
['states']:
10993 if 'extension_flag' in item
:
10995 if not item
['enum'] in gl_state_valid
:
10996 gl_state_valid
.append(item
['enum'])
10997 for capability
in _CAPABILITY_FLAGS
:
10998 valid_value
= "GL_%s" % capability
['name'].upper()
10999 if not valid_value
in gl_state_valid
:
11000 gl_state_valid
.append(valid_value
)
11002 # This script lives under gpu/command_buffer, cd to base directory.
11003 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
11004 base_dir
= os
.getcwd()
11005 gen
= GLGenerator(options
.verbose
)
11006 gen
.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
11008 # Support generating files under gen/
11009 if options
.output_dir
!= None:
11010 os
.chdir(options
.output_dir
)
11012 gen
.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
11013 gen
.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
11014 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
11015 gen
.WritePepperGLES2Implementation(
11016 "ppapi/shared_impl/ppb_opengles2_shared.cc")
11018 gen
.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
11019 gen
.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
11020 gen
.WriteFormatTest(
11021 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
11022 gen
.WriteGLES2InterfaceHeader(
11023 "gpu/command_buffer/client/gles2_interface_autogen.h")
11024 gen
.WriteMojoGLES2ImplHeader(
11025 "mojo/gpu/mojo_gles2_impl_autogen.h")
11026 gen
.WriteMojoGLES2Impl(
11027 "mojo/gpu/mojo_gles2_impl_autogen.cc")
11028 gen
.WriteGLES2InterfaceStub(
11029 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
11030 gen
.WriteGLES2InterfaceStubImpl(
11031 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
11032 gen
.WriteGLES2ImplementationHeader(
11033 "gpu/command_buffer/client/gles2_implementation_autogen.h")
11034 gen
.WriteGLES2Implementation(
11035 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
11036 gen
.WriteGLES2ImplementationUnitTests(
11037 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
11038 gen
.WriteGLES2TraceImplementationHeader(
11039 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
11040 gen
.WriteGLES2TraceImplementation(
11041 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
11042 gen
.WriteGLES2CLibImplementation(
11043 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
11044 gen
.WriteCmdHelperHeader(
11045 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
11046 gen
.WriteServiceImplementation(
11047 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
11048 gen
.WriteServiceContextStateHeader(
11049 "gpu/command_buffer/service/context_state_autogen.h")
11050 gen
.WriteServiceContextStateImpl(
11051 "gpu/command_buffer/service/context_state_impl_autogen.h")
11052 gen
.WriteClientContextStateHeader(
11053 "gpu/command_buffer/client/client_context_state_autogen.h")
11054 gen
.WriteClientContextStateImpl(
11055 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
11056 gen
.WriteServiceUnitTests(
11057 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
11058 gen
.WriteServiceUnitTestsForExtensions(
11059 "gpu/command_buffer/service/"
11060 "gles2_cmd_decoder_unittest_extensions_autogen.h")
11061 gen
.WriteServiceUtilsHeader(
11062 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
11063 gen
.WriteServiceUtilsImplementation(
11064 "gpu/command_buffer/service/"
11065 "gles2_cmd_validation_implementation_autogen.h")
11066 gen
.WriteCommonUtilsHeader(
11067 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
11068 gen
.WriteCommonUtilsImpl(
11069 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
11070 gen
.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
11071 mojo_gles2_prefix
= ("third_party/mojo/src/mojo/public/c/gles2/"
11072 "gles2_call_visitor")
11073 gen
.WriteMojoGLCallVisitor(mojo_gles2_prefix
+ "_autogen.h")
11074 gen
.WriteMojoGLCallVisitorForExtension(
11075 mojo_gles2_prefix
+ "_chromium_texture_mailbox_autogen.h",
11076 "CHROMIUM_texture_mailbox")
11077 gen
.WriteMojoGLCallVisitorForExtension(
11078 mojo_gles2_prefix
+ "_chromium_sync_point_autogen.h",
11079 "CHROMIUM_sync_point")
11080 gen
.WriteMojoGLCallVisitorForExtension(
11081 mojo_gles2_prefix
+ "_chromium_sub_image_autogen.h",
11082 "CHROMIUM_sub_image")
11083 gen
.WriteMojoGLCallVisitorForExtension(
11084 mojo_gles2_prefix
+ "_chromium_miscellaneous_autogen.h",
11085 "CHROMIUM_miscellaneous")
11086 gen
.WriteMojoGLCallVisitorForExtension(
11087 mojo_gles2_prefix
+ "_occlusion_query_ext_autogen.h",
11088 "occlusion_query_EXT")
11089 gen
.WriteMojoGLCallVisitorForExtension(
11090 mojo_gles2_prefix
+ "_chromium_image_autogen.h",
11092 gen
.WriteMojoGLCallVisitorForExtension(
11093 mojo_gles2_prefix
+ "_chromium_copy_texture_autogen.h",
11094 "CHROMIUM_copy_texture")
11095 gen
.WriteMojoGLCallVisitorForExtension(
11096 mojo_gles2_prefix
+ "_chromium_pixel_transfer_buffer_object_autogen.h",
11097 "CHROMIUM_pixel_transfer_buffer_object")
11099 Format(gen
.generated_cpp_filenames
)
11102 print "%d errors" % gen
.errors
11107 if __name__
== '__main__':
11108 sys
.exit(main(sys
.argv
[1:]))