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',
816 'GL_MAX_3D_TEXTURE_SIZE',
817 'GL_MAX_ARRAY_TEXTURE_LAYERS',
818 'GL_MAX_COLOR_ATTACHMENTS',
819 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
820 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
821 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
822 'GL_MAX_DRAW_BUFFERS',
823 'GL_MAX_ELEMENT_INDEX',
824 'GL_MAX_ELEMENTS_INDICES',
825 'GL_MAX_ELEMENTS_VERTICES',
826 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
827 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
828 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
829 'GL_MAX_PROGRAM_TEXEL_OFFSET',
831 'GL_MAX_SERVER_WAIT_TIMEOUT',
832 'GL_MAX_TEXTURE_LOD_BIAS',
833 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
834 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
835 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
836 'GL_MAX_UNIFORM_BLOCK_SIZE',
837 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
838 'GL_MAX_VARYING_COMPONENTS',
839 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
840 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
841 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
842 'GL_MIN_PROGRAM_TEXEL_OFFSET',
845 'GL_NUM_PROGRAM_BINARY_FORMATS',
846 'GL_PACK_ROW_LENGTH',
847 'GL_PACK_SKIP_PIXELS',
849 'GL_PIXEL_PACK_BUFFER_BINDING',
850 'GL_PIXEL_UNPACK_BUFFER_BINDING',
851 'GL_PROGRAM_BINARY_FORMATS',
853 'GL_READ_FRAMEBUFFER_BINDING',
854 'GL_SAMPLER_BINDING',
855 'GL_TEXTURE_BINDING_2D_ARRAY',
856 'GL_TEXTURE_BINDING_3D',
857 'GL_TRANSFORM_FEEDBACK_BINDING',
858 'GL_TRANSFORM_FEEDBACK_ACTIVE',
859 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
860 'GL_TRANSFORM_FEEDBACK_PAUSED',
861 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
862 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
863 'GL_UNIFORM_BUFFER_BINDING',
864 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
865 'GL_UNIFORM_BUFFER_SIZE',
866 'GL_UNIFORM_BUFFER_START',
867 'GL_UNPACK_IMAGE_HEIGHT',
868 'GL_UNPACK_ROW_LENGTH',
869 'GL_UNPACK_SKIP_IMAGES',
870 'GL_UNPACK_SKIP_PIXELS',
871 'GL_UNPACK_SKIP_ROWS',
872 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
873 # 'GL_VERTEX_ARRAY_BINDING',
882 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
883 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
884 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
885 'GL_UNIFORM_BUFFER_BINDING',
886 'GL_UNIFORM_BUFFER_SIZE',
887 'GL_UNIFORM_BUFFER_START',
893 'GetTexParamTarget': {
897 'GL_TEXTURE_CUBE_MAP',
900 'GL_TEXTURE_2D_ARRAY',
904 'GL_PROXY_TEXTURE_CUBE_MAP',
912 'GL_COLOR_ATTACHMENT0',
913 'GL_COLOR_ATTACHMENT1',
914 'GL_COLOR_ATTACHMENT2',
915 'GL_COLOR_ATTACHMENT3',
916 'GL_COLOR_ATTACHMENT4',
917 'GL_COLOR_ATTACHMENT5',
918 'GL_COLOR_ATTACHMENT6',
919 'GL_COLOR_ATTACHMENT7',
920 'GL_COLOR_ATTACHMENT8',
921 'GL_COLOR_ATTACHMENT9',
922 'GL_COLOR_ATTACHMENT10',
923 'GL_COLOR_ATTACHMENT11',
924 'GL_COLOR_ATTACHMENT12',
925 'GL_COLOR_ATTACHMENT13',
926 'GL_COLOR_ATTACHMENT14',
927 'GL_COLOR_ATTACHMENT15',
937 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
938 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
939 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
940 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
941 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
942 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
945 'GL_PROXY_TEXTURE_CUBE_MAP',
952 'GL_TEXTURE_2D_ARRAY',
958 'TextureBindTarget': {
962 'GL_TEXTURE_CUBE_MAP',
966 'GL_TEXTURE_2D_ARRAY',
973 'TransformFeedbackBindTarget': {
976 'GL_TRANSFORM_FEEDBACK',
982 'TransformFeedbackPrimitiveMode': {
997 'GL_FRAGMENT_SHADER',
1000 'GL_GEOMETRY_SHADER',
1008 'GL_FRONT_AND_BACK',
1036 'GL_FUNC_REVERSE_SUBTRACT',
1052 'GL_ONE_MINUS_SRC_COLOR',
1054 'GL_ONE_MINUS_DST_COLOR',
1056 'GL_ONE_MINUS_SRC_ALPHA',
1058 'GL_ONE_MINUS_DST_ALPHA',
1059 'GL_CONSTANT_COLOR',
1060 'GL_ONE_MINUS_CONSTANT_COLOR',
1061 'GL_CONSTANT_ALPHA',
1062 'GL_ONE_MINUS_CONSTANT_ALPHA',
1063 'GL_SRC_ALPHA_SATURATE',
1072 'GL_ONE_MINUS_SRC_COLOR',
1074 'GL_ONE_MINUS_DST_COLOR',
1076 'GL_ONE_MINUS_SRC_ALPHA',
1078 'GL_ONE_MINUS_DST_ALPHA',
1079 'GL_CONSTANT_COLOR',
1080 'GL_ONE_MINUS_CONSTANT_COLOR',
1081 'GL_CONSTANT_ALPHA',
1082 'GL_ONE_MINUS_CONSTANT_ALPHA',
1087 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1088 if 'es3' not in cap
or cap
['es3'] != True],
1089 'valid_es3': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1090 if 'es3' in cap
and cap
['es3'] == True],
1103 'GL_TRIANGLE_STRIP',
1116 'GL_UNSIGNED_SHORT',
1125 'GetMaxIndexType': {
1129 'GL_UNSIGNED_SHORT',
1139 'GL_COLOR_ATTACHMENT0',
1140 'GL_DEPTH_ATTACHMENT',
1141 'GL_STENCIL_ATTACHMENT',
1144 'GL_DEPTH_STENCIL_ATTACHMENT',
1147 'BackbufferAttachment': {
1155 'BufferParameter': {
1162 'GL_BUFFER_ACCESS_FLAGS',
1166 'GL_PIXEL_PACK_BUFFER',
1169 'BufferParameter64': {
1173 'GL_BUFFER_MAP_LENGTH',
1174 'GL_BUFFER_MAP_OFFSET',
1177 'GL_PIXEL_PACK_BUFFER',
1183 'GL_INTERLEAVED_ATTRIBS',
1184 'GL_SEPARATE_ATTRIBS',
1187 'GL_PIXEL_PACK_BUFFER',
1190 'FrameBufferParameter': {
1193 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1194 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1195 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1196 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1199 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1200 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1201 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1202 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1203 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1204 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1205 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1206 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1207 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1213 'GL_PATH_PROJECTION_CHROMIUM',
1214 'GL_PATH_MODELVIEW_CHROMIUM',
1217 'ProgramParameter': {
1222 'GL_VALIDATE_STATUS',
1223 'GL_INFO_LOG_LENGTH',
1224 'GL_ATTACHED_SHADERS',
1225 'GL_ACTIVE_ATTRIBUTES',
1226 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1227 'GL_ACTIVE_UNIFORMS',
1228 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1231 'GL_ACTIVE_UNIFORM_BLOCKS',
1232 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1233 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1234 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1235 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1238 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1241 'QueryObjectParameter': {
1244 'GL_QUERY_RESULT_EXT',
1245 'GL_QUERY_RESULT_AVAILABLE_EXT',
1251 'GL_CURRENT_QUERY_EXT',
1257 'GL_ANY_SAMPLES_PASSED_EXT',
1258 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1259 'GL_COMMANDS_ISSUED_CHROMIUM',
1260 'GL_LATENCY_QUERY_CHROMIUM',
1261 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1262 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1263 'GL_COMMANDS_COMPLETED_CHROMIUM',
1266 'RenderBufferParameter': {
1269 'GL_RENDERBUFFER_RED_SIZE',
1270 'GL_RENDERBUFFER_GREEN_SIZE',
1271 'GL_RENDERBUFFER_BLUE_SIZE',
1272 'GL_RENDERBUFFER_ALPHA_SIZE',
1273 'GL_RENDERBUFFER_DEPTH_SIZE',
1274 'GL_RENDERBUFFER_STENCIL_SIZE',
1275 'GL_RENDERBUFFER_WIDTH',
1276 'GL_RENDERBUFFER_HEIGHT',
1277 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1280 'GL_RENDERBUFFER_SAMPLES',
1283 'InternalFormatParameter': {
1286 'GL_NUM_SAMPLE_COUNTS',
1290 'SamplerParameter': {
1293 'GL_TEXTURE_MAG_FILTER',
1294 'GL_TEXTURE_MIN_FILTER',
1295 'GL_TEXTURE_MIN_LOD',
1296 'GL_TEXTURE_MAX_LOD',
1297 'GL_TEXTURE_WRAP_S',
1298 'GL_TEXTURE_WRAP_T',
1299 'GL_TEXTURE_WRAP_R',
1300 'GL_TEXTURE_COMPARE_MODE',
1301 'GL_TEXTURE_COMPARE_FUNC',
1304 'GL_GENERATE_MIPMAP',
1307 'ShaderParameter': {
1312 'GL_COMPILE_STATUS',
1313 'GL_INFO_LOG_LENGTH',
1314 'GL_SHADER_SOURCE_LENGTH',
1315 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1318 'ShaderPrecision': {
1335 'GL_SHADING_LANGUAGE_VERSION',
1339 'TextureParameter': {
1342 'GL_TEXTURE_MAG_FILTER',
1343 'GL_TEXTURE_MIN_FILTER',
1344 'GL_TEXTURE_POOL_CHROMIUM',
1345 'GL_TEXTURE_WRAP_S',
1346 'GL_TEXTURE_WRAP_T',
1349 'GL_TEXTURE_BASE_LEVEL',
1350 'GL_TEXTURE_COMPARE_FUNC',
1351 'GL_TEXTURE_COMPARE_MODE',
1352 'GL_TEXTURE_IMMUTABLE_FORMAT',
1353 'GL_TEXTURE_IMMUTABLE_LEVELS',
1354 'GL_TEXTURE_MAX_LEVEL',
1355 'GL_TEXTURE_MAX_LOD',
1356 'GL_TEXTURE_MIN_LOD',
1357 'GL_TEXTURE_WRAP_R',
1360 'GL_GENERATE_MIPMAP',
1366 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1367 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1370 'TextureWrapMode': {
1374 'GL_MIRRORED_REPEAT',
1378 'TextureMinFilterMode': {
1383 'GL_NEAREST_MIPMAP_NEAREST',
1384 'GL_LINEAR_MIPMAP_NEAREST',
1385 'GL_NEAREST_MIPMAP_LINEAR',
1386 'GL_LINEAR_MIPMAP_LINEAR',
1389 'TextureMagFilterMode': {
1396 'TextureCompareFunc': {
1409 'TextureCompareMode': {
1413 'GL_COMPARE_REF_TO_TEXTURE',
1420 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1423 'VertexAttribute': {
1426 # some enum that the decoder actually passes through to GL needs
1427 # to be the first listed here since it's used in unit tests.
1428 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1429 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1430 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1431 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1432 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1433 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1434 'GL_CURRENT_VERTEX_ATTRIB',
1437 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1438 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1444 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1450 'GL_GENERATE_MIPMAP_HINT',
1453 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1456 'GL_PERSPECTIVE_CORRECTION_HINT',
1470 'GL_PACK_ALIGNMENT',
1471 'GL_UNPACK_ALIGNMENT',
1474 'GL_PACK_ROW_LENGTH',
1475 'GL_PACK_SKIP_PIXELS',
1476 'GL_PACK_SKIP_ROWS',
1477 'GL_UNPACK_ROW_LENGTH',
1478 'GL_UNPACK_IMAGE_HEIGHT',
1479 'GL_UNPACK_SKIP_PIXELS',
1480 'GL_UNPACK_SKIP_ROWS',
1481 'GL_UNPACK_SKIP_IMAGES',
1484 'GL_PACK_SWAP_BYTES',
1485 'GL_UNPACK_SWAP_BYTES',
1488 'PixelStoreAlignment': {
1501 'ReadPixelFormat': {
1520 'GL_UNSIGNED_SHORT_5_6_5',
1521 'GL_UNSIGNED_SHORT_4_4_4_4',
1522 'GL_UNSIGNED_SHORT_5_5_5_1',
1526 'GL_UNSIGNED_SHORT',
1532 'GL_UNSIGNED_INT_2_10_10_10_REV',
1533 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1534 'GL_UNSIGNED_INT_5_9_9_9_REV',
1535 'GL_UNSIGNED_INT_24_8',
1536 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1539 'GL_UNSIGNED_BYTE_3_3_2',
1548 'GL_UNSIGNED_SHORT',
1555 'GL_CONVEX_HULL_CHROMIUM',
1556 'GL_BOUNDING_BOX_CHROMIUM',
1563 'GL_COUNT_UP_CHROMIUM',
1564 'GL_COUNT_DOWN_CHROMIUM',
1570 'GL_PATH_STROKE_WIDTH_CHROMIUM',
1571 'GL_PATH_END_CAPS_CHROMIUM',
1572 'GL_PATH_JOIN_STYLE_CHROMIUM',
1573 'GL_PATH_MITER_LIMIT_CHROMIUM',
1574 'GL_PATH_STROKE_BOUND_CHROMIUM',
1577 'PathParameterCapValues': {
1581 'GL_SQUARE_CHROMIUM',
1582 'GL_ROUND_CHROMIUM',
1585 'PathParameterJoinValues': {
1588 'GL_MITER_REVERT_CHROMIUM',
1589 'GL_BEVEL_CHROMIUM',
1590 'GL_ROUND_CHROMIUM',
1597 'GL_UNSIGNED_SHORT_5_6_5',
1598 'GL_UNSIGNED_SHORT_4_4_4_4',
1599 'GL_UNSIGNED_SHORT_5_5_5_1',
1608 'GL_UNSIGNED_INT_2_10_10_10_REV',
1611 'GL_UNSIGNED_SHORT_5_6_5',
1612 'GL_UNSIGNED_SHORT_4_4_4_4',
1613 'GL_UNSIGNED_SHORT_5_5_5_1',
1616 'RenderBufferFormat': {
1622 'GL_DEPTH_COMPONENT16',
1623 'GL_STENCIL_INDEX8',
1651 'GL_DEPTH_COMPONENT24',
1652 'GL_DEPTH_COMPONENT32F',
1653 'GL_DEPTH24_STENCIL8',
1654 'GL_DEPTH32F_STENCIL8',
1657 'ShaderBinaryFormat': {
1680 'GL_LUMINANCE_ALPHA',
1691 'GL_DEPTH_COMPONENT',
1699 'TextureInternalFormat': {
1704 'GL_LUMINANCE_ALPHA',
1733 'GL_R11F_G11F_B10F',
1758 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1759 # We will reject them dynamically in GPU command buffer.
1760 'GL_DEPTH_COMPONENT16',
1761 'GL_DEPTH_COMPONENT24',
1762 'GL_DEPTH_COMPONENT32F',
1763 'GL_DEPTH24_STENCIL8',
1764 'GL_DEPTH32F_STENCIL8',
1771 'TextureInternalFormatStorage': {
1778 'GL_LUMINANCE8_EXT',
1779 'GL_LUMINANCE8_ALPHA8_EXT',
1807 'GL_R11F_G11F_B10F',
1830 'GL_DEPTH_COMPONENT16',
1831 'GL_DEPTH_COMPONENT24',
1832 'GL_DEPTH_COMPONENT32F',
1833 'GL_DEPTH24_STENCIL8',
1834 'GL_DEPTH32F_STENCIL8',
1835 'GL_COMPRESSED_R11_EAC',
1836 'GL_COMPRESSED_SIGNED_R11_EAC',
1837 'GL_COMPRESSED_RG11_EAC',
1838 'GL_COMPRESSED_SIGNED_RG11_EAC',
1839 'GL_COMPRESSED_RGB8_ETC2',
1840 'GL_COMPRESSED_SRGB8_ETC2',
1841 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1842 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1843 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1844 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1848 'GL_LUMINANCE8_EXT',
1849 'GL_LUMINANCE8_ALPHA8_EXT',
1851 'GL_LUMINANCE16F_EXT',
1852 'GL_LUMINANCE_ALPHA16F_EXT',
1854 'GL_LUMINANCE32F_EXT',
1855 'GL_LUMINANCE_ALPHA32F_EXT',
1858 'ImageInternalFormat': {
1862 'GL_RGB_YUV_420_CHROMIUM',
1870 'GL_SCANOUT_CHROMIUM'
1873 'ValueBufferTarget': {
1876 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1879 'SubscriptionTarget': {
1882 'GL_MOUSE_POSITION_CHROMIUM',
1885 'UniformParameter': {
1890 'GL_UNIFORM_NAME_LENGTH',
1891 'GL_UNIFORM_BLOCK_INDEX',
1892 'GL_UNIFORM_OFFSET',
1893 'GL_UNIFORM_ARRAY_STRIDE',
1894 'GL_UNIFORM_MATRIX_STRIDE',
1895 'GL_UNIFORM_IS_ROW_MAJOR',
1898 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1901 'UniformBlockParameter': {
1904 'GL_UNIFORM_BLOCK_BINDING',
1905 'GL_UNIFORM_BLOCK_DATA_SIZE',
1906 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1907 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1908 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1909 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1910 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1916 'VertexAttribType': {
1922 'GL_UNSIGNED_SHORT',
1923 # 'GL_FIXED', // This is not available on Desktop GL.
1930 'GL_INT_2_10_10_10_REV',
1931 'GL_UNSIGNED_INT_2_10_10_10_REV',
1937 'VertexAttribIType': {
1943 'GL_UNSIGNED_SHORT',
1954 'is_complete': True,
1962 'VertexAttribSize': {
1977 'is_complete': True,
1986 'type': 'GLboolean',
1987 'is_complete': True,
1998 'GL_GUILTY_CONTEXT_RESET_ARB',
1999 'GL_INNOCENT_CONTEXT_RESET_ARB',
2000 'GL_UNKNOWN_CONTEXT_RESET_ARB',
2005 'is_complete': True,
2007 'GL_SYNC_GPU_COMMANDS_COMPLETE',
2014 'type': 'GLbitfield',
2015 'is_complete': True,
2024 'type': 'GLbitfield',
2026 'GL_SYNC_FLUSH_COMMANDS_BIT',
2036 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
2038 'GL_SYNC_CONDITION',
2047 # This table specifies the different pepper interfaces that are supported for
2048 # GL commands. 'dev' is true if it's a dev interface.
2049 _PEPPER_INTERFACES
= [
2050 {'name': '', 'dev': False},
2051 {'name': 'InstancedArrays', 'dev': False},
2052 {'name': 'FramebufferBlit', 'dev': False},
2053 {'name': 'FramebufferMultisample', 'dev': False},
2054 {'name': 'ChromiumEnableFeature', 'dev': False},
2055 {'name': 'ChromiumMapSub', 'dev': False},
2056 {'name': 'Query', 'dev': False},
2057 {'name': 'VertexArrayObject', 'dev': False},
2058 {'name': 'DrawBuffers', 'dev': True},
2061 # A function info object specifies the type and other special data for the
2062 # command that will be generated. A base function info object is generated by
2063 # parsing the "cmd_buffer_functions.txt", one for each function in the
2064 # file. These function info objects can be augmented and their values can be
2065 # overridden by adding an object to the table below.
2067 # Must match function names specified in "cmd_buffer_functions.txt".
2069 # cmd_comment: A comment added to the cmd format.
2070 # type: defines which handler will be used to generate code.
2071 # decoder_func: defines which function to call in the decoder to execute the
2072 # corresponding GL command. If not specified the GL command will
2073 # be called directly.
2074 # gl_test_func: GL function that is expected to be called when testing.
2075 # cmd_args: The arguments to use for the command. This overrides generating
2076 # them based on the GL function arguments.
2077 # gen_cmd: Whether or not this function geneates a command. Default = True.
2078 # data_transfer_methods: Array of methods that are used for transfering the
2079 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
2080 # The default is 'immediate' if the command has one pointer
2081 # argument, otherwise 'shm'. One command is generated for each
2082 # transfer method. Affects only commands which are not of type
2083 # 'HandWritten', 'GETn' or 'GLcharN'.
2084 # Note: the command arguments that affect this are the final args,
2085 # taking cmd_args override into consideration.
2086 # impl_func: Whether or not to generate the GLES2Implementation part of this
2088 # impl_decl: Whether or not to generate the GLES2Implementation declaration
2090 # needs_size: If True a data_size field is added to the command.
2091 # count: The number of units per element. For PUTn or PUT types.
2092 # use_count_func: If True the actual data count needs to be computed; the count
2093 # argument specifies the maximum count.
2094 # unit_test: If False no service side unit test will be generated.
2095 # client_test: If False no client side unit test will be generated.
2096 # expectation: If False the unit test will have no expected calls.
2097 # gen_func: Name of function that generates GL resource for corresponding
2099 # states: array of states that get set by this function corresponding to
2100 # the given arguments
2101 # state_flag: name of flag that is set to true when function is called.
2102 # no_gl: no GL function is called.
2103 # valid_args: A dictionary of argument indices to args to use in unit tests
2104 # when they can not be automatically determined.
2105 # pepper_interface: The pepper interface that is used for this extension
2106 # pepper_name: The name of the function as exposed to pepper.
2107 # pepper_args: A string representing the argument list (what would appear in
2108 # C/C++ between the parentheses for the function declaration)
2109 # that the Pepper API expects for this function. Use this only if
2110 # the stable Pepper API differs from the GLES2 argument list.
2111 # invalid_test: False if no invalid test needed.
2112 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2113 # first_element_only: For PUT types, True if only the first element of an
2114 # array is used and we end up calling the single value
2115 # corresponding function. eg. TexParameteriv -> TexParameteri
2116 # extension: Function is an extension to GL and should not be exposed to
2117 # pepper unless pepper_interface is defined.
2118 # extension_flag: Function is an extension and should be enabled only when
2119 # the corresponding feature info flag is enabled. Implies
2120 # 'extension': True.
2121 # not_shared: For GENn types, True if objects can't be shared between contexts
2122 # unsafe: True = no validation is implemented on the service side and the
2123 # command is only available with --enable-unsafe-es3-apis.
2124 # id_mapping: A list of resource type names whose client side IDs need to be
2125 # mapped to service side IDs. This is only used for unsafe APIs.
2129 'decoder_func': 'DoActiveTexture',
2132 'client_test': False,
2134 'AttachShader': {'decoder_func': 'DoAttachShader'},
2135 'BindAttribLocation': {
2137 'data_transfer_methods': ['bucket'],
2142 'decoder_func': 'DoBindBuffer',
2143 'gen_func': 'GenBuffersARB',
2147 'id_mapping': [ 'Buffer' ],
2148 'gen_func': 'GenBuffersARB',
2151 'BindBufferRange': {
2153 'id_mapping': [ 'Buffer' ],
2154 'gen_func': 'GenBuffersARB',
2161 'BindFramebuffer': {
2163 'decoder_func': 'DoBindFramebuffer',
2164 'gl_test_func': 'glBindFramebufferEXT',
2165 'gen_func': 'GenFramebuffersEXT',
2168 'BindRenderbuffer': {
2170 'decoder_func': 'DoBindRenderbuffer',
2171 'gl_test_func': 'glBindRenderbufferEXT',
2172 'gen_func': 'GenRenderbuffersEXT',
2176 'id_mapping': [ 'Sampler' ],
2181 'decoder_func': 'DoBindTexture',
2182 'gen_func': 'GenTextures',
2183 # TODO(gman): remove this once client side caching works.
2184 'client_test': False,
2187 'BindTransformFeedback': {
2189 'id_mapping': [ 'TransformFeedback' ],
2192 'BlitFramebufferCHROMIUM': {
2193 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2195 'extension_flag': 'chromium_framebuffer_multisample',
2196 'pepper_interface': 'FramebufferBlit',
2197 'pepper_name': 'BlitFramebufferEXT',
2198 'defer_reads': True,
2199 'defer_draws': True,
2204 'data_transfer_methods': ['shm'],
2205 'client_test': False,
2210 'client_test': False,
2211 'decoder_func': 'DoBufferSubData',
2212 'data_transfer_methods': ['shm'],
2215 'CheckFramebufferStatus': {
2217 'decoder_func': 'DoCheckFramebufferStatus',
2218 'gl_test_func': 'glCheckFramebufferStatusEXT',
2219 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2220 'result': ['GLenum'],
2223 'decoder_func': 'DoClear',
2224 'defer_draws': True,
2229 'use_count_func': True,
2242 'use_count_func': True,
2253 'state': 'ClearColor',
2257 'state': 'ClearDepthf',
2258 'decoder_func': 'glClearDepth',
2259 'gl_test_func': 'glClearDepth',
2266 'data_transfer_methods': ['shm'],
2267 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2268 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2270 'result': ['GLenum'],
2275 'state': 'ColorMask',
2277 'expectation': False,
2279 'ConsumeTextureCHROMIUM': {
2280 'decoder_func': 'DoConsumeTextureCHROMIUM',
2283 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2285 'client_test': False,
2286 'extension': "CHROMIUM_texture_mailbox",
2290 'CopyBufferSubData': {
2293 'CreateAndConsumeTextureCHROMIUM': {
2294 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2296 'type': 'HandWritten',
2297 'data_transfer_methods': ['immediate'],
2299 'client_test': False,
2300 'extension': "CHROMIUM_texture_mailbox",
2304 'GenValuebuffersCHROMIUM': {
2306 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2307 'resource_type': 'Valuebuffer',
2308 'resource_types': 'Valuebuffers',
2313 'DeleteValuebuffersCHROMIUM': {
2315 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2316 'resource_type': 'Valuebuffer',
2317 'resource_types': 'Valuebuffers',
2322 'IsValuebufferCHROMIUM': {
2324 'decoder_func': 'DoIsValuebufferCHROMIUM',
2325 'expectation': False,
2329 'BindValuebufferCHROMIUM': {
2331 'decoder_func': 'DoBindValueBufferCHROMIUM',
2332 'gen_func': 'GenValueBuffersCHROMIUM',
2337 'SubscribeValueCHROMIUM': {
2338 'decoder_func': 'DoSubscribeValueCHROMIUM',
2343 'PopulateSubscribedValuesCHROMIUM': {
2344 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2349 'UniformValuebufferCHROMIUM': {
2350 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2357 'state': 'ClearStencil',
2359 'EnableFeatureCHROMIUM': {
2361 'data_transfer_methods': ['shm'],
2362 'decoder_func': 'DoEnableFeatureCHROMIUM',
2363 'expectation': False,
2364 'cmd_args': 'GLuint bucket_id, GLint* result',
2365 'result': ['GLint'],
2368 'pepper_interface': 'ChromiumEnableFeature',
2370 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2371 'CompressedTexImage2D': {
2373 'data_transfer_methods': ['bucket', 'shm'],
2376 'CompressedTexSubImage2D': {
2378 'data_transfer_methods': ['bucket', 'shm'],
2379 'decoder_func': 'DoCompressedTexSubImage2D',
2383 'decoder_func': 'DoCopyTexImage2D',
2385 'defer_reads': True,
2388 'CopyTexSubImage2D': {
2389 'decoder_func': 'DoCopyTexSubImage2D',
2390 'defer_reads': True,
2393 'CompressedTexImage3D': {
2395 'data_transfer_methods': ['bucket', 'shm'],
2399 'CompressedTexSubImage3D': {
2401 'data_transfer_methods': ['bucket', 'shm'],
2402 'decoder_func': 'DoCompressedTexSubImage3D',
2406 'CopyTexSubImage3D': {
2407 'defer_reads': True,
2411 'CreateImageCHROMIUM': {
2414 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2415 'GLenum internalformat',
2416 'result': ['GLuint'],
2417 'client_test': False,
2419 'expectation': False,
2420 'extension': "CHROMIUM_image",
2424 'DestroyImageCHROMIUM': {
2426 'client_test': False,
2428 'extension': "CHROMIUM_image",
2432 'CreateGpuMemoryBufferImageCHROMIUM': {
2435 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2436 'result': ['GLuint'],
2437 'client_test': False,
2439 'expectation': False,
2440 'extension': "CHROMIUM_image",
2446 'client_test': False,
2450 'client_test': False,
2454 'state': 'BlendColor',
2457 'type': 'StateSetRGBAlpha',
2458 'state': 'BlendEquation',
2460 '0': 'GL_FUNC_SUBTRACT'
2463 'BlendEquationSeparate': {
2465 'state': 'BlendEquation',
2467 '0': 'GL_FUNC_SUBTRACT'
2471 'type': 'StateSetRGBAlpha',
2472 'state': 'BlendFunc',
2474 'BlendFuncSeparate': {
2476 'state': 'BlendFunc',
2478 'BlendBarrierKHR': {
2479 'gl_test_func': 'glBlendBarrierKHR',
2481 'extension_flag': 'blend_equation_advanced',
2482 'client_test': False,
2484 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2486 'type': 'StateSetFrontBack',
2487 'state': 'StencilFunc',
2489 'StencilFuncSeparate': {
2490 'type': 'StateSetFrontBackSeparate',
2491 'state': 'StencilFunc',
2494 'type': 'StateSetFrontBack',
2495 'state': 'StencilOp',
2500 'StencilOpSeparate': {
2501 'type': 'StateSetFrontBackSeparate',
2502 'state': 'StencilOp',
2508 'type': 'StateSetNamedParameter',
2511 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2512 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2513 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2516 'state': 'LineWidth',
2523 'state': 'PolygonOffset',
2527 'gl_test_func': 'glDeleteBuffersARB',
2528 'resource_type': 'Buffer',
2529 'resource_types': 'Buffers',
2531 'DeleteFramebuffers': {
2533 'gl_test_func': 'glDeleteFramebuffersEXT',
2534 'resource_type': 'Framebuffer',
2535 'resource_types': 'Framebuffers',
2538 'DeleteProgram': { 'type': 'Delete' },
2539 'DeleteRenderbuffers': {
2541 'gl_test_func': 'glDeleteRenderbuffersEXT',
2542 'resource_type': 'Renderbuffer',
2543 'resource_types': 'Renderbuffers',
2548 'resource_type': 'Sampler',
2549 'resource_types': 'Samplers',
2552 'DeleteShader': { 'type': 'Delete' },
2555 'cmd_args': 'GLuint sync',
2556 'resource_type': 'Sync',
2561 'resource_type': 'Texture',
2562 'resource_types': 'Textures',
2564 'DeleteTransformFeedbacks': {
2566 'resource_type': 'TransformFeedback',
2567 'resource_types': 'TransformFeedbacks',
2571 'decoder_func': 'DoDepthRangef',
2572 'gl_test_func': 'glDepthRange',
2576 'state': 'DepthMask',
2578 'expectation': False,
2580 'DetachShader': {'decoder_func': 'DoDetachShader'},
2582 'decoder_func': 'DoDisable',
2584 'client_test': False,
2586 'DisableVertexAttribArray': {
2587 'decoder_func': 'DoDisableVertexAttribArray',
2592 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2593 'defer_draws': True,
2598 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2599 'GLenumIndexType type, GLuint index_offset',
2600 'client_test': False,
2601 'defer_draws': True,
2604 'DrawRangeElements': {
2610 'decoder_func': 'DoEnable',
2612 'client_test': False,
2614 'EnableVertexAttribArray': {
2615 'decoder_func': 'DoEnableVertexAttribArray',
2620 'client_test': False,
2626 'client_test': False,
2627 'decoder_func': 'DoFinish',
2628 'defer_reads': True,
2633 'decoder_func': 'DoFlush',
2636 'FramebufferRenderbuffer': {
2637 'decoder_func': 'DoFramebufferRenderbuffer',
2638 'gl_test_func': 'glFramebufferRenderbufferEXT',
2641 'FramebufferTexture2D': {
2642 'decoder_func': 'DoFramebufferTexture2D',
2643 'gl_test_func': 'glFramebufferTexture2DEXT',
2646 'FramebufferTexture2DMultisampleEXT': {
2647 'decoder_func': 'DoFramebufferTexture2DMultisample',
2648 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2649 'expectation': False,
2651 'extension_flag': 'multisampled_render_to_texture',
2654 'FramebufferTextureLayer': {
2655 'decoder_func': 'DoFramebufferTextureLayer',
2660 'decoder_func': 'DoGenerateMipmap',
2661 'gl_test_func': 'glGenerateMipmapEXT',
2666 'gl_test_func': 'glGenBuffersARB',
2667 'resource_type': 'Buffer',
2668 'resource_types': 'Buffers',
2670 'GenMailboxCHROMIUM': {
2671 'type': 'HandWritten',
2673 'extension': "CHROMIUM_texture_mailbox",
2676 'GenFramebuffers': {
2678 'gl_test_func': 'glGenFramebuffersEXT',
2679 'resource_type': 'Framebuffer',
2680 'resource_types': 'Framebuffers',
2682 'GenRenderbuffers': {
2683 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2684 'resource_type': 'Renderbuffer',
2685 'resource_types': 'Renderbuffers',
2689 'gl_test_func': 'glGenSamplers',
2690 'resource_type': 'Sampler',
2691 'resource_types': 'Samplers',
2696 'gl_test_func': 'glGenTextures',
2697 'resource_type': 'Texture',
2698 'resource_types': 'Textures',
2700 'GenTransformFeedbacks': {
2702 'gl_test_func': 'glGenTransformFeedbacks',
2703 'resource_type': 'TransformFeedback',
2704 'resource_types': 'TransformFeedbacks',
2707 'GetActiveAttrib': {
2709 'data_transfer_methods': ['shm'],
2711 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2719 'GetActiveUniform': {
2721 'data_transfer_methods': ['shm'],
2723 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2731 'GetActiveUniformBlockiv': {
2733 'data_transfer_methods': ['shm'],
2734 'result': ['SizedResult<GLint>'],
2737 'GetActiveUniformBlockName': {
2739 'data_transfer_methods': ['shm'],
2741 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2743 'result': ['int32_t'],
2746 'GetActiveUniformsiv': {
2748 'data_transfer_methods': ['shm'],
2750 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2752 'result': ['SizedResult<GLint>'],
2755 'GetAttachedShaders': {
2757 'data_transfer_methods': ['shm'],
2758 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2759 'result': ['SizedResult<GLuint>'],
2761 'GetAttribLocation': {
2763 'data_transfer_methods': ['shm'],
2765 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2766 'result': ['GLint'],
2769 'GetFragDataLocation': {
2771 'data_transfer_methods': ['shm'],
2773 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2774 'result': ['GLint'],
2780 'result': ['SizedResult<GLboolean>'],
2781 'decoder_func': 'DoGetBooleanv',
2782 'gl_test_func': 'glGetBooleanv',
2784 'GetBufferParameteri64v': {
2786 'result': ['SizedResult<GLint64>'],
2787 'decoder_func': 'DoGetBufferParameteri64v',
2788 'expectation': False,
2792 'GetBufferParameteriv': {
2794 'result': ['SizedResult<GLint>'],
2795 'decoder_func': 'DoGetBufferParameteriv',
2796 'expectation': False,
2801 'decoder_func': 'GetErrorState()->GetGLError',
2803 'result': ['GLenum'],
2804 'client_test': False,
2808 'result': ['SizedResult<GLfloat>'],
2809 'decoder_func': 'DoGetFloatv',
2810 'gl_test_func': 'glGetFloatv',
2812 'GetFramebufferAttachmentParameteriv': {
2814 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2815 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2816 'result': ['SizedResult<GLint>'],
2818 'GetGraphicsResetStatusKHR': {
2820 'client_test': False,
2826 'result': ['SizedResult<GLint64>'],
2827 'client_test': False,
2828 'decoder_func': 'DoGetInteger64v',
2833 'result': ['SizedResult<GLint>'],
2834 'decoder_func': 'DoGetIntegerv',
2835 'client_test': False,
2837 'GetInteger64i_v': {
2839 'result': ['SizedResult<GLint64>'],
2840 'client_test': False,
2845 'result': ['SizedResult<GLint>'],
2846 'client_test': False,
2849 'GetInternalformativ': {
2851 'data_transfer_methods': ['shm'],
2852 'result': ['SizedResult<GLint>'],
2854 'GLenumRenderBufferTarget target, GLenumRenderBufferFormat format, '
2855 'GLenumInternalFormatParameter pname, GLint* params',
2858 'GetMaxValueInBufferCHROMIUM': {
2860 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2861 'result': ['GLuint'],
2863 'client_test': False,
2870 'decoder_func': 'DoGetProgramiv',
2871 'result': ['SizedResult<GLint>'],
2872 'expectation': False,
2874 'GetProgramInfoCHROMIUM': {
2876 'expectation': False,
2880 'client_test': False,
2881 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2883 'uint32_t link_status',
2884 'uint32_t num_attribs',
2885 'uint32_t num_uniforms',
2888 'GetProgramInfoLog': {
2890 'expectation': False,
2892 'GetRenderbufferParameteriv': {
2894 'decoder_func': 'DoGetRenderbufferParameteriv',
2895 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2896 'result': ['SizedResult<GLint>'],
2898 'GetSamplerParameterfv': {
2900 'result': ['SizedResult<GLfloat>'],
2901 'id_mapping': [ 'Sampler' ],
2904 'GetSamplerParameteriv': {
2906 'result': ['SizedResult<GLint>'],
2907 'id_mapping': [ 'Sampler' ],
2912 'decoder_func': 'DoGetShaderiv',
2913 'result': ['SizedResult<GLint>'],
2915 'GetShaderInfoLog': {
2917 'get_len_func': 'glGetShaderiv',
2918 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2921 'GetShaderPrecisionFormat': {
2923 'data_transfer_methods': ['shm'],
2925 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2929 'int32_t min_range',
2930 'int32_t max_range',
2931 'int32_t precision',
2934 'GetShaderSource': {
2936 'get_len_func': 'DoGetShaderiv',
2937 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2939 'client_test': False,
2943 'client_test': False,
2944 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2948 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2949 'result': ['SizedResult<GLint>'],
2950 'id_mapping': ['Sync'],
2953 'GetTexParameterfv': {
2955 'decoder_func': 'DoGetTexParameterfv',
2956 'result': ['SizedResult<GLfloat>']
2958 'GetTexParameteriv': {
2960 'decoder_func': 'DoGetTexParameteriv',
2961 'result': ['SizedResult<GLint>']
2963 'GetTranslatedShaderSourceANGLE': {
2965 'get_len_func': 'DoGetShaderiv',
2966 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2970 'GetUniformBlockIndex': {
2972 'data_transfer_methods': ['shm'],
2974 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2975 'result': ['GLuint'],
2976 'error_return': 'GL_INVALID_INDEX',
2979 'GetUniformBlocksCHROMIUM': {
2981 'expectation': False,
2985 'client_test': False,
2986 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2987 'result': ['uint32_t'],
2990 'GetUniformsES3CHROMIUM': {
2992 'expectation': False,
2996 'client_test': False,
2997 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2998 'result': ['uint32_t'],
3001 'GetTransformFeedbackVarying': {
3003 'data_transfer_methods': ['shm'],
3005 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
3014 'GetTransformFeedbackVaryingsCHROMIUM': {
3016 'expectation': False,
3020 'client_test': False,
3021 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3022 'result': ['uint32_t'],
3027 'data_transfer_methods': ['shm'],
3028 'result': ['SizedResult<GLfloat>'],
3032 'data_transfer_methods': ['shm'],
3033 'result': ['SizedResult<GLint>'],
3037 'data_transfer_methods': ['shm'],
3038 'result': ['SizedResult<GLuint>'],
3041 'GetUniformIndices': {
3043 'data_transfer_methods': ['shm'],
3044 'result': ['SizedResult<GLuint>'],
3045 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
3049 'GetUniformLocation': {
3051 'data_transfer_methods': ['shm'],
3053 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
3054 'result': ['GLint'],
3055 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
3057 'GetVertexAttribfv': {
3059 'result': ['SizedResult<GLfloat>'],
3061 'decoder_func': 'DoGetVertexAttribfv',
3062 'expectation': False,
3063 'client_test': False,
3065 'GetVertexAttribiv': {
3067 'result': ['SizedResult<GLint>'],
3069 'decoder_func': 'DoGetVertexAttribiv',
3070 'expectation': False,
3071 'client_test': False,
3073 'GetVertexAttribIiv': {
3075 'result': ['SizedResult<GLint>'],
3077 'decoder_func': 'DoGetVertexAttribIiv',
3078 'expectation': False,
3079 'client_test': False,
3082 'GetVertexAttribIuiv': {
3084 'result': ['SizedResult<GLuint>'],
3086 'decoder_func': 'DoGetVertexAttribIuiv',
3087 'expectation': False,
3088 'client_test': False,
3091 'GetVertexAttribPointerv': {
3093 'data_transfer_methods': ['shm'],
3094 'result': ['SizedResult<GLuint>'],
3095 'client_test': False,
3097 'InvalidateFramebuffer': {
3100 'client_test': False,
3104 'InvalidateSubFramebuffer': {
3107 'client_test': False,
3113 'decoder_func': 'DoIsBuffer',
3114 'expectation': False,
3118 'decoder_func': 'DoIsEnabled',
3119 'client_test': False,
3121 'expectation': False,
3125 'decoder_func': 'DoIsFramebuffer',
3126 'expectation': False,
3130 'decoder_func': 'DoIsProgram',
3131 'expectation': False,
3135 'decoder_func': 'DoIsRenderbuffer',
3136 'expectation': False,
3140 'decoder_func': 'DoIsShader',
3141 'expectation': False,
3145 'id_mapping': [ 'Sampler' ],
3146 'expectation': False,
3151 'id_mapping': [ 'Sync' ],
3152 'cmd_args': 'GLuint sync',
3153 'expectation': False,
3158 'decoder_func': 'DoIsTexture',
3159 'expectation': False,
3161 'IsTransformFeedback': {
3163 'id_mapping': [ 'TransformFeedback' ],
3164 'expectation': False,
3168 'decoder_func': 'DoLinkProgram',
3172 'MapBufferCHROMIUM': {
3174 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3176 'client_test': False,
3179 'MapBufferSubDataCHROMIUM': {
3183 'client_test': False,
3184 'pepper_interface': 'ChromiumMapSub',
3187 'MapTexSubImage2DCHROMIUM': {
3189 'extension': "CHROMIUM_sub_image",
3191 'client_test': False,
3192 'pepper_interface': 'ChromiumMapSub',
3197 'data_transfer_methods': ['shm'],
3198 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3199 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3200 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3201 'uint32_t result_shm_id, uint32_t result_shm_offset',
3203 'result': ['uint32_t'],
3206 'PauseTransformFeedback': {
3209 'PixelStorei': {'type': 'Manual'},
3210 'PostSubBufferCHROMIUM': {
3214 'client_test': False,
3218 'ProduceTextureCHROMIUM': {
3219 'decoder_func': 'DoProduceTextureCHROMIUM',
3222 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3224 'client_test': False,
3225 'extension': "CHROMIUM_texture_mailbox",
3229 'ProduceTextureDirectCHROMIUM': {
3230 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3233 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3235 'client_test': False,
3236 'extension': "CHROMIUM_texture_mailbox",
3240 'RenderbufferStorage': {
3241 'decoder_func': 'DoRenderbufferStorage',
3242 'gl_test_func': 'glRenderbufferStorageEXT',
3243 'expectation': False,
3246 'RenderbufferStorageMultisampleCHROMIUM': {
3248 '// GL_CHROMIUM_framebuffer_multisample\n',
3249 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3250 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3251 'expectation': False,
3253 'extension_flag': 'chromium_framebuffer_multisample',
3254 'pepper_interface': 'FramebufferMultisample',
3255 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3258 'RenderbufferStorageMultisampleEXT': {
3260 '// GL_EXT_multisampled_render_to_texture\n',
3261 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3262 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3263 'expectation': False,
3265 'extension_flag': 'multisampled_render_to_texture',
3270 'decoder_func': 'DoReadBuffer',
3275 '// ReadPixels has the result separated from the pixel buffer so that\n'
3276 '// it is easier to specify the result going to some specific place\n'
3277 '// that exactly fits the rectangle of pixels.\n',
3279 'data_transfer_methods': ['shm'],
3281 'client_test': False,
3283 'GLint x, GLint y, GLsizei width, GLsizei height, '
3284 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3285 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3286 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3288 'result': ['uint32_t'],
3289 'defer_reads': True,
3292 'ReleaseShaderCompiler': {
3293 'decoder_func': 'DoReleaseShaderCompiler',
3296 'ResumeTransformFeedback': {
3299 'SamplerParameterf': {
3303 'id_mapping': [ 'Sampler' ],
3306 'SamplerParameterfv': {
3308 'data_value': 'GL_NEAREST',
3310 'gl_test_func': 'glSamplerParameterf',
3311 'decoder_func': 'DoSamplerParameterfv',
3312 'first_element_only': True,
3313 'id_mapping': [ 'Sampler' ],
3316 'SamplerParameteri': {
3320 'id_mapping': [ 'Sampler' ],
3323 'SamplerParameteriv': {
3325 'data_value': 'GL_NEAREST',
3327 'gl_test_func': 'glSamplerParameteri',
3328 'decoder_func': 'DoSamplerParameteriv',
3329 'first_element_only': True,
3334 'client_test': False,
3338 'decoder_func': 'DoShaderSource',
3339 'expectation': False,
3340 'data_transfer_methods': ['bucket'],
3342 'GLuint shader, const char** str',
3344 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3347 'type': 'StateSetFrontBack',
3348 'state': 'StencilMask',
3350 'expectation': False,
3352 'StencilMaskSeparate': {
3353 'type': 'StateSetFrontBackSeparate',
3354 'state': 'StencilMask',
3356 'expectation': False,
3360 'decoder_func': 'DoSwapBuffers',
3362 'client_test': False,
3368 'decoder_func': 'DoSwapInterval',
3370 'client_test': False,
3376 'data_transfer_methods': ['shm'],
3377 'client_test': False,
3382 'data_transfer_methods': ['shm'],
3383 'client_test': False,
3388 'decoder_func': 'DoTexParameterf',
3394 'decoder_func': 'DoTexParameteri',
3401 'data_value': 'GL_NEAREST',
3403 'decoder_func': 'DoTexParameterfv',
3404 'gl_test_func': 'glTexParameterf',
3405 'first_element_only': True,
3409 'data_value': 'GL_NEAREST',
3411 'decoder_func': 'DoTexParameteriv',
3412 'gl_test_func': 'glTexParameteri',
3413 'first_element_only': True,
3421 'data_transfer_methods': ['shm'],
3422 'client_test': False,
3424 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3425 'GLint xoffset, GLint yoffset, '
3426 'GLsizei width, GLsizei height, '
3427 'GLenumTextureFormat format, GLenumPixelType type, '
3428 'const void* pixels, GLboolean internal'
3432 'data_transfer_methods': ['shm'],
3433 'client_test': False,
3435 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3436 'GLint xoffset, GLint yoffset, GLint zoffset, '
3437 'GLsizei width, GLsizei height, GLsizei depth, '
3438 'GLenumTextureFormat format, GLenumPixelType type, '
3439 'const void* pixels, GLboolean internal',
3442 'TransformFeedbackVaryings': {
3444 'data_transfer_methods': ['bucket'],
3445 'decoder_func': 'DoTransformFeedbackVaryings',
3447 'GLuint program, const char** varyings, GLenum buffermode',
3450 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3454 'decoder_func': 'DoUniform1fv',
3456 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3460 'decoder_func': 'DoUniform1iv',
3473 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3474 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3478 'decoder_func': 'DoUniform2fv',
3483 'decoder_func': 'DoUniform2iv',
3495 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3496 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3500 'decoder_func': 'DoUniform3fv',
3505 'decoder_func': 'DoUniform3iv',
3517 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3518 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3522 'decoder_func': 'DoUniform4fv',
3527 'decoder_func': 'DoUniform4iv',
3539 'UniformMatrix2fv': {
3542 'decoder_func': 'DoUniformMatrix2fv',
3544 'UniformMatrix2x3fv': {
3549 'UniformMatrix2x4fv': {
3554 'UniformMatrix3fv': {
3557 'decoder_func': 'DoUniformMatrix3fv',
3559 'UniformMatrix3x2fv': {
3564 'UniformMatrix3x4fv': {
3569 'UniformMatrix4fv': {
3572 'decoder_func': 'DoUniformMatrix4fv',
3574 'UniformMatrix4x2fv': {
3579 'UniformMatrix4x3fv': {
3584 'UniformBlockBinding': {
3589 'UnmapBufferCHROMIUM': {
3591 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3593 'client_test': False,
3596 'UnmapBufferSubDataCHROMIUM': {
3600 'client_test': False,
3601 'pepper_interface': 'ChromiumMapSub',
3609 'UnmapTexSubImage2DCHROMIUM': {
3611 'extension': "CHROMIUM_sub_image",
3613 'client_test': False,
3614 'pepper_interface': 'ChromiumMapSub',
3619 'decoder_func': 'DoUseProgram',
3621 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3622 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3623 'VertexAttrib1fv': {
3626 'decoder_func': 'DoVertexAttrib1fv',
3628 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3629 'VertexAttrib2fv': {
3632 'decoder_func': 'DoVertexAttrib2fv',
3634 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3635 'VertexAttrib3fv': {
3638 'decoder_func': 'DoVertexAttrib3fv',
3640 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3641 'VertexAttrib4fv': {
3644 'decoder_func': 'DoVertexAttrib4fv',
3646 'VertexAttribI4i': {
3648 'decoder_func': 'DoVertexAttribI4i',
3650 'VertexAttribI4iv': {
3654 'decoder_func': 'DoVertexAttribI4iv',
3656 'VertexAttribI4ui': {
3658 'decoder_func': 'DoVertexAttribI4ui',
3660 'VertexAttribI4uiv': {
3664 'decoder_func': 'DoVertexAttribI4uiv',
3666 'VertexAttribIPointer': {
3668 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3669 'GLenumVertexAttribIType type, GLsizei stride, '
3671 'client_test': False,
3674 'VertexAttribPointer': {
3676 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3677 'GLenumVertexAttribType type, GLboolean normalized, '
3678 'GLsizei stride, GLuint offset',
3679 'client_test': False,
3683 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3684 'GLuint timeout_0, GLuint timeout_1',
3686 'client_test': False,
3695 'decoder_func': 'DoViewport',
3705 'GetRequestableExtensionsCHROMIUM': {
3708 'cmd_args': 'uint32_t bucket_id',
3712 'RequestExtensionCHROMIUM': {
3715 'client_test': False,
3716 'cmd_args': 'uint32_t bucket_id',
3720 'RateLimitOffscreenContextCHROMIUM': {
3724 'client_test': False,
3726 'CreateStreamTextureCHROMIUM': {
3727 'type': 'HandWritten',
3734 'TexImageIOSurface2DCHROMIUM': {
3735 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3741 'CopyTextureCHROMIUM': {
3742 'decoder_func': 'DoCopyTextureCHROMIUM',
3744 'extension': "CHROMIUM_copy_texture",
3748 'CopySubTextureCHROMIUM': {
3749 'decoder_func': 'DoCopySubTextureCHROMIUM',
3751 'extension': "CHROMIUM_copy_texture",
3755 'CompressedCopyTextureCHROMIUM': {
3756 'decoder_func': 'DoCompressedCopyTextureCHROMIUM',
3761 'TexStorage2DEXT': {
3764 'decoder_func': 'DoTexStorage2DEXT',
3767 'DrawArraysInstancedANGLE': {
3769 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3770 'GLsizei primcount',
3773 'pepper_interface': 'InstancedArrays',
3774 'defer_draws': True,
3779 'decoder_func': 'DoDrawBuffersEXT',
3781 'client_test': False,
3783 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3786 'pepper_interface': 'DrawBuffers',
3789 'DrawElementsInstancedANGLE': {
3791 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3792 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3795 'client_test': False,
3796 'pepper_interface': 'InstancedArrays',
3797 'defer_draws': True,
3800 'VertexAttribDivisorANGLE': {
3802 'cmd_args': 'GLuint index, GLuint divisor',
3805 'pepper_interface': 'InstancedArrays',
3809 'gl_test_func': 'glGenQueriesARB',
3810 'resource_type': 'Query',
3811 'resource_types': 'Queries',
3813 'pepper_interface': 'Query',
3814 'not_shared': 'True',
3815 'extension': "occlusion_query_EXT",
3817 'DeleteQueriesEXT': {
3819 'gl_test_func': 'glDeleteQueriesARB',
3820 'resource_type': 'Query',
3821 'resource_types': 'Queries',
3823 'pepper_interface': 'Query',
3824 'extension': "occlusion_query_EXT",
3828 'client_test': False,
3829 'pepper_interface': 'Query',
3830 'extension': "occlusion_query_EXT",
3834 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3835 'data_transfer_methods': ['shm'],
3836 'gl_test_func': 'glBeginQuery',
3837 'pepper_interface': 'Query',
3838 'extension': "occlusion_query_EXT",
3840 'BeginTransformFeedback': {
3845 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3846 'gl_test_func': 'glEndnQuery',
3847 'client_test': False,
3848 'pepper_interface': 'Query',
3849 'extension': "occlusion_query_EXT",
3851 'EndTransformFeedback': {
3854 'FlushDriverCachesCHROMIUM': {
3855 'decoder_func': 'DoFlushDriverCachesCHROMIUM',
3863 'client_test': False,
3864 'gl_test_func': 'glGetQueryiv',
3865 'pepper_interface': 'Query',
3866 'extension': "occlusion_query_EXT",
3868 'QueryCounterEXT' : {
3870 'cmd_args': 'GLidQuery id, GLenumQueryTarget target, '
3871 'void* sync_data, GLuint submit_count',
3872 'data_transfer_methods': ['shm'],
3873 'gl_test_func': 'glQueryCounter',
3874 'extension': "disjoint_timer_query_EXT",
3876 'GetQueryObjectuivEXT': {
3878 'client_test': False,
3879 'gl_test_func': 'glGetQueryObjectuiv',
3880 'pepper_interface': 'Query',
3881 'extension': "occlusion_query_EXT",
3883 'GetQueryObjectui64vEXT': {
3885 'client_test': False,
3886 'gl_test_func': 'glGetQueryObjectui64v',
3887 'extension': "disjoint_timer_query_EXT",
3889 'BindUniformLocationCHROMIUM': {
3892 'data_transfer_methods': ['bucket'],
3894 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3896 'InsertEventMarkerEXT': {
3898 'decoder_func': 'DoInsertEventMarkerEXT',
3899 'expectation': False,
3902 'PushGroupMarkerEXT': {
3904 'decoder_func': 'DoPushGroupMarkerEXT',
3905 'expectation': False,
3908 'PopGroupMarkerEXT': {
3909 'decoder_func': 'DoPopGroupMarkerEXT',
3910 'expectation': False,
3915 'GenVertexArraysOES': {
3918 'gl_test_func': 'glGenVertexArraysOES',
3919 'resource_type': 'VertexArray',
3920 'resource_types': 'VertexArrays',
3922 'pepper_interface': 'VertexArrayObject',
3924 'BindVertexArrayOES': {
3927 'gl_test_func': 'glBindVertexArrayOES',
3928 'decoder_func': 'DoBindVertexArrayOES',
3929 'gen_func': 'GenVertexArraysOES',
3931 'client_test': False,
3932 'pepper_interface': 'VertexArrayObject',
3934 'DeleteVertexArraysOES': {
3937 'gl_test_func': 'glDeleteVertexArraysOES',
3938 'resource_type': 'VertexArray',
3939 'resource_types': 'VertexArrays',
3941 'pepper_interface': 'VertexArrayObject',
3943 'IsVertexArrayOES': {
3946 'gl_test_func': 'glIsVertexArrayOES',
3947 'decoder_func': 'DoIsVertexArrayOES',
3948 'expectation': False,
3950 'pepper_interface': 'VertexArrayObject',
3952 'BindTexImage2DCHROMIUM': {
3953 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3955 'extension': "CHROMIUM_image",
3958 'ReleaseTexImage2DCHROMIUM': {
3959 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3961 'extension': "CHROMIUM_image",
3964 'ShallowFinishCHROMIUM': {
3969 'client_test': False,
3971 'ShallowFlushCHROMIUM': {
3974 'extension': "CHROMIUM_miscellaneous",
3976 'client_test': False,
3978 'OrderingBarrierCHROMIUM': {
3983 'client_test': False,
3985 'TraceBeginCHROMIUM': {
3988 'client_test': False,
3989 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3993 'TraceEndCHROMIUM': {
3995 'client_test': False,
3996 'decoder_func': 'DoTraceEndCHROMIUM',
4001 'AsyncTexImage2DCHROMIUM': {
4003 'data_transfer_methods': ['shm'],
4004 'client_test': False,
4005 'cmd_args': 'GLenumTextureTarget target, GLint level, '
4006 'GLintTextureInternalFormat internalformat, '
4007 'GLsizei width, GLsizei height, '
4008 'GLintTextureBorder border, '
4009 'GLenumTextureFormat format, GLenumPixelType type, '
4010 'const void* pixels, '
4011 'uint32_t async_upload_token, '
4017 'AsyncTexSubImage2DCHROMIUM': {
4019 'data_transfer_methods': ['shm'],
4020 'client_test': False,
4021 'cmd_args': 'GLenumTextureTarget target, GLint level, '
4022 'GLint xoffset, GLint yoffset, '
4023 'GLsizei width, GLsizei height, '
4024 'GLenumTextureFormat format, GLenumPixelType type, '
4025 'const void* data, '
4026 'uint32_t async_upload_token, '
4032 'WaitAsyncTexImage2DCHROMIUM': {
4034 'client_test': False,
4039 'WaitAllAsyncTexImage2DCHROMIUM': {
4041 'client_test': False,
4046 'DiscardFramebufferEXT': {
4049 'decoder_func': 'DoDiscardFramebufferEXT',
4051 'client_test': False,
4052 'extension_flag': 'ext_discard_framebuffer',
4055 'LoseContextCHROMIUM': {
4056 'decoder_func': 'DoLoseContextCHROMIUM',
4062 'InsertSyncPointCHROMIUM': {
4063 'type': 'HandWritten',
4065 'extension': "CHROMIUM_sync_point",
4069 'WaitSyncPointCHROMIUM': {
4072 'extension': "CHROMIUM_sync_point",
4076 'DiscardBackbufferCHROMIUM': {
4083 'ScheduleOverlayPlaneCHROMIUM': {
4087 'client_test': False,
4091 'MatrixLoadfCHROMIUM': {
4094 'data_type': 'GLfloat',
4095 'decoder_func': 'DoMatrixLoadfCHROMIUM',
4096 'gl_test_func': 'glMatrixLoadfEXT',
4099 'extension_flag': 'chromium_path_rendering',
4101 'MatrixLoadIdentityCHROMIUM': {
4102 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
4103 'gl_test_func': 'glMatrixLoadIdentityEXT',
4106 'extension_flag': 'chromium_path_rendering',
4108 'GenPathsCHROMIUM': {
4110 'cmd_args': 'GLuint first_client_id, GLsizei range',
4113 'extension_flag': 'chromium_path_rendering',
4115 'DeletePathsCHROMIUM': {
4117 'cmd_args': 'GLuint first_client_id, GLsizei range',
4122 'extension_flag': 'chromium_path_rendering',
4126 'decoder_func': 'DoIsPathCHROMIUM',
4127 'gl_test_func': 'glIsPathNV',
4130 'extension_flag': 'chromium_path_rendering',
4132 'PathCommandsCHROMIUM': {
4137 'extension_flag': 'chromium_path_rendering',
4139 'PathParameterfCHROMIUM': {
4143 'extension_flag': 'chromium_path_rendering',
4145 'PathParameteriCHROMIUM': {
4149 'extension_flag': 'chromium_path_rendering',
4151 'PathStencilFuncCHROMIUM': {
4153 'state': 'PathStencilFuncCHROMIUM',
4154 'decoder_func': 'glPathStencilFuncNV',
4157 'extension_flag': 'chromium_path_rendering',
4159 'StencilFillPathCHROMIUM': {
4163 'extension_flag': 'chromium_path_rendering',
4165 'StencilStrokePathCHROMIUM': {
4169 'extension_flag': 'chromium_path_rendering',
4171 'CoverFillPathCHROMIUM': {
4175 'extension_flag': 'chromium_path_rendering',
4177 'CoverStrokePathCHROMIUM': {
4181 'extension_flag': 'chromium_path_rendering',
4183 'StencilThenCoverFillPathCHROMIUM': {
4187 'extension_flag': 'chromium_path_rendering',
4189 'StencilThenCoverStrokePathCHROMIUM': {
4193 'extension_flag': 'chromium_path_rendering',
4199 def Grouper(n
, iterable
, fillvalue
=None):
4200 """Collect data into fixed-length chunks or blocks"""
4201 args
= [iter(iterable
)] * n
4202 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
4205 def SplitWords(input_string
):
4206 """Split by '_' if found, otherwise split at uppercase/numeric chars.
4208 Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
4209 "Case"], and "Vector3" into ["Vector", "3"].
4211 if input_string
.find('_') > -1:
4212 # 'some_TEXT_' -> 'some TEXT'
4213 return input_string
.replace('_', ' ').strip().split()
4215 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
4217 # look for capitalization to cut input_strings
4218 # 'SomeText' -> 'Some Text'
4219 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
4220 # 'Vector3' -> 'Vector 3'
4221 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
4222 return input_string
.split()
4224 def ToUnderscore(input_string
):
4225 """converts CamelCase to camel_case."""
4226 words
= SplitWords(input_string
)
4227 return '_'.join([word
.lower() for word
in words
])
4229 def CachedStateName(item
):
4230 if item
.get('cached', False):
4231 return 'cached_' + item
['name']
4234 def ToGLExtensionString(extension_flag
):
4235 """Returns GL-type extension string of a extension flag."""
4236 if extension_flag
== "oes_compressed_etc1_rgb8_texture":
4237 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
4239 uppercase_words
= [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
4240 'egl', 'atc', 'etc1', 'angle']
4241 parts
= extension_flag
.split('_')
4243 [part
.upper() if part
in uppercase_words
else part
for part
in parts
])
4245 def ToCamelCase(input_string
):
4246 """converts ABC_underscore_case to ABCUnderscoreCase."""
4247 return ''.join(w
[0].upper() + w
[1:] for w
in input_string
.split('_'))
4249 def GetGLGetTypeConversion(result_type
, value_type
, value
):
4250 """Makes a gl compatible type conversion string for accessing state variables.
4252 Useful when accessing state variables through glGetXXX calls.
4253 glGet documetation (for example, the manual pages):
4254 [...] If glGetIntegerv is called, [...] most floating-point values are
4255 rounded to the nearest integer value. [...]
4258 result_type: the gl type to be obtained
4259 value_type: the GL type of the state variable
4260 value: the name of the state variable
4263 String that converts the state variable to desired GL type according to GL
4267 if result_type
== 'GLint':
4268 if value_type
== 'GLfloat':
4269 return 'static_cast<GLint>(round(%s))' % value
4270 return 'static_cast<%s>(%s)' % (result_type
, value
)
4273 class CWriter(object):
4274 """Context manager that creates a C source file.
4276 To be used with the `with` statement. Returns a normal `file` type, open only
4277 for writing - any existing files with that name will be overwritten. It will
4278 automatically write the contents of `_LICENSE` and `_DO_NOT_EDIT_WARNING`
4282 with CWriter("file.cpp") as myfile:
4283 myfile.write("hello")
4284 # type(myfile) == file
4286 def __init__(self
, filename
):
4287 self
.filename
= filename
4288 self
._file
= open(filename
, 'w')
4289 self
._ENTER
_MSG
= _LICENSE
+ _DO_NOT_EDIT_WARNING
4292 def __enter__(self
):
4293 self
._file
.write(self
._ENTER
_MSG
)
4296 def __exit__(self
, exc_type
, exc_value
, traceback
):
4297 self
._file
.write(self
._EXIT
_MSG
)
4301 class CHeaderWriter(CWriter
):
4302 """Context manager that creates a C header file.
4304 Works the same way as CWriter, except it will also add the #ifdef guard
4305 around it. If `file_comment` is set, it will write that before the #ifdef
4308 def __init__(self
, filename
, file_comment
=None):
4309 super(CHeaderWriter
, self
).__init
__(filename
)
4310 guard
= self
._get
_guard
()
4311 if file_comment
is None:
4313 self
._ENTER
_MSG
= self
._ENTER
_MSG
+ file_comment \
4314 + "#ifndef %s\n#define %s\n\n" % (guard
, guard
)
4315 self
._EXIT
_MSG
= self
._EXIT
_MSG
+ "#endif // %s\n" % guard
4317 def _get_guard(self
):
4318 non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
4319 base
= os
.path
.abspath(self
.filename
)
4320 while os
.path
.basename(base
) != 'src':
4321 new_base
= os
.path
.dirname(base
)
4322 assert new_base
!= base
# Prevent infinite loop.
4324 hpath
= os
.path
.relpath(self
.filename
, base
)
4325 return non_alnum_re
.sub('_', hpath
).upper() + '_'
4328 class TypeHandler(object):
4329 """This class emits code for a particular type of function."""
4331 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
4333 def InitFunction(self
, func
):
4334 """Add or adjust anything type specific for this function."""
4335 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
4336 func
.AddCmdArg(DataSizeArgument('data_size'))
4338 def NeedsDataTransferFunction(self
, func
):
4339 """Overriden from TypeHandler."""
4340 return func
.num_pointer_args
>= 1
4342 def WriteStruct(self
, func
, f
):
4343 """Writes a structure that matches the arguments to a function."""
4344 comment
= func
.GetInfo('cmd_comment')
4345 if not comment
== None:
4347 f
.write("struct %s {\n" % func
.name
)
4348 f
.write(" typedef %s ValueType;\n" % func
.name
)
4349 f
.write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
4350 func
.WriteCmdArgFlag(f
)
4351 func
.WriteCmdFlag(f
)
4353 result
= func
.GetInfo('result')
4354 if not result
== None:
4355 if len(result
) == 1:
4356 f
.write(" typedef %s Result;\n\n" % result
[0])
4358 f
.write(" struct Result {\n")
4360 f
.write(" %s;\n" % line
)
4363 func
.WriteCmdComputeSize(f
)
4364 func
.WriteCmdSetHeader(f
)
4365 func
.WriteCmdInit(f
)
4368 f
.write(" gpu::CommandHeader header;\n")
4369 args
= func
.GetCmdArgs()
4371 f
.write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
4373 consts
= func
.GetCmdConstants()
4374 for const
in consts
:
4375 f
.write(" static const %s %s = %s;\n" %
4376 (const
.cmd_type
, const
.name
, const
.GetConstantValue()))
4381 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
4382 f
.write("static_assert(sizeof(%s) == %d,\n" % (func
.name
, size
))
4383 f
.write(" \"size of %s should be %d\");\n" %
4385 f
.write("static_assert(offsetof(%s, header) == 0,\n" % func
.name
)
4386 f
.write(" \"offset of %s header should be 0\");\n" %
4388 offset
= _SIZE_OF_COMMAND_HEADER
4390 f
.write("static_assert(offsetof(%s, %s) == %d,\n" %
4391 (func
.name
, arg
.name
, offset
))
4392 f
.write(" \"offset of %s %s should be %d\");\n" %
4393 (func
.name
, arg
.name
, offset
))
4394 offset
+= _SIZE_OF_UINT32
4395 if not result
== None and len(result
) > 1:
4398 parts
= line
.split()
4401 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4402 "offset of %(cmd_name)s Result %(field_name)s should be "
4405 f
.write((check
.strip() + "\n") % {
4406 'cmd_name': func
.name
,
4410 offset
+= _SIZE_OF_UINT32
4413 def WriteHandlerImplementation(self
, func
, f
):
4414 """Writes the handler implementation for this command."""
4415 if func
.IsUnsafe() and func
.GetInfo('id_mapping'):
4416 code_no_gen
= """ if (!group_->Get%(type)sServiceId(
4417 %(var)s, &%(service_var)s)) {
4418 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4419 return error::kNoError;
4422 code_gen
= """ if (!group_->Get%(type)sServiceId(
4423 %(var)s, &%(service_var)s)) {
4424 if (!group_->bind_generates_resource()) {
4426 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4427 return error::kNoError;
4429 GLuint client_id = %(var)s;
4430 gl%(gen_func)s(1, &%(service_var)s);
4431 Create%(type)s(client_id, %(service_var)s);
4434 gen_func
= func
.GetInfo('gen_func')
4435 for id_type
in func
.GetInfo('id_mapping'):
4436 service_var
= id_type
.lower()
4437 if id_type
== 'Sync':
4438 service_var
= "service_%s" % service_var
4439 f
.write(" GLsync %s = 0;\n" % service_var
)
4440 if gen_func
and id_type
in gen_func
:
4441 f
.write(code_gen
% { 'type': id_type
,
4442 'var': id_type
.lower(),
4443 'service_var': service_var
,
4444 'func': func
.GetGLFunctionName(),
4445 'gen_func': gen_func
})
4447 f
.write(code_no_gen
% { 'type': id_type
,
4448 'var': id_type
.lower(),
4449 'service_var': service_var
,
4450 'func': func
.GetGLFunctionName() })
4452 for arg
in func
.GetOriginalArgs():
4453 if arg
.type == "GLsync":
4454 args
.append("service_%s" % arg
.name
)
4455 elif arg
.name
.endswith("size") and arg
.type == "GLsizei":
4456 args
.append("num_%s" % func
.GetLastOriginalArg().name
)
4457 elif arg
.name
== "length":
4458 args
.append("nullptr")
4460 args
.append(arg
.name
)
4461 f
.write(" %s(%s);\n" %
4462 (func
.GetGLFunctionName(), ", ".join(args
)))
4464 def WriteCmdSizeTest(self
, func
, f
):
4465 """Writes the size test for a command."""
4466 f
.write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4468 def WriteFormatTest(self
, func
, f
):
4469 """Writes a format test for a command."""
4470 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4471 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4472 (func
.name
, func
.name
))
4473 f
.write(" void* next_cmd = cmd.Set(\n")
4475 args
= func
.GetCmdArgs()
4476 for value
, arg
in enumerate(args
):
4477 f
.write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
4479 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4481 f
.write(" cmd.header.command);\n")
4482 func
.type_handler
.WriteCmdSizeTest(func
, f
)
4483 for value
, arg
in enumerate(args
):
4484 f
.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4485 (arg
.type, value
+ 11, arg
.name
))
4486 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
4487 f
.write(" next_cmd, sizeof(cmd));\n")
4491 def WriteImmediateFormatTest(self
, func
, f
):
4492 """Writes a format test for an immediate version of a command."""
4495 def WriteGetDataSizeCode(self
, func
, f
):
4496 """Writes the code to set data_size used in validation"""
4499 def __WriteIdMapping(self
, func
, f
):
4500 """Writes client side / service side ID mapping."""
4501 if not func
.IsUnsafe() or not func
.GetInfo('id_mapping'):
4503 for id_type
in func
.GetInfo('id_mapping'):
4504 f
.write(" group_->Get%sServiceId(%s, &%s);\n" %
4505 (id_type
, id_type
.lower(), id_type
.lower()))
4507 def WriteImmediateHandlerImplementation (self
, func
, f
):
4508 """Writes the handler impl for the immediate version of a command."""
4509 self
.__WriteIdMapping
(func
, f
)
4510 f
.write(" %s(%s);\n" %
4511 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4513 def WriteBucketHandlerImplementation (self
, func
, f
):
4514 """Writes the handler impl for the bucket version of a command."""
4515 self
.__WriteIdMapping
(func
, f
)
4516 f
.write(" %s(%s);\n" %
4517 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4519 def WriteServiceHandlerFunctionHeader(self
, func
, f
):
4520 """Writes function header for service implementation handlers."""
4521 f
.write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4522 uint32_t immediate_data_size, const void* cmd_data) {
4523 """ % {'name': func
.name
})
4525 f
.write("""if (!unsafe_es3_apis_enabled())
4526 return error::kUnknownCommand;
4528 f
.write("""const gles2::cmds::%(name)s& c =
4529 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4531 """ % {'name': func
.name
})
4533 def WriteServiceImplementation(self
, func
, f
):
4534 """Writes the service implementation for a command."""
4535 self
.WriteServiceHandlerFunctionHeader(func
, f
)
4536 self
.WriteHandlerExtensionCheck(func
, f
)
4537 self
.WriteHandlerDeferReadWrite(func
, f
);
4538 if len(func
.GetOriginalArgs()) > 0:
4539 last_arg
= func
.GetLastOriginalArg()
4540 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
4541 for arg
in all_but_last_arg
:
4543 self
.WriteGetDataSizeCode(func
, f
)
4544 last_arg
.WriteGetCode(f
)
4545 func
.WriteHandlerValidation(f
)
4546 func
.WriteHandlerImplementation(f
)
4547 f
.write(" return error::kNoError;\n")
4551 def WriteImmediateServiceImplementation(self
, func
, f
):
4552 """Writes the service implementation for an immediate version of command."""
4553 self
.WriteServiceHandlerFunctionHeader(func
, f
)
4554 self
.WriteHandlerExtensionCheck(func
, f
)
4555 self
.WriteHandlerDeferReadWrite(func
, f
);
4556 for arg
in func
.GetOriginalArgs():
4558 self
.WriteGetDataSizeCode(func
, f
)
4560 func
.WriteHandlerValidation(f
)
4561 func
.WriteHandlerImplementation(f
)
4562 f
.write(" return error::kNoError;\n")
4566 def WriteBucketServiceImplementation(self
, func
, f
):
4567 """Writes the service implementation for a bucket version of command."""
4568 self
.WriteServiceHandlerFunctionHeader(func
, f
)
4569 self
.WriteHandlerExtensionCheck(func
, f
)
4570 self
.WriteHandlerDeferReadWrite(func
, f
);
4571 for arg
in func
.GetCmdArgs():
4573 func
.WriteHandlerValidation(f
)
4574 func
.WriteHandlerImplementation(f
)
4575 f
.write(" return error::kNoError;\n")
4579 def WriteHandlerExtensionCheck(self
, func
, f
):
4580 if func
.GetInfo('extension_flag'):
4581 f
.write(" if (!features().%s) {\n" % func
.GetInfo('extension_flag'))
4582 f
.write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4583 " \"function not available\");\n" % func
.original_name
)
4584 f
.write(" return error::kNoError;")
4587 def WriteHandlerDeferReadWrite(self
, func
, f
):
4588 """Writes the code to handle deferring reads or writes."""
4589 defer_draws
= func
.GetInfo('defer_draws')
4590 defer_reads
= func
.GetInfo('defer_reads')
4591 if defer_draws
or defer_reads
:
4592 f
.write(" error::Error error;\n")
4594 f
.write(" error = WillAccessBoundFramebufferForDraw();\n")
4595 f
.write(" if (error != error::kNoError)\n")
4596 f
.write(" return error;\n")
4598 f
.write(" error = WillAccessBoundFramebufferForRead();\n")
4599 f
.write(" if (error != error::kNoError)\n")
4600 f
.write(" return error;\n")
4602 def WriteValidUnitTest(self
, func
, f
, test
, *extras
):
4603 """Writes a valid unit test for the service implementation."""
4604 if func
.GetInfo('expectation') == False:
4605 test
= self
._remove
_expected
_call
_re
.sub('', test
)
4608 arg
.GetValidArg(func
) \
4609 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4612 arg
.GetValidGLArg(func
) \
4613 for arg
in func
.GetOriginalArgs()
4615 gl_func_name
= func
.GetGLTestFunctionName()
4618 'gl_func_name': gl_func_name
,
4619 'args': ", ".join(arg_strings
),
4620 'gl_args': ", ".join(gl_arg_strings
),
4622 for extra
in extras
:
4625 while (old_test
!= test
):
4628 f
.write(test
% vars)
4630 def WriteInvalidUnitTest(self
, func
, f
, test
, *extras
):
4631 """Writes an invalid unit test for the service implementation."""
4634 for invalid_arg_index
, invalid_arg
in enumerate(func
.GetOriginalArgs()):
4635 # Service implementation does not test constants, as they are not part of
4636 # the call in the service side.
4637 if invalid_arg
.IsConstant():
4640 num_invalid_values
= invalid_arg
.GetNumInvalidValues(func
)
4641 for value_index
in range(0, num_invalid_values
):
4643 parse_result
= "kNoError"
4645 for arg
in func
.GetOriginalArgs():
4646 if arg
.IsConstant():
4648 if invalid_arg
is arg
:
4649 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
4652 arg_string
= arg
.GetValidArg(func
)
4653 arg_strings
.append(arg_string
)
4655 for arg
in func
.GetOriginalArgs():
4656 gl_arg_strings
.append("_")
4657 gl_func_name
= func
.GetGLTestFunctionName()
4659 if not gl_error
== None:
4660 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4664 'arg_index': invalid_arg_index
,
4665 'value_index': value_index
,
4666 'gl_func_name': gl_func_name
,
4667 'args': ", ".join(arg_strings
),
4668 'all_but_last_args': ", ".join(arg_strings
[:-1]),
4669 'gl_args': ", ".join(gl_arg_strings
),
4670 'parse_result': parse_result
,
4671 'gl_error_test': gl_error_test
,
4673 for extra
in extras
:
4675 f
.write(test
% vars)
4677 def WriteServiceUnitTest(self
, func
, f
, *extras
):
4678 """Writes the service unit test for a command."""
4680 if func
.name
== 'Enable':
4682 TEST_P(%(test_name)s, %(name)sValidArgs) {
4683 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4684 SpecializedSetup<cmds::%(name)s, 0>(true);
4686 cmd.Init(%(args)s);"""
4687 elif func
.name
== 'Disable':
4689 TEST_P(%(test_name)s, %(name)sValidArgs) {
4690 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4691 SpecializedSetup<cmds::%(name)s, 0>(true);
4693 cmd.Init(%(args)s);"""
4696 TEST_P(%(test_name)s, %(name)sValidArgs) {
4697 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4698 SpecializedSetup<cmds::%(name)s, 0>(true);
4700 cmd.Init(%(args)s);"""
4703 decoder_->set_unsafe_es3_apis_enabled(true);
4704 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4705 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4706 decoder_->set_unsafe_es3_apis_enabled(false);
4707 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4712 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4713 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4716 self
.WriteValidUnitTest(func
, f
, valid_test
, *extras
)
4718 if not func
.IsUnsafe():
4720 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4721 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4722 SpecializedSetup<cmds::%(name)s, 0>(false);
4725 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4728 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, *extras
)
4730 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
4731 """Writes the service unit test for an immediate command."""
4732 f
.write("// TODO(gman): %s\n" % func
.name
)
4734 def WriteImmediateValidationCode(self
, func
, f
):
4735 """Writes the validation code for an immediate version of a command."""
4738 def WriteBucketServiceUnitTest(self
, func
, f
, *extras
):
4739 """Writes the service unit test for a bucket command."""
4740 f
.write("// TODO(gman): %s\n" % func
.name
)
4742 def WriteGLES2ImplementationDeclaration(self
, func
, f
):
4743 """Writes the GLES2 Implemention declaration."""
4744 impl_decl
= func
.GetInfo('impl_decl')
4745 if impl_decl
== None or impl_decl
== True:
4746 f
.write("%s %s(%s) override;\n" %
4747 (func
.return_type
, func
.original_name
,
4748 func
.MakeTypedOriginalArgString("")))
4751 def WriteGLES2CLibImplementation(self
, func
, f
):
4752 f
.write("%s GL_APIENTRY GLES2%s(%s) {\n" %
4753 (func
.return_type
, func
.name
,
4754 func
.MakeTypedOriginalArgString("")))
4755 result_string
= "return "
4756 if func
.return_type
== "void":
4758 f
.write(" %sgles2::GetGLContext()->%s(%s);\n" %
4759 (result_string
, func
.original_name
,
4760 func
.MakeOriginalArgString("")))
4763 def WriteGLES2Header(self
, func
, f
):
4764 """Writes a re-write macro for GLES"""
4765 f
.write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
4767 def WriteClientGLCallLog(self
, func
, f
):
4768 """Writes a logging macro for the client side code."""
4770 if len(func
.GetOriginalArgs()):
4773 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4774 (func
.original_name
, comma
, func
.MakeLogArgString()))
4776 def WriteClientGLReturnLog(self
, func
, f
):
4777 """Writes the return value logging code."""
4778 if func
.return_type
!= "void":
4779 f
.write(' GPU_CLIENT_LOG("return:" << result)\n')
4781 def WriteGLES2ImplementationHeader(self
, func
, f
):
4782 """Writes the GLES2 Implemention."""
4783 self
.WriteGLES2ImplementationDeclaration(func
, f
)
4785 def WriteGLES2TraceImplementationHeader(self
, func
, f
):
4786 """Writes the GLES2 Trace Implemention header."""
4787 f
.write("%s %s(%s) override;\n" %
4788 (func
.return_type
, func
.original_name
,
4789 func
.MakeTypedOriginalArgString("")))
4791 def WriteGLES2TraceImplementation(self
, func
, f
):
4792 """Writes the GLES2 Trace Implemention."""
4793 f
.write("%s GLES2TraceImplementation::%s(%s) {\n" %
4794 (func
.return_type
, func
.original_name
,
4795 func
.MakeTypedOriginalArgString("")))
4796 result_string
= "return "
4797 if func
.return_type
== "void":
4799 f
.write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4801 f
.write(" %sgl_->%s(%s);\n" %
4802 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
4806 def WriteGLES2Implementation(self
, func
, f
):
4807 """Writes the GLES2 Implemention."""
4808 impl_func
= func
.GetInfo('impl_func')
4809 impl_decl
= func
.GetInfo('impl_decl')
4810 gen_cmd
= func
.GetInfo('gen_cmd')
4811 if (func
.can_auto_generate
and
4812 (impl_func
== None or impl_func
== True) and
4813 (impl_decl
== None or impl_decl
== True) and
4814 (gen_cmd
== None or gen_cmd
== True)):
4815 f
.write("%s GLES2Implementation::%s(%s) {\n" %
4816 (func
.return_type
, func
.original_name
,
4817 func
.MakeTypedOriginalArgString("")))
4818 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4819 self
.WriteClientGLCallLog(func
, f
)
4820 func
.WriteDestinationInitalizationValidation(f
)
4821 for arg
in func
.GetOriginalArgs():
4822 arg
.WriteClientSideValidationCode(f
, func
)
4823 f
.write(" helper_->%s(%s);\n" %
4824 (func
.name
, func
.MakeHelperArgString("")))
4825 f
.write(" CheckGLError();\n")
4826 self
.WriteClientGLReturnLog(func
, f
)
4830 def WriteGLES2InterfaceHeader(self
, func
, f
):
4831 """Writes the GLES2 Interface."""
4832 f
.write("virtual %s %s(%s) = 0;\n" %
4833 (func
.return_type
, func
.original_name
,
4834 func
.MakeTypedOriginalArgString("")))
4836 def WriteMojoGLES2ImplHeader(self
, func
, f
):
4837 """Writes the Mojo GLES2 implementation header."""
4838 f
.write("%s %s(%s) override;\n" %
4839 (func
.return_type
, func
.original_name
,
4840 func
.MakeTypedOriginalArgString("")))
4842 def WriteMojoGLES2Impl(self
, func
, f
):
4843 """Writes the Mojo GLES2 implementation."""
4844 f
.write("%s MojoGLES2Impl::%s(%s) {\n" %
4845 (func
.return_type
, func
.original_name
,
4846 func
.MakeTypedOriginalArgString("")))
4847 extensions
= ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4848 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4849 "occlusion_query_EXT", "CHROMIUM_image",
4850 "CHROMIUM_copy_texture",
4851 "CHROMIUM_pixel_transfer_buffer_object"]
4852 if func
.IsCoreGLFunction() or func
.GetInfo("extension") in extensions
:
4853 f
.write("MojoGLES2MakeCurrent(context_);");
4854 func_return
= "gl" + func
.original_name
+ "(" + \
4855 func
.MakeOriginalArgString("") + ");"
4856 if func
.return_type
== "void":
4857 f
.write(func_return
);
4859 f
.write("return " + func_return
);
4861 f
.write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4862 func
.original_name
);
4863 if func
.return_type
!= "void":
4864 f
.write("return 0;")
4867 def WriteGLES2InterfaceStub(self
, func
, f
):
4868 """Writes the GLES2 Interface stub declaration."""
4869 f
.write("%s %s(%s) override;\n" %
4870 (func
.return_type
, func
.original_name
,
4871 func
.MakeTypedOriginalArgString("")))
4873 def WriteGLES2InterfaceStubImpl(self
, func
, f
):
4874 """Writes the GLES2 Interface stub declaration."""
4875 args
= func
.GetOriginalArgs()
4876 arg_string
= ", ".join(
4877 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
4878 f
.write("%s GLES2InterfaceStub::%s(%s) {\n" %
4879 (func
.return_type
, func
.original_name
, arg_string
))
4880 if func
.return_type
!= "void":
4881 f
.write(" return 0;\n")
4884 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
4885 """Writes the GLES2 Implemention unit test."""
4886 client_test
= func
.GetInfo('client_test')
4887 if (func
.can_auto_generate
and
4888 (client_test
== None or client_test
== True)):
4890 TEST_F(GLES2ImplementationTest, %(name)s) {
4895 expected.cmd.Init(%(cmd_args)s);
4897 gl_->%(name)s(%(args)s);
4898 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4902 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
4906 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
4911 'args': ", ".join(gl_arg_strings
),
4912 'cmd_args': ", ".join(cmd_arg_strings
),
4915 # Test constants for invalid values, as they are not tested by the
4917 constants
= [arg
for arg
in func
.GetOriginalArgs() if arg
.IsConstant()]
4920 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4921 gl_->%(name)s(%(args)s);
4922 EXPECT_TRUE(NoCommandsWritten());
4923 EXPECT_EQ(%(gl_error)s, CheckError());
4926 for invalid_arg
in constants
:
4928 invalid
= invalid_arg
.GetInvalidArg(func
)
4929 for arg
in func
.GetOriginalArgs():
4930 if arg
is invalid_arg
:
4931 gl_arg_strings
.append(invalid
[0])
4933 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
4937 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
4938 'args': ", ".join(gl_arg_strings
),
4939 'gl_error': invalid
[2],
4942 if client_test
!= False:
4943 f
.write("// TODO(zmo): Implement unit test for %s\n" % func
.name
)
4945 def WriteDestinationInitalizationValidation(self
, func
, f
):
4946 """Writes the client side destintion initialization validation."""
4947 for arg
in func
.GetOriginalArgs():
4948 arg
.WriteDestinationInitalizationValidation(f
, func
)
4950 def WriteTraceEvent(self
, func
, f
):
4951 f
.write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4954 def WriteImmediateCmdComputeSize(self
, func
, f
):
4955 """Writes the size computation code for the immediate version of a cmd."""
4956 f
.write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4957 f
.write(" return static_cast<uint32_t>(\n")
4958 f
.write(" sizeof(ValueType) + // NOLINT\n")
4959 f
.write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4963 def WriteImmediateCmdSetHeader(self
, func
, f
):
4964 """Writes the SetHeader function for the immediate version of a cmd."""
4965 f
.write(" void SetHeader(uint32_t size_in_bytes) {\n")
4966 f
.write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4970 def WriteImmediateCmdInit(self
, func
, f
):
4971 """Writes the Init function for the immediate version of a command."""
4972 raise NotImplementedError(func
.name
)
4974 def WriteImmediateCmdSet(self
, func
, f
):
4975 """Writes the Set function for the immediate version of a command."""
4976 raise NotImplementedError(func
.name
)
4978 def WriteCmdHelper(self
, func
, f
):
4979 """Writes the cmd helper definition for a cmd."""
4980 code
= """ void %(name)s(%(typed_args)s) {
4981 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4990 "typed_args": func
.MakeTypedCmdArgString(""),
4991 "args": func
.MakeCmdArgString(""),
4994 def WriteImmediateCmdHelper(self
, func
, f
):
4995 """Writes the cmd helper definition for the immediate version of a cmd."""
4996 code
= """ void %(name)s(%(typed_args)s) {
4997 const uint32_t s = 0; // TODO(gman): compute correct size
4998 gles2::cmds::%(name)s* c =
4999 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
5008 "typed_args": func
.MakeTypedCmdArgString(""),
5009 "args": func
.MakeCmdArgString(""),
5013 class StateSetHandler(TypeHandler
):
5014 """Handler for commands that simply set state."""
5016 def WriteHandlerImplementation(self
, func
, f
):
5017 """Overrriden from TypeHandler."""
5018 state_name
= func
.GetInfo('state')
5019 state
= _STATES
[state_name
]
5020 states
= state
['states']
5021 args
= func
.GetOriginalArgs()
5022 for ndx
,item
in enumerate(states
):
5024 if 'range_checks' in item
:
5025 for range_check
in item
['range_checks']:
5026 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
5027 if 'nan_check' in item
:
5028 # Drivers might generate an INVALID_VALUE error when a value is set
5029 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
5030 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
5031 # Make this behavior consistent within Chromium, and avoid leaking GL
5032 # errors by generating the error in the command buffer instead of
5033 # letting the GL driver generate it.
5034 code
.append("std::isnan(%s)" % args
[ndx
].name
)
5036 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5038 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
5039 ' "%s", "%s out of range");\n' %
5040 (func
.name
, args
[ndx
].name
))
5041 f
.write(" return error::kNoError;\n")
5044 for ndx
,item
in enumerate(states
):
5045 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
5046 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5047 for ndx
,item
in enumerate(states
):
5048 f
.write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
5049 if 'state_flag' in state
:
5050 f
.write(" %s = true;\n" % state
['state_flag'])
5051 if not func
.GetInfo("no_gl"):
5052 for ndx
,item
in enumerate(states
):
5053 if item
.get('cached', False):
5054 f
.write(" state_.%s = %s;\n" %
5055 (CachedStateName(item
), args
[ndx
].name
))
5056 f
.write(" %s(%s);\n" %
5057 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5060 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5061 """Overrriden from TypeHandler."""
5062 TypeHandler
.WriteServiceUnitTest(self
, func
, f
, *extras
)
5063 state_name
= func
.GetInfo('state')
5064 state
= _STATES
[state_name
]
5065 states
= state
['states']
5066 for ndx
,item
in enumerate(states
):
5067 if 'range_checks' in item
:
5068 for check_ndx
, range_check
in enumerate(item
['range_checks']):
5070 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
5071 SpecializedSetup<cmds::%(name)s, 0>(false);
5074 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5075 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5080 arg
.GetValidArg(func
) \
5081 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
5084 arg_strings
[ndx
] = range_check
['test_value']
5088 'check_ndx': check_ndx
,
5089 'args': ", ".join(arg_strings
),
5091 for extra
in extras
:
5093 f
.write(valid_test
% vars)
5094 if 'nan_check' in item
:
5096 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
5097 SpecializedSetup<cmds::%(name)s, 0>(false);
5100 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5101 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5106 arg
.GetValidArg(func
) \
5107 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
5110 arg_strings
[ndx
] = 'nanf("")'
5114 'args': ", ".join(arg_strings
),
5116 for extra
in extras
:
5118 f
.write(valid_test
% vars)
5121 class StateSetRGBAlphaHandler(TypeHandler
):
5122 """Handler for commands that simply set state that have rgb/alpha."""
5124 def WriteHandlerImplementation(self
, func
, f
):
5125 """Overrriden from TypeHandler."""
5126 state_name
= func
.GetInfo('state')
5127 state
= _STATES
[state_name
]
5128 states
= state
['states']
5129 args
= func
.GetOriginalArgs()
5130 num_args
= len(args
)
5132 for ndx
,item
in enumerate(states
):
5133 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
5134 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5135 for ndx
, item
in enumerate(states
):
5136 f
.write(" state_.%s = %s;\n" %
5137 (item
['name'], args
[ndx
% num_args
].name
))
5138 if 'state_flag' in state
:
5139 f
.write(" %s = true;\n" % state
['state_flag'])
5140 if not func
.GetInfo("no_gl"):
5141 f
.write(" %s(%s);\n" %
5142 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5146 class StateSetFrontBackSeparateHandler(TypeHandler
):
5147 """Handler for commands that simply set state that have front/back."""
5149 def WriteHandlerImplementation(self
, func
, f
):
5150 """Overrriden from TypeHandler."""
5151 state_name
= func
.GetInfo('state')
5152 state
= _STATES
[state_name
]
5153 states
= state
['states']
5154 args
= func
.GetOriginalArgs()
5156 num_args
= len(args
)
5157 f
.write(" bool changed = false;\n")
5158 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
5159 f
.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5160 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
5162 for ndx
, item
in enumerate(group
):
5163 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
5164 f
.write(" changed |= %s;\n" % " ||\n ".join(code
))
5166 f
.write(" if (changed) {\n")
5167 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
5168 f
.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5169 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
5170 for ndx
, item
in enumerate(group
):
5171 f
.write(" state_.%s = %s;\n" %
5172 (item
['name'], args
[ndx
+ 1].name
))
5174 if 'state_flag' in state
:
5175 f
.write(" %s = true;\n" % state
['state_flag'])
5176 if not func
.GetInfo("no_gl"):
5177 f
.write(" %s(%s);\n" %
5178 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5182 class StateSetFrontBackHandler(TypeHandler
):
5183 """Handler for commands that simply set state that set both front/back."""
5185 def WriteHandlerImplementation(self
, func
, f
):
5186 """Overrriden from TypeHandler."""
5187 state_name
= func
.GetInfo('state')
5188 state
= _STATES
[state_name
]
5189 states
= state
['states']
5190 args
= func
.GetOriginalArgs()
5191 num_args
= len(args
)
5193 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
5194 for ndx
, item
in enumerate(group
):
5195 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
5196 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5197 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
5198 for ndx
, item
in enumerate(group
):
5199 f
.write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
5200 if 'state_flag' in state
:
5201 f
.write(" %s = true;\n" % state
['state_flag'])
5202 if not func
.GetInfo("no_gl"):
5203 f
.write(" %s(%s);\n" %
5204 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5208 class StateSetNamedParameter(TypeHandler
):
5209 """Handler for commands that set a state chosen with an enum parameter."""
5211 def WriteHandlerImplementation(self
, func
, f
):
5212 """Overridden from TypeHandler."""
5213 state_name
= func
.GetInfo('state')
5214 state
= _STATES
[state_name
]
5215 states
= state
['states']
5216 args
= func
.GetOriginalArgs()
5217 num_args
= len(args
)
5218 assert num_args
== 2
5219 f
.write(" switch (%s) {\n" % args
[0].name
)
5220 for state
in states
:
5221 f
.write(" case %s:\n" % state
['enum'])
5222 f
.write(" if (state_.%s != %s) {\n" %
5223 (state
['name'], args
[1].name
))
5224 f
.write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
5225 if not func
.GetInfo("no_gl"):
5226 f
.write(" %s(%s);\n" %
5227 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5229 f
.write(" break;\n")
5230 f
.write(" default:\n")
5231 f
.write(" NOTREACHED();\n")
5235 class CustomHandler(TypeHandler
):
5236 """Handler for commands that are auto-generated but require minor tweaks."""
5238 def WriteServiceImplementation(self
, func
, f
):
5239 """Overrriden from TypeHandler."""
5242 def WriteImmediateServiceImplementation(self
, func
, f
):
5243 """Overrriden from TypeHandler."""
5246 def WriteBucketServiceImplementation(self
, func
, f
):
5247 """Overrriden from TypeHandler."""
5250 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5251 """Overrriden from TypeHandler."""
5252 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5254 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5255 """Overrriden from TypeHandler."""
5256 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5258 def WriteImmediateCmdGetTotalSize(self
, func
, f
):
5259 """Overrriden from TypeHandler."""
5261 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5263 def WriteImmediateCmdInit(self
, func
, f
):
5264 """Overrriden from TypeHandler."""
5265 f
.write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5266 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5267 f
.write(" SetHeader(total_size);\n")
5268 args
= func
.GetCmdArgs()
5270 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5274 def WriteImmediateCmdSet(self
, func
, f
):
5275 """Overrriden from TypeHandler."""
5276 copy_args
= func
.MakeCmdArgString("_", False)
5277 f
.write(" void* Set(void* cmd%s) {\n" %
5278 func
.MakeTypedCmdArgString("_", True))
5279 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5280 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5281 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5282 "cmd, total_size);\n")
5287 class HandWrittenHandler(CustomHandler
):
5288 """Handler for comands where everything must be written by hand."""
5290 def InitFunction(self
, func
):
5291 """Add or adjust anything type specific for this function."""
5292 CustomHandler
.InitFunction(self
, func
)
5293 func
.can_auto_generate
= False
5295 def NeedsDataTransferFunction(self
, func
):
5296 """Overriden from TypeHandler."""
5297 # If specified explicitly, force the data transfer method.
5298 if func
.GetInfo('data_transfer_methods'):
5302 def WriteStruct(self
, func
, f
):
5303 """Overrriden from TypeHandler."""
5306 def WriteDocs(self
, func
, f
):
5307 """Overrriden from TypeHandler."""
5310 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5311 """Overrriden from TypeHandler."""
5312 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5314 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5315 """Overrriden from TypeHandler."""
5316 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5318 def WriteBucketServiceUnitTest(self
, func
, f
, *extras
):
5319 """Overrriden from TypeHandler."""
5320 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5322 def WriteServiceImplementation(self
, func
, f
):
5323 """Overrriden from TypeHandler."""
5326 def WriteImmediateServiceImplementation(self
, func
, f
):
5327 """Overrriden from TypeHandler."""
5330 def WriteBucketServiceImplementation(self
, func
, f
):
5331 """Overrriden from TypeHandler."""
5334 def WriteImmediateCmdHelper(self
, func
, f
):
5335 """Overrriden from TypeHandler."""
5338 def WriteCmdHelper(self
, func
, f
):
5339 """Overrriden from TypeHandler."""
5342 def WriteFormatTest(self
, func
, f
):
5343 """Overrriden from TypeHandler."""
5344 f
.write("// TODO(gman): Write test for %s\n" % func
.name
)
5346 def WriteImmediateFormatTest(self
, func
, f
):
5347 """Overrriden from TypeHandler."""
5348 f
.write("// TODO(gman): Write test for %s\n" % func
.name
)
5351 class ManualHandler(CustomHandler
):
5352 """Handler for commands who's handlers must be written by hand."""
5354 def InitFunction(self
, func
):
5355 """Overrriden from TypeHandler."""
5356 if (func
.name
== 'CompressedTexImage2DBucket' or
5357 func
.name
== 'CompressedTexImage3DBucket'):
5358 func
.cmd_args
= func
.cmd_args
[:-1]
5359 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5361 CustomHandler
.InitFunction(self
, func
)
5363 def WriteServiceImplementation(self
, func
, f
):
5364 """Overrriden from TypeHandler."""
5367 def WriteBucketServiceImplementation(self
, func
, f
):
5368 """Overrriden from TypeHandler."""
5371 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5372 """Overrriden from TypeHandler."""
5373 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5375 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5376 """Overrriden from TypeHandler."""
5377 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5379 def WriteImmediateServiceImplementation(self
, func
, f
):
5380 """Overrriden from TypeHandler."""
5383 def WriteImmediateFormatTest(self
, func
, f
):
5384 """Overrriden from TypeHandler."""
5385 f
.write("// TODO(gman): Implement test for %s\n" % func
.name
)
5387 def WriteGLES2Implementation(self
, func
, f
):
5388 """Overrriden from TypeHandler."""
5389 if func
.GetInfo('impl_func'):
5390 super(ManualHandler
, self
).WriteGLES2Implementation(func
, f
)
5392 def WriteGLES2ImplementationHeader(self
, func
, f
):
5393 """Overrriden from TypeHandler."""
5394 f
.write("%s %s(%s) override;\n" %
5395 (func
.return_type
, func
.original_name
,
5396 func
.MakeTypedOriginalArgString("")))
5399 def WriteImmediateCmdGetTotalSize(self
, func
, f
):
5400 """Overrriden from TypeHandler."""
5401 # TODO(gman): Move this data to _FUNCTION_INFO?
5402 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, f
)
5405 class DataHandler(TypeHandler
):
5406 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5407 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5409 def InitFunction(self
, func
):
5410 """Overrriden from TypeHandler."""
5411 if (func
.name
== 'CompressedTexSubImage2DBucket' or
5412 func
.name
== 'CompressedTexSubImage3DBucket'):
5413 func
.cmd_args
= func
.cmd_args
[:-1]
5414 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5416 def WriteGetDataSizeCode(self
, func
, f
):
5417 """Overrriden from TypeHandler."""
5418 # TODO(gman): Move this data to _FUNCTION_INFO?
5420 if name
.endswith("Immediate"):
5422 if name
== 'BufferData' or name
== 'BufferSubData':
5423 f
.write(" uint32_t data_size = size;\n")
5424 elif (name
== 'CompressedTexImage2D' or
5425 name
== 'CompressedTexSubImage2D' or
5426 name
== 'CompressedTexImage3D' or
5427 name
== 'CompressedTexSubImage3D'):
5428 f
.write(" uint32_t data_size = imageSize;\n")
5429 elif (name
== 'CompressedTexSubImage2DBucket' or
5430 name
== 'CompressedTexSubImage3DBucket'):
5431 f
.write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5432 f
.write(" uint32_t data_size = bucket->size();\n")
5433 f
.write(" GLsizei imageSize = data_size;\n")
5434 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
5435 code
= """ uint32_t data_size;
5436 if (!GLES2Util::ComputeImageDataSize(
5437 width, height, format, type, unpack_alignment_, &data_size)) {
5438 return error::kOutOfBounds;
5444 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5446 def WriteImmediateCmdGetTotalSize(self
, func
, f
):
5447 """Overrriden from TypeHandler."""
5450 def WriteImmediateCmdInit(self
, func
, f
):
5451 """Overrriden from TypeHandler."""
5452 f
.write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5453 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5454 f
.write(" SetHeader(total_size);\n")
5455 args
= func
.GetCmdArgs()
5457 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5461 def WriteImmediateCmdSet(self
, func
, f
):
5462 """Overrriden from TypeHandler."""
5463 copy_args
= func
.MakeCmdArgString("_", False)
5464 f
.write(" void* Set(void* cmd%s) {\n" %
5465 func
.MakeTypedCmdArgString("_", True))
5466 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5467 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5468 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5469 "cmd, total_size);\n")
5473 def WriteImmediateFormatTest(self
, func
, f
):
5474 """Overrriden from TypeHandler."""
5475 # TODO(gman): Remove this exception.
5476 f
.write("// TODO(gman): Implement test for %s\n" % func
.name
)
5479 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5480 """Overrriden from TypeHandler."""
5481 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5483 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5484 """Overrriden from TypeHandler."""
5485 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5487 def WriteBucketServiceImplementation(self
, func
, f
):
5488 """Overrriden from TypeHandler."""
5489 if ((not func
.name
== 'CompressedTexSubImage2DBucket') and
5490 (not func
.name
== 'CompressedTexSubImage3DBucket')):
5491 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, f
)
5494 class BindHandler(TypeHandler
):
5495 """Handler for glBind___ type functions."""
5497 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5498 """Overrriden from TypeHandler."""
5500 if len(func
.GetOriginalArgs()) == 1:
5502 TEST_P(%(test_name)s, %(name)sValidArgs) {
5503 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5504 SpecializedSetup<cmds::%(name)s, 0>(true);
5506 cmd.Init(%(args)s);"""
5509 decoder_->set_unsafe_es3_apis_enabled(true);
5510 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5511 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5512 decoder_->set_unsafe_es3_apis_enabled(false);
5513 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5518 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5519 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5522 if func
.GetInfo("gen_func"):
5524 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5525 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5526 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5527 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5528 SpecializedSetup<cmds::%(name)s, 0>(true);
5530 cmd.Init(kNewClientId);
5531 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5532 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5533 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5536 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5537 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
5538 'gl_gen_func_name': func
.GetInfo("gen_func"),
5542 TEST_P(%(test_name)s, %(name)sValidArgs) {
5543 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5544 SpecializedSetup<cmds::%(name)s, 0>(true);
5546 cmd.Init(%(args)s);"""
5549 decoder_->set_unsafe_es3_apis_enabled(true);
5550 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5551 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5552 decoder_->set_unsafe_es3_apis_enabled(false);
5553 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5558 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5559 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5562 if func
.GetInfo("gen_func"):
5564 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5566 %(gl_func_name)s(%(gl_args_with_new_id)s));
5567 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5568 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5569 SpecializedSetup<cmds::%(name)s, 0>(true);
5571 cmd.Init(%(args_with_new_id)s);"""
5574 decoder_->set_unsafe_es3_apis_enabled(true);
5575 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5576 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5577 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5578 decoder_->set_unsafe_es3_apis_enabled(false);
5579 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5584 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5585 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5586 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5590 gl_args_with_new_id
= []
5591 args_with_new_id
= []
5592 for arg
in func
.GetOriginalArgs():
5593 if hasattr(arg
, 'resource_type'):
5594 gl_args_with_new_id
.append('kNewServiceId')
5595 args_with_new_id
.append('kNewClientId')
5597 gl_args_with_new_id
.append(arg
.GetValidGLArg(func
))
5598 args_with_new_id
.append(arg
.GetValidArg(func
))
5599 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5600 'args_with_new_id': ", ".join(args_with_new_id
),
5601 'gl_args_with_new_id': ", ".join(gl_args_with_new_id
),
5602 'resource_type': func
.GetResourceIdArg().resource_type
,
5603 'gl_gen_func_name': func
.GetInfo("gen_func"),
5607 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5608 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5609 SpecializedSetup<cmds::%(name)s, 0>(false);
5612 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5615 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, *extras
)
5617 def WriteGLES2Implementation(self
, func
, f
):
5618 """Writes the GLES2 Implemention."""
5620 impl_func
= func
.GetInfo('impl_func')
5621 impl_decl
= func
.GetInfo('impl_decl')
5623 if (func
.can_auto_generate
and
5624 (impl_func
== None or impl_func
== True) and
5625 (impl_decl
== None or impl_decl
== True)):
5627 f
.write("%s GLES2Implementation::%s(%s) {\n" %
5628 (func
.return_type
, func
.original_name
,
5629 func
.MakeTypedOriginalArgString("")))
5630 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5631 func
.WriteDestinationInitalizationValidation(f
)
5632 self
.WriteClientGLCallLog(func
, f
)
5633 for arg
in func
.GetOriginalArgs():
5634 arg
.WriteClientSideValidationCode(f
, func
)
5636 code
= """ if (Is%(type)sReservedId(%(id)s)) {
5637 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5640 %(name)sHelper(%(arg_string)s);
5645 name_arg
= func
.GetResourceIdArg()
5648 'arg_string': func
.MakeOriginalArgString(""),
5649 'id': name_arg
.name
,
5650 'type': name_arg
.resource_type
,
5651 'lc_type': name_arg
.resource_type
.lower(),
5654 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
5655 """Overrriden from TypeHandler."""
5656 client_test
= func
.GetInfo('client_test')
5657 if client_test
== False:
5660 TEST_F(GLES2ImplementationTest, %(name)s) {
5665 expected.cmd.Init(%(cmd_args)s);
5667 gl_->%(name)s(%(args)s);
5668 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5669 if not func
.IsUnsafe():
5672 gl_->%(name)s(%(args)s);
5673 EXPECT_TRUE(NoCommandsWritten());"""
5678 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
5681 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
5686 'args': ", ".join(gl_arg_strings
),
5687 'cmd_args': ", ".join(cmd_arg_strings
),
5691 class GENnHandler(TypeHandler
):
5692 """Handler for glGen___ type functions."""
5694 def InitFunction(self
, func
):
5695 """Overrriden from TypeHandler."""
5698 def WriteGetDataSizeCode(self
, func
, f
):
5699 """Overrriden from TypeHandler."""
5700 code
= """ uint32_t data_size;
5701 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5702 return error::kOutOfBounds;
5707 def WriteHandlerImplementation (self
, func
, f
):
5708 """Overrriden from TypeHandler."""
5709 f
.write(" if (!%sHelper(n, %s)) {\n"
5710 " return error::kInvalidArguments;\n"
5712 (func
.name
, func
.GetLastOriginalArg().name
))
5714 def WriteImmediateHandlerImplementation(self
, func
, f
):
5715 """Overrriden from TypeHandler."""
5717 f
.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5718 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5719 return error::kInvalidArguments;
5722 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5723 gl%(func_name)s(n, service_ids.get());
5724 for (GLsizei ii = 0; ii < n; ++ii) {
5725 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5727 """ % { 'func_name': func
.original_name
,
5728 'last_arg_name': func
.GetLastOriginalArg().name
,
5729 'resource_name': func
.GetInfo('resource_type') })
5731 f
.write(" if (!%sHelper(n, %s)) {\n"
5732 " return error::kInvalidArguments;\n"
5734 (func
.original_name
, func
.GetLastOriginalArg().name
))
5736 def WriteGLES2Implementation(self
, func
, f
):
5737 """Overrriden from TypeHandler."""
5738 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
5739 for (GLsizei i = 0; i < n; ++i) {
5740 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5742 });""" % func
.GetOriginalArgs()[1].name
)
5744 'log_code': log_code
,
5745 'return_type': func
.return_type
,
5746 'name': func
.original_name
,
5747 'typed_args': func
.MakeTypedOriginalArgString(""),
5748 'args': func
.MakeOriginalArgString(""),
5749 'resource_types': func
.GetInfo('resource_types'),
5750 'count_name': func
.GetOriginalArgs()[0].name
,
5753 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5755 func
.WriteDestinationInitalizationValidation(f
)
5756 self
.WriteClientGLCallLog(func
, f
)
5757 for arg
in func
.GetOriginalArgs():
5758 arg
.WriteClientSideValidationCode(f
, func
)
5759 not_shared
= func
.GetInfo('not_shared')
5763 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5764 for (GLsizei ii = 0; ii < n; ++ii)
5765 %s[ii] = id_allocator->AllocateID();""" %
5766 (func
.GetInfo('resource_types'), func
.GetOriginalArgs()[1].name
))
5768 alloc_code
= (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5769 MakeIds(this, 0, %(args)s);""" % args
)
5770 args
['alloc_code'] = alloc_code
5772 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5774 %(name)sHelper(%(args)s);
5775 helper_->%(name)sImmediate(%(args)s);
5776 if (share_group_->bind_generates_resource())
5777 helper_->CommandBufferHelper::Flush();
5783 f
.write(code
% args
)
5785 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
5786 """Overrriden from TypeHandler."""
5788 TEST_F(GLES2ImplementationTest, %(name)s) {
5789 GLuint ids[2] = { 0, };
5791 cmds::%(name)sImmediate gen;
5795 expected.gen.Init(arraysize(ids), &ids[0]);
5796 expected.data[0] = k%(types)sStartId;
5797 expected.data[1] = k%(types)sStartId + 1;
5798 gl_->%(name)s(arraysize(ids), &ids[0]);
5799 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5800 EXPECT_EQ(k%(types)sStartId, ids[0]);
5801 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5806 'types': func
.GetInfo('resource_types'),
5809 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5810 """Overrriden from TypeHandler."""
5812 TEST_P(%(test_name)s, %(name)sValidArgs) {
5813 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5814 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5815 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5816 SpecializedSetup<cmds::%(name)s, 0>(true);
5819 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5820 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5824 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5825 EXPECT_EQ(kNewServiceId, service_id)
5830 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5833 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5834 'resource_name': func
.GetInfo('resource_type'),
5837 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5838 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5839 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5840 SpecializedSetup<cmds::%(name)s, 0>(false);
5843 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5846 self
.WriteValidUnitTest(func
, f
, invalid_test
, {
5847 'resource_name': func
.GetInfo('resource_type').lower(),
5850 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5851 """Overrriden from TypeHandler."""
5853 TEST_P(%(test_name)s, %(name)sValidArgs) {
5854 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5855 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5856 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5857 GLuint temp = kNewClientId;
5858 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5861 decoder_->set_unsafe_es3_apis_enabled(true);"""
5863 cmd->Init(1, &temp);
5864 EXPECT_EQ(error::kNoError,
5865 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5866 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5870 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5871 EXPECT_EQ(kNewServiceId, service_id);
5872 decoder_->set_unsafe_es3_apis_enabled(false);
5873 EXPECT_EQ(error::kUnknownCommand,
5874 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5879 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5882 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5883 'resource_name': func
.GetInfo('resource_type'),
5886 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5887 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5888 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5889 SpecializedSetup<cmds::%(name)s, 0>(false);
5890 cmd->Init(1, &client_%(resource_name)s_id_);"""
5893 decoder_->set_unsafe_es3_apis_enabled(true);
5894 EXPECT_EQ(error::kInvalidArguments,
5895 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5896 decoder_->set_unsafe_es3_apis_enabled(false);
5901 EXPECT_EQ(error::kInvalidArguments,
5902 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5905 self
.WriteValidUnitTest(func
, f
, invalid_test
, {
5906 'resource_name': func
.GetInfo('resource_type').lower(),
5909 def WriteImmediateCmdComputeSize(self
, func
, f
):
5910 """Overrriden from TypeHandler."""
5911 f
.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5913 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5916 f
.write(" static uint32_t ComputeSize(GLsizei n) {\n")
5917 f
.write(" return static_cast<uint32_t>(\n")
5918 f
.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5922 def WriteImmediateCmdSetHeader(self
, func
, f
):
5923 """Overrriden from TypeHandler."""
5924 f
.write(" void SetHeader(GLsizei n) {\n")
5925 f
.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5929 def WriteImmediateCmdInit(self
, func
, f
):
5930 """Overrriden from TypeHandler."""
5931 last_arg
= func
.GetLastOriginalArg()
5932 f
.write(" void Init(%s, %s _%s) {\n" %
5933 (func
.MakeTypedCmdArgString("_"),
5934 last_arg
.type, last_arg
.name
))
5935 f
.write(" SetHeader(_n);\n")
5936 args
= func
.GetCmdArgs()
5938 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5939 f
.write(" memcpy(ImmediateDataAddress(this),\n")
5940 f
.write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
5944 def WriteImmediateCmdSet(self
, func
, f
):
5945 """Overrriden from TypeHandler."""
5946 last_arg
= func
.GetLastOriginalArg()
5947 copy_args
= func
.MakeCmdArgString("_", False)
5948 f
.write(" void* Set(void* cmd%s, %s _%s) {\n" %
5949 (func
.MakeTypedCmdArgString("_", True),
5950 last_arg
.type, last_arg
.name
))
5951 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5952 (copy_args
, last_arg
.name
))
5953 f
.write(" const uint32_t size = ComputeSize(_n);\n")
5954 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5959 def WriteImmediateCmdHelper(self
, func
, f
):
5960 """Overrriden from TypeHandler."""
5961 code
= """ void %(name)s(%(typed_args)s) {
5962 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5963 gles2::cmds::%(name)s* c =
5964 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5973 "typed_args": func
.MakeTypedOriginalArgString(""),
5974 "args": func
.MakeOriginalArgString(""),
5977 def WriteImmediateFormatTest(self
, func
, f
):
5978 """Overrriden from TypeHandler."""
5979 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
5980 f
.write(" static GLuint ids[] = { 12, 23, 34, };\n")
5981 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5982 (func
.name
, func
.name
))
5983 f
.write(" void* next_cmd = cmd.Set(\n")
5984 f
.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5985 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5987 f
.write(" cmd.header.command);\n")
5988 f
.write(" EXPECT_EQ(sizeof(cmd) +\n")
5989 f
.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5990 f
.write(" cmd.header.size * 4u);\n")
5991 f
.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5992 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
5993 f
.write(" next_cmd, sizeof(cmd) +\n")
5994 f
.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5995 f
.write(" // TODO(gman): Check that ids were inserted;\n")
6000 class CreateHandler(TypeHandler
):
6001 """Handler for glCreate___ type functions."""
6003 def InitFunction(self
, func
):
6004 """Overrriden from TypeHandler."""
6005 func
.AddCmdArg(Argument("client_id", 'uint32_t'))
6007 def __GetResourceType(self
, func
):
6008 if func
.return_type
== "GLsync":
6011 return func
.name
[6:] # Create*
6013 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6014 """Overrriden from TypeHandler."""
6016 TEST_P(%(test_name)s, %(name)sValidArgs) {
6017 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
6018 .WillOnce(Return(%(const_service_id)s));
6019 SpecializedSetup<cmds::%(name)s, 0>(true);
6021 cmd.Init(%(args)s%(comma)skNewClientId);"""
6024 decoder_->set_unsafe_es3_apis_enabled(true);"""
6026 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6027 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6030 %(return_type)s service_id = 0;
6031 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
6032 EXPECT_EQ(%(const_service_id)s, service_id);
6033 decoder_->set_unsafe_es3_apis_enabled(false);
6034 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
6039 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
6044 for arg
in func
.GetOriginalArgs():
6045 if not arg
.IsConstant():
6049 if func
.return_type
== 'GLsync':
6050 id_type_cast
= ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
6051 "<GLsync>(kNewServiceId);\n ")
6052 const_service_id
= "kNewServiceIdGLuint"
6055 const_service_id
= "kNewServiceId"
6056 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6058 'resource_type': self
.__GetResourceType
(func
),
6059 'return_type': func
.return_type
,
6060 'id_type_cast': id_type_cast
,
6061 'const_service_id': const_service_id
,
6064 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6065 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6066 SpecializedSetup<cmds::%(name)s, 0>(false);
6068 cmd.Init(%(args)s%(comma)skNewClientId);
6069 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
6072 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, {
6076 def WriteHandlerImplementation (self
, func
, f
):
6077 """Overrriden from TypeHandler."""
6079 code
= """ uint32_t client_id = c.client_id;
6080 %(return_type)s service_id = 0;
6081 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
6082 return error::kInvalidArguments;
6084 service_id = %(gl_func_name)s(%(gl_args)s);
6086 group_->Add%(resource_name)sId(client_id, service_id);
6090 code
= """ uint32_t client_id = c.client_id;
6091 if (Get%(resource_name)s(client_id)) {
6092 return error::kInvalidArguments;
6094 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
6096 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
6100 'resource_name': self
.__GetResourceType
(func
),
6101 'return_type': func
.return_type
,
6102 'gl_func_name': func
.GetGLFunctionName(),
6103 'gl_args': func
.MakeOriginalArgString(""),
6104 'gl_args_with_comma': func
.MakeOriginalArgString("", True) })
6106 def WriteGLES2Implementation(self
, func
, f
):
6107 """Overrriden from TypeHandler."""
6108 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6109 (func
.return_type
, func
.original_name
,
6110 func
.MakeTypedOriginalArgString("")))
6111 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6112 func
.WriteDestinationInitalizationValidation(f
)
6113 self
.WriteClientGLCallLog(func
, f
)
6114 for arg
in func
.GetOriginalArgs():
6115 arg
.WriteClientSideValidationCode(f
, func
)
6116 f
.write(" GLuint client_id;\n")
6117 if func
.return_type
== "GLsync":
6119 " GetIdHandler(id_namespaces::kSyncs)->\n")
6122 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
6123 f
.write(" MakeIds(this, 0, 1, &client_id);\n")
6124 f
.write(" helper_->%s(%s);\n" %
6125 (func
.name
, func
.MakeCmdArgString("")))
6126 f
.write(' GPU_CLIENT_LOG("returned " << client_id);\n')
6127 f
.write(" CheckGLError();\n")
6128 if func
.return_type
== "GLsync":
6129 f
.write(" return reinterpret_cast<GLsync>(client_id);\n")
6131 f
.write(" return client_id;\n")
6136 class DeleteHandler(TypeHandler
):
6137 """Handler for glDelete___ single resource type functions."""
6139 def WriteServiceImplementation(self
, func
, f
):
6140 """Overrriden from TypeHandler."""
6142 TypeHandler
.WriteServiceImplementation(self
, func
, f
)
6143 # HandleDeleteShader and HandleDeleteProgram are manually written.
6146 def WriteGLES2Implementation(self
, func
, f
):
6147 """Overrriden from TypeHandler."""
6148 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6149 (func
.return_type
, func
.original_name
,
6150 func
.MakeTypedOriginalArgString("")))
6151 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6152 func
.WriteDestinationInitalizationValidation(f
)
6153 self
.WriteClientGLCallLog(func
, f
)
6154 for arg
in func
.GetOriginalArgs():
6155 arg
.WriteClientSideValidationCode(f
, func
)
6157 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
6158 f
.write(" %sHelper(%s);\n" %
6159 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
6160 f
.write(" CheckGLError();\n")
6164 def WriteHandlerImplementation (self
, func
, f
):
6165 """Overrriden from TypeHandler."""
6166 assert len(func
.GetOriginalArgs()) == 1
6167 arg
= func
.GetOriginalArgs()[0]
6169 f
.write(""" %(arg_type)s service_id = 0;
6170 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
6171 glDelete%(resource_type)s(service_id);
6172 group_->Remove%(resource_type)sId(%(arg_name)s);
6175 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
6177 """ % { 'resource_type': func
.GetInfo('resource_type'),
6178 'arg_name': arg
.name
,
6179 'arg_type': arg
.type,
6180 'func_name': func
.original_name
})
6182 f
.write(" %sHelper(%s);\n" % (func
.original_name
, arg
.name
))
6184 class DELnHandler(TypeHandler
):
6185 """Handler for glDelete___ type functions."""
6187 def WriteGetDataSizeCode(self
, func
, f
):
6188 """Overrriden from TypeHandler."""
6189 code
= """ uint32_t data_size;
6190 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6191 return error::kOutOfBounds;
6196 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
6197 """Overrriden from TypeHandler."""
6199 TEST_F(GLES2ImplementationTest, %(name)s) {
6200 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6202 cmds::%(name)sImmediate del;
6206 expected.del.Init(arraysize(ids), &ids[0]);
6207 expected.data[0] = k%(types)sStartId;
6208 expected.data[1] = k%(types)sStartId + 1;
6209 gl_->%(name)s(arraysize(ids), &ids[0]);
6210 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6215 'types': func
.GetInfo('resource_types'),
6218 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6219 """Overrriden from TypeHandler."""
6221 TEST_P(%(test_name)s, %(name)sValidArgs) {
6224 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6226 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6227 SpecializedSetup<cmds::%(name)s, 0>(true);
6230 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6231 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6233 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6236 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6237 'resource_name': func
.GetInfo('resource_type').lower(),
6238 'upper_resource_name': func
.GetInfo('resource_type'),
6241 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6242 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6243 SpecializedSetup<cmds::%(name)s, 0>(false);
6246 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6249 self
.WriteValidUnitTest(func
, f
, invalid_test
, *extras
)
6251 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
6252 """Overrriden from TypeHandler."""
6254 TEST_P(%(test_name)s, %(name)sValidArgs) {
6257 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6259 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6260 SpecializedSetup<cmds::%(name)s, 0>(true);
6261 cmd.Init(1, &client_%(resource_name)s_id_);"""
6264 decoder_->set_unsafe_es3_apis_enabled(true);"""
6266 EXPECT_EQ(error::kNoError,
6267 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6268 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6271 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6272 client_%(resource_name)s_id_, NULL));
6273 decoder_->set_unsafe_es3_apis_enabled(false);
6274 EXPECT_EQ(error::kUnknownCommand,
6275 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6281 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6284 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6285 'resource_name': func
.GetInfo('resource_type').lower(),
6286 'upper_resource_name': func
.GetInfo('resource_type'),
6289 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6290 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6291 SpecializedSetup<cmds::%(name)s, 0>(false);
6292 GLuint temp = kInvalidClientId;
6293 cmd.Init(1, &temp);"""
6296 decoder_->set_unsafe_es3_apis_enabled(true);
6297 EXPECT_EQ(error::kNoError,
6298 ExecuteImmediateCmd(cmd, sizeof(temp)));
6299 decoder_->set_unsafe_es3_apis_enabled(false);
6300 EXPECT_EQ(error::kUnknownCommand,
6301 ExecuteImmediateCmd(cmd, sizeof(temp)));
6306 EXPECT_EQ(error::kNoError,
6307 ExecuteImmediateCmd(cmd, sizeof(temp)));
6310 self
.WriteValidUnitTest(func
, f
, invalid_test
, *extras
)
6312 def WriteHandlerImplementation (self
, func
, f
):
6313 """Overrriden from TypeHandler."""
6314 f
.write(" %sHelper(n, %s);\n" %
6315 (func
.name
, func
.GetLastOriginalArg().name
))
6317 def WriteImmediateHandlerImplementation (self
, func
, f
):
6318 """Overrriden from TypeHandler."""
6320 f
.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6321 GLuint service_id = 0;
6322 if (group_->Get%(resource_type)sServiceId(
6323 %(last_arg_name)s[ii], &service_id)) {
6324 glDelete%(resource_type)ss(1, &service_id);
6325 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6328 """ % { 'resource_type': func
.GetInfo('resource_type'),
6329 'last_arg_name': func
.GetLastOriginalArg().name
})
6331 f
.write(" %sHelper(n, %s);\n" %
6332 (func
.original_name
, func
.GetLastOriginalArg().name
))
6334 def WriteGLES2Implementation(self
, func
, f
):
6335 """Overrriden from TypeHandler."""
6336 impl_decl
= func
.GetInfo('impl_decl')
6337 if impl_decl
== None or impl_decl
== True:
6339 'return_type': func
.return_type
,
6340 'name': func
.original_name
,
6341 'typed_args': func
.MakeTypedOriginalArgString(""),
6342 'args': func
.MakeOriginalArgString(""),
6343 'resource_type': func
.GetInfo('resource_type').lower(),
6344 'count_name': func
.GetOriginalArgs()[0].name
,
6347 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6349 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6350 func
.WriteDestinationInitalizationValidation(f
)
6351 self
.WriteClientGLCallLog(func
, f
)
6352 f
.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6353 for (GLsizei i = 0; i < n; ++i) {
6354 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6357 """ % func
.GetOriginalArgs()[1].name
)
6358 f
.write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6359 for (GLsizei i = 0; i < n; ++i) {
6363 """ % func
.GetOriginalArgs()[1].name
)
6364 for arg
in func
.GetOriginalArgs():
6365 arg
.WriteClientSideValidationCode(f
, func
)
6366 code
= """ %(name)sHelper(%(args)s);
6371 f
.write(code
% args
)
6373 def WriteImmediateCmdComputeSize(self
, func
, f
):
6374 """Overrriden from TypeHandler."""
6375 f
.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6377 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6380 f
.write(" static uint32_t ComputeSize(GLsizei n) {\n")
6381 f
.write(" return static_cast<uint32_t>(\n")
6382 f
.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6386 def WriteImmediateCmdSetHeader(self
, func
, f
):
6387 """Overrriden from TypeHandler."""
6388 f
.write(" void SetHeader(GLsizei n) {\n")
6389 f
.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6393 def WriteImmediateCmdInit(self
, func
, f
):
6394 """Overrriden from TypeHandler."""
6395 last_arg
= func
.GetLastOriginalArg()
6396 f
.write(" void Init(%s, %s _%s) {\n" %
6397 (func
.MakeTypedCmdArgString("_"),
6398 last_arg
.type, last_arg
.name
))
6399 f
.write(" SetHeader(_n);\n")
6400 args
= func
.GetCmdArgs()
6402 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6403 f
.write(" memcpy(ImmediateDataAddress(this),\n")
6404 f
.write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
6408 def WriteImmediateCmdSet(self
, func
, f
):
6409 """Overrriden from TypeHandler."""
6410 last_arg
= func
.GetLastOriginalArg()
6411 copy_args
= func
.MakeCmdArgString("_", False)
6412 f
.write(" void* Set(void* cmd%s, %s _%s) {\n" %
6413 (func
.MakeTypedCmdArgString("_", True),
6414 last_arg
.type, last_arg
.name
))
6415 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6416 (copy_args
, last_arg
.name
))
6417 f
.write(" const uint32_t size = ComputeSize(_n);\n")
6418 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6423 def WriteImmediateCmdHelper(self
, func
, f
):
6424 """Overrriden from TypeHandler."""
6425 code
= """ void %(name)s(%(typed_args)s) {
6426 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6427 gles2::cmds::%(name)s* c =
6428 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6437 "typed_args": func
.MakeTypedOriginalArgString(""),
6438 "args": func
.MakeOriginalArgString(""),
6441 def WriteImmediateFormatTest(self
, func
, f
):
6442 """Overrriden from TypeHandler."""
6443 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6444 f
.write(" static GLuint ids[] = { 12, 23, 34, };\n")
6445 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6446 (func
.name
, func
.name
))
6447 f
.write(" void* next_cmd = cmd.Set(\n")
6448 f
.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6449 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6451 f
.write(" cmd.header.command);\n")
6452 f
.write(" EXPECT_EQ(sizeof(cmd) +\n")
6453 f
.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6454 f
.write(" cmd.header.size * 4u);\n")
6455 f
.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6456 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
6457 f
.write(" next_cmd, sizeof(cmd) +\n")
6458 f
.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6459 f
.write(" // TODO(gman): Check that ids were inserted;\n")
6464 class GETnHandler(TypeHandler
):
6465 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6467 def NeedsDataTransferFunction(self
, func
):
6468 """Overriden from TypeHandler."""
6471 def WriteServiceImplementation(self
, func
, f
):
6472 """Overrriden from TypeHandler."""
6473 self
.WriteServiceHandlerFunctionHeader(func
, f
)
6474 last_arg
= func
.GetLastOriginalArg()
6475 # All except shm_id and shm_offset.
6476 all_but_last_args
= func
.GetCmdArgs()[:-2]
6477 for arg
in all_but_last_args
:
6480 code
= """ typedef cmds::%(func_name)s::Result Result;
6481 GLsizei num_values = 0;
6482 GetNumValuesReturnedForGLGet(pname, &num_values);
6483 Result* result = GetSharedMemoryAs<Result*>(
6484 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6485 Result::ComputeSize(num_values));
6486 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6489 'last_arg_type': last_arg
.type,
6490 'last_arg_name': last_arg
.name
,
6491 'func_name': func
.name
,
6493 func
.WriteHandlerValidation(f
)
6494 code
= """ // Check that the client initialized the result.
6495 if (result->size != 0) {
6496 return error::kInvalidArguments;
6499 shadowed
= func
.GetInfo('shadowed')
6501 f
.write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
6503 func
.WriteHandlerImplementation(f
)
6505 code
= """ result->SetNumResults(num_values);
6506 return error::kNoError;
6510 code
= """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
6511 if (error == GL_NO_ERROR) {
6512 result->SetNumResults(num_values);
6514 return error::kNoError;
6518 f
.write(code
% {'func_name': func
.name
})
6520 def WriteGLES2Implementation(self
, func
, f
):
6521 """Overrriden from TypeHandler."""
6522 impl_decl
= func
.GetInfo('impl_decl')
6523 if impl_decl
== None or impl_decl
== True:
6524 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6525 (func
.return_type
, func
.original_name
,
6526 func
.MakeTypedOriginalArgString("")))
6527 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6528 func
.WriteDestinationInitalizationValidation(f
)
6529 self
.WriteClientGLCallLog(func
, f
)
6530 for arg
in func
.GetOriginalArgs():
6531 arg
.WriteClientSideValidationCode(f
, func
)
6532 all_but_last_args
= func
.GetOriginalArgs()[:-1]
6534 has_length_arg
= False
6535 for arg
in all_but_last_args
:
6536 if arg
.type == 'GLsync':
6537 args
.append('ToGLuint(%s)' % arg
.name
)
6538 elif arg
.name
.endswith('size') and arg
.type == 'GLsizei':
6540 elif arg
.name
== 'length':
6541 has_length_arg
= True
6544 args
.append(arg
.name
)
6545 arg_string
= ", ".join(args
)
6549 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()]))
6550 self
.WriteTraceEvent(func
, f
)
6551 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6554 typedef cmds::%(func_name)s::Result Result;
6555 Result* result = GetResultAs<Result*>();
6559 result->SetNumResults(0);
6560 helper_->%(func_name)s(%(arg_string)s,
6561 GetResultShmId(), GetResultShmOffset());
6563 result->CopyResult(%(last_arg_name)s);
6564 GPU_CLIENT_LOG_CODE_BLOCK({
6565 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6566 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6572 *length = result->GetNumResults();
6579 'func_name': func
.name
,
6580 'arg_string': arg_string
,
6581 'all_arg_string': all_arg_string
,
6582 'last_arg_name': func
.GetLastOriginalArg().name
,
6585 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
6586 """Writes the GLES2 Implemention unit test."""
6588 TEST_F(GLES2ImplementationTest, %(name)s) {
6592 typedef cmds::%(name)s::Result::Type ResultType;
6593 ResultType result = 0;
6595 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6596 sizeof(uint32_t) + sizeof(ResultType));
6597 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6598 EXPECT_CALL(*command_buffer(), OnFlush())
6599 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6600 .RetiresOnSaturation();
6601 gl_->%(name)s(%(args)s, &result);
6602 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6603 EXPECT_EQ(static_cast<ResultType>(1), result);
6606 first_cmd_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func
)
6607 if not first_cmd_arg
:
6610 first_gl_arg
= func
.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6613 cmd_arg_strings
= [first_cmd_arg
]
6614 for arg
in func
.GetCmdArgs()[1:-2]:
6615 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
6616 gl_arg_strings
= [first_gl_arg
]
6617 for arg
in func
.GetOriginalArgs()[1:-1]:
6618 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
6622 'args': ", ".join(gl_arg_strings
),
6623 'cmd_args': ", ".join(cmd_arg_strings
),
6626 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6627 """Overrriden from TypeHandler."""
6629 TEST_P(%(test_name)s, %(name)sValidArgs) {
6630 EXPECT_CALL(*gl_, GetError())
6631 .WillOnce(Return(GL_NO_ERROR))
6632 .WillOnce(Return(GL_NO_ERROR))
6633 .RetiresOnSaturation();
6634 SpecializedSetup<cmds::%(name)s, 0>(true);
6635 typedef cmds::%(name)s::Result Result;
6636 Result* result = static_cast<Result*>(shared_memory_address_);
6637 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6640 cmd.Init(%(cmd_args)s);"""
6643 decoder_->set_unsafe_es3_apis_enabled(true);"""
6645 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6646 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6648 result->GetNumResults());
6649 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6652 decoder_->set_unsafe_es3_apis_enabled(false);
6653 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6658 cmd_arg_strings
= []
6660 for arg
in func
.GetOriginalArgs()[:-1]:
6661 if arg
.name
== 'length':
6662 gl_arg_value
= 'nullptr'
6663 elif arg
.name
.endswith('size'):
6664 gl_arg_value
= ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6666 elif arg
.type == 'GLsync':
6667 gl_arg_value
= 'reinterpret_cast<GLsync>(kServiceSyncId)'
6669 gl_arg_value
= arg
.GetValidGLArg(func
)
6670 gl_arg_strings
.append(gl_arg_value
)
6671 if arg
.name
== 'pname':
6672 valid_pname
= gl_arg_value
6673 if arg
.name
.endswith('size') or arg
.name
== 'length':
6675 if arg
.type == 'GLsync':
6676 arg_value
= 'client_sync_id_'
6678 arg_value
= arg
.GetValidArg(func
)
6679 cmd_arg_strings
.append(arg_value
)
6680 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
6681 gl_arg_strings
.append("_")
6683 gl_arg_strings
.append("result->GetData()")
6684 cmd_arg_strings
.append("shared_memory_id_")
6685 cmd_arg_strings
.append("shared_memory_offset_")
6687 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6688 'local_gl_args': ", ".join(gl_arg_strings
),
6689 'cmd_args': ", ".join(cmd_arg_strings
),
6690 'valid_pname': valid_pname
,
6693 if not func
.IsUnsafe():
6695 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6696 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6697 SpecializedSetup<cmds::%(name)s, 0>(false);
6698 cmds::%(name)s::Result* result =
6699 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6703 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6704 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6707 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, *extras
)
6709 class ArrayArgTypeHandler(TypeHandler
):
6710 """Base class for type handlers that handle args that are arrays"""
6712 def GetArrayType(self
, func
):
6713 """Returns the type of the element in the element array being PUT to."""
6714 for arg
in func
.GetOriginalArgs():
6716 element_type
= arg
.GetPointedType()
6719 # Special case: array type handler is used for a function that is forwarded
6720 # to the actual array type implementation
6721 element_type
= func
.GetOriginalArgs()[-1].type
6722 assert all(arg
.type == element_type \
6723 for arg
in func
.GetOriginalArgs()[-self
.GetArrayCount(func
):])
6726 def GetArrayCount(self
, func
):
6727 """Returns the count of the elements in the array being PUT to."""
6728 return func
.GetInfo('count')
6730 class PUTHandler(ArrayArgTypeHandler
):
6731 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6733 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6734 """Writes the service unit test for a command."""
6735 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6736 if func
.GetInfo("first_element_only"):
6738 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()
6740 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
6741 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6742 ", ".join(gl_arg_strings
))
6744 TEST_P(%(test_name)s, %(name)sValidArgs) {
6745 SpecializedSetup<cmds::%(name)s, 0>(true);
6748 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6750 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6751 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6755 'data_type': self
.GetArrayType(func
),
6756 'data_value': func
.GetInfo('data_value') or '0',
6757 'expected_call': expected_call
,
6759 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
6762 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6763 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6764 SpecializedSetup<cmds::%(name)s, 0>(false);
6767 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6768 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6771 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, extra
, *extras
)
6773 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
6774 """Writes the service unit test for a command."""
6776 TEST_P(%(test_name)s, %(name)sValidArgs) {
6777 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6778 SpecializedSetup<cmds::%(name)s, 0>(true);
6779 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6780 cmd.Init(%(gl_args)s, &temp[0]);
6783 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6784 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6787 decoder_->set_unsafe_es3_apis_enabled(true);"""
6789 EXPECT_EQ(error::kNoError,
6790 ExecuteImmediateCmd(cmd, sizeof(temp)));
6791 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6794 decoder_->set_unsafe_es3_apis_enabled(false);
6795 EXPECT_EQ(error::kUnknownCommand,
6796 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6801 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6803 gl_any_strings
= ["_"] * len(gl_arg_strings
)
6806 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
6807 'data_type': self
.GetArrayType(func
),
6808 'data_count': self
.GetArrayCount(func
),
6809 'data_value': func
.GetInfo('data_value') or '0',
6810 'gl_args': ", ".join(gl_arg_strings
),
6811 'gl_any_args': ", ".join(gl_any_strings
),
6813 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
6816 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6817 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6820 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6824 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6827 SpecializedSetup<cmds::%(name)s, 0>(false);
6828 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6829 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6832 decoder_->set_unsafe_es3_apis_enabled(true);
6833 EXPECT_EQ(error::%(parse_result)s,
6834 ExecuteImmediateCmd(cmd, sizeof(temp)));
6835 decoder_->set_unsafe_es3_apis_enabled(false);
6840 EXPECT_EQ(error::%(parse_result)s,
6841 ExecuteImmediateCmd(cmd, sizeof(temp)));
6845 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, extra
, *extras
)
6847 def WriteGetDataSizeCode(self
, func
, f
):
6848 """Overrriden from TypeHandler."""
6849 code
= """ uint32_t data_size;
6850 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6851 return error::kOutOfBounds;
6854 f
.write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6855 if func
.IsImmediate():
6856 f
.write(" if (data_size > immediate_data_size) {\n")
6857 f
.write(" return error::kOutOfBounds;\n")
6860 def __NeedsToCalcDataCount(self
, func
):
6861 use_count_func
= func
.GetInfo('use_count_func')
6862 return use_count_func
!= None and use_count_func
!= False
6864 def WriteGLES2Implementation(self
, func
, f
):
6865 """Overrriden from TypeHandler."""
6866 impl_func
= func
.GetInfo('impl_func')
6867 if (impl_func
!= None and impl_func
!= True):
6869 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6870 (func
.return_type
, func
.original_name
,
6871 func
.MakeTypedOriginalArgString("")))
6872 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6873 func
.WriteDestinationInitalizationValidation(f
)
6874 self
.WriteClientGLCallLog(func
, f
)
6876 if self
.__NeedsToCalcDataCount
(func
):
6877 f
.write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6878 (func
.name
, func
.GetOriginalArgs()[0].name
))
6879 f
.write(" DCHECK_LE(count, %du);\n" % self
.GetArrayCount(func
))
6881 f
.write(" size_t count = %d;" % self
.GetArrayCount(func
))
6882 f
.write(" for (size_t ii = 0; ii < count; ++ii)\n")
6883 f
.write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6884 func
.GetLastOriginalArg().name
)
6885 for arg
in func
.GetOriginalArgs():
6886 arg
.WriteClientSideValidationCode(f
, func
)
6887 f
.write(" helper_->%sImmediate(%s);\n" %
6888 (func
.name
, func
.MakeOriginalArgString("")))
6889 f
.write(" CheckGLError();\n")
6893 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
6894 """Writes the GLES2 Implemention unit test."""
6895 client_test
= func
.GetInfo('client_test')
6896 if (client_test
!= None and client_test
!= True):
6899 TEST_F(GLES2ImplementationTest, %(name)s) {
6900 %(type)s data[%(count)d] = {0};
6902 cmds::%(name)sImmediate cmd;
6903 %(type)s data[%(count)d];
6906 for (int jj = 0; jj < %(count)d; ++jj) {
6907 data[jj] = static_cast<%(type)s>(jj);
6910 expected.cmd.Init(%(cmd_args)s, &data[0]);
6911 gl_->%(name)s(%(args)s, &data[0]);
6912 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6916 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
6919 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6924 'type': self
.GetArrayType(func
),
6925 'count': self
.GetArrayCount(func
),
6926 'args': ", ".join(gl_arg_strings
),
6927 'cmd_args': ", ".join(cmd_arg_strings
),
6930 def WriteImmediateCmdComputeSize(self
, func
, f
):
6931 """Overrriden from TypeHandler."""
6932 f
.write(" static uint32_t ComputeDataSize() {\n")
6933 f
.write(" return static_cast<uint32_t>(\n")
6934 f
.write(" sizeof(%s) * %d);\n" %
6935 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6938 if self
.__NeedsToCalcDataCount
(func
):
6939 f
.write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6940 (func
.GetOriginalArgs()[0].type,
6941 func
.GetOriginalArgs()[0].name
))
6942 f
.write(" return static_cast<uint32_t>(\n")
6943 f
.write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6944 (self
.GetArrayType(func
), func
.original_name
,
6945 func
.GetOriginalArgs()[0].name
))
6948 f
.write(" static uint32_t ComputeSize() {\n")
6949 f
.write(" return static_cast<uint32_t>(\n")
6951 " sizeof(ValueType) + ComputeDataSize());\n")
6955 def WriteImmediateCmdSetHeader(self
, func
, f
):
6956 """Overrriden from TypeHandler."""
6957 f
.write(" void SetHeader() {\n")
6959 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6963 def WriteImmediateCmdInit(self
, func
, f
):
6964 """Overrriden from TypeHandler."""
6965 last_arg
= func
.GetLastOriginalArg()
6966 f
.write(" void Init(%s, %s _%s) {\n" %
6967 (func
.MakeTypedCmdArgString("_"),
6968 last_arg
.type, last_arg
.name
))
6969 f
.write(" SetHeader();\n")
6970 args
= func
.GetCmdArgs()
6972 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6973 f
.write(" memcpy(ImmediateDataAddress(this),\n")
6974 if self
.__NeedsToCalcDataCount
(func
):
6975 f
.write(" _%s, ComputeEffectiveDataSize(%s));" %
6976 (last_arg
.name
, func
.GetOriginalArgs()[0].name
))
6978 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6979 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6980 ComputeEffectiveDataSize(%(arg)s);
6981 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6982 """ % { 'arg': func
.GetOriginalArgs()[0].name
, })
6984 f
.write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
6988 def WriteImmediateCmdSet(self
, func
, f
):
6989 """Overrriden from TypeHandler."""
6990 last_arg
= func
.GetLastOriginalArg()
6991 copy_args
= func
.MakeCmdArgString("_", False)
6992 f
.write(" void* Set(void* cmd%s, %s _%s) {\n" %
6993 (func
.MakeTypedCmdArgString("_", True),
6994 last_arg
.type, last_arg
.name
))
6995 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6996 (copy_args
, last_arg
.name
))
6997 f
.write(" const uint32_t size = ComputeSize();\n")
6998 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7003 def WriteImmediateCmdHelper(self
, func
, f
):
7004 """Overrriden from TypeHandler."""
7005 code
= """ void %(name)s(%(typed_args)s) {
7006 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
7007 gles2::cmds::%(name)s* c =
7008 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7017 "typed_args": func
.MakeTypedOriginalArgString(""),
7018 "args": func
.MakeOriginalArgString(""),
7021 def WriteImmediateFormatTest(self
, func
, f
):
7022 """Overrriden from TypeHandler."""
7023 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
7024 f
.write(" const int kSomeBaseValueToTestWith = 51;\n")
7025 f
.write(" static %s data[] = {\n" % self
.GetArrayType(func
))
7026 for v
in range(0, self
.GetArrayCount(func
)):
7027 f
.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7028 (self
.GetArrayType(func
), v
))
7030 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7031 (func
.name
, func
.name
))
7032 f
.write(" void* next_cmd = cmd.Set(\n")
7034 args
= func
.GetCmdArgs()
7035 for value
, arg
in enumerate(args
):
7036 f
.write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
7037 f
.write(",\n data);\n")
7038 args
= func
.GetCmdArgs()
7039 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
7041 f
.write(" cmd.header.command);\n")
7042 f
.write(" EXPECT_EQ(sizeof(cmd) +\n")
7043 f
.write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
7044 f
.write(" cmd.header.size * 4u);\n")
7045 for value
, arg
in enumerate(args
):
7046 f
.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7047 (arg
.type, value
+ 11, arg
.name
))
7048 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7049 f
.write(" next_cmd, sizeof(cmd) +\n")
7050 f
.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7051 f
.write(" // TODO(gman): Check that data was inserted;\n")
7056 class PUTnHandler(ArrayArgTypeHandler
):
7057 """Handler for PUTn 'glUniform__v' type functions."""
7059 def WriteServiceUnitTest(self
, func
, f
, *extras
):
7060 """Overridden from TypeHandler."""
7061 ArrayArgTypeHandler
.WriteServiceUnitTest(self
, func
, f
, *extras
)
7064 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
7065 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7066 SpecializedSetup<cmds::%(name)s, 0>(true);
7069 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7070 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7075 for count
, arg
in enumerate(func
.GetOriginalArgs()):
7076 # hardcoded to match unit tests.
7078 # the location of the second element of the 2nd uniform.
7079 # defined in GLES2DecoderBase::SetupShaderForUniform
7080 gl_arg_strings
.append("3")
7081 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
7083 # the number of elements that gl will be called with.
7084 gl_arg_strings
.append("3")
7085 # the number of elements requested in the command.
7086 arg_strings
.append("5")
7088 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
7089 if not arg
.IsConstant():
7090 arg_strings
.append(arg
.GetValidArg(func
))
7092 'gl_args': ", ".join(gl_arg_strings
),
7093 'args': ", ".join(arg_strings
),
7095 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
7097 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
7098 """Overridden from TypeHandler."""
7100 TEST_P(%(test_name)s, %(name)sValidArgs) {
7101 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7104 %(gl_func_name)s(%(gl_args)s,
7105 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
7106 SpecializedSetup<cmds::%(name)s, 0>(true);
7107 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7108 cmd.Init(%(args)s, &temp[0]);"""
7111 decoder_->set_unsafe_es3_apis_enabled(true);"""
7113 EXPECT_EQ(error::kNoError,
7114 ExecuteImmediateCmd(cmd, sizeof(temp)));
7115 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7118 decoder_->set_unsafe_es3_apis_enabled(false);
7119 EXPECT_EQ(error::kUnknownCommand,
7120 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
7127 for arg
in func
.GetOriginalArgs()[0:-1]:
7128 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
7129 gl_any_strings
.append("_")
7130 if not arg
.IsConstant():
7131 arg_strings
.append(arg
.GetValidArg(func
))
7133 'data_type': self
.GetArrayType(func
),
7134 'data_count': self
.GetArrayCount(func
),
7135 'args': ", ".join(arg_strings
),
7136 'gl_args': ", ".join(gl_arg_strings
),
7137 'gl_any_args': ", ".join(gl_any_strings
),
7139 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
7142 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7143 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7144 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
7145 SpecializedSetup<cmds::%(name)s, 0>(false);
7146 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7147 cmd.Init(%(all_but_last_args)s, &temp[0]);
7148 EXPECT_EQ(error::%(parse_result)s,
7149 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
7152 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, extra
, *extras
)
7154 def WriteGetDataSizeCode(self
, func
, f
):
7155 """Overrriden from TypeHandler."""
7156 code
= """ uint32_t data_size;
7157 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
7158 return error::kOutOfBounds;
7161 f
.write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7162 if func
.IsImmediate():
7163 f
.write(" if (data_size > immediate_data_size) {\n")
7164 f
.write(" return error::kOutOfBounds;\n")
7167 def WriteGLES2Implementation(self
, func
, f
):
7168 """Overrriden from TypeHandler."""
7169 f
.write("%s GLES2Implementation::%s(%s) {\n" %
7170 (func
.return_type
, func
.original_name
,
7171 func
.MakeTypedOriginalArgString("")))
7172 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7173 func
.WriteDestinationInitalizationValidation(f
)
7174 self
.WriteClientGLCallLog(func
, f
)
7175 last_pointer_name
= func
.GetLastOriginalPointerArg().name
7176 f
.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7177 for (GLsizei i = 0; i < count; ++i) {
7179 values_str
= ' << ", " << '.join(
7180 ["%s[%d + i * %d]" % (
7181 last_pointer_name
, ndx
, self
.GetArrayCount(func
)) for ndx
in range(
7182 0, self
.GetArrayCount(func
))])
7183 f
.write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
7184 f
.write(" }\n });\n")
7185 for arg
in func
.GetOriginalArgs():
7186 arg
.WriteClientSideValidationCode(f
, func
)
7187 f
.write(" helper_->%sImmediate(%s);\n" %
7188 (func
.name
, func
.MakeInitString("")))
7189 f
.write(" CheckGLError();\n")
7193 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
7194 """Writes the GLES2 Implemention unit test."""
7196 TEST_F(GLES2ImplementationTest, %(name)s) {
7197 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7199 cmds::%(name)sImmediate cmd;
7200 %(type)s data[%(count_param)d][%(count)d];
7204 for (int ii = 0; ii < %(count_param)d; ++ii) {
7205 for (int jj = 0; jj < %(count)d; ++jj) {
7206 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7209 expected.cmd.Init(%(cmd_args)s);
7210 gl_->%(name)s(%(args)s);
7211 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7214 cmd_arg_strings
= []
7215 for arg
in func
.GetCmdArgs():
7216 if arg
.name
.endswith("_shm_id"):
7217 cmd_arg_strings
.append("&data[0][0]")
7218 elif arg
.name
.endswith("_shm_offset"):
7221 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
7224 for arg
in func
.GetOriginalArgs():
7226 valid_value
= "&data[0][0]"
7228 valid_value
= arg
.GetValidClientSideArg(func
)
7229 gl_arg_strings
.append(valid_value
)
7230 if arg
.name
== "count":
7231 count_param
= int(valid_value
)
7234 'type': self
.GetArrayType(func
),
7235 'count': self
.GetArrayCount(func
),
7236 'args': ", ".join(gl_arg_strings
),
7237 'cmd_args': ", ".join(cmd_arg_strings
),
7238 'count_param': count_param
,
7241 # Test constants for invalid values, as they are not tested by the
7244 arg
for arg
in func
.GetOriginalArgs()[0:-1] if arg
.IsConstant()
7250 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7251 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7252 for (int ii = 0; ii < %(count_param)d; ++ii) {
7253 for (int jj = 0; jj < %(count)d; ++jj) {
7254 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7257 gl_->%(name)s(%(args)s);
7258 EXPECT_TRUE(NoCommandsWritten());
7259 EXPECT_EQ(%(gl_error)s, CheckError());
7262 for invalid_arg
in constants
:
7264 invalid
= invalid_arg
.GetInvalidArg(func
)
7265 for arg
in func
.GetOriginalArgs():
7266 if arg
is invalid_arg
:
7267 gl_arg_strings
.append(invalid
[0])
7268 elif arg
.IsPointer():
7269 gl_arg_strings
.append("&data[0][0]")
7271 valid_value
= arg
.GetValidClientSideArg(func
)
7272 gl_arg_strings
.append(valid_value
)
7273 if arg
.name
== "count":
7274 count_param
= int(valid_value
)
7278 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
7279 'type': self
.GetArrayType(func
),
7280 'count': self
.GetArrayCount(func
),
7281 'args': ", ".join(gl_arg_strings
),
7282 'gl_error': invalid
[2],
7283 'count_param': count_param
,
7287 def WriteImmediateCmdComputeSize(self
, func
, f
):
7288 """Overrriden from TypeHandler."""
7289 f
.write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7290 f
.write(" return static_cast<uint32_t>(\n")
7291 f
.write(" sizeof(%s) * %d * count); // NOLINT\n" %
7292 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7295 f
.write(" static uint32_t ComputeSize(GLsizei count) {\n")
7296 f
.write(" return static_cast<uint32_t>(\n")
7298 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7302 def WriteImmediateCmdSetHeader(self
, func
, f
):
7303 """Overrriden from TypeHandler."""
7304 f
.write(" void SetHeader(GLsizei count) {\n")
7306 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7310 def WriteImmediateCmdInit(self
, func
, f
):
7311 """Overrriden from TypeHandler."""
7312 f
.write(" void Init(%s) {\n" %
7313 func
.MakeTypedInitString("_"))
7314 f
.write(" SetHeader(_count);\n")
7315 args
= func
.GetCmdArgs()
7317 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
7318 f
.write(" memcpy(ImmediateDataAddress(this),\n")
7319 pointer_arg
= func
.GetLastOriginalPointerArg()
7320 f
.write(" _%s, ComputeDataSize(_count));\n" % pointer_arg
.name
)
7324 def WriteImmediateCmdSet(self
, func
, f
):
7325 """Overrriden from TypeHandler."""
7326 f
.write(" void* Set(void* cmd%s) {\n" %
7327 func
.MakeTypedInitString("_", True))
7328 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7329 func
.MakeInitString("_"))
7330 f
.write(" const uint32_t size = ComputeSize(_count);\n")
7331 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7336 def WriteImmediateCmdHelper(self
, func
, f
):
7337 """Overrriden from TypeHandler."""
7338 code
= """ void %(name)s(%(typed_args)s) {
7339 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7340 gles2::cmds::%(name)s* c =
7341 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7350 "typed_args": func
.MakeTypedInitString(""),
7351 "args": func
.MakeInitString("")
7354 def WriteImmediateFormatTest(self
, func
, f
):
7355 """Overrriden from TypeHandler."""
7356 args
= func
.GetOriginalArgs()
7359 if arg
.name
== "count":
7360 count_param
= int(arg
.GetValidClientSideCmdArg(func
))
7361 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
7362 f
.write(" const int kSomeBaseValueToTestWith = 51;\n")
7363 f
.write(" static %s data[] = {\n" % self
.GetArrayType(func
))
7364 for v
in range(0, self
.GetArrayCount(func
) * count_param
):
7365 f
.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7366 (self
.GetArrayType(func
), v
))
7368 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7369 (func
.name
, func
.name
))
7370 f
.write(" const GLsizei kNumElements = %d;\n" % count_param
)
7371 f
.write(" const size_t kExpectedCmdSize =\n")
7372 f
.write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7373 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7374 f
.write(" void* next_cmd = cmd.Set(\n")
7376 for value
, arg
in enumerate(args
):
7379 elif arg
.IsConstant():
7382 f
.write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
7384 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7386 f
.write(" cmd.header.command);\n")
7387 f
.write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7388 for value
, arg
in enumerate(args
):
7389 if arg
.IsPointer() or arg
.IsConstant():
7391 f
.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7392 (arg
.type, value
+ 1, arg
.name
))
7393 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7394 f
.write(" next_cmd, sizeof(cmd) +\n")
7395 f
.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7396 f
.write(" // TODO(gman): Check that data was inserted;\n")
7400 class PUTSTRHandler(ArrayArgTypeHandler
):
7401 """Handler for functions that pass a string array."""
7403 def __GetDataArg(self
, func
):
7404 """Return the argument that points to the 2D char arrays"""
7405 for arg
in func
.GetOriginalArgs():
7406 if arg
.IsPointer2D():
7410 def __GetLengthArg(self
, func
):
7411 """Return the argument that holds length for each char array"""
7412 for arg
in func
.GetOriginalArgs():
7413 if arg
.IsPointer() and not arg
.IsPointer2D():
7417 def WriteGLES2Implementation(self
, func
, f
):
7418 """Overrriden from TypeHandler."""
7419 f
.write("%s GLES2Implementation::%s(%s) {\n" %
7420 (func
.return_type
, func
.original_name
,
7421 func
.MakeTypedOriginalArgString("")))
7422 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7423 func
.WriteDestinationInitalizationValidation(f
)
7424 self
.WriteClientGLCallLog(func
, f
)
7425 data_arg
= self
.__GetDataArg
(func
)
7426 length_arg
= self
.__GetLengthArg
(func
)
7427 log_code_block
= """ GPU_CLIENT_LOG_CODE_BLOCK({
7428 for (GLsizei ii = 0; ii < count; ++ii) {
7429 if (%(data)s[ii]) {"""
7430 if length_arg
== None:
7431 log_code_block
+= """
7432 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7434 log_code_block
+= """
7435 if (%(length)s && %(length)s[ii] >= 0) {
7436 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7437 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7439 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7441 log_code_block
+= """
7443 GPU_CLIENT_LOG(" " << ii << ": NULL");
7448 f
.write(log_code_block
% {
7449 'data': data_arg
.name
,
7450 'length': length_arg
.name
if not length_arg
== None else ''
7452 for arg
in func
.GetOriginalArgs():
7453 arg
.WriteClientSideValidationCode(f
, func
)
7456 for arg
in func
.GetOriginalArgs():
7457 if arg
.name
== 'count' or arg
== self
.__GetLengthArg
(func
):
7459 if arg
== self
.__GetDataArg
(func
):
7460 bucket_args
.append('kResultBucketId')
7462 bucket_args
.append(arg
.name
)
7464 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7467 helper_->%(func_name)sBucket(%(bucket_args)s);
7468 helper_->SetBucketSize(kResultBucketId, 0);
7473 f
.write(code_block
% {
7474 'data': data_arg
.name
,
7475 'length': length_arg
.name
if not length_arg
== None else 'NULL',
7476 'func_name': func
.name
,
7477 'bucket_args': ', '.join(bucket_args
),
7480 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
7481 """Overrriden from TypeHandler."""
7483 TEST_F(GLES2ImplementationTest, %(name)s) {
7484 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7485 const char* kString1 = "happy";
7486 const char* kString2 = "ending";
7487 const size_t kString1Size = ::strlen(kString1) + 1;
7488 const size_t kString2Size = ::strlen(kString2) + 1;
7489 const size_t kHeaderSize = sizeof(GLint) * 3;
7490 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7491 const size_t kPaddedHeaderSize =
7492 transfer_buffer_->RoundToAlignment(kHeaderSize);
7493 const size_t kPaddedString1Size =
7494 transfer_buffer_->RoundToAlignment(kString1Size);
7495 const size_t kPaddedString2Size =
7496 transfer_buffer_->RoundToAlignment(kString2Size);
7498 cmd::SetBucketSize set_bucket_size;
7499 cmd::SetBucketData set_bucket_header;
7500 cmd::SetToken set_token1;
7501 cmd::SetBucketData set_bucket_data1;
7502 cmd::SetToken set_token2;
7503 cmd::SetBucketData set_bucket_data2;
7504 cmd::SetToken set_token3;
7505 cmds::%(name)sBucket cmd_bucket;
7506 cmd::SetBucketSize clear_bucket_size;
7509 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7510 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7511 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7514 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7515 expected.set_bucket_header.Init(
7516 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7517 expected.set_token1.Init(GetNextToken());
7518 expected.set_bucket_data1.Init(
7519 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7520 expected.set_token2.Init(GetNextToken());
7521 expected.set_bucket_data2.Init(
7522 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7524 expected.set_token3.Init(GetNextToken());
7525 expected.cmd_bucket.Init(%(bucket_args)s);
7526 expected.clear_bucket_size.Init(kBucketId, 0);
7527 const char* kStrings[] = { kString1, kString2 };
7528 gl_->%(name)s(%(gl_args)s);
7529 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7534 for arg
in func
.GetOriginalArgs():
7535 if arg
== self
.__GetDataArg
(func
):
7536 gl_args
.append('kStrings')
7537 bucket_args
.append('kBucketId')
7538 elif arg
== self
.__GetLengthArg
(func
):
7539 gl_args
.append('NULL')
7540 elif arg
.name
== 'count':
7543 gl_args
.append(arg
.GetValidClientSideArg(func
))
7544 bucket_args
.append(arg
.GetValidClientSideArg(func
))
7547 'gl_args': ", ".join(gl_args
),
7548 'bucket_args': ", ".join(bucket_args
),
7551 if self
.__GetLengthArg
(func
) == None:
7554 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7555 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7556 const char* kString = "foobar******";
7557 const size_t kStringSize = 6; // We only need "foobar".
7558 const size_t kHeaderSize = sizeof(GLint) * 2;
7559 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7560 const size_t kPaddedHeaderSize =
7561 transfer_buffer_->RoundToAlignment(kHeaderSize);
7562 const size_t kPaddedStringSize =
7563 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7565 cmd::SetBucketSize set_bucket_size;
7566 cmd::SetBucketData set_bucket_header;
7567 cmd::SetToken set_token1;
7568 cmd::SetBucketData set_bucket_data;
7569 cmd::SetToken set_token2;
7570 cmds::ShaderSourceBucket shader_source_bucket;
7571 cmd::SetBucketSize clear_bucket_size;
7574 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7575 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7578 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7579 expected.set_bucket_header.Init(
7580 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7581 expected.set_token1.Init(GetNextToken());
7582 expected.set_bucket_data.Init(
7583 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7584 expected.set_token2.Init(GetNextToken());
7585 expected.shader_source_bucket.Init(%(bucket_args)s);
7586 expected.clear_bucket_size.Init(kBucketId, 0);
7587 const char* kStrings[] = { kString };
7588 const GLint kLength[] = { kStringSize };
7589 gl_->%(name)s(%(gl_args)s);
7590 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7594 for arg
in func
.GetOriginalArgs():
7595 if arg
== self
.__GetDataArg
(func
):
7596 gl_args
.append('kStrings')
7597 elif arg
== self
.__GetLengthArg
(func
):
7598 gl_args
.append('kLength')
7599 elif arg
.name
== 'count':
7602 gl_args
.append(arg
.GetValidClientSideArg(func
))
7605 'gl_args': ", ".join(gl_args
),
7606 'bucket_args': ", ".join(bucket_args
),
7609 def WriteBucketServiceUnitTest(self
, func
, f
, *extras
):
7610 """Overrriden from TypeHandler."""
7612 cmd_args_with_invalid_id
= []
7614 for index
, arg
in enumerate(func
.GetOriginalArgs()):
7615 if arg
== self
.__GetLengthArg
(func
):
7617 elif arg
.name
== 'count':
7619 elif arg
== self
.__GetDataArg
(func
):
7620 cmd_args
.append('kBucketId')
7621 cmd_args_with_invalid_id
.append('kBucketId')
7623 elif index
== 0: # Resource ID arg
7624 cmd_args
.append(arg
.GetValidArg(func
))
7625 cmd_args_with_invalid_id
.append('kInvalidClientId')
7626 gl_args
.append(arg
.GetValidGLArg(func
))
7628 cmd_args
.append(arg
.GetValidArg(func
))
7629 cmd_args_with_invalid_id
.append(arg
.GetValidArg(func
))
7630 gl_args
.append(arg
.GetValidGLArg(func
))
7633 TEST_P(%(test_name)s, %(name)sValidArgs) {
7634 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7635 const uint32 kBucketId = 123;
7636 const char kSource0[] = "hello";
7637 const char* kSource[] = { kSource0 };
7638 const char kValidStrEnd = 0;
7639 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7641 cmd.Init(%(cmd_args)s);
7642 decoder_->set_unsafe_es3_apis_enabled(true);
7643 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7646 decoder_->set_unsafe_es3_apis_enabled(false);
7647 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7652 self
.WriteValidUnitTest(func
, f
, test
, {
7653 'cmd_args': ", ".join(cmd_args
),
7654 'gl_args': ", ".join(gl_args
),
7658 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7659 const uint32 kBucketId = 123;
7660 const char kSource0[] = "hello";
7661 const char* kSource[] = { kSource0 };
7662 const char kValidStrEnd = 0;
7663 decoder_->set_unsafe_es3_apis_enabled(true);
7666 cmd.Init(%(cmd_args)s);
7667 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7668 // Test invalid client.
7669 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7670 cmd.Init(%(cmd_args_with_invalid_id)s);
7671 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7672 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7675 self
.WriteValidUnitTest(func
, f
, test
, {
7676 'cmd_args': ", ".join(cmd_args
),
7677 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id
),
7681 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7682 const uint32 kBucketId = 123;
7683 const char kSource0[] = "hello";
7684 const char* kSource[] = { kSource0 };
7685 const char kValidStrEnd = 0;
7686 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7687 const GLsizei kTests[] = {
7690 std::numeric_limits<GLsizei>::max(),
7693 decoder_->set_unsafe_es3_apis_enabled(true);
7694 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7695 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7697 cmd.Init(%(cmd_args)s);
7698 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7702 self
.WriteValidUnitTest(func
, f
, test
, {
7703 'cmd_args': ", ".join(cmd_args
),
7707 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7708 const uint32 kBucketId = 123;
7709 const char kSource0[] = "hello";
7710 const char* kSource[] = { kSource0 };
7711 const char kInvalidStrEnd = '*';
7712 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7714 cmd.Init(%(cmd_args)s);
7715 decoder_->set_unsafe_es3_apis_enabled(true);
7716 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7719 self
.WriteValidUnitTest(func
, f
, test
, {
7720 'cmd_args': ", ".join(cmd_args
),
7724 class PUTXnHandler(ArrayArgTypeHandler
):
7725 """Handler for glUniform?f functions."""
7727 def WriteHandlerImplementation(self
, func
, f
):
7728 """Overrriden from TypeHandler."""
7729 code
= """ %(type)s temp[%(count)s] = { %(values)s};"""
7732 gl%(name)sv(%(location)s, 1, &temp[0]);
7736 Do%(name)sv(%(location)s, 1, &temp[0]);
7739 args
= func
.GetOriginalArgs()
7740 count
= int(self
.GetArrayCount(func
))
7741 num_args
= len(args
)
7742 for ii
in range(count
):
7743 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
7747 'count': self
.GetArrayCount(func
),
7748 'type': self
.GetArrayType(func
),
7749 'location': args
[0].name
,
7750 'args': func
.MakeOriginalArgString(""),
7754 def WriteServiceUnitTest(self
, func
, f
, *extras
):
7755 """Overrriden from TypeHandler."""
7757 TEST_P(%(test_name)s, %(name)sValidArgs) {
7758 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7759 SpecializedSetup<cmds::%(name)s, 0>(true);
7761 cmd.Init(%(args)s);"""
7764 decoder_->set_unsafe_es3_apis_enabled(true);"""
7766 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7767 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7770 decoder_->set_unsafe_es3_apis_enabled(false);
7771 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7775 args
= func
.GetOriginalArgs()
7776 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
)
7777 self
.WriteValidUnitTest(func
, f
, valid_test
, {
7779 'count': self
.GetArrayCount(func
),
7780 'local_args': local_args
,
7784 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7785 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7786 SpecializedSetup<cmds::%(name)s, 0>(false);
7789 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7792 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, {
7793 'name': func
.GetInfo('name'),
7794 'count': self
.GetArrayCount(func
),
7798 class GLcharHandler(CustomHandler
):
7799 """Handler for functions that pass a single string ."""
7801 def WriteImmediateCmdComputeSize(self
, func
, f
):
7802 """Overrriden from TypeHandler."""
7803 f
.write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7804 f
.write(" return static_cast<uint32_t>(\n")
7805 f
.write(" sizeof(ValueType) + data_size); // NOLINT\n")
7808 def WriteImmediateCmdSetHeader(self
, func
, f
):
7809 """Overrriden from TypeHandler."""
7811 void SetHeader(uint32_t data_size) {
7812 header.SetCmdBySize<ValueType>(data_size);
7817 def WriteImmediateCmdInit(self
, func
, f
):
7818 """Overrriden from TypeHandler."""
7819 last_arg
= func
.GetLastOriginalArg()
7820 args
= func
.GetCmdArgs()
7823 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
7825 void Init(%(typed_args)s, uint32_t _data_size) {
7826 SetHeader(_data_size);
7828 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7833 "typed_args": func
.MakeTypedArgString("_"),
7834 "set_code": "\n".join(set_code
),
7835 "last_arg": last_arg
.name
7838 def WriteImmediateCmdSet(self
, func
, f
):
7839 """Overrriden from TypeHandler."""
7840 last_arg
= func
.GetLastOriginalArg()
7841 f
.write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7842 func
.MakeTypedCmdArgString("_", True))
7843 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7844 func
.MakeCmdArgString("_"))
7845 f
.write(" return NextImmediateCmdAddress<ValueType>("
7846 "cmd, _data_size);\n")
7850 def WriteImmediateCmdHelper(self
, func
, f
):
7851 """Overrriden from TypeHandler."""
7852 code
= """ void %(name)s(%(typed_args)s) {
7853 const uint32_t data_size = strlen(name);
7854 gles2::cmds::%(name)s* c =
7855 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7857 c->Init(%(args)s, data_size);
7864 "typed_args": func
.MakeTypedOriginalArgString(""),
7865 "args": func
.MakeOriginalArgString(""),
7869 def WriteImmediateFormatTest(self
, func
, f
):
7870 """Overrriden from TypeHandler."""
7873 all_but_last_arg
= func
.GetCmdArgs()[:-1]
7874 for value
, arg
in enumerate(all_but_last_arg
):
7875 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
7876 for value
, arg
in enumerate(all_but_last_arg
):
7877 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7878 (arg
.type, value
+ 11, arg
.name
))
7880 TEST_F(GLES2FormatTest, %(func_name)s) {
7881 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7882 static const char* const test_str = \"test string\";
7883 void* next_cmd = cmd.Set(
7888 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7889 cmd.header.command);
7890 EXPECT_EQ(sizeof(cmd) +
7891 RoundSizeToMultipleOfEntries(strlen(test_str)),
7892 cmd.header.size * 4u);
7893 EXPECT_EQ(static_cast<char*>(next_cmd),
7894 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7895 RoundSizeToMultipleOfEntries(strlen(test_str)));
7897 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7898 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7901 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7902 sizeof(cmd) + strlen(test_str));
7907 'func_name': func
.name
,
7908 'init_code': "\n".join(init_code
),
7909 'check_code': "\n".join(check_code
),
7913 class GLcharNHandler(CustomHandler
):
7914 """Handler for functions that pass a single string with an optional len."""
7916 def InitFunction(self
, func
):
7917 """Overrriden from TypeHandler."""
7919 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
7921 def NeedsDataTransferFunction(self
, func
):
7922 """Overriden from TypeHandler."""
7925 def WriteServiceImplementation(self
, func
, f
):
7926 """Overrriden from TypeHandler."""
7927 self
.WriteServiceHandlerFunctionHeader(func
, f
)
7929 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7930 Bucket* bucket = GetBucket(bucket_id);
7931 if (!bucket || bucket->size() == 0) {
7932 return error::kInvalidArguments;
7935 if (!bucket->GetAsString(&str)) {
7936 return error::kInvalidArguments;
7938 %(gl_func_name)s(0, str.c_str());
7939 return error::kNoError;
7944 'gl_func_name': func
.GetGLFunctionName(),
7945 'bucket_id': func
.cmd_args
[0].name
,
7949 class IsHandler(TypeHandler
):
7950 """Handler for glIs____ type and glGetError functions."""
7952 def InitFunction(self
, func
):
7953 """Overrriden from TypeHandler."""
7954 func
.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7955 func
.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7956 if func
.GetInfo('result') == None:
7957 func
.AddInfo('result', ['uint32_t'])
7959 def WriteServiceUnitTest(self
, func
, f
, *extras
):
7960 """Overrriden from TypeHandler."""
7962 TEST_P(%(test_name)s, %(name)sValidArgs) {
7963 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7964 SpecializedSetup<cmds::%(name)s, 0>(true);
7966 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7969 decoder_->set_unsafe_es3_apis_enabled(true);"""
7971 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7972 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7975 decoder_->set_unsafe_es3_apis_enabled(false);
7976 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7981 if len(func
.GetOriginalArgs()):
7983 self
.WriteValidUnitTest(func
, f
, valid_test
, {
7988 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7989 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7990 SpecializedSetup<cmds::%(name)s, 0>(false);
7992 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7993 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7996 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, {
8001 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
8002 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8003 SpecializedSetup<cmds::%(name)s, 0>(false);"""
8006 decoder_->set_unsafe_es3_apis_enabled(true);"""
8009 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
8010 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
8011 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
8012 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
8015 decoder_->set_unsafe_es3_apis_enabled(true);"""
8019 self
.WriteValidUnitTest(func
, f
, invalid_test
, {
8023 def WriteServiceImplementation(self
, func
, f
):
8024 """Overrriden from TypeHandler."""
8025 self
.WriteServiceHandlerFunctionHeader(func
, f
)
8026 self
.WriteHandlerExtensionCheck(func
, f
)
8027 args
= func
.GetOriginalArgs()
8031 code
= """ typedef cmds::%(func_name)s::Result Result;
8032 Result* result_dst = GetSharedMemoryAs<Result*>(
8033 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
8035 return error::kOutOfBounds;
8038 f
.write(code
% {'func_name': func
.name
})
8039 func
.WriteHandlerValidation(f
)
8041 assert func
.GetInfo('id_mapping')
8042 assert len(func
.GetInfo('id_mapping')) == 1
8043 assert len(args
) == 1
8044 id_type
= func
.GetInfo('id_mapping')[0]
8045 f
.write(" %s service_%s = 0;\n" % (args
[0].type, id_type
.lower()))
8046 f
.write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
8047 (id_type
, id_type
.lower(), id_type
.lower()))
8049 f
.write(" *result_dst = %s(%s);\n" %
8050 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
8051 f
.write(" return error::kNoError;\n")
8055 def WriteGLES2Implementation(self
, func
, f
):
8056 """Overrriden from TypeHandler."""
8057 impl_func
= func
.GetInfo('impl_func')
8058 if impl_func
== None or impl_func
== True:
8059 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
8060 f
.write("%s GLES2Implementation::%s(%s) {\n" %
8061 (func
.return_type
, func
.original_name
,
8062 func
.MakeTypedOriginalArgString("")))
8063 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
8064 self
.WriteTraceEvent(func
, f
)
8065 func
.WriteDestinationInitalizationValidation(f
)
8066 self
.WriteClientGLCallLog(func
, f
)
8067 f
.write(" typedef cmds::%s::Result Result;\n" % func
.name
)
8068 f
.write(" Result* result = GetResultAs<Result*>();\n")
8069 f
.write(" if (!result) {\n")
8070 f
.write(" return %s;\n" % error_value
)
8072 f
.write(" *result = 0;\n")
8073 assert len(func
.GetOriginalArgs()) == 1
8074 id_arg
= func
.GetOriginalArgs()[0]
8075 if id_arg
.type == 'GLsync':
8076 arg_string
= "ToGLuint(%s)" % func
.MakeOriginalArgString("")
8078 arg_string
= func
.MakeOriginalArgString("")
8080 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
8081 (func
.name
, arg_string
))
8082 f
.write(" WaitForCmd();\n")
8083 f
.write(" %s result_value = *result" % func
.return_type
)
8084 if func
.return_type
== "GLboolean":
8086 f
.write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
8087 f
.write(" CheckGLError();\n")
8088 f
.write(" return result_value;\n")
8092 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
8093 """Overrriden from TypeHandler."""
8094 client_test
= func
.GetInfo('client_test')
8095 if client_test
== None or client_test
== True:
8097 TEST_F(GLES2ImplementationTest, %(name)s) {
8103 ExpectedMemoryInfo result1 =
8104 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
8105 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
8107 EXPECT_CALL(*command_buffer(), OnFlush())
8108 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
8109 .RetiresOnSaturation();
8111 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
8112 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
8113 EXPECT_TRUE(result);
8116 args
= func
.GetOriginalArgs()
8117 assert len(args
) == 1
8120 'cmd_id_value': args
[0].GetValidClientSideCmdArg(func
),
8121 'gl_id_value': args
[0].GetValidClientSideArg(func
) })
8124 class STRnHandler(TypeHandler
):
8125 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
8126 GetTranslatedShaderSourceANGLE."""
8128 def InitFunction(self
, func
):
8129 """Overrriden from TypeHandler."""
8130 # remove all but the first cmd args.
8131 cmd_args
= func
.GetCmdArgs()
8133 func
.AddCmdArg(cmd_args
[0])
8134 # add on a bucket id.
8135 func
.AddCmdArg(Argument('bucket_id', 'uint32_t'))
8137 def WriteGLES2Implementation(self
, func
, f
):
8138 """Overrriden from TypeHandler."""
8139 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
8140 GPU_CLIENT_SINGLE_THREAD_CHECK();
8142 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
8143 << "] gl%(func_name)s" << "("
8146 << static_cast<void*>(%(arg2)s) << ", "
8147 << static_cast<void*>(%(arg3)s) << ")");
8148 helper_->SetBucketSize(kResultBucketId, 0);
8149 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8151 GLsizei max_size = 0;
8152 if (GetBucketAsString(kResultBucketId, &str)) {
8155 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8156 memcpy(%(dest_name)s, str.c_str(), max_size);
8157 %(dest_name)s[max_size] = '\\0';
8158 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8161 if (%(length_name)s != NULL) {
8162 *%(length_name)s = max_size;
8167 args
= func
.GetOriginalArgs()
8169 'return_type': func
.return_type
,
8170 'func_name': func
.original_name
,
8171 'args': func
.MakeTypedOriginalArgString(""),
8172 'id_name': args
[0].name
,
8173 'bufsize_name': args
[1].name
,
8174 'length_name': args
[2].name
,
8175 'dest_name': args
[3].name
,
8176 'arg0': args
[0].name
,
8177 'arg1': args
[1].name
,
8178 'arg2': args
[2].name
,
8179 'arg3': args
[3].name
,
8181 f
.write(code_1
% str_args
)
8182 func
.WriteDestinationInitalizationValidation(f
)
8183 f
.write(code_2
% str_args
)
8185 def WriteServiceUnitTest(self
, func
, f
, *extras
):
8186 """Overrriden from TypeHandler."""
8188 TEST_P(%(test_name)s, %(name)sValidArgs) {
8189 const char* kInfo = "hello";
8190 const uint32_t kBucketId = 123;
8191 SpecializedSetup<cmds::%(name)s, 0>(true);
8193 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8194 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8195 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8198 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8199 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8200 ASSERT_TRUE(bucket != NULL);
8201 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8202 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8204 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8207 args
= func
.GetOriginalArgs()
8208 id_name
= args
[0].GetValidGLArg(func
)
8209 get_len_func
= func
.GetInfo('get_len_func')
8210 get_len_enum
= func
.GetInfo('get_len_enum')
8213 'get_len_func': get_len_func
,
8214 'get_len_enum': get_len_enum
,
8215 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8216 args
[0].GetValidGLArg(func
),
8217 'args': '%s, kBucketId' % args
[0].GetValidArg(func
),
8218 'expect_len_code': '',
8220 if get_len_func
and get_len_func
[0:2] == 'gl':
8221 sub
['expect_len_code'] = (
8222 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8223 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8224 get_len_func
[2:], id_name
, get_len_enum
)
8225 self
.WriteValidUnitTest(func
, f
, valid_test
, sub
, *extras
)
8228 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8229 const uint32_t kBucketId = 123;
8230 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8233 cmd.Init(kInvalidClientId, kBucketId);
8234 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8235 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8238 self
.WriteValidUnitTest(func
, f
, invalid_test
, *extras
)
8240 def WriteServiceImplementation(self
, func
, f
):
8241 """Overrriden from TypeHandler."""
8244 class NamedType(object):
8245 """A class that represents a type of an argument in a client function.
8247 A type of an argument that is to be passed through in the command buffer
8248 command. Currently used only for the arguments that are specificly named in
8249 the 'cmd_buffer_functions.txt' f, mostly enums.
8252 def __init__(self
, info
):
8253 assert not 'is_complete' in info
or info
['is_complete'] == True
8255 self
.valid
= info
['valid']
8256 if 'invalid' in info
:
8257 self
.invalid
= info
['invalid']
8260 if 'valid_es3' in info
:
8261 self
.valid_es3
= info
['valid_es3']
8264 if 'deprecated_es3' in info
:
8265 self
.deprecated_es3
= info
['deprecated_es3']
8267 self
.deprecated_es3
= []
8270 return self
.info
['type']
8272 def GetInvalidValues(self
):
8275 def GetValidValues(self
):
8278 def GetValidValuesES3(self
):
8279 return self
.valid_es3
8281 def GetDeprecatedValuesES3(self
):
8282 return self
.deprecated_es3
8284 def IsConstant(self
):
8285 if not 'is_complete' in self
.info
:
8288 return len(self
.GetValidValues()) == 1
8290 def GetConstantValue(self
):
8291 return self
.GetValidValues()[0]
8293 class Argument(object):
8294 """A class that represents a function argument."""
8297 'GLenum': 'uint32_t',
8299 'GLintptr': 'int32_t',
8300 'GLsizei': 'int32_t',
8301 'GLsizeiptr': 'int32_t',
8303 'GLclampf': 'float',
8305 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8307 def __init__(self
, name
, type):
8309 self
.optional
= type.endswith("Optional*")
8311 type = type[:-9] + "*"
8314 if type in self
.cmd_type_map_
:
8315 self
.cmd_type
= self
.cmd_type_map_
[type]
8317 self
.cmd_type
= 'uint32_t'
8319 def IsPointer(self
):
8320 """Returns true if argument is a pointer."""
8323 def IsPointer2D(self
):
8324 """Returns true if argument is a 2D pointer."""
8327 def IsConstant(self
):
8328 """Returns true if the argument has only one valid value."""
8331 def AddCmdArgs(self
, args
):
8332 """Adds command arguments for this argument to the given list."""
8333 if not self
.IsConstant():
8334 return args
.append(self
)
8336 def AddInitArgs(self
, args
):
8337 """Adds init arguments for this argument to the given list."""
8338 if not self
.IsConstant():
8339 return args
.append(self
)
8341 def GetValidArg(self
, func
):
8342 """Gets a valid value for this argument."""
8343 valid_arg
= func
.GetValidArg(self
)
8344 if valid_arg
!= None:
8347 index
= func
.GetOriginalArgs().index(self
)
8348 return str(index
+ 1)
8350 def GetValidClientSideArg(self
, func
):
8351 """Gets a valid value for this argument."""
8352 valid_arg
= func
.GetValidArg(self
)
8353 if valid_arg
!= None:
8356 if self
.IsPointer():
8358 index
= func
.GetOriginalArgs().index(self
)
8359 if self
.type == 'GLsync':
8360 return ("reinterpret_cast<GLsync>(%d)" % (index
+ 1))
8361 return str(index
+ 1)
8363 def GetValidClientSideCmdArg(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)
8373 index
= func
.GetCmdArgs().index(self
)
8374 return str(index
+ 1)
8376 def GetValidGLArg(self
, func
):
8377 """Gets a valid GL value for this argument."""
8378 value
= self
.GetValidArg(func
)
8379 if self
.type == 'GLsync':
8380 return ("reinterpret_cast<GLsync>(%s)" % value
)
8383 def GetValidNonCachedClientSideArg(self
, func
):
8384 """Returns a valid value for this argument in a GL call.
8385 Using the value will produce a command buffer service invocation.
8386 Returns None if there is no such value."""
8388 if self
.type == 'GLsync':
8389 return ("reinterpret_cast<GLsync>(%s)" % value
)
8392 def GetValidNonCachedClientSideCmdArg(self
, func
):
8393 """Returns a valid value for this argument in a command buffer command.
8394 Calling the GL function with the value returned by
8395 GetValidNonCachedClientSideArg will result in a command buffer command
8396 that contains the value returned by this function. """
8399 def GetNumInvalidValues(self
, func
):
8400 """returns the number of invalid values to be tested."""
8403 def GetInvalidArg(self
, index
):
8404 """returns an invalid value and expected parse result by index."""
8405 return ("---ERROR0---", "---ERROR2---", None)
8407 def GetLogArg(self
):
8408 """Get argument appropriate for LOG macro."""
8409 if self
.type == 'GLboolean':
8410 return 'GLES2Util::GetStringBool(%s)' % self
.name
8411 if self
.type == 'GLenum':
8412 return 'GLES2Util::GetStringEnum(%s)' % self
.name
8415 def WriteGetCode(self
, f
):
8416 """Writes the code to get an argument from a command structure."""
8417 if self
.type == 'GLsync':
8421 f
.write(" %s %s = static_cast<%s>(c.%s);\n" %
8422 (my_type
, self
.name
, my_type
, self
.name
))
8424 def WriteValidationCode(self
, f
, func
):
8425 """Writes the validation code for an argument."""
8428 def WriteClientSideValidationCode(self
, f
, func
):
8429 """Writes the validation code for an argument."""
8432 def WriteDestinationInitalizationValidation(self
, f
, func
):
8433 """Writes the client side destintion initialization validation."""
8436 def WriteDestinationInitalizationValidatationIfNeeded(self
, f
, func
):
8437 """Writes the client side destintion initialization validation if needed."""
8438 parts
= self
.type.split(" ")
8441 if parts
[0] in self
.need_validation_
:
8443 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8444 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
8446 def GetImmediateVersion(self
):
8447 """Gets the immediate version of this argument."""
8450 def GetBucketVersion(self
):
8451 """Gets the bucket version of this argument."""
8455 class BoolArgument(Argument
):
8456 """class for GLboolean"""
8458 def __init__(self
, name
, type):
8459 Argument
.__init
__(self
, name
, 'GLboolean')
8461 def GetValidArg(self
, func
):
8462 """Gets a valid value for this argument."""
8465 def GetValidClientSideArg(self
, func
):
8466 """Gets a valid value for this argument."""
8469 def GetValidClientSideCmdArg(self
, func
):
8470 """Gets a valid value for this argument."""
8473 def GetValidGLArg(self
, func
):
8474 """Gets a valid GL value for this argument."""
8478 class UniformLocationArgument(Argument
):
8479 """class for uniform locations."""
8481 def __init__(self
, name
):
8482 Argument
.__init
__(self
, name
, "GLint")
8484 def WriteGetCode(self
, f
):
8485 """Writes the code to get an argument from a command structure."""
8486 code
= """ %s %s = static_cast<%s>(c.%s);
8488 f
.write(code
% (self
.type, self
.name
, self
.type, self
.name
))
8490 class DataSizeArgument(Argument
):
8491 """class for data_size which Bucket commands do not need."""
8493 def __init__(self
, name
):
8494 Argument
.__init
__(self
, name
, "uint32_t")
8496 def GetBucketVersion(self
):
8500 class SizeArgument(Argument
):
8501 """class for GLsizei and GLsizeiptr."""
8503 def GetNumInvalidValues(self
, func
):
8504 """overridden from Argument."""
8505 if func
.IsImmediate():
8509 def GetInvalidArg(self
, index
):
8510 """overridden from Argument."""
8511 return ("-1", "kNoError", "GL_INVALID_VALUE")
8513 def WriteValidationCode(self
, f
, func
):
8514 """overridden from Argument."""
8517 code
= """ if (%(var_name)s < 0) {
8518 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8519 return error::kNoError;
8523 "var_name": self
.name
,
8524 "func_name": func
.original_name
,
8527 def WriteClientSideValidationCode(self
, f
, func
):
8528 """overridden from Argument."""
8529 code
= """ if (%(var_name)s < 0) {
8530 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8535 "var_name": self
.name
,
8536 "func_name": func
.original_name
,
8540 class SizeNotNegativeArgument(SizeArgument
):
8541 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8543 def __init__(self
, name
, type, gl_type
):
8544 SizeArgument
.__init
__(self
, name
, gl_type
)
8546 def GetInvalidArg(self
, index
):
8547 """overridden from SizeArgument."""
8548 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8550 def WriteValidationCode(self
, f
, func
):
8551 """overridden from SizeArgument."""
8555 class EnumBaseArgument(Argument
):
8556 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8557 ValidatedBoolArgument."""
8559 def __init__(self
, name
, gl_type
, type, gl_error
):
8560 Argument
.__init
__(self
, name
, gl_type
)
8562 self
.gl_error
= gl_error
8563 name
= type[len(gl_type
):]
8564 self
.type_name
= name
8565 self
.named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8567 def IsConstant(self
):
8568 return self
.named_type
.IsConstant()
8570 def GetConstantValue(self
):
8571 return self
.named_type
.GetConstantValue()
8573 def WriteValidationCode(self
, f
, func
):
8576 if self
.named_type
.IsConstant():
8578 f
.write(" if (!validators_->%s.IsValid(%s)) {\n" %
8579 (ToUnderscore(self
.type_name
), self
.name
))
8580 if self
.gl_error
== "GL_INVALID_ENUM":
8582 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8583 (func
.original_name
, self
.name
, self
.name
))
8586 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8587 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8588 f
.write(" return error::kNoError;\n")
8591 def WriteClientSideValidationCode(self
, f
, func
):
8592 if not self
.named_type
.IsConstant():
8594 f
.write(" if (%s != %s) {" % (self
.name
,
8595 self
.GetConstantValue()))
8597 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8598 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8599 if func
.return_type
== "void":
8600 f
.write(" return;\n")
8602 f
.write(" return %s;\n" % func
.GetErrorReturnString())
8605 def GetValidArg(self
, func
):
8606 valid_arg
= func
.GetValidArg(self
)
8607 if valid_arg
!= None:
8609 valid
= self
.named_type
.GetValidValues()
8613 index
= func
.GetOriginalArgs().index(self
)
8614 return str(index
+ 1)
8616 def GetValidClientSideArg(self
, func
):
8617 """Gets a valid value for this argument."""
8618 return self
.GetValidArg(func
)
8620 def GetValidClientSideCmdArg(self
, func
):
8621 """Gets a valid value for this argument."""
8622 valid_arg
= func
.GetValidArg(self
)
8623 if valid_arg
!= None:
8626 valid
= self
.named_type
.GetValidValues()
8631 index
= func
.GetOriginalArgs().index(self
)
8632 return str(index
+ 1)
8635 index
= func
.GetCmdArgs().index(self
)
8636 return str(index
+ 1)
8638 def GetValidGLArg(self
, func
):
8639 """Gets a valid value for this argument."""
8640 return self
.GetValidArg(func
)
8642 def GetNumInvalidValues(self
, func
):
8643 """returns the number of invalid values to be tested."""
8644 return len(self
.named_type
.GetInvalidValues())
8646 def GetInvalidArg(self
, index
):
8647 """returns an invalid value by index."""
8648 invalid
= self
.named_type
.GetInvalidValues()
8650 num_invalid
= len(invalid
)
8651 if index
>= num_invalid
:
8652 index
= num_invalid
- 1
8653 return (invalid
[index
], "kNoError", self
.gl_error
)
8654 return ("---ERROR1---", "kNoError", self
.gl_error
)
8657 class EnumArgument(EnumBaseArgument
):
8658 """A class that represents a GLenum argument"""
8660 def __init__(self
, name
, type):
8661 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
8663 def GetLogArg(self
):
8664 """Overridden from Argument."""
8665 return ("GLES2Util::GetString%s(%s)" %
8666 (self
.type_name
, self
.name
))
8669 class IntArgument(EnumBaseArgument
):
8670 """A class for a GLint argument that can only accept specific values.
8672 For example glTexImage2D takes a GLint for its internalformat
8673 argument instead of a GLenum.
8676 def __init__(self
, name
, type):
8677 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
8680 class ValidatedBoolArgument(EnumBaseArgument
):
8681 """A class for a GLboolean argument that can only accept specific values.
8683 For example glUniformMatrix takes a GLboolean for it's transpose but it
8687 def __init__(self
, name
, type):
8688 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
8690 def GetLogArg(self
):
8691 """Overridden from Argument."""
8692 return 'GLES2Util::GetStringBool(%s)' % self
.name
8695 class BitFieldArgument(EnumBaseArgument
):
8696 """A class for a GLbitfield argument that can only accept specific values.
8698 For example glFenceSync takes a GLbitfield for its flags argument bit it
8702 def __init__(self
, name
, type):
8703 EnumBaseArgument
.__init
__(self
, name
, "GLbitfield", type,
8707 class ImmediatePointerArgument(Argument
):
8708 """A class that represents an immediate argument to a function.
8710 An immediate argument is one where the data follows the command.
8713 def IsPointer(self
):
8716 def GetPointedType(self
):
8717 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8719 return match
.groupdict()['element_type']
8721 def AddCmdArgs(self
, args
):
8722 """Overridden from Argument."""
8725 def WriteGetCode(self
, f
):
8726 """Overridden from Argument."""
8728 " %s %s = GetImmediateDataAs<%s>(\n" %
8729 (self
.type, self
.name
, self
.type))
8730 f
.write(" c, data_size, immediate_data_size);\n")
8732 def WriteValidationCode(self
, f
, func
):
8733 """Overridden from Argument."""
8736 f
.write(" if (%s == NULL) {\n" % self
.name
)
8737 f
.write(" return error::kOutOfBounds;\n")
8740 def GetImmediateVersion(self
):
8741 """Overridden from Argument."""
8744 def WriteDestinationInitalizationValidation(self
, f
, func
):
8745 """Overridden from Argument."""
8746 self
.WriteDestinationInitalizationValidatationIfNeeded(f
, func
)
8748 def GetLogArg(self
):
8749 """Overridden from Argument."""
8750 return "static_cast<const void*>(%s)" % self
.name
8753 class PointerArgument(Argument
):
8754 """A class that represents a pointer argument to a function."""
8756 def IsPointer(self
):
8757 """Overridden from Argument."""
8760 def IsPointer2D(self
):
8761 """Overridden from Argument."""
8762 return self
.type.count('*') == 2
8764 def GetPointedType(self
):
8765 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8767 return match
.groupdict()['element_type']
8769 def GetValidArg(self
, func
):
8770 """Overridden from Argument."""
8771 return "shared_memory_id_, shared_memory_offset_"
8773 def GetValidGLArg(self
, func
):
8774 """Overridden from Argument."""
8775 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
8777 def GetNumInvalidValues(self
, func
):
8778 """Overridden from Argument."""
8781 def GetInvalidArg(self
, index
):
8782 """Overridden from Argument."""
8784 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8786 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8787 "kOutOfBounds", None)
8789 def GetLogArg(self
):
8790 """Overridden from Argument."""
8791 return "static_cast<const void*>(%s)" % self
.name
8793 def AddCmdArgs(self
, args
):
8794 """Overridden from Argument."""
8795 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32_t'))
8796 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32_t'))
8798 def WriteGetCode(self
, f
):
8799 """Overridden from Argument."""
8801 " %s %s = GetSharedMemoryAs<%s>(\n" %
8802 (self
.type, self
.name
, self
.type))
8804 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8805 (self
.name
, self
.name
))
8807 def WriteValidationCode(self
, f
, func
):
8808 """Overridden from Argument."""
8811 f
.write(" if (%s == NULL) {\n" % self
.name
)
8812 f
.write(" return error::kOutOfBounds;\n")
8815 def GetImmediateVersion(self
):
8816 """Overridden from Argument."""
8817 return ImmediatePointerArgument(self
.name
, self
.type)
8819 def GetBucketVersion(self
):
8820 """Overridden from Argument."""
8821 if self
.type.find('char') >= 0:
8822 if self
.IsPointer2D():
8823 return InputStringArrayBucketArgument(self
.name
, self
.type)
8824 return InputStringBucketArgument(self
.name
, self
.type)
8825 return BucketPointerArgument(self
.name
, self
.type)
8827 def WriteDestinationInitalizationValidation(self
, f
, func
):
8828 """Overridden from Argument."""
8829 self
.WriteDestinationInitalizationValidatationIfNeeded(f
, func
)
8832 class BucketPointerArgument(PointerArgument
):
8833 """A class that represents an bucket argument to a function."""
8835 def AddCmdArgs(self
, args
):
8836 """Overridden from Argument."""
8839 def WriteGetCode(self
, f
):
8840 """Overridden from Argument."""
8842 " %s %s = bucket->GetData(0, data_size);\n" %
8843 (self
.type, self
.name
))
8845 def WriteValidationCode(self
, f
, func
):
8846 """Overridden from Argument."""
8849 def GetImmediateVersion(self
):
8850 """Overridden from Argument."""
8853 def WriteDestinationInitalizationValidation(self
, f
, func
):
8854 """Overridden from Argument."""
8855 self
.WriteDestinationInitalizationValidatationIfNeeded(f
, func
)
8857 def GetLogArg(self
):
8858 """Overridden from Argument."""
8859 return "static_cast<const void*>(%s)" % self
.name
8862 class InputStringBucketArgument(Argument
):
8863 """A string input argument where the string is passed in a bucket."""
8865 def __init__(self
, name
, type):
8866 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8868 def IsPointer(self
):
8869 """Overridden from Argument."""
8872 def IsPointer2D(self
):
8873 """Overridden from Argument."""
8877 class InputStringArrayBucketArgument(Argument
):
8878 """A string array input argument where the strings are passed in a bucket."""
8880 def __init__(self
, name
, type):
8881 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8882 self
._original
_name
= name
8884 def WriteGetCode(self
, f
):
8885 """Overridden from Argument."""
8887 Bucket* bucket = GetBucket(c.%(name)s);
8889 return error::kInvalidArguments;
8892 std::vector<char*> strs;
8893 std::vector<GLint> len;
8894 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8895 return error::kInvalidArguments;
8897 const char** %(original_name)s =
8898 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8899 const GLint* length =
8900 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8905 'original_name': self
._original
_name
,
8908 def GetValidArg(self
, func
):
8909 return "kNameBucketId"
8911 def GetValidGLArg(self
, func
):
8914 def IsPointer(self
):
8915 """Overridden from Argument."""
8918 def IsPointer2D(self
):
8919 """Overridden from Argument."""
8923 class ResourceIdArgument(Argument
):
8924 """A class that represents a resource id argument to a function."""
8926 def __init__(self
, name
, type):
8927 match
= re
.match("(GLid\w+)", type)
8928 self
.resource_type
= match
.group(1)[4:]
8929 if self
.resource_type
== "Sync":
8930 type = type.replace(match
.group(1), "GLsync")
8932 type = type.replace(match
.group(1), "GLuint")
8933 Argument
.__init
__(self
, name
, type)
8935 def WriteGetCode(self
, f
):
8936 """Overridden from Argument."""
8937 if self
.type == "GLsync":
8941 f
.write(" %s %s = c.%s;\n" % (my_type
, self
.name
, self
.name
))
8943 def GetValidArg(self
, func
):
8944 return "client_%s_id_" % self
.resource_type
.lower()
8946 def GetValidGLArg(self
, func
):
8947 if self
.resource_type
== "Sync":
8948 return "reinterpret_cast<GLsync>(kService%sId)" % self
.resource_type
8949 return "kService%sId" % self
.resource_type
8952 class ResourceIdBindArgument(Argument
):
8953 """Represents a resource id argument to a bind function."""
8955 def __init__(self
, name
, type):
8956 match
= re
.match("(GLidBind\w+)", type)
8957 self
.resource_type
= match
.group(1)[8:]
8958 type = type.replace(match
.group(1), "GLuint")
8959 Argument
.__init
__(self
, name
, type)
8961 def WriteGetCode(self
, f
):
8962 """Overridden from Argument."""
8963 code
= """ %(type)s %(name)s = c.%(name)s;
8965 f
.write(code
% {'type': self
.type, 'name': self
.name
})
8967 def GetValidArg(self
, func
):
8968 return "client_%s_id_" % self
.resource_type
.lower()
8970 def GetValidGLArg(self
, func
):
8971 return "kService%sId" % self
.resource_type
8974 class ResourceIdZeroArgument(Argument
):
8975 """Represents a resource id argument to a function that can be zero."""
8977 def __init__(self
, name
, type):
8978 match
= re
.match("(GLidZero\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 f
.write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
8987 def GetValidArg(self
, func
):
8988 return "client_%s_id_" % self
.resource_type
.lower()
8990 def GetValidGLArg(self
, func
):
8991 return "kService%sId" % self
.resource_type
8993 def GetNumInvalidValues(self
, func
):
8994 """returns the number of invalid values to be tested."""
8997 def GetInvalidArg(self
, index
):
8998 """returns an invalid value by index."""
8999 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
9002 class Function(object):
9003 """A class that represents a function."""
9007 'Bind': BindHandler(),
9008 'Create': CreateHandler(),
9009 'Custom': CustomHandler(),
9010 'Data': DataHandler(),
9011 'Delete': DeleteHandler(),
9012 'DELn': DELnHandler(),
9013 'GENn': GENnHandler(),
9014 'GETn': GETnHandler(),
9015 'GLchar': GLcharHandler(),
9016 'GLcharN': GLcharNHandler(),
9017 'HandWritten': HandWrittenHandler(),
9019 'Manual': ManualHandler(),
9020 'PUT': PUTHandler(),
9021 'PUTn': PUTnHandler(),
9022 'PUTSTR': PUTSTRHandler(),
9023 'PUTXn': PUTXnHandler(),
9024 'StateSet': StateSetHandler(),
9025 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
9026 'StateSetFrontBack': StateSetFrontBackHandler(),
9027 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
9028 'StateSetNamedParameter': StateSetNamedParameter(),
9029 'STRn': STRnHandler(),
9032 def __init__(self
, name
, info
):
9034 self
.original_name
= info
['original_name']
9036 self
.original_args
= self
.ParseArgs(info
['original_args'])
9038 if 'cmd_args' in info
:
9039 self
.args_for_cmds
= self
.ParseArgs(info
['cmd_args'])
9041 self
.args_for_cmds
= self
.original_args
[:]
9043 self
.return_type
= info
['return_type']
9044 if self
.return_type
!= 'void':
9045 self
.return_arg
= CreateArg(info
['return_type'] + " result")
9047 self
.return_arg
= None
9049 self
.num_pointer_args
= sum(
9050 [1 for arg
in self
.args_for_cmds
if arg
.IsPointer()])
9051 if self
.num_pointer_args
> 0:
9052 for arg
in reversed(self
.original_args
):
9054 self
.last_original_pointer_arg
= arg
9057 self
.last_original_pointer_arg
= None
9059 self
.type_handler
= self
.type_handlers
[info
['type']]
9060 self
.can_auto_generate
= (self
.num_pointer_args
== 0 and
9061 info
['return_type'] == "void")
9064 def ParseArgs(self
, arg_string
):
9065 """Parses a function arg string."""
9067 parts
= arg_string
.split(',')
9068 for arg_string
in parts
:
9069 arg
= CreateArg(arg_string
)
9074 def IsType(self
, type_name
):
9075 """Returns true if function is a certain type."""
9076 return self
.info
['type'] == type_name
9078 def InitFunction(self
):
9079 """Creates command args and calls the init function for the type handler.
9081 Creates argument lists for command buffer commands, eg. self.cmd_args and
9083 Calls the type function initialization.
9084 Override to create different kind of command buffer command argument lists.
9087 for arg
in self
.args_for_cmds
:
9088 arg
.AddCmdArgs(self
.cmd_args
)
9091 for arg
in self
.args_for_cmds
:
9092 arg
.AddInitArgs(self
.init_args
)
9095 self
.init_args
.append(self
.return_arg
)
9097 self
.type_handler
.InitFunction(self
)
9099 def IsImmediate(self
):
9100 """Returns whether the function is immediate data function or not."""
9104 """Returns whether the function has service side validation or not."""
9105 return self
.GetInfo('unsafe', False)
9107 def GetInfo(self
, name
, default
= None):
9108 """Returns a value from the function info for this function."""
9109 if name
in self
.info
:
9110 return self
.info
[name
]
9113 def GetValidArg(self
, arg
):
9114 """Gets a valid argument value for the parameter arg from the function info
9117 index
= self
.GetOriginalArgs().index(arg
)
9121 valid_args
= self
.GetInfo('valid_args')
9122 if valid_args
and str(index
) in valid_args
:
9123 return valid_args
[str(index
)]
9126 def AddInfo(self
, name
, value
):
9128 self
.info
[name
] = value
9130 def IsExtension(self
):
9131 return self
.GetInfo('extension') or self
.GetInfo('extension_flag')
9133 def IsCoreGLFunction(self
):
9134 return (not self
.IsExtension() and
9135 not self
.GetInfo('pepper_interface') and
9136 not self
.IsUnsafe())
9138 def InPepperInterface(self
, interface
):
9139 ext
= self
.GetInfo('pepper_interface')
9140 if not interface
.GetName():
9141 return self
.IsCoreGLFunction()
9142 return ext
== interface
.GetName()
9144 def InAnyPepperExtension(self
):
9145 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
9147 def GetErrorReturnString(self
):
9148 if self
.GetInfo("error_return"):
9149 return self
.GetInfo("error_return")
9150 elif self
.return_type
== "GLboolean":
9152 elif "*" in self
.return_type
:
9156 def GetGLFunctionName(self
):
9157 """Gets the function to call to execute GL for this command."""
9158 if self
.GetInfo('decoder_func'):
9159 return self
.GetInfo('decoder_func')
9160 return "gl%s" % self
.original_name
9162 def GetGLTestFunctionName(self
):
9163 gl_func_name
= self
.GetInfo('gl_test_func')
9164 if gl_func_name
== None:
9165 gl_func_name
= self
.GetGLFunctionName()
9166 if gl_func_name
.startswith("gl"):
9167 gl_func_name
= gl_func_name
[2:]
9169 gl_func_name
= self
.original_name
9172 def GetDataTransferMethods(self
):
9173 return self
.GetInfo('data_transfer_methods',
9174 ['immediate' if self
.num_pointer_args
== 1 else 'shm'])
9176 def AddCmdArg(self
, arg
):
9177 """Adds a cmd argument to this function."""
9178 self
.cmd_args
.append(arg
)
9180 def GetCmdArgs(self
):
9181 """Gets the command args for this function."""
9182 return self
.cmd_args
9184 def ClearCmdArgs(self
):
9185 """Clears the command args for this function."""
9188 def GetCmdConstants(self
):
9189 """Gets the constants for this function."""
9190 return [arg
for arg
in self
.args_for_cmds
if arg
.IsConstant()]
9192 def GetInitArgs(self
):
9193 """Gets the init args for this function."""
9194 return self
.init_args
9196 def GetOriginalArgs(self
):
9197 """Gets the original arguments to this function."""
9198 return self
.original_args
9200 def GetLastOriginalArg(self
):
9201 """Gets the last original argument to this function."""
9202 return self
.original_args
[len(self
.original_args
) - 1]
9204 def GetLastOriginalPointerArg(self
):
9205 return self
.last_original_pointer_arg
9207 def GetResourceIdArg(self
):
9208 for arg
in self
.original_args
:
9209 if hasattr(arg
, 'resource_type'):
9213 def _MaybePrependComma(self
, arg_string
, add_comma
):
9214 """Adds a comma if arg_string is not empty and add_comma is true."""
9216 if add_comma
and len(arg_string
):
9218 return "%s%s" % (comma
, arg_string
)
9220 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
9221 """Gets a list of arguments as they are in GL."""
9222 args
= self
.GetOriginalArgs()
9223 arg_string
= ", ".join(
9224 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9225 return self
._MaybePrependComma
(arg_string
, add_comma
)
9227 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9228 """Gets the list of arguments as they are in GL."""
9229 args
= self
.GetOriginalArgs()
9230 arg_string
= separator
.join(
9231 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9232 return self
._MaybePrependComma
(arg_string
, add_comma
)
9234 def MakeHelperArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9235 """Gets a list of GL arguments after removing unneeded arguments."""
9236 args
= self
.GetOriginalArgs()
9237 arg_string
= separator
.join(
9238 ["%s%s" % (prefix
, arg
.name
)
9239 for arg
in args
if not arg
.IsConstant()])
9240 return self
._MaybePrependComma
(arg_string
, add_comma
)
9242 def MakeTypedPepperArgString(self
, prefix
):
9243 """Gets a list of arguments as they need to be for Pepper."""
9244 if self
.GetInfo("pepper_args"):
9245 return self
.GetInfo("pepper_args")
9247 return self
.MakeTypedOriginalArgString(prefix
, False)
9249 def MapCTypeToPepperIdlType(self
, ctype
, is_for_return_type
=False):
9250 """Converts a C type name to the corresponding Pepper IDL type."""
9252 'char*': '[out] str_t',
9253 'const GLchar* const*': '[out] cstr_t',
9254 'const char*': 'cstr_t',
9255 'const void*': 'mem_t',
9256 'void*': '[out] mem_t',
9257 'void**': '[out] mem_ptr_t',
9259 # We use "GLxxx_ptr_t" for "GLxxx*".
9260 matched
= re
.match(r
'(const )?(GL\w+)\*$', ctype
)
9262 idltype
= matched
.group(2) + '_ptr_t'
9263 if not matched
.group(1):
9264 idltype
= '[out] ' + idltype
9265 # If an in/out specifier is not specified yet, prepend [in].
9266 if idltype
[0] != '[':
9267 idltype
= '[in] ' + idltype
9268 # Strip the in/out specifier for a return type.
9269 if is_for_return_type
:
9270 idltype
= re
.sub(r
'\[\w+\] ', '', idltype
)
9273 def MakeTypedPepperIdlArgStrings(self
):
9274 """Gets a list of arguments as they need to be for Pepper IDL."""
9275 args
= self
.GetOriginalArgs()
9276 return ["%s %s" % (self
.MapCTypeToPepperIdlType(arg
.type), arg
.name
)
9279 def GetPepperName(self
):
9280 if self
.GetInfo("pepper_name"):
9281 return self
.GetInfo("pepper_name")
9284 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
9285 """Gets a typed list of arguments as they need to be for command buffers."""
9286 args
= self
.GetCmdArgs()
9287 arg_string
= ", ".join(
9288 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9289 return self
._MaybePrependComma
(arg_string
, add_comma
)
9291 def MakeCmdArgString(self
, prefix
, add_comma
= False):
9292 """Gets the list of arguments as they need to be for command buffers."""
9293 args
= self
.GetCmdArgs()
9294 arg_string
= ", ".join(
9295 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9296 return self
._MaybePrependComma
(arg_string
, add_comma
)
9298 def MakeTypedInitString(self
, prefix
, add_comma
= False):
9299 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9300 args
= self
.GetInitArgs()
9301 arg_string
= ", ".join(
9302 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9303 return self
._MaybePrependComma
(arg_string
, add_comma
)
9305 def MakeInitString(self
, prefix
, add_comma
= False):
9306 """Gets the list of arguments as they need to be for cmd Init/Set."""
9307 args
= self
.GetInitArgs()
9308 arg_string
= ", ".join(
9309 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9310 return self
._MaybePrependComma
(arg_string
, add_comma
)
9312 def MakeLogArgString(self
):
9313 """Makes a string of the arguments for the LOG macros"""
9314 args
= self
.GetOriginalArgs()
9315 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
9317 def WriteHandlerValidation(self
, f
):
9318 """Writes validation code for the function."""
9319 for arg
in self
.GetOriginalArgs():
9320 arg
.WriteValidationCode(f
, self
)
9321 self
.WriteValidationCode(f
)
9323 def WriteHandlerImplementation(self
, f
):
9324 """Writes the handler implementation for this command."""
9325 self
.type_handler
.WriteHandlerImplementation(self
, f
)
9327 def WriteValidationCode(self
, f
):
9328 """Writes the validation code for a command."""
9331 def WriteCmdFlag(self
, f
):
9332 """Writes the cmd cmd_flags constant."""
9334 # By default trace only at the highest level 3.
9335 trace_level
= int(self
.GetInfo('trace_level', default
= 3))
9336 if trace_level
not in xrange(0, 4):
9337 raise KeyError("Unhandled trace_level: %d" % trace_level
)
9339 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
9342 cmd_flags
= ' | '.join(flags
)
9346 f
.write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
9349 def WriteCmdArgFlag(self
, f
):
9350 """Writes the cmd kArgFlags constant."""
9351 f
.write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9353 def WriteCmdComputeSize(self
, f
):
9354 """Writes the ComputeSize function for the command."""
9355 f
.write(" static uint32_t ComputeSize() {\n")
9357 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9361 def WriteCmdSetHeader(self
, f
):
9362 """Writes the cmd's SetHeader function."""
9363 f
.write(" void SetHeader() {\n")
9364 f
.write(" header.SetCmd<ValueType>();\n")
9368 def WriteCmdInit(self
, f
):
9369 """Writes the cmd's Init function."""
9370 f
.write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
9371 f
.write(" SetHeader();\n")
9372 args
= self
.GetCmdArgs()
9374 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
9378 def WriteCmdSet(self
, f
):
9379 """Writes the cmd's Set function."""
9380 copy_args
= self
.MakeCmdArgString("_", False)
9381 f
.write(" void* Set(void* cmd%s) {\n" %
9382 self
.MakeTypedCmdArgString("_", True))
9383 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
9384 f
.write(" return NextCmdAddress<ValueType>(cmd);\n")
9388 def WriteStruct(self
, f
):
9389 self
.type_handler
.WriteStruct(self
, f
)
9391 def WriteDocs(self
, f
):
9392 self
.type_handler
.WriteDocs(self
, f
)
9394 def WriteCmdHelper(self
, f
):
9395 """Writes the cmd's helper."""
9396 self
.type_handler
.WriteCmdHelper(self
, f
)
9398 def WriteServiceImplementation(self
, f
):
9399 """Writes the service implementation for a command."""
9400 self
.type_handler
.WriteServiceImplementation(self
, f
)
9402 def WriteServiceUnitTest(self
, f
, *extras
):
9403 """Writes the service implementation for a command."""
9404 self
.type_handler
.WriteServiceUnitTest(self
, f
, *extras
)
9406 def WriteGLES2CLibImplementation(self
, f
):
9407 """Writes the GLES2 C Lib Implemention."""
9408 self
.type_handler
.WriteGLES2CLibImplementation(self
, f
)
9410 def WriteGLES2InterfaceHeader(self
, f
):
9411 """Writes the GLES2 Interface declaration."""
9412 self
.type_handler
.WriteGLES2InterfaceHeader(self
, f
)
9414 def WriteMojoGLES2ImplHeader(self
, f
):
9415 """Writes the Mojo GLES2 implementation header declaration."""
9416 self
.type_handler
.WriteMojoGLES2ImplHeader(self
, f
)
9418 def WriteMojoGLES2Impl(self
, f
):
9419 """Writes the Mojo GLES2 implementation declaration."""
9420 self
.type_handler
.WriteMojoGLES2Impl(self
, f
)
9422 def WriteGLES2InterfaceStub(self
, f
):
9423 """Writes the GLES2 Interface Stub declaration."""
9424 self
.type_handler
.WriteGLES2InterfaceStub(self
, f
)
9426 def WriteGLES2InterfaceStubImpl(self
, f
):
9427 """Writes the GLES2 Interface Stub declaration."""
9428 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, f
)
9430 def WriteGLES2ImplementationHeader(self
, f
):
9431 """Writes the GLES2 Implemention declaration."""
9432 self
.type_handler
.WriteGLES2ImplementationHeader(self
, f
)
9434 def WriteGLES2Implementation(self
, f
):
9435 """Writes the GLES2 Implemention definition."""
9436 self
.type_handler
.WriteGLES2Implementation(self
, f
)
9438 def WriteGLES2TraceImplementationHeader(self
, f
):
9439 """Writes the GLES2 Trace Implemention declaration."""
9440 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, f
)
9442 def WriteGLES2TraceImplementation(self
, f
):
9443 """Writes the GLES2 Trace Implemention definition."""
9444 self
.type_handler
.WriteGLES2TraceImplementation(self
, f
)
9446 def WriteGLES2Header(self
, f
):
9447 """Writes the GLES2 Implemention unit test."""
9448 self
.type_handler
.WriteGLES2Header(self
, f
)
9450 def WriteGLES2ImplementationUnitTest(self
, f
):
9451 """Writes the GLES2 Implemention unit test."""
9452 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, f
)
9454 def WriteDestinationInitalizationValidation(self
, f
):
9455 """Writes the client side destintion initialization validation."""
9456 self
.type_handler
.WriteDestinationInitalizationValidation(self
, f
)
9458 def WriteFormatTest(self
, f
):
9459 """Writes the cmd's format test."""
9460 self
.type_handler
.WriteFormatTest(self
, f
)
9463 class PepperInterface(object):
9464 """A class that represents a function."""
9466 def __init__(self
, info
):
9467 self
.name
= info
["name"]
9468 self
.dev
= info
["dev"]
9473 def GetInterfaceName(self
):
9477 upperint
= "_" + self
.name
.upper()
9480 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
9482 def GetStructName(self
):
9486 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
9489 class ImmediateFunction(Function
):
9490 """A class that represnets an immediate function command."""
9492 def __init__(self
, func
):
9495 "%sImmediate" % func
.name
,
9498 def InitFunction(self
):
9499 # Override args in original_args and args_for_cmds with immediate versions
9502 new_original_args
= []
9503 for arg
in self
.original_args
:
9504 new_arg
= arg
.GetImmediateVersion()
9506 new_original_args
.append(new_arg
)
9507 self
.original_args
= new_original_args
9509 new_args_for_cmds
= []
9510 for arg
in self
.args_for_cmds
:
9511 new_arg
= arg
.GetImmediateVersion()
9513 new_args_for_cmds
.append(new_arg
)
9515 self
.args_for_cmds
= new_args_for_cmds
9517 Function
.InitFunction(self
)
9519 def IsImmediate(self
):
9522 def WriteServiceImplementation(self
, f
):
9523 """Overridden from Function"""
9524 self
.type_handler
.WriteImmediateServiceImplementation(self
, f
)
9526 def WriteHandlerImplementation(self
, f
):
9527 """Overridden from Function"""
9528 self
.type_handler
.WriteImmediateHandlerImplementation(self
, f
)
9530 def WriteServiceUnitTest(self
, f
, *extras
):
9531 """Writes the service implementation for a command."""
9532 self
.type_handler
.WriteImmediateServiceUnitTest(self
, f
, *extras
)
9534 def WriteValidationCode(self
, f
):
9535 """Overridden from Function"""
9536 self
.type_handler
.WriteImmediateValidationCode(self
, f
)
9538 def WriteCmdArgFlag(self
, f
):
9539 """Overridden from Function"""
9540 f
.write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9542 def WriteCmdComputeSize(self
, f
):
9543 """Overridden from Function"""
9544 self
.type_handler
.WriteImmediateCmdComputeSize(self
, f
)
9546 def WriteCmdSetHeader(self
, f
):
9547 """Overridden from Function"""
9548 self
.type_handler
.WriteImmediateCmdSetHeader(self
, f
)
9550 def WriteCmdInit(self
, f
):
9551 """Overridden from Function"""
9552 self
.type_handler
.WriteImmediateCmdInit(self
, f
)
9554 def WriteCmdSet(self
, f
):
9555 """Overridden from Function"""
9556 self
.type_handler
.WriteImmediateCmdSet(self
, f
)
9558 def WriteCmdHelper(self
, f
):
9559 """Overridden from Function"""
9560 self
.type_handler
.WriteImmediateCmdHelper(self
, f
)
9562 def WriteFormatTest(self
, f
):
9563 """Overridden from Function"""
9564 self
.type_handler
.WriteImmediateFormatTest(self
, f
)
9567 class BucketFunction(Function
):
9568 """A class that represnets a bucket version of a function command."""
9570 def __init__(self
, func
):
9573 "%sBucket" % func
.name
,
9576 def InitFunction(self
):
9577 # Override args in original_args and args_for_cmds with bucket versions
9580 new_original_args
= []
9581 for arg
in self
.original_args
:
9582 new_arg
= arg
.GetBucketVersion()
9584 new_original_args
.append(new_arg
)
9585 self
.original_args
= new_original_args
9587 new_args_for_cmds
= []
9588 for arg
in self
.args_for_cmds
:
9589 new_arg
= arg
.GetBucketVersion()
9591 new_args_for_cmds
.append(new_arg
)
9593 self
.args_for_cmds
= new_args_for_cmds
9595 Function
.InitFunction(self
)
9597 def WriteServiceImplementation(self
, f
):
9598 """Overridden from Function"""
9599 self
.type_handler
.WriteBucketServiceImplementation(self
, f
)
9601 def WriteHandlerImplementation(self
, f
):
9602 """Overridden from Function"""
9603 self
.type_handler
.WriteBucketHandlerImplementation(self
, f
)
9605 def WriteServiceUnitTest(self
, f
, *extras
):
9606 """Overridden from Function"""
9607 self
.type_handler
.WriteBucketServiceUnitTest(self
, f
, *extras
)
9609 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9610 """Overridden from Function"""
9611 args
= self
.GetOriginalArgs()
9612 arg_string
= separator
.join(
9613 ["%s%s" % (prefix
, arg
.name
[0:-10] if arg
.name
.endswith("_bucket_id")
9614 else arg
.name
) for arg
in args
])
9615 return super(BucketFunction
, self
)._MaybePrependComma
(arg_string
, add_comma
)
9618 def CreateArg(arg_string
):
9619 """Creates an Argument."""
9620 arg_parts
= arg_string
.split()
9621 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
9623 # Is this a pointer argument?
9624 elif arg_string
.find('*') >= 0:
9625 return PointerArgument(
9627 " ".join(arg_parts
[0:-1]))
9628 # Is this a resource argument? Must come after pointer check.
9629 elif arg_parts
[0].startswith('GLidBind'):
9630 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9631 elif arg_parts
[0].startswith('GLidZero'):
9632 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9633 elif arg_parts
[0].startswith('GLid'):
9634 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9635 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
9636 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9637 elif arg_parts
[0].startswith('GLbitfield') and len(arg_parts
[0]) > 10:
9638 return BitFieldArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9639 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
9640 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9641 elif arg_parts
[0].startswith('GLboolean'):
9642 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9643 elif arg_parts
[0].startswith('GLintUniformLocation'):
9644 return UniformLocationArgument(arg_parts
[-1])
9645 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
9646 not arg_parts
[0].startswith('GLintptr')):
9647 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9648 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
9649 arg_parts
[0].startswith('GLintptrNotNegative')):
9650 return SizeNotNegativeArgument(arg_parts
[-1],
9651 " ".join(arg_parts
[0:-1]),
9652 arg_parts
[0][0:-11])
9653 elif arg_parts
[0].startswith('GLsize'):
9654 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9656 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9659 class GLGenerator(object):
9660 """A class to generate GL command buffers."""
9662 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9664 def __init__(self
, verbose
):
9665 self
.original_functions
= []
9667 self
.verbose
= verbose
9669 self
.pepper_interfaces
= []
9670 self
.interface_info
= {}
9671 self
.generated_cpp_filenames
= []
9673 for interface
in _PEPPER_INTERFACES
:
9674 interface
= PepperInterface(interface
)
9675 self
.pepper_interfaces
.append(interface
)
9676 self
.interface_info
[interface
.GetName()] = interface
9678 def AddFunction(self
, func
):
9679 """Adds a function."""
9680 self
.functions
.append(func
)
9682 def GetFunctionInfo(self
, name
):
9683 """Gets a type info for the given function name."""
9684 if name
in _FUNCTION_INFO
:
9685 func_info
= _FUNCTION_INFO
[name
].copy()
9689 if not 'type' in func_info
:
9690 func_info
['type'] = ''
9695 """Prints something if verbose is true."""
9699 def Error(self
, msg
):
9700 """Prints an error."""
9701 print "Error: %s" % msg
9704 def ParseGLH(self
, filename
):
9705 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9706 with
open(filename
, "r") as f
:
9707 functions
= f
.read()
9708 for line
in functions
.splitlines():
9709 match
= self
._function
_re
.match(line
)
9711 func_name
= match
.group(2)[2:]
9712 func_info
= self
.GetFunctionInfo(func_name
)
9713 if func_info
['type'] == 'Noop':
9716 parsed_func_info
= {
9717 'original_name': func_name
,
9718 'original_args': match
.group(3),
9719 'return_type': match
.group(1).strip(),
9722 for k
in parsed_func_info
.keys():
9723 if not k
in func_info
:
9724 func_info
[k
] = parsed_func_info
[k
]
9726 f
= Function(func_name
, func_info
)
9727 self
.original_functions
.append(f
)
9729 #for arg in f.GetOriginalArgs():
9730 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9731 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9733 gen_cmd
= f
.GetInfo('gen_cmd')
9734 if gen_cmd
== True or gen_cmd
== None:
9735 if f
.type_handler
.NeedsDataTransferFunction(f
):
9736 methods
= f
.GetDataTransferMethods()
9737 if 'immediate' in methods
:
9738 self
.AddFunction(ImmediateFunction(f
))
9739 if 'bucket' in methods
:
9740 self
.AddFunction(BucketFunction(f
))
9741 if 'shm' in methods
:
9746 self
.Log("Auto Generated Functions : %d" %
9747 len([f
for f
in self
.functions
if f
.can_auto_generate
or
9748 (not f
.IsType('') and not f
.IsType('Custom') and
9749 not f
.IsType('Todo'))]))
9751 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
9752 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
9753 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
9756 self
.Log(" %-10s %-20s gl%s" % (f
.info
['type'], f
.return_type
, f
.name
))
9758 def WriteCommandIds(self
, filename
):
9759 """Writes the command buffer format"""
9760 with
CHeaderWriter(filename
) as f
:
9761 f
.write("#define GLES2_COMMAND_LIST(OP) \\\n")
9763 for func
in self
.functions
:
9764 f
.write(" %-60s /* %d */ \\\n" %
9765 ("OP(%s)" % func
.name
, id))
9769 f
.write("enum CommandId {\n")
9770 f
.write(" kStartPoint = cmd::kLastCommonId, "
9771 "// All GLES2 commands start after this.\n")
9772 f
.write("#define GLES2_CMD_OP(name) k ## name,\n")
9773 f
.write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9774 f
.write("#undef GLES2_CMD_OP\n")
9775 f
.write(" kNumCommands\n")
9778 self
.generated_cpp_filenames
.append(filename
)
9780 def WriteFormat(self
, filename
):
9781 """Writes the command buffer format"""
9782 with
CHeaderWriter(filename
) as f
:
9783 # Forward declaration of a few enums used in constant argument
9784 # to avoid including GL header files.
9786 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9787 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9790 for enum
in enum_defines
:
9791 f
.write("#define %s %s\n" % (enum
, enum_defines
[enum
]))
9793 for func
in self
.functions
:
9795 #gen_cmd = func.GetInfo('gen_cmd')
9796 #if gen_cmd == True or gen_cmd == None:
9799 self
.generated_cpp_filenames
.append(filename
)
9801 def WriteDocs(self
, filename
):
9802 """Writes the command buffer doc version of the commands"""
9803 with
CHeaderWriter(filename
) as f
:
9804 for func
in self
.functions
:
9806 #gen_cmd = func.GetInfo('gen_cmd')
9807 #if gen_cmd == True or gen_cmd == None:
9810 self
.generated_cpp_filenames
.append(filename
)
9812 def WriteFormatTest(self
, filename
):
9813 """Writes the command buffer format test."""
9814 comment
= ("// This file contains unit tests for gles2 commmands\n"
9815 "// It is included by gles2_cmd_format_test.cc\n\n")
9816 with
CHeaderWriter(filename
, comment
) as f
:
9817 for func
in self
.functions
:
9819 #gen_cmd = func.GetInfo('gen_cmd')
9820 #if gen_cmd == True or gen_cmd == None:
9821 func
.WriteFormatTest(f
)
9822 self
.generated_cpp_filenames
.append(filename
)
9824 def WriteCmdHelperHeader(self
, filename
):
9825 """Writes the gles2 command helper."""
9826 with
CHeaderWriter(filename
) as f
:
9827 for func
in self
.functions
:
9829 #gen_cmd = func.GetInfo('gen_cmd')
9830 #if gen_cmd == True or gen_cmd == None:
9831 func
.WriteCmdHelper(f
)
9832 self
.generated_cpp_filenames
.append(filename
)
9834 def WriteServiceContextStateHeader(self
, filename
):
9835 """Writes the service context state header."""
9836 comment
= "// It is included by context_state.h\n"
9837 with
CHeaderWriter(filename
, comment
) as f
:
9838 f
.write("struct EnableFlags {\n")
9839 f
.write(" EnableFlags();\n")
9840 for capability
in _CAPABILITY_FLAGS
:
9841 f
.write(" bool %s;\n" % capability
['name'])
9842 f
.write(" bool cached_%s;\n" % capability
['name'])
9845 for state_name
in sorted(_STATES
.keys()):
9846 state
= _STATES
[state_name
]
9847 for item
in state
['states']:
9848 if isinstance(item
['default'], list):
9849 f
.write("%s %s[%d];\n" % (item
['type'], item
['name'],
9850 len(item
['default'])))
9852 f
.write("%s %s;\n" % (item
['type'], item
['name']))
9854 if item
.get('cached', False):
9855 if isinstance(item
['default'], list):
9856 f
.write("%s cached_%s[%d];\n" % (item
['type'], item
['name'],
9857 len(item
['default'])))
9859 f
.write("%s cached_%s;\n" % (item
['type'], item
['name']))
9863 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9866 for capability
in _CAPABILITY_FLAGS
:
9869 """ % capability
['name'].upper())
9871 if (enable_flags.cached_%(name)s == enable &&
9872 !ignore_cached_state)
9874 enable_flags.cached_%(name)s = enable;
9889 self
.generated_cpp_filenames
.append(filename
)
9891 def WriteClientContextStateHeader(self
, filename
):
9892 """Writes the client context state header."""
9893 comment
= "// It is included by client_context_state.h\n"
9894 with
CHeaderWriter(filename
, comment
) as f
:
9895 f
.write("struct EnableFlags {\n")
9896 f
.write(" EnableFlags();\n")
9897 for capability
in _CAPABILITY_FLAGS
:
9898 f
.write(" bool %s;\n" % capability
['name'])
9900 self
.generated_cpp_filenames
.append(filename
)
9902 def WriteContextStateGetters(self
, f
, class_name
):
9903 """Writes the state getters."""
9904 for gl_type
in ["GLint", "GLfloat"]:
9906 bool %s::GetStateAs%s(
9907 GLenum pname, %s* params, GLsizei* num_written) const {
9909 """ % (class_name
, gl_type
, gl_type
))
9910 for state_name
in sorted(_STATES
.keys()):
9911 state
= _STATES
[state_name
]
9913 f
.write(" case %s:\n" % state
['enum'])
9914 f
.write(" *num_written = %d;\n" % len(state
['states']))
9915 f
.write(" if (params) {\n")
9916 for ndx
,item
in enumerate(state
['states']):
9917 f
.write(" params[%d] = static_cast<%s>(%s);\n" %
9918 (ndx
, gl_type
, item
['name']))
9920 f
.write(" return true;\n")
9922 for item
in state
['states']:
9923 f
.write(" case %s:\n" % item
['enum'])
9924 if isinstance(item
['default'], list):
9925 item_len
= len(item
['default'])
9926 f
.write(" *num_written = %d;\n" % item_len
)
9927 f
.write(" if (params) {\n")
9928 if item
['type'] == gl_type
:
9929 f
.write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9930 (item
['name'], item
['type'], item_len
))
9932 f
.write(" for (size_t i = 0; i < %s; ++i) {\n" %
9934 f
.write(" params[i] = %s;\n" %
9935 (GetGLGetTypeConversion(gl_type
, item
['type'],
9936 "%s[i]" % item
['name'])))
9939 f
.write(" *num_written = 1;\n")
9940 f
.write(" if (params) {\n")
9941 f
.write(" params[0] = %s;\n" %
9942 (GetGLGetTypeConversion(gl_type
, item
['type'],
9945 f
.write(" return true;\n")
9946 for capability
in _CAPABILITY_FLAGS
:
9947 f
.write(" case GL_%s:\n" % capability
['name'].upper())
9948 f
.write(" *num_written = 1;\n")
9949 f
.write(" if (params) {\n")
9951 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9952 (gl_type
, capability
['name']))
9954 f
.write(" return true;\n")
9955 f
.write(""" default:
9961 def WriteServiceContextStateImpl(self
, filename
):
9962 """Writes the context state service implementation."""
9963 comment
= "// It is included by context_state.cc\n"
9964 with
CHeaderWriter(filename
, comment
) as f
:
9966 for capability
in _CAPABILITY_FLAGS
:
9967 code
.append("%s(%s)" %
9968 (capability
['name'],
9969 ('false', 'true')['default' in capability
]))
9970 code
.append("cached_%s(%s)" %
9971 (capability
['name'],
9972 ('false', 'true')['default' in capability
]))
9973 f
.write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9977 f
.write("void ContextState::Initialize() {\n")
9978 for state_name
in sorted(_STATES
.keys()):
9979 state
= _STATES
[state_name
]
9980 for item
in state
['states']:
9981 if isinstance(item
['default'], list):
9982 for ndx
, value
in enumerate(item
['default']):
9983 f
.write(" %s[%d] = %s;\n" % (item
['name'], ndx
, value
))
9985 f
.write(" %s = %s;\n" % (item
['name'], item
['default']))
9986 if item
.get('cached', False):
9987 if isinstance(item
['default'], list):
9988 for ndx
, value
in enumerate(item
['default']):
9989 f
.write(" cached_%s[%d] = %s;\n" % (item
['name'], ndx
, value
))
9991 f
.write(" cached_%s = %s;\n" % (item
['name'], item
['default']))
9995 void ContextState::InitCapabilities(const ContextState* prev_state) const {
9997 def WriteCapabilities(test_prev
, es3_caps
):
9998 for capability
in _CAPABILITY_FLAGS
:
9999 capability_name
= capability
['name']
10000 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10001 if capability_es3
and not es3_caps
or not capability_es3
and es3_caps
:
10004 f
.write(""" if (prev_state->enable_flags.cached_%s !=
10005 enable_flags.cached_%s) {\n""" %
10006 (capability_name
, capability_name
))
10007 f
.write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
10008 (capability_name
.upper(), capability_name
))
10012 f
.write(" if (prev_state) {")
10013 WriteCapabilities(True, False)
10014 f
.write(" if (feature_info_->IsES3Capable()) {\n")
10015 WriteCapabilities(True, True)
10017 f
.write(" } else {")
10018 WriteCapabilities(False, False)
10019 f
.write(" if (feature_info_->IsES3Capable()) {\n")
10020 WriteCapabilities(False, True)
10025 void ContextState::InitState(const ContextState *prev_state) const {
10028 def WriteStates(test_prev
):
10029 # We need to sort the keys so the expectations match
10030 for state_name
in sorted(_STATES
.keys()):
10031 state
= _STATES
[state_name
]
10032 if state
['type'] == 'FrontBack':
10033 num_states
= len(state
['states'])
10034 for ndx
, group
in enumerate(Grouper(num_states
/ 2,
10039 for place
, item
in enumerate(group
):
10040 item_name
= CachedStateName(item
)
10041 args
.append('%s' % item_name
)
10045 f
.write("(%s != prev_state->%s)" % (item_name
, item_name
))
10049 " gl%s(%s, %s);\n" %
10050 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
],
10052 elif state
['type'] == 'NamedParameter':
10053 for item
in state
['states']:
10054 item_name
= CachedStateName(item
)
10056 if 'extension_flag' in item
:
10057 f
.write(" if (feature_info_->feature_flags().%s) {\n " %
10058 item
['extension_flag'])
10060 if isinstance(item
['default'], list):
10061 f
.write(" if (memcmp(prev_state->%s, %s, "
10062 "sizeof(%s) * %d)) {\n" %
10063 (item_name
, item_name
, item
['type'],
10064 len(item
['default'])))
10066 f
.write(" if (prev_state->%s != %s) {\n " %
10067 (item_name
, item_name
))
10068 if 'gl_version_flag' in item
:
10069 item_name
= item
['gl_version_flag']
10071 if item_name
[0] == '!':
10073 item_name
= item_name
[1:]
10074 f
.write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10075 (inverted
, item_name
))
10076 f
.write(" gl%s(%s, %s);\n" %
10079 if 'enum_set' in item
else item
['enum']),
10081 if 'gl_version_flag' in item
:
10084 if 'extension_flag' in item
:
10087 if 'extension_flag' in item
:
10090 if 'extension_flag' in state
:
10091 f
.write(" if (feature_info_->feature_flags().%s)\n " %
10092 state
['extension_flag'])
10096 for place
, item
in enumerate(state
['states']):
10097 item_name
= CachedStateName(item
)
10098 args
.append('%s' % item_name
)
10102 f
.write("(%s != prev_state->%s)" %
10103 (item_name
, item_name
))
10106 f
.write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
10108 f
.write(" if (prev_state) {")
10110 f
.write(" } else {")
10115 f
.write("""bool ContextState::GetEnabled(GLenum cap) const {
10118 for capability
in _CAPABILITY_FLAGS
:
10119 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10120 f
.write(" return enable_flags.%s;\n" % capability
['name'])
10121 f
.write(""" default:
10127 self
.WriteContextStateGetters(f
, "ContextState")
10128 self
.generated_cpp_filenames
.append(filename
)
10130 def WriteClientContextStateImpl(self
, filename
):
10131 """Writes the context state client side implementation."""
10132 comment
= "// It is included by client_context_state.cc\n"
10133 with
CHeaderWriter(filename
, comment
) as f
:
10135 for capability
in _CAPABILITY_FLAGS
:
10136 code
.append("%s(%s)" %
10137 (capability
['name'],
10138 ('false', 'true')['default' in capability
]))
10140 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10145 bool ClientContextState::SetCapabilityState(
10146 GLenum cap, bool enabled, bool* changed) {
10150 for capability
in _CAPABILITY_FLAGS
:
10151 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10152 f
.write(""" if (enable_flags.%(name)s != enabled) {
10154 enable_flags.%(name)s = enabled;
10158 f
.write(""" default:
10163 f
.write("""bool ClientContextState::GetEnabled(
10164 GLenum cap, bool* enabled) const {
10167 for capability
in _CAPABILITY_FLAGS
:
10168 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10169 f
.write(" *enabled = enable_flags.%s;\n" % capability
['name'])
10170 f
.write(" return true;\n")
10171 f
.write(""" default:
10176 self
.generated_cpp_filenames
.append(filename
)
10178 def WriteServiceImplementation(self
, filename
):
10179 """Writes the service decorder implementation."""
10180 comment
= "// It is included by gles2_cmd_decoder.cc\n"
10181 with
CHeaderWriter(filename
, comment
) as f
:
10182 for func
in self
.functions
:
10184 #gen_cmd = func.GetInfo('gen_cmd')
10185 #if gen_cmd == True or gen_cmd == None:
10186 func
.WriteServiceImplementation(f
)
10189 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10192 for capability
in _CAPABILITY_FLAGS
:
10193 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10194 if 'state_flag' in capability
:
10197 state_.enable_flags.%(name)s = enabled;
10198 if (state_.enable_flags.cached_%(name)s != enabled
10199 || state_.ignore_cached_state) {
10200 %(state_flag)s = true;
10206 state_.enable_flags.%(name)s = enabled;
10207 if (state_.enable_flags.cached_%(name)s != enabled
10208 || state_.ignore_cached_state) {
10209 state_.enable_flags.cached_%(name)s = enabled;
10214 f
.write(""" default:
10220 self
.generated_cpp_filenames
.append(filename
)
10222 def WriteServiceUnitTests(self
, filename_pattern
):
10223 """Writes the service decorder unit tests."""
10224 num_tests
= len(self
.functions
)
10225 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
10227 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
10229 filename
= filename_pattern
% count
10230 comment
= "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" \
10232 with
CHeaderWriter(filename
, comment
) as f
:
10233 test_name
= 'GLES2DecoderTest%d' % count
10234 end
= test_num
+ FUNCTIONS_PER_FILE
10235 if end
> num_tests
:
10237 for idx
in range(test_num
, end
):
10238 func
= self
.functions
[idx
]
10240 # Do any filtering of the functions here, so that the functions
10241 # will not move between the numbered files if filtering properties
10243 if func
.GetInfo('extension_flag'):
10247 #gen_cmd = func.GetInfo('gen_cmd')
10248 #if gen_cmd == True or gen_cmd == None:
10249 if func
.GetInfo('unit_test') == False:
10250 f
.write("// TODO(gman): %s\n" % func
.name
)
10252 func
.WriteServiceUnitTest(f
, {
10253 'test_name': test_name
10255 self
.generated_cpp_filenames
.append(filename
)
10257 comment
= "// It is included by gles2_cmd_decoder_unittest_base.cc\n"
10258 filename
= filename_pattern
% 0
10259 with
CHeaderWriter(filename
, comment
) as f
:
10261 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10262 bool es3_capable) {""")
10263 for capability
in _CAPABILITY_FLAGS
:
10264 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10265 if not capability_es3
:
10266 f
.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10267 (capability
['name'].upper(),
10268 ('false', 'true')['default' in capability
]))
10270 f
.write(" if (es3_capable) {")
10271 for capability
in _CAPABILITY_FLAGS
:
10272 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10274 f
.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10275 (capability
['name'].upper(),
10276 ('false', 'true')['default' in capability
]))
10280 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10282 # We need to sort the keys so the expectations match
10283 for state_name
in sorted(_STATES
.keys()):
10284 state
= _STATES
[state_name
]
10285 if state
['type'] == 'FrontBack':
10286 num_states
= len(state
['states'])
10287 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
10290 if 'expected' in item
:
10291 args
.append(item
['expected'])
10293 args
.append(item
['default'])
10295 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10296 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
10297 f
.write(" .Times(1)\n")
10298 f
.write(" .RetiresOnSaturation();\n")
10299 elif state
['type'] == 'NamedParameter':
10300 for item
in state
['states']:
10301 if 'extension_flag' in item
:
10302 f
.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10303 item
['extension_flag'])
10305 expect_value
= item
['default']
10306 if isinstance(expect_value
, list):
10307 # TODO: Currently we do not check array values.
10311 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10314 if 'enum_set' in item
else item
['enum']),
10316 f
.write(" .Times(1)\n")
10317 f
.write(" .RetiresOnSaturation();\n")
10318 if 'extension_flag' in item
:
10321 if 'extension_flag' in state
:
10322 f
.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10323 state
['extension_flag'])
10326 for item
in state
['states']:
10327 if 'expected' in item
:
10328 args
.append(item
['expected'])
10330 args
.append(item
['default'])
10331 # TODO: Currently we do not check array values.
10332 args
= ["_" if isinstance(arg
, list) else arg
for arg
in args
]
10333 f
.write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10334 (state
['func'], ", ".join(args
)))
10335 f
.write(" .Times(1)\n")
10336 f
.write(" .RetiresOnSaturation();\n")
10337 if 'extension_flag' in state
:
10340 self
.generated_cpp_filenames
.append(filename
)
10342 def WriteServiceUnitTestsForExtensions(self
, filename
):
10343 """Writes the service decorder unit tests for functions with extension_flag.
10345 The functions are special in that they need a specific unit test
10346 baseclass to turn on the extension.
10348 functions
= [f
for f
in self
.functions
if f
.GetInfo('extension_flag')]
10349 comment
= "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n"
10350 with
CHeaderWriter(filename
, comment
) as f
:
10351 for func
in functions
:
10353 if func
.GetInfo('unit_test') == False:
10354 f
.write("// TODO(gman): %s\n" % func
.name
)
10356 extension
= ToCamelCase(
10357 ToGLExtensionString(func
.GetInfo('extension_flag')))
10358 func
.WriteServiceUnitTest(f
, {
10359 'test_name': 'GLES2DecoderTestWith%s' % extension
10361 self
.generated_cpp_filenames
.append(filename
)
10363 def WriteGLES2Header(self
, filename
):
10364 """Writes the GLES2 header."""
10365 comment
= "// This file contains Chromium-specific GLES2 declarations.\n\n"
10366 with
CHeaderWriter(filename
, comment
) as f
:
10367 for func
in self
.original_functions
:
10368 func
.WriteGLES2Header(f
)
10370 self
.generated_cpp_filenames
.append(filename
)
10372 def WriteGLES2CLibImplementation(self
, filename
):
10373 """Writes the GLES2 c lib implementation."""
10374 comment
= "// These functions emulate GLES2 over command buffers.\n"
10375 with
CHeaderWriter(filename
, comment
) as f
:
10376 for func
in self
.original_functions
:
10377 func
.WriteGLES2CLibImplementation(f
)
10381 extern const NameToFunc g_gles2_function_table[] = {
10383 for func
in self
.original_functions
:
10385 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10386 (func
.name
, func
.name
))
10387 f
.write(""" { NULL, NULL, },
10390 } // namespace gles2
10392 self
.generated_cpp_filenames
.append(filename
)
10394 def WriteGLES2InterfaceHeader(self
, filename
):
10395 """Writes the GLES2 interface header."""
10396 comment
= ("// This file is included by gles2_interface.h to declare the\n"
10397 "// GL api functions.\n")
10398 with
CHeaderWriter(filename
, comment
) as f
:
10399 for func
in self
.original_functions
:
10400 func
.WriteGLES2InterfaceHeader(f
)
10401 self
.generated_cpp_filenames
.append(filename
)
10403 def WriteMojoGLES2ImplHeader(self
, filename
):
10404 """Writes the Mojo GLES2 implementation header."""
10405 comment
= ("// This file is included by gles2_interface.h to declare the\n"
10406 "// GL api functions.\n")
10408 #include "gpu/command_buffer/client/gles2_interface.h"
10409 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10413 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10415 explicit MojoGLES2Impl(MojoGLES2Context context) {
10416 context_ = context;
10418 ~MojoGLES2Impl() override {}
10420 with
CHeaderWriter(filename
, comment
) as f
:
10422 for func
in self
.original_functions
:
10423 func
.WriteMojoGLES2ImplHeader(f
)
10426 MojoGLES2Context context_;
10429 } // namespace mojo
10432 self
.generated_cpp_filenames
.append(filename
)
10434 def WriteMojoGLES2Impl(self
, filename
):
10435 """Writes the Mojo GLES2 implementation."""
10437 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10439 #include "base/logging.h"
10440 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_copy_texture.h"
10441 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_image.h"
10442 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10443 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_pixel_transfer_buffer_object.h"
10444 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10445 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10446 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10447 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10448 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10453 with
CWriter(filename
) as f
:
10455 for func
in self
.original_functions
:
10456 func
.WriteMojoGLES2Impl(f
)
10459 } // namespace mojo
10462 self
.generated_cpp_filenames
.append(filename
)
10464 def WriteGLES2InterfaceStub(self
, filename
):
10465 """Writes the GLES2 interface stub header."""
10466 comment
= "// This file is included by gles2_interface_stub.h.\n"
10467 with
CHeaderWriter(filename
, comment
) as f
:
10468 for func
in self
.original_functions
:
10469 func
.WriteGLES2InterfaceStub(f
)
10470 self
.generated_cpp_filenames
.append(filename
)
10472 def WriteGLES2InterfaceStubImpl(self
, filename
):
10473 """Writes the GLES2 interface header."""
10474 comment
= "// This file is included by gles2_interface_stub.cc.\n"
10475 with
CHeaderWriter(filename
, comment
) as f
:
10476 for func
in self
.original_functions
:
10477 func
.WriteGLES2InterfaceStubImpl(f
)
10478 self
.generated_cpp_filenames
.append(filename
)
10480 def WriteGLES2ImplementationHeader(self
, filename
):
10481 """Writes the GLES2 Implementation header."""
10483 ("// This file is included by gles2_implementation.h to declare the\n"
10484 "// GL api functions.\n")
10485 with
CHeaderWriter(filename
, comment
) as f
:
10486 for func
in self
.original_functions
:
10487 func
.WriteGLES2ImplementationHeader(f
)
10488 self
.generated_cpp_filenames
.append(filename
)
10490 def WriteGLES2Implementation(self
, filename
):
10491 """Writes the GLES2 Implementation."""
10493 ("// This file is included by gles2_implementation.cc to define the\n"
10494 "// GL api functions.\n")
10495 with
CHeaderWriter(filename
, comment
) as f
:
10496 for func
in self
.original_functions
:
10497 func
.WriteGLES2Implementation(f
)
10498 self
.generated_cpp_filenames
.append(filename
)
10500 def WriteGLES2TraceImplementationHeader(self
, filename
):
10501 """Writes the GLES2 Trace Implementation header."""
10502 comment
= "// This file is included by gles2_trace_implementation.h\n"
10503 with
CHeaderWriter(filename
, comment
) as f
:
10504 for func
in self
.original_functions
:
10505 func
.WriteGLES2TraceImplementationHeader(f
)
10506 self
.generated_cpp_filenames
.append(filename
)
10508 def WriteGLES2TraceImplementation(self
, filename
):
10509 """Writes the GLES2 Trace Implementation."""
10510 comment
= "// This file is included by gles2_trace_implementation.cc\n"
10511 with
CHeaderWriter(filename
, comment
) as f
:
10512 for func
in self
.original_functions
:
10513 func
.WriteGLES2TraceImplementation(f
)
10514 self
.generated_cpp_filenames
.append(filename
)
10516 def WriteGLES2ImplementationUnitTests(self
, filename
):
10517 """Writes the GLES2 helper header."""
10519 ("// This file is included by gles2_implementation.h to declare the\n"
10520 "// GL api functions.\n")
10521 with
CHeaderWriter(filename
, comment
) as f
:
10522 for func
in self
.original_functions
:
10523 func
.WriteGLES2ImplementationUnitTest(f
)
10524 self
.generated_cpp_filenames
.append(filename
)
10526 def WriteServiceUtilsHeader(self
, filename
):
10527 """Writes the gles2 auto generated utility header."""
10528 with
CHeaderWriter(filename
) as f
:
10529 for name
in sorted(_NAMED_TYPE_INFO
.keys()):
10530 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10531 if named_type
.IsConstant():
10533 f
.write("ValueValidator<%s> %s;\n" %
10534 (named_type
.GetType(), ToUnderscore(name
)))
10536 self
.generated_cpp_filenames
.append(filename
)
10538 def WriteServiceUtilsImplementation(self
, filename
):
10539 """Writes the gles2 auto generated utility implementation."""
10540 with
CHeaderWriter(filename
) as f
:
10541 names
= sorted(_NAMED_TYPE_INFO
.keys())
10543 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10544 if named_type
.IsConstant():
10546 if named_type
.GetValidValues():
10547 f
.write("static const %s valid_%s_table[] = {\n" %
10548 (named_type
.GetType(), ToUnderscore(name
)))
10549 for value
in named_type
.GetValidValues():
10550 f
.write(" %s,\n" % value
)
10553 if named_type
.GetValidValuesES3():
10554 f
.write("static const %s valid_%s_table_es3[] = {\n" %
10555 (named_type
.GetType(), ToUnderscore(name
)))
10556 for value
in named_type
.GetValidValuesES3():
10557 f
.write(" %s,\n" % value
)
10560 if named_type
.GetDeprecatedValuesES3():
10561 f
.write("static const %s deprecated_%s_table_es3[] = {\n" %
10562 (named_type
.GetType(), ToUnderscore(name
)))
10563 for value
in named_type
.GetDeprecatedValuesES3():
10564 f
.write(" %s,\n" % value
)
10567 f
.write("Validators::Validators()")
10569 for count
, name
in enumerate(names
):
10570 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10571 if named_type
.IsConstant():
10573 if named_type
.GetValidValues():
10574 code
= """%(pre)s%(name)s(
10575 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10577 code
= "%(pre)s%(name)s()"
10579 'name': ToUnderscore(name
),
10586 f
.write("void Validators::UpdateValuesES3() {\n")
10588 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10589 if named_type
.GetDeprecatedValuesES3():
10590 code
= """ %(name)s.RemoveValues(
10591 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10594 'name': ToUnderscore(name
),
10596 if named_type
.GetValidValuesES3():
10597 code
= """ %(name)s.AddValues(
10598 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10601 'name': ToUnderscore(name
),
10604 self
.generated_cpp_filenames
.append(filename
)
10606 def WriteCommonUtilsHeader(self
, filename
):
10607 """Writes the gles2 common utility header."""
10608 with
CHeaderWriter(filename
) as f
:
10609 type_infos
= sorted(_NAMED_TYPE_INFO
.keys())
10610 for type_info
in type_infos
:
10611 if _NAMED_TYPE_INFO
[type_info
]['type'] == 'GLenum':
10612 f
.write("static std::string GetString%s(uint32_t value);\n" %
10615 self
.generated_cpp_filenames
.append(filename
)
10617 def WriteCommonUtilsImpl(self
, filename
):
10618 """Writes the gles2 common utility header."""
10619 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10621 for fname
in ['third_party/khronos/GLES2/gl2.h',
10622 'third_party/khronos/GLES2/gl2ext.h',
10623 'third_party/khronos/GLES3/gl3.h',
10624 'gpu/GLES2/gl2chromium.h',
10625 'gpu/GLES2/gl2extchromium.h']:
10626 lines
= open(fname
).readlines()
10628 m
= enum_re
.match(line
)
10632 if len(value
) <= 10:
10633 if not value
in dict:
10635 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10636 elif dict[value
] != name
and (name
.endswith('_CHROMIUM') or
10637 dict[value
].endswith('_CHROMIUM')):
10638 self
.Error("code collision: %s and %s have the same code %s" %
10639 (dict[value
], name
, value
))
10641 with
CHeaderWriter(filename
) as f
:
10642 f
.write("static const GLES2Util::EnumToString "
10643 "enum_to_string_table[] = {\n")
10645 f
.write(' { %s, "%s", },\n' % (value
, dict[value
]))
10648 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10649 enum_to_string_table;
10650 const size_t GLES2Util::enum_to_string_table_len_ =
10651 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10655 enums
= sorted(_NAMED_TYPE_INFO
.keys())
10657 if _NAMED_TYPE_INFO
[enum
]['type'] == 'GLenum':
10658 f
.write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10660 valid_list
= _NAMED_TYPE_INFO
[enum
]['valid']
10661 if 'valid_es3' in _NAMED_TYPE_INFO
[enum
]:
10662 valid_list
= valid_list
+ _NAMED_TYPE_INFO
[enum
]['valid_es3']
10663 assert len(valid_list
) == len(set(valid_list
))
10664 if len(valid_list
) > 0:
10665 f
.write(" static const EnumToString string_table[] = {\n")
10666 for value
in valid_list
:
10667 f
.write(' { %s, "%s" },\n' % (value
, value
))
10669 return GLES2Util::GetQualifiedEnumString(
10670 string_table, arraysize(string_table), value);
10675 f
.write(""" return GLES2Util::GetQualifiedEnumString(
10680 self
.generated_cpp_filenames
.append(filename
)
10682 def WritePepperGLES2Interface(self
, filename
, dev
):
10683 """Writes the Pepper OpenGLES interface definition."""
10684 with
CWriter(filename
) as f
:
10685 f
.write("label Chrome {\n")
10686 f
.write(" M39 = 1.0\n")
10690 # Declare GL types.
10691 f
.write("[version=1.0]\n")
10692 f
.write("describe {\n")
10693 for gltype
in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10694 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10695 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10696 'GLubyte', 'GLuint', 'GLushort']:
10697 f
.write(" %s;\n" % gltype
)
10698 f
.write(" %s_ptr_t;\n" % gltype
)
10701 # C level typedefs.
10702 f
.write("#inline c\n")
10703 f
.write("#include \"ppapi/c/pp_resource.h\"\n")
10705 f
.write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10707 f
.write("\n#ifndef __gl2_h_\n")
10708 for (k
, v
) in _GL_TYPES
.iteritems():
10709 f
.write("typedef %s %s;\n" % (v
, k
))
10710 f
.write("#ifdef _WIN64\n")
10711 for (k
, v
) in _GL_TYPES_64
.iteritems():
10712 f
.write("typedef %s %s;\n" % (v
, k
))
10714 for (k
, v
) in _GL_TYPES_32
.iteritems():
10715 f
.write("typedef %s %s;\n" % (v
, k
))
10716 f
.write("#endif // _WIN64\n")
10717 f
.write("#endif // __gl2_h_\n\n")
10718 f
.write("#endinl\n")
10720 for interface
in self
.pepper_interfaces
:
10721 if interface
.dev
!= dev
:
10723 # Historically, we provide OpenGLES2 interfaces with struct
10724 # namespace. Not to break code which uses the interface as
10725 # "struct OpenGLES2", we put it in struct namespace.
10726 f
.write('\n[macro="%s", force_struct_namespace]\n' %
10727 interface
.GetInterfaceName())
10728 f
.write("interface %s {\n" % interface
.GetStructName())
10729 for func
in self
.original_functions
:
10730 if not func
.InPepperInterface(interface
):
10733 ret_type
= func
.MapCTypeToPepperIdlType(func
.return_type
,
10734 is_for_return_type
=True)
10735 func_prefix
= " %s %s(" % (ret_type
, func
.GetPepperName())
10736 f
.write(func_prefix
)
10737 f
.write("[in] PP_Resource context")
10738 for arg
in func
.MakeTypedPepperIdlArgStrings():
10739 f
.write(",\n" + " " * len(func_prefix
) + arg
)
10743 def WritePepperGLES2Implementation(self
, filename
):
10744 """Writes the Pepper OpenGLES interface implementation."""
10745 with
CWriter(filename
) as f
:
10746 f
.write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10747 f
.write("#include \"base/logging.h\"\n")
10748 f
.write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10749 f
.write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10750 f
.write("#include \"ppapi/thunk/enter.h\"\n\n")
10752 f
.write("namespace ppapi {\n\n")
10753 f
.write("namespace {\n\n")
10755 f
.write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10758 f
.write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10760 f
.write(" DCHECK(enter);\n")
10761 f
.write(" DCHECK(enter->succeeded());\n")
10762 f
.write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10763 "gles2_impl();\n");
10766 for func
in self
.original_functions
:
10767 if not func
.InAnyPepperExtension():
10770 original_arg
= func
.MakeTypedPepperArgString("")
10771 context_arg
= "PP_Resource context_id"
10772 if len(original_arg
):
10773 arg
= context_arg
+ ", " + original_arg
10776 f
.write("%s %s(%s) {\n" %
10777 (func
.return_type
, func
.GetPepperName(), arg
))
10778 f
.write(" Enter3D enter(context_id, true);\n")
10779 f
.write(" if (enter.succeeded()) {\n")
10781 return_str
= "" if func
.return_type
== "void" else "return "
10782 f
.write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10783 (return_str
, func
.original_name
,
10784 func
.MakeOriginalArgString("")))
10786 if func
.return_type
== "void":
10789 f
.write(" else {\n")
10790 f
.write(" return %s;\n" % func
.GetErrorReturnString())
10794 f
.write("} // namespace\n")
10796 for interface
in self
.pepper_interfaces
:
10797 f
.write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10798 (interface
.GetStructName(), interface
.GetName()))
10799 f
.write(" static const struct %s "
10800 "ppb_opengles2 = {\n" % interface
.GetStructName())
10802 f
.write(",\n &".join(
10803 f
.GetPepperName() for f
in self
.original_functions
10804 if f
.InPepperInterface(interface
)))
10808 f
.write(" return &ppb_opengles2;\n")
10811 f
.write("} // namespace ppapi\n")
10812 self
.generated_cpp_filenames
.append(filename
)
10814 def WriteGLES2ToPPAPIBridge(self
, filename
):
10815 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10816 with
CWriter(filename
) as f
:
10817 f
.write("#ifndef GL_GLEXT_PROTOTYPES\n")
10818 f
.write("#define GL_GLEXT_PROTOTYPES\n")
10819 f
.write("#endif\n")
10820 f
.write("#include <GLES2/gl2.h>\n")
10821 f
.write("#include <GLES2/gl2ext.h>\n")
10822 f
.write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10824 for func
in self
.original_functions
:
10825 if not func
.InAnyPepperExtension():
10828 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
10830 f
.write("%s GL_APIENTRY gl%s(%s) {\n" %
10831 (func
.return_type
, func
.GetPepperName(),
10832 func
.MakeTypedPepperArgString("")))
10833 return_str
= "" if func
.return_type
== "void" else "return "
10834 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
10835 original_arg
= func
.MakeOriginalArgString("")
10836 context_arg
= "glGetCurrentContextPPAPI()"
10837 if len(original_arg
):
10838 arg
= context_arg
+ ", " + original_arg
10841 if interface
.GetName():
10842 f
.write(" const struct %s* ext = %s;\n" %
10843 (interface
.GetStructName(), interface_str
))
10844 f
.write(" if (ext)\n")
10845 f
.write(" %sext->%s(%s);\n" %
10846 (return_str
, func
.GetPepperName(), arg
))
10848 f
.write(" %s0;\n" % return_str
)
10850 f
.write(" %s%s->%s(%s);\n" %
10851 (return_str
, interface_str
, func
.GetPepperName(), arg
))
10853 self
.generated_cpp_filenames
.append(filename
)
10855 def WriteMojoGLCallVisitor(self
, filename
):
10856 """Provides the GL implementation for mojo"""
10857 with
CWriter(filename
) as f
:
10858 for func
in self
.original_functions
:
10859 if not func
.IsCoreGLFunction():
10861 f
.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10862 (func
.name
, func
.return_type
,
10863 func
.MakeTypedOriginalArgString(""),
10864 func
.MakeOriginalArgString("")))
10865 self
.generated_cpp_filenames
.append(filename
)
10867 def WriteMojoGLCallVisitorForExtension(self
, filename
, extension
):
10868 """Provides the GL implementation for mojo for a particular extension"""
10869 with
CWriter(filename
) as f
:
10870 for func
in self
.original_functions
:
10871 if func
.GetInfo("extension") != extension
:
10873 f
.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10874 (func
.name
, func
.return_type
,
10875 func
.MakeTypedOriginalArgString(""),
10876 func
.MakeOriginalArgString("")))
10877 self
.generated_cpp_filenames
.append(filename
)
10879 def Format(generated_files
):
10880 formatter
= "clang-format"
10881 if platform
.system() == "Windows":
10882 formatter
+= ".bat"
10883 for filename
in generated_files
:
10884 call([formatter
, "-i", "-style=chromium", filename
])
10887 """This is the main function."""
10888 parser
= OptionParser()
10891 help="base directory for resulting files, under chrome/src. default is "
10892 "empty. Use this if you want the result stored under gen.")
10894 "-v", "--verbose", action
="store_true",
10895 help="prints more output.")
10897 (options
, args
) = parser
.parse_args(args
=argv
)
10899 # Add in states and capabilites to GLState
10900 gl_state_valid
= _NAMED_TYPE_INFO
['GLState']['valid']
10901 for state_name
in sorted(_STATES
.keys()):
10902 state
= _STATES
[state_name
]
10903 if 'extension_flag' in state
:
10905 if 'enum' in state
:
10906 if not state
['enum'] in gl_state_valid
:
10907 gl_state_valid
.append(state
['enum'])
10909 for item
in state
['states']:
10910 if 'extension_flag' in item
:
10912 if not item
['enum'] in gl_state_valid
:
10913 gl_state_valid
.append(item
['enum'])
10914 for capability
in _CAPABILITY_FLAGS
:
10915 valid_value
= "GL_%s" % capability
['name'].upper()
10916 if not valid_value
in gl_state_valid
:
10917 gl_state_valid
.append(valid_value
)
10919 # This script lives under gpu/command_buffer, cd to base directory.
10920 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
10921 base_dir
= os
.getcwd()
10922 gen
= GLGenerator(options
.verbose
)
10923 gen
.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10925 # Support generating files under gen/
10926 if options
.output_dir
!= None:
10927 os
.chdir(options
.output_dir
)
10929 gen
.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10930 gen
.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10931 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10932 gen
.WritePepperGLES2Implementation(
10933 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10935 gen
.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10936 gen
.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10937 gen
.WriteFormatTest(
10938 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10939 gen
.WriteGLES2InterfaceHeader(
10940 "gpu/command_buffer/client/gles2_interface_autogen.h")
10941 gen
.WriteMojoGLES2ImplHeader(
10942 "mojo/gpu/mojo_gles2_impl_autogen.h")
10943 gen
.WriteMojoGLES2Impl(
10944 "mojo/gpu/mojo_gles2_impl_autogen.cc")
10945 gen
.WriteGLES2InterfaceStub(
10946 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10947 gen
.WriteGLES2InterfaceStubImpl(
10948 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10949 gen
.WriteGLES2ImplementationHeader(
10950 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10951 gen
.WriteGLES2Implementation(
10952 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10953 gen
.WriteGLES2ImplementationUnitTests(
10954 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10955 gen
.WriteGLES2TraceImplementationHeader(
10956 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10957 gen
.WriteGLES2TraceImplementation(
10958 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10959 gen
.WriteGLES2CLibImplementation(
10960 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10961 gen
.WriteCmdHelperHeader(
10962 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
10963 gen
.WriteServiceImplementation(
10964 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
10965 gen
.WriteServiceContextStateHeader(
10966 "gpu/command_buffer/service/context_state_autogen.h")
10967 gen
.WriteServiceContextStateImpl(
10968 "gpu/command_buffer/service/context_state_impl_autogen.h")
10969 gen
.WriteClientContextStateHeader(
10970 "gpu/command_buffer/client/client_context_state_autogen.h")
10971 gen
.WriteClientContextStateImpl(
10972 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
10973 gen
.WriteServiceUnitTests(
10974 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
10975 gen
.WriteServiceUnitTestsForExtensions(
10976 "gpu/command_buffer/service/"
10977 "gles2_cmd_decoder_unittest_extensions_autogen.h")
10978 gen
.WriteServiceUtilsHeader(
10979 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
10980 gen
.WriteServiceUtilsImplementation(
10981 "gpu/command_buffer/service/"
10982 "gles2_cmd_validation_implementation_autogen.h")
10983 gen
.WriteCommonUtilsHeader(
10984 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
10985 gen
.WriteCommonUtilsImpl(
10986 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
10987 gen
.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
10988 mojo_gles2_prefix
= ("third_party/mojo/src/mojo/public/c/gles2/"
10989 "gles2_call_visitor")
10990 gen
.WriteMojoGLCallVisitor(mojo_gles2_prefix
+ "_autogen.h")
10991 gen
.WriteMojoGLCallVisitorForExtension(
10992 mojo_gles2_prefix
+ "_chromium_texture_mailbox_autogen.h",
10993 "CHROMIUM_texture_mailbox")
10994 gen
.WriteMojoGLCallVisitorForExtension(
10995 mojo_gles2_prefix
+ "_chromium_sync_point_autogen.h",
10996 "CHROMIUM_sync_point")
10997 gen
.WriteMojoGLCallVisitorForExtension(
10998 mojo_gles2_prefix
+ "_chromium_sub_image_autogen.h",
10999 "CHROMIUM_sub_image")
11000 gen
.WriteMojoGLCallVisitorForExtension(
11001 mojo_gles2_prefix
+ "_chromium_miscellaneous_autogen.h",
11002 "CHROMIUM_miscellaneous")
11003 gen
.WriteMojoGLCallVisitorForExtension(
11004 mojo_gles2_prefix
+ "_occlusion_query_ext_autogen.h",
11005 "occlusion_query_EXT")
11006 gen
.WriteMojoGLCallVisitorForExtension(
11007 mojo_gles2_prefix
+ "_chromium_image_autogen.h",
11009 gen
.WriteMojoGLCallVisitorForExtension(
11010 mojo_gles2_prefix
+ "_chromium_copy_texture_autogen.h",
11011 "CHROMIUM_copy_texture")
11012 gen
.WriteMojoGLCallVisitorForExtension(
11013 mojo_gles2_prefix
+ "_chromium_pixel_transfer_buffer_object_autogen.h",
11014 "CHROMIUM_pixel_transfer_buffer_object")
11016 Format(gen
.generated_cpp_filenames
)
11019 print "%d errors" % gen
.errors
11024 if __name__
== '__main__':
11025 sys
.exit(main(sys
.argv
[1:]))