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',
543 'PathStencilFuncCHROMIUM': {
545 'func': 'PathStencilFuncNV',
546 'extension_flag': 'chromium_path_rendering',
549 'name': 'stencil_path_func',
551 'enum': 'GL_PATH_STENCIL_FUNC_CHROMIUM',
552 'default': 'GL_ALWAYS',
555 'name': 'stencil_path_ref',
557 'enum': 'GL_PATH_STENCIL_REF_CHROMIUM',
561 'name': 'stencil_path_mask',
563 'enum': 'GL_PATH_STENCIL_VALUE_MASK_CHROMIUM',
564 'default': '0xFFFFFFFFU',
570 # Named type info object represents a named type that is used in OpenGL call
571 # arguments. Each named type defines a set of valid OpenGL call arguments. The
572 # named types are used in 'cmd_buffer_functions.txt'.
573 # type: The actual GL type of the named type.
574 # valid: The list of values that are valid for both the client and the service.
575 # valid_es3: The list of values that are valid in OpenGL ES 3, but not ES 2.
576 # invalid: Examples of invalid values for the type. At least these values
577 # should be tested to be invalid.
578 # deprecated_es3: The list of values that are valid in OpenGL ES 2, but
579 # deprecated in ES 3.
580 # is_complete: The list of valid values of type are final and will not be
581 # modified during runtime.
590 'GL_LINEAR_MIPMAP_LINEAR',
593 'FrameBufferTarget': {
599 'GL_DRAW_FRAMEBUFFER' ,
600 'GL_READ_FRAMEBUFFER' ,
606 'InvalidateFrameBufferTarget': {
612 'GL_DRAW_FRAMEBUFFER' ,
613 'GL_READ_FRAMEBUFFER' ,
616 'RenderBufferTarget': {
629 'GL_ELEMENT_ARRAY_BUFFER',
632 'GL_COPY_READ_BUFFER',
633 'GL_COPY_WRITE_BUFFER',
634 'GL_PIXEL_PACK_BUFFER',
635 'GL_PIXEL_UNPACK_BUFFER',
636 'GL_TRANSFORM_FEEDBACK_BUFFER',
643 'IndexedBufferTarget': {
646 'GL_TRANSFORM_FEEDBACK_BUFFER',
658 'GL_MAP_INVALIDATE_RANGE_BIT',
659 'GL_MAP_INVALIDATE_BUFFER_BIT',
660 'GL_MAP_FLUSH_EXPLICIT_BIT',
661 'GL_MAP_UNSYNCHRONIZED_BIT',
664 'GL_SYNC_FLUSH_COMMANDS_BIT',
724 'CompressedTextureFormat': {
729 'GL_COMPRESSED_R11_EAC',
730 'GL_COMPRESSED_SIGNED_R11_EAC',
731 'GL_COMPRESSED_RG11_EAC',
732 'GL_COMPRESSED_SIGNED_RG11_EAC',
733 'GL_COMPRESSED_RGB8_ETC2',
734 'GL_COMPRESSED_SRGB8_ETC2',
735 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
736 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
737 'GL_COMPRESSED_RGBA8_ETC2_EAC',
738 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
744 # NOTE: State an Capability entries added later.
746 'GL_ALIASED_LINE_WIDTH_RANGE',
747 'GL_ALIASED_POINT_SIZE_RANGE',
749 'GL_ARRAY_BUFFER_BINDING',
751 'GL_COMPRESSED_TEXTURE_FORMATS',
752 'GL_CURRENT_PROGRAM',
755 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
756 'GL_FRAMEBUFFER_BINDING',
757 'GL_GENERATE_MIPMAP_HINT',
759 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
760 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
761 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
762 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
763 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
764 'GL_MAX_RENDERBUFFER_SIZE',
765 'GL_MAX_TEXTURE_IMAGE_UNITS',
766 'GL_MAX_TEXTURE_SIZE',
767 'GL_MAX_VARYING_VECTORS',
768 'GL_MAX_VERTEX_ATTRIBS',
769 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
770 'GL_MAX_VERTEX_UNIFORM_VECTORS',
771 'GL_MAX_VIEWPORT_DIMS',
772 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
773 'GL_NUM_SHADER_BINARY_FORMATS',
776 'GL_RENDERBUFFER_BINDING',
778 'GL_SAMPLE_COVERAGE_INVERT',
779 'GL_SAMPLE_COVERAGE_VALUE',
782 'GL_SHADER_BINARY_FORMATS',
783 'GL_SHADER_COMPILER',
786 'GL_TEXTURE_BINDING_2D',
787 'GL_TEXTURE_BINDING_CUBE_MAP',
788 'GL_UNPACK_ALIGNMENT',
789 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
790 # we can add this because we emulate it if the driver does not support it.
791 'GL_VERTEX_ARRAY_BINDING_OES',
795 'GL_COPY_READ_BUFFER_BINDING',
796 'GL_COPY_WRITE_BUFFER_BINDING',
813 'GL_DRAW_FRAMEBUFFER_BINDING',
814 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
815 'GL_GPU_DISJOINT_EXT',
817 'GL_MAX_3D_TEXTURE_SIZE',
818 'GL_MAX_ARRAY_TEXTURE_LAYERS',
819 'GL_MAX_COLOR_ATTACHMENTS',
820 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
821 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
822 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
823 'GL_MAX_DRAW_BUFFERS',
824 'GL_MAX_ELEMENT_INDEX',
825 'GL_MAX_ELEMENTS_INDICES',
826 'GL_MAX_ELEMENTS_VERTICES',
827 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
828 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
829 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
830 'GL_MAX_PROGRAM_TEXEL_OFFSET',
832 'GL_MAX_SERVER_WAIT_TIMEOUT',
833 'GL_MAX_TEXTURE_LOD_BIAS',
834 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
835 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
836 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
837 'GL_MAX_UNIFORM_BLOCK_SIZE',
838 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
839 'GL_MAX_VARYING_COMPONENTS',
840 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
841 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
842 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
843 'GL_MIN_PROGRAM_TEXEL_OFFSET',
846 'GL_NUM_PROGRAM_BINARY_FORMATS',
847 'GL_PACK_ROW_LENGTH',
848 'GL_PACK_SKIP_PIXELS',
850 'GL_PIXEL_PACK_BUFFER_BINDING',
851 'GL_PIXEL_UNPACK_BUFFER_BINDING',
852 'GL_PROGRAM_BINARY_FORMATS',
854 'GL_READ_FRAMEBUFFER_BINDING',
855 'GL_SAMPLER_BINDING',
857 'GL_TEXTURE_BINDING_2D_ARRAY',
858 'GL_TEXTURE_BINDING_3D',
859 'GL_TRANSFORM_FEEDBACK_BINDING',
860 'GL_TRANSFORM_FEEDBACK_ACTIVE',
861 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
862 'GL_TRANSFORM_FEEDBACK_PAUSED',
863 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
864 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
865 'GL_UNIFORM_BUFFER_BINDING',
866 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
867 'GL_UNIFORM_BUFFER_SIZE',
868 'GL_UNIFORM_BUFFER_START',
869 'GL_UNPACK_IMAGE_HEIGHT',
870 'GL_UNPACK_ROW_LENGTH',
871 'GL_UNPACK_SKIP_IMAGES',
872 'GL_UNPACK_SKIP_PIXELS',
873 'GL_UNPACK_SKIP_ROWS',
874 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
875 # 'GL_VERTEX_ARRAY_BINDING',
884 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
885 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
886 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
887 'GL_UNIFORM_BUFFER_BINDING',
888 'GL_UNIFORM_BUFFER_SIZE',
889 'GL_UNIFORM_BUFFER_START',
895 'GetTexParamTarget': {
899 'GL_TEXTURE_CUBE_MAP',
902 'GL_TEXTURE_2D_ARRAY',
906 'GL_PROXY_TEXTURE_CUBE_MAP',
914 'GL_COLOR_ATTACHMENT0',
915 'GL_COLOR_ATTACHMENT1',
916 'GL_COLOR_ATTACHMENT2',
917 'GL_COLOR_ATTACHMENT3',
918 'GL_COLOR_ATTACHMENT4',
919 'GL_COLOR_ATTACHMENT5',
920 'GL_COLOR_ATTACHMENT6',
921 'GL_COLOR_ATTACHMENT7',
922 'GL_COLOR_ATTACHMENT8',
923 'GL_COLOR_ATTACHMENT9',
924 'GL_COLOR_ATTACHMENT10',
925 'GL_COLOR_ATTACHMENT11',
926 'GL_COLOR_ATTACHMENT12',
927 'GL_COLOR_ATTACHMENT13',
928 'GL_COLOR_ATTACHMENT14',
929 'GL_COLOR_ATTACHMENT15',
939 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
940 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
941 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
942 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
943 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
944 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
947 'GL_PROXY_TEXTURE_CUBE_MAP',
954 'GL_TEXTURE_2D_ARRAY',
960 'TextureBindTarget': {
964 'GL_TEXTURE_CUBE_MAP',
968 'GL_TEXTURE_2D_ARRAY',
975 'TransformFeedbackBindTarget': {
978 'GL_TRANSFORM_FEEDBACK',
984 'TransformFeedbackPrimitiveMode': {
999 'GL_FRAGMENT_SHADER',
1002 'GL_GEOMETRY_SHADER',
1010 'GL_FRONT_AND_BACK',
1038 'GL_FUNC_REVERSE_SUBTRACT',
1054 'GL_ONE_MINUS_SRC_COLOR',
1056 'GL_ONE_MINUS_DST_COLOR',
1058 'GL_ONE_MINUS_SRC_ALPHA',
1060 'GL_ONE_MINUS_DST_ALPHA',
1061 'GL_CONSTANT_COLOR',
1062 'GL_ONE_MINUS_CONSTANT_COLOR',
1063 'GL_CONSTANT_ALPHA',
1064 'GL_ONE_MINUS_CONSTANT_ALPHA',
1065 'GL_SRC_ALPHA_SATURATE',
1074 'GL_ONE_MINUS_SRC_COLOR',
1076 'GL_ONE_MINUS_DST_COLOR',
1078 'GL_ONE_MINUS_SRC_ALPHA',
1080 'GL_ONE_MINUS_DST_ALPHA',
1081 'GL_CONSTANT_COLOR',
1082 'GL_ONE_MINUS_CONSTANT_COLOR',
1083 'GL_CONSTANT_ALPHA',
1084 'GL_ONE_MINUS_CONSTANT_ALPHA',
1089 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1090 if 'es3' not in cap
or cap
['es3'] != True],
1091 'valid_es3': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1092 if 'es3' in cap
and cap
['es3'] == True],
1105 'GL_TRIANGLE_STRIP',
1118 'GL_UNSIGNED_SHORT',
1127 'GetMaxIndexType': {
1131 'GL_UNSIGNED_SHORT',
1141 'GL_COLOR_ATTACHMENT0',
1142 'GL_DEPTH_ATTACHMENT',
1143 'GL_STENCIL_ATTACHMENT',
1146 'GL_DEPTH_STENCIL_ATTACHMENT',
1153 'BackbufferAttachment': {
1161 'BufferParameter': {
1168 'GL_BUFFER_ACCESS_FLAGS',
1172 'GL_PIXEL_PACK_BUFFER',
1175 'BufferParameter64': {
1179 'GL_BUFFER_MAP_LENGTH',
1180 'GL_BUFFER_MAP_OFFSET',
1183 'GL_PIXEL_PACK_BUFFER',
1189 'GL_INTERLEAVED_ATTRIBS',
1190 'GL_SEPARATE_ATTRIBS',
1193 'GL_PIXEL_PACK_BUFFER',
1196 'FrameBufferParameter': {
1199 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1200 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1201 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1202 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1205 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1206 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1207 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1208 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1209 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1210 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1211 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1212 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1213 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1219 'GL_PATH_PROJECTION_CHROMIUM',
1220 'GL_PATH_MODELVIEW_CHROMIUM',
1223 'ProgramParameter': {
1228 'GL_VALIDATE_STATUS',
1229 'GL_INFO_LOG_LENGTH',
1230 'GL_ATTACHED_SHADERS',
1231 'GL_ACTIVE_ATTRIBUTES',
1232 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1233 'GL_ACTIVE_UNIFORMS',
1234 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1237 'GL_ACTIVE_UNIFORM_BLOCKS',
1238 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1239 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1240 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1241 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1244 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1247 'QueryObjectParameter': {
1250 'GL_QUERY_RESULT_EXT',
1251 'GL_QUERY_RESULT_AVAILABLE_EXT',
1257 'GL_CURRENT_QUERY_EXT',
1263 'GL_ANY_SAMPLES_PASSED_EXT',
1264 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1265 'GL_COMMANDS_ISSUED_CHROMIUM',
1266 'GL_LATENCY_QUERY_CHROMIUM',
1267 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1268 'GL_COMMANDS_COMPLETED_CHROMIUM',
1271 'RenderBufferParameter': {
1274 'GL_RENDERBUFFER_RED_SIZE',
1275 'GL_RENDERBUFFER_GREEN_SIZE',
1276 'GL_RENDERBUFFER_BLUE_SIZE',
1277 'GL_RENDERBUFFER_ALPHA_SIZE',
1278 'GL_RENDERBUFFER_DEPTH_SIZE',
1279 'GL_RENDERBUFFER_STENCIL_SIZE',
1280 'GL_RENDERBUFFER_WIDTH',
1281 'GL_RENDERBUFFER_HEIGHT',
1282 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1285 'GL_RENDERBUFFER_SAMPLES',
1288 'InternalFormatParameter': {
1291 'GL_NUM_SAMPLE_COUNTS',
1295 'SamplerParameter': {
1298 'GL_TEXTURE_MAG_FILTER',
1299 'GL_TEXTURE_MIN_FILTER',
1300 'GL_TEXTURE_MIN_LOD',
1301 'GL_TEXTURE_MAX_LOD',
1302 'GL_TEXTURE_WRAP_S',
1303 'GL_TEXTURE_WRAP_T',
1304 'GL_TEXTURE_WRAP_R',
1305 'GL_TEXTURE_COMPARE_MODE',
1306 'GL_TEXTURE_COMPARE_FUNC',
1309 'GL_GENERATE_MIPMAP',
1312 'ShaderParameter': {
1317 'GL_COMPILE_STATUS',
1318 'GL_INFO_LOG_LENGTH',
1319 'GL_SHADER_SOURCE_LENGTH',
1320 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1323 'ShaderPrecision': {
1340 'GL_SHADING_LANGUAGE_VERSION',
1344 'TextureParameter': {
1347 'GL_TEXTURE_MAG_FILTER',
1348 'GL_TEXTURE_MIN_FILTER',
1349 'GL_TEXTURE_POOL_CHROMIUM',
1350 'GL_TEXTURE_WRAP_S',
1351 'GL_TEXTURE_WRAP_T',
1354 'GL_TEXTURE_BASE_LEVEL',
1355 'GL_TEXTURE_COMPARE_FUNC',
1356 'GL_TEXTURE_COMPARE_MODE',
1357 'GL_TEXTURE_IMMUTABLE_FORMAT',
1358 'GL_TEXTURE_IMMUTABLE_LEVELS',
1359 'GL_TEXTURE_MAX_LEVEL',
1360 'GL_TEXTURE_MAX_LOD',
1361 'GL_TEXTURE_MIN_LOD',
1362 'GL_TEXTURE_WRAP_R',
1365 'GL_GENERATE_MIPMAP',
1371 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1372 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1375 'TextureWrapMode': {
1379 'GL_MIRRORED_REPEAT',
1383 'TextureMinFilterMode': {
1388 'GL_NEAREST_MIPMAP_NEAREST',
1389 'GL_LINEAR_MIPMAP_NEAREST',
1390 'GL_NEAREST_MIPMAP_LINEAR',
1391 'GL_LINEAR_MIPMAP_LINEAR',
1394 'TextureMagFilterMode': {
1401 'TextureCompareFunc': {
1414 'TextureCompareMode': {
1418 'GL_COMPARE_REF_TO_TEXTURE',
1425 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1428 'VertexAttribute': {
1431 # some enum that the decoder actually passes through to GL needs
1432 # to be the first listed here since it's used in unit tests.
1433 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1434 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1435 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1436 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1437 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1438 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1439 'GL_CURRENT_VERTEX_ATTRIB',
1442 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1443 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1449 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1455 'GL_GENERATE_MIPMAP_HINT',
1458 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1461 'GL_PERSPECTIVE_CORRECTION_HINT',
1475 'GL_PACK_ALIGNMENT',
1476 'GL_UNPACK_ALIGNMENT',
1479 'GL_PACK_ROW_LENGTH',
1480 'GL_PACK_SKIP_PIXELS',
1481 'GL_PACK_SKIP_ROWS',
1482 'GL_UNPACK_ROW_LENGTH',
1483 'GL_UNPACK_IMAGE_HEIGHT',
1484 'GL_UNPACK_SKIP_PIXELS',
1485 'GL_UNPACK_SKIP_ROWS',
1486 'GL_UNPACK_SKIP_IMAGES',
1489 'GL_PACK_SWAP_BYTES',
1490 'GL_UNPACK_SWAP_BYTES',
1493 'PixelStoreAlignment': {
1506 'ReadPixelFormat': {
1526 'GL_UNSIGNED_SHORT_5_6_5',
1527 'GL_UNSIGNED_SHORT_4_4_4_4',
1528 'GL_UNSIGNED_SHORT_5_5_5_1',
1532 'GL_UNSIGNED_SHORT',
1538 'GL_UNSIGNED_INT_2_10_10_10_REV',
1539 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1540 'GL_UNSIGNED_INT_5_9_9_9_REV',
1541 'GL_UNSIGNED_INT_24_8',
1542 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1545 'GL_UNSIGNED_BYTE_3_3_2',
1554 'GL_UNSIGNED_SHORT',
1561 'GL_CONVEX_HULL_CHROMIUM',
1562 'GL_BOUNDING_BOX_CHROMIUM',
1569 'GL_COUNT_UP_CHROMIUM',
1570 'GL_COUNT_DOWN_CHROMIUM',
1576 'GL_PATH_STROKE_WIDTH_CHROMIUM',
1577 'GL_PATH_END_CAPS_CHROMIUM',
1578 'GL_PATH_JOIN_STYLE_CHROMIUM',
1579 'GL_PATH_MITER_LIMIT_CHROMIUM',
1580 'GL_PATH_STROKE_BOUND_CHROMIUM',
1583 'PathParameterCapValues': {
1587 'GL_SQUARE_CHROMIUM',
1588 'GL_ROUND_CHROMIUM',
1591 'PathParameterJoinValues': {
1594 'GL_MITER_REVERT_CHROMIUM',
1595 'GL_BEVEL_CHROMIUM',
1596 'GL_ROUND_CHROMIUM',
1603 'GL_UNSIGNED_SHORT_5_6_5',
1604 'GL_UNSIGNED_SHORT_4_4_4_4',
1605 'GL_UNSIGNED_SHORT_5_5_5_1',
1609 'GL_UNSIGNED_SHORT',
1615 'GL_UNSIGNED_INT_2_10_10_10_REV',
1618 'RenderBufferFormat': {
1624 'GL_DEPTH_COMPONENT16',
1625 'GL_STENCIL_INDEX8',
1653 'GL_DEPTH_COMPONENT24',
1654 'GL_DEPTH_COMPONENT32F',
1655 'GL_DEPTH24_STENCIL8',
1656 'GL_DEPTH32F_STENCIL8',
1659 'ShaderBinaryFormat': {
1682 'GL_LUMINANCE_ALPHA',
1693 'GL_DEPTH_COMPONENT',
1701 'TextureInternalFormat': {
1706 'GL_LUMINANCE_ALPHA',
1735 'GL_R11F_G11F_B10F',
1760 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1761 # We will reject them dynamically in GPU command buffer.
1762 'GL_DEPTH_COMPONENT16',
1763 'GL_DEPTH_COMPONENT24',
1764 'GL_DEPTH_COMPONENT32F',
1765 'GL_DEPTH24_STENCIL8',
1766 'GL_DEPTH32F_STENCIL8',
1773 'TextureInternalFormatStorage': {
1780 'GL_LUMINANCE8_EXT',
1781 'GL_LUMINANCE8_ALPHA8_EXT',
1809 'GL_R11F_G11F_B10F',
1832 'GL_DEPTH_COMPONENT16',
1833 'GL_DEPTH_COMPONENT24',
1834 'GL_DEPTH_COMPONENT32F',
1835 'GL_DEPTH24_STENCIL8',
1836 'GL_DEPTH32F_STENCIL8',
1837 'GL_COMPRESSED_R11_EAC',
1838 'GL_COMPRESSED_SIGNED_R11_EAC',
1839 'GL_COMPRESSED_RG11_EAC',
1840 'GL_COMPRESSED_SIGNED_RG11_EAC',
1841 'GL_COMPRESSED_RGB8_ETC2',
1842 'GL_COMPRESSED_SRGB8_ETC2',
1843 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1844 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1845 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1846 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1850 'GL_LUMINANCE8_EXT',
1851 'GL_LUMINANCE8_ALPHA8_EXT',
1853 'GL_LUMINANCE16F_EXT',
1854 'GL_LUMINANCE_ALPHA16F_EXT',
1856 'GL_LUMINANCE32F_EXT',
1857 'GL_LUMINANCE_ALPHA32F_EXT',
1860 'ImageInternalFormat': {
1864 'GL_RGB_YUV_420_CHROMIUM',
1865 'GL_RGB_YCBCR_422_CHROMIUM',
1873 'GL_SCANOUT_CHROMIUM'
1876 'ValueBufferTarget': {
1879 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1882 'SubscriptionTarget': {
1885 'GL_MOUSE_POSITION_CHROMIUM',
1888 'UniformParameter': {
1893 'GL_UNIFORM_NAME_LENGTH',
1894 'GL_UNIFORM_BLOCK_INDEX',
1895 'GL_UNIFORM_OFFSET',
1896 'GL_UNIFORM_ARRAY_STRIDE',
1897 'GL_UNIFORM_MATRIX_STRIDE',
1898 'GL_UNIFORM_IS_ROW_MAJOR',
1901 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1904 'UniformBlockParameter': {
1907 'GL_UNIFORM_BLOCK_BINDING',
1908 'GL_UNIFORM_BLOCK_DATA_SIZE',
1909 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1910 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1911 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1912 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1913 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1919 'VertexAttribType': {
1925 'GL_UNSIGNED_SHORT',
1926 # 'GL_FIXED', // This is not available on Desktop GL.
1933 'GL_INT_2_10_10_10_REV',
1934 'GL_UNSIGNED_INT_2_10_10_10_REV',
1940 'VertexAttribIType': {
1946 'GL_UNSIGNED_SHORT',
1957 'is_complete': True,
1965 'VertexAttribSize': {
1980 'is_complete': True,
1989 'type': 'GLboolean',
1990 'is_complete': True,
2001 'GL_GUILTY_CONTEXT_RESET_ARB',
2002 'GL_INNOCENT_CONTEXT_RESET_ARB',
2003 'GL_UNKNOWN_CONTEXT_RESET_ARB',
2008 'is_complete': True,
2010 'GL_SYNC_GPU_COMMANDS_COMPLETE',
2017 'type': 'GLbitfield',
2018 'is_complete': True,
2027 'type': 'GLbitfield',
2029 'GL_SYNC_FLUSH_COMMANDS_BIT',
2039 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
2041 'GL_SYNC_CONDITION',
2050 # This table specifies the different pepper interfaces that are supported for
2051 # GL commands. 'dev' is true if it's a dev interface.
2052 _PEPPER_INTERFACES
= [
2053 {'name': '', 'dev': False},
2054 {'name': 'InstancedArrays', 'dev': False},
2055 {'name': 'FramebufferBlit', 'dev': False},
2056 {'name': 'FramebufferMultisample', 'dev': False},
2057 {'name': 'ChromiumEnableFeature', 'dev': False},
2058 {'name': 'ChromiumMapSub', 'dev': False},
2059 {'name': 'Query', 'dev': False},
2060 {'name': 'VertexArrayObject', 'dev': False},
2061 {'name': 'DrawBuffers', 'dev': True},
2064 # A function info object specifies the type and other special data for the
2065 # command that will be generated. A base function info object is generated by
2066 # parsing the "cmd_buffer_functions.txt", one for each function in the
2067 # file. These function info objects can be augmented and their values can be
2068 # overridden by adding an object to the table below.
2070 # Must match function names specified in "cmd_buffer_functions.txt".
2072 # cmd_comment: A comment added to the cmd format.
2073 # type: defines which handler will be used to generate code.
2074 # decoder_func: defines which function to call in the decoder to execute the
2075 # corresponding GL command. If not specified the GL command will
2076 # be called directly.
2077 # gl_test_func: GL function that is expected to be called when testing.
2078 # cmd_args: The arguments to use for the command. This overrides generating
2079 # them based on the GL function arguments.
2080 # gen_cmd: Whether or not this function geneates a command. Default = True.
2081 # data_transfer_methods: Array of methods that are used for transfering the
2082 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
2083 # The default is 'immediate' if the command has one pointer
2084 # argument, otherwise 'shm'. One command is generated for each
2085 # transfer method. Affects only commands which are not of type
2086 # 'HandWritten', 'GETn' or 'GLcharN'.
2087 # Note: the command arguments that affect this are the final args,
2088 # taking cmd_args override into consideration.
2089 # impl_func: Whether or not to generate the GLES2Implementation part of this
2091 # impl_decl: Whether or not to generate the GLES2Implementation declaration
2093 # needs_size: If True a data_size field is added to the command.
2094 # count: The number of units per element. For PUTn or PUT types.
2095 # use_count_func: If True the actual data count needs to be computed; the count
2096 # argument specifies the maximum count.
2097 # unit_test: If False no service side unit test will be generated.
2098 # client_test: If False no client side unit test will be generated.
2099 # expectation: If False the unit test will have no expected calls.
2100 # gen_func: Name of function that generates GL resource for corresponding
2102 # states: array of states that get set by this function corresponding to
2103 # the given arguments
2104 # state_flag: name of flag that is set to true when function is called.
2105 # no_gl: no GL function is called.
2106 # valid_args: A dictionary of argument indices to args to use in unit tests
2107 # when they can not be automatically determined.
2108 # pepper_interface: The pepper interface that is used for this extension
2109 # pepper_name: The name of the function as exposed to pepper.
2110 # pepper_args: A string representing the argument list (what would appear in
2111 # C/C++ between the parentheses for the function declaration)
2112 # that the Pepper API expects for this function. Use this only if
2113 # the stable Pepper API differs from the GLES2 argument list.
2114 # invalid_test: False if no invalid test needed.
2115 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2116 # first_element_only: For PUT types, True if only the first element of an
2117 # array is used and we end up calling the single value
2118 # corresponding function. eg. TexParameteriv -> TexParameteri
2119 # extension: Function is an extension to GL and should not be exposed to
2120 # pepper unless pepper_interface is defined.
2121 # extension_flag: Function is an extension and should be enabled only when
2122 # the corresponding feature info flag is enabled. Implies
2123 # 'extension': True.
2124 # not_shared: For GENn types, True if objects can't be shared between contexts
2125 # unsafe: True = no validation is implemented on the service side and the
2126 # command is only available with --enable-unsafe-es3-apis.
2127 # id_mapping: A list of resource type names whose client side IDs need to be
2128 # mapped to service side IDs. This is only used for unsafe APIs.
2132 'decoder_func': 'DoActiveTexture',
2135 'client_test': False,
2137 'ApplyScreenSpaceAntialiasingCHROMIUM': {
2138 'decoder_func': 'DoApplyScreenSpaceAntialiasingCHROMIUM',
2139 'extension': 'CHROMIUM_screen_space_antialiasing',
2140 'extension_flag': 'chromium_screen_space_antialiasing',
2142 'client_test': False,
2144 'AttachShader': {'decoder_func': 'DoAttachShader'},
2145 'BindAttribLocation': {
2147 'data_transfer_methods': ['bucket'],
2152 'decoder_func': 'DoBindBuffer',
2153 'gen_func': 'GenBuffersARB',
2157 'decoder_func': 'DoBindBufferBase',
2158 'gen_func': 'GenBuffersARB',
2161 'BindBufferRange': {
2163 'decoder_func': 'DoBindBufferRange',
2164 'gen_func': 'GenBuffersARB',
2171 'BindFramebuffer': {
2173 'decoder_func': 'DoBindFramebuffer',
2174 'gl_test_func': 'glBindFramebufferEXT',
2175 'gen_func': 'GenFramebuffersEXT',
2178 'BindRenderbuffer': {
2180 'decoder_func': 'DoBindRenderbuffer',
2181 'gl_test_func': 'glBindRenderbufferEXT',
2182 'gen_func': 'GenRenderbuffersEXT',
2186 'id_mapping': [ 'Sampler' ],
2191 'decoder_func': 'DoBindTexture',
2192 'gen_func': 'GenTextures',
2193 # TODO(gman): remove this once client side caching works.
2194 'client_test': False,
2197 'BindTransformFeedback': {
2199 'id_mapping': [ 'TransformFeedback' ],
2202 'BlitFramebufferCHROMIUM': {
2203 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2205 'extension': 'chromium_framebuffer_multisample',
2206 'extension_flag': 'chromium_framebuffer_multisample',
2207 'pepper_interface': 'FramebufferBlit',
2208 'pepper_name': 'BlitFramebufferEXT',
2209 'defer_reads': True,
2210 'defer_draws': True,
2215 'data_transfer_methods': ['shm'],
2216 'client_test': False,
2221 'client_test': False,
2222 'decoder_func': 'DoBufferSubData',
2223 'data_transfer_methods': ['shm'],
2226 'CheckFramebufferStatus': {
2228 'decoder_func': 'DoCheckFramebufferStatus',
2229 'gl_test_func': 'glCheckFramebufferStatusEXT',
2230 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2231 'result': ['GLenum'],
2234 'decoder_func': 'DoClear',
2235 'defer_draws': True,
2240 'use_count_func': True,
2242 'decoder_func': 'DoClearBufferiv',
2250 'decoder_func': 'DoClearBufferuiv',
2257 'use_count_func': True,
2259 'decoder_func': 'DoClearBufferfv',
2266 'decoder_func': 'DoClearBufferfi',
2272 'state': 'ClearColor',
2276 'state': 'ClearDepthf',
2277 'decoder_func': 'glClearDepth',
2278 'gl_test_func': 'glClearDepth',
2285 'data_transfer_methods': ['shm'],
2286 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2287 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2289 'result': ['GLenum'],
2294 'state': 'ColorMask',
2296 'expectation': False,
2298 'ConsumeTextureCHROMIUM': {
2299 'decoder_func': 'DoConsumeTextureCHROMIUM',
2302 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2304 'client_test': False,
2305 'extension': "CHROMIUM_texture_mailbox",
2309 'CopyBufferSubData': {
2312 'CreateAndConsumeTextureCHROMIUM': {
2313 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2315 'type': 'HandWritten',
2316 'data_transfer_methods': ['immediate'],
2318 'client_test': False,
2319 'extension': "CHROMIUM_texture_mailbox",
2323 'GenValuebuffersCHROMIUM': {
2325 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2326 'resource_type': 'Valuebuffer',
2327 'resource_types': 'Valuebuffers',
2329 'extension': 'CHROMIUM_subscribe_uniform',
2332 'DeleteValuebuffersCHROMIUM': {
2334 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2335 'resource_type': 'Valuebuffer',
2336 'resource_types': 'Valuebuffers',
2338 'extension': 'CHROMIUM_subscribe_uniform',
2341 'IsValuebufferCHROMIUM': {
2343 'decoder_func': 'DoIsValuebufferCHROMIUM',
2344 'expectation': False,
2345 'extension': 'CHROMIUM_subscribe_uniform',
2348 'BindValuebufferCHROMIUM': {
2350 'decoder_func': 'DoBindValueBufferCHROMIUM',
2351 'gen_func': 'GenValueBuffersCHROMIUM',
2353 'extension': 'CHROMIUM_subscribe_uniform',
2356 'SubscribeValueCHROMIUM': {
2357 'decoder_func': 'DoSubscribeValueCHROMIUM',
2359 'extension': 'CHROMIUM_subscribe_uniform',
2362 'PopulateSubscribedValuesCHROMIUM': {
2363 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2365 'extension': 'CHROMIUM_subscribe_uniform',
2368 'UniformValuebufferCHROMIUM': {
2369 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2371 'extension': 'CHROMIUM_subscribe_uniform',
2376 'state': 'ClearStencil',
2378 'EnableFeatureCHROMIUM': {
2380 'data_transfer_methods': ['shm'],
2381 'decoder_func': 'DoEnableFeatureCHROMIUM',
2382 'expectation': False,
2383 'cmd_args': 'GLuint bucket_id, GLint* result',
2384 'result': ['GLint'],
2385 'extension': 'GL_CHROMIUM_enable_feature',
2387 'pepper_interface': 'ChromiumEnableFeature',
2389 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2390 'CompressedTexImage2D': {
2392 'data_transfer_methods': ['bucket', 'shm'],
2395 'CompressedTexSubImage2D': {
2397 'data_transfer_methods': ['bucket', 'shm'],
2398 'decoder_func': 'DoCompressedTexSubImage2D',
2402 'decoder_func': 'DoCopyTexImage2D',
2404 'defer_reads': True,
2407 'CopyTexSubImage2D': {
2408 'decoder_func': 'DoCopyTexSubImage2D',
2409 'defer_reads': True,
2412 'CompressedTexImage3D': {
2414 'data_transfer_methods': ['bucket', 'shm'],
2418 'CompressedTexSubImage3D': {
2420 'data_transfer_methods': ['bucket', 'shm'],
2421 'decoder_func': 'DoCompressedTexSubImage3D',
2425 'CopyTexSubImage3D': {
2426 'defer_reads': True,
2430 'CreateImageCHROMIUM': {
2433 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2434 'GLenum internalformat',
2435 'result': ['GLuint'],
2436 'client_test': False,
2438 'expectation': False,
2439 'extension': "CHROMIUM_image",
2443 'DestroyImageCHROMIUM': {
2445 'client_test': False,
2447 'extension': "CHROMIUM_image",
2451 'CreateGpuMemoryBufferImageCHROMIUM': {
2454 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2455 'result': ['GLuint'],
2456 'client_test': False,
2458 'expectation': False,
2459 'extension': "CHROMIUM_gpu_memory_buffer_image",
2465 'client_test': False,
2469 'client_test': False,
2473 'state': 'BlendColor',
2476 'type': 'StateSetRGBAlpha',
2477 'state': 'BlendEquation',
2479 '0': 'GL_FUNC_SUBTRACT'
2482 'BlendEquationSeparate': {
2484 'state': 'BlendEquation',
2486 '0': 'GL_FUNC_SUBTRACT'
2490 'type': 'StateSetRGBAlpha',
2491 'state': 'BlendFunc',
2493 'BlendFuncSeparate': {
2495 'state': 'BlendFunc',
2497 'BlendBarrierKHR': {
2498 'gl_test_func': 'glBlendBarrierKHR',
2499 'extension': 'KHR_blend_equation_advanced',
2500 'extension_flag': 'blend_equation_advanced',
2501 'client_test': False,
2503 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2505 'type': 'StateSetFrontBack',
2506 'state': 'StencilFunc',
2508 'StencilFuncSeparate': {
2509 'type': 'StateSetFrontBackSeparate',
2510 'state': 'StencilFunc',
2513 'type': 'StateSetFrontBack',
2514 'state': 'StencilOp',
2519 'StencilOpSeparate': {
2520 'type': 'StateSetFrontBackSeparate',
2521 'state': 'StencilOp',
2527 'type': 'StateSetNamedParameter',
2530 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2531 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2532 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2535 'state': 'LineWidth',
2542 'state': 'PolygonOffset',
2546 'gl_test_func': 'glDeleteBuffersARB',
2547 'resource_type': 'Buffer',
2548 'resource_types': 'Buffers',
2550 'DeleteFramebuffers': {
2552 'gl_test_func': 'glDeleteFramebuffersEXT',
2553 'resource_type': 'Framebuffer',
2554 'resource_types': 'Framebuffers',
2557 'DeleteProgram': { 'type': 'Delete' },
2558 'DeleteRenderbuffers': {
2560 'gl_test_func': 'glDeleteRenderbuffersEXT',
2561 'resource_type': 'Renderbuffer',
2562 'resource_types': 'Renderbuffers',
2567 'resource_type': 'Sampler',
2568 'resource_types': 'Samplers',
2571 'DeleteShader': { 'type': 'Delete' },
2574 'cmd_args': 'GLuint sync',
2575 'resource_type': 'Sync',
2580 'resource_type': 'Texture',
2581 'resource_types': 'Textures',
2583 'DeleteTransformFeedbacks': {
2585 'resource_type': 'TransformFeedback',
2586 'resource_types': 'TransformFeedbacks',
2590 'decoder_func': 'DoDepthRangef',
2591 'gl_test_func': 'glDepthRange',
2595 'state': 'DepthMask',
2597 'expectation': False,
2599 'DetachShader': {'decoder_func': 'DoDetachShader'},
2601 'decoder_func': 'DoDisable',
2603 'client_test': False,
2605 'DisableVertexAttribArray': {
2606 'decoder_func': 'DoDisableVertexAttribArray',
2611 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2612 'defer_draws': True,
2617 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2618 'GLenumIndexType type, GLuint index_offset',
2619 'client_test': False,
2620 'defer_draws': True,
2623 'DrawRangeElements': {
2629 'decoder_func': 'DoEnable',
2631 'client_test': False,
2633 'EnableVertexAttribArray': {
2634 'decoder_func': 'DoEnableVertexAttribArray',
2639 'client_test': False,
2645 'client_test': False,
2646 'decoder_func': 'DoFinish',
2647 'defer_reads': True,
2652 'decoder_func': 'DoFlush',
2655 'FramebufferRenderbuffer': {
2656 'decoder_func': 'DoFramebufferRenderbuffer',
2657 'gl_test_func': 'glFramebufferRenderbufferEXT',
2660 'FramebufferTexture2D': {
2661 'decoder_func': 'DoFramebufferTexture2D',
2662 'gl_test_func': 'glFramebufferTexture2DEXT',
2665 'FramebufferTexture2DMultisampleEXT': {
2666 'decoder_func': 'DoFramebufferTexture2DMultisample',
2667 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2668 'expectation': False,
2670 'extension': 'EXT_multisampled_render_to_texture',
2671 'extension_flag': 'multisampled_render_to_texture',
2674 'FramebufferTextureLayer': {
2675 'decoder_func': 'DoFramebufferTextureLayer',
2680 'decoder_func': 'DoGenerateMipmap',
2681 'gl_test_func': 'glGenerateMipmapEXT',
2686 'gl_test_func': 'glGenBuffersARB',
2687 'resource_type': 'Buffer',
2688 'resource_types': 'Buffers',
2690 'GenMailboxCHROMIUM': {
2691 'type': 'HandWritten',
2693 'extension': "CHROMIUM_texture_mailbox",
2696 'GenFramebuffers': {
2698 'gl_test_func': 'glGenFramebuffersEXT',
2699 'resource_type': 'Framebuffer',
2700 'resource_types': 'Framebuffers',
2702 'GenRenderbuffers': {
2703 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2704 'resource_type': 'Renderbuffer',
2705 'resource_types': 'Renderbuffers',
2709 'gl_test_func': 'glGenSamplers',
2710 'resource_type': 'Sampler',
2711 'resource_types': 'Samplers',
2716 'gl_test_func': 'glGenTextures',
2717 'resource_type': 'Texture',
2718 'resource_types': 'Textures',
2720 'GenTransformFeedbacks': {
2722 'gl_test_func': 'glGenTransformFeedbacks',
2723 'resource_type': 'TransformFeedback',
2724 'resource_types': 'TransformFeedbacks',
2727 'GetActiveAttrib': {
2729 'data_transfer_methods': ['shm'],
2731 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2739 'GetActiveUniform': {
2741 'data_transfer_methods': ['shm'],
2743 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2751 'GetActiveUniformBlockiv': {
2753 'data_transfer_methods': ['shm'],
2754 'result': ['SizedResult<GLint>'],
2757 'GetActiveUniformBlockName': {
2759 'data_transfer_methods': ['shm'],
2761 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2763 'result': ['int32_t'],
2766 'GetActiveUniformsiv': {
2768 'data_transfer_methods': ['shm'],
2770 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2772 'result': ['SizedResult<GLint>'],
2775 'GetAttachedShaders': {
2777 'data_transfer_methods': ['shm'],
2778 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2779 'result': ['SizedResult<GLuint>'],
2781 'GetAttribLocation': {
2783 'data_transfer_methods': ['shm'],
2785 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2786 'result': ['GLint'],
2789 'GetFragDataLocation': {
2791 'data_transfer_methods': ['shm'],
2793 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2794 'result': ['GLint'],
2800 'result': ['SizedResult<GLboolean>'],
2801 'decoder_func': 'DoGetBooleanv',
2802 'gl_test_func': 'glGetBooleanv',
2804 'GetBufferParameteri64v': {
2806 'result': ['SizedResult<GLint64>'],
2807 'decoder_func': 'DoGetBufferParameteri64v',
2808 'expectation': False,
2812 'GetBufferParameteriv': {
2814 'result': ['SizedResult<GLint>'],
2815 'decoder_func': 'DoGetBufferParameteriv',
2816 'expectation': False,
2821 'decoder_func': 'GetErrorState()->GetGLError',
2823 'result': ['GLenum'],
2824 'client_test': False,
2828 'result': ['SizedResult<GLfloat>'],
2829 'decoder_func': 'DoGetFloatv',
2830 'gl_test_func': 'glGetFloatv',
2832 'GetFramebufferAttachmentParameteriv': {
2834 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2835 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2836 'result': ['SizedResult<GLint>'],
2838 'GetGraphicsResetStatusKHR': {
2840 'client_test': False,
2846 'result': ['SizedResult<GLint64>'],
2847 'client_test': False,
2848 'decoder_func': 'DoGetInteger64v',
2853 'result': ['SizedResult<GLint>'],
2854 'decoder_func': 'DoGetIntegerv',
2855 'client_test': False,
2857 'GetInteger64i_v': {
2859 'result': ['SizedResult<GLint64>'],
2860 'client_test': False,
2865 'result': ['SizedResult<GLint>'],
2866 'client_test': False,
2869 'GetInternalformativ': {
2871 'data_transfer_methods': ['shm'],
2872 'result': ['SizedResult<GLint>'],
2874 'GLenumRenderBufferTarget target, GLenumRenderBufferFormat format, '
2875 'GLenumInternalFormatParameter pname, GLint* params',
2878 'GetMaxValueInBufferCHROMIUM': {
2880 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2881 'result': ['GLuint'],
2883 'client_test': False,
2890 'decoder_func': 'DoGetProgramiv',
2891 'result': ['SizedResult<GLint>'],
2892 'expectation': False,
2894 'GetProgramInfoCHROMIUM': {
2896 'expectation': False,
2898 'extension': 'CHROMIUM_get_multiple',
2900 'client_test': False,
2901 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2903 'uint32_t link_status',
2904 'uint32_t num_attribs',
2905 'uint32_t num_uniforms',
2908 'GetProgramInfoLog': {
2910 'expectation': False,
2912 'GetRenderbufferParameteriv': {
2914 'decoder_func': 'DoGetRenderbufferParameteriv',
2915 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2916 'result': ['SizedResult<GLint>'],
2918 'GetSamplerParameterfv': {
2920 'result': ['SizedResult<GLfloat>'],
2921 'id_mapping': [ 'Sampler' ],
2924 'GetSamplerParameteriv': {
2926 'result': ['SizedResult<GLint>'],
2927 'id_mapping': [ 'Sampler' ],
2932 'decoder_func': 'DoGetShaderiv',
2933 'result': ['SizedResult<GLint>'],
2935 'GetShaderInfoLog': {
2937 'get_len_func': 'glGetShaderiv',
2938 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2941 'GetShaderPrecisionFormat': {
2943 'data_transfer_methods': ['shm'],
2945 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2949 'int32_t min_range',
2950 'int32_t max_range',
2951 'int32_t precision',
2954 'GetShaderSource': {
2956 'get_len_func': 'DoGetShaderiv',
2957 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2959 'client_test': False,
2963 'client_test': False,
2964 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2968 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2969 'result': ['SizedResult<GLint>'],
2970 'id_mapping': ['Sync'],
2973 'GetTexParameterfv': {
2975 'decoder_func': 'DoGetTexParameterfv',
2976 'result': ['SizedResult<GLfloat>']
2978 'GetTexParameteriv': {
2980 'decoder_func': 'DoGetTexParameteriv',
2981 'result': ['SizedResult<GLint>']
2983 'GetTranslatedShaderSourceANGLE': {
2985 'get_len_func': 'DoGetShaderiv',
2986 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2990 'GetUniformBlockIndex': {
2992 'data_transfer_methods': ['shm'],
2994 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2995 'result': ['GLuint'],
2996 'error_return': 'GL_INVALID_INDEX',
2999 'GetUniformBlocksCHROMIUM': {
3001 'expectation': False,
3005 'client_test': False,
3006 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3007 'result': ['uint32_t'],
3010 'GetUniformsES3CHROMIUM': {
3012 'expectation': False,
3016 'client_test': False,
3017 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3018 'result': ['uint32_t'],
3021 'GetTransformFeedbackVarying': {
3023 'data_transfer_methods': ['shm'],
3025 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
3034 'GetTransformFeedbackVaryingsCHROMIUM': {
3036 'expectation': False,
3040 'client_test': False,
3041 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3042 'result': ['uint32_t'],
3047 'data_transfer_methods': ['shm'],
3048 'result': ['SizedResult<GLfloat>'],
3052 'data_transfer_methods': ['shm'],
3053 'result': ['SizedResult<GLint>'],
3057 'data_transfer_methods': ['shm'],
3058 'result': ['SizedResult<GLuint>'],
3061 'GetUniformIndices': {
3063 'data_transfer_methods': ['shm'],
3064 'result': ['SizedResult<GLuint>'],
3065 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
3069 'GetUniformLocation': {
3071 'data_transfer_methods': ['shm'],
3073 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
3074 'result': ['GLint'],
3075 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
3077 'GetVertexAttribfv': {
3079 'result': ['SizedResult<GLfloat>'],
3081 'decoder_func': 'DoGetVertexAttribfv',
3082 'expectation': False,
3083 'client_test': False,
3085 'GetVertexAttribiv': {
3087 'result': ['SizedResult<GLint>'],
3089 'decoder_func': 'DoGetVertexAttribiv',
3090 'expectation': False,
3091 'client_test': False,
3093 'GetVertexAttribIiv': {
3095 'result': ['SizedResult<GLint>'],
3097 'decoder_func': 'DoGetVertexAttribIiv',
3098 'expectation': False,
3099 'client_test': False,
3102 'GetVertexAttribIuiv': {
3104 'result': ['SizedResult<GLuint>'],
3106 'decoder_func': 'DoGetVertexAttribIuiv',
3107 'expectation': False,
3108 'client_test': False,
3111 'GetVertexAttribPointerv': {
3113 'data_transfer_methods': ['shm'],
3114 'result': ['SizedResult<GLuint>'],
3115 'client_test': False,
3117 'InvalidateFramebuffer': {
3120 'client_test': False,
3124 'InvalidateSubFramebuffer': {
3127 'client_test': False,
3133 'decoder_func': 'DoIsBuffer',
3134 'expectation': False,
3138 'decoder_func': 'DoIsEnabled',
3139 'client_test': False,
3141 'expectation': False,
3145 'decoder_func': 'DoIsFramebuffer',
3146 'expectation': False,
3150 'decoder_func': 'DoIsProgram',
3151 'expectation': False,
3155 'decoder_func': 'DoIsRenderbuffer',
3156 'expectation': False,
3160 'decoder_func': 'DoIsShader',
3161 'expectation': False,
3165 'id_mapping': [ 'Sampler' ],
3166 'expectation': False,
3171 'id_mapping': [ 'Sync' ],
3172 'cmd_args': 'GLuint sync',
3173 'expectation': False,
3178 'decoder_func': 'DoIsTexture',
3179 'expectation': False,
3181 'IsTransformFeedback': {
3183 'id_mapping': [ 'TransformFeedback' ],
3184 'expectation': False,
3188 'decoder_func': 'DoLinkProgram',
3192 'MapBufferCHROMIUM': {
3194 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3196 'client_test': False,
3199 'MapBufferSubDataCHROMIUM': {
3201 'extension': 'CHROMIUM_map_sub',
3203 'client_test': False,
3204 'pepper_interface': 'ChromiumMapSub',
3207 'MapTexSubImage2DCHROMIUM': {
3209 'extension': "CHROMIUM_sub_image",
3211 'client_test': False,
3212 'pepper_interface': 'ChromiumMapSub',
3217 'data_transfer_methods': ['shm'],
3218 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3219 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3220 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3221 'uint32_t result_shm_id, uint32_t result_shm_offset',
3223 'result': ['uint32_t'],
3226 'PauseTransformFeedback': {
3229 'PixelStorei': {'type': 'Manual'},
3230 'PostSubBufferCHROMIUM': {
3234 'client_test': False,
3238 'ProduceTextureCHROMIUM': {
3239 'decoder_func': 'DoProduceTextureCHROMIUM',
3242 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3244 'client_test': False,
3245 'extension': "CHROMIUM_texture_mailbox",
3249 'ProduceTextureDirectCHROMIUM': {
3250 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3253 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3255 'client_test': False,
3256 'extension': "CHROMIUM_texture_mailbox",
3260 'RenderbufferStorage': {
3261 'decoder_func': 'DoRenderbufferStorage',
3262 'gl_test_func': 'glRenderbufferStorageEXT',
3263 'expectation': False,
3266 'RenderbufferStorageMultisampleCHROMIUM': {
3268 '// GL_CHROMIUM_framebuffer_multisample\n',
3269 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3270 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3271 'expectation': False,
3273 'extension': 'chromium_framebuffer_multisample',
3274 'extension_flag': 'chromium_framebuffer_multisample',
3275 'pepper_interface': 'FramebufferMultisample',
3276 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3279 'RenderbufferStorageMultisampleEXT': {
3281 '// GL_EXT_multisampled_render_to_texture\n',
3282 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3283 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3284 'expectation': False,
3286 'extension': 'EXT_multisampled_render_to_texture',
3287 'extension_flag': 'multisampled_render_to_texture',
3292 'decoder_func': 'DoReadBuffer',
3297 '// ReadPixels has the result separated from the pixel buffer so that\n'
3298 '// it is easier to specify the result going to some specific place\n'
3299 '// that exactly fits the rectangle of pixels.\n',
3301 'data_transfer_methods': ['shm'],
3303 'client_test': False,
3305 'GLint x, GLint y, GLsizei width, GLsizei height, '
3306 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3307 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3308 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3310 'result': ['uint32_t'],
3311 'defer_reads': True,
3314 'ReleaseShaderCompiler': {
3315 'decoder_func': 'DoReleaseShaderCompiler',
3318 'ResumeTransformFeedback': {
3321 'SamplerParameterf': {
3325 'id_mapping': [ 'Sampler' ],
3328 'SamplerParameterfv': {
3330 'data_value': 'GL_NEAREST',
3332 'gl_test_func': 'glSamplerParameterf',
3333 'decoder_func': 'DoSamplerParameterfv',
3334 'first_element_only': True,
3335 'id_mapping': [ 'Sampler' ],
3338 'SamplerParameteri': {
3342 'id_mapping': [ 'Sampler' ],
3345 'SamplerParameteriv': {
3347 'data_value': 'GL_NEAREST',
3349 'gl_test_func': 'glSamplerParameteri',
3350 'decoder_func': 'DoSamplerParameteriv',
3351 'first_element_only': True,
3356 'client_test': False,
3360 'decoder_func': 'DoShaderSource',
3361 'expectation': False,
3362 'data_transfer_methods': ['bucket'],
3364 'GLuint shader, const char** str',
3366 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3369 'type': 'StateSetFrontBack',
3370 'state': 'StencilMask',
3372 'expectation': False,
3374 'StencilMaskSeparate': {
3375 'type': 'StateSetFrontBackSeparate',
3376 'state': 'StencilMask',
3378 'expectation': False,
3382 'decoder_func': 'DoSwapBuffers',
3384 'client_test': False,
3390 'decoder_func': 'DoSwapInterval',
3392 'client_test': False,
3398 'data_transfer_methods': ['shm'],
3399 'client_test': False,
3404 'data_transfer_methods': ['shm'],
3405 'client_test': False,
3410 'decoder_func': 'DoTexParameterf',
3416 'decoder_func': 'DoTexParameteri',
3423 'data_value': 'GL_NEAREST',
3425 'decoder_func': 'DoTexParameterfv',
3426 'gl_test_func': 'glTexParameterf',
3427 'first_element_only': True,
3431 'data_value': 'GL_NEAREST',
3433 'decoder_func': 'DoTexParameteriv',
3434 'gl_test_func': 'glTexParameteri',
3435 'first_element_only': True,
3443 'data_transfer_methods': ['shm'],
3444 'client_test': False,
3446 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3447 'GLint xoffset, GLint yoffset, '
3448 'GLsizei width, GLsizei height, '
3449 'GLenumTextureFormat format, GLenumPixelType type, '
3450 'const void* pixels, GLboolean internal'
3454 'data_transfer_methods': ['shm'],
3455 'client_test': False,
3457 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3458 'GLint xoffset, GLint yoffset, GLint zoffset, '
3459 'GLsizei width, GLsizei height, GLsizei depth, '
3460 'GLenumTextureFormat format, GLenumPixelType type, '
3461 'const void* pixels, GLboolean internal',
3464 'TransformFeedbackVaryings': {
3466 'data_transfer_methods': ['bucket'],
3467 'decoder_func': 'DoTransformFeedbackVaryings',
3469 'GLuint program, const char** varyings, GLenum buffermode',
3470 'expectation': False,
3473 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3477 'decoder_func': 'DoUniform1fv',
3479 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3483 'decoder_func': 'DoUniform1iv',
3495 'decoder_func': 'DoUniform1uiv',
3499 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3500 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3504 'decoder_func': 'DoUniform2fv',
3509 'decoder_func': 'DoUniform2iv',
3520 'decoder_func': 'DoUniform2uiv',
3524 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3525 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3529 'decoder_func': 'DoUniform3fv',
3534 'decoder_func': 'DoUniform3iv',
3545 'decoder_func': 'DoUniform3uiv',
3549 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3550 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3554 'decoder_func': 'DoUniform4fv',
3559 'decoder_func': 'DoUniform4iv',
3570 'decoder_func': 'DoUniform4uiv',
3574 'UniformMatrix2fv': {
3577 'decoder_func': 'DoUniformMatrix2fv',
3579 'UniformMatrix2x3fv': {
3582 'decoder_func': 'DoUniformMatrix2x3fv',
3585 'UniformMatrix2x4fv': {
3588 'decoder_func': 'DoUniformMatrix2x4fv',
3591 'UniformMatrix3fv': {
3594 'decoder_func': 'DoUniformMatrix3fv',
3596 'UniformMatrix3x2fv': {
3599 'decoder_func': 'DoUniformMatrix3x2fv',
3602 'UniformMatrix3x4fv': {
3605 'decoder_func': 'DoUniformMatrix3x4fv',
3608 'UniformMatrix4fv': {
3611 'decoder_func': 'DoUniformMatrix4fv',
3613 'UniformMatrix4x2fv': {
3616 'decoder_func': 'DoUniformMatrix4x2fv',
3619 'UniformMatrix4x3fv': {
3622 'decoder_func': 'DoUniformMatrix4x3fv',
3625 'UniformBlockBinding': {
3630 'UnmapBufferCHROMIUM': {
3632 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3634 'client_test': False,
3637 'UnmapBufferSubDataCHROMIUM': {
3639 'extension': 'CHROMIUM_map_sub',
3641 'client_test': False,
3642 'pepper_interface': 'ChromiumMapSub',
3650 'UnmapTexSubImage2DCHROMIUM': {
3652 'extension': "CHROMIUM_sub_image",
3654 'client_test': False,
3655 'pepper_interface': 'ChromiumMapSub',
3660 'decoder_func': 'DoUseProgram',
3662 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3663 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3664 'VertexAttrib1fv': {
3667 'decoder_func': 'DoVertexAttrib1fv',
3669 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3670 'VertexAttrib2fv': {
3673 'decoder_func': 'DoVertexAttrib2fv',
3675 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3676 'VertexAttrib3fv': {
3679 'decoder_func': 'DoVertexAttrib3fv',
3681 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3682 'VertexAttrib4fv': {
3685 'decoder_func': 'DoVertexAttrib4fv',
3687 'VertexAttribI4i': {
3689 'decoder_func': 'DoVertexAttribI4i',
3691 'VertexAttribI4iv': {
3695 'decoder_func': 'DoVertexAttribI4iv',
3697 'VertexAttribI4ui': {
3699 'decoder_func': 'DoVertexAttribI4ui',
3701 'VertexAttribI4uiv': {
3705 'decoder_func': 'DoVertexAttribI4uiv',
3707 'VertexAttribIPointer': {
3709 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3710 'GLenumVertexAttribIType type, GLsizei stride, '
3712 'client_test': False,
3715 'VertexAttribPointer': {
3717 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3718 'GLenumVertexAttribType type, GLboolean normalized, '
3719 'GLsizei stride, GLuint offset',
3720 'client_test': False,
3724 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3725 'GLuint timeout_0, GLuint timeout_1',
3727 'client_test': False,
3736 'decoder_func': 'DoViewport',
3746 'GetRequestableExtensionsCHROMIUM': {
3749 'cmd_args': 'uint32_t bucket_id',
3753 'RequestExtensionCHROMIUM': {
3756 'client_test': False,
3757 'cmd_args': 'uint32_t bucket_id',
3758 'extension': 'CHROMIUM_request_extension',
3761 'RateLimitOffscreenContextCHROMIUM': {
3765 'client_test': False,
3767 'CreateStreamTextureCHROMIUM': {
3768 'type': 'HandWritten',
3775 'TexImageIOSurface2DCHROMIUM': {
3776 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3782 'CopyTextureCHROMIUM': {
3783 'decoder_func': 'DoCopyTextureCHROMIUM',
3785 'extension': "CHROMIUM_copy_texture",
3789 'CopySubTextureCHROMIUM': {
3790 'decoder_func': 'DoCopySubTextureCHROMIUM',
3792 'extension': "CHROMIUM_copy_texture",
3796 'CompressedCopyTextureCHROMIUM': {
3797 'decoder_func': 'DoCompressedCopyTextureCHROMIUM',
3799 'extension': 'CHROMIUM_copy_compressed_texture',
3802 'CompressedCopySubTextureCHROMIUM': {
3803 'decoder_func': 'DoCompressedCopySubTextureCHROMIUM',
3805 'extension': 'CHROMIUM_copy_compressed_texture',
3808 'TexStorage2DEXT': {
3810 'extension': 'EXT_texture_storage',
3811 'decoder_func': 'DoTexStorage2DEXT',
3814 'DrawArraysInstancedANGLE': {
3816 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3817 'GLsizei primcount',
3818 'extension': 'ANGLE_instanced_arrays',
3820 'pepper_interface': 'InstancedArrays',
3821 'defer_draws': True,
3826 'decoder_func': 'DoDrawBuffersEXT',
3828 'client_test': False,
3830 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3832 'extension': 'EXT_draw_buffers',
3833 'pepper_interface': 'DrawBuffers',
3836 'DrawElementsInstancedANGLE': {
3838 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3839 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3840 'extension': 'ANGLE_instanced_arrays',
3842 'client_test': False,
3843 'pepper_interface': 'InstancedArrays',
3844 'defer_draws': True,
3847 'VertexAttribDivisorANGLE': {
3849 'cmd_args': 'GLuint index, GLuint divisor',
3850 'extension': 'ANGLE_instanced_arrays',
3852 'pepper_interface': 'InstancedArrays',
3856 'gl_test_func': 'glGenQueriesARB',
3857 'resource_type': 'Query',
3858 'resource_types': 'Queries',
3860 'pepper_interface': 'Query',
3861 'not_shared': 'True',
3862 'extension': "occlusion_query_EXT",
3864 'DeleteQueriesEXT': {
3866 'gl_test_func': 'glDeleteQueriesARB',
3867 'resource_type': 'Query',
3868 'resource_types': 'Queries',
3870 'pepper_interface': 'Query',
3871 'extension': "occlusion_query_EXT",
3875 'client_test': False,
3876 'pepper_interface': 'Query',
3877 'extension': "occlusion_query_EXT",
3881 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3882 'data_transfer_methods': ['shm'],
3883 'gl_test_func': 'glBeginQuery',
3884 'pepper_interface': 'Query',
3885 'extension': "occlusion_query_EXT",
3887 'BeginTransformFeedback': {
3892 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3893 'gl_test_func': 'glEndnQuery',
3894 'client_test': False,
3895 'pepper_interface': 'Query',
3896 'extension': "occlusion_query_EXT",
3898 'EndTransformFeedback': {
3901 'FlushDriverCachesCHROMIUM': {
3902 'decoder_func': 'DoFlushDriverCachesCHROMIUM',
3910 'client_test': False,
3911 'gl_test_func': 'glGetQueryiv',
3912 'pepper_interface': 'Query',
3913 'extension': "occlusion_query_EXT",
3915 'QueryCounterEXT' : {
3917 'cmd_args': 'GLidQuery id, GLenumQueryTarget target, '
3918 'void* sync_data, GLuint submit_count',
3919 'data_transfer_methods': ['shm'],
3920 'gl_test_func': 'glQueryCounter',
3921 'extension': "disjoint_timer_query_EXT",
3923 'GetQueryObjectivEXT': {
3925 'client_test': False,
3926 'gl_test_func': 'glGetQueryObjectiv',
3927 'extension': "disjoint_timer_query_EXT",
3929 'GetQueryObjectuivEXT': {
3931 'client_test': False,
3932 'gl_test_func': 'glGetQueryObjectuiv',
3933 'pepper_interface': 'Query',
3934 'extension': "occlusion_query_EXT",
3936 'GetQueryObjecti64vEXT': {
3938 'client_test': False,
3939 'gl_test_func': 'glGetQueryObjecti64v',
3940 'extension': "disjoint_timer_query_EXT",
3942 'GetQueryObjectui64vEXT': {
3944 'client_test': False,
3945 'gl_test_func': 'glGetQueryObjectui64v',
3946 'extension': "disjoint_timer_query_EXT",
3948 'SetDisjointValueSyncCHROMIUM': {
3950 'data_transfer_methods': ['shm'],
3951 'client_test': False,
3952 'cmd_args': 'void* sync_data',
3956 'BindUniformLocationCHROMIUM': {
3958 'extension': 'CHROMIUM_bind_uniform_location',
3959 'data_transfer_methods': ['bucket'],
3961 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3963 'InsertEventMarkerEXT': {
3965 'decoder_func': 'DoInsertEventMarkerEXT',
3966 'expectation': False,
3967 'extension': 'EXT_debug_marker',
3969 'PushGroupMarkerEXT': {
3971 'decoder_func': 'DoPushGroupMarkerEXT',
3972 'expectation': False,
3973 'extension': 'EXT_debug_marker',
3975 'PopGroupMarkerEXT': {
3976 'decoder_func': 'DoPopGroupMarkerEXT',
3977 'expectation': False,
3978 'extension': 'EXT_debug_marker',
3982 'GenVertexArraysOES': {
3984 'extension': 'OES_vertex_array_object',
3985 'gl_test_func': 'glGenVertexArraysOES',
3986 'resource_type': 'VertexArray',
3987 'resource_types': 'VertexArrays',
3989 'pepper_interface': 'VertexArrayObject',
3991 'BindVertexArrayOES': {
3993 'extension': 'OES_vertex_array_object',
3994 'gl_test_func': 'glBindVertexArrayOES',
3995 'decoder_func': 'DoBindVertexArrayOES',
3996 'gen_func': 'GenVertexArraysOES',
3998 'client_test': False,
3999 'pepper_interface': 'VertexArrayObject',
4001 'DeleteVertexArraysOES': {
4003 'extension': 'OES_vertex_array_object',
4004 'gl_test_func': 'glDeleteVertexArraysOES',
4005 'resource_type': 'VertexArray',
4006 'resource_types': 'VertexArrays',
4008 'pepper_interface': 'VertexArrayObject',
4010 'IsVertexArrayOES': {
4012 'extension': 'OES_vertex_array_object',
4013 'gl_test_func': 'glIsVertexArrayOES',
4014 'decoder_func': 'DoIsVertexArrayOES',
4015 'expectation': False,
4017 'pepper_interface': 'VertexArrayObject',
4019 'BindTexImage2DCHROMIUM': {
4020 'decoder_func': 'DoBindTexImage2DCHROMIUM',
4022 'extension': "CHROMIUM_image",
4025 'ReleaseTexImage2DCHROMIUM': {
4026 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
4028 'extension': "CHROMIUM_image",
4031 'ShallowFinishCHROMIUM': {
4036 'client_test': False,
4038 'ShallowFlushCHROMIUM': {
4041 'extension': "CHROMIUM_miscellaneous",
4043 'client_test': False,
4045 'OrderingBarrierCHROMIUM': {
4048 'extension': "CHROMIUM_miscellaneous",
4050 'client_test': False,
4052 'TraceBeginCHROMIUM': {
4055 'client_test': False,
4056 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
4057 'extension': 'CHROMIUM_trace_marker',
4060 'TraceEndCHROMIUM': {
4062 'client_test': False,
4063 'decoder_func': 'DoTraceEndCHROMIUM',
4065 'extension': 'CHROMIUM_trace_marker',
4068 'DiscardFramebufferEXT': {
4071 'decoder_func': 'DoDiscardFramebufferEXT',
4073 'client_test': False,
4074 'extension': 'EXT_discard_framebuffer',
4075 'extension_flag': 'ext_discard_framebuffer',
4078 'LoseContextCHROMIUM': {
4079 'decoder_func': 'DoLoseContextCHROMIUM',
4081 'extension': 'CHROMIUM_lose_context',
4085 'InsertSyncPointCHROMIUM': {
4086 'type': 'HandWritten',
4088 'extension': "CHROMIUM_sync_point",
4092 'WaitSyncPointCHROMIUM': {
4095 'extension': "CHROMIUM_sync_point",
4099 'DiscardBackbufferCHROMIUM': {
4106 'ScheduleOverlayPlaneCHROMIUM': {
4110 'client_test': False,
4111 'extension': 'CHROMIUM_schedule_overlay_plane',
4114 'MatrixLoadfCHROMIUM': {
4117 'data_type': 'GLfloat',
4118 'decoder_func': 'DoMatrixLoadfCHROMIUM',
4119 'gl_test_func': 'glMatrixLoadfEXT',
4121 'extension': 'CHROMIUM_path_rendering',
4122 'extension_flag': 'chromium_path_rendering',
4124 'MatrixLoadIdentityCHROMIUM': {
4125 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
4126 'gl_test_func': 'glMatrixLoadIdentityEXT',
4128 'extension': 'CHROMIUM_path_rendering',
4129 'extension_flag': 'chromium_path_rendering',
4131 'GenPathsCHROMIUM': {
4133 'cmd_args': 'GLuint first_client_id, GLsizei range',
4135 'extension': 'CHROMIUM_path_rendering',
4136 'extension_flag': 'chromium_path_rendering',
4138 'DeletePathsCHROMIUM': {
4140 'cmd_args': 'GLuint first_client_id, GLsizei range',
4144 'extension': 'CHROMIUM_path_rendering',
4145 'extension_flag': 'chromium_path_rendering',
4149 'decoder_func': 'DoIsPathCHROMIUM',
4150 'gl_test_func': 'glIsPathNV',
4152 'extension': 'CHROMIUM_path_rendering',
4153 'extension_flag': 'chromium_path_rendering',
4155 'PathCommandsCHROMIUM': {
4159 'extension': 'CHROMIUM_path_rendering',
4160 'extension_flag': 'chromium_path_rendering',
4162 'PathParameterfCHROMIUM': {
4165 'extension': 'CHROMIUM_path_rendering',
4166 'extension_flag': 'chromium_path_rendering',
4168 'PathParameteriCHROMIUM': {
4171 'extension': 'CHROMIUM_path_rendering',
4172 'extension_flag': 'chromium_path_rendering',
4174 'PathStencilFuncCHROMIUM': {
4176 'state': 'PathStencilFuncCHROMIUM',
4177 'decoder_func': 'glPathStencilFuncNV',
4179 'extension': 'CHROMIUM_path_rendering',
4180 'extension_flag': 'chromium_path_rendering',
4182 'StencilFillPathCHROMIUM': {
4185 'extension': 'CHROMIUM_path_rendering',
4186 'extension_flag': 'chromium_path_rendering',
4188 'StencilStrokePathCHROMIUM': {
4191 'extension': 'CHROMIUM_path_rendering',
4192 'extension_flag': 'chromium_path_rendering',
4194 'CoverFillPathCHROMIUM': {
4197 'extension': 'CHROMIUM_path_rendering',
4198 'extension_flag': 'chromium_path_rendering',
4200 'CoverStrokePathCHROMIUM': {
4203 'extension': 'CHROMIUM_path_rendering',
4204 'extension_flag': 'chromium_path_rendering',
4206 'StencilThenCoverFillPathCHROMIUM': {
4209 'extension': 'CHROMIUM_path_rendering',
4210 'extension_flag': 'chromium_path_rendering',
4212 'StencilThenCoverStrokePathCHROMIUM': {
4215 'extension': 'CHROMIUM_path_rendering',
4216 'extension_flag': 'chromium_path_rendering',
4222 def Grouper(n
, iterable
, fillvalue
=None):
4223 """Collect data into fixed-length chunks or blocks"""
4224 args
= [iter(iterable
)] * n
4225 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
4228 def SplitWords(input_string
):
4229 """Split by '_' if found, otherwise split at uppercase/numeric chars.
4231 Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
4232 "Case"], and "Vector3" into ["Vector", "3"].
4234 if input_string
.find('_') > -1:
4235 # 'some_TEXT_' -> 'some TEXT'
4236 return input_string
.replace('_', ' ').strip().split()
4238 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
4240 # look for capitalization to cut input_strings
4241 # 'SomeText' -> 'Some Text'
4242 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
4243 # 'Vector3' -> 'Vector 3'
4244 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
4245 return input_string
.split()
4247 def ToUnderscore(input_string
):
4248 """converts CamelCase to camel_case."""
4249 words
= SplitWords(input_string
)
4250 return '_'.join([word
.lower() for word
in words
])
4252 def CachedStateName(item
):
4253 if item
.get('cached', False):
4254 return 'cached_' + item
['name']
4257 def ToGLExtensionString(extension_flag
):
4258 """Returns GL-type extension string of a extension flag."""
4259 if extension_flag
== "oes_compressed_etc1_rgb8_texture":
4260 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
4262 uppercase_words
= [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
4263 'egl', 'atc', 'etc1', 'angle']
4264 parts
= extension_flag
.split('_')
4266 [part
.upper() if part
in uppercase_words
else part
for part
in parts
])
4268 def ToCamelCase(input_string
):
4269 """converts ABC_underscore_case to ABCUnderscoreCase."""
4270 return ''.join(w
[0].upper() + w
[1:] for w
in input_string
.split('_'))
4272 def GetGLGetTypeConversion(result_type
, value_type
, value
):
4273 """Makes a gl compatible type conversion string for accessing state variables.
4275 Useful when accessing state variables through glGetXXX calls.
4276 glGet documetation (for example, the manual pages):
4277 [...] If glGetIntegerv is called, [...] most floating-point values are
4278 rounded to the nearest integer value. [...]
4281 result_type: the gl type to be obtained
4282 value_type: the GL type of the state variable
4283 value: the name of the state variable
4286 String that converts the state variable to desired GL type according to GL
4290 if result_type
== 'GLint':
4291 if value_type
== 'GLfloat':
4292 return 'static_cast<GLint>(round(%s))' % value
4293 return 'static_cast<%s>(%s)' % (result_type
, value
)
4296 class CWriter(object):
4297 """Context manager that creates a C source file.
4299 To be used with the `with` statement. Returns a normal `file` type, open only
4300 for writing - any existing files with that name will be overwritten. It will
4301 automatically write the contents of `_LICENSE` and `_DO_NOT_EDIT_WARNING`
4305 with CWriter("file.cpp") as myfile:
4306 myfile.write("hello")
4307 # type(myfile) == file
4309 def __init__(self
, filename
):
4310 self
.filename
= filename
4311 self
._file
= open(filename
, 'w')
4312 self
._ENTER
_MSG
= _LICENSE
+ _DO_NOT_EDIT_WARNING
4315 def __enter__(self
):
4316 self
._file
.write(self
._ENTER
_MSG
)
4319 def __exit__(self
, exc_type
, exc_value
, traceback
):
4320 self
._file
.write(self
._EXIT
_MSG
)
4324 class CHeaderWriter(CWriter
):
4325 """Context manager that creates a C header file.
4327 Works the same way as CWriter, except it will also add the #ifdef guard
4328 around it. If `file_comment` is set, it will write that before the #ifdef
4331 def __init__(self
, filename
, file_comment
=None):
4332 super(CHeaderWriter
, self
).__init
__(filename
)
4333 guard
= self
._get
_guard
()
4334 if file_comment
is None:
4336 self
._ENTER
_MSG
= self
._ENTER
_MSG
+ file_comment \
4337 + "#ifndef %s\n#define %s\n\n" % (guard
, guard
)
4338 self
._EXIT
_MSG
= self
._EXIT
_MSG
+ "#endif // %s\n" % guard
4340 def _get_guard(self
):
4341 non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
4342 base
= os
.path
.abspath(self
.filename
)
4343 while os
.path
.basename(base
) != 'src':
4344 new_base
= os
.path
.dirname(base
)
4345 assert new_base
!= base
# Prevent infinite loop.
4347 hpath
= os
.path
.relpath(self
.filename
, base
)
4348 return non_alnum_re
.sub('_', hpath
).upper() + '_'
4351 class TypeHandler(object):
4352 """This class emits code for a particular type of function."""
4354 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
4356 def InitFunction(self
, func
):
4357 """Add or adjust anything type specific for this function."""
4358 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
4359 func
.AddCmdArg(DataSizeArgument('data_size'))
4361 def NeedsDataTransferFunction(self
, func
):
4362 """Overriden from TypeHandler."""
4363 return func
.num_pointer_args
>= 1
4365 def WriteStruct(self
, func
, f
):
4366 """Writes a structure that matches the arguments to a function."""
4367 comment
= func
.GetInfo('cmd_comment')
4368 if not comment
== None:
4370 f
.write("struct %s {\n" % func
.name
)
4371 f
.write(" typedef %s ValueType;\n" % func
.name
)
4372 f
.write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
4373 func
.WriteCmdArgFlag(f
)
4374 func
.WriteCmdFlag(f
)
4376 result
= func
.GetInfo('result')
4377 if not result
== None:
4378 if len(result
) == 1:
4379 f
.write(" typedef %s Result;\n\n" % result
[0])
4381 f
.write(" struct Result {\n")
4383 f
.write(" %s;\n" % line
)
4386 func
.WriteCmdComputeSize(f
)
4387 func
.WriteCmdSetHeader(f
)
4388 func
.WriteCmdInit(f
)
4391 f
.write(" gpu::CommandHeader header;\n")
4392 args
= func
.GetCmdArgs()
4394 f
.write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
4396 consts
= func
.GetCmdConstants()
4397 for const
in consts
:
4398 f
.write(" static const %s %s = %s;\n" %
4399 (const
.cmd_type
, const
.name
, const
.GetConstantValue()))
4404 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
4405 f
.write("static_assert(sizeof(%s) == %d,\n" % (func
.name
, size
))
4406 f
.write(" \"size of %s should be %d\");\n" %
4408 f
.write("static_assert(offsetof(%s, header) == 0,\n" % func
.name
)
4409 f
.write(" \"offset of %s header should be 0\");\n" %
4411 offset
= _SIZE_OF_COMMAND_HEADER
4413 f
.write("static_assert(offsetof(%s, %s) == %d,\n" %
4414 (func
.name
, arg
.name
, offset
))
4415 f
.write(" \"offset of %s %s should be %d\");\n" %
4416 (func
.name
, arg
.name
, offset
))
4417 offset
+= _SIZE_OF_UINT32
4418 if not result
== None and len(result
) > 1:
4421 parts
= line
.split()
4424 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4425 "offset of %(cmd_name)s Result %(field_name)s should be "
4428 f
.write((check
.strip() + "\n") % {
4429 'cmd_name': func
.name
,
4433 offset
+= _SIZE_OF_UINT32
4436 def WriteHandlerImplementation(self
, func
, f
):
4437 """Writes the handler implementation for this command."""
4438 if func
.IsUnsafe() and func
.GetInfo('id_mapping'):
4439 code_no_gen
= """ if (!group_->Get%(type)sServiceId(
4440 %(var)s, &%(service_var)s)) {
4441 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4442 return error::kNoError;
4445 code_gen
= """ if (!group_->Get%(type)sServiceId(
4446 %(var)s, &%(service_var)s)) {
4447 if (!group_->bind_generates_resource()) {
4449 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4450 return error::kNoError;
4452 GLuint client_id = %(var)s;
4453 gl%(gen_func)s(1, &%(service_var)s);
4454 Create%(type)s(client_id, %(service_var)s);
4457 gen_func
= func
.GetInfo('gen_func')
4458 for id_type
in func
.GetInfo('id_mapping'):
4459 service_var
= id_type
.lower()
4460 if id_type
== 'Sync':
4461 service_var
= "service_%s" % service_var
4462 f
.write(" GLsync %s = 0;\n" % service_var
)
4463 if id_type
== 'Sampler' and func
.IsType('Bind'):
4464 # No error generated when binding a reserved zero sampler.
4465 args
= [arg
.name
for arg
in func
.GetOriginalArgs()]
4466 f
.write(""" if(%(var)s == 0) {
4468 return error::kNoError;
4469 }""" % { 'var': id_type
.lower(),
4470 'func': func
.GetGLFunctionName(),
4471 'args': ", ".join(args
) })
4472 if gen_func
and id_type
in gen_func
:
4473 f
.write(code_gen
% { 'type': id_type
,
4474 'var': id_type
.lower(),
4475 'service_var': service_var
,
4476 'func': func
.GetGLFunctionName(),
4477 'gen_func': gen_func
})
4479 f
.write(code_no_gen
% { 'type': id_type
,
4480 'var': id_type
.lower(),
4481 'service_var': service_var
,
4482 'func': func
.GetGLFunctionName() })
4484 for arg
in func
.GetOriginalArgs():
4485 if arg
.type == "GLsync":
4486 args
.append("service_%s" % arg
.name
)
4487 elif arg
.name
.endswith("size") and arg
.type == "GLsizei":
4488 args
.append("num_%s" % func
.GetLastOriginalArg().name
)
4489 elif arg
.name
== "length":
4490 args
.append("nullptr")
4492 args
.append(arg
.name
)
4493 f
.write(" %s(%s);\n" %
4494 (func
.GetGLFunctionName(), ", ".join(args
)))
4496 def WriteCmdSizeTest(self
, func
, f
):
4497 """Writes the size test for a command."""
4498 f
.write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4500 def WriteFormatTest(self
, func
, f
):
4501 """Writes a format test for a command."""
4502 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4503 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4504 (func
.name
, func
.name
))
4505 f
.write(" void* next_cmd = cmd.Set(\n")
4507 args
= func
.GetCmdArgs()
4508 for value
, arg
in enumerate(args
):
4509 f
.write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
4511 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4513 f
.write(" cmd.header.command);\n")
4514 func
.type_handler
.WriteCmdSizeTest(func
, f
)
4515 for value
, arg
in enumerate(args
):
4516 f
.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4517 (arg
.type, value
+ 11, arg
.name
))
4518 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
4519 f
.write(" next_cmd, sizeof(cmd));\n")
4523 def WriteImmediateFormatTest(self
, func
, f
):
4524 """Writes a format test for an immediate version of a command."""
4527 def WriteGetDataSizeCode(self
, func
, f
):
4528 """Writes the code to set data_size used in validation"""
4531 def __WriteIdMapping(self
, func
, f
):
4532 """Writes client side / service side ID mapping."""
4533 if not func
.IsUnsafe() or not func
.GetInfo('id_mapping'):
4535 for id_type
in func
.GetInfo('id_mapping'):
4536 f
.write(" group_->Get%sServiceId(%s, &%s);\n" %
4537 (id_type
, id_type
.lower(), id_type
.lower()))
4539 def WriteImmediateHandlerImplementation (self
, func
, f
):
4540 """Writes the handler impl for the immediate version of a command."""
4541 self
.__WriteIdMapping
(func
, f
)
4542 f
.write(" %s(%s);\n" %
4543 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4545 def WriteBucketHandlerImplementation (self
, func
, f
):
4546 """Writes the handler impl for the bucket version of a command."""
4547 self
.__WriteIdMapping
(func
, f
)
4548 f
.write(" %s(%s);\n" %
4549 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4551 def WriteServiceHandlerFunctionHeader(self
, func
, f
):
4552 """Writes function header for service implementation handlers."""
4553 f
.write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4554 uint32_t immediate_data_size, const void* cmd_data) {
4555 """ % {'name': func
.name
})
4557 f
.write("""if (!unsafe_es3_apis_enabled())
4558 return error::kUnknownCommand;
4560 f
.write("""const gles2::cmds::%(name)s& c =
4561 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4563 """ % {'name': func
.name
})
4565 def WriteServiceImplementation(self
, func
, f
):
4566 """Writes the service implementation for a command."""
4567 self
.WriteServiceHandlerFunctionHeader(func
, f
)
4568 self
.WriteHandlerExtensionCheck(func
, f
)
4569 self
.WriteHandlerDeferReadWrite(func
, f
);
4570 if len(func
.GetOriginalArgs()) > 0:
4571 last_arg
= func
.GetLastOriginalArg()
4572 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
4573 for arg
in all_but_last_arg
:
4575 self
.WriteGetDataSizeCode(func
, f
)
4576 last_arg
.WriteGetCode(f
)
4577 func
.WriteHandlerValidation(f
)
4578 func
.WriteHandlerImplementation(f
)
4579 f
.write(" return error::kNoError;\n")
4583 def WriteImmediateServiceImplementation(self
, func
, f
):
4584 """Writes the service implementation for an immediate version of command."""
4585 self
.WriteServiceHandlerFunctionHeader(func
, f
)
4586 self
.WriteHandlerExtensionCheck(func
, f
)
4587 self
.WriteHandlerDeferReadWrite(func
, f
);
4588 for arg
in func
.GetOriginalArgs():
4590 self
.WriteGetDataSizeCode(func
, f
)
4592 func
.WriteHandlerValidation(f
)
4593 func
.WriteHandlerImplementation(f
)
4594 f
.write(" return error::kNoError;\n")
4598 def WriteBucketServiceImplementation(self
, func
, f
):
4599 """Writes the service implementation for a bucket version of command."""
4600 self
.WriteServiceHandlerFunctionHeader(func
, f
)
4601 self
.WriteHandlerExtensionCheck(func
, f
)
4602 self
.WriteHandlerDeferReadWrite(func
, f
);
4603 for arg
in func
.GetCmdArgs():
4605 func
.WriteHandlerValidation(f
)
4606 func
.WriteHandlerImplementation(f
)
4607 f
.write(" return error::kNoError;\n")
4611 def WriteHandlerExtensionCheck(self
, func
, f
):
4612 if func
.GetInfo('extension_flag'):
4613 f
.write(" if (!features().%s) {\n" % func
.GetInfo('extension_flag'))
4614 f
.write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4615 " \"function not available\");\n" % func
.original_name
)
4616 f
.write(" return error::kNoError;")
4619 def WriteHandlerDeferReadWrite(self
, func
, f
):
4620 """Writes the code to handle deferring reads or writes."""
4621 defer_draws
= func
.GetInfo('defer_draws')
4622 defer_reads
= func
.GetInfo('defer_reads')
4623 if defer_draws
or defer_reads
:
4624 f
.write(" error::Error error;\n")
4626 f
.write(" error = WillAccessBoundFramebufferForDraw();\n")
4627 f
.write(" if (error != error::kNoError)\n")
4628 f
.write(" return error;\n")
4630 f
.write(" error = WillAccessBoundFramebufferForRead();\n")
4631 f
.write(" if (error != error::kNoError)\n")
4632 f
.write(" return error;\n")
4634 def WriteValidUnitTest(self
, func
, f
, test
, *extras
):
4635 """Writes a valid unit test for the service implementation."""
4636 if func
.GetInfo('expectation') == False:
4637 test
= self
._remove
_expected
_call
_re
.sub('', test
)
4640 arg
.GetValidArg(func
) \
4641 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4644 arg
.GetValidGLArg(func
) \
4645 for arg
in func
.GetOriginalArgs()
4647 gl_func_name
= func
.GetGLTestFunctionName()
4650 'gl_func_name': gl_func_name
,
4651 'args': ", ".join(arg_strings
),
4652 'gl_args': ", ".join(gl_arg_strings
),
4654 for extra
in extras
:
4657 while (old_test
!= test
):
4660 f
.write(test
% vars)
4662 def WriteInvalidUnitTest(self
, func
, f
, test
, *extras
):
4663 """Writes an invalid unit test for the service implementation."""
4666 for invalid_arg_index
, invalid_arg
in enumerate(func
.GetOriginalArgs()):
4667 # Service implementation does not test constants, as they are not part of
4668 # the call in the service side.
4669 if invalid_arg
.IsConstant():
4672 num_invalid_values
= invalid_arg
.GetNumInvalidValues(func
)
4673 for value_index
in range(0, num_invalid_values
):
4675 parse_result
= "kNoError"
4677 for arg
in func
.GetOriginalArgs():
4678 if arg
.IsConstant():
4680 if invalid_arg
is arg
:
4681 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
4684 arg_string
= arg
.GetValidArg(func
)
4685 arg_strings
.append(arg_string
)
4687 for arg
in func
.GetOriginalArgs():
4688 gl_arg_strings
.append("_")
4689 gl_func_name
= func
.GetGLTestFunctionName()
4691 if not gl_error
== None:
4692 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4696 'arg_index': invalid_arg_index
,
4697 'value_index': value_index
,
4698 'gl_func_name': gl_func_name
,
4699 'args': ", ".join(arg_strings
),
4700 'all_but_last_args': ", ".join(arg_strings
[:-1]),
4701 'gl_args': ", ".join(gl_arg_strings
),
4702 'parse_result': parse_result
,
4703 'gl_error_test': gl_error_test
,
4705 for extra
in extras
:
4707 f
.write(test
% vars)
4709 def WriteServiceUnitTest(self
, func
, f
, *extras
):
4710 """Writes the service unit test for a command."""
4712 if func
.name
== 'Enable':
4714 TEST_P(%(test_name)s, %(name)sValidArgs) {
4715 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4716 SpecializedSetup<cmds::%(name)s, 0>(true);
4718 cmd.Init(%(args)s);"""
4719 elif func
.name
== 'Disable':
4721 TEST_P(%(test_name)s, %(name)sValidArgs) {
4722 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4723 SpecializedSetup<cmds::%(name)s, 0>(true);
4725 cmd.Init(%(args)s);"""
4728 TEST_P(%(test_name)s, %(name)sValidArgs) {
4729 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4730 SpecializedSetup<cmds::%(name)s, 0>(true);
4732 cmd.Init(%(args)s);"""
4735 decoder_->set_unsafe_es3_apis_enabled(true);
4736 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4737 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4738 decoder_->set_unsafe_es3_apis_enabled(false);
4739 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4744 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4745 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4748 self
.WriteValidUnitTest(func
, f
, valid_test
, *extras
)
4750 if not func
.IsUnsafe():
4752 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4753 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4754 SpecializedSetup<cmds::%(name)s, 0>(false);
4757 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4760 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, *extras
)
4762 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
4763 """Writes the service unit test for an immediate command."""
4764 f
.write("// TODO(gman): %s\n" % func
.name
)
4766 def WriteImmediateValidationCode(self
, func
, f
):
4767 """Writes the validation code for an immediate version of a command."""
4770 def WriteBucketServiceUnitTest(self
, func
, f
, *extras
):
4771 """Writes the service unit test for a bucket command."""
4772 f
.write("// TODO(gman): %s\n" % func
.name
)
4774 def WriteGLES2ImplementationDeclaration(self
, func
, f
):
4775 """Writes the GLES2 Implemention declaration."""
4776 impl_decl
= func
.GetInfo('impl_decl')
4777 if impl_decl
== None or impl_decl
== True:
4778 f
.write("%s %s(%s) override;\n" %
4779 (func
.return_type
, func
.original_name
,
4780 func
.MakeTypedOriginalArgString("")))
4783 def WriteGLES2CLibImplementation(self
, func
, f
):
4784 f
.write("%s GL_APIENTRY GLES2%s(%s) {\n" %
4785 (func
.return_type
, func
.name
,
4786 func
.MakeTypedOriginalArgString("")))
4787 result_string
= "return "
4788 if func
.return_type
== "void":
4790 f
.write(" %sgles2::GetGLContext()->%s(%s);\n" %
4791 (result_string
, func
.original_name
,
4792 func
.MakeOriginalArgString("")))
4795 def WriteGLES2Header(self
, func
, f
):
4796 """Writes a re-write macro for GLES"""
4797 f
.write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
4799 def WriteClientGLCallLog(self
, func
, f
):
4800 """Writes a logging macro for the client side code."""
4802 if len(func
.GetOriginalArgs()):
4805 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4806 (func
.original_name
, comma
, func
.MakeLogArgString()))
4808 def WriteClientGLReturnLog(self
, func
, f
):
4809 """Writes the return value logging code."""
4810 if func
.return_type
!= "void":
4811 f
.write(' GPU_CLIENT_LOG("return:" << result)\n')
4813 def WriteGLES2ImplementationHeader(self
, func
, f
):
4814 """Writes the GLES2 Implemention."""
4815 self
.WriteGLES2ImplementationDeclaration(func
, f
)
4817 def WriteGLES2TraceImplementationHeader(self
, func
, f
):
4818 """Writes the GLES2 Trace Implemention header."""
4819 f
.write("%s %s(%s) override;\n" %
4820 (func
.return_type
, func
.original_name
,
4821 func
.MakeTypedOriginalArgString("")))
4823 def WriteGLES2TraceImplementation(self
, func
, f
):
4824 """Writes the GLES2 Trace Implemention."""
4825 f
.write("%s GLES2TraceImplementation::%s(%s) {\n" %
4826 (func
.return_type
, func
.original_name
,
4827 func
.MakeTypedOriginalArgString("")))
4828 result_string
= "return "
4829 if func
.return_type
== "void":
4831 f
.write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4833 f
.write(" %sgl_->%s(%s);\n" %
4834 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
4838 def WriteGLES2Implementation(self
, func
, f
):
4839 """Writes the GLES2 Implemention."""
4840 impl_func
= func
.GetInfo('impl_func')
4841 impl_decl
= func
.GetInfo('impl_decl')
4842 gen_cmd
= func
.GetInfo('gen_cmd')
4843 if (func
.can_auto_generate
and
4844 (impl_func
== None or impl_func
== True) and
4845 (impl_decl
== None or impl_decl
== True) and
4846 (gen_cmd
== None or gen_cmd
== True)):
4847 f
.write("%s GLES2Implementation::%s(%s) {\n" %
4848 (func
.return_type
, func
.original_name
,
4849 func
.MakeTypedOriginalArgString("")))
4850 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4851 self
.WriteClientGLCallLog(func
, f
)
4852 func
.WriteDestinationInitalizationValidation(f
)
4853 for arg
in func
.GetOriginalArgs():
4854 arg
.WriteClientSideValidationCode(f
, func
)
4855 f
.write(" helper_->%s(%s);\n" %
4856 (func
.name
, func
.MakeHelperArgString("")))
4857 f
.write(" CheckGLError();\n")
4858 self
.WriteClientGLReturnLog(func
, f
)
4862 def WriteGLES2InterfaceHeader(self
, func
, f
):
4863 """Writes the GLES2 Interface."""
4864 f
.write("virtual %s %s(%s) = 0;\n" %
4865 (func
.return_type
, func
.original_name
,
4866 func
.MakeTypedOriginalArgString("")))
4868 def WriteMojoGLES2ImplHeader(self
, func
, f
):
4869 """Writes the Mojo GLES2 implementation header."""
4870 f
.write("%s %s(%s) override;\n" %
4871 (func
.return_type
, func
.original_name
,
4872 func
.MakeTypedOriginalArgString("")))
4874 def WriteMojoGLES2Impl(self
, func
, f
):
4875 """Writes the Mojo GLES2 implementation."""
4876 f
.write("%s MojoGLES2Impl::%s(%s) {\n" %
4877 (func
.return_type
, func
.original_name
,
4878 func
.MakeTypedOriginalArgString("")))
4879 is_core_gl_func
= func
.IsCoreGLFunction()
4880 is_ext
= bool(func
.GetInfo("extension"))
4881 is_safe
= not func
.IsUnsafe()
4882 if is_core_gl_func
or (is_safe
and is_ext
):
4883 f
.write("MojoGLES2MakeCurrent(context_);");
4884 func_return
= "gl" + func
.original_name
+ "(" + \
4885 func
.MakeOriginalArgString("") + ");"
4886 if func
.return_type
== "void":
4887 f
.write(func_return
);
4889 f
.write("return " + func_return
);
4891 f
.write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4892 func
.original_name
);
4893 if func
.return_type
!= "void":
4894 f
.write("return 0;")
4897 def WriteGLES2InterfaceStub(self
, func
, f
):
4898 """Writes the GLES2 Interface stub declaration."""
4899 f
.write("%s %s(%s) override;\n" %
4900 (func
.return_type
, func
.original_name
,
4901 func
.MakeTypedOriginalArgString("")))
4903 def WriteGLES2InterfaceStubImpl(self
, func
, f
):
4904 """Writes the GLES2 Interface stub declaration."""
4905 args
= func
.GetOriginalArgs()
4906 arg_string
= ", ".join(
4907 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
4908 f
.write("%s GLES2InterfaceStub::%s(%s) {\n" %
4909 (func
.return_type
, func
.original_name
, arg_string
))
4910 if func
.return_type
!= "void":
4911 f
.write(" return 0;\n")
4914 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
4915 """Writes the GLES2 Implemention unit test."""
4916 client_test
= func
.GetInfo('client_test')
4917 if (func
.can_auto_generate
and
4918 (client_test
== None or client_test
== True)):
4920 TEST_F(GLES2ImplementationTest, %(name)s) {
4925 expected.cmd.Init(%(cmd_args)s);
4927 gl_->%(name)s(%(args)s);
4928 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4932 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
4936 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
4941 'args': ", ".join(gl_arg_strings
),
4942 'cmd_args': ", ".join(cmd_arg_strings
),
4945 # Test constants for invalid values, as they are not tested by the
4947 constants
= [arg
for arg
in func
.GetOriginalArgs() if arg
.IsConstant()]
4950 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4951 gl_->%(name)s(%(args)s);
4952 EXPECT_TRUE(NoCommandsWritten());
4953 EXPECT_EQ(%(gl_error)s, CheckError());
4956 for invalid_arg
in constants
:
4958 invalid
= invalid_arg
.GetInvalidArg(func
)
4959 for arg
in func
.GetOriginalArgs():
4960 if arg
is invalid_arg
:
4961 gl_arg_strings
.append(invalid
[0])
4963 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
4967 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
4968 'args': ", ".join(gl_arg_strings
),
4969 'gl_error': invalid
[2],
4972 if client_test
!= False:
4973 f
.write("// TODO(zmo): Implement unit test for %s\n" % func
.name
)
4975 def WriteDestinationInitalizationValidation(self
, func
, f
):
4976 """Writes the client side destintion initialization validation."""
4977 for arg
in func
.GetOriginalArgs():
4978 arg
.WriteDestinationInitalizationValidation(f
, func
)
4980 def WriteTraceEvent(self
, func
, f
):
4981 f
.write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4984 def WriteImmediateCmdComputeSize(self
, func
, f
):
4985 """Writes the size computation code for the immediate version of a cmd."""
4986 f
.write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4987 f
.write(" return static_cast<uint32_t>(\n")
4988 f
.write(" sizeof(ValueType) + // NOLINT\n")
4989 f
.write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4993 def WriteImmediateCmdSetHeader(self
, func
, f
):
4994 """Writes the SetHeader function for the immediate version of a cmd."""
4995 f
.write(" void SetHeader(uint32_t size_in_bytes) {\n")
4996 f
.write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
5000 def WriteImmediateCmdInit(self
, func
, f
):
5001 """Writes the Init function for the immediate version of a command."""
5002 raise NotImplementedError(func
.name
)
5004 def WriteImmediateCmdSet(self
, func
, f
):
5005 """Writes the Set function for the immediate version of a command."""
5006 raise NotImplementedError(func
.name
)
5008 def WriteCmdHelper(self
, func
, f
):
5009 """Writes the cmd helper definition for a cmd."""
5010 code
= """ void %(name)s(%(typed_args)s) {
5011 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
5020 "typed_args": func
.MakeTypedCmdArgString(""),
5021 "args": func
.MakeCmdArgString(""),
5024 def WriteImmediateCmdHelper(self
, func
, f
):
5025 """Writes the cmd helper definition for the immediate version of a cmd."""
5026 code
= """ void %(name)s(%(typed_args)s) {
5027 const uint32_t s = 0; // TODO(gman): compute correct size
5028 gles2::cmds::%(name)s* c =
5029 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
5038 "typed_args": func
.MakeTypedCmdArgString(""),
5039 "args": func
.MakeCmdArgString(""),
5043 class StateSetHandler(TypeHandler
):
5044 """Handler for commands that simply set state."""
5046 def WriteHandlerImplementation(self
, func
, f
):
5047 """Overrriden from TypeHandler."""
5048 state_name
= func
.GetInfo('state')
5049 state
= _STATES
[state_name
]
5050 states
= state
['states']
5051 args
= func
.GetOriginalArgs()
5052 for ndx
,item
in enumerate(states
):
5054 if 'range_checks' in item
:
5055 for range_check
in item
['range_checks']:
5056 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
5057 if 'nan_check' in item
:
5058 # Drivers might generate an INVALID_VALUE error when a value is set
5059 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
5060 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
5061 # Make this behavior consistent within Chromium, and avoid leaking GL
5062 # errors by generating the error in the command buffer instead of
5063 # letting the GL driver generate it.
5064 code
.append("std::isnan(%s)" % args
[ndx
].name
)
5066 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5068 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
5069 ' "%s", "%s out of range");\n' %
5070 (func
.name
, args
[ndx
].name
))
5071 f
.write(" return error::kNoError;\n")
5074 for ndx
,item
in enumerate(states
):
5075 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
5076 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5077 for ndx
,item
in enumerate(states
):
5078 f
.write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
5079 if 'state_flag' in state
:
5080 f
.write(" %s = true;\n" % state
['state_flag'])
5081 if not func
.GetInfo("no_gl"):
5082 for ndx
,item
in enumerate(states
):
5083 if item
.get('cached', False):
5084 f
.write(" state_.%s = %s;\n" %
5085 (CachedStateName(item
), args
[ndx
].name
))
5086 f
.write(" %s(%s);\n" %
5087 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5090 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5091 """Overrriden from TypeHandler."""
5092 TypeHandler
.WriteServiceUnitTest(self
, func
, f
, *extras
)
5093 state_name
= func
.GetInfo('state')
5094 state
= _STATES
[state_name
]
5095 states
= state
['states']
5096 for ndx
,item
in enumerate(states
):
5097 if 'range_checks' in item
:
5098 for check_ndx
, range_check
in enumerate(item
['range_checks']):
5100 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
5101 SpecializedSetup<cmds::%(name)s, 0>(false);
5104 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5105 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5110 arg
.GetValidArg(func
) \
5111 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
5114 arg_strings
[ndx
] = range_check
['test_value']
5118 'check_ndx': check_ndx
,
5119 'args': ", ".join(arg_strings
),
5121 for extra
in extras
:
5123 f
.write(valid_test
% vars)
5124 if 'nan_check' in item
:
5126 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
5127 SpecializedSetup<cmds::%(name)s, 0>(false);
5130 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5131 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5136 arg
.GetValidArg(func
) \
5137 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
5140 arg_strings
[ndx
] = 'nanf("")'
5144 'args': ", ".join(arg_strings
),
5146 for extra
in extras
:
5148 f
.write(valid_test
% vars)
5151 class StateSetRGBAlphaHandler(TypeHandler
):
5152 """Handler for commands that simply set state that have rgb/alpha."""
5154 def WriteHandlerImplementation(self
, func
, f
):
5155 """Overrriden from TypeHandler."""
5156 state_name
= func
.GetInfo('state')
5157 state
= _STATES
[state_name
]
5158 states
= state
['states']
5159 args
= func
.GetOriginalArgs()
5160 num_args
= len(args
)
5162 for ndx
,item
in enumerate(states
):
5163 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
5164 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5165 for ndx
, item
in enumerate(states
):
5166 f
.write(" state_.%s = %s;\n" %
5167 (item
['name'], args
[ndx
% num_args
].name
))
5168 if 'state_flag' in state
:
5169 f
.write(" %s = true;\n" % state
['state_flag'])
5170 if not func
.GetInfo("no_gl"):
5171 f
.write(" %s(%s);\n" %
5172 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5176 class StateSetFrontBackSeparateHandler(TypeHandler
):
5177 """Handler for commands that simply set state that have front/back."""
5179 def WriteHandlerImplementation(self
, func
, f
):
5180 """Overrriden from TypeHandler."""
5181 state_name
= func
.GetInfo('state')
5182 state
= _STATES
[state_name
]
5183 states
= state
['states']
5184 args
= func
.GetOriginalArgs()
5186 num_args
= len(args
)
5187 f
.write(" bool changed = false;\n")
5188 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
5189 f
.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5190 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
5192 for ndx
, item
in enumerate(group
):
5193 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
5194 f
.write(" changed |= %s;\n" % " ||\n ".join(code
))
5196 f
.write(" if (changed) {\n")
5197 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
5198 f
.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5199 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
5200 for ndx
, item
in enumerate(group
):
5201 f
.write(" state_.%s = %s;\n" %
5202 (item
['name'], args
[ndx
+ 1].name
))
5204 if 'state_flag' in state
:
5205 f
.write(" %s = true;\n" % state
['state_flag'])
5206 if not func
.GetInfo("no_gl"):
5207 f
.write(" %s(%s);\n" %
5208 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5212 class StateSetFrontBackHandler(TypeHandler
):
5213 """Handler for commands that simply set state that set both front/back."""
5215 def WriteHandlerImplementation(self
, func
, f
):
5216 """Overrriden from TypeHandler."""
5217 state_name
= func
.GetInfo('state')
5218 state
= _STATES
[state_name
]
5219 states
= state
['states']
5220 args
= func
.GetOriginalArgs()
5221 num_args
= len(args
)
5223 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
5224 for ndx
, item
in enumerate(group
):
5225 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
5226 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5227 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
5228 for ndx
, item
in enumerate(group
):
5229 f
.write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
5230 if 'state_flag' in state
:
5231 f
.write(" %s = true;\n" % state
['state_flag'])
5232 if not func
.GetInfo("no_gl"):
5233 f
.write(" %s(%s);\n" %
5234 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5238 class StateSetNamedParameter(TypeHandler
):
5239 """Handler for commands that set a state chosen with an enum parameter."""
5241 def WriteHandlerImplementation(self
, func
, f
):
5242 """Overridden from TypeHandler."""
5243 state_name
= func
.GetInfo('state')
5244 state
= _STATES
[state_name
]
5245 states
= state
['states']
5246 args
= func
.GetOriginalArgs()
5247 num_args
= len(args
)
5248 assert num_args
== 2
5249 f
.write(" switch (%s) {\n" % args
[0].name
)
5250 for state
in states
:
5251 f
.write(" case %s:\n" % state
['enum'])
5252 f
.write(" if (state_.%s != %s) {\n" %
5253 (state
['name'], args
[1].name
))
5254 f
.write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
5255 if not func
.GetInfo("no_gl"):
5256 f
.write(" %s(%s);\n" %
5257 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5259 f
.write(" break;\n")
5260 f
.write(" default:\n")
5261 f
.write(" NOTREACHED();\n")
5265 class CustomHandler(TypeHandler
):
5266 """Handler for commands that are auto-generated but require minor tweaks."""
5268 def WriteServiceImplementation(self
, func
, f
):
5269 """Overrriden from TypeHandler."""
5272 def WriteImmediateServiceImplementation(self
, func
, f
):
5273 """Overrriden from TypeHandler."""
5276 def WriteBucketServiceImplementation(self
, func
, f
):
5277 """Overrriden from TypeHandler."""
5280 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5281 """Overrriden from TypeHandler."""
5282 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5284 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5285 """Overrriden from TypeHandler."""
5286 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5288 def WriteImmediateCmdGetTotalSize(self
, func
, f
):
5289 """Overrriden from TypeHandler."""
5291 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5293 def WriteImmediateCmdInit(self
, func
, f
):
5294 """Overrriden from TypeHandler."""
5295 f
.write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5296 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5297 f
.write(" SetHeader(total_size);\n")
5298 args
= func
.GetCmdArgs()
5300 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5304 def WriteImmediateCmdSet(self
, func
, f
):
5305 """Overrriden from TypeHandler."""
5306 copy_args
= func
.MakeCmdArgString("_", False)
5307 f
.write(" void* Set(void* cmd%s) {\n" %
5308 func
.MakeTypedCmdArgString("_", True))
5309 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5310 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5311 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5312 "cmd, total_size);\n")
5317 class HandWrittenHandler(CustomHandler
):
5318 """Handler for comands where everything must be written by hand."""
5320 def InitFunction(self
, func
):
5321 """Add or adjust anything type specific for this function."""
5322 CustomHandler
.InitFunction(self
, func
)
5323 func
.can_auto_generate
= False
5325 def NeedsDataTransferFunction(self
, func
):
5326 """Overriden from TypeHandler."""
5327 # If specified explicitly, force the data transfer method.
5328 if func
.GetInfo('data_transfer_methods'):
5332 def WriteStruct(self
, func
, f
):
5333 """Overrriden from TypeHandler."""
5336 def WriteDocs(self
, func
, f
):
5337 """Overrriden from TypeHandler."""
5340 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5341 """Overrriden from TypeHandler."""
5342 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5344 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5345 """Overrriden from TypeHandler."""
5346 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5348 def WriteBucketServiceUnitTest(self
, func
, f
, *extras
):
5349 """Overrriden from TypeHandler."""
5350 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5352 def WriteServiceImplementation(self
, func
, f
):
5353 """Overrriden from TypeHandler."""
5356 def WriteImmediateServiceImplementation(self
, func
, f
):
5357 """Overrriden from TypeHandler."""
5360 def WriteBucketServiceImplementation(self
, func
, f
):
5361 """Overrriden from TypeHandler."""
5364 def WriteImmediateCmdHelper(self
, func
, f
):
5365 """Overrriden from TypeHandler."""
5368 def WriteCmdHelper(self
, func
, f
):
5369 """Overrriden from TypeHandler."""
5372 def WriteFormatTest(self
, func
, f
):
5373 """Overrriden from TypeHandler."""
5374 f
.write("// TODO(gman): Write test for %s\n" % func
.name
)
5376 def WriteImmediateFormatTest(self
, func
, f
):
5377 """Overrriden from TypeHandler."""
5378 f
.write("// TODO(gman): Write test for %s\n" % func
.name
)
5381 class ManualHandler(CustomHandler
):
5382 """Handler for commands who's handlers must be written by hand."""
5384 def InitFunction(self
, func
):
5385 """Overrriden from TypeHandler."""
5386 if (func
.name
== 'CompressedTexImage2DBucket' or
5387 func
.name
== 'CompressedTexImage3DBucket'):
5388 func
.cmd_args
= func
.cmd_args
[:-1]
5389 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5391 CustomHandler
.InitFunction(self
, func
)
5393 def WriteServiceImplementation(self
, func
, f
):
5394 """Overrriden from TypeHandler."""
5397 def WriteBucketServiceImplementation(self
, func
, f
):
5398 """Overrriden from TypeHandler."""
5401 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5402 """Overrriden from TypeHandler."""
5403 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5405 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5406 """Overrriden from TypeHandler."""
5407 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5409 def WriteImmediateServiceImplementation(self
, func
, f
):
5410 """Overrriden from TypeHandler."""
5413 def WriteImmediateFormatTest(self
, func
, f
):
5414 """Overrriden from TypeHandler."""
5415 f
.write("// TODO(gman): Implement test for %s\n" % func
.name
)
5417 def WriteGLES2Implementation(self
, func
, f
):
5418 """Overrriden from TypeHandler."""
5419 if func
.GetInfo('impl_func'):
5420 super(ManualHandler
, self
).WriteGLES2Implementation(func
, f
)
5422 def WriteGLES2ImplementationHeader(self
, func
, f
):
5423 """Overrriden from TypeHandler."""
5424 f
.write("%s %s(%s) override;\n" %
5425 (func
.return_type
, func
.original_name
,
5426 func
.MakeTypedOriginalArgString("")))
5429 def WriteImmediateCmdGetTotalSize(self
, func
, f
):
5430 """Overrriden from TypeHandler."""
5431 # TODO(gman): Move this data to _FUNCTION_INFO?
5432 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, f
)
5435 class DataHandler(TypeHandler
):
5436 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5437 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5439 def InitFunction(self
, func
):
5440 """Overrriden from TypeHandler."""
5441 if (func
.name
== 'CompressedTexSubImage2DBucket' or
5442 func
.name
== 'CompressedTexSubImage3DBucket'):
5443 func
.cmd_args
= func
.cmd_args
[:-1]
5444 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5446 def WriteGetDataSizeCode(self
, func
, f
):
5447 """Overrriden from TypeHandler."""
5448 # TODO(gman): Move this data to _FUNCTION_INFO?
5450 if name
.endswith("Immediate"):
5452 if name
== 'BufferData' or name
== 'BufferSubData':
5453 f
.write(" uint32_t data_size = size;\n")
5454 elif (name
== 'CompressedTexImage2D' or
5455 name
== 'CompressedTexSubImage2D' or
5456 name
== 'CompressedTexImage3D' or
5457 name
== 'CompressedTexSubImage3D'):
5458 f
.write(" uint32_t data_size = imageSize;\n")
5459 elif (name
== 'CompressedTexSubImage2DBucket' or
5460 name
== 'CompressedTexSubImage3DBucket'):
5461 f
.write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5462 f
.write(" uint32_t data_size = bucket->size();\n")
5463 f
.write(" GLsizei imageSize = data_size;\n")
5464 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
5465 code
= """ uint32_t data_size;
5466 if (!GLES2Util::ComputeImageDataSize(
5467 width, height, format, type, unpack_alignment_, &data_size)) {
5468 return error::kOutOfBounds;
5474 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5476 def WriteImmediateCmdGetTotalSize(self
, func
, f
):
5477 """Overrriden from TypeHandler."""
5480 def WriteImmediateCmdInit(self
, func
, f
):
5481 """Overrriden from TypeHandler."""
5482 f
.write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5483 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5484 f
.write(" SetHeader(total_size);\n")
5485 args
= func
.GetCmdArgs()
5487 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5491 def WriteImmediateCmdSet(self
, func
, f
):
5492 """Overrriden from TypeHandler."""
5493 copy_args
= func
.MakeCmdArgString("_", False)
5494 f
.write(" void* Set(void* cmd%s) {\n" %
5495 func
.MakeTypedCmdArgString("_", True))
5496 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5497 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5498 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5499 "cmd, total_size);\n")
5503 def WriteImmediateFormatTest(self
, func
, f
):
5504 """Overrriden from TypeHandler."""
5505 # TODO(gman): Remove this exception.
5506 f
.write("// TODO(gman): Implement test for %s\n" % func
.name
)
5509 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5510 """Overrriden from TypeHandler."""
5511 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5513 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5514 """Overrriden from TypeHandler."""
5515 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5517 def WriteBucketServiceImplementation(self
, func
, f
):
5518 """Overrriden from TypeHandler."""
5519 if ((not func
.name
== 'CompressedTexSubImage2DBucket') and
5520 (not func
.name
== 'CompressedTexSubImage3DBucket')):
5521 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, f
)
5524 class BindHandler(TypeHandler
):
5525 """Handler for glBind___ type functions."""
5527 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5528 """Overrriden from TypeHandler."""
5530 if len(func
.GetOriginalArgs()) == 1:
5532 TEST_P(%(test_name)s, %(name)sValidArgs) {
5533 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5534 SpecializedSetup<cmds::%(name)s, 0>(true);
5536 cmd.Init(%(args)s);"""
5539 decoder_->set_unsafe_es3_apis_enabled(true);
5540 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5541 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5542 decoder_->set_unsafe_es3_apis_enabled(false);
5543 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5548 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5549 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5552 if func
.GetInfo("gen_func"):
5554 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5555 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5556 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5557 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5558 SpecializedSetup<cmds::%(name)s, 0>(true);
5560 cmd.Init(kNewClientId);
5561 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5562 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5563 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5566 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5567 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
5568 'gl_gen_func_name': func
.GetInfo("gen_func"),
5572 TEST_P(%(test_name)s, %(name)sValidArgs) {
5573 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5574 SpecializedSetup<cmds::%(name)s, 0>(true);
5576 cmd.Init(%(args)s);"""
5579 decoder_->set_unsafe_es3_apis_enabled(true);
5580 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5581 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5582 decoder_->set_unsafe_es3_apis_enabled(false);
5583 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5588 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5589 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5592 if func
.GetInfo("gen_func"):
5594 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5596 %(gl_func_name)s(%(gl_args_with_new_id)s));
5597 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5598 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5599 SpecializedSetup<cmds::%(name)s, 0>(true);
5601 cmd.Init(%(args_with_new_id)s);"""
5604 decoder_->set_unsafe_es3_apis_enabled(true);
5605 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5606 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5607 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5608 decoder_->set_unsafe_es3_apis_enabled(false);
5609 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5614 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5615 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5616 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5620 gl_args_with_new_id
= []
5621 args_with_new_id
= []
5622 for arg
in func
.GetOriginalArgs():
5623 if hasattr(arg
, 'resource_type'):
5624 gl_args_with_new_id
.append('kNewServiceId')
5625 args_with_new_id
.append('kNewClientId')
5627 gl_args_with_new_id
.append(arg
.GetValidGLArg(func
))
5628 args_with_new_id
.append(arg
.GetValidArg(func
))
5629 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5630 'args_with_new_id': ", ".join(args_with_new_id
),
5631 'gl_args_with_new_id': ", ".join(gl_args_with_new_id
),
5632 'resource_type': func
.GetResourceIdArg().resource_type
,
5633 'gl_gen_func_name': func
.GetInfo("gen_func"),
5637 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5638 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5639 SpecializedSetup<cmds::%(name)s, 0>(false);
5642 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5645 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, *extras
)
5647 def WriteGLES2Implementation(self
, func
, f
):
5648 """Writes the GLES2 Implemention."""
5650 impl_func
= func
.GetInfo('impl_func')
5651 impl_decl
= func
.GetInfo('impl_decl')
5653 if (func
.can_auto_generate
and
5654 (impl_func
== None or impl_func
== True) and
5655 (impl_decl
== None or impl_decl
== True)):
5657 f
.write("%s GLES2Implementation::%s(%s) {\n" %
5658 (func
.return_type
, func
.original_name
,
5659 func
.MakeTypedOriginalArgString("")))
5660 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5661 func
.WriteDestinationInitalizationValidation(f
)
5662 self
.WriteClientGLCallLog(func
, f
)
5663 for arg
in func
.GetOriginalArgs():
5664 arg
.WriteClientSideValidationCode(f
, func
)
5666 code
= """ if (Is%(type)sReservedId(%(id)s)) {
5667 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5670 %(name)sHelper(%(arg_string)s);
5675 name_arg
= func
.GetResourceIdArg()
5678 'arg_string': func
.MakeOriginalArgString(""),
5679 'id': name_arg
.name
,
5680 'type': name_arg
.resource_type
,
5681 'lc_type': name_arg
.resource_type
.lower(),
5684 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
5685 """Overrriden from TypeHandler."""
5686 client_test
= func
.GetInfo('client_test')
5687 if client_test
== False:
5690 TEST_F(GLES2ImplementationTest, %(name)s) {
5695 expected.cmd.Init(%(cmd_args)s);
5697 gl_->%(name)s(%(args)s);
5698 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5699 if not func
.IsUnsafe():
5702 gl_->%(name)s(%(args)s);
5703 EXPECT_TRUE(NoCommandsWritten());"""
5708 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
5711 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
5716 'args': ", ".join(gl_arg_strings
),
5717 'cmd_args': ", ".join(cmd_arg_strings
),
5721 class GENnHandler(TypeHandler
):
5722 """Handler for glGen___ type functions."""
5724 def InitFunction(self
, func
):
5725 """Overrriden from TypeHandler."""
5728 def WriteGetDataSizeCode(self
, func
, f
):
5729 """Overrriden from TypeHandler."""
5730 code
= """ uint32_t data_size;
5731 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5732 return error::kOutOfBounds;
5737 def WriteHandlerImplementation (self
, func
, f
):
5738 """Overrriden from TypeHandler."""
5739 f
.write(" if (!%sHelper(n, %s)) {\n"
5740 " return error::kInvalidArguments;\n"
5742 (func
.name
, func
.GetLastOriginalArg().name
))
5744 def WriteImmediateHandlerImplementation(self
, func
, f
):
5745 """Overrriden from TypeHandler."""
5747 f
.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5748 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5749 return error::kInvalidArguments;
5752 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5753 gl%(func_name)s(n, service_ids.get());
5754 for (GLsizei ii = 0; ii < n; ++ii) {
5755 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5757 """ % { 'func_name': func
.original_name
,
5758 'last_arg_name': func
.GetLastOriginalArg().name
,
5759 'resource_name': func
.GetInfo('resource_type') })
5761 f
.write(" if (!%sHelper(n, %s)) {\n"
5762 " return error::kInvalidArguments;\n"
5764 (func
.original_name
, func
.GetLastOriginalArg().name
))
5766 def WriteGLES2Implementation(self
, func
, f
):
5767 """Overrriden from TypeHandler."""
5768 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
5769 for (GLsizei i = 0; i < n; ++i) {
5770 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5772 });""" % func
.GetOriginalArgs()[1].name
)
5774 'log_code': log_code
,
5775 'return_type': func
.return_type
,
5776 'name': func
.original_name
,
5777 'typed_args': func
.MakeTypedOriginalArgString(""),
5778 'args': func
.MakeOriginalArgString(""),
5779 'resource_types': func
.GetInfo('resource_types'),
5780 'count_name': func
.GetOriginalArgs()[0].name
,
5783 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5785 func
.WriteDestinationInitalizationValidation(f
)
5786 self
.WriteClientGLCallLog(func
, f
)
5787 for arg
in func
.GetOriginalArgs():
5788 arg
.WriteClientSideValidationCode(f
, func
)
5789 not_shared
= func
.GetInfo('not_shared')
5793 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5794 for (GLsizei ii = 0; ii < n; ++ii)
5795 %s[ii] = id_allocator->AllocateID();""" %
5796 (func
.GetInfo('resource_types'), func
.GetOriginalArgs()[1].name
))
5798 alloc_code
= (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5799 MakeIds(this, 0, %(args)s);""" % args
)
5800 args
['alloc_code'] = alloc_code
5802 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5804 %(name)sHelper(%(args)s);
5805 helper_->%(name)sImmediate(%(args)s);
5806 if (share_group_->bind_generates_resource())
5807 helper_->CommandBufferHelper::Flush();
5813 f
.write(code
% args
)
5815 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
5816 """Overrriden from TypeHandler."""
5818 TEST_F(GLES2ImplementationTest, %(name)s) {
5819 GLuint ids[2] = { 0, };
5821 cmds::%(name)sImmediate gen;
5825 expected.gen.Init(arraysize(ids), &ids[0]);
5826 expected.data[0] = k%(types)sStartId;
5827 expected.data[1] = k%(types)sStartId + 1;
5828 gl_->%(name)s(arraysize(ids), &ids[0]);
5829 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5830 EXPECT_EQ(k%(types)sStartId, ids[0]);
5831 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5836 'types': func
.GetInfo('resource_types'),
5839 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5840 """Overrriden from TypeHandler."""
5842 TEST_P(%(test_name)s, %(name)sValidArgs) {
5843 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5844 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5845 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5846 SpecializedSetup<cmds::%(name)s, 0>(true);
5849 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5850 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5854 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5855 EXPECT_EQ(kNewServiceId, service_id)
5860 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5863 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5864 'resource_name': func
.GetInfo('resource_type'),
5867 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5868 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5869 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5870 SpecializedSetup<cmds::%(name)s, 0>(false);
5873 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5876 self
.WriteValidUnitTest(func
, f
, invalid_test
, {
5877 'resource_name': func
.GetInfo('resource_type').lower(),
5880 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5881 """Overrriden from TypeHandler."""
5883 TEST_P(%(test_name)s, %(name)sValidArgs) {
5884 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5885 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5886 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5887 GLuint temp = kNewClientId;
5888 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5891 decoder_->set_unsafe_es3_apis_enabled(true);"""
5893 cmd->Init(1, &temp);
5894 EXPECT_EQ(error::kNoError,
5895 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5896 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5900 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5901 EXPECT_EQ(kNewServiceId, service_id);
5902 decoder_->set_unsafe_es3_apis_enabled(false);
5903 EXPECT_EQ(error::kUnknownCommand,
5904 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5909 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5912 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5913 'resource_name': func
.GetInfo('resource_type'),
5916 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5917 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5918 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5919 SpecializedSetup<cmds::%(name)s, 0>(false);
5920 cmd->Init(1, &client_%(resource_name)s_id_);"""
5923 decoder_->set_unsafe_es3_apis_enabled(true);
5924 EXPECT_EQ(error::kInvalidArguments,
5925 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5926 decoder_->set_unsafe_es3_apis_enabled(false);
5931 EXPECT_EQ(error::kInvalidArguments,
5932 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5935 self
.WriteValidUnitTest(func
, f
, invalid_test
, {
5936 'resource_name': func
.GetInfo('resource_type').lower(),
5939 def WriteImmediateCmdComputeSize(self
, func
, f
):
5940 """Overrriden from TypeHandler."""
5941 f
.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5943 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5946 f
.write(" static uint32_t ComputeSize(GLsizei n) {\n")
5947 f
.write(" return static_cast<uint32_t>(\n")
5948 f
.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5952 def WriteImmediateCmdSetHeader(self
, func
, f
):
5953 """Overrriden from TypeHandler."""
5954 f
.write(" void SetHeader(GLsizei n) {\n")
5955 f
.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5959 def WriteImmediateCmdInit(self
, func
, f
):
5960 """Overrriden from TypeHandler."""
5961 last_arg
= func
.GetLastOriginalArg()
5962 f
.write(" void Init(%s, %s _%s) {\n" %
5963 (func
.MakeTypedCmdArgString("_"),
5964 last_arg
.type, last_arg
.name
))
5965 f
.write(" SetHeader(_n);\n")
5966 args
= func
.GetCmdArgs()
5968 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5969 f
.write(" memcpy(ImmediateDataAddress(this),\n")
5970 f
.write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
5974 def WriteImmediateCmdSet(self
, func
, f
):
5975 """Overrriden from TypeHandler."""
5976 last_arg
= func
.GetLastOriginalArg()
5977 copy_args
= func
.MakeCmdArgString("_", False)
5978 f
.write(" void* Set(void* cmd%s, %s _%s) {\n" %
5979 (func
.MakeTypedCmdArgString("_", True),
5980 last_arg
.type, last_arg
.name
))
5981 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5982 (copy_args
, last_arg
.name
))
5983 f
.write(" const uint32_t size = ComputeSize(_n);\n")
5984 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5989 def WriteImmediateCmdHelper(self
, func
, f
):
5990 """Overrriden from TypeHandler."""
5991 code
= """ void %(name)s(%(typed_args)s) {
5992 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5993 gles2::cmds::%(name)s* c =
5994 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6003 "typed_args": func
.MakeTypedOriginalArgString(""),
6004 "args": func
.MakeOriginalArgString(""),
6007 def WriteImmediateFormatTest(self
, func
, f
):
6008 """Overrriden from TypeHandler."""
6009 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6010 f
.write(" static GLuint ids[] = { 12, 23, 34, };\n")
6011 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6012 (func
.name
, func
.name
))
6013 f
.write(" void* next_cmd = cmd.Set(\n")
6014 f
.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6015 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6017 f
.write(" cmd.header.command);\n")
6018 f
.write(" EXPECT_EQ(sizeof(cmd) +\n")
6019 f
.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6020 f
.write(" cmd.header.size * 4u);\n")
6021 f
.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6022 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
6023 f
.write(" next_cmd, sizeof(cmd) +\n")
6024 f
.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6025 f
.write(" // TODO(gman): Check that ids were inserted;\n")
6030 class CreateHandler(TypeHandler
):
6031 """Handler for glCreate___ type functions."""
6033 def InitFunction(self
, func
):
6034 """Overrriden from TypeHandler."""
6035 func
.AddCmdArg(Argument("client_id", 'uint32_t'))
6037 def __GetResourceType(self
, func
):
6038 if func
.return_type
== "GLsync":
6041 return func
.name
[6:] # Create*
6043 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6044 """Overrriden from TypeHandler."""
6046 TEST_P(%(test_name)s, %(name)sValidArgs) {
6047 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
6048 .WillOnce(Return(%(const_service_id)s));
6049 SpecializedSetup<cmds::%(name)s, 0>(true);
6051 cmd.Init(%(args)s%(comma)skNewClientId);"""
6054 decoder_->set_unsafe_es3_apis_enabled(true);"""
6056 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6057 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6060 %(return_type)s service_id = 0;
6061 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
6062 EXPECT_EQ(%(const_service_id)s, service_id);
6063 decoder_->set_unsafe_es3_apis_enabled(false);
6064 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
6069 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
6074 for arg
in func
.GetOriginalArgs():
6075 if not arg
.IsConstant():
6079 if func
.return_type
== 'GLsync':
6080 id_type_cast
= ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
6081 "<GLsync>(kNewServiceId);\n ")
6082 const_service_id
= "kNewServiceIdGLuint"
6085 const_service_id
= "kNewServiceId"
6086 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6088 'resource_type': self
.__GetResourceType
(func
),
6089 'return_type': func
.return_type
,
6090 'id_type_cast': id_type_cast
,
6091 'const_service_id': const_service_id
,
6094 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6095 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6096 SpecializedSetup<cmds::%(name)s, 0>(false);
6098 cmd.Init(%(args)s%(comma)skNewClientId);
6099 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
6102 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, {
6106 def WriteHandlerImplementation (self
, func
, f
):
6107 """Overrriden from TypeHandler."""
6109 code
= """ uint32_t client_id = c.client_id;
6110 %(return_type)s service_id = 0;
6111 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
6112 return error::kInvalidArguments;
6114 service_id = %(gl_func_name)s(%(gl_args)s);
6116 group_->Add%(resource_name)sId(client_id, service_id);
6120 code
= """ uint32_t client_id = c.client_id;
6121 if (Get%(resource_name)s(client_id)) {
6122 return error::kInvalidArguments;
6124 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
6126 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
6130 'resource_name': self
.__GetResourceType
(func
),
6131 'return_type': func
.return_type
,
6132 'gl_func_name': func
.GetGLFunctionName(),
6133 'gl_args': func
.MakeOriginalArgString(""),
6134 'gl_args_with_comma': func
.MakeOriginalArgString("", True) })
6136 def WriteGLES2Implementation(self
, func
, f
):
6137 """Overrriden from TypeHandler."""
6138 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6139 (func
.return_type
, func
.original_name
,
6140 func
.MakeTypedOriginalArgString("")))
6141 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6142 func
.WriteDestinationInitalizationValidation(f
)
6143 self
.WriteClientGLCallLog(func
, f
)
6144 for arg
in func
.GetOriginalArgs():
6145 arg
.WriteClientSideValidationCode(f
, func
)
6146 f
.write(" GLuint client_id;\n")
6147 if func
.return_type
== "GLsync":
6149 " GetIdHandler(id_namespaces::kSyncs)->\n")
6152 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
6153 f
.write(" MakeIds(this, 0, 1, &client_id);\n")
6154 f
.write(" helper_->%s(%s);\n" %
6155 (func
.name
, func
.MakeCmdArgString("")))
6156 f
.write(' GPU_CLIENT_LOG("returned " << client_id);\n')
6157 f
.write(" CheckGLError();\n")
6158 if func
.return_type
== "GLsync":
6159 f
.write(" return reinterpret_cast<GLsync>(client_id);\n")
6161 f
.write(" return client_id;\n")
6166 class DeleteHandler(TypeHandler
):
6167 """Handler for glDelete___ single resource type functions."""
6169 def WriteServiceImplementation(self
, func
, f
):
6170 """Overrriden from TypeHandler."""
6172 TypeHandler
.WriteServiceImplementation(self
, func
, f
)
6173 # HandleDeleteShader and HandleDeleteProgram are manually written.
6176 def WriteGLES2Implementation(self
, func
, f
):
6177 """Overrriden from TypeHandler."""
6178 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6179 (func
.return_type
, func
.original_name
,
6180 func
.MakeTypedOriginalArgString("")))
6181 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6182 func
.WriteDestinationInitalizationValidation(f
)
6183 self
.WriteClientGLCallLog(func
, f
)
6184 for arg
in func
.GetOriginalArgs():
6185 arg
.WriteClientSideValidationCode(f
, func
)
6187 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
6188 f
.write(" %sHelper(%s);\n" %
6189 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
6190 f
.write(" CheckGLError();\n")
6194 def WriteHandlerImplementation (self
, func
, f
):
6195 """Overrriden from TypeHandler."""
6196 assert len(func
.GetOriginalArgs()) == 1
6197 arg
= func
.GetOriginalArgs()[0]
6199 f
.write(""" %(arg_type)s service_id = 0;
6200 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
6201 glDelete%(resource_type)s(service_id);
6202 group_->Remove%(resource_type)sId(%(arg_name)s);
6205 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
6207 """ % { 'resource_type': func
.GetInfo('resource_type'),
6208 'arg_name': arg
.name
,
6209 'arg_type': arg
.type,
6210 'func_name': func
.original_name
})
6212 f
.write(" %sHelper(%s);\n" % (func
.original_name
, arg
.name
))
6214 class DELnHandler(TypeHandler
):
6215 """Handler for glDelete___ type functions."""
6217 def WriteGetDataSizeCode(self
, func
, f
):
6218 """Overrriden from TypeHandler."""
6219 code
= """ uint32_t data_size;
6220 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6221 return error::kOutOfBounds;
6226 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
6227 """Overrriden from TypeHandler."""
6229 TEST_F(GLES2ImplementationTest, %(name)s) {
6230 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6232 cmds::%(name)sImmediate del;
6236 expected.del.Init(arraysize(ids), &ids[0]);
6237 expected.data[0] = k%(types)sStartId;
6238 expected.data[1] = k%(types)sStartId + 1;
6239 gl_->%(name)s(arraysize(ids), &ids[0]);
6240 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6245 'types': func
.GetInfo('resource_types'),
6248 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6249 """Overrriden from TypeHandler."""
6251 TEST_P(%(test_name)s, %(name)sValidArgs) {
6254 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6256 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6257 SpecializedSetup<cmds::%(name)s, 0>(true);
6260 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6261 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6263 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6266 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6267 'resource_name': func
.GetInfo('resource_type').lower(),
6268 'upper_resource_name': func
.GetInfo('resource_type'),
6271 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6272 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6273 SpecializedSetup<cmds::%(name)s, 0>(false);
6276 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6279 self
.WriteValidUnitTest(func
, f
, invalid_test
, *extras
)
6281 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
6282 """Overrriden from TypeHandler."""
6284 TEST_P(%(test_name)s, %(name)sValidArgs) {
6287 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6289 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6290 SpecializedSetup<cmds::%(name)s, 0>(true);
6291 cmd.Init(1, &client_%(resource_name)s_id_);"""
6294 decoder_->set_unsafe_es3_apis_enabled(true);"""
6296 EXPECT_EQ(error::kNoError,
6297 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6298 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6301 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6302 client_%(resource_name)s_id_, NULL));
6303 decoder_->set_unsafe_es3_apis_enabled(false);
6304 EXPECT_EQ(error::kUnknownCommand,
6305 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6311 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6314 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6315 'resource_name': func
.GetInfo('resource_type').lower(),
6316 'upper_resource_name': func
.GetInfo('resource_type'),
6319 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6320 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6321 SpecializedSetup<cmds::%(name)s, 0>(false);
6322 GLuint temp = kInvalidClientId;
6323 cmd.Init(1, &temp);"""
6326 decoder_->set_unsafe_es3_apis_enabled(true);
6327 EXPECT_EQ(error::kNoError,
6328 ExecuteImmediateCmd(cmd, sizeof(temp)));
6329 decoder_->set_unsafe_es3_apis_enabled(false);
6330 EXPECT_EQ(error::kUnknownCommand,
6331 ExecuteImmediateCmd(cmd, sizeof(temp)));
6336 EXPECT_EQ(error::kNoError,
6337 ExecuteImmediateCmd(cmd, sizeof(temp)));
6340 self
.WriteValidUnitTest(func
, f
, invalid_test
, *extras
)
6342 def WriteHandlerImplementation (self
, func
, f
):
6343 """Overrriden from TypeHandler."""
6344 f
.write(" %sHelper(n, %s);\n" %
6345 (func
.name
, func
.GetLastOriginalArg().name
))
6347 def WriteImmediateHandlerImplementation (self
, func
, f
):
6348 """Overrriden from TypeHandler."""
6350 f
.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6351 GLuint service_id = 0;
6352 if (group_->Get%(resource_type)sServiceId(
6353 %(last_arg_name)s[ii], &service_id)) {
6354 glDelete%(resource_type)ss(1, &service_id);
6355 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6358 """ % { 'resource_type': func
.GetInfo('resource_type'),
6359 'last_arg_name': func
.GetLastOriginalArg().name
})
6361 f
.write(" %sHelper(n, %s);\n" %
6362 (func
.original_name
, func
.GetLastOriginalArg().name
))
6364 def WriteGLES2Implementation(self
, func
, f
):
6365 """Overrriden from TypeHandler."""
6366 impl_decl
= func
.GetInfo('impl_decl')
6367 if impl_decl
== None or impl_decl
== True:
6369 'return_type': func
.return_type
,
6370 'name': func
.original_name
,
6371 'typed_args': func
.MakeTypedOriginalArgString(""),
6372 'args': func
.MakeOriginalArgString(""),
6373 'resource_type': func
.GetInfo('resource_type').lower(),
6374 'count_name': func
.GetOriginalArgs()[0].name
,
6377 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6379 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6380 func
.WriteDestinationInitalizationValidation(f
)
6381 self
.WriteClientGLCallLog(func
, f
)
6382 f
.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6383 for (GLsizei i = 0; i < n; ++i) {
6384 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6387 """ % func
.GetOriginalArgs()[1].name
)
6388 f
.write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6389 for (GLsizei i = 0; i < n; ++i) {
6393 """ % func
.GetOriginalArgs()[1].name
)
6394 for arg
in func
.GetOriginalArgs():
6395 arg
.WriteClientSideValidationCode(f
, func
)
6396 code
= """ %(name)sHelper(%(args)s);
6401 f
.write(code
% args
)
6403 def WriteImmediateCmdComputeSize(self
, func
, f
):
6404 """Overrriden from TypeHandler."""
6405 f
.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6407 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6410 f
.write(" static uint32_t ComputeSize(GLsizei n) {\n")
6411 f
.write(" return static_cast<uint32_t>(\n")
6412 f
.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6416 def WriteImmediateCmdSetHeader(self
, func
, f
):
6417 """Overrriden from TypeHandler."""
6418 f
.write(" void SetHeader(GLsizei n) {\n")
6419 f
.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6423 def WriteImmediateCmdInit(self
, func
, f
):
6424 """Overrriden from TypeHandler."""
6425 last_arg
= func
.GetLastOriginalArg()
6426 f
.write(" void Init(%s, %s _%s) {\n" %
6427 (func
.MakeTypedCmdArgString("_"),
6428 last_arg
.type, last_arg
.name
))
6429 f
.write(" SetHeader(_n);\n")
6430 args
= func
.GetCmdArgs()
6432 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6433 f
.write(" memcpy(ImmediateDataAddress(this),\n")
6434 f
.write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
6438 def WriteImmediateCmdSet(self
, func
, f
):
6439 """Overrriden from TypeHandler."""
6440 last_arg
= func
.GetLastOriginalArg()
6441 copy_args
= func
.MakeCmdArgString("_", False)
6442 f
.write(" void* Set(void* cmd%s, %s _%s) {\n" %
6443 (func
.MakeTypedCmdArgString("_", True),
6444 last_arg
.type, last_arg
.name
))
6445 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6446 (copy_args
, last_arg
.name
))
6447 f
.write(" const uint32_t size = ComputeSize(_n);\n")
6448 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6453 def WriteImmediateCmdHelper(self
, func
, f
):
6454 """Overrriden from TypeHandler."""
6455 code
= """ void %(name)s(%(typed_args)s) {
6456 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6457 gles2::cmds::%(name)s* c =
6458 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6467 "typed_args": func
.MakeTypedOriginalArgString(""),
6468 "args": func
.MakeOriginalArgString(""),
6471 def WriteImmediateFormatTest(self
, func
, f
):
6472 """Overrriden from TypeHandler."""
6473 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6474 f
.write(" static GLuint ids[] = { 12, 23, 34, };\n")
6475 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6476 (func
.name
, func
.name
))
6477 f
.write(" void* next_cmd = cmd.Set(\n")
6478 f
.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6479 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6481 f
.write(" cmd.header.command);\n")
6482 f
.write(" EXPECT_EQ(sizeof(cmd) +\n")
6483 f
.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6484 f
.write(" cmd.header.size * 4u);\n")
6485 f
.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6486 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
6487 f
.write(" next_cmd, sizeof(cmd) +\n")
6488 f
.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6489 f
.write(" // TODO(gman): Check that ids were inserted;\n")
6494 class GETnHandler(TypeHandler
):
6495 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6497 def NeedsDataTransferFunction(self
, func
):
6498 """Overriden from TypeHandler."""
6501 def WriteServiceImplementation(self
, func
, f
):
6502 """Overrriden from TypeHandler."""
6503 self
.WriteServiceHandlerFunctionHeader(func
, f
)
6504 last_arg
= func
.GetLastOriginalArg()
6505 # All except shm_id and shm_offset.
6506 all_but_last_args
= func
.GetCmdArgs()[:-2]
6507 for arg
in all_but_last_args
:
6510 code
= """ typedef cmds::%(func_name)s::Result Result;
6511 GLsizei num_values = 0;
6512 GetNumValuesReturnedForGLGet(pname, &num_values);
6513 Result* result = GetSharedMemoryAs<Result*>(
6514 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6515 Result::ComputeSize(num_values));
6516 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6519 'last_arg_type': last_arg
.type,
6520 'last_arg_name': last_arg
.name
,
6521 'func_name': func
.name
,
6523 func
.WriteHandlerValidation(f
)
6524 code
= """ // Check that the client initialized the result.
6525 if (result->size != 0) {
6526 return error::kInvalidArguments;
6529 shadowed
= func
.GetInfo('shadowed')
6531 f
.write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
6533 func
.WriteHandlerImplementation(f
)
6535 code
= """ result->SetNumResults(num_values);
6536 return error::kNoError;
6540 code
= """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
6541 if (error == GL_NO_ERROR) {
6542 result->SetNumResults(num_values);
6544 return error::kNoError;
6548 f
.write(code
% {'func_name': func
.name
})
6550 def WriteGLES2Implementation(self
, func
, f
):
6551 """Overrriden from TypeHandler."""
6552 impl_decl
= func
.GetInfo('impl_decl')
6553 if impl_decl
== None or impl_decl
== True:
6554 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6555 (func
.return_type
, func
.original_name
,
6556 func
.MakeTypedOriginalArgString("")))
6557 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6558 func
.WriteDestinationInitalizationValidation(f
)
6559 self
.WriteClientGLCallLog(func
, f
)
6560 for arg
in func
.GetOriginalArgs():
6561 arg
.WriteClientSideValidationCode(f
, func
)
6562 all_but_last_args
= func
.GetOriginalArgs()[:-1]
6564 has_length_arg
= False
6565 for arg
in all_but_last_args
:
6566 if arg
.type == 'GLsync':
6567 args
.append('ToGLuint(%s)' % arg
.name
)
6568 elif arg
.name
.endswith('size') and arg
.type == 'GLsizei':
6570 elif arg
.name
== 'length':
6571 has_length_arg
= True
6574 args
.append(arg
.name
)
6575 arg_string
= ", ".join(args
)
6579 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()]))
6580 self
.WriteTraceEvent(func
, f
)
6581 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6584 typedef cmds::%(func_name)s::Result Result;
6585 Result* result = GetResultAs<Result*>();
6589 result->SetNumResults(0);
6590 helper_->%(func_name)s(%(arg_string)s,
6591 GetResultShmId(), GetResultShmOffset());
6593 result->CopyResult(%(last_arg_name)s);
6594 GPU_CLIENT_LOG_CODE_BLOCK({
6595 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6596 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6602 *length = result->GetNumResults();
6609 'func_name': func
.name
,
6610 'arg_string': arg_string
,
6611 'all_arg_string': all_arg_string
,
6612 'last_arg_name': func
.GetLastOriginalArg().name
,
6615 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
6616 """Writes the GLES2 Implemention unit test."""
6618 TEST_F(GLES2ImplementationTest, %(name)s) {
6622 typedef cmds::%(name)s::Result::Type ResultType;
6623 ResultType result = 0;
6625 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6626 sizeof(uint32_t) + sizeof(ResultType));
6627 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6628 EXPECT_CALL(*command_buffer(), OnFlush())
6629 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6630 .RetiresOnSaturation();
6631 gl_->%(name)s(%(args)s, &result);
6632 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6633 EXPECT_EQ(static_cast<ResultType>(1), result);
6636 first_cmd_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func
)
6637 if not first_cmd_arg
:
6640 first_gl_arg
= func
.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6643 cmd_arg_strings
= [first_cmd_arg
]
6644 for arg
in func
.GetCmdArgs()[1:-2]:
6645 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
6646 gl_arg_strings
= [first_gl_arg
]
6647 for arg
in func
.GetOriginalArgs()[1:-1]:
6648 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
6652 'args': ", ".join(gl_arg_strings
),
6653 'cmd_args': ", ".join(cmd_arg_strings
),
6656 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6657 """Overrriden from TypeHandler."""
6659 TEST_P(%(test_name)s, %(name)sValidArgs) {
6660 EXPECT_CALL(*gl_, GetError())
6661 .WillRepeatedly(Return(GL_NO_ERROR));
6662 SpecializedSetup<cmds::%(name)s, 0>(true);
6663 typedef cmds::%(name)s::Result Result;
6664 Result* result = static_cast<Result*>(shared_memory_address_);
6665 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6668 cmd.Init(%(cmd_args)s);"""
6671 decoder_->set_unsafe_es3_apis_enabled(true);"""
6673 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6674 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6676 result->GetNumResults());
6677 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6680 decoder_->set_unsafe_es3_apis_enabled(false);
6681 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6686 cmd_arg_strings
= []
6688 for arg
in func
.GetOriginalArgs()[:-1]:
6689 if arg
.name
== 'length':
6690 gl_arg_value
= 'nullptr'
6691 elif arg
.name
.endswith('size'):
6692 gl_arg_value
= ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6694 elif arg
.type == 'GLsync':
6695 gl_arg_value
= 'reinterpret_cast<GLsync>(kServiceSyncId)'
6697 gl_arg_value
= arg
.GetValidGLArg(func
)
6698 gl_arg_strings
.append(gl_arg_value
)
6699 if arg
.name
== 'pname':
6700 valid_pname
= gl_arg_value
6701 if arg
.name
.endswith('size') or arg
.name
== 'length':
6703 if arg
.type == 'GLsync':
6704 arg_value
= 'client_sync_id_'
6706 arg_value
= arg
.GetValidArg(func
)
6707 cmd_arg_strings
.append(arg_value
)
6708 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
6709 gl_arg_strings
.append("_")
6711 gl_arg_strings
.append("result->GetData()")
6712 cmd_arg_strings
.append("shared_memory_id_")
6713 cmd_arg_strings
.append("shared_memory_offset_")
6715 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6716 'local_gl_args': ", ".join(gl_arg_strings
),
6717 'cmd_args': ", ".join(cmd_arg_strings
),
6718 'valid_pname': valid_pname
,
6721 if not func
.IsUnsafe():
6723 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6724 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6725 SpecializedSetup<cmds::%(name)s, 0>(false);
6726 cmds::%(name)s::Result* result =
6727 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6731 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6732 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6735 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, *extras
)
6737 class ArrayArgTypeHandler(TypeHandler
):
6738 """Base class for type handlers that handle args that are arrays"""
6740 def GetArrayType(self
, func
):
6741 """Returns the type of the element in the element array being PUT to."""
6742 for arg
in func
.GetOriginalArgs():
6744 element_type
= arg
.GetPointedType()
6747 # Special case: array type handler is used for a function that is forwarded
6748 # to the actual array type implementation
6749 element_type
= func
.GetOriginalArgs()[-1].type
6750 assert all(arg
.type == element_type \
6751 for arg
in func
.GetOriginalArgs()[-self
.GetArrayCount(func
):])
6754 def GetArrayCount(self
, func
):
6755 """Returns the count of the elements in the array being PUT to."""
6756 return func
.GetInfo('count')
6758 class PUTHandler(ArrayArgTypeHandler
):
6759 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6761 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6762 """Writes the service unit test for a command."""
6763 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6764 if func
.GetInfo("first_element_only"):
6766 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()
6768 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
6769 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6770 ", ".join(gl_arg_strings
))
6772 TEST_P(%(test_name)s, %(name)sValidArgs) {
6773 SpecializedSetup<cmds::%(name)s, 0>(true);
6776 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6778 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6779 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6783 'data_type': self
.GetArrayType(func
),
6784 'data_value': func
.GetInfo('data_value') or '0',
6785 'expected_call': expected_call
,
6787 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
6790 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6791 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6792 SpecializedSetup<cmds::%(name)s, 0>(false);
6795 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6796 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6799 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, extra
, *extras
)
6801 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
6802 """Writes the service unit test for a command."""
6804 TEST_P(%(test_name)s, %(name)sValidArgs) {
6805 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6806 SpecializedSetup<cmds::%(name)s, 0>(true);
6807 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6808 cmd.Init(%(gl_args)s, &temp[0]);
6811 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6812 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6815 decoder_->set_unsafe_es3_apis_enabled(true);"""
6817 EXPECT_EQ(error::kNoError,
6818 ExecuteImmediateCmd(cmd, sizeof(temp)));
6819 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6822 decoder_->set_unsafe_es3_apis_enabled(false);
6823 EXPECT_EQ(error::kUnknownCommand,
6824 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6829 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6831 gl_any_strings
= ["_"] * len(gl_arg_strings
)
6834 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
6835 'data_type': self
.GetArrayType(func
),
6836 'data_count': self
.GetArrayCount(func
),
6837 'data_value': func
.GetInfo('data_value') or '0',
6838 'gl_args': ", ".join(gl_arg_strings
),
6839 'gl_any_args': ", ".join(gl_any_strings
),
6841 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
6844 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6845 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6848 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6852 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6855 SpecializedSetup<cmds::%(name)s, 0>(false);
6856 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6857 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6860 decoder_->set_unsafe_es3_apis_enabled(true);
6861 EXPECT_EQ(error::%(parse_result)s,
6862 ExecuteImmediateCmd(cmd, sizeof(temp)));
6863 decoder_->set_unsafe_es3_apis_enabled(false);
6868 EXPECT_EQ(error::%(parse_result)s,
6869 ExecuteImmediateCmd(cmd, sizeof(temp)));
6873 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, extra
, *extras
)
6875 def WriteGetDataSizeCode(self
, func
, f
):
6876 """Overrriden from TypeHandler."""
6877 code
= """ uint32_t data_size;
6878 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6879 return error::kOutOfBounds;
6882 f
.write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6883 if func
.IsImmediate():
6884 f
.write(" if (data_size > immediate_data_size) {\n")
6885 f
.write(" return error::kOutOfBounds;\n")
6888 def __NeedsToCalcDataCount(self
, func
):
6889 use_count_func
= func
.GetInfo('use_count_func')
6890 return use_count_func
!= None and use_count_func
!= False
6892 def WriteGLES2Implementation(self
, func
, f
):
6893 """Overrriden from TypeHandler."""
6894 impl_func
= func
.GetInfo('impl_func')
6895 if (impl_func
!= None and impl_func
!= True):
6897 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6898 (func
.return_type
, func
.original_name
,
6899 func
.MakeTypedOriginalArgString("")))
6900 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6901 func
.WriteDestinationInitalizationValidation(f
)
6902 self
.WriteClientGLCallLog(func
, f
)
6904 if self
.__NeedsToCalcDataCount
(func
):
6905 f
.write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6906 (func
.name
, func
.GetOriginalArgs()[0].name
))
6907 f
.write(" DCHECK_LE(count, %du);\n" % self
.GetArrayCount(func
))
6909 f
.write(" size_t count = %d;" % self
.GetArrayCount(func
))
6910 f
.write(" for (size_t ii = 0; ii < count; ++ii)\n")
6911 f
.write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6912 func
.GetLastOriginalArg().name
)
6913 for arg
in func
.GetOriginalArgs():
6914 arg
.WriteClientSideValidationCode(f
, func
)
6915 f
.write(" helper_->%sImmediate(%s);\n" %
6916 (func
.name
, func
.MakeOriginalArgString("")))
6917 f
.write(" CheckGLError();\n")
6921 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
6922 """Writes the GLES2 Implemention unit test."""
6923 client_test
= func
.GetInfo('client_test')
6924 if (client_test
!= None and client_test
!= True):
6927 TEST_F(GLES2ImplementationTest, %(name)s) {
6928 %(type)s data[%(count)d] = {0};
6930 cmds::%(name)sImmediate cmd;
6931 %(type)s data[%(count)d];
6934 for (int jj = 0; jj < %(count)d; ++jj) {
6935 data[jj] = static_cast<%(type)s>(jj);
6938 expected.cmd.Init(%(cmd_args)s, &data[0]);
6939 gl_->%(name)s(%(args)s, &data[0]);
6940 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6944 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
6947 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6952 'type': self
.GetArrayType(func
),
6953 'count': self
.GetArrayCount(func
),
6954 'args': ", ".join(gl_arg_strings
),
6955 'cmd_args': ", ".join(cmd_arg_strings
),
6958 def WriteImmediateCmdComputeSize(self
, func
, f
):
6959 """Overrriden from TypeHandler."""
6960 f
.write(" static uint32_t ComputeDataSize() {\n")
6961 f
.write(" return static_cast<uint32_t>(\n")
6962 f
.write(" sizeof(%s) * %d);\n" %
6963 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6966 if self
.__NeedsToCalcDataCount
(func
):
6967 f
.write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6968 (func
.GetOriginalArgs()[0].type,
6969 func
.GetOriginalArgs()[0].name
))
6970 f
.write(" return static_cast<uint32_t>(\n")
6971 f
.write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6972 (self
.GetArrayType(func
), func
.original_name
,
6973 func
.GetOriginalArgs()[0].name
))
6976 f
.write(" static uint32_t ComputeSize() {\n")
6977 f
.write(" return static_cast<uint32_t>(\n")
6979 " sizeof(ValueType) + ComputeDataSize());\n")
6983 def WriteImmediateCmdSetHeader(self
, func
, f
):
6984 """Overrriden from TypeHandler."""
6985 f
.write(" void SetHeader() {\n")
6987 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6991 def WriteImmediateCmdInit(self
, func
, f
):
6992 """Overrriden from TypeHandler."""
6993 last_arg
= func
.GetLastOriginalArg()
6994 f
.write(" void Init(%s, %s _%s) {\n" %
6995 (func
.MakeTypedCmdArgString("_"),
6996 last_arg
.type, last_arg
.name
))
6997 f
.write(" SetHeader();\n")
6998 args
= func
.GetCmdArgs()
7000 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
7001 f
.write(" memcpy(ImmediateDataAddress(this),\n")
7002 if self
.__NeedsToCalcDataCount
(func
):
7003 f
.write(" _%s, ComputeEffectiveDataSize(%s));" %
7004 (last_arg
.name
, func
.GetOriginalArgs()[0].name
))
7006 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
7007 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
7008 ComputeEffectiveDataSize(%(arg)s);
7009 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
7010 """ % { 'arg': func
.GetOriginalArgs()[0].name
, })
7012 f
.write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
7016 def WriteImmediateCmdSet(self
, func
, f
):
7017 """Overrriden from TypeHandler."""
7018 last_arg
= func
.GetLastOriginalArg()
7019 copy_args
= func
.MakeCmdArgString("_", False)
7020 f
.write(" void* Set(void* cmd%s, %s _%s) {\n" %
7021 (func
.MakeTypedCmdArgString("_", True),
7022 last_arg
.type, last_arg
.name
))
7023 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
7024 (copy_args
, last_arg
.name
))
7025 f
.write(" const uint32_t size = ComputeSize();\n")
7026 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7031 def WriteImmediateCmdHelper(self
, func
, f
):
7032 """Overrriden from TypeHandler."""
7033 code
= """ void %(name)s(%(typed_args)s) {
7034 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
7035 gles2::cmds::%(name)s* c =
7036 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7045 "typed_args": func
.MakeTypedOriginalArgString(""),
7046 "args": func
.MakeOriginalArgString(""),
7049 def WriteImmediateFormatTest(self
, func
, f
):
7050 """Overrriden from TypeHandler."""
7051 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
7052 f
.write(" const int kSomeBaseValueToTestWith = 51;\n")
7053 f
.write(" static %s data[] = {\n" % self
.GetArrayType(func
))
7054 for v
in range(0, self
.GetArrayCount(func
)):
7055 f
.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7056 (self
.GetArrayType(func
), v
))
7058 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7059 (func
.name
, func
.name
))
7060 f
.write(" void* next_cmd = cmd.Set(\n")
7062 args
= func
.GetCmdArgs()
7063 for value
, arg
in enumerate(args
):
7064 f
.write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
7065 f
.write(",\n data);\n")
7066 args
= func
.GetCmdArgs()
7067 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
7069 f
.write(" cmd.header.command);\n")
7070 f
.write(" EXPECT_EQ(sizeof(cmd) +\n")
7071 f
.write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
7072 f
.write(" cmd.header.size * 4u);\n")
7073 for value
, arg
in enumerate(args
):
7074 f
.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7075 (arg
.type, value
+ 11, arg
.name
))
7076 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7077 f
.write(" next_cmd, sizeof(cmd) +\n")
7078 f
.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7079 f
.write(" // TODO(gman): Check that data was inserted;\n")
7084 class PUTnHandler(ArrayArgTypeHandler
):
7085 """Handler for PUTn 'glUniform__v' type functions."""
7087 def WriteServiceUnitTest(self
, func
, f
, *extras
):
7088 """Overridden from TypeHandler."""
7089 ArrayArgTypeHandler
.WriteServiceUnitTest(self
, func
, f
, *extras
)
7092 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
7093 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7094 SpecializedSetup<cmds::%(name)s, 0>(true);
7097 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7098 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7103 for count
, arg
in enumerate(func
.GetOriginalArgs()):
7104 # hardcoded to match unit tests.
7106 # the location of the second element of the 2nd uniform.
7107 # defined in GLES2DecoderBase::SetupShaderForUniform
7108 gl_arg_strings
.append("3")
7109 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
7111 # the number of elements that gl will be called with.
7112 gl_arg_strings
.append("3")
7113 # the number of elements requested in the command.
7114 arg_strings
.append("5")
7116 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
7117 if not arg
.IsConstant():
7118 arg_strings
.append(arg
.GetValidArg(func
))
7120 'gl_args': ", ".join(gl_arg_strings
),
7121 'args': ", ".join(arg_strings
),
7123 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
7125 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
7126 """Overridden from TypeHandler."""
7128 TEST_P(%(test_name)s, %(name)sValidArgs) {
7129 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7132 %(gl_func_name)s(%(gl_args)s,
7133 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
7134 SpecializedSetup<cmds::%(name)s, 0>(true);
7135 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7136 cmd.Init(%(args)s, &temp[0]);"""
7139 decoder_->set_unsafe_es3_apis_enabled(true);"""
7141 EXPECT_EQ(error::kNoError,
7142 ExecuteImmediateCmd(cmd, sizeof(temp)));
7143 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7146 decoder_->set_unsafe_es3_apis_enabled(false);
7147 EXPECT_EQ(error::kUnknownCommand,
7148 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
7155 for arg
in func
.GetOriginalArgs()[0:-1]:
7156 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
7157 gl_any_strings
.append("_")
7158 if not arg
.IsConstant():
7159 arg_strings
.append(arg
.GetValidArg(func
))
7161 'data_type': self
.GetArrayType(func
),
7162 'data_count': self
.GetArrayCount(func
),
7163 'args': ", ".join(arg_strings
),
7164 'gl_args': ", ".join(gl_arg_strings
),
7165 'gl_any_args': ", ".join(gl_any_strings
),
7167 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
7170 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7171 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7172 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
7173 SpecializedSetup<cmds::%(name)s, 0>(false);
7174 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7175 cmd.Init(%(all_but_last_args)s, &temp[0]);
7176 EXPECT_EQ(error::%(parse_result)s,
7177 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
7180 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, extra
, *extras
)
7182 def WriteGetDataSizeCode(self
, func
, f
):
7183 """Overrriden from TypeHandler."""
7184 code
= """ uint32_t data_size;
7185 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
7186 return error::kOutOfBounds;
7189 f
.write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7190 if func
.IsImmediate():
7191 f
.write(" if (data_size > immediate_data_size) {\n")
7192 f
.write(" return error::kOutOfBounds;\n")
7195 def WriteGLES2Implementation(self
, func
, f
):
7196 """Overrriden from TypeHandler."""
7197 f
.write("%s GLES2Implementation::%s(%s) {\n" %
7198 (func
.return_type
, func
.original_name
,
7199 func
.MakeTypedOriginalArgString("")))
7200 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7201 func
.WriteDestinationInitalizationValidation(f
)
7202 self
.WriteClientGLCallLog(func
, f
)
7203 last_pointer_name
= func
.GetLastOriginalPointerArg().name
7204 f
.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7205 for (GLsizei i = 0; i < count; ++i) {
7207 values_str
= ' << ", " << '.join(
7208 ["%s[%d + i * %d]" % (
7209 last_pointer_name
, ndx
, self
.GetArrayCount(func
)) for ndx
in range(
7210 0, self
.GetArrayCount(func
))])
7211 f
.write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
7212 f
.write(" }\n });\n")
7213 for arg
in func
.GetOriginalArgs():
7214 arg
.WriteClientSideValidationCode(f
, func
)
7215 f
.write(" helper_->%sImmediate(%s);\n" %
7216 (func
.name
, func
.MakeInitString("")))
7217 f
.write(" CheckGLError();\n")
7221 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
7222 """Writes the GLES2 Implemention unit test."""
7224 TEST_F(GLES2ImplementationTest, %(name)s) {
7225 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7227 cmds::%(name)sImmediate cmd;
7228 %(type)s data[%(count_param)d][%(count)d];
7232 for (int ii = 0; ii < %(count_param)d; ++ii) {
7233 for (int jj = 0; jj < %(count)d; ++jj) {
7234 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7237 expected.cmd.Init(%(cmd_args)s);
7238 gl_->%(name)s(%(args)s);
7239 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7242 cmd_arg_strings
= []
7243 for arg
in func
.GetCmdArgs():
7244 if arg
.name
.endswith("_shm_id"):
7245 cmd_arg_strings
.append("&data[0][0]")
7246 elif arg
.name
.endswith("_shm_offset"):
7249 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
7252 for arg
in func
.GetOriginalArgs():
7254 valid_value
= "&data[0][0]"
7256 valid_value
= arg
.GetValidClientSideArg(func
)
7257 gl_arg_strings
.append(valid_value
)
7258 if arg
.name
== "count":
7259 count_param
= int(valid_value
)
7262 'type': self
.GetArrayType(func
),
7263 'count': self
.GetArrayCount(func
),
7264 'args': ", ".join(gl_arg_strings
),
7265 'cmd_args': ", ".join(cmd_arg_strings
),
7266 'count_param': count_param
,
7269 # Test constants for invalid values, as they are not tested by the
7272 arg
for arg
in func
.GetOriginalArgs()[0:-1] if arg
.IsConstant()
7278 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7279 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7280 for (int ii = 0; ii < %(count_param)d; ++ii) {
7281 for (int jj = 0; jj < %(count)d; ++jj) {
7282 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7285 gl_->%(name)s(%(args)s);
7286 EXPECT_TRUE(NoCommandsWritten());
7287 EXPECT_EQ(%(gl_error)s, CheckError());
7290 for invalid_arg
in constants
:
7292 invalid
= invalid_arg
.GetInvalidArg(func
)
7293 for arg
in func
.GetOriginalArgs():
7294 if arg
is invalid_arg
:
7295 gl_arg_strings
.append(invalid
[0])
7296 elif arg
.IsPointer():
7297 gl_arg_strings
.append("&data[0][0]")
7299 valid_value
= arg
.GetValidClientSideArg(func
)
7300 gl_arg_strings
.append(valid_value
)
7301 if arg
.name
== "count":
7302 count_param
= int(valid_value
)
7306 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
7307 'type': self
.GetArrayType(func
),
7308 'count': self
.GetArrayCount(func
),
7309 'args': ", ".join(gl_arg_strings
),
7310 'gl_error': invalid
[2],
7311 'count_param': count_param
,
7315 def WriteImmediateCmdComputeSize(self
, func
, f
):
7316 """Overrriden from TypeHandler."""
7317 f
.write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7318 f
.write(" return static_cast<uint32_t>(\n")
7319 f
.write(" sizeof(%s) * %d * count); // NOLINT\n" %
7320 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7323 f
.write(" static uint32_t ComputeSize(GLsizei count) {\n")
7324 f
.write(" return static_cast<uint32_t>(\n")
7326 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7330 def WriteImmediateCmdSetHeader(self
, func
, f
):
7331 """Overrriden from TypeHandler."""
7332 f
.write(" void SetHeader(GLsizei count) {\n")
7334 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7338 def WriteImmediateCmdInit(self
, func
, f
):
7339 """Overrriden from TypeHandler."""
7340 f
.write(" void Init(%s) {\n" %
7341 func
.MakeTypedInitString("_"))
7342 f
.write(" SetHeader(_count);\n")
7343 args
= func
.GetCmdArgs()
7345 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
7346 f
.write(" memcpy(ImmediateDataAddress(this),\n")
7347 pointer_arg
= func
.GetLastOriginalPointerArg()
7348 f
.write(" _%s, ComputeDataSize(_count));\n" % pointer_arg
.name
)
7352 def WriteImmediateCmdSet(self
, func
, f
):
7353 """Overrriden from TypeHandler."""
7354 f
.write(" void* Set(void* cmd%s) {\n" %
7355 func
.MakeTypedInitString("_", True))
7356 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7357 func
.MakeInitString("_"))
7358 f
.write(" const uint32_t size = ComputeSize(_count);\n")
7359 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7364 def WriteImmediateCmdHelper(self
, func
, f
):
7365 """Overrriden from TypeHandler."""
7366 code
= """ void %(name)s(%(typed_args)s) {
7367 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7368 gles2::cmds::%(name)s* c =
7369 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7378 "typed_args": func
.MakeTypedInitString(""),
7379 "args": func
.MakeInitString("")
7382 def WriteImmediateFormatTest(self
, func
, f
):
7383 """Overrriden from TypeHandler."""
7384 args
= func
.GetOriginalArgs()
7387 if arg
.name
== "count":
7388 count_param
= int(arg
.GetValidClientSideCmdArg(func
))
7389 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
7390 f
.write(" const int kSomeBaseValueToTestWith = 51;\n")
7391 f
.write(" static %s data[] = {\n" % self
.GetArrayType(func
))
7392 for v
in range(0, self
.GetArrayCount(func
) * count_param
):
7393 f
.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7394 (self
.GetArrayType(func
), v
))
7396 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7397 (func
.name
, func
.name
))
7398 f
.write(" const GLsizei kNumElements = %d;\n" % count_param
)
7399 f
.write(" const size_t kExpectedCmdSize =\n")
7400 f
.write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7401 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7402 f
.write(" void* next_cmd = cmd.Set(\n")
7404 for value
, arg
in enumerate(args
):
7407 elif arg
.IsConstant():
7410 f
.write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
7412 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7414 f
.write(" cmd.header.command);\n")
7415 f
.write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7416 for value
, arg
in enumerate(args
):
7417 if arg
.IsPointer() or arg
.IsConstant():
7419 f
.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7420 (arg
.type, value
+ 1, arg
.name
))
7421 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7422 f
.write(" next_cmd, sizeof(cmd) +\n")
7423 f
.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7424 f
.write(" // TODO(gman): Check that data was inserted;\n")
7428 class PUTSTRHandler(ArrayArgTypeHandler
):
7429 """Handler for functions that pass a string array."""
7431 def __GetDataArg(self
, func
):
7432 """Return the argument that points to the 2D char arrays"""
7433 for arg
in func
.GetOriginalArgs():
7434 if arg
.IsPointer2D():
7438 def __GetLengthArg(self
, func
):
7439 """Return the argument that holds length for each char array"""
7440 for arg
in func
.GetOriginalArgs():
7441 if arg
.IsPointer() and not arg
.IsPointer2D():
7445 def WriteGLES2Implementation(self
, func
, f
):
7446 """Overrriden from TypeHandler."""
7447 f
.write("%s GLES2Implementation::%s(%s) {\n" %
7448 (func
.return_type
, func
.original_name
,
7449 func
.MakeTypedOriginalArgString("")))
7450 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7451 func
.WriteDestinationInitalizationValidation(f
)
7452 self
.WriteClientGLCallLog(func
, f
)
7453 data_arg
= self
.__GetDataArg
(func
)
7454 length_arg
= self
.__GetLengthArg
(func
)
7455 log_code_block
= """ GPU_CLIENT_LOG_CODE_BLOCK({
7456 for (GLsizei ii = 0; ii < count; ++ii) {
7457 if (%(data)s[ii]) {"""
7458 if length_arg
== None:
7459 log_code_block
+= """
7460 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7462 log_code_block
+= """
7463 if (%(length)s && %(length)s[ii] >= 0) {
7464 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7465 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7467 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7469 log_code_block
+= """
7471 GPU_CLIENT_LOG(" " << ii << ": NULL");
7476 f
.write(log_code_block
% {
7477 'data': data_arg
.name
,
7478 'length': length_arg
.name
if not length_arg
== None else ''
7480 for arg
in func
.GetOriginalArgs():
7481 arg
.WriteClientSideValidationCode(f
, func
)
7484 for arg
in func
.GetOriginalArgs():
7485 if arg
.name
== 'count' or arg
== self
.__GetLengthArg
(func
):
7487 if arg
== self
.__GetDataArg
(func
):
7488 bucket_args
.append('kResultBucketId')
7490 bucket_args
.append(arg
.name
)
7492 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7495 helper_->%(func_name)sBucket(%(bucket_args)s);
7496 helper_->SetBucketSize(kResultBucketId, 0);
7501 f
.write(code_block
% {
7502 'data': data_arg
.name
,
7503 'length': length_arg
.name
if not length_arg
== None else 'NULL',
7504 'func_name': func
.name
,
7505 'bucket_args': ', '.join(bucket_args
),
7508 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
7509 """Overrriden from TypeHandler."""
7511 TEST_F(GLES2ImplementationTest, %(name)s) {
7512 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7513 const char* kString1 = "happy";
7514 const char* kString2 = "ending";
7515 const size_t kString1Size = ::strlen(kString1) + 1;
7516 const size_t kString2Size = ::strlen(kString2) + 1;
7517 const size_t kHeaderSize = sizeof(GLint) * 3;
7518 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7519 const size_t kPaddedHeaderSize =
7520 transfer_buffer_->RoundToAlignment(kHeaderSize);
7521 const size_t kPaddedString1Size =
7522 transfer_buffer_->RoundToAlignment(kString1Size);
7523 const size_t kPaddedString2Size =
7524 transfer_buffer_->RoundToAlignment(kString2Size);
7526 cmd::SetBucketSize set_bucket_size;
7527 cmd::SetBucketData set_bucket_header;
7528 cmd::SetToken set_token1;
7529 cmd::SetBucketData set_bucket_data1;
7530 cmd::SetToken set_token2;
7531 cmd::SetBucketData set_bucket_data2;
7532 cmd::SetToken set_token3;
7533 cmds::%(name)sBucket cmd_bucket;
7534 cmd::SetBucketSize clear_bucket_size;
7537 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7538 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7539 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7542 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7543 expected.set_bucket_header.Init(
7544 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7545 expected.set_token1.Init(GetNextToken());
7546 expected.set_bucket_data1.Init(
7547 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7548 expected.set_token2.Init(GetNextToken());
7549 expected.set_bucket_data2.Init(
7550 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7552 expected.set_token3.Init(GetNextToken());
7553 expected.cmd_bucket.Init(%(bucket_args)s);
7554 expected.clear_bucket_size.Init(kBucketId, 0);
7555 const char* kStrings[] = { kString1, kString2 };
7556 gl_->%(name)s(%(gl_args)s);
7557 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7562 for arg
in func
.GetOriginalArgs():
7563 if arg
== self
.__GetDataArg
(func
):
7564 gl_args
.append('kStrings')
7565 bucket_args
.append('kBucketId')
7566 elif arg
== self
.__GetLengthArg
(func
):
7567 gl_args
.append('NULL')
7568 elif arg
.name
== 'count':
7571 gl_args
.append(arg
.GetValidClientSideArg(func
))
7572 bucket_args
.append(arg
.GetValidClientSideArg(func
))
7575 'gl_args': ", ".join(gl_args
),
7576 'bucket_args': ", ".join(bucket_args
),
7579 if self
.__GetLengthArg
(func
) == None:
7582 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7583 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7584 const char* kString = "foobar******";
7585 const size_t kStringSize = 6; // We only need "foobar".
7586 const size_t kHeaderSize = sizeof(GLint) * 2;
7587 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7588 const size_t kPaddedHeaderSize =
7589 transfer_buffer_->RoundToAlignment(kHeaderSize);
7590 const size_t kPaddedStringSize =
7591 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7593 cmd::SetBucketSize set_bucket_size;
7594 cmd::SetBucketData set_bucket_header;
7595 cmd::SetToken set_token1;
7596 cmd::SetBucketData set_bucket_data;
7597 cmd::SetToken set_token2;
7598 cmds::ShaderSourceBucket shader_source_bucket;
7599 cmd::SetBucketSize clear_bucket_size;
7602 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7603 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7606 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7607 expected.set_bucket_header.Init(
7608 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7609 expected.set_token1.Init(GetNextToken());
7610 expected.set_bucket_data.Init(
7611 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7612 expected.set_token2.Init(GetNextToken());
7613 expected.shader_source_bucket.Init(%(bucket_args)s);
7614 expected.clear_bucket_size.Init(kBucketId, 0);
7615 const char* kStrings[] = { kString };
7616 const GLint kLength[] = { kStringSize };
7617 gl_->%(name)s(%(gl_args)s);
7618 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7622 for arg
in func
.GetOriginalArgs():
7623 if arg
== self
.__GetDataArg
(func
):
7624 gl_args
.append('kStrings')
7625 elif arg
== self
.__GetLengthArg
(func
):
7626 gl_args
.append('kLength')
7627 elif arg
.name
== 'count':
7630 gl_args
.append(arg
.GetValidClientSideArg(func
))
7633 'gl_args': ", ".join(gl_args
),
7634 'bucket_args': ", ".join(bucket_args
),
7637 def WriteBucketServiceUnitTest(self
, func
, f
, *extras
):
7638 """Overrriden from TypeHandler."""
7640 cmd_args_with_invalid_id
= []
7642 for index
, arg
in enumerate(func
.GetOriginalArgs()):
7643 if arg
== self
.__GetLengthArg
(func
):
7645 elif arg
.name
== 'count':
7647 elif arg
== self
.__GetDataArg
(func
):
7648 cmd_args
.append('kBucketId')
7649 cmd_args_with_invalid_id
.append('kBucketId')
7651 elif index
== 0: # Resource ID arg
7652 cmd_args
.append(arg
.GetValidArg(func
))
7653 cmd_args_with_invalid_id
.append('kInvalidClientId')
7654 gl_args
.append(arg
.GetValidGLArg(func
))
7656 cmd_args
.append(arg
.GetValidArg(func
))
7657 cmd_args_with_invalid_id
.append(arg
.GetValidArg(func
))
7658 gl_args
.append(arg
.GetValidGLArg(func
))
7661 TEST_P(%(test_name)s, %(name)sValidArgs) {
7662 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7663 const uint32 kBucketId = 123;
7664 const char kSource0[] = "hello";
7665 const char* kSource[] = { kSource0 };
7666 const char kValidStrEnd = 0;
7667 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7669 cmd.Init(%(cmd_args)s);
7670 decoder_->set_unsafe_es3_apis_enabled(true);
7671 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7674 decoder_->set_unsafe_es3_apis_enabled(false);
7675 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7680 self
.WriteValidUnitTest(func
, f
, test
, {
7681 'cmd_args': ", ".join(cmd_args
),
7682 'gl_args': ", ".join(gl_args
),
7686 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7687 const uint32 kBucketId = 123;
7688 const char kSource0[] = "hello";
7689 const char* kSource[] = { kSource0 };
7690 const char kValidStrEnd = 0;
7691 decoder_->set_unsafe_es3_apis_enabled(true);
7694 cmd.Init(%(cmd_args)s);
7695 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7696 // Test invalid client.
7697 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7698 cmd.Init(%(cmd_args_with_invalid_id)s);
7699 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7700 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7703 self
.WriteValidUnitTest(func
, f
, test
, {
7704 'cmd_args': ", ".join(cmd_args
),
7705 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id
),
7709 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7710 const uint32 kBucketId = 123;
7711 const char kSource0[] = "hello";
7712 const char* kSource[] = { kSource0 };
7713 const char kValidStrEnd = 0;
7714 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7715 const GLsizei kTests[] = {
7718 std::numeric_limits<GLsizei>::max(),
7721 decoder_->set_unsafe_es3_apis_enabled(true);
7722 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7723 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7725 cmd.Init(%(cmd_args)s);
7726 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7730 self
.WriteValidUnitTest(func
, f
, test
, {
7731 'cmd_args': ", ".join(cmd_args
),
7735 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7736 const uint32 kBucketId = 123;
7737 const char kSource0[] = "hello";
7738 const char* kSource[] = { kSource0 };
7739 const char kInvalidStrEnd = '*';
7740 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7742 cmd.Init(%(cmd_args)s);
7743 decoder_->set_unsafe_es3_apis_enabled(true);
7744 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7747 self
.WriteValidUnitTest(func
, f
, test
, {
7748 'cmd_args': ", ".join(cmd_args
),
7752 class PUTXnHandler(ArrayArgTypeHandler
):
7753 """Handler for glUniform?f functions."""
7755 def WriteHandlerImplementation(self
, func
, f
):
7756 """Overrriden from TypeHandler."""
7757 code
= """ %(type)s temp[%(count)s] = { %(values)s};
7758 Do%(name)sv(%(location)s, 1, &temp[0]);
7761 args
= func
.GetOriginalArgs()
7762 count
= int(self
.GetArrayCount(func
))
7763 num_args
= len(args
)
7764 for ii
in range(count
):
7765 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
7769 'count': self
.GetArrayCount(func
),
7770 'type': self
.GetArrayType(func
),
7771 'location': args
[0].name
,
7772 'args': func
.MakeOriginalArgString(""),
7776 def WriteServiceUnitTest(self
, func
, f
, *extras
):
7777 """Overrriden from TypeHandler."""
7779 TEST_P(%(test_name)s, %(name)sValidArgs) {
7780 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7781 SpecializedSetup<cmds::%(name)s, 0>(true);
7783 cmd.Init(%(args)s);"""
7786 decoder_->set_unsafe_es3_apis_enabled(true);"""
7788 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7789 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7792 decoder_->set_unsafe_es3_apis_enabled(false);
7793 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7797 args
= func
.GetOriginalArgs()
7798 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
)
7799 self
.WriteValidUnitTest(func
, f
, valid_test
, {
7801 'count': self
.GetArrayCount(func
),
7802 'local_args': local_args
,
7806 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7807 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7808 SpecializedSetup<cmds::%(name)s, 0>(false);
7811 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7814 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, {
7815 'name': func
.GetInfo('name'),
7816 'count': self
.GetArrayCount(func
),
7820 class GLcharHandler(CustomHandler
):
7821 """Handler for functions that pass a single string ."""
7823 def WriteImmediateCmdComputeSize(self
, func
, f
):
7824 """Overrriden from TypeHandler."""
7825 f
.write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7826 f
.write(" return static_cast<uint32_t>(\n")
7827 f
.write(" sizeof(ValueType) + data_size); // NOLINT\n")
7830 def WriteImmediateCmdSetHeader(self
, func
, f
):
7831 """Overrriden from TypeHandler."""
7833 void SetHeader(uint32_t data_size) {
7834 header.SetCmdBySize<ValueType>(data_size);
7839 def WriteImmediateCmdInit(self
, func
, f
):
7840 """Overrriden from TypeHandler."""
7841 last_arg
= func
.GetLastOriginalArg()
7842 args
= func
.GetCmdArgs()
7845 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
7847 void Init(%(typed_args)s, uint32_t _data_size) {
7848 SetHeader(_data_size);
7850 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7855 "typed_args": func
.MakeTypedArgString("_"),
7856 "set_code": "\n".join(set_code
),
7857 "last_arg": last_arg
.name
7860 def WriteImmediateCmdSet(self
, func
, f
):
7861 """Overrriden from TypeHandler."""
7862 last_arg
= func
.GetLastOriginalArg()
7863 f
.write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7864 func
.MakeTypedCmdArgString("_", True))
7865 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7866 func
.MakeCmdArgString("_"))
7867 f
.write(" return NextImmediateCmdAddress<ValueType>("
7868 "cmd, _data_size);\n")
7872 def WriteImmediateCmdHelper(self
, func
, f
):
7873 """Overrriden from TypeHandler."""
7874 code
= """ void %(name)s(%(typed_args)s) {
7875 const uint32_t data_size = strlen(name);
7876 gles2::cmds::%(name)s* c =
7877 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7879 c->Init(%(args)s, data_size);
7886 "typed_args": func
.MakeTypedOriginalArgString(""),
7887 "args": func
.MakeOriginalArgString(""),
7891 def WriteImmediateFormatTest(self
, func
, f
):
7892 """Overrriden from TypeHandler."""
7895 all_but_last_arg
= func
.GetCmdArgs()[:-1]
7896 for value
, arg
in enumerate(all_but_last_arg
):
7897 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
7898 for value
, arg
in enumerate(all_but_last_arg
):
7899 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7900 (arg
.type, value
+ 11, arg
.name
))
7902 TEST_F(GLES2FormatTest, %(func_name)s) {
7903 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7904 static const char* const test_str = \"test string\";
7905 void* next_cmd = cmd.Set(
7910 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7911 cmd.header.command);
7912 EXPECT_EQ(sizeof(cmd) +
7913 RoundSizeToMultipleOfEntries(strlen(test_str)),
7914 cmd.header.size * 4u);
7915 EXPECT_EQ(static_cast<char*>(next_cmd),
7916 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7917 RoundSizeToMultipleOfEntries(strlen(test_str)));
7919 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7920 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7923 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7924 sizeof(cmd) + strlen(test_str));
7929 'func_name': func
.name
,
7930 'init_code': "\n".join(init_code
),
7931 'check_code': "\n".join(check_code
),
7935 class GLcharNHandler(CustomHandler
):
7936 """Handler for functions that pass a single string with an optional len."""
7938 def InitFunction(self
, func
):
7939 """Overrriden from TypeHandler."""
7941 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
7943 def NeedsDataTransferFunction(self
, func
):
7944 """Overriden from TypeHandler."""
7947 def WriteServiceImplementation(self
, func
, f
):
7948 """Overrriden from TypeHandler."""
7949 self
.WriteServiceHandlerFunctionHeader(func
, f
)
7951 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7952 Bucket* bucket = GetBucket(bucket_id);
7953 if (!bucket || bucket->size() == 0) {
7954 return error::kInvalidArguments;
7957 if (!bucket->GetAsString(&str)) {
7958 return error::kInvalidArguments;
7960 %(gl_func_name)s(0, str.c_str());
7961 return error::kNoError;
7966 'gl_func_name': func
.GetGLFunctionName(),
7967 'bucket_id': func
.cmd_args
[0].name
,
7971 class IsHandler(TypeHandler
):
7972 """Handler for glIs____ type and glGetError functions."""
7974 def InitFunction(self
, func
):
7975 """Overrriden from TypeHandler."""
7976 func
.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7977 func
.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7978 if func
.GetInfo('result') == None:
7979 func
.AddInfo('result', ['uint32_t'])
7981 def WriteServiceUnitTest(self
, func
, f
, *extras
):
7982 """Overrriden from TypeHandler."""
7984 TEST_P(%(test_name)s, %(name)sValidArgs) {
7985 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7986 SpecializedSetup<cmds::%(name)s, 0>(true);
7988 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7991 decoder_->set_unsafe_es3_apis_enabled(true);"""
7993 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7994 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7997 decoder_->set_unsafe_es3_apis_enabled(false);
7998 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
8003 if len(func
.GetOriginalArgs()):
8005 self
.WriteValidUnitTest(func
, f
, valid_test
, {
8010 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
8011 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8012 SpecializedSetup<cmds::%(name)s, 0>(false);
8014 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
8015 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
8018 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, {
8023 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
8024 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8025 SpecializedSetup<cmds::%(name)s, 0>(false);"""
8028 decoder_->set_unsafe_es3_apis_enabled(true);"""
8031 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
8032 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
8033 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
8034 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
8037 decoder_->set_unsafe_es3_apis_enabled(true);"""
8041 self
.WriteValidUnitTest(func
, f
, invalid_test
, {
8045 def WriteServiceImplementation(self
, func
, f
):
8046 """Overrriden from TypeHandler."""
8047 self
.WriteServiceHandlerFunctionHeader(func
, f
)
8048 self
.WriteHandlerExtensionCheck(func
, f
)
8049 args
= func
.GetOriginalArgs()
8053 code
= """ typedef cmds::%(func_name)s::Result Result;
8054 Result* result_dst = GetSharedMemoryAs<Result*>(
8055 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
8057 return error::kOutOfBounds;
8060 f
.write(code
% {'func_name': func
.name
})
8061 func
.WriteHandlerValidation(f
)
8063 assert func
.GetInfo('id_mapping')
8064 assert len(func
.GetInfo('id_mapping')) == 1
8065 assert len(args
) == 1
8066 id_type
= func
.GetInfo('id_mapping')[0]
8067 f
.write(" %s service_%s = 0;\n" % (args
[0].type, id_type
.lower()))
8068 f
.write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
8069 (id_type
, id_type
.lower(), id_type
.lower()))
8071 f
.write(" *result_dst = %s(%s);\n" %
8072 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
8073 f
.write(" return error::kNoError;\n")
8077 def WriteGLES2Implementation(self
, func
, f
):
8078 """Overrriden from TypeHandler."""
8079 impl_func
= func
.GetInfo('impl_func')
8080 if impl_func
== None or impl_func
== True:
8081 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
8082 f
.write("%s GLES2Implementation::%s(%s) {\n" %
8083 (func
.return_type
, func
.original_name
,
8084 func
.MakeTypedOriginalArgString("")))
8085 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
8086 self
.WriteTraceEvent(func
, f
)
8087 func
.WriteDestinationInitalizationValidation(f
)
8088 self
.WriteClientGLCallLog(func
, f
)
8089 f
.write(" typedef cmds::%s::Result Result;\n" % func
.name
)
8090 f
.write(" Result* result = GetResultAs<Result*>();\n")
8091 f
.write(" if (!result) {\n")
8092 f
.write(" return %s;\n" % error_value
)
8094 f
.write(" *result = 0;\n")
8095 assert len(func
.GetOriginalArgs()) == 1
8096 id_arg
= func
.GetOriginalArgs()[0]
8097 if id_arg
.type == 'GLsync':
8098 arg_string
= "ToGLuint(%s)" % func
.MakeOriginalArgString("")
8100 arg_string
= func
.MakeOriginalArgString("")
8102 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
8103 (func
.name
, arg_string
))
8104 f
.write(" WaitForCmd();\n")
8105 f
.write(" %s result_value = *result" % func
.return_type
)
8106 if func
.return_type
== "GLboolean":
8108 f
.write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
8109 f
.write(" CheckGLError();\n")
8110 f
.write(" return result_value;\n")
8114 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
8115 """Overrriden from TypeHandler."""
8116 client_test
= func
.GetInfo('client_test')
8117 if client_test
== None or client_test
== True:
8119 TEST_F(GLES2ImplementationTest, %(name)s) {
8125 ExpectedMemoryInfo result1 =
8126 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
8127 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
8129 EXPECT_CALL(*command_buffer(), OnFlush())
8130 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
8131 .RetiresOnSaturation();
8133 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
8134 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
8135 EXPECT_TRUE(result);
8138 args
= func
.GetOriginalArgs()
8139 assert len(args
) == 1
8142 'cmd_id_value': args
[0].GetValidClientSideCmdArg(func
),
8143 'gl_id_value': args
[0].GetValidClientSideArg(func
) })
8146 class STRnHandler(TypeHandler
):
8147 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
8148 GetTranslatedShaderSourceANGLE."""
8150 def InitFunction(self
, func
):
8151 """Overrriden from TypeHandler."""
8152 # remove all but the first cmd args.
8153 cmd_args
= func
.GetCmdArgs()
8155 func
.AddCmdArg(cmd_args
[0])
8156 # add on a bucket id.
8157 func
.AddCmdArg(Argument('bucket_id', 'uint32_t'))
8159 def WriteGLES2Implementation(self
, func
, f
):
8160 """Overrriden from TypeHandler."""
8161 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
8162 GPU_CLIENT_SINGLE_THREAD_CHECK();
8164 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
8165 << "] gl%(func_name)s" << "("
8168 << static_cast<void*>(%(arg2)s) << ", "
8169 << static_cast<void*>(%(arg3)s) << ")");
8170 helper_->SetBucketSize(kResultBucketId, 0);
8171 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8173 GLsizei max_size = 0;
8174 if (GetBucketAsString(kResultBucketId, &str)) {
8177 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8178 memcpy(%(dest_name)s, str.c_str(), max_size);
8179 %(dest_name)s[max_size] = '\\0';
8180 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8183 if (%(length_name)s != NULL) {
8184 *%(length_name)s = max_size;
8189 args
= func
.GetOriginalArgs()
8191 'return_type': func
.return_type
,
8192 'func_name': func
.original_name
,
8193 'args': func
.MakeTypedOriginalArgString(""),
8194 'id_name': args
[0].name
,
8195 'bufsize_name': args
[1].name
,
8196 'length_name': args
[2].name
,
8197 'dest_name': args
[3].name
,
8198 'arg0': args
[0].name
,
8199 'arg1': args
[1].name
,
8200 'arg2': args
[2].name
,
8201 'arg3': args
[3].name
,
8203 f
.write(code_1
% str_args
)
8204 func
.WriteDestinationInitalizationValidation(f
)
8205 f
.write(code_2
% str_args
)
8207 def WriteServiceUnitTest(self
, func
, f
, *extras
):
8208 """Overrriden from TypeHandler."""
8210 TEST_P(%(test_name)s, %(name)sValidArgs) {
8211 const char* kInfo = "hello";
8212 const uint32_t kBucketId = 123;
8213 SpecializedSetup<cmds::%(name)s, 0>(true);
8215 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8216 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8217 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8220 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8221 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8222 ASSERT_TRUE(bucket != NULL);
8223 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8224 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8226 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8229 args
= func
.GetOriginalArgs()
8230 id_name
= args
[0].GetValidGLArg(func
)
8231 get_len_func
= func
.GetInfo('get_len_func')
8232 get_len_enum
= func
.GetInfo('get_len_enum')
8235 'get_len_func': get_len_func
,
8236 'get_len_enum': get_len_enum
,
8237 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8238 args
[0].GetValidGLArg(func
),
8239 'args': '%s, kBucketId' % args
[0].GetValidArg(func
),
8240 'expect_len_code': '',
8242 if get_len_func
and get_len_func
[0:2] == 'gl':
8243 sub
['expect_len_code'] = (
8244 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8245 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8246 get_len_func
[2:], id_name
, get_len_enum
)
8247 self
.WriteValidUnitTest(func
, f
, valid_test
, sub
, *extras
)
8250 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8251 const uint32_t kBucketId = 123;
8252 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8255 cmd.Init(kInvalidClientId, kBucketId);
8256 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8257 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8260 self
.WriteValidUnitTest(func
, f
, invalid_test
, *extras
)
8262 def WriteServiceImplementation(self
, func
, f
):
8263 """Overrriden from TypeHandler."""
8266 class NamedType(object):
8267 """A class that represents a type of an argument in a client function.
8269 A type of an argument that is to be passed through in the command buffer
8270 command. Currently used only for the arguments that are specificly named in
8271 the 'cmd_buffer_functions.txt' f, mostly enums.
8274 def __init__(self
, info
):
8275 assert not 'is_complete' in info
or info
['is_complete'] == True
8277 self
.valid
= info
['valid']
8278 if 'invalid' in info
:
8279 self
.invalid
= info
['invalid']
8282 if 'valid_es3' in info
:
8283 self
.valid_es3
= info
['valid_es3']
8286 if 'deprecated_es3' in info
:
8287 self
.deprecated_es3
= info
['deprecated_es3']
8289 self
.deprecated_es3
= []
8292 return self
.info
['type']
8294 def GetInvalidValues(self
):
8297 def GetValidValues(self
):
8300 def GetValidValuesES3(self
):
8301 return self
.valid_es3
8303 def GetDeprecatedValuesES3(self
):
8304 return self
.deprecated_es3
8306 def IsConstant(self
):
8307 if not 'is_complete' in self
.info
:
8310 return len(self
.GetValidValues()) == 1
8312 def GetConstantValue(self
):
8313 return self
.GetValidValues()[0]
8315 class Argument(object):
8316 """A class that represents a function argument."""
8319 'GLenum': 'uint32_t',
8321 'GLintptr': 'int32_t',
8322 'GLsizei': 'int32_t',
8323 'GLsizeiptr': 'int32_t',
8325 'GLclampf': 'float',
8327 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8329 def __init__(self
, name
, type):
8331 self
.optional
= type.endswith("Optional*")
8333 type = type[:-9] + "*"
8336 if type in self
.cmd_type_map_
:
8337 self
.cmd_type
= self
.cmd_type_map_
[type]
8339 self
.cmd_type
= 'uint32_t'
8341 def IsPointer(self
):
8342 """Returns true if argument is a pointer."""
8345 def IsPointer2D(self
):
8346 """Returns true if argument is a 2D pointer."""
8349 def IsConstant(self
):
8350 """Returns true if the argument has only one valid value."""
8353 def AddCmdArgs(self
, args
):
8354 """Adds command arguments for this argument to the given list."""
8355 if not self
.IsConstant():
8356 return args
.append(self
)
8358 def AddInitArgs(self
, args
):
8359 """Adds init arguments for this argument to the given list."""
8360 if not self
.IsConstant():
8361 return args
.append(self
)
8363 def GetValidArg(self
, func
):
8364 """Gets a valid value for this argument."""
8365 valid_arg
= func
.GetValidArg(self
)
8366 if valid_arg
!= None:
8369 index
= func
.GetOriginalArgs().index(self
)
8370 return str(index
+ 1)
8372 def GetValidClientSideArg(self
, func
):
8373 """Gets a valid value for this argument."""
8374 valid_arg
= func
.GetValidArg(self
)
8375 if valid_arg
!= None:
8378 if self
.IsPointer():
8380 index
= func
.GetOriginalArgs().index(self
)
8381 if self
.type == 'GLsync':
8382 return ("reinterpret_cast<GLsync>(%d)" % (index
+ 1))
8383 return str(index
+ 1)
8385 def GetValidClientSideCmdArg(self
, func
):
8386 """Gets a valid value for this argument."""
8387 valid_arg
= func
.GetValidArg(self
)
8388 if valid_arg
!= None:
8391 index
= func
.GetOriginalArgs().index(self
)
8392 return str(index
+ 1)
8395 index
= func
.GetCmdArgs().index(self
)
8396 return str(index
+ 1)
8398 def GetValidGLArg(self
, func
):
8399 """Gets a valid GL value for this argument."""
8400 value
= self
.GetValidArg(func
)
8401 if self
.type == 'GLsync':
8402 return ("reinterpret_cast<GLsync>(%s)" % value
)
8405 def GetValidNonCachedClientSideArg(self
, func
):
8406 """Returns a valid value for this argument in a GL call.
8407 Using the value will produce a command buffer service invocation.
8408 Returns None if there is no such value."""
8410 if self
.type == 'GLsync':
8411 return ("reinterpret_cast<GLsync>(%s)" % value
)
8414 def GetValidNonCachedClientSideCmdArg(self
, func
):
8415 """Returns a valid value for this argument in a command buffer command.
8416 Calling the GL function with the value returned by
8417 GetValidNonCachedClientSideArg will result in a command buffer command
8418 that contains the value returned by this function. """
8421 def GetNumInvalidValues(self
, func
):
8422 """returns the number of invalid values to be tested."""
8425 def GetInvalidArg(self
, index
):
8426 """returns an invalid value and expected parse result by index."""
8427 return ("---ERROR0---", "---ERROR2---", None)
8429 def GetLogArg(self
):
8430 """Get argument appropriate for LOG macro."""
8431 if self
.type == 'GLboolean':
8432 return 'GLES2Util::GetStringBool(%s)' % self
.name
8433 if self
.type == 'GLenum':
8434 return 'GLES2Util::GetStringEnum(%s)' % self
.name
8437 def WriteGetCode(self
, f
):
8438 """Writes the code to get an argument from a command structure."""
8439 if self
.type == 'GLsync':
8443 f
.write(" %s %s = static_cast<%s>(c.%s);\n" %
8444 (my_type
, self
.name
, my_type
, self
.name
))
8446 def WriteValidationCode(self
, f
, func
):
8447 """Writes the validation code for an argument."""
8450 def WriteClientSideValidationCode(self
, f
, func
):
8451 """Writes the validation code for an argument."""
8454 def WriteDestinationInitalizationValidation(self
, f
, func
):
8455 """Writes the client side destintion initialization validation."""
8458 def WriteDestinationInitalizationValidatationIfNeeded(self
, f
, func
):
8459 """Writes the client side destintion initialization validation if needed."""
8460 parts
= self
.type.split(" ")
8463 if parts
[0] in self
.need_validation_
:
8465 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8466 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
8468 def GetImmediateVersion(self
):
8469 """Gets the immediate version of this argument."""
8472 def GetBucketVersion(self
):
8473 """Gets the bucket version of this argument."""
8477 class BoolArgument(Argument
):
8478 """class for GLboolean"""
8480 def __init__(self
, name
, type):
8481 Argument
.__init
__(self
, name
, 'GLboolean')
8483 def GetValidArg(self
, func
):
8484 """Gets a valid value for this argument."""
8487 def GetValidClientSideArg(self
, func
):
8488 """Gets a valid value for this argument."""
8491 def GetValidClientSideCmdArg(self
, func
):
8492 """Gets a valid value for this argument."""
8495 def GetValidGLArg(self
, func
):
8496 """Gets a valid GL value for this argument."""
8500 class UniformLocationArgument(Argument
):
8501 """class for uniform locations."""
8503 def __init__(self
, name
):
8504 Argument
.__init
__(self
, name
, "GLint")
8506 def WriteGetCode(self
, f
):
8507 """Writes the code to get an argument from a command structure."""
8508 code
= """ %s %s = static_cast<%s>(c.%s);
8510 f
.write(code
% (self
.type, self
.name
, self
.type, self
.name
))
8512 class DataSizeArgument(Argument
):
8513 """class for data_size which Bucket commands do not need."""
8515 def __init__(self
, name
):
8516 Argument
.__init
__(self
, name
, "uint32_t")
8518 def GetBucketVersion(self
):
8522 class SizeArgument(Argument
):
8523 """class for GLsizei and GLsizeiptr."""
8525 def GetNumInvalidValues(self
, func
):
8526 """overridden from Argument."""
8527 if func
.IsImmediate():
8531 def GetInvalidArg(self
, index
):
8532 """overridden from Argument."""
8533 return ("-1", "kNoError", "GL_INVALID_VALUE")
8535 def WriteValidationCode(self
, f
, func
):
8536 """overridden from Argument."""
8539 code
= """ if (%(var_name)s < 0) {
8540 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8541 return error::kNoError;
8545 "var_name": self
.name
,
8546 "func_name": func
.original_name
,
8549 def WriteClientSideValidationCode(self
, f
, func
):
8550 """overridden from Argument."""
8551 code
= """ if (%(var_name)s < 0) {
8552 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8557 "var_name": self
.name
,
8558 "func_name": func
.original_name
,
8562 class SizeNotNegativeArgument(SizeArgument
):
8563 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8565 def __init__(self
, name
, type, gl_type
):
8566 SizeArgument
.__init
__(self
, name
, gl_type
)
8568 def GetInvalidArg(self
, index
):
8569 """overridden from SizeArgument."""
8570 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8572 def WriteValidationCode(self
, f
, func
):
8573 """overridden from SizeArgument."""
8577 class EnumBaseArgument(Argument
):
8578 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8579 ValidatedBoolArgument."""
8581 def __init__(self
, name
, gl_type
, type, gl_error
):
8582 Argument
.__init
__(self
, name
, gl_type
)
8584 self
.gl_error
= gl_error
8585 name
= type[len(gl_type
):]
8586 self
.type_name
= name
8587 self
.named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8589 def IsConstant(self
):
8590 return self
.named_type
.IsConstant()
8592 def GetConstantValue(self
):
8593 return self
.named_type
.GetConstantValue()
8595 def WriteValidationCode(self
, f
, func
):
8598 if self
.named_type
.IsConstant():
8600 f
.write(" if (!validators_->%s.IsValid(%s)) {\n" %
8601 (ToUnderscore(self
.type_name
), self
.name
))
8602 if self
.gl_error
== "GL_INVALID_ENUM":
8604 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8605 (func
.original_name
, self
.name
, self
.name
))
8608 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8609 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8610 f
.write(" return error::kNoError;\n")
8613 def WriteClientSideValidationCode(self
, f
, func
):
8614 if not self
.named_type
.IsConstant():
8616 f
.write(" if (%s != %s) {" % (self
.name
,
8617 self
.GetConstantValue()))
8619 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8620 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8621 if func
.return_type
== "void":
8622 f
.write(" return;\n")
8624 f
.write(" return %s;\n" % func
.GetErrorReturnString())
8627 def GetValidArg(self
, func
):
8628 valid_arg
= func
.GetValidArg(self
)
8629 if valid_arg
!= None:
8631 valid
= self
.named_type
.GetValidValues()
8635 index
= func
.GetOriginalArgs().index(self
)
8636 return str(index
+ 1)
8638 def GetValidClientSideArg(self
, func
):
8639 """Gets a valid value for this argument."""
8640 return self
.GetValidArg(func
)
8642 def GetValidClientSideCmdArg(self
, func
):
8643 """Gets a valid value for this argument."""
8644 valid_arg
= func
.GetValidArg(self
)
8645 if valid_arg
!= None:
8648 valid
= self
.named_type
.GetValidValues()
8653 index
= func
.GetOriginalArgs().index(self
)
8654 return str(index
+ 1)
8657 index
= func
.GetCmdArgs().index(self
)
8658 return str(index
+ 1)
8660 def GetValidGLArg(self
, func
):
8661 """Gets a valid value for this argument."""
8662 return self
.GetValidArg(func
)
8664 def GetNumInvalidValues(self
, func
):
8665 """returns the number of invalid values to be tested."""
8666 return len(self
.named_type
.GetInvalidValues())
8668 def GetInvalidArg(self
, index
):
8669 """returns an invalid value by index."""
8670 invalid
= self
.named_type
.GetInvalidValues()
8672 num_invalid
= len(invalid
)
8673 if index
>= num_invalid
:
8674 index
= num_invalid
- 1
8675 return (invalid
[index
], "kNoError", self
.gl_error
)
8676 return ("---ERROR1---", "kNoError", self
.gl_error
)
8679 class EnumArgument(EnumBaseArgument
):
8680 """A class that represents a GLenum argument"""
8682 def __init__(self
, name
, type):
8683 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
8685 def GetLogArg(self
):
8686 """Overridden from Argument."""
8687 return ("GLES2Util::GetString%s(%s)" %
8688 (self
.type_name
, self
.name
))
8691 class IntArgument(EnumBaseArgument
):
8692 """A class for a GLint argument that can only accept specific values.
8694 For example glTexImage2D takes a GLint for its internalformat
8695 argument instead of a GLenum.
8698 def __init__(self
, name
, type):
8699 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
8702 class ValidatedBoolArgument(EnumBaseArgument
):
8703 """A class for a GLboolean argument that can only accept specific values.
8705 For example glUniformMatrix takes a GLboolean for it's transpose but it
8709 def __init__(self
, name
, type):
8710 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
8712 def GetLogArg(self
):
8713 """Overridden from Argument."""
8714 return 'GLES2Util::GetStringBool(%s)' % self
.name
8717 class BitFieldArgument(EnumBaseArgument
):
8718 """A class for a GLbitfield argument that can only accept specific values.
8720 For example glFenceSync takes a GLbitfield for its flags argument bit it
8724 def __init__(self
, name
, type):
8725 EnumBaseArgument
.__init
__(self
, name
, "GLbitfield", type,
8729 class ImmediatePointerArgument(Argument
):
8730 """A class that represents an immediate argument to a function.
8732 An immediate argument is one where the data follows the command.
8735 def IsPointer(self
):
8738 def GetPointedType(self
):
8739 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8741 return match
.groupdict()['element_type']
8743 def AddCmdArgs(self
, args
):
8744 """Overridden from Argument."""
8747 def WriteGetCode(self
, f
):
8748 """Overridden from Argument."""
8750 " %s %s = GetImmediateDataAs<%s>(\n" %
8751 (self
.type, self
.name
, self
.type))
8752 f
.write(" c, data_size, immediate_data_size);\n")
8754 def WriteValidationCode(self
, f
, func
):
8755 """Overridden from Argument."""
8758 f
.write(" if (%s == NULL) {\n" % self
.name
)
8759 f
.write(" return error::kOutOfBounds;\n")
8762 def GetImmediateVersion(self
):
8763 """Overridden from Argument."""
8766 def WriteDestinationInitalizationValidation(self
, f
, func
):
8767 """Overridden from Argument."""
8768 self
.WriteDestinationInitalizationValidatationIfNeeded(f
, func
)
8770 def GetLogArg(self
):
8771 """Overridden from Argument."""
8772 return "static_cast<const void*>(%s)" % self
.name
8775 class PointerArgument(Argument
):
8776 """A class that represents a pointer argument to a function."""
8778 def IsPointer(self
):
8779 """Overridden from Argument."""
8782 def IsPointer2D(self
):
8783 """Overridden from Argument."""
8784 return self
.type.count('*') == 2
8786 def GetPointedType(self
):
8787 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8789 return match
.groupdict()['element_type']
8791 def GetValidArg(self
, func
):
8792 """Overridden from Argument."""
8793 return "shared_memory_id_, shared_memory_offset_"
8795 def GetValidGLArg(self
, func
):
8796 """Overridden from Argument."""
8797 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
8799 def GetNumInvalidValues(self
, func
):
8800 """Overridden from Argument."""
8803 def GetInvalidArg(self
, index
):
8804 """Overridden from Argument."""
8806 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8808 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8809 "kOutOfBounds", None)
8811 def GetLogArg(self
):
8812 """Overridden from Argument."""
8813 return "static_cast<const void*>(%s)" % self
.name
8815 def AddCmdArgs(self
, args
):
8816 """Overridden from Argument."""
8817 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32_t'))
8818 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32_t'))
8820 def WriteGetCode(self
, f
):
8821 """Overridden from Argument."""
8823 " %s %s = GetSharedMemoryAs<%s>(\n" %
8824 (self
.type, self
.name
, self
.type))
8826 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8827 (self
.name
, self
.name
))
8829 def WriteValidationCode(self
, f
, func
):
8830 """Overridden from Argument."""
8833 f
.write(" if (%s == NULL) {\n" % self
.name
)
8834 f
.write(" return error::kOutOfBounds;\n")
8837 def GetImmediateVersion(self
):
8838 """Overridden from Argument."""
8839 return ImmediatePointerArgument(self
.name
, self
.type)
8841 def GetBucketVersion(self
):
8842 """Overridden from Argument."""
8843 if self
.type.find('char') >= 0:
8844 if self
.IsPointer2D():
8845 return InputStringArrayBucketArgument(self
.name
, self
.type)
8846 return InputStringBucketArgument(self
.name
, self
.type)
8847 return BucketPointerArgument(self
.name
, self
.type)
8849 def WriteDestinationInitalizationValidation(self
, f
, func
):
8850 """Overridden from Argument."""
8851 self
.WriteDestinationInitalizationValidatationIfNeeded(f
, func
)
8854 class BucketPointerArgument(PointerArgument
):
8855 """A class that represents an bucket argument to a function."""
8857 def AddCmdArgs(self
, args
):
8858 """Overridden from Argument."""
8861 def WriteGetCode(self
, f
):
8862 """Overridden from Argument."""
8864 " %s %s = bucket->GetData(0, data_size);\n" %
8865 (self
.type, self
.name
))
8867 def WriteValidationCode(self
, f
, func
):
8868 """Overridden from Argument."""
8871 def GetImmediateVersion(self
):
8872 """Overridden from Argument."""
8875 def WriteDestinationInitalizationValidation(self
, f
, func
):
8876 """Overridden from Argument."""
8877 self
.WriteDestinationInitalizationValidatationIfNeeded(f
, func
)
8879 def GetLogArg(self
):
8880 """Overridden from Argument."""
8881 return "static_cast<const void*>(%s)" % self
.name
8884 class InputStringBucketArgument(Argument
):
8885 """A string input argument where the string is passed in a bucket."""
8887 def __init__(self
, name
, type):
8888 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8890 def IsPointer(self
):
8891 """Overridden from Argument."""
8894 def IsPointer2D(self
):
8895 """Overridden from Argument."""
8899 class InputStringArrayBucketArgument(Argument
):
8900 """A string array input argument where the strings are passed in a bucket."""
8902 def __init__(self
, name
, type):
8903 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8904 self
._original
_name
= name
8906 def WriteGetCode(self
, f
):
8907 """Overridden from Argument."""
8909 Bucket* bucket = GetBucket(c.%(name)s);
8911 return error::kInvalidArguments;
8914 std::vector<char*> strs;
8915 std::vector<GLint> len;
8916 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8917 return error::kInvalidArguments;
8919 const char** %(original_name)s =
8920 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8921 const GLint* length =
8922 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8927 'original_name': self
._original
_name
,
8930 def GetValidArg(self
, func
):
8931 return "kNameBucketId"
8933 def GetValidGLArg(self
, func
):
8936 def IsPointer(self
):
8937 """Overridden from Argument."""
8940 def IsPointer2D(self
):
8941 """Overridden from Argument."""
8945 class ResourceIdArgument(Argument
):
8946 """A class that represents a resource id argument to a function."""
8948 def __init__(self
, name
, type):
8949 match
= re
.match("(GLid\w+)", type)
8950 self
.resource_type
= match
.group(1)[4:]
8951 if self
.resource_type
== "Sync":
8952 type = type.replace(match
.group(1), "GLsync")
8954 type = type.replace(match
.group(1), "GLuint")
8955 Argument
.__init
__(self
, name
, type)
8957 def WriteGetCode(self
, f
):
8958 """Overridden from Argument."""
8959 if self
.type == "GLsync":
8963 f
.write(" %s %s = c.%s;\n" % (my_type
, self
.name
, self
.name
))
8965 def GetValidArg(self
, func
):
8966 return "client_%s_id_" % self
.resource_type
.lower()
8968 def GetValidGLArg(self
, func
):
8969 if self
.resource_type
== "Sync":
8970 return "reinterpret_cast<GLsync>(kService%sId)" % self
.resource_type
8971 return "kService%sId" % self
.resource_type
8974 class ResourceIdBindArgument(Argument
):
8975 """Represents a resource id argument to a bind function."""
8977 def __init__(self
, name
, type):
8978 match
= re
.match("(GLidBind\w+)", type)
8979 self
.resource_type
= match
.group(1)[8:]
8980 type = type.replace(match
.group(1), "GLuint")
8981 Argument
.__init
__(self
, name
, type)
8983 def WriteGetCode(self
, f
):
8984 """Overridden from Argument."""
8985 code
= """ %(type)s %(name)s = c.%(name)s;
8987 f
.write(code
% {'type': self
.type, 'name': self
.name
})
8989 def GetValidArg(self
, func
):
8990 return "client_%s_id_" % self
.resource_type
.lower()
8992 def GetValidGLArg(self
, func
):
8993 return "kService%sId" % self
.resource_type
8996 class ResourceIdZeroArgument(Argument
):
8997 """Represents a resource id argument to a function that can be zero."""
8999 def __init__(self
, name
, type):
9000 match
= re
.match("(GLidZero\w+)", type)
9001 self
.resource_type
= match
.group(1)[8:]
9002 type = type.replace(match
.group(1), "GLuint")
9003 Argument
.__init
__(self
, name
, type)
9005 def WriteGetCode(self
, f
):
9006 """Overridden from Argument."""
9007 f
.write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
9009 def GetValidArg(self
, func
):
9010 return "client_%s_id_" % self
.resource_type
.lower()
9012 def GetValidGLArg(self
, func
):
9013 return "kService%sId" % self
.resource_type
9015 def GetNumInvalidValues(self
, func
):
9016 """returns the number of invalid values to be tested."""
9019 def GetInvalidArg(self
, index
):
9020 """returns an invalid value by index."""
9021 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
9024 class Function(object):
9025 """A class that represents a function."""
9029 'Bind': BindHandler(),
9030 'Create': CreateHandler(),
9031 'Custom': CustomHandler(),
9032 'Data': DataHandler(),
9033 'Delete': DeleteHandler(),
9034 'DELn': DELnHandler(),
9035 'GENn': GENnHandler(),
9036 'GETn': GETnHandler(),
9037 'GLchar': GLcharHandler(),
9038 'GLcharN': GLcharNHandler(),
9039 'HandWritten': HandWrittenHandler(),
9041 'Manual': ManualHandler(),
9042 'PUT': PUTHandler(),
9043 'PUTn': PUTnHandler(),
9044 'PUTSTR': PUTSTRHandler(),
9045 'PUTXn': PUTXnHandler(),
9046 'StateSet': StateSetHandler(),
9047 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
9048 'StateSetFrontBack': StateSetFrontBackHandler(),
9049 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
9050 'StateSetNamedParameter': StateSetNamedParameter(),
9051 'STRn': STRnHandler(),
9054 def __init__(self
, name
, info
):
9056 self
.original_name
= info
['original_name']
9058 self
.original_args
= self
.ParseArgs(info
['original_args'])
9060 if 'cmd_args' in info
:
9061 self
.args_for_cmds
= self
.ParseArgs(info
['cmd_args'])
9063 self
.args_for_cmds
= self
.original_args
[:]
9065 self
.return_type
= info
['return_type']
9066 if self
.return_type
!= 'void':
9067 self
.return_arg
= CreateArg(info
['return_type'] + " result")
9069 self
.return_arg
= None
9071 self
.num_pointer_args
= sum(
9072 [1 for arg
in self
.args_for_cmds
if arg
.IsPointer()])
9073 if self
.num_pointer_args
> 0:
9074 for arg
in reversed(self
.original_args
):
9076 self
.last_original_pointer_arg
= arg
9079 self
.last_original_pointer_arg
= None
9081 self
.type_handler
= self
.type_handlers
[info
['type']]
9082 self
.can_auto_generate
= (self
.num_pointer_args
== 0 and
9083 info
['return_type'] == "void")
9086 def ParseArgs(self
, arg_string
):
9087 """Parses a function arg string."""
9089 parts
= arg_string
.split(',')
9090 for arg_string
in parts
:
9091 arg
= CreateArg(arg_string
)
9096 def IsType(self
, type_name
):
9097 """Returns true if function is a certain type."""
9098 return self
.info
['type'] == type_name
9100 def InitFunction(self
):
9101 """Creates command args and calls the init function for the type handler.
9103 Creates argument lists for command buffer commands, eg. self.cmd_args and
9105 Calls the type function initialization.
9106 Override to create different kind of command buffer command argument lists.
9109 for arg
in self
.args_for_cmds
:
9110 arg
.AddCmdArgs(self
.cmd_args
)
9113 for arg
in self
.args_for_cmds
:
9114 arg
.AddInitArgs(self
.init_args
)
9117 self
.init_args
.append(self
.return_arg
)
9119 self
.type_handler
.InitFunction(self
)
9121 def IsImmediate(self
):
9122 """Returns whether the function is immediate data function or not."""
9126 """Returns whether the function has service side validation or not."""
9127 return self
.GetInfo('unsafe', False)
9129 def GetInfo(self
, name
, default
= None):
9130 """Returns a value from the function info for this function."""
9131 if name
in self
.info
:
9132 return self
.info
[name
]
9135 def GetValidArg(self
, arg
):
9136 """Gets a valid argument value for the parameter arg from the function info
9139 index
= self
.GetOriginalArgs().index(arg
)
9143 valid_args
= self
.GetInfo('valid_args')
9144 if valid_args
and str(index
) in valid_args
:
9145 return valid_args
[str(index
)]
9148 def AddInfo(self
, name
, value
):
9150 self
.info
[name
] = value
9152 def IsExtension(self
):
9153 return self
.GetInfo('extension') or self
.GetInfo('extension_flag')
9155 def IsCoreGLFunction(self
):
9156 return (not self
.IsExtension() and
9157 not self
.GetInfo('pepper_interface') and
9158 not self
.IsUnsafe())
9160 def InPepperInterface(self
, interface
):
9161 ext
= self
.GetInfo('pepper_interface')
9162 if not interface
.GetName():
9163 return self
.IsCoreGLFunction()
9164 return ext
== interface
.GetName()
9166 def InAnyPepperExtension(self
):
9167 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
9169 def GetErrorReturnString(self
):
9170 if self
.GetInfo("error_return"):
9171 return self
.GetInfo("error_return")
9172 elif self
.return_type
== "GLboolean":
9174 elif "*" in self
.return_type
:
9178 def GetGLFunctionName(self
):
9179 """Gets the function to call to execute GL for this command."""
9180 if self
.GetInfo('decoder_func'):
9181 return self
.GetInfo('decoder_func')
9182 return "gl%s" % self
.original_name
9184 def GetGLTestFunctionName(self
):
9185 gl_func_name
= self
.GetInfo('gl_test_func')
9186 if gl_func_name
== None:
9187 gl_func_name
= self
.GetGLFunctionName()
9188 if gl_func_name
.startswith("gl"):
9189 gl_func_name
= gl_func_name
[2:]
9191 gl_func_name
= self
.original_name
9194 def GetDataTransferMethods(self
):
9195 return self
.GetInfo('data_transfer_methods',
9196 ['immediate' if self
.num_pointer_args
== 1 else 'shm'])
9198 def AddCmdArg(self
, arg
):
9199 """Adds a cmd argument to this function."""
9200 self
.cmd_args
.append(arg
)
9202 def GetCmdArgs(self
):
9203 """Gets the command args for this function."""
9204 return self
.cmd_args
9206 def ClearCmdArgs(self
):
9207 """Clears the command args for this function."""
9210 def GetCmdConstants(self
):
9211 """Gets the constants for this function."""
9212 return [arg
for arg
in self
.args_for_cmds
if arg
.IsConstant()]
9214 def GetInitArgs(self
):
9215 """Gets the init args for this function."""
9216 return self
.init_args
9218 def GetOriginalArgs(self
):
9219 """Gets the original arguments to this function."""
9220 return self
.original_args
9222 def GetLastOriginalArg(self
):
9223 """Gets the last original argument to this function."""
9224 return self
.original_args
[len(self
.original_args
) - 1]
9226 def GetLastOriginalPointerArg(self
):
9227 return self
.last_original_pointer_arg
9229 def GetResourceIdArg(self
):
9230 for arg
in self
.original_args
:
9231 if hasattr(arg
, 'resource_type'):
9235 def _MaybePrependComma(self
, arg_string
, add_comma
):
9236 """Adds a comma if arg_string is not empty and add_comma is true."""
9238 if add_comma
and len(arg_string
):
9240 return "%s%s" % (comma
, arg_string
)
9242 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
9243 """Gets a list of arguments as they are in GL."""
9244 args
= self
.GetOriginalArgs()
9245 arg_string
= ", ".join(
9246 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9247 return self
._MaybePrependComma
(arg_string
, add_comma
)
9249 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9250 """Gets the list of arguments as they are in GL."""
9251 args
= self
.GetOriginalArgs()
9252 arg_string
= separator
.join(
9253 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9254 return self
._MaybePrependComma
(arg_string
, add_comma
)
9256 def MakeHelperArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9257 """Gets a list of GL arguments after removing unneeded arguments."""
9258 args
= self
.GetOriginalArgs()
9259 arg_string
= separator
.join(
9260 ["%s%s" % (prefix
, arg
.name
)
9261 for arg
in args
if not arg
.IsConstant()])
9262 return self
._MaybePrependComma
(arg_string
, add_comma
)
9264 def MakeTypedPepperArgString(self
, prefix
):
9265 """Gets a list of arguments as they need to be for Pepper."""
9266 if self
.GetInfo("pepper_args"):
9267 return self
.GetInfo("pepper_args")
9269 return self
.MakeTypedOriginalArgString(prefix
, False)
9271 def MapCTypeToPepperIdlType(self
, ctype
, is_for_return_type
=False):
9272 """Converts a C type name to the corresponding Pepper IDL type."""
9274 'char*': '[out] str_t',
9275 'const GLchar* const*': '[out] cstr_t',
9276 'const char*': 'cstr_t',
9277 'const void*': 'mem_t',
9278 'void*': '[out] mem_t',
9279 'void**': '[out] mem_ptr_t',
9281 # We use "GLxxx_ptr_t" for "GLxxx*".
9282 matched
= re
.match(r
'(const )?(GL\w+)\*$', ctype
)
9284 idltype
= matched
.group(2) + '_ptr_t'
9285 if not matched
.group(1):
9286 idltype
= '[out] ' + idltype
9287 # If an in/out specifier is not specified yet, prepend [in].
9288 if idltype
[0] != '[':
9289 idltype
= '[in] ' + idltype
9290 # Strip the in/out specifier for a return type.
9291 if is_for_return_type
:
9292 idltype
= re
.sub(r
'\[\w+\] ', '', idltype
)
9295 def MakeTypedPepperIdlArgStrings(self
):
9296 """Gets a list of arguments as they need to be for Pepper IDL."""
9297 args
= self
.GetOriginalArgs()
9298 return ["%s %s" % (self
.MapCTypeToPepperIdlType(arg
.type), arg
.name
)
9301 def GetPepperName(self
):
9302 if self
.GetInfo("pepper_name"):
9303 return self
.GetInfo("pepper_name")
9306 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
9307 """Gets a typed list of arguments as they need to be for command buffers."""
9308 args
= self
.GetCmdArgs()
9309 arg_string
= ", ".join(
9310 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9311 return self
._MaybePrependComma
(arg_string
, add_comma
)
9313 def MakeCmdArgString(self
, prefix
, add_comma
= False):
9314 """Gets the list of arguments as they need to be for command buffers."""
9315 args
= self
.GetCmdArgs()
9316 arg_string
= ", ".join(
9317 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9318 return self
._MaybePrependComma
(arg_string
, add_comma
)
9320 def MakeTypedInitString(self
, prefix
, add_comma
= False):
9321 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9322 args
= self
.GetInitArgs()
9323 arg_string
= ", ".join(
9324 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9325 return self
._MaybePrependComma
(arg_string
, add_comma
)
9327 def MakeInitString(self
, prefix
, add_comma
= False):
9328 """Gets the list of arguments as they need to be for cmd Init/Set."""
9329 args
= self
.GetInitArgs()
9330 arg_string
= ", ".join(
9331 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9332 return self
._MaybePrependComma
(arg_string
, add_comma
)
9334 def MakeLogArgString(self
):
9335 """Makes a string of the arguments for the LOG macros"""
9336 args
= self
.GetOriginalArgs()
9337 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
9339 def WriteHandlerValidation(self
, f
):
9340 """Writes validation code for the function."""
9341 for arg
in self
.GetOriginalArgs():
9342 arg
.WriteValidationCode(f
, self
)
9343 self
.WriteValidationCode(f
)
9345 def WriteHandlerImplementation(self
, f
):
9346 """Writes the handler implementation for this command."""
9347 self
.type_handler
.WriteHandlerImplementation(self
, f
)
9349 def WriteValidationCode(self
, f
):
9350 """Writes the validation code for a command."""
9353 def WriteCmdFlag(self
, f
):
9354 """Writes the cmd cmd_flags constant."""
9356 # By default trace only at the highest level 3.
9357 trace_level
= int(self
.GetInfo('trace_level', default
= 3))
9358 if trace_level
not in xrange(0, 4):
9359 raise KeyError("Unhandled trace_level: %d" % trace_level
)
9361 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
9364 cmd_flags
= ' | '.join(flags
)
9368 f
.write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
9371 def WriteCmdArgFlag(self
, f
):
9372 """Writes the cmd kArgFlags constant."""
9373 f
.write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9375 def WriteCmdComputeSize(self
, f
):
9376 """Writes the ComputeSize function for the command."""
9377 f
.write(" static uint32_t ComputeSize() {\n")
9379 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9383 def WriteCmdSetHeader(self
, f
):
9384 """Writes the cmd's SetHeader function."""
9385 f
.write(" void SetHeader() {\n")
9386 f
.write(" header.SetCmd<ValueType>();\n")
9390 def WriteCmdInit(self
, f
):
9391 """Writes the cmd's Init function."""
9392 f
.write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
9393 f
.write(" SetHeader();\n")
9394 args
= self
.GetCmdArgs()
9396 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
9400 def WriteCmdSet(self
, f
):
9401 """Writes the cmd's Set function."""
9402 copy_args
= self
.MakeCmdArgString("_", False)
9403 f
.write(" void* Set(void* cmd%s) {\n" %
9404 self
.MakeTypedCmdArgString("_", True))
9405 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
9406 f
.write(" return NextCmdAddress<ValueType>(cmd);\n")
9410 def WriteStruct(self
, f
):
9411 self
.type_handler
.WriteStruct(self
, f
)
9413 def WriteDocs(self
, f
):
9414 self
.type_handler
.WriteDocs(self
, f
)
9416 def WriteCmdHelper(self
, f
):
9417 """Writes the cmd's helper."""
9418 self
.type_handler
.WriteCmdHelper(self
, f
)
9420 def WriteServiceImplementation(self
, f
):
9421 """Writes the service implementation for a command."""
9422 self
.type_handler
.WriteServiceImplementation(self
, f
)
9424 def WriteServiceUnitTest(self
, f
, *extras
):
9425 """Writes the service implementation for a command."""
9426 self
.type_handler
.WriteServiceUnitTest(self
, f
, *extras
)
9428 def WriteGLES2CLibImplementation(self
, f
):
9429 """Writes the GLES2 C Lib Implemention."""
9430 self
.type_handler
.WriteGLES2CLibImplementation(self
, f
)
9432 def WriteGLES2InterfaceHeader(self
, f
):
9433 """Writes the GLES2 Interface declaration."""
9434 self
.type_handler
.WriteGLES2InterfaceHeader(self
, f
)
9436 def WriteMojoGLES2ImplHeader(self
, f
):
9437 """Writes the Mojo GLES2 implementation header declaration."""
9438 self
.type_handler
.WriteMojoGLES2ImplHeader(self
, f
)
9440 def WriteMojoGLES2Impl(self
, f
):
9441 """Writes the Mojo GLES2 implementation declaration."""
9442 self
.type_handler
.WriteMojoGLES2Impl(self
, f
)
9444 def WriteGLES2InterfaceStub(self
, f
):
9445 """Writes the GLES2 Interface Stub declaration."""
9446 self
.type_handler
.WriteGLES2InterfaceStub(self
, f
)
9448 def WriteGLES2InterfaceStubImpl(self
, f
):
9449 """Writes the GLES2 Interface Stub declaration."""
9450 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, f
)
9452 def WriteGLES2ImplementationHeader(self
, f
):
9453 """Writes the GLES2 Implemention declaration."""
9454 self
.type_handler
.WriteGLES2ImplementationHeader(self
, f
)
9456 def WriteGLES2Implementation(self
, f
):
9457 """Writes the GLES2 Implemention definition."""
9458 self
.type_handler
.WriteGLES2Implementation(self
, f
)
9460 def WriteGLES2TraceImplementationHeader(self
, f
):
9461 """Writes the GLES2 Trace Implemention declaration."""
9462 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, f
)
9464 def WriteGLES2TraceImplementation(self
, f
):
9465 """Writes the GLES2 Trace Implemention definition."""
9466 self
.type_handler
.WriteGLES2TraceImplementation(self
, f
)
9468 def WriteGLES2Header(self
, f
):
9469 """Writes the GLES2 Implemention unit test."""
9470 self
.type_handler
.WriteGLES2Header(self
, f
)
9472 def WriteGLES2ImplementationUnitTest(self
, f
):
9473 """Writes the GLES2 Implemention unit test."""
9474 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, f
)
9476 def WriteDestinationInitalizationValidation(self
, f
):
9477 """Writes the client side destintion initialization validation."""
9478 self
.type_handler
.WriteDestinationInitalizationValidation(self
, f
)
9480 def WriteFormatTest(self
, f
):
9481 """Writes the cmd's format test."""
9482 self
.type_handler
.WriteFormatTest(self
, f
)
9485 class PepperInterface(object):
9486 """A class that represents a function."""
9488 def __init__(self
, info
):
9489 self
.name
= info
["name"]
9490 self
.dev
= info
["dev"]
9495 def GetInterfaceName(self
):
9499 upperint
= "_" + self
.name
.upper()
9502 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
9504 def GetStructName(self
):
9508 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
9511 class ImmediateFunction(Function
):
9512 """A class that represnets an immediate function command."""
9514 def __init__(self
, func
):
9517 "%sImmediate" % func
.name
,
9520 def InitFunction(self
):
9521 # Override args in original_args and args_for_cmds with immediate versions
9524 new_original_args
= []
9525 for arg
in self
.original_args
:
9526 new_arg
= arg
.GetImmediateVersion()
9528 new_original_args
.append(new_arg
)
9529 self
.original_args
= new_original_args
9531 new_args_for_cmds
= []
9532 for arg
in self
.args_for_cmds
:
9533 new_arg
= arg
.GetImmediateVersion()
9535 new_args_for_cmds
.append(new_arg
)
9537 self
.args_for_cmds
= new_args_for_cmds
9539 Function
.InitFunction(self
)
9541 def IsImmediate(self
):
9544 def WriteServiceImplementation(self
, f
):
9545 """Overridden from Function"""
9546 self
.type_handler
.WriteImmediateServiceImplementation(self
, f
)
9548 def WriteHandlerImplementation(self
, f
):
9549 """Overridden from Function"""
9550 self
.type_handler
.WriteImmediateHandlerImplementation(self
, f
)
9552 def WriteServiceUnitTest(self
, f
, *extras
):
9553 """Writes the service implementation for a command."""
9554 self
.type_handler
.WriteImmediateServiceUnitTest(self
, f
, *extras
)
9556 def WriteValidationCode(self
, f
):
9557 """Overridden from Function"""
9558 self
.type_handler
.WriteImmediateValidationCode(self
, f
)
9560 def WriteCmdArgFlag(self
, f
):
9561 """Overridden from Function"""
9562 f
.write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9564 def WriteCmdComputeSize(self
, f
):
9565 """Overridden from Function"""
9566 self
.type_handler
.WriteImmediateCmdComputeSize(self
, f
)
9568 def WriteCmdSetHeader(self
, f
):
9569 """Overridden from Function"""
9570 self
.type_handler
.WriteImmediateCmdSetHeader(self
, f
)
9572 def WriteCmdInit(self
, f
):
9573 """Overridden from Function"""
9574 self
.type_handler
.WriteImmediateCmdInit(self
, f
)
9576 def WriteCmdSet(self
, f
):
9577 """Overridden from Function"""
9578 self
.type_handler
.WriteImmediateCmdSet(self
, f
)
9580 def WriteCmdHelper(self
, f
):
9581 """Overridden from Function"""
9582 self
.type_handler
.WriteImmediateCmdHelper(self
, f
)
9584 def WriteFormatTest(self
, f
):
9585 """Overridden from Function"""
9586 self
.type_handler
.WriteImmediateFormatTest(self
, f
)
9589 class BucketFunction(Function
):
9590 """A class that represnets a bucket version of a function command."""
9592 def __init__(self
, func
):
9595 "%sBucket" % func
.name
,
9598 def InitFunction(self
):
9599 # Override args in original_args and args_for_cmds with bucket versions
9602 new_original_args
= []
9603 for arg
in self
.original_args
:
9604 new_arg
= arg
.GetBucketVersion()
9606 new_original_args
.append(new_arg
)
9607 self
.original_args
= new_original_args
9609 new_args_for_cmds
= []
9610 for arg
in self
.args_for_cmds
:
9611 new_arg
= arg
.GetBucketVersion()
9613 new_args_for_cmds
.append(new_arg
)
9615 self
.args_for_cmds
= new_args_for_cmds
9617 Function
.InitFunction(self
)
9619 def WriteServiceImplementation(self
, f
):
9620 """Overridden from Function"""
9621 self
.type_handler
.WriteBucketServiceImplementation(self
, f
)
9623 def WriteHandlerImplementation(self
, f
):
9624 """Overridden from Function"""
9625 self
.type_handler
.WriteBucketHandlerImplementation(self
, f
)
9627 def WriteServiceUnitTest(self
, f
, *extras
):
9628 """Overridden from Function"""
9629 self
.type_handler
.WriteBucketServiceUnitTest(self
, f
, *extras
)
9631 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9632 """Overridden from Function"""
9633 args
= self
.GetOriginalArgs()
9634 arg_string
= separator
.join(
9635 ["%s%s" % (prefix
, arg
.name
[0:-10] if arg
.name
.endswith("_bucket_id")
9636 else arg
.name
) for arg
in args
])
9637 return super(BucketFunction
, self
)._MaybePrependComma
(arg_string
, add_comma
)
9640 def CreateArg(arg_string
):
9641 """Creates an Argument."""
9642 arg_parts
= arg_string
.split()
9643 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
9645 # Is this a pointer argument?
9646 elif arg_string
.find('*') >= 0:
9647 return PointerArgument(
9649 " ".join(arg_parts
[0:-1]))
9650 # Is this a resource argument? Must come after pointer check.
9651 elif arg_parts
[0].startswith('GLidBind'):
9652 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9653 elif arg_parts
[0].startswith('GLidZero'):
9654 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9655 elif arg_parts
[0].startswith('GLid'):
9656 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9657 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
9658 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9659 elif arg_parts
[0].startswith('GLbitfield') and len(arg_parts
[0]) > 10:
9660 return BitFieldArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9661 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
9662 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9663 elif arg_parts
[0].startswith('GLboolean'):
9664 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9665 elif arg_parts
[0].startswith('GLintUniformLocation'):
9666 return UniformLocationArgument(arg_parts
[-1])
9667 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
9668 not arg_parts
[0].startswith('GLintptr')):
9669 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9670 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
9671 arg_parts
[0].startswith('GLintptrNotNegative')):
9672 return SizeNotNegativeArgument(arg_parts
[-1],
9673 " ".join(arg_parts
[0:-1]),
9674 arg_parts
[0][0:-11])
9675 elif arg_parts
[0].startswith('GLsize'):
9676 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9678 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9681 class GLGenerator(object):
9682 """A class to generate GL command buffers."""
9684 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9686 def __init__(self
, verbose
):
9687 self
.original_functions
= []
9689 self
.verbose
= verbose
9691 self
.pepper_interfaces
= []
9692 self
.interface_info
= {}
9693 self
.generated_cpp_filenames
= []
9695 for interface
in _PEPPER_INTERFACES
:
9696 interface
= PepperInterface(interface
)
9697 self
.pepper_interfaces
.append(interface
)
9698 self
.interface_info
[interface
.GetName()] = interface
9700 def AddFunction(self
, func
):
9701 """Adds a function."""
9702 self
.functions
.append(func
)
9704 def GetFunctionInfo(self
, name
):
9705 """Gets a type info for the given function name."""
9706 if name
in _FUNCTION_INFO
:
9707 func_info
= _FUNCTION_INFO
[name
].copy()
9711 if not 'type' in func_info
:
9712 func_info
['type'] = ''
9717 """Prints something if verbose is true."""
9721 def Error(self
, msg
):
9722 """Prints an error."""
9723 print "Error: %s" % msg
9726 def ParseGLH(self
, filename
):
9727 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9728 with
open(filename
, "r") as f
:
9729 functions
= f
.read()
9730 for line
in functions
.splitlines():
9731 match
= self
._function
_re
.match(line
)
9733 func_name
= match
.group(2)[2:]
9734 func_info
= self
.GetFunctionInfo(func_name
)
9735 if func_info
['type'] == 'Noop':
9738 parsed_func_info
= {
9739 'original_name': func_name
,
9740 'original_args': match
.group(3),
9741 'return_type': match
.group(1).strip(),
9744 for k
in parsed_func_info
.keys():
9745 if not k
in func_info
:
9746 func_info
[k
] = parsed_func_info
[k
]
9748 f
= Function(func_name
, func_info
)
9749 self
.original_functions
.append(f
)
9751 #for arg in f.GetOriginalArgs():
9752 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9753 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9755 gen_cmd
= f
.GetInfo('gen_cmd')
9756 if gen_cmd
== True or gen_cmd
== None:
9757 if f
.type_handler
.NeedsDataTransferFunction(f
):
9758 methods
= f
.GetDataTransferMethods()
9759 if 'immediate' in methods
:
9760 self
.AddFunction(ImmediateFunction(f
))
9761 if 'bucket' in methods
:
9762 self
.AddFunction(BucketFunction(f
))
9763 if 'shm' in methods
:
9768 self
.Log("Auto Generated Functions : %d" %
9769 len([f
for f
in self
.functions
if f
.can_auto_generate
or
9770 (not f
.IsType('') and not f
.IsType('Custom') and
9771 not f
.IsType('Todo'))]))
9773 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
9774 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
9775 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
9778 self
.Log(" %-10s %-20s gl%s" % (f
.info
['type'], f
.return_type
, f
.name
))
9780 def WriteCommandIds(self
, filename
):
9781 """Writes the command buffer format"""
9782 with
CHeaderWriter(filename
) as f
:
9783 f
.write("#define GLES2_COMMAND_LIST(OP) \\\n")
9785 for func
in self
.functions
:
9786 f
.write(" %-60s /* %d */ \\\n" %
9787 ("OP(%s)" % func
.name
, id))
9791 f
.write("enum CommandId {\n")
9792 f
.write(" kStartPoint = cmd::kLastCommonId, "
9793 "// All GLES2 commands start after this.\n")
9794 f
.write("#define GLES2_CMD_OP(name) k ## name,\n")
9795 f
.write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9796 f
.write("#undef GLES2_CMD_OP\n")
9797 f
.write(" kNumCommands\n")
9800 self
.generated_cpp_filenames
.append(filename
)
9802 def WriteFormat(self
, filename
):
9803 """Writes the command buffer format"""
9804 with
CHeaderWriter(filename
) as f
:
9805 # Forward declaration of a few enums used in constant argument
9806 # to avoid including GL header files.
9808 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9809 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9812 for enum
in enum_defines
:
9813 f
.write("#define %s %s\n" % (enum
, enum_defines
[enum
]))
9815 for func
in self
.functions
:
9817 #gen_cmd = func.GetInfo('gen_cmd')
9818 #if gen_cmd == True or gen_cmd == None:
9821 self
.generated_cpp_filenames
.append(filename
)
9823 def WriteDocs(self
, filename
):
9824 """Writes the command buffer doc version of the commands"""
9825 with
CHeaderWriter(filename
) as f
:
9826 for func
in self
.functions
:
9828 #gen_cmd = func.GetInfo('gen_cmd')
9829 #if gen_cmd == True or gen_cmd == None:
9832 self
.generated_cpp_filenames
.append(filename
)
9834 def WriteFormatTest(self
, filename
):
9835 """Writes the command buffer format test."""
9836 comment
= ("// This file contains unit tests for gles2 commmands\n"
9837 "// It is included by gles2_cmd_format_test.cc\n\n")
9838 with
CHeaderWriter(filename
, comment
) as f
:
9839 for func
in self
.functions
:
9841 #gen_cmd = func.GetInfo('gen_cmd')
9842 #if gen_cmd == True or gen_cmd == None:
9843 func
.WriteFormatTest(f
)
9844 self
.generated_cpp_filenames
.append(filename
)
9846 def WriteCmdHelperHeader(self
, filename
):
9847 """Writes the gles2 command helper."""
9848 with
CHeaderWriter(filename
) as f
:
9849 for func
in self
.functions
:
9851 #gen_cmd = func.GetInfo('gen_cmd')
9852 #if gen_cmd == True or gen_cmd == None:
9853 func
.WriteCmdHelper(f
)
9854 self
.generated_cpp_filenames
.append(filename
)
9856 def WriteServiceContextStateHeader(self
, filename
):
9857 """Writes the service context state header."""
9858 comment
= "// It is included by context_state.h\n"
9859 with
CHeaderWriter(filename
, comment
) as f
:
9860 f
.write("struct EnableFlags {\n")
9861 f
.write(" EnableFlags();\n")
9862 for capability
in _CAPABILITY_FLAGS
:
9863 f
.write(" bool %s;\n" % capability
['name'])
9864 f
.write(" bool cached_%s;\n" % capability
['name'])
9867 for state_name
in sorted(_STATES
.keys()):
9868 state
= _STATES
[state_name
]
9869 for item
in state
['states']:
9870 if isinstance(item
['default'], list):
9871 f
.write("%s %s[%d];\n" % (item
['type'], item
['name'],
9872 len(item
['default'])))
9874 f
.write("%s %s;\n" % (item
['type'], item
['name']))
9876 if item
.get('cached', False):
9877 if isinstance(item
['default'], list):
9878 f
.write("%s cached_%s[%d];\n" % (item
['type'], item
['name'],
9879 len(item
['default'])))
9881 f
.write("%s cached_%s;\n" % (item
['type'], item
['name']))
9885 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9888 for capability
in _CAPABILITY_FLAGS
:
9891 """ % capability
['name'].upper())
9893 if (enable_flags.cached_%(name)s == enable &&
9894 !ignore_cached_state)
9896 enable_flags.cached_%(name)s = enable;
9911 self
.generated_cpp_filenames
.append(filename
)
9913 def WriteClientContextStateHeader(self
, filename
):
9914 """Writes the client context state header."""
9915 comment
= "// It is included by client_context_state.h\n"
9916 with
CHeaderWriter(filename
, comment
) as f
:
9917 f
.write("struct EnableFlags {\n")
9918 f
.write(" EnableFlags();\n")
9919 for capability
in _CAPABILITY_FLAGS
:
9920 f
.write(" bool %s;\n" % capability
['name'])
9922 self
.generated_cpp_filenames
.append(filename
)
9924 def WriteContextStateGetters(self
, f
, class_name
):
9925 """Writes the state getters."""
9926 for gl_type
in ["GLint", "GLfloat"]:
9928 bool %s::GetStateAs%s(
9929 GLenum pname, %s* params, GLsizei* num_written) const {
9931 """ % (class_name
, gl_type
, gl_type
))
9932 for state_name
in sorted(_STATES
.keys()):
9933 state
= _STATES
[state_name
]
9935 f
.write(" case %s:\n" % state
['enum'])
9936 f
.write(" *num_written = %d;\n" % len(state
['states']))
9937 f
.write(" if (params) {\n")
9938 for ndx
,item
in enumerate(state
['states']):
9939 f
.write(" params[%d] = static_cast<%s>(%s);\n" %
9940 (ndx
, gl_type
, item
['name']))
9942 f
.write(" return true;\n")
9944 for item
in state
['states']:
9945 f
.write(" case %s:\n" % item
['enum'])
9946 if isinstance(item
['default'], list):
9947 item_len
= len(item
['default'])
9948 f
.write(" *num_written = %d;\n" % item_len
)
9949 f
.write(" if (params) {\n")
9950 if item
['type'] == gl_type
:
9951 f
.write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9952 (item
['name'], item
['type'], item_len
))
9954 f
.write(" for (size_t i = 0; i < %s; ++i) {\n" %
9956 f
.write(" params[i] = %s;\n" %
9957 (GetGLGetTypeConversion(gl_type
, item
['type'],
9958 "%s[i]" % item
['name'])))
9961 f
.write(" *num_written = 1;\n")
9962 f
.write(" if (params) {\n")
9963 f
.write(" params[0] = %s;\n" %
9964 (GetGLGetTypeConversion(gl_type
, item
['type'],
9967 f
.write(" return true;\n")
9968 for capability
in _CAPABILITY_FLAGS
:
9969 f
.write(" case GL_%s:\n" % capability
['name'].upper())
9970 f
.write(" *num_written = 1;\n")
9971 f
.write(" if (params) {\n")
9973 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9974 (gl_type
, capability
['name']))
9976 f
.write(" return true;\n")
9977 f
.write(""" default:
9983 def WriteServiceContextStateImpl(self
, filename
):
9984 """Writes the context state service implementation."""
9985 comment
= "// It is included by context_state.cc\n"
9986 with
CHeaderWriter(filename
, comment
) as f
:
9988 for capability
in _CAPABILITY_FLAGS
:
9989 code
.append("%s(%s)" %
9990 (capability
['name'],
9991 ('false', 'true')['default' in capability
]))
9992 code
.append("cached_%s(%s)" %
9993 (capability
['name'],
9994 ('false', 'true')['default' in capability
]))
9995 f
.write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9999 f
.write("void ContextState::Initialize() {\n")
10000 for state_name
in sorted(_STATES
.keys()):
10001 state
= _STATES
[state_name
]
10002 for item
in state
['states']:
10003 if isinstance(item
['default'], list):
10004 for ndx
, value
in enumerate(item
['default']):
10005 f
.write(" %s[%d] = %s;\n" % (item
['name'], ndx
, value
))
10007 f
.write(" %s = %s;\n" % (item
['name'], item
['default']))
10008 if item
.get('cached', False):
10009 if isinstance(item
['default'], list):
10010 for ndx
, value
in enumerate(item
['default']):
10011 f
.write(" cached_%s[%d] = %s;\n" % (item
['name'], ndx
, value
))
10013 f
.write(" cached_%s = %s;\n" % (item
['name'], item
['default']))
10017 void ContextState::InitCapabilities(const ContextState* prev_state) const {
10019 def WriteCapabilities(test_prev
, es3_caps
):
10020 for capability
in _CAPABILITY_FLAGS
:
10021 capability_name
= capability
['name']
10022 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10023 if capability_es3
and not es3_caps
or not capability_es3
and es3_caps
:
10026 f
.write(""" if (prev_state->enable_flags.cached_%s !=
10027 enable_flags.cached_%s) {\n""" %
10028 (capability_name
, capability_name
))
10029 f
.write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
10030 (capability_name
.upper(), capability_name
))
10034 f
.write(" if (prev_state) {")
10035 WriteCapabilities(True, False)
10036 f
.write(" if (feature_info_->IsES3Capable()) {\n")
10037 WriteCapabilities(True, True)
10039 f
.write(" } else {")
10040 WriteCapabilities(False, False)
10041 f
.write(" if (feature_info_->IsES3Capable()) {\n")
10042 WriteCapabilities(False, True)
10047 void ContextState::InitState(const ContextState *prev_state) const {
10050 def WriteStates(test_prev
):
10051 # We need to sort the keys so the expectations match
10052 for state_name
in sorted(_STATES
.keys()):
10053 state
= _STATES
[state_name
]
10054 if state
['type'] == 'FrontBack':
10055 num_states
= len(state
['states'])
10056 for ndx
, group
in enumerate(Grouper(num_states
/ 2,
10061 for place
, item
in enumerate(group
):
10062 item_name
= CachedStateName(item
)
10063 args
.append('%s' % item_name
)
10067 f
.write("(%s != prev_state->%s)" % (item_name
, item_name
))
10071 " gl%s(%s, %s);\n" %
10072 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
],
10074 elif state
['type'] == 'NamedParameter':
10075 for item
in state
['states']:
10076 item_name
= CachedStateName(item
)
10078 if 'extension_flag' in item
:
10079 f
.write(" if (feature_info_->feature_flags().%s) {\n " %
10080 item
['extension_flag'])
10082 if isinstance(item
['default'], list):
10083 f
.write(" if (memcmp(prev_state->%s, %s, "
10084 "sizeof(%s) * %d)) {\n" %
10085 (item_name
, item_name
, item
['type'],
10086 len(item
['default'])))
10088 f
.write(" if (prev_state->%s != %s) {\n " %
10089 (item_name
, item_name
))
10090 if 'gl_version_flag' in item
:
10091 item_name
= item
['gl_version_flag']
10093 if item_name
[0] == '!':
10095 item_name
= item_name
[1:]
10096 f
.write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10097 (inverted
, item_name
))
10098 f
.write(" gl%s(%s, %s);\n" %
10101 if 'enum_set' in item
else item
['enum']),
10103 if 'gl_version_flag' in item
:
10106 if 'extension_flag' in item
:
10109 if 'extension_flag' in item
:
10112 if 'extension_flag' in state
:
10113 f
.write(" if (feature_info_->feature_flags().%s)\n " %
10114 state
['extension_flag'])
10118 for place
, item
in enumerate(state
['states']):
10119 item_name
= CachedStateName(item
)
10120 args
.append('%s' % item_name
)
10124 f
.write("(%s != prev_state->%s)" %
10125 (item_name
, item_name
))
10128 f
.write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
10130 f
.write(" if (prev_state) {")
10132 f
.write(" } else {")
10137 f
.write("""bool ContextState::GetEnabled(GLenum cap) const {
10140 for capability
in _CAPABILITY_FLAGS
:
10141 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10142 f
.write(" return enable_flags.%s;\n" % capability
['name'])
10143 f
.write(""" default:
10149 self
.WriteContextStateGetters(f
, "ContextState")
10150 self
.generated_cpp_filenames
.append(filename
)
10152 def WriteClientContextStateImpl(self
, filename
):
10153 """Writes the context state client side implementation."""
10154 comment
= "// It is included by client_context_state.cc\n"
10155 with
CHeaderWriter(filename
, comment
) as f
:
10157 for capability
in _CAPABILITY_FLAGS
:
10158 code
.append("%s(%s)" %
10159 (capability
['name'],
10160 ('false', 'true')['default' in capability
]))
10162 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10167 bool ClientContextState::SetCapabilityState(
10168 GLenum cap, bool enabled, bool* changed) {
10172 for capability
in _CAPABILITY_FLAGS
:
10173 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10174 f
.write(""" if (enable_flags.%(name)s != enabled) {
10176 enable_flags.%(name)s = enabled;
10180 f
.write(""" default:
10185 f
.write("""bool ClientContextState::GetEnabled(
10186 GLenum cap, bool* enabled) const {
10189 for capability
in _CAPABILITY_FLAGS
:
10190 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10191 f
.write(" *enabled = enable_flags.%s;\n" % capability
['name'])
10192 f
.write(" return true;\n")
10193 f
.write(""" default:
10198 self
.generated_cpp_filenames
.append(filename
)
10200 def WriteServiceImplementation(self
, filename
):
10201 """Writes the service decorder implementation."""
10202 comment
= "// It is included by gles2_cmd_decoder.cc\n"
10203 with
CHeaderWriter(filename
, comment
) as f
:
10204 for func
in self
.functions
:
10206 #gen_cmd = func.GetInfo('gen_cmd')
10207 #if gen_cmd == True or gen_cmd == None:
10208 func
.WriteServiceImplementation(f
)
10211 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10214 for capability
in _CAPABILITY_FLAGS
:
10215 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10216 if 'state_flag' in capability
:
10219 state_.enable_flags.%(name)s = enabled;
10220 if (state_.enable_flags.cached_%(name)s != enabled
10221 || state_.ignore_cached_state) {
10222 %(state_flag)s = true;
10228 state_.enable_flags.%(name)s = enabled;
10229 if (state_.enable_flags.cached_%(name)s != enabled
10230 || state_.ignore_cached_state) {
10231 state_.enable_flags.cached_%(name)s = enabled;
10236 f
.write(""" default:
10242 self
.generated_cpp_filenames
.append(filename
)
10244 def WriteServiceUnitTests(self
, filename_pattern
):
10245 """Writes the service decorder unit tests."""
10246 num_tests
= len(self
.functions
)
10247 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
10249 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
10251 filename
= filename_pattern
% count
10252 comment
= "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" \
10254 with
CHeaderWriter(filename
, comment
) as f
:
10255 test_name
= 'GLES2DecoderTest%d' % count
10256 end
= test_num
+ FUNCTIONS_PER_FILE
10257 if end
> num_tests
:
10259 for idx
in range(test_num
, end
):
10260 func
= self
.functions
[idx
]
10262 # Do any filtering of the functions here, so that the functions
10263 # will not move between the numbered files if filtering properties
10265 if func
.GetInfo('extension_flag'):
10269 #gen_cmd = func.GetInfo('gen_cmd')
10270 #if gen_cmd == True or gen_cmd == None:
10271 if func
.GetInfo('unit_test') == False:
10272 f
.write("// TODO(gman): %s\n" % func
.name
)
10274 func
.WriteServiceUnitTest(f
, {
10275 'test_name': test_name
10277 self
.generated_cpp_filenames
.append(filename
)
10279 comment
= "// It is included by gles2_cmd_decoder_unittest_base.cc\n"
10280 filename
= filename_pattern
% 0
10281 with
CHeaderWriter(filename
, comment
) as f
:
10283 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10284 bool es3_capable) {""")
10285 for capability
in _CAPABILITY_FLAGS
:
10286 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10287 if not capability_es3
:
10288 f
.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10289 (capability
['name'].upper(),
10290 ('false', 'true')['default' in capability
]))
10292 f
.write(" if (es3_capable) {")
10293 for capability
in _CAPABILITY_FLAGS
:
10294 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10296 f
.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10297 (capability
['name'].upper(),
10298 ('false', 'true')['default' in capability
]))
10302 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10304 # We need to sort the keys so the expectations match
10305 for state_name
in sorted(_STATES
.keys()):
10306 state
= _STATES
[state_name
]
10307 if state
['type'] == 'FrontBack':
10308 num_states
= len(state
['states'])
10309 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
10312 if 'expected' in item
:
10313 args
.append(item
['expected'])
10315 args
.append(item
['default'])
10317 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10318 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
10319 f
.write(" .Times(1)\n")
10320 f
.write(" .RetiresOnSaturation();\n")
10321 elif state
['type'] == 'NamedParameter':
10322 for item
in state
['states']:
10323 if 'extension_flag' in item
:
10324 f
.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10325 item
['extension_flag'])
10327 expect_value
= item
['default']
10328 if isinstance(expect_value
, list):
10329 # TODO: Currently we do not check array values.
10333 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10336 if 'enum_set' in item
else item
['enum']),
10338 f
.write(" .Times(1)\n")
10339 f
.write(" .RetiresOnSaturation();\n")
10340 if 'extension_flag' in item
:
10343 if 'extension_flag' in state
:
10344 f
.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10345 state
['extension_flag'])
10348 for item
in state
['states']:
10349 if 'expected' in item
:
10350 args
.append(item
['expected'])
10352 args
.append(item
['default'])
10353 # TODO: Currently we do not check array values.
10354 args
= ["_" if isinstance(arg
, list) else arg
for arg
in args
]
10355 f
.write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10356 (state
['func'], ", ".join(args
)))
10357 f
.write(" .Times(1)\n")
10358 f
.write(" .RetiresOnSaturation();\n")
10359 if 'extension_flag' in state
:
10362 self
.generated_cpp_filenames
.append(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 comment
= "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n"
10372 with
CHeaderWriter(filename
, comment
) as f
:
10373 for func
in functions
:
10375 if func
.GetInfo('unit_test') == False:
10376 f
.write("// TODO(gman): %s\n" % func
.name
)
10378 extension
= ToCamelCase(
10379 ToGLExtensionString(func
.GetInfo('extension_flag')))
10380 func
.WriteServiceUnitTest(f
, {
10381 'test_name': 'GLES2DecoderTestWith%s' % extension
10383 self
.generated_cpp_filenames
.append(filename
)
10385 def WriteGLES2Header(self
, filename
):
10386 """Writes the GLES2 header."""
10387 comment
= "// This file contains Chromium-specific GLES2 declarations.\n\n"
10388 with
CHeaderWriter(filename
, comment
) as f
:
10389 for func
in self
.original_functions
:
10390 func
.WriteGLES2Header(f
)
10392 self
.generated_cpp_filenames
.append(filename
)
10394 def WriteGLES2CLibImplementation(self
, filename
):
10395 """Writes the GLES2 c lib implementation."""
10396 comment
= "// These functions emulate GLES2 over command buffers.\n"
10397 with
CHeaderWriter(filename
, comment
) as f
:
10398 for func
in self
.original_functions
:
10399 func
.WriteGLES2CLibImplementation(f
)
10403 extern const NameToFunc g_gles2_function_table[] = {
10405 for func
in self
.original_functions
:
10407 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10408 (func
.name
, func
.name
))
10409 f
.write(""" { NULL, NULL, },
10412 } // namespace gles2
10414 self
.generated_cpp_filenames
.append(filename
)
10416 def WriteGLES2InterfaceHeader(self
, filename
):
10417 """Writes the GLES2 interface header."""
10418 comment
= ("// This file is included by gles2_interface.h to declare the\n"
10419 "// GL api functions.\n")
10420 with
CHeaderWriter(filename
, comment
) as f
:
10421 for func
in self
.original_functions
:
10422 func
.WriteGLES2InterfaceHeader(f
)
10423 self
.generated_cpp_filenames
.append(filename
)
10425 def WriteMojoGLES2ImplHeader(self
, filename
):
10426 """Writes the Mojo GLES2 implementation header."""
10427 comment
= ("// This file is included by gles2_interface.h to declare the\n"
10428 "// GL api functions.\n")
10430 #include "gpu/command_buffer/client/gles2_interface.h"
10431 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10435 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10437 explicit MojoGLES2Impl(MojoGLES2Context context) {
10438 context_ = context;
10440 ~MojoGLES2Impl() override {}
10442 with
CHeaderWriter(filename
, comment
) as f
:
10444 for func
in self
.original_functions
:
10445 func
.WriteMojoGLES2ImplHeader(f
)
10448 MojoGLES2Context context_;
10451 } // namespace mojo
10454 self
.generated_cpp_filenames
.append(filename
)
10456 def WriteMojoGLES2Impl(self
, filename
):
10457 """Writes the Mojo GLES2 implementation."""
10459 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10461 #include "base/logging.h"
10462 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_extension.h"
10463 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10468 with
CWriter(filename
) as f
:
10470 for func
in self
.original_functions
:
10471 func
.WriteMojoGLES2Impl(f
)
10474 } // namespace mojo
10477 self
.generated_cpp_filenames
.append(filename
)
10479 def WriteGLES2InterfaceStub(self
, filename
):
10480 """Writes the GLES2 interface stub header."""
10481 comment
= "// This file is included by gles2_interface_stub.h.\n"
10482 with
CHeaderWriter(filename
, comment
) as f
:
10483 for func
in self
.original_functions
:
10484 func
.WriteGLES2InterfaceStub(f
)
10485 self
.generated_cpp_filenames
.append(filename
)
10487 def WriteGLES2InterfaceStubImpl(self
, filename
):
10488 """Writes the GLES2 interface header."""
10489 comment
= "// This file is included by gles2_interface_stub.cc.\n"
10490 with
CHeaderWriter(filename
, comment
) as f
:
10491 for func
in self
.original_functions
:
10492 func
.WriteGLES2InterfaceStubImpl(f
)
10493 self
.generated_cpp_filenames
.append(filename
)
10495 def WriteGLES2ImplementationHeader(self
, filename
):
10496 """Writes the GLES2 Implementation header."""
10498 ("// This file is included by gles2_implementation.h to declare the\n"
10499 "// GL api functions.\n")
10500 with
CHeaderWriter(filename
, comment
) as f
:
10501 for func
in self
.original_functions
:
10502 func
.WriteGLES2ImplementationHeader(f
)
10503 self
.generated_cpp_filenames
.append(filename
)
10505 def WriteGLES2Implementation(self
, filename
):
10506 """Writes the GLES2 Implementation."""
10508 ("// This file is included by gles2_implementation.cc to define the\n"
10509 "// GL api functions.\n")
10510 with
CHeaderWriter(filename
, comment
) as f
:
10511 for func
in self
.original_functions
:
10512 func
.WriteGLES2Implementation(f
)
10513 self
.generated_cpp_filenames
.append(filename
)
10515 def WriteGLES2TraceImplementationHeader(self
, filename
):
10516 """Writes the GLES2 Trace Implementation header."""
10517 comment
= "// This file is included by gles2_trace_implementation.h\n"
10518 with
CHeaderWriter(filename
, comment
) as f
:
10519 for func
in self
.original_functions
:
10520 func
.WriteGLES2TraceImplementationHeader(f
)
10521 self
.generated_cpp_filenames
.append(filename
)
10523 def WriteGLES2TraceImplementation(self
, filename
):
10524 """Writes the GLES2 Trace Implementation."""
10525 comment
= "// This file is included by gles2_trace_implementation.cc\n"
10526 with
CHeaderWriter(filename
, comment
) as f
:
10527 for func
in self
.original_functions
:
10528 func
.WriteGLES2TraceImplementation(f
)
10529 self
.generated_cpp_filenames
.append(filename
)
10531 def WriteGLES2ImplementationUnitTests(self
, filename
):
10532 """Writes the GLES2 helper header."""
10534 ("// This file is included by gles2_implementation.h to declare the\n"
10535 "// GL api functions.\n")
10536 with
CHeaderWriter(filename
, comment
) as f
:
10537 for func
in self
.original_functions
:
10538 func
.WriteGLES2ImplementationUnitTest(f
)
10539 self
.generated_cpp_filenames
.append(filename
)
10541 def WriteServiceUtilsHeader(self
, filename
):
10542 """Writes the gles2 auto generated utility header."""
10543 with
CHeaderWriter(filename
) as f
:
10544 for name
in sorted(_NAMED_TYPE_INFO
.keys()):
10545 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10546 if named_type
.IsConstant():
10548 f
.write("ValueValidator<%s> %s;\n" %
10549 (named_type
.GetType(), ToUnderscore(name
)))
10551 self
.generated_cpp_filenames
.append(filename
)
10553 def WriteServiceUtilsImplementation(self
, filename
):
10554 """Writes the gles2 auto generated utility implementation."""
10555 with
CHeaderWriter(filename
) as f
:
10556 names
= sorted(_NAMED_TYPE_INFO
.keys())
10558 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10559 if named_type
.IsConstant():
10561 if named_type
.GetValidValues():
10562 f
.write("static const %s valid_%s_table[] = {\n" %
10563 (named_type
.GetType(), ToUnderscore(name
)))
10564 for value
in named_type
.GetValidValues():
10565 f
.write(" %s,\n" % value
)
10568 if named_type
.GetValidValuesES3():
10569 f
.write("static const %s valid_%s_table_es3[] = {\n" %
10570 (named_type
.GetType(), ToUnderscore(name
)))
10571 for value
in named_type
.GetValidValuesES3():
10572 f
.write(" %s,\n" % value
)
10575 if named_type
.GetDeprecatedValuesES3():
10576 f
.write("static const %s deprecated_%s_table_es3[] = {\n" %
10577 (named_type
.GetType(), ToUnderscore(name
)))
10578 for value
in named_type
.GetDeprecatedValuesES3():
10579 f
.write(" %s,\n" % value
)
10582 f
.write("Validators::Validators()")
10584 for count
, name
in enumerate(names
):
10585 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10586 if named_type
.IsConstant():
10588 if named_type
.GetValidValues():
10589 code
= """%(pre)s%(name)s(
10590 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10592 code
= "%(pre)s%(name)s()"
10594 'name': ToUnderscore(name
),
10601 f
.write("void Validators::UpdateValuesES3() {\n")
10603 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10604 if named_type
.GetDeprecatedValuesES3():
10605 code
= """ %(name)s.RemoveValues(
10606 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10609 'name': ToUnderscore(name
),
10611 if named_type
.GetValidValuesES3():
10612 code
= """ %(name)s.AddValues(
10613 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10616 'name': ToUnderscore(name
),
10619 self
.generated_cpp_filenames
.append(filename
)
10621 def WriteCommonUtilsHeader(self
, filename
):
10622 """Writes the gles2 common utility header."""
10623 with
CHeaderWriter(filename
) as f
:
10624 type_infos
= sorted(_NAMED_TYPE_INFO
.keys())
10625 for type_info
in type_infos
:
10626 if _NAMED_TYPE_INFO
[type_info
]['type'] == 'GLenum':
10627 f
.write("static std::string GetString%s(uint32_t value);\n" %
10630 self
.generated_cpp_filenames
.append(filename
)
10632 def WriteCommonUtilsImpl(self
, filename
):
10633 """Writes the gles2 common utility header."""
10634 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10636 for fname
in ['third_party/khronos/GLES2/gl2.h',
10637 'third_party/khronos/GLES2/gl2ext.h',
10638 'third_party/khronos/GLES3/gl3.h',
10639 'gpu/GLES2/gl2chromium.h',
10640 'gpu/GLES2/gl2extchromium.h']:
10641 lines
= open(fname
).readlines()
10643 m
= enum_re
.match(line
)
10647 if len(value
) <= 10:
10648 if not value
in dict:
10650 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10651 elif dict[value
] != name
and (name
.endswith('_CHROMIUM') or
10652 dict[value
].endswith('_CHROMIUM')):
10653 self
.Error("code collision: %s and %s have the same code %s" %
10654 (dict[value
], name
, value
))
10656 with
CHeaderWriter(filename
) as f
:
10657 f
.write("static const GLES2Util::EnumToString "
10658 "enum_to_string_table[] = {\n")
10660 f
.write(' { %s, "%s", },\n' % (value
, dict[value
]))
10663 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10664 enum_to_string_table;
10665 const size_t GLES2Util::enum_to_string_table_len_ =
10666 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10670 enums
= sorted(_NAMED_TYPE_INFO
.keys())
10672 if _NAMED_TYPE_INFO
[enum
]['type'] == 'GLenum':
10673 f
.write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10675 valid_list
= _NAMED_TYPE_INFO
[enum
]['valid']
10676 if 'valid_es3' in _NAMED_TYPE_INFO
[enum
]:
10677 valid_list
= valid_list
+ _NAMED_TYPE_INFO
[enum
]['valid_es3']
10678 assert len(valid_list
) == len(set(valid_list
))
10679 if len(valid_list
) > 0:
10680 f
.write(" static const EnumToString string_table[] = {\n")
10681 for value
in valid_list
:
10682 f
.write(' { %s, "%s" },\n' % (value
, value
))
10684 return GLES2Util::GetQualifiedEnumString(
10685 string_table, arraysize(string_table), value);
10690 f
.write(""" return GLES2Util::GetQualifiedEnumString(
10695 self
.generated_cpp_filenames
.append(filename
)
10697 def WritePepperGLES2Interface(self
, filename
, dev
):
10698 """Writes the Pepper OpenGLES interface definition."""
10699 with
CWriter(filename
) as f
:
10700 f
.write("label Chrome {\n")
10701 f
.write(" M39 = 1.0\n")
10705 # Declare GL types.
10706 f
.write("[version=1.0]\n")
10707 f
.write("describe {\n")
10708 for gltype
in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10709 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10710 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10711 'GLubyte', 'GLuint', 'GLushort']:
10712 f
.write(" %s;\n" % gltype
)
10713 f
.write(" %s_ptr_t;\n" % gltype
)
10716 # C level typedefs.
10717 f
.write("#inline c\n")
10718 f
.write("#include \"ppapi/c/pp_resource.h\"\n")
10720 f
.write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10722 f
.write("\n#ifndef __gl2_h_\n")
10723 for (k
, v
) in _GL_TYPES
.iteritems():
10724 f
.write("typedef %s %s;\n" % (v
, k
))
10725 f
.write("#ifdef _WIN64\n")
10726 for (k
, v
) in _GL_TYPES_64
.iteritems():
10727 f
.write("typedef %s %s;\n" % (v
, k
))
10729 for (k
, v
) in _GL_TYPES_32
.iteritems():
10730 f
.write("typedef %s %s;\n" % (v
, k
))
10731 f
.write("#endif // _WIN64\n")
10732 f
.write("#endif // __gl2_h_\n\n")
10733 f
.write("#endinl\n")
10735 for interface
in self
.pepper_interfaces
:
10736 if interface
.dev
!= dev
:
10738 # Historically, we provide OpenGLES2 interfaces with struct
10739 # namespace. Not to break code which uses the interface as
10740 # "struct OpenGLES2", we put it in struct namespace.
10741 f
.write('\n[macro="%s", force_struct_namespace]\n' %
10742 interface
.GetInterfaceName())
10743 f
.write("interface %s {\n" % interface
.GetStructName())
10744 for func
in self
.original_functions
:
10745 if not func
.InPepperInterface(interface
):
10748 ret_type
= func
.MapCTypeToPepperIdlType(func
.return_type
,
10749 is_for_return_type
=True)
10750 func_prefix
= " %s %s(" % (ret_type
, func
.GetPepperName())
10751 f
.write(func_prefix
)
10752 f
.write("[in] PP_Resource context")
10753 for arg
in func
.MakeTypedPepperIdlArgStrings():
10754 f
.write(",\n" + " " * len(func_prefix
) + arg
)
10758 def WritePepperGLES2Implementation(self
, filename
):
10759 """Writes the Pepper OpenGLES interface implementation."""
10760 with
CWriter(filename
) as f
:
10761 f
.write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10762 f
.write("#include \"base/logging.h\"\n")
10763 f
.write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10764 f
.write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10765 f
.write("#include \"ppapi/thunk/enter.h\"\n\n")
10767 f
.write("namespace ppapi {\n\n")
10768 f
.write("namespace {\n\n")
10770 f
.write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10773 f
.write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10775 f
.write(" DCHECK(enter);\n")
10776 f
.write(" DCHECK(enter->succeeded());\n")
10777 f
.write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10778 "gles2_impl();\n");
10781 for func
in self
.original_functions
:
10782 if not func
.InAnyPepperExtension():
10785 original_arg
= func
.MakeTypedPepperArgString("")
10786 context_arg
= "PP_Resource context_id"
10787 if len(original_arg
):
10788 arg
= context_arg
+ ", " + original_arg
10791 f
.write("%s %s(%s) {\n" %
10792 (func
.return_type
, func
.GetPepperName(), arg
))
10793 f
.write(" Enter3D enter(context_id, true);\n")
10794 f
.write(" if (enter.succeeded()) {\n")
10796 return_str
= "" if func
.return_type
== "void" else "return "
10797 f
.write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10798 (return_str
, func
.original_name
,
10799 func
.MakeOriginalArgString("")))
10801 if func
.return_type
== "void":
10804 f
.write(" else {\n")
10805 f
.write(" return %s;\n" % func
.GetErrorReturnString())
10809 f
.write("} // namespace\n")
10811 for interface
in self
.pepper_interfaces
:
10812 f
.write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10813 (interface
.GetStructName(), interface
.GetName()))
10814 f
.write(" static const struct %s "
10815 "ppb_opengles2 = {\n" % interface
.GetStructName())
10817 f
.write(",\n &".join(
10818 f
.GetPepperName() for f
in self
.original_functions
10819 if f
.InPepperInterface(interface
)))
10823 f
.write(" return &ppb_opengles2;\n")
10826 f
.write("} // namespace ppapi\n")
10827 self
.generated_cpp_filenames
.append(filename
)
10829 def WriteGLES2ToPPAPIBridge(self
, filename
):
10830 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10831 with
CWriter(filename
) as f
:
10832 f
.write("#ifndef GL_GLEXT_PROTOTYPES\n")
10833 f
.write("#define GL_GLEXT_PROTOTYPES\n")
10834 f
.write("#endif\n")
10835 f
.write("#include <GLES2/gl2.h>\n")
10836 f
.write("#include <GLES2/gl2ext.h>\n")
10837 f
.write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10839 for func
in self
.original_functions
:
10840 if not func
.InAnyPepperExtension():
10843 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
10845 f
.write("%s GL_APIENTRY gl%s(%s) {\n" %
10846 (func
.return_type
, func
.GetPepperName(),
10847 func
.MakeTypedPepperArgString("")))
10848 return_str
= "" if func
.return_type
== "void" else "return "
10849 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
10850 original_arg
= func
.MakeOriginalArgString("")
10851 context_arg
= "glGetCurrentContextPPAPI()"
10852 if len(original_arg
):
10853 arg
= context_arg
+ ", " + original_arg
10856 if interface
.GetName():
10857 f
.write(" const struct %s* ext = %s;\n" %
10858 (interface
.GetStructName(), interface_str
))
10859 f
.write(" if (ext)\n")
10860 f
.write(" %sext->%s(%s);\n" %
10861 (return_str
, func
.GetPepperName(), arg
))
10863 f
.write(" %s0;\n" % return_str
)
10865 f
.write(" %s%s->%s(%s);\n" %
10866 (return_str
, interface_str
, func
.GetPepperName(), arg
))
10868 self
.generated_cpp_filenames
.append(filename
)
10870 def WriteMojoGLCallVisitor(self
, filename
):
10871 """Provides the GL implementation for mojo"""
10872 with
CWriter(filename
) as f
:
10873 for func
in self
.original_functions
:
10874 if not func
.IsCoreGLFunction():
10876 f
.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10877 (func
.name
, func
.return_type
,
10878 func
.MakeTypedOriginalArgString(""),
10879 func
.MakeOriginalArgString("")))
10880 self
.generated_cpp_filenames
.append(filename
)
10882 def WriteMojoGLCallVisitorForExtension(self
, filename
):
10883 """Provides the GL implementation for mojo for all extensions"""
10884 with
CWriter(filename
) as f
:
10885 for func
in self
.original_functions
:
10886 if not func
.GetInfo("extension"):
10888 if func
.IsUnsafe():
10890 f
.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10891 (func
.name
, func
.return_type
,
10892 func
.MakeTypedOriginalArgString(""),
10893 func
.MakeOriginalArgString("")))
10894 self
.generated_cpp_filenames
.append(filename
)
10896 def Format(generated_files
):
10897 formatter
= "clang-format"
10898 if platform
.system() == "Windows":
10899 formatter
+= ".bat"
10900 for filename
in generated_files
:
10901 call([formatter
, "-i", "-style=chromium", filename
])
10904 """This is the main function."""
10905 parser
= OptionParser()
10908 help="base directory for resulting files, under chrome/src. default is "
10909 "empty. Use this if you want the result stored under gen.")
10911 "-v", "--verbose", action
="store_true",
10912 help="prints more output.")
10914 (options
, args
) = parser
.parse_args(args
=argv
)
10916 # Add in states and capabilites to GLState
10917 gl_state_valid
= _NAMED_TYPE_INFO
['GLState']['valid']
10918 for state_name
in sorted(_STATES
.keys()):
10919 state
= _STATES
[state_name
]
10920 if 'extension_flag' in state
:
10922 if 'enum' in state
:
10923 if not state
['enum'] in gl_state_valid
:
10924 gl_state_valid
.append(state
['enum'])
10926 for item
in state
['states']:
10927 if 'extension_flag' in item
:
10929 if not item
['enum'] in gl_state_valid
:
10930 gl_state_valid
.append(item
['enum'])
10931 for capability
in _CAPABILITY_FLAGS
:
10932 valid_value
= "GL_%s" % capability
['name'].upper()
10933 if not valid_value
in gl_state_valid
:
10934 gl_state_valid
.append(valid_value
)
10936 # This script lives under gpu/command_buffer, cd to base directory.
10937 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
10938 base_dir
= os
.getcwd()
10939 gen
= GLGenerator(options
.verbose
)
10940 gen
.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10942 # Support generating files under gen/
10943 if options
.output_dir
!= None:
10944 os
.chdir(options
.output_dir
)
10946 gen
.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10947 gen
.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10948 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10949 gen
.WritePepperGLES2Implementation(
10950 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10952 gen
.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10953 gen
.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10954 gen
.WriteFormatTest(
10955 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10956 gen
.WriteGLES2InterfaceHeader(
10957 "gpu/command_buffer/client/gles2_interface_autogen.h")
10958 gen
.WriteMojoGLES2ImplHeader(
10959 "mojo/gpu/mojo_gles2_impl_autogen.h")
10960 gen
.WriteMojoGLES2Impl(
10961 "mojo/gpu/mojo_gles2_impl_autogen.cc")
10962 gen
.WriteGLES2InterfaceStub(
10963 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10964 gen
.WriteGLES2InterfaceStubImpl(
10965 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10966 gen
.WriteGLES2ImplementationHeader(
10967 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10968 gen
.WriteGLES2Implementation(
10969 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10970 gen
.WriteGLES2ImplementationUnitTests(
10971 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10972 gen
.WriteGLES2TraceImplementationHeader(
10973 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10974 gen
.WriteGLES2TraceImplementation(
10975 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10976 gen
.WriteGLES2CLibImplementation(
10977 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10978 gen
.WriteCmdHelperHeader(
10979 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
10980 gen
.WriteServiceImplementation(
10981 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
10982 gen
.WriteServiceContextStateHeader(
10983 "gpu/command_buffer/service/context_state_autogen.h")
10984 gen
.WriteServiceContextStateImpl(
10985 "gpu/command_buffer/service/context_state_impl_autogen.h")
10986 gen
.WriteClientContextStateHeader(
10987 "gpu/command_buffer/client/client_context_state_autogen.h")
10988 gen
.WriteClientContextStateImpl(
10989 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
10990 gen
.WriteServiceUnitTests(
10991 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
10992 gen
.WriteServiceUnitTestsForExtensions(
10993 "gpu/command_buffer/service/"
10994 "gles2_cmd_decoder_unittest_extensions_autogen.h")
10995 gen
.WriteServiceUtilsHeader(
10996 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
10997 gen
.WriteServiceUtilsImplementation(
10998 "gpu/command_buffer/service/"
10999 "gles2_cmd_validation_implementation_autogen.h")
11000 gen
.WriteCommonUtilsHeader(
11001 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
11002 gen
.WriteCommonUtilsImpl(
11003 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
11004 gen
.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
11005 mojo_gles2_prefix
= ("third_party/mojo/src/mojo/public/c/gles2/"
11006 "gles2_call_visitor")
11007 gen
.WriteMojoGLCallVisitor(mojo_gles2_prefix
+ "_autogen.h")
11008 gen
.WriteMojoGLCallVisitorForExtension(
11009 mojo_gles2_prefix
+ "_chromium_extension_autogen.h")
11011 Format(gen
.generated_cpp_filenames
)
11014 print "%d errors" % gen
.errors
11019 if __name__
== '__main__':
11020 sys
.exit(main(sys
.argv
[1:]))