2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """code generator for GLES2 command buffers."""
14 from optparse
import OptionParser
15 from subprocess
import call
18 _SIZE_OF_COMMAND_HEADER
= 4
19 _FIRST_SPECIFIC_COMMAND_ID
= 256
21 _LICENSE
= """// Copyright 2014 The Chromium Authors. All rights reserved.
22 // Use of this source code is governed by a BSD-style license that can be
23 // found in the LICENSE file.
27 _DO_NOT_EDIT_WARNING
= """// This file is auto-generated from
28 // gpu/command_buffer/build_gles2_cmd_buffer.py
29 // It's formatted by clang-format using chromium coding style:
30 // clang-format -i -style=chromium filename
35 # This string is copied directly out of the gl2.h file from GLES2.0
39 # *) Any argument that is a resourceID has been changed to GLid<Type>.
40 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
41 # If it's allowed to not exist it's GLidBind<Type>
43 # *) All GLenums have been changed to GLenumTypeOfEnum
46 'GLenum': 'unsigned int',
47 'GLboolean': 'unsigned char',
48 'GLbitfield': 'unsigned int',
49 'GLbyte': 'signed char',
53 'GLubyte': 'unsigned char',
54 'GLushort': 'unsigned short',
55 'GLuint': 'unsigned int',
64 'GLintptr': 'long int',
65 'GLsizeiptr': 'long int'
69 'GLintptr': 'long long int',
70 'GLsizeiptr': 'long long int'
73 # Capabilites selected with glEnable
76 {'name': 'cull_face'},
77 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
78 {'name': 'dither', 'default': True},
79 {'name': 'polygon_offset_fill'},
80 {'name': 'sample_alpha_to_coverage'},
81 {'name': 'sample_coverage'},
82 {'name': 'scissor_test'},
83 {'name': 'stencil_test',
84 'state_flag': 'framebuffer_state_.clear_state_dirty'},
85 {'name': 'rasterizer_discard', 'es3': True},
86 {'name': 'primitive_restart_fixed_index', 'es3': True},
93 'enum': 'GL_COLOR_CLEAR_VALUE',
95 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
97 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
98 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
103 'func': 'ClearDepth',
104 'enum': 'GL_DEPTH_CLEAR_VALUE',
106 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
112 'enum': 'GL_COLOR_WRITEMASK',
115 'name': 'color_mask_red',
121 'name': 'color_mask_green',
127 'name': 'color_mask_blue',
133 'name': 'color_mask_alpha',
139 'state_flag': 'framebuffer_state_.clear_state_dirty',
143 'func': 'ClearStencil',
144 'enum': 'GL_STENCIL_CLEAR_VALUE',
146 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
151 'func': 'BlendColor',
152 'enum': 'GL_BLEND_COLOR',
154 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
155 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
156 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
157 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
162 'func': 'BlendEquationSeparate',
165 'name': 'blend_equation_rgb',
167 'enum': 'GL_BLEND_EQUATION_RGB',
168 'default': 'GL_FUNC_ADD',
171 'name': 'blend_equation_alpha',
173 'enum': 'GL_BLEND_EQUATION_ALPHA',
174 'default': 'GL_FUNC_ADD',
180 'func': 'BlendFuncSeparate',
183 'name': 'blend_source_rgb',
185 'enum': 'GL_BLEND_SRC_RGB',
189 'name': 'blend_dest_rgb',
191 'enum': 'GL_BLEND_DST_RGB',
192 'default': 'GL_ZERO',
195 'name': 'blend_source_alpha',
197 'enum': 'GL_BLEND_SRC_ALPHA',
201 'name': 'blend_dest_alpha',
203 'enum': 'GL_BLEND_DST_ALPHA',
204 'default': 'GL_ZERO',
210 'func': 'PolygonOffset',
213 'name': 'polygon_offset_factor',
215 'enum': 'GL_POLYGON_OFFSET_FACTOR',
219 'name': 'polygon_offset_units',
221 'enum': 'GL_POLYGON_OFFSET_UNITS',
229 'enum': 'GL_CULL_FACE_MODE',
234 'default': 'GL_BACK',
241 'enum': 'GL_FRONT_FACE',
242 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
247 'enum': 'GL_DEPTH_FUNC',
248 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
252 'func': 'DepthRange',
253 'enum': 'GL_DEPTH_RANGE',
255 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
256 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
261 'func': 'SampleCoverage',
264 'name': 'sample_coverage_value',
266 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
270 'name': 'sample_coverage_invert',
272 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
279 'func': 'StencilMaskSeparate',
280 'state_flag': 'framebuffer_state_.clear_state_dirty',
283 'name': 'stencil_front_writemask',
285 'enum': 'GL_STENCIL_WRITEMASK',
286 'default': '0xFFFFFFFFU',
290 'name': 'stencil_back_writemask',
292 'enum': 'GL_STENCIL_BACK_WRITEMASK',
293 'default': '0xFFFFFFFFU',
300 'func': 'StencilOpSeparate',
303 'name': 'stencil_front_fail_op',
305 'enum': 'GL_STENCIL_FAIL',
306 'default': 'GL_KEEP',
309 'name': 'stencil_front_z_fail_op',
311 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
312 'default': 'GL_KEEP',
315 'name': 'stencil_front_z_pass_op',
317 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
318 'default': 'GL_KEEP',
321 'name': 'stencil_back_fail_op',
323 'enum': 'GL_STENCIL_BACK_FAIL',
324 'default': 'GL_KEEP',
327 'name': 'stencil_back_z_fail_op',
329 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
330 'default': 'GL_KEEP',
333 'name': 'stencil_back_z_pass_op',
335 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
336 'default': 'GL_KEEP',
342 'func': 'StencilFuncSeparate',
345 'name': 'stencil_front_func',
347 'enum': 'GL_STENCIL_FUNC',
348 'default': 'GL_ALWAYS',
351 'name': 'stencil_front_ref',
353 'enum': 'GL_STENCIL_REF',
357 'name': 'stencil_front_mask',
359 'enum': 'GL_STENCIL_VALUE_MASK',
360 'default': '0xFFFFFFFFU',
363 'name': 'stencil_back_func',
365 'enum': 'GL_STENCIL_BACK_FUNC',
366 'default': 'GL_ALWAYS',
369 'name': 'stencil_back_ref',
371 'enum': 'GL_STENCIL_BACK_REF',
375 'name': 'stencil_back_mask',
377 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
378 'default': '0xFFFFFFFFU',
383 'type': 'NamedParameter',
387 'name': 'hint_generate_mipmap',
389 'enum': 'GL_GENERATE_MIPMAP_HINT',
390 'default': 'GL_DONT_CARE',
391 'gl_version_flag': '!is_desktop_core_profile'
394 'name': 'hint_fragment_shader_derivative',
396 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
397 'default': 'GL_DONT_CARE',
398 'extension_flag': 'oes_standard_derivatives'
403 'type': 'NamedParameter',
404 'func': 'PixelStorei',
407 'name': 'pack_alignment',
409 'enum': 'GL_PACK_ALIGNMENT',
413 'name': 'unpack_alignment',
415 'enum': 'GL_UNPACK_ALIGNMENT',
420 # TODO: Consider implemenenting these states
425 'enum': 'GL_LINE_WIDTH',
428 'name': 'line_width',
431 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
438 'enum': 'GL_DEPTH_WRITEMASK',
441 'name': 'depth_mask',
447 'state_flag': 'framebuffer_state_.clear_state_dirty',
452 'enum': 'GL_SCISSOR_BOX',
454 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
459 'expected': 'kViewportX',
465 'expected': 'kViewportY',
468 'name': 'scissor_width',
471 'expected': 'kViewportWidth',
474 'name': 'scissor_height',
477 'expected': 'kViewportHeight',
484 'enum': 'GL_VIEWPORT',
486 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
488 'name': 'viewport_x',
491 'expected': 'kViewportX',
494 'name': 'viewport_y',
497 'expected': 'kViewportY',
500 'name': 'viewport_width',
503 'expected': 'kViewportWidth',
506 'name': 'viewport_height',
509 'expected': 'kViewportHeight',
513 'MatrixValuesCHROMIUM': {
514 'type': 'NamedParameter',
515 'func': 'MatrixLoadfEXT',
517 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
518 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
519 'name': 'modelview_matrix',
522 '1.0f', '0.0f','0.0f','0.0f',
523 '0.0f', '1.0f','0.0f','0.0f',
524 '0.0f', '0.0f','1.0f','0.0f',
525 '0.0f', '0.0f','0.0f','1.0f',
527 'extension_flag': 'chromium_path_rendering',
529 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
530 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
531 'name': 'projection_matrix',
534 '1.0f', '0.0f','0.0f','0.0f',
535 '0.0f', '1.0f','0.0f','0.0f',
536 '0.0f', '0.0f','1.0f','0.0f',
537 '0.0f', '0.0f','0.0f','1.0f',
539 'extension_flag': 'chromium_path_rendering',
543 'PathStencilFuncCHROMIUM': {
545 'func': 'PathStencilFuncNV',
546 'extension_flag': 'chromium_path_rendering',
549 'name': 'stencil_path_func',
551 'enum': 'GL_PATH_STENCIL_FUNC_CHROMIUM',
552 'default': 'GL_ALWAYS',
555 'name': 'stencil_path_ref',
557 'enum': 'GL_PATH_STENCIL_REF_CHROMIUM',
561 'name': 'stencil_path_mask',
563 'enum': 'GL_PATH_STENCIL_VALUE_MASK_CHROMIUM',
564 'default': '0xFFFFFFFFU',
570 # Named type info object represents a named type that is used in OpenGL call
571 # arguments. Each named type defines a set of valid OpenGL call arguments. The
572 # named types are used in 'cmd_buffer_functions.txt'.
573 # type: The actual GL type of the named type.
574 # valid: The list of values that are valid for both the client and the service.
575 # valid_es3: The list of values that are valid in OpenGL ES 3, but not ES 2.
576 # invalid: Examples of invalid values for the type. At least these values
577 # should be tested to be invalid.
578 # deprecated_es3: The list of values that are valid in OpenGL ES 2, but
579 # deprecated in ES 3.
580 # is_complete: The list of valid values of type are final and will not be
581 # modified during runtime.
590 'GL_LINEAR_MIPMAP_LINEAR',
593 'FrameBufferTarget': {
599 'GL_DRAW_FRAMEBUFFER' ,
600 'GL_READ_FRAMEBUFFER' ,
606 'InvalidateFrameBufferTarget': {
612 'GL_DRAW_FRAMEBUFFER' ,
613 'GL_READ_FRAMEBUFFER' ,
616 'RenderBufferTarget': {
629 'GL_ELEMENT_ARRAY_BUFFER',
632 'GL_COPY_READ_BUFFER',
633 'GL_COPY_WRITE_BUFFER',
634 'GL_PIXEL_PACK_BUFFER',
635 'GL_PIXEL_UNPACK_BUFFER',
636 'GL_TRANSFORM_FEEDBACK_BUFFER',
643 'IndexedBufferTarget': {
646 'GL_TRANSFORM_FEEDBACK_BUFFER',
658 'GL_MAP_INVALIDATE_RANGE_BIT',
659 'GL_MAP_INVALIDATE_BUFFER_BIT',
660 'GL_MAP_FLUSH_EXPLICIT_BIT',
661 'GL_MAP_UNSYNCHRONIZED_BIT',
664 'GL_SYNC_FLUSH_COMMANDS_BIT',
724 'CompressedTextureFormat': {
729 'GL_COMPRESSED_R11_EAC',
730 'GL_COMPRESSED_SIGNED_R11_EAC',
731 'GL_COMPRESSED_RG11_EAC',
732 'GL_COMPRESSED_SIGNED_RG11_EAC',
733 'GL_COMPRESSED_RGB8_ETC2',
734 'GL_COMPRESSED_SRGB8_ETC2',
735 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
736 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
737 'GL_COMPRESSED_RGBA8_ETC2_EAC',
738 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
744 # NOTE: State an Capability entries added later.
746 'GL_ALIASED_LINE_WIDTH_RANGE',
747 'GL_ALIASED_POINT_SIZE_RANGE',
749 'GL_ARRAY_BUFFER_BINDING',
751 'GL_COMPRESSED_TEXTURE_FORMATS',
752 'GL_CURRENT_PROGRAM',
755 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
756 'GL_FRAMEBUFFER_BINDING',
757 'GL_GENERATE_MIPMAP_HINT',
759 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
760 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
761 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
762 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
763 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
764 'GL_MAX_RENDERBUFFER_SIZE',
765 'GL_MAX_TEXTURE_IMAGE_UNITS',
766 'GL_MAX_TEXTURE_SIZE',
767 'GL_MAX_VARYING_VECTORS',
768 'GL_MAX_VERTEX_ATTRIBS',
769 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
770 'GL_MAX_VERTEX_UNIFORM_VECTORS',
771 'GL_MAX_VIEWPORT_DIMS',
772 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
773 'GL_NUM_SHADER_BINARY_FORMATS',
776 'GL_RENDERBUFFER_BINDING',
778 'GL_SAMPLE_COVERAGE_INVERT',
779 'GL_SAMPLE_COVERAGE_VALUE',
782 'GL_SHADER_BINARY_FORMATS',
783 'GL_SHADER_COMPILER',
786 'GL_TEXTURE_BINDING_2D',
787 'GL_TEXTURE_BINDING_CUBE_MAP',
788 'GL_UNPACK_ALIGNMENT',
789 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
790 # we can add this because we emulate it if the driver does not support it.
791 'GL_VERTEX_ARRAY_BINDING_OES',
795 'GL_COPY_READ_BUFFER_BINDING',
796 'GL_COPY_WRITE_BUFFER_BINDING',
813 'GL_DRAW_FRAMEBUFFER_BINDING',
814 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
815 'GL_GPU_DISJOINT_EXT',
817 'GL_MAX_3D_TEXTURE_SIZE',
818 'GL_MAX_ARRAY_TEXTURE_LAYERS',
819 'GL_MAX_COLOR_ATTACHMENTS',
820 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
821 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
822 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
823 'GL_MAX_DRAW_BUFFERS',
824 'GL_MAX_ELEMENT_INDEX',
825 'GL_MAX_ELEMENTS_INDICES',
826 'GL_MAX_ELEMENTS_VERTICES',
827 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
828 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
829 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
830 'GL_MAX_PROGRAM_TEXEL_OFFSET',
832 'GL_MAX_SERVER_WAIT_TIMEOUT',
833 'GL_MAX_TEXTURE_LOD_BIAS',
834 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
835 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
836 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
837 'GL_MAX_UNIFORM_BLOCK_SIZE',
838 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
839 'GL_MAX_VARYING_COMPONENTS',
840 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
841 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
842 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
843 'GL_MIN_PROGRAM_TEXEL_OFFSET',
846 'GL_NUM_PROGRAM_BINARY_FORMATS',
847 'GL_PACK_ROW_LENGTH',
848 'GL_PACK_SKIP_PIXELS',
850 'GL_PIXEL_PACK_BUFFER_BINDING',
851 'GL_PIXEL_UNPACK_BUFFER_BINDING',
852 'GL_PROGRAM_BINARY_FORMATS',
854 'GL_READ_FRAMEBUFFER_BINDING',
855 'GL_SAMPLER_BINDING',
857 'GL_TEXTURE_BINDING_2D_ARRAY',
858 'GL_TEXTURE_BINDING_3D',
859 'GL_TRANSFORM_FEEDBACK_BINDING',
860 'GL_TRANSFORM_FEEDBACK_ACTIVE',
861 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
862 'GL_TRANSFORM_FEEDBACK_PAUSED',
863 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
864 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
865 'GL_UNIFORM_BUFFER_BINDING',
866 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
867 'GL_UNIFORM_BUFFER_SIZE',
868 'GL_UNIFORM_BUFFER_START',
869 'GL_UNPACK_IMAGE_HEIGHT',
870 'GL_UNPACK_ROW_LENGTH',
871 'GL_UNPACK_SKIP_IMAGES',
872 'GL_UNPACK_SKIP_PIXELS',
873 'GL_UNPACK_SKIP_ROWS',
874 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
875 # 'GL_VERTEX_ARRAY_BINDING',
884 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
885 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
886 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
887 'GL_UNIFORM_BUFFER_BINDING',
888 'GL_UNIFORM_BUFFER_SIZE',
889 'GL_UNIFORM_BUFFER_START',
895 'GetTexParamTarget': {
899 'GL_TEXTURE_CUBE_MAP',
902 'GL_TEXTURE_2D_ARRAY',
906 'GL_PROXY_TEXTURE_CUBE_MAP',
914 'GL_COLOR_ATTACHMENT0',
915 'GL_COLOR_ATTACHMENT1',
916 'GL_COLOR_ATTACHMENT2',
917 'GL_COLOR_ATTACHMENT3',
918 'GL_COLOR_ATTACHMENT4',
919 'GL_COLOR_ATTACHMENT5',
920 'GL_COLOR_ATTACHMENT6',
921 'GL_COLOR_ATTACHMENT7',
922 'GL_COLOR_ATTACHMENT8',
923 'GL_COLOR_ATTACHMENT9',
924 'GL_COLOR_ATTACHMENT10',
925 'GL_COLOR_ATTACHMENT11',
926 'GL_COLOR_ATTACHMENT12',
927 'GL_COLOR_ATTACHMENT13',
928 'GL_COLOR_ATTACHMENT14',
929 'GL_COLOR_ATTACHMENT15',
939 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
940 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
941 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
942 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
943 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
944 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
947 'GL_PROXY_TEXTURE_CUBE_MAP',
954 'GL_TEXTURE_2D_ARRAY',
960 'TextureBindTarget': {
964 'GL_TEXTURE_CUBE_MAP',
968 'GL_TEXTURE_2D_ARRAY',
975 'TransformFeedbackBindTarget': {
978 'GL_TRANSFORM_FEEDBACK',
984 'TransformFeedbackPrimitiveMode': {
999 'GL_FRAGMENT_SHADER',
1002 'GL_GEOMETRY_SHADER',
1010 'GL_FRONT_AND_BACK',
1038 'GL_FUNC_REVERSE_SUBTRACT',
1054 'GL_ONE_MINUS_SRC_COLOR',
1056 'GL_ONE_MINUS_DST_COLOR',
1058 'GL_ONE_MINUS_SRC_ALPHA',
1060 'GL_ONE_MINUS_DST_ALPHA',
1061 'GL_CONSTANT_COLOR',
1062 'GL_ONE_MINUS_CONSTANT_COLOR',
1063 'GL_CONSTANT_ALPHA',
1064 'GL_ONE_MINUS_CONSTANT_ALPHA',
1065 'GL_SRC_ALPHA_SATURATE',
1074 'GL_ONE_MINUS_SRC_COLOR',
1076 'GL_ONE_MINUS_DST_COLOR',
1078 'GL_ONE_MINUS_SRC_ALPHA',
1080 'GL_ONE_MINUS_DST_ALPHA',
1081 'GL_CONSTANT_COLOR',
1082 'GL_ONE_MINUS_CONSTANT_COLOR',
1083 'GL_CONSTANT_ALPHA',
1084 'GL_ONE_MINUS_CONSTANT_ALPHA',
1089 'valid': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1090 if 'es3' not in cap
or cap
['es3'] != True],
1091 'valid_es3': ["GL_%s" % cap
['name'].upper() for cap
in _CAPABILITY_FLAGS
1092 if 'es3' in cap
and cap
['es3'] == True],
1105 'GL_TRIANGLE_STRIP',
1118 'GL_UNSIGNED_SHORT',
1127 'GetMaxIndexType': {
1131 'GL_UNSIGNED_SHORT',
1141 'GL_COLOR_ATTACHMENT0',
1142 'GL_DEPTH_ATTACHMENT',
1143 'GL_STENCIL_ATTACHMENT',
1146 'GL_DEPTH_STENCIL_ATTACHMENT',
1149 'BackbufferAttachment': {
1157 'BufferParameter': {
1164 'GL_BUFFER_ACCESS_FLAGS',
1168 'GL_PIXEL_PACK_BUFFER',
1171 'BufferParameter64': {
1175 'GL_BUFFER_MAP_LENGTH',
1176 'GL_BUFFER_MAP_OFFSET',
1179 'GL_PIXEL_PACK_BUFFER',
1185 'GL_INTERLEAVED_ATTRIBS',
1186 'GL_SEPARATE_ATTRIBS',
1189 'GL_PIXEL_PACK_BUFFER',
1192 'FrameBufferParameter': {
1195 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1196 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1197 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1198 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1201 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1202 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1203 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1204 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1205 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1206 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1207 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1208 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1209 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1215 'GL_PATH_PROJECTION_CHROMIUM',
1216 'GL_PATH_MODELVIEW_CHROMIUM',
1219 'ProgramParameter': {
1224 'GL_VALIDATE_STATUS',
1225 'GL_INFO_LOG_LENGTH',
1226 'GL_ATTACHED_SHADERS',
1227 'GL_ACTIVE_ATTRIBUTES',
1228 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1229 'GL_ACTIVE_UNIFORMS',
1230 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1233 'GL_ACTIVE_UNIFORM_BLOCKS',
1234 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1235 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1236 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1237 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1240 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1243 'QueryObjectParameter': {
1246 'GL_QUERY_RESULT_EXT',
1247 'GL_QUERY_RESULT_AVAILABLE_EXT',
1253 'GL_CURRENT_QUERY_EXT',
1259 'GL_ANY_SAMPLES_PASSED_EXT',
1260 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1261 'GL_COMMANDS_ISSUED_CHROMIUM',
1262 'GL_LATENCY_QUERY_CHROMIUM',
1263 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1264 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1265 'GL_COMMANDS_COMPLETED_CHROMIUM',
1268 'RenderBufferParameter': {
1271 'GL_RENDERBUFFER_RED_SIZE',
1272 'GL_RENDERBUFFER_GREEN_SIZE',
1273 'GL_RENDERBUFFER_BLUE_SIZE',
1274 'GL_RENDERBUFFER_ALPHA_SIZE',
1275 'GL_RENDERBUFFER_DEPTH_SIZE',
1276 'GL_RENDERBUFFER_STENCIL_SIZE',
1277 'GL_RENDERBUFFER_WIDTH',
1278 'GL_RENDERBUFFER_HEIGHT',
1279 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1282 'GL_RENDERBUFFER_SAMPLES',
1285 'InternalFormatParameter': {
1288 'GL_NUM_SAMPLE_COUNTS',
1292 'SamplerParameter': {
1295 'GL_TEXTURE_MAG_FILTER',
1296 'GL_TEXTURE_MIN_FILTER',
1297 'GL_TEXTURE_MIN_LOD',
1298 'GL_TEXTURE_MAX_LOD',
1299 'GL_TEXTURE_WRAP_S',
1300 'GL_TEXTURE_WRAP_T',
1301 'GL_TEXTURE_WRAP_R',
1302 'GL_TEXTURE_COMPARE_MODE',
1303 'GL_TEXTURE_COMPARE_FUNC',
1306 'GL_GENERATE_MIPMAP',
1309 'ShaderParameter': {
1314 'GL_COMPILE_STATUS',
1315 'GL_INFO_LOG_LENGTH',
1316 'GL_SHADER_SOURCE_LENGTH',
1317 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1320 'ShaderPrecision': {
1337 'GL_SHADING_LANGUAGE_VERSION',
1341 'TextureParameter': {
1344 'GL_TEXTURE_MAG_FILTER',
1345 'GL_TEXTURE_MIN_FILTER',
1346 'GL_TEXTURE_POOL_CHROMIUM',
1347 'GL_TEXTURE_WRAP_S',
1348 'GL_TEXTURE_WRAP_T',
1351 'GL_TEXTURE_BASE_LEVEL',
1352 'GL_TEXTURE_COMPARE_FUNC',
1353 'GL_TEXTURE_COMPARE_MODE',
1354 'GL_TEXTURE_IMMUTABLE_FORMAT',
1355 'GL_TEXTURE_IMMUTABLE_LEVELS',
1356 'GL_TEXTURE_MAX_LEVEL',
1357 'GL_TEXTURE_MAX_LOD',
1358 'GL_TEXTURE_MIN_LOD',
1359 'GL_TEXTURE_WRAP_R',
1362 'GL_GENERATE_MIPMAP',
1368 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1369 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1372 'TextureWrapMode': {
1376 'GL_MIRRORED_REPEAT',
1380 'TextureMinFilterMode': {
1385 'GL_NEAREST_MIPMAP_NEAREST',
1386 'GL_LINEAR_MIPMAP_NEAREST',
1387 'GL_NEAREST_MIPMAP_LINEAR',
1388 'GL_LINEAR_MIPMAP_LINEAR',
1391 'TextureMagFilterMode': {
1398 'TextureCompareFunc': {
1411 'TextureCompareMode': {
1415 'GL_COMPARE_REF_TO_TEXTURE',
1422 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1425 'VertexAttribute': {
1428 # some enum that the decoder actually passes through to GL needs
1429 # to be the first listed here since it's used in unit tests.
1430 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1431 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1432 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1433 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1434 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1435 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1436 'GL_CURRENT_VERTEX_ATTRIB',
1439 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1440 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1446 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1452 'GL_GENERATE_MIPMAP_HINT',
1455 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1458 'GL_PERSPECTIVE_CORRECTION_HINT',
1472 'GL_PACK_ALIGNMENT',
1473 'GL_UNPACK_ALIGNMENT',
1476 'GL_PACK_ROW_LENGTH',
1477 'GL_PACK_SKIP_PIXELS',
1478 'GL_PACK_SKIP_ROWS',
1479 'GL_UNPACK_ROW_LENGTH',
1480 'GL_UNPACK_IMAGE_HEIGHT',
1481 'GL_UNPACK_SKIP_PIXELS',
1482 'GL_UNPACK_SKIP_ROWS',
1483 'GL_UNPACK_SKIP_IMAGES',
1486 'GL_PACK_SWAP_BYTES',
1487 'GL_UNPACK_SWAP_BYTES',
1490 'PixelStoreAlignment': {
1503 'ReadPixelFormat': {
1522 'GL_UNSIGNED_SHORT_5_6_5',
1523 'GL_UNSIGNED_SHORT_4_4_4_4',
1524 'GL_UNSIGNED_SHORT_5_5_5_1',
1528 'GL_UNSIGNED_SHORT',
1534 'GL_UNSIGNED_INT_2_10_10_10_REV',
1535 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1536 'GL_UNSIGNED_INT_5_9_9_9_REV',
1537 'GL_UNSIGNED_INT_24_8',
1538 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1541 'GL_UNSIGNED_BYTE_3_3_2',
1550 'GL_UNSIGNED_SHORT',
1557 'GL_CONVEX_HULL_CHROMIUM',
1558 'GL_BOUNDING_BOX_CHROMIUM',
1565 'GL_COUNT_UP_CHROMIUM',
1566 'GL_COUNT_DOWN_CHROMIUM',
1572 'GL_PATH_STROKE_WIDTH_CHROMIUM',
1573 'GL_PATH_END_CAPS_CHROMIUM',
1574 'GL_PATH_JOIN_STYLE_CHROMIUM',
1575 'GL_PATH_MITER_LIMIT_CHROMIUM',
1576 'GL_PATH_STROKE_BOUND_CHROMIUM',
1579 'PathParameterCapValues': {
1583 'GL_SQUARE_CHROMIUM',
1584 'GL_ROUND_CHROMIUM',
1587 'PathParameterJoinValues': {
1590 'GL_MITER_REVERT_CHROMIUM',
1591 'GL_BEVEL_CHROMIUM',
1592 'GL_ROUND_CHROMIUM',
1599 'GL_UNSIGNED_SHORT_5_6_5',
1600 'GL_UNSIGNED_SHORT_4_4_4_4',
1601 'GL_UNSIGNED_SHORT_5_5_5_1',
1610 'GL_UNSIGNED_INT_2_10_10_10_REV',
1613 'GL_UNSIGNED_SHORT_5_6_5',
1614 'GL_UNSIGNED_SHORT_4_4_4_4',
1615 'GL_UNSIGNED_SHORT_5_5_5_1',
1618 'RenderBufferFormat': {
1624 'GL_DEPTH_COMPONENT16',
1625 'GL_STENCIL_INDEX8',
1653 'GL_DEPTH_COMPONENT24',
1654 'GL_DEPTH_COMPONENT32F',
1655 'GL_DEPTH24_STENCIL8',
1656 'GL_DEPTH32F_STENCIL8',
1659 'ShaderBinaryFormat': {
1682 'GL_LUMINANCE_ALPHA',
1693 'GL_DEPTH_COMPONENT',
1701 'TextureInternalFormat': {
1706 'GL_LUMINANCE_ALPHA',
1735 'GL_R11F_G11F_B10F',
1760 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1761 # We will reject them dynamically in GPU command buffer.
1762 'GL_DEPTH_COMPONENT16',
1763 'GL_DEPTH_COMPONENT24',
1764 'GL_DEPTH_COMPONENT32F',
1765 'GL_DEPTH24_STENCIL8',
1766 'GL_DEPTH32F_STENCIL8',
1773 'TextureInternalFormatStorage': {
1780 'GL_LUMINANCE8_EXT',
1781 'GL_LUMINANCE8_ALPHA8_EXT',
1809 'GL_R11F_G11F_B10F',
1832 'GL_DEPTH_COMPONENT16',
1833 'GL_DEPTH_COMPONENT24',
1834 'GL_DEPTH_COMPONENT32F',
1835 'GL_DEPTH24_STENCIL8',
1836 'GL_DEPTH32F_STENCIL8',
1837 'GL_COMPRESSED_R11_EAC',
1838 'GL_COMPRESSED_SIGNED_R11_EAC',
1839 'GL_COMPRESSED_RG11_EAC',
1840 'GL_COMPRESSED_SIGNED_RG11_EAC',
1841 'GL_COMPRESSED_RGB8_ETC2',
1842 'GL_COMPRESSED_SRGB8_ETC2',
1843 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1844 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1845 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1846 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1850 'GL_LUMINANCE8_EXT',
1851 'GL_LUMINANCE8_ALPHA8_EXT',
1853 'GL_LUMINANCE16F_EXT',
1854 'GL_LUMINANCE_ALPHA16F_EXT',
1856 'GL_LUMINANCE32F_EXT',
1857 'GL_LUMINANCE_ALPHA32F_EXT',
1860 'ImageInternalFormat': {
1864 'GL_RGB_YUV_420_CHROMIUM',
1872 'GL_SCANOUT_CHROMIUM'
1875 'ValueBufferTarget': {
1878 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1881 'SubscriptionTarget': {
1884 'GL_MOUSE_POSITION_CHROMIUM',
1887 'UniformParameter': {
1892 'GL_UNIFORM_NAME_LENGTH',
1893 'GL_UNIFORM_BLOCK_INDEX',
1894 'GL_UNIFORM_OFFSET',
1895 'GL_UNIFORM_ARRAY_STRIDE',
1896 'GL_UNIFORM_MATRIX_STRIDE',
1897 'GL_UNIFORM_IS_ROW_MAJOR',
1900 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1903 'UniformBlockParameter': {
1906 'GL_UNIFORM_BLOCK_BINDING',
1907 'GL_UNIFORM_BLOCK_DATA_SIZE',
1908 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1909 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1910 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1911 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1912 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1918 'VertexAttribType': {
1924 'GL_UNSIGNED_SHORT',
1925 # 'GL_FIXED', // This is not available on Desktop GL.
1932 'GL_INT_2_10_10_10_REV',
1933 'GL_UNSIGNED_INT_2_10_10_10_REV',
1939 'VertexAttribIType': {
1945 'GL_UNSIGNED_SHORT',
1956 'is_complete': True,
1964 'VertexAttribSize': {
1979 'is_complete': True,
1988 'type': 'GLboolean',
1989 'is_complete': True,
2000 'GL_GUILTY_CONTEXT_RESET_ARB',
2001 'GL_INNOCENT_CONTEXT_RESET_ARB',
2002 'GL_UNKNOWN_CONTEXT_RESET_ARB',
2007 'is_complete': True,
2009 'GL_SYNC_GPU_COMMANDS_COMPLETE',
2016 'type': 'GLbitfield',
2017 'is_complete': True,
2026 'type': 'GLbitfield',
2028 'GL_SYNC_FLUSH_COMMANDS_BIT',
2038 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
2040 'GL_SYNC_CONDITION',
2049 # This table specifies the different pepper interfaces that are supported for
2050 # GL commands. 'dev' is true if it's a dev interface.
2051 _PEPPER_INTERFACES
= [
2052 {'name': '', 'dev': False},
2053 {'name': 'InstancedArrays', 'dev': False},
2054 {'name': 'FramebufferBlit', 'dev': False},
2055 {'name': 'FramebufferMultisample', 'dev': False},
2056 {'name': 'ChromiumEnableFeature', 'dev': False},
2057 {'name': 'ChromiumMapSub', 'dev': False},
2058 {'name': 'Query', 'dev': False},
2059 {'name': 'VertexArrayObject', 'dev': False},
2060 {'name': 'DrawBuffers', 'dev': True},
2063 # A function info object specifies the type and other special data for the
2064 # command that will be generated. A base function info object is generated by
2065 # parsing the "cmd_buffer_functions.txt", one for each function in the
2066 # file. These function info objects can be augmented and their values can be
2067 # overridden by adding an object to the table below.
2069 # Must match function names specified in "cmd_buffer_functions.txt".
2071 # cmd_comment: A comment added to the cmd format.
2072 # type: defines which handler will be used to generate code.
2073 # decoder_func: defines which function to call in the decoder to execute the
2074 # corresponding GL command. If not specified the GL command will
2075 # be called directly.
2076 # gl_test_func: GL function that is expected to be called when testing.
2077 # cmd_args: The arguments to use for the command. This overrides generating
2078 # them based on the GL function arguments.
2079 # gen_cmd: Whether or not this function geneates a command. Default = True.
2080 # data_transfer_methods: Array of methods that are used for transfering the
2081 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
2082 # The default is 'immediate' if the command has one pointer
2083 # argument, otherwise 'shm'. One command is generated for each
2084 # transfer method. Affects only commands which are not of type
2085 # 'HandWritten', 'GETn' or 'GLcharN'.
2086 # Note: the command arguments that affect this are the final args,
2087 # taking cmd_args override into consideration.
2088 # impl_func: Whether or not to generate the GLES2Implementation part of this
2090 # impl_decl: Whether or not to generate the GLES2Implementation declaration
2092 # needs_size: If True a data_size field is added to the command.
2093 # count: The number of units per element. For PUTn or PUT types.
2094 # use_count_func: If True the actual data count needs to be computed; the count
2095 # argument specifies the maximum count.
2096 # unit_test: If False no service side unit test will be generated.
2097 # client_test: If False no client side unit test will be generated.
2098 # expectation: If False the unit test will have no expected calls.
2099 # gen_func: Name of function that generates GL resource for corresponding
2101 # states: array of states that get set by this function corresponding to
2102 # the given arguments
2103 # state_flag: name of flag that is set to true when function is called.
2104 # no_gl: no GL function is called.
2105 # valid_args: A dictionary of argument indices to args to use in unit tests
2106 # when they can not be automatically determined.
2107 # pepper_interface: The pepper interface that is used for this extension
2108 # pepper_name: The name of the function as exposed to pepper.
2109 # pepper_args: A string representing the argument list (what would appear in
2110 # C/C++ between the parentheses for the function declaration)
2111 # that the Pepper API expects for this function. Use this only if
2112 # the stable Pepper API differs from the GLES2 argument list.
2113 # invalid_test: False if no invalid test needed.
2114 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2115 # first_element_only: For PUT types, True if only the first element of an
2116 # array is used and we end up calling the single value
2117 # corresponding function. eg. TexParameteriv -> TexParameteri
2118 # extension: Function is an extension to GL and should not be exposed to
2119 # pepper unless pepper_interface is defined.
2120 # extension_flag: Function is an extension and should be enabled only when
2121 # the corresponding feature info flag is enabled. Implies
2122 # 'extension': True.
2123 # not_shared: For GENn types, True if objects can't be shared between contexts
2124 # unsafe: True = no validation is implemented on the service side and the
2125 # command is only available with --enable-unsafe-es3-apis.
2126 # id_mapping: A list of resource type names whose client side IDs need to be
2127 # mapped to service side IDs. This is only used for unsafe APIs.
2131 'decoder_func': 'DoActiveTexture',
2134 'client_test': False,
2136 'AttachShader': {'decoder_func': 'DoAttachShader'},
2137 'BindAttribLocation': {
2139 'data_transfer_methods': ['bucket'],
2144 'decoder_func': 'DoBindBuffer',
2145 'gen_func': 'GenBuffersARB',
2149 'id_mapping': [ 'Buffer' ],
2150 'gen_func': 'GenBuffersARB',
2153 'BindBufferRange': {
2155 'id_mapping': [ 'Buffer' ],
2156 'gen_func': 'GenBuffersARB',
2163 'BindFramebuffer': {
2165 'decoder_func': 'DoBindFramebuffer',
2166 'gl_test_func': 'glBindFramebufferEXT',
2167 'gen_func': 'GenFramebuffersEXT',
2170 'BindRenderbuffer': {
2172 'decoder_func': 'DoBindRenderbuffer',
2173 'gl_test_func': 'glBindRenderbufferEXT',
2174 'gen_func': 'GenRenderbuffersEXT',
2178 'id_mapping': [ 'Sampler' ],
2183 'decoder_func': 'DoBindTexture',
2184 'gen_func': 'GenTextures',
2185 # TODO(gman): remove this once client side caching works.
2186 'client_test': False,
2189 'BindTransformFeedback': {
2191 'id_mapping': [ 'TransformFeedback' ],
2194 'BlitFramebufferCHROMIUM': {
2195 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2197 'extension_flag': 'chromium_framebuffer_multisample',
2198 'pepper_interface': 'FramebufferBlit',
2199 'pepper_name': 'BlitFramebufferEXT',
2200 'defer_reads': True,
2201 'defer_draws': True,
2206 'data_transfer_methods': ['shm'],
2207 'client_test': False,
2212 'client_test': False,
2213 'decoder_func': 'DoBufferSubData',
2214 'data_transfer_methods': ['shm'],
2217 'CheckFramebufferStatus': {
2219 'decoder_func': 'DoCheckFramebufferStatus',
2220 'gl_test_func': 'glCheckFramebufferStatusEXT',
2221 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2222 'result': ['GLenum'],
2225 'decoder_func': 'DoClear',
2226 'defer_draws': True,
2231 'use_count_func': True,
2244 'use_count_func': True,
2255 'state': 'ClearColor',
2259 'state': 'ClearDepthf',
2260 'decoder_func': 'glClearDepth',
2261 'gl_test_func': 'glClearDepth',
2268 'data_transfer_methods': ['shm'],
2269 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2270 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2272 'result': ['GLenum'],
2277 'state': 'ColorMask',
2279 'expectation': False,
2281 'ConsumeTextureCHROMIUM': {
2282 'decoder_func': 'DoConsumeTextureCHROMIUM',
2285 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2287 'client_test': False,
2288 'extension': "CHROMIUM_texture_mailbox",
2292 'CopyBufferSubData': {
2295 'CreateAndConsumeTextureCHROMIUM': {
2296 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2298 'type': 'HandWritten',
2299 'data_transfer_methods': ['immediate'],
2301 'client_test': False,
2302 'extension': "CHROMIUM_texture_mailbox",
2306 'GenValuebuffersCHROMIUM': {
2308 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2309 'resource_type': 'Valuebuffer',
2310 'resource_types': 'Valuebuffers',
2315 'DeleteValuebuffersCHROMIUM': {
2317 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2318 'resource_type': 'Valuebuffer',
2319 'resource_types': 'Valuebuffers',
2324 'IsValuebufferCHROMIUM': {
2326 'decoder_func': 'DoIsValuebufferCHROMIUM',
2327 'expectation': False,
2331 'BindValuebufferCHROMIUM': {
2333 'decoder_func': 'DoBindValueBufferCHROMIUM',
2334 'gen_func': 'GenValueBuffersCHROMIUM',
2339 'SubscribeValueCHROMIUM': {
2340 'decoder_func': 'DoSubscribeValueCHROMIUM',
2345 'PopulateSubscribedValuesCHROMIUM': {
2346 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2351 'UniformValuebufferCHROMIUM': {
2352 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2359 'state': 'ClearStencil',
2361 'EnableFeatureCHROMIUM': {
2363 'data_transfer_methods': ['shm'],
2364 'decoder_func': 'DoEnableFeatureCHROMIUM',
2365 'expectation': False,
2366 'cmd_args': 'GLuint bucket_id, GLint* result',
2367 'result': ['GLint'],
2370 'pepper_interface': 'ChromiumEnableFeature',
2372 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2373 'CompressedTexImage2D': {
2375 'data_transfer_methods': ['bucket', 'shm'],
2378 'CompressedTexSubImage2D': {
2380 'data_transfer_methods': ['bucket', 'shm'],
2381 'decoder_func': 'DoCompressedTexSubImage2D',
2385 'decoder_func': 'DoCopyTexImage2D',
2387 'defer_reads': True,
2390 'CopyTexSubImage2D': {
2391 'decoder_func': 'DoCopyTexSubImage2D',
2392 'defer_reads': True,
2395 'CompressedTexImage3D': {
2397 'data_transfer_methods': ['bucket', 'shm'],
2401 'CompressedTexSubImage3D': {
2403 'data_transfer_methods': ['bucket', 'shm'],
2404 'decoder_func': 'DoCompressedTexSubImage3D',
2408 'CopyTexSubImage3D': {
2409 'defer_reads': True,
2413 'CreateImageCHROMIUM': {
2416 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2417 'GLenum internalformat',
2418 'result': ['GLuint'],
2419 'client_test': False,
2421 'expectation': False,
2422 'extension': "CHROMIUM_image",
2426 'DestroyImageCHROMIUM': {
2428 'client_test': False,
2430 'extension': "CHROMIUM_image",
2434 'CreateGpuMemoryBufferImageCHROMIUM': {
2437 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2438 'result': ['GLuint'],
2439 'client_test': False,
2441 'expectation': False,
2442 'extension': "CHROMIUM_image",
2448 'client_test': False,
2452 'client_test': False,
2456 'state': 'BlendColor',
2459 'type': 'StateSetRGBAlpha',
2460 'state': 'BlendEquation',
2462 '0': 'GL_FUNC_SUBTRACT'
2465 'BlendEquationSeparate': {
2467 'state': 'BlendEquation',
2469 '0': 'GL_FUNC_SUBTRACT'
2473 'type': 'StateSetRGBAlpha',
2474 'state': 'BlendFunc',
2476 'BlendFuncSeparate': {
2478 'state': 'BlendFunc',
2480 'BlendBarrierKHR': {
2481 'gl_test_func': 'glBlendBarrierKHR',
2483 'extension_flag': 'blend_equation_advanced',
2484 'client_test': False,
2486 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2488 'type': 'StateSetFrontBack',
2489 'state': 'StencilFunc',
2491 'StencilFuncSeparate': {
2492 'type': 'StateSetFrontBackSeparate',
2493 'state': 'StencilFunc',
2496 'type': 'StateSetFrontBack',
2497 'state': 'StencilOp',
2502 'StencilOpSeparate': {
2503 'type': 'StateSetFrontBackSeparate',
2504 'state': 'StencilOp',
2510 'type': 'StateSetNamedParameter',
2513 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2514 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2515 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2518 'state': 'LineWidth',
2525 'state': 'PolygonOffset',
2529 'gl_test_func': 'glDeleteBuffersARB',
2530 'resource_type': 'Buffer',
2531 'resource_types': 'Buffers',
2533 'DeleteFramebuffers': {
2535 'gl_test_func': 'glDeleteFramebuffersEXT',
2536 'resource_type': 'Framebuffer',
2537 'resource_types': 'Framebuffers',
2540 'DeleteProgram': { 'type': 'Delete' },
2541 'DeleteRenderbuffers': {
2543 'gl_test_func': 'glDeleteRenderbuffersEXT',
2544 'resource_type': 'Renderbuffer',
2545 'resource_types': 'Renderbuffers',
2550 'resource_type': 'Sampler',
2551 'resource_types': 'Samplers',
2554 'DeleteShader': { 'type': 'Delete' },
2557 'cmd_args': 'GLuint sync',
2558 'resource_type': 'Sync',
2563 'resource_type': 'Texture',
2564 'resource_types': 'Textures',
2566 'DeleteTransformFeedbacks': {
2568 'resource_type': 'TransformFeedback',
2569 'resource_types': 'TransformFeedbacks',
2573 'decoder_func': 'DoDepthRangef',
2574 'gl_test_func': 'glDepthRange',
2578 'state': 'DepthMask',
2580 'expectation': False,
2582 'DetachShader': {'decoder_func': 'DoDetachShader'},
2584 'decoder_func': 'DoDisable',
2586 'client_test': False,
2588 'DisableVertexAttribArray': {
2589 'decoder_func': 'DoDisableVertexAttribArray',
2594 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2595 'defer_draws': True,
2600 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2601 'GLenumIndexType type, GLuint index_offset',
2602 'client_test': False,
2603 'defer_draws': True,
2606 'DrawRangeElements': {
2612 'decoder_func': 'DoEnable',
2614 'client_test': False,
2616 'EnableVertexAttribArray': {
2617 'decoder_func': 'DoEnableVertexAttribArray',
2622 'client_test': False,
2628 'client_test': False,
2629 'decoder_func': 'DoFinish',
2630 'defer_reads': True,
2635 'decoder_func': 'DoFlush',
2638 'FramebufferRenderbuffer': {
2639 'decoder_func': 'DoFramebufferRenderbuffer',
2640 'gl_test_func': 'glFramebufferRenderbufferEXT',
2643 'FramebufferTexture2D': {
2644 'decoder_func': 'DoFramebufferTexture2D',
2645 'gl_test_func': 'glFramebufferTexture2DEXT',
2648 'FramebufferTexture2DMultisampleEXT': {
2649 'decoder_func': 'DoFramebufferTexture2DMultisample',
2650 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2651 'expectation': False,
2653 'extension_flag': 'multisampled_render_to_texture',
2656 'FramebufferTextureLayer': {
2657 'decoder_func': 'DoFramebufferTextureLayer',
2662 'decoder_func': 'DoGenerateMipmap',
2663 'gl_test_func': 'glGenerateMipmapEXT',
2668 'gl_test_func': 'glGenBuffersARB',
2669 'resource_type': 'Buffer',
2670 'resource_types': 'Buffers',
2672 'GenMailboxCHROMIUM': {
2673 'type': 'HandWritten',
2675 'extension': "CHROMIUM_texture_mailbox",
2678 'GenFramebuffers': {
2680 'gl_test_func': 'glGenFramebuffersEXT',
2681 'resource_type': 'Framebuffer',
2682 'resource_types': 'Framebuffers',
2684 'GenRenderbuffers': {
2685 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2686 'resource_type': 'Renderbuffer',
2687 'resource_types': 'Renderbuffers',
2691 'gl_test_func': 'glGenSamplers',
2692 'resource_type': 'Sampler',
2693 'resource_types': 'Samplers',
2698 'gl_test_func': 'glGenTextures',
2699 'resource_type': 'Texture',
2700 'resource_types': 'Textures',
2702 'GenTransformFeedbacks': {
2704 'gl_test_func': 'glGenTransformFeedbacks',
2705 'resource_type': 'TransformFeedback',
2706 'resource_types': 'TransformFeedbacks',
2709 'GetActiveAttrib': {
2711 'data_transfer_methods': ['shm'],
2713 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2721 'GetActiveUniform': {
2723 'data_transfer_methods': ['shm'],
2725 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2733 'GetActiveUniformBlockiv': {
2735 'data_transfer_methods': ['shm'],
2736 'result': ['SizedResult<GLint>'],
2739 'GetActiveUniformBlockName': {
2741 'data_transfer_methods': ['shm'],
2743 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2745 'result': ['int32_t'],
2748 'GetActiveUniformsiv': {
2750 'data_transfer_methods': ['shm'],
2752 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2754 'result': ['SizedResult<GLint>'],
2757 'GetAttachedShaders': {
2759 'data_transfer_methods': ['shm'],
2760 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2761 'result': ['SizedResult<GLuint>'],
2763 'GetAttribLocation': {
2765 'data_transfer_methods': ['shm'],
2767 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2768 'result': ['GLint'],
2771 'GetFragDataLocation': {
2773 'data_transfer_methods': ['shm'],
2775 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2776 'result': ['GLint'],
2782 'result': ['SizedResult<GLboolean>'],
2783 'decoder_func': 'DoGetBooleanv',
2784 'gl_test_func': 'glGetBooleanv',
2786 'GetBufferParameteri64v': {
2788 'result': ['SizedResult<GLint64>'],
2789 'decoder_func': 'DoGetBufferParameteri64v',
2790 'expectation': False,
2794 'GetBufferParameteriv': {
2796 'result': ['SizedResult<GLint>'],
2797 'decoder_func': 'DoGetBufferParameteriv',
2798 'expectation': False,
2803 'decoder_func': 'GetErrorState()->GetGLError',
2805 'result': ['GLenum'],
2806 'client_test': False,
2810 'result': ['SizedResult<GLfloat>'],
2811 'decoder_func': 'DoGetFloatv',
2812 'gl_test_func': 'glGetFloatv',
2814 'GetFramebufferAttachmentParameteriv': {
2816 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2817 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2818 'result': ['SizedResult<GLint>'],
2820 'GetGraphicsResetStatusKHR': {
2822 'client_test': False,
2828 'result': ['SizedResult<GLint64>'],
2829 'client_test': False,
2830 'decoder_func': 'DoGetInteger64v',
2835 'result': ['SizedResult<GLint>'],
2836 'decoder_func': 'DoGetIntegerv',
2837 'client_test': False,
2839 'GetInteger64i_v': {
2841 'result': ['SizedResult<GLint64>'],
2842 'client_test': False,
2847 'result': ['SizedResult<GLint>'],
2848 'client_test': False,
2851 'GetInternalformativ': {
2853 'data_transfer_methods': ['shm'],
2854 'result': ['SizedResult<GLint>'],
2856 'GLenumRenderBufferTarget target, GLenumRenderBufferFormat format, '
2857 'GLenumInternalFormatParameter pname, GLint* params',
2860 'GetMaxValueInBufferCHROMIUM': {
2862 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2863 'result': ['GLuint'],
2865 'client_test': False,
2872 'decoder_func': 'DoGetProgramiv',
2873 'result': ['SizedResult<GLint>'],
2874 'expectation': False,
2876 'GetProgramInfoCHROMIUM': {
2878 'expectation': False,
2882 'client_test': False,
2883 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2885 'uint32_t link_status',
2886 'uint32_t num_attribs',
2887 'uint32_t num_uniforms',
2890 'GetProgramInfoLog': {
2892 'expectation': False,
2894 'GetRenderbufferParameteriv': {
2896 'decoder_func': 'DoGetRenderbufferParameteriv',
2897 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2898 'result': ['SizedResult<GLint>'],
2900 'GetSamplerParameterfv': {
2902 'result': ['SizedResult<GLfloat>'],
2903 'id_mapping': [ 'Sampler' ],
2906 'GetSamplerParameteriv': {
2908 'result': ['SizedResult<GLint>'],
2909 'id_mapping': [ 'Sampler' ],
2914 'decoder_func': 'DoGetShaderiv',
2915 'result': ['SizedResult<GLint>'],
2917 'GetShaderInfoLog': {
2919 'get_len_func': 'glGetShaderiv',
2920 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2923 'GetShaderPrecisionFormat': {
2925 'data_transfer_methods': ['shm'],
2927 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2931 'int32_t min_range',
2932 'int32_t max_range',
2933 'int32_t precision',
2936 'GetShaderSource': {
2938 'get_len_func': 'DoGetShaderiv',
2939 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2941 'client_test': False,
2945 'client_test': False,
2946 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2950 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2951 'result': ['SizedResult<GLint>'],
2952 'id_mapping': ['Sync'],
2955 'GetTexParameterfv': {
2957 'decoder_func': 'DoGetTexParameterfv',
2958 'result': ['SizedResult<GLfloat>']
2960 'GetTexParameteriv': {
2962 'decoder_func': 'DoGetTexParameteriv',
2963 'result': ['SizedResult<GLint>']
2965 'GetTranslatedShaderSourceANGLE': {
2967 'get_len_func': 'DoGetShaderiv',
2968 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2972 'GetUniformBlockIndex': {
2974 'data_transfer_methods': ['shm'],
2976 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2977 'result': ['GLuint'],
2978 'error_return': 'GL_INVALID_INDEX',
2981 'GetUniformBlocksCHROMIUM': {
2983 'expectation': False,
2987 'client_test': False,
2988 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2989 'result': ['uint32_t'],
2992 'GetUniformsES3CHROMIUM': {
2994 'expectation': False,
2998 'client_test': False,
2999 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3000 'result': ['uint32_t'],
3003 'GetTransformFeedbackVarying': {
3005 'data_transfer_methods': ['shm'],
3007 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
3016 'GetTransformFeedbackVaryingsCHROMIUM': {
3018 'expectation': False,
3022 'client_test': False,
3023 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3024 'result': ['uint32_t'],
3029 'data_transfer_methods': ['shm'],
3030 'result': ['SizedResult<GLfloat>'],
3034 'data_transfer_methods': ['shm'],
3035 'result': ['SizedResult<GLint>'],
3039 'data_transfer_methods': ['shm'],
3040 'result': ['SizedResult<GLuint>'],
3043 'GetUniformIndices': {
3045 'data_transfer_methods': ['shm'],
3046 'result': ['SizedResult<GLuint>'],
3047 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
3051 'GetUniformLocation': {
3053 'data_transfer_methods': ['shm'],
3055 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
3056 'result': ['GLint'],
3057 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
3059 'GetVertexAttribfv': {
3061 'result': ['SizedResult<GLfloat>'],
3063 'decoder_func': 'DoGetVertexAttribfv',
3064 'expectation': False,
3065 'client_test': False,
3067 'GetVertexAttribiv': {
3069 'result': ['SizedResult<GLint>'],
3071 'decoder_func': 'DoGetVertexAttribiv',
3072 'expectation': False,
3073 'client_test': False,
3075 'GetVertexAttribIiv': {
3077 'result': ['SizedResult<GLint>'],
3079 'decoder_func': 'DoGetVertexAttribIiv',
3080 'expectation': False,
3081 'client_test': False,
3084 'GetVertexAttribIuiv': {
3086 'result': ['SizedResult<GLuint>'],
3088 'decoder_func': 'DoGetVertexAttribIuiv',
3089 'expectation': False,
3090 'client_test': False,
3093 'GetVertexAttribPointerv': {
3095 'data_transfer_methods': ['shm'],
3096 'result': ['SizedResult<GLuint>'],
3097 'client_test': False,
3099 'InvalidateFramebuffer': {
3102 'client_test': False,
3106 'InvalidateSubFramebuffer': {
3109 'client_test': False,
3115 'decoder_func': 'DoIsBuffer',
3116 'expectation': False,
3120 'decoder_func': 'DoIsEnabled',
3121 'client_test': False,
3123 'expectation': False,
3127 'decoder_func': 'DoIsFramebuffer',
3128 'expectation': False,
3132 'decoder_func': 'DoIsProgram',
3133 'expectation': False,
3137 'decoder_func': 'DoIsRenderbuffer',
3138 'expectation': False,
3142 'decoder_func': 'DoIsShader',
3143 'expectation': False,
3147 'id_mapping': [ 'Sampler' ],
3148 'expectation': False,
3153 'id_mapping': [ 'Sync' ],
3154 'cmd_args': 'GLuint sync',
3155 'expectation': False,
3160 'decoder_func': 'DoIsTexture',
3161 'expectation': False,
3163 'IsTransformFeedback': {
3165 'id_mapping': [ 'TransformFeedback' ],
3166 'expectation': False,
3170 'decoder_func': 'DoLinkProgram',
3174 'MapBufferCHROMIUM': {
3176 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3178 'client_test': False,
3181 'MapBufferSubDataCHROMIUM': {
3185 'client_test': False,
3186 'pepper_interface': 'ChromiumMapSub',
3189 'MapTexSubImage2DCHROMIUM': {
3191 'extension': "CHROMIUM_sub_image",
3193 'client_test': False,
3194 'pepper_interface': 'ChromiumMapSub',
3199 'data_transfer_methods': ['shm'],
3200 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3201 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3202 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3203 'uint32_t result_shm_id, uint32_t result_shm_offset',
3205 'result': ['uint32_t'],
3208 'PauseTransformFeedback': {
3211 'PixelStorei': {'type': 'Manual'},
3212 'PostSubBufferCHROMIUM': {
3216 'client_test': False,
3220 'ProduceTextureCHROMIUM': {
3221 'decoder_func': 'DoProduceTextureCHROMIUM',
3224 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3226 'client_test': False,
3227 'extension': "CHROMIUM_texture_mailbox",
3231 'ProduceTextureDirectCHROMIUM': {
3232 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3235 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3237 'client_test': False,
3238 'extension': "CHROMIUM_texture_mailbox",
3242 'RenderbufferStorage': {
3243 'decoder_func': 'DoRenderbufferStorage',
3244 'gl_test_func': 'glRenderbufferStorageEXT',
3245 'expectation': False,
3248 'RenderbufferStorageMultisampleCHROMIUM': {
3250 '// GL_CHROMIUM_framebuffer_multisample\n',
3251 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3252 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3253 'expectation': False,
3255 'extension_flag': 'chromium_framebuffer_multisample',
3256 'pepper_interface': 'FramebufferMultisample',
3257 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3260 'RenderbufferStorageMultisampleEXT': {
3262 '// GL_EXT_multisampled_render_to_texture\n',
3263 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3264 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3265 'expectation': False,
3267 'extension_flag': 'multisampled_render_to_texture',
3272 'decoder_func': 'DoReadBuffer',
3277 '// ReadPixels has the result separated from the pixel buffer so that\n'
3278 '// it is easier to specify the result going to some specific place\n'
3279 '// that exactly fits the rectangle of pixels.\n',
3281 'data_transfer_methods': ['shm'],
3283 'client_test': False,
3285 'GLint x, GLint y, GLsizei width, GLsizei height, '
3286 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3287 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3288 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3290 'result': ['uint32_t'],
3291 'defer_reads': True,
3294 'ReleaseShaderCompiler': {
3295 'decoder_func': 'DoReleaseShaderCompiler',
3298 'ResumeTransformFeedback': {
3301 'SamplerParameterf': {
3305 'id_mapping': [ 'Sampler' ],
3308 'SamplerParameterfv': {
3310 'data_value': 'GL_NEAREST',
3312 'gl_test_func': 'glSamplerParameterf',
3313 'decoder_func': 'DoSamplerParameterfv',
3314 'first_element_only': True,
3315 'id_mapping': [ 'Sampler' ],
3318 'SamplerParameteri': {
3322 'id_mapping': [ 'Sampler' ],
3325 'SamplerParameteriv': {
3327 'data_value': 'GL_NEAREST',
3329 'gl_test_func': 'glSamplerParameteri',
3330 'decoder_func': 'DoSamplerParameteriv',
3331 'first_element_only': True,
3336 'client_test': False,
3340 'decoder_func': 'DoShaderSource',
3341 'expectation': False,
3342 'data_transfer_methods': ['bucket'],
3344 'GLuint shader, const char** str',
3346 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3349 'type': 'StateSetFrontBack',
3350 'state': 'StencilMask',
3352 'expectation': False,
3354 'StencilMaskSeparate': {
3355 'type': 'StateSetFrontBackSeparate',
3356 'state': 'StencilMask',
3358 'expectation': False,
3362 'decoder_func': 'DoSwapBuffers',
3364 'client_test': False,
3370 'decoder_func': 'DoSwapInterval',
3372 'client_test': False,
3378 'data_transfer_methods': ['shm'],
3379 'client_test': False,
3384 'data_transfer_methods': ['shm'],
3385 'client_test': False,
3390 'decoder_func': 'DoTexParameterf',
3396 'decoder_func': 'DoTexParameteri',
3403 'data_value': 'GL_NEAREST',
3405 'decoder_func': 'DoTexParameterfv',
3406 'gl_test_func': 'glTexParameterf',
3407 'first_element_only': True,
3411 'data_value': 'GL_NEAREST',
3413 'decoder_func': 'DoTexParameteriv',
3414 'gl_test_func': 'glTexParameteri',
3415 'first_element_only': True,
3423 'data_transfer_methods': ['shm'],
3424 'client_test': False,
3426 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3427 'GLint xoffset, GLint yoffset, '
3428 'GLsizei width, GLsizei height, '
3429 'GLenumTextureFormat format, GLenumPixelType type, '
3430 'const void* pixels, GLboolean internal'
3434 'data_transfer_methods': ['shm'],
3435 'client_test': False,
3437 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3438 'GLint xoffset, GLint yoffset, GLint zoffset, '
3439 'GLsizei width, GLsizei height, GLsizei depth, '
3440 'GLenumTextureFormat format, GLenumPixelType type, '
3441 'const void* pixels, GLboolean internal',
3444 'TransformFeedbackVaryings': {
3446 'data_transfer_methods': ['bucket'],
3447 'decoder_func': 'DoTransformFeedbackVaryings',
3449 'GLuint program, const char** varyings, GLenum buffermode',
3452 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3456 'decoder_func': 'DoUniform1fv',
3458 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3462 'decoder_func': 'DoUniform1iv',
3475 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3476 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3480 'decoder_func': 'DoUniform2fv',
3485 'decoder_func': 'DoUniform2iv',
3497 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3498 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3502 'decoder_func': 'DoUniform3fv',
3507 'decoder_func': 'DoUniform3iv',
3519 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3520 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3524 'decoder_func': 'DoUniform4fv',
3529 'decoder_func': 'DoUniform4iv',
3541 'UniformMatrix2fv': {
3544 'decoder_func': 'DoUniformMatrix2fv',
3546 'UniformMatrix2x3fv': {
3551 'UniformMatrix2x4fv': {
3556 'UniformMatrix3fv': {
3559 'decoder_func': 'DoUniformMatrix3fv',
3561 'UniformMatrix3x2fv': {
3566 'UniformMatrix3x4fv': {
3571 'UniformMatrix4fv': {
3574 'decoder_func': 'DoUniformMatrix4fv',
3576 'UniformMatrix4x2fv': {
3581 'UniformMatrix4x3fv': {
3586 'UniformBlockBinding': {
3591 'UnmapBufferCHROMIUM': {
3593 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3595 'client_test': False,
3598 'UnmapBufferSubDataCHROMIUM': {
3602 'client_test': False,
3603 'pepper_interface': 'ChromiumMapSub',
3611 'UnmapTexSubImage2DCHROMIUM': {
3613 'extension': "CHROMIUM_sub_image",
3615 'client_test': False,
3616 'pepper_interface': 'ChromiumMapSub',
3621 'decoder_func': 'DoUseProgram',
3623 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3624 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3625 'VertexAttrib1fv': {
3628 'decoder_func': 'DoVertexAttrib1fv',
3630 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3631 'VertexAttrib2fv': {
3634 'decoder_func': 'DoVertexAttrib2fv',
3636 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3637 'VertexAttrib3fv': {
3640 'decoder_func': 'DoVertexAttrib3fv',
3642 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3643 'VertexAttrib4fv': {
3646 'decoder_func': 'DoVertexAttrib4fv',
3648 'VertexAttribI4i': {
3650 'decoder_func': 'DoVertexAttribI4i',
3652 'VertexAttribI4iv': {
3656 'decoder_func': 'DoVertexAttribI4iv',
3658 'VertexAttribI4ui': {
3660 'decoder_func': 'DoVertexAttribI4ui',
3662 'VertexAttribI4uiv': {
3666 'decoder_func': 'DoVertexAttribI4uiv',
3668 'VertexAttribIPointer': {
3670 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3671 'GLenumVertexAttribIType type, GLsizei stride, '
3673 'client_test': False,
3676 'VertexAttribPointer': {
3678 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3679 'GLenumVertexAttribType type, GLboolean normalized, '
3680 'GLsizei stride, GLuint offset',
3681 'client_test': False,
3685 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3686 'GLuint timeout_0, GLuint timeout_1',
3688 'client_test': False,
3697 'decoder_func': 'DoViewport',
3707 'GetRequestableExtensionsCHROMIUM': {
3710 'cmd_args': 'uint32_t bucket_id',
3714 'RequestExtensionCHROMIUM': {
3717 'client_test': False,
3718 'cmd_args': 'uint32_t bucket_id',
3722 'RateLimitOffscreenContextCHROMIUM': {
3726 'client_test': False,
3728 'CreateStreamTextureCHROMIUM': {
3729 'type': 'HandWritten',
3736 'TexImageIOSurface2DCHROMIUM': {
3737 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3743 'CopyTextureCHROMIUM': {
3744 'decoder_func': 'DoCopyTextureCHROMIUM',
3746 'extension': "CHROMIUM_copy_texture",
3750 'CopySubTextureCHROMIUM': {
3751 'decoder_func': 'DoCopySubTextureCHROMIUM',
3753 'extension': "CHROMIUM_copy_texture",
3757 'CompressedCopyTextureCHROMIUM': {
3758 'decoder_func': 'DoCompressedCopyTextureCHROMIUM',
3763 'CompressedCopySubTextureCHROMIUM': {
3764 'decoder_func': 'DoCompressedCopySubTextureCHROMIUM',
3769 'TexStorage2DEXT': {
3772 'decoder_func': 'DoTexStorage2DEXT',
3775 'DrawArraysInstancedANGLE': {
3777 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3778 'GLsizei primcount',
3781 'pepper_interface': 'InstancedArrays',
3782 'defer_draws': True,
3787 'decoder_func': 'DoDrawBuffersEXT',
3789 'client_test': False,
3791 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3794 'pepper_interface': 'DrawBuffers',
3797 'DrawElementsInstancedANGLE': {
3799 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3800 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3803 'client_test': False,
3804 'pepper_interface': 'InstancedArrays',
3805 'defer_draws': True,
3808 'VertexAttribDivisorANGLE': {
3810 'cmd_args': 'GLuint index, GLuint divisor',
3813 'pepper_interface': 'InstancedArrays',
3817 'gl_test_func': 'glGenQueriesARB',
3818 'resource_type': 'Query',
3819 'resource_types': 'Queries',
3821 'pepper_interface': 'Query',
3822 'not_shared': 'True',
3823 'extension': "occlusion_query_EXT",
3825 'DeleteQueriesEXT': {
3827 'gl_test_func': 'glDeleteQueriesARB',
3828 'resource_type': 'Query',
3829 'resource_types': 'Queries',
3831 'pepper_interface': 'Query',
3832 'extension': "occlusion_query_EXT",
3836 'client_test': False,
3837 'pepper_interface': 'Query',
3838 'extension': "occlusion_query_EXT",
3842 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3843 'data_transfer_methods': ['shm'],
3844 'gl_test_func': 'glBeginQuery',
3845 'pepper_interface': 'Query',
3846 'extension': "occlusion_query_EXT",
3848 'BeginTransformFeedback': {
3853 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3854 'gl_test_func': 'glEndnQuery',
3855 'client_test': False,
3856 'pepper_interface': 'Query',
3857 'extension': "occlusion_query_EXT",
3859 'EndTransformFeedback': {
3862 'FlushDriverCachesCHROMIUM': {
3863 'decoder_func': 'DoFlushDriverCachesCHROMIUM',
3871 'client_test': False,
3872 'gl_test_func': 'glGetQueryiv',
3873 'pepper_interface': 'Query',
3874 'extension': "occlusion_query_EXT",
3876 'QueryCounterEXT' : {
3878 'cmd_args': 'GLidQuery id, GLenumQueryTarget target, '
3879 'void* sync_data, GLuint submit_count',
3880 'data_transfer_methods': ['shm'],
3881 'gl_test_func': 'glQueryCounter',
3882 'extension': "disjoint_timer_query_EXT",
3884 'GetQueryObjectivEXT': {
3886 'client_test': False,
3887 'gl_test_func': 'glGetQueryObjectiv',
3888 'extension': "disjoint_timer_query_EXT",
3890 'GetQueryObjectuivEXT': {
3892 'client_test': False,
3893 'gl_test_func': 'glGetQueryObjectuiv',
3894 'pepper_interface': 'Query',
3895 'extension': "occlusion_query_EXT",
3897 'GetQueryObjecti64vEXT': {
3899 'client_test': False,
3900 'gl_test_func': 'glGetQueryObjecti64v',
3901 'extension': "disjoint_timer_query_EXT",
3903 'GetQueryObjectui64vEXT': {
3905 'client_test': False,
3906 'gl_test_func': 'glGetQueryObjectui64v',
3907 'extension': "disjoint_timer_query_EXT",
3909 'SetDisjointValueSyncCHROMIUM': {
3911 'data_transfer_methods': ['shm'],
3912 'client_test': False,
3913 'cmd_args': 'void* sync_data',
3917 'BindUniformLocationCHROMIUM': {
3920 'data_transfer_methods': ['bucket'],
3922 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3924 'InsertEventMarkerEXT': {
3926 'decoder_func': 'DoInsertEventMarkerEXT',
3927 'expectation': False,
3930 'PushGroupMarkerEXT': {
3932 'decoder_func': 'DoPushGroupMarkerEXT',
3933 'expectation': False,
3936 'PopGroupMarkerEXT': {
3937 'decoder_func': 'DoPopGroupMarkerEXT',
3938 'expectation': False,
3943 'GenVertexArraysOES': {
3946 'gl_test_func': 'glGenVertexArraysOES',
3947 'resource_type': 'VertexArray',
3948 'resource_types': 'VertexArrays',
3950 'pepper_interface': 'VertexArrayObject',
3952 'BindVertexArrayOES': {
3955 'gl_test_func': 'glBindVertexArrayOES',
3956 'decoder_func': 'DoBindVertexArrayOES',
3957 'gen_func': 'GenVertexArraysOES',
3959 'client_test': False,
3960 'pepper_interface': 'VertexArrayObject',
3962 'DeleteVertexArraysOES': {
3965 'gl_test_func': 'glDeleteVertexArraysOES',
3966 'resource_type': 'VertexArray',
3967 'resource_types': 'VertexArrays',
3969 'pepper_interface': 'VertexArrayObject',
3971 'IsVertexArrayOES': {
3974 'gl_test_func': 'glIsVertexArrayOES',
3975 'decoder_func': 'DoIsVertexArrayOES',
3976 'expectation': False,
3978 'pepper_interface': 'VertexArrayObject',
3980 'BindTexImage2DCHROMIUM': {
3981 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3983 'extension': "CHROMIUM_image",
3986 'ReleaseTexImage2DCHROMIUM': {
3987 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3989 'extension': "CHROMIUM_image",
3992 'ShallowFinishCHROMIUM': {
3997 'client_test': False,
3999 'ShallowFlushCHROMIUM': {
4002 'extension': "CHROMIUM_miscellaneous",
4004 'client_test': False,
4006 'OrderingBarrierCHROMIUM': {
4009 'extension': "CHROMIUM_miscellaneous",
4011 'client_test': False,
4013 'TraceBeginCHROMIUM': {
4016 'client_test': False,
4017 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
4021 'TraceEndCHROMIUM': {
4023 'client_test': False,
4024 'decoder_func': 'DoTraceEndCHROMIUM',
4029 'AsyncTexImage2DCHROMIUM': {
4031 'data_transfer_methods': ['shm'],
4032 'client_test': False,
4033 'cmd_args': 'GLenumTextureTarget target, GLint level, '
4034 'GLintTextureInternalFormat internalformat, '
4035 'GLsizei width, GLsizei height, '
4036 'GLintTextureBorder border, '
4037 'GLenumTextureFormat format, GLenumPixelType type, '
4038 'const void* pixels, '
4039 'uint32_t async_upload_token, '
4045 'AsyncTexSubImage2DCHROMIUM': {
4047 'data_transfer_methods': ['shm'],
4048 'client_test': False,
4049 'cmd_args': 'GLenumTextureTarget target, GLint level, '
4050 'GLint xoffset, GLint yoffset, '
4051 'GLsizei width, GLsizei height, '
4052 'GLenumTextureFormat format, GLenumPixelType type, '
4053 'const void* data, '
4054 'uint32_t async_upload_token, '
4060 'WaitAsyncTexImage2DCHROMIUM': {
4062 'client_test': False,
4067 'WaitAllAsyncTexImage2DCHROMIUM': {
4069 'client_test': False,
4074 'DiscardFramebufferEXT': {
4077 'decoder_func': 'DoDiscardFramebufferEXT',
4079 'client_test': False,
4080 'extension_flag': 'ext_discard_framebuffer',
4083 'LoseContextCHROMIUM': {
4084 'decoder_func': 'DoLoseContextCHROMIUM',
4090 'InsertSyncPointCHROMIUM': {
4091 'type': 'HandWritten',
4093 'extension': "CHROMIUM_sync_point",
4097 'WaitSyncPointCHROMIUM': {
4100 'extension': "CHROMIUM_sync_point",
4104 'DiscardBackbufferCHROMIUM': {
4111 'ScheduleOverlayPlaneCHROMIUM': {
4115 'client_test': False,
4119 'MatrixLoadfCHROMIUM': {
4122 'data_type': 'GLfloat',
4123 'decoder_func': 'DoMatrixLoadfCHROMIUM',
4124 'gl_test_func': 'glMatrixLoadfEXT',
4127 'extension_flag': 'chromium_path_rendering',
4129 'MatrixLoadIdentityCHROMIUM': {
4130 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
4131 'gl_test_func': 'glMatrixLoadIdentityEXT',
4134 'extension_flag': 'chromium_path_rendering',
4136 'GenPathsCHROMIUM': {
4138 'cmd_args': 'GLuint first_client_id, GLsizei range',
4141 'extension_flag': 'chromium_path_rendering',
4143 'DeletePathsCHROMIUM': {
4145 'cmd_args': 'GLuint first_client_id, GLsizei range',
4150 'extension_flag': 'chromium_path_rendering',
4154 'decoder_func': 'DoIsPathCHROMIUM',
4155 'gl_test_func': 'glIsPathNV',
4158 'extension_flag': 'chromium_path_rendering',
4160 'PathCommandsCHROMIUM': {
4165 'extension_flag': 'chromium_path_rendering',
4167 'PathParameterfCHROMIUM': {
4171 'extension_flag': 'chromium_path_rendering',
4173 'PathParameteriCHROMIUM': {
4177 'extension_flag': 'chromium_path_rendering',
4179 'PathStencilFuncCHROMIUM': {
4181 'state': 'PathStencilFuncCHROMIUM',
4182 'decoder_func': 'glPathStencilFuncNV',
4185 'extension_flag': 'chromium_path_rendering',
4187 'StencilFillPathCHROMIUM': {
4191 'extension_flag': 'chromium_path_rendering',
4193 'StencilStrokePathCHROMIUM': {
4197 'extension_flag': 'chromium_path_rendering',
4199 'CoverFillPathCHROMIUM': {
4203 'extension_flag': 'chromium_path_rendering',
4205 'CoverStrokePathCHROMIUM': {
4209 'extension_flag': 'chromium_path_rendering',
4211 'StencilThenCoverFillPathCHROMIUM': {
4215 'extension_flag': 'chromium_path_rendering',
4217 'StencilThenCoverStrokePathCHROMIUM': {
4221 'extension_flag': 'chromium_path_rendering',
4227 def Grouper(n
, iterable
, fillvalue
=None):
4228 """Collect data into fixed-length chunks or blocks"""
4229 args
= [iter(iterable
)] * n
4230 return itertools
.izip_longest(fillvalue
=fillvalue
, *args
)
4233 def SplitWords(input_string
):
4234 """Split by '_' if found, otherwise split at uppercase/numeric chars.
4236 Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
4237 "Case"], and "Vector3" into ["Vector", "3"].
4239 if input_string
.find('_') > -1:
4240 # 'some_TEXT_' -> 'some TEXT'
4241 return input_string
.replace('_', ' ').strip().split()
4243 if re
.search('[A-Z]', input_string
) and re
.search('[a-z]', input_string
):
4245 # look for capitalization to cut input_strings
4246 # 'SomeText' -> 'Some Text'
4247 input_string
= re
.sub('([A-Z])', r
' \1', input_string
).strip()
4248 # 'Vector3' -> 'Vector 3'
4249 input_string
= re
.sub('([^0-9])([0-9])', r
'\1 \2', input_string
)
4250 return input_string
.split()
4252 def ToUnderscore(input_string
):
4253 """converts CamelCase to camel_case."""
4254 words
= SplitWords(input_string
)
4255 return '_'.join([word
.lower() for word
in words
])
4257 def CachedStateName(item
):
4258 if item
.get('cached', False):
4259 return 'cached_' + item
['name']
4262 def ToGLExtensionString(extension_flag
):
4263 """Returns GL-type extension string of a extension flag."""
4264 if extension_flag
== "oes_compressed_etc1_rgb8_texture":
4265 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
4267 uppercase_words
= [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
4268 'egl', 'atc', 'etc1', 'angle']
4269 parts
= extension_flag
.split('_')
4271 [part
.upper() if part
in uppercase_words
else part
for part
in parts
])
4273 def ToCamelCase(input_string
):
4274 """converts ABC_underscore_case to ABCUnderscoreCase."""
4275 return ''.join(w
[0].upper() + w
[1:] for w
in input_string
.split('_'))
4277 def GetGLGetTypeConversion(result_type
, value_type
, value
):
4278 """Makes a gl compatible type conversion string for accessing state variables.
4280 Useful when accessing state variables through glGetXXX calls.
4281 glGet documetation (for example, the manual pages):
4282 [...] If glGetIntegerv is called, [...] most floating-point values are
4283 rounded to the nearest integer value. [...]
4286 result_type: the gl type to be obtained
4287 value_type: the GL type of the state variable
4288 value: the name of the state variable
4291 String that converts the state variable to desired GL type according to GL
4295 if result_type
== 'GLint':
4296 if value_type
== 'GLfloat':
4297 return 'static_cast<GLint>(round(%s))' % value
4298 return 'static_cast<%s>(%s)' % (result_type
, value
)
4301 class CWriter(object):
4302 """Context manager that creates a C source file.
4304 To be used with the `with` statement. Returns a normal `file` type, open only
4305 for writing - any existing files with that name will be overwritten. It will
4306 automatically write the contents of `_LICENSE` and `_DO_NOT_EDIT_WARNING`
4310 with CWriter("file.cpp") as myfile:
4311 myfile.write("hello")
4312 # type(myfile) == file
4314 def __init__(self
, filename
):
4315 self
.filename
= filename
4316 self
._file
= open(filename
, 'w')
4317 self
._ENTER
_MSG
= _LICENSE
+ _DO_NOT_EDIT_WARNING
4320 def __enter__(self
):
4321 self
._file
.write(self
._ENTER
_MSG
)
4324 def __exit__(self
, exc_type
, exc_value
, traceback
):
4325 self
._file
.write(self
._EXIT
_MSG
)
4329 class CHeaderWriter(CWriter
):
4330 """Context manager that creates a C header file.
4332 Works the same way as CWriter, except it will also add the #ifdef guard
4333 around it. If `file_comment` is set, it will write that before the #ifdef
4336 def __init__(self
, filename
, file_comment
=None):
4337 super(CHeaderWriter
, self
).__init
__(filename
)
4338 guard
= self
._get
_guard
()
4339 if file_comment
is None:
4341 self
._ENTER
_MSG
= self
._ENTER
_MSG
+ file_comment \
4342 + "#ifndef %s\n#define %s\n\n" % (guard
, guard
)
4343 self
._EXIT
_MSG
= self
._EXIT
_MSG
+ "#endif // %s\n" % guard
4345 def _get_guard(self
):
4346 non_alnum_re
= re
.compile(r
'[^a-zA-Z0-9]')
4347 base
= os
.path
.abspath(self
.filename
)
4348 while os
.path
.basename(base
) != 'src':
4349 new_base
= os
.path
.dirname(base
)
4350 assert new_base
!= base
# Prevent infinite loop.
4352 hpath
= os
.path
.relpath(self
.filename
, base
)
4353 return non_alnum_re
.sub('_', hpath
).upper() + '_'
4356 class TypeHandler(object):
4357 """This class emits code for a particular type of function."""
4359 _remove_expected_call_re
= re
.compile(r
' EXPECT_CALL.*?;\n', re
.S
)
4361 def InitFunction(self
, func
):
4362 """Add or adjust anything type specific for this function."""
4363 if func
.GetInfo('needs_size') and not func
.name
.endswith('Bucket'):
4364 func
.AddCmdArg(DataSizeArgument('data_size'))
4366 def NeedsDataTransferFunction(self
, func
):
4367 """Overriden from TypeHandler."""
4368 return func
.num_pointer_args
>= 1
4370 def WriteStruct(self
, func
, f
):
4371 """Writes a structure that matches the arguments to a function."""
4372 comment
= func
.GetInfo('cmd_comment')
4373 if not comment
== None:
4375 f
.write("struct %s {\n" % func
.name
)
4376 f
.write(" typedef %s ValueType;\n" % func
.name
)
4377 f
.write(" static const CommandId kCmdId = k%s;\n" % func
.name
)
4378 func
.WriteCmdArgFlag(f
)
4379 func
.WriteCmdFlag(f
)
4381 result
= func
.GetInfo('result')
4382 if not result
== None:
4383 if len(result
) == 1:
4384 f
.write(" typedef %s Result;\n\n" % result
[0])
4386 f
.write(" struct Result {\n")
4388 f
.write(" %s;\n" % line
)
4391 func
.WriteCmdComputeSize(f
)
4392 func
.WriteCmdSetHeader(f
)
4393 func
.WriteCmdInit(f
)
4396 f
.write(" gpu::CommandHeader header;\n")
4397 args
= func
.GetCmdArgs()
4399 f
.write(" %s %s;\n" % (arg
.cmd_type
, arg
.name
))
4401 consts
= func
.GetCmdConstants()
4402 for const
in consts
:
4403 f
.write(" static const %s %s = %s;\n" %
4404 (const
.cmd_type
, const
.name
, const
.GetConstantValue()))
4409 size
= len(args
) * _SIZE_OF_UINT32
+ _SIZE_OF_COMMAND_HEADER
4410 f
.write("static_assert(sizeof(%s) == %d,\n" % (func
.name
, size
))
4411 f
.write(" \"size of %s should be %d\");\n" %
4413 f
.write("static_assert(offsetof(%s, header) == 0,\n" % func
.name
)
4414 f
.write(" \"offset of %s header should be 0\");\n" %
4416 offset
= _SIZE_OF_COMMAND_HEADER
4418 f
.write("static_assert(offsetof(%s, %s) == %d,\n" %
4419 (func
.name
, arg
.name
, offset
))
4420 f
.write(" \"offset of %s %s should be %d\");\n" %
4421 (func
.name
, arg
.name
, offset
))
4422 offset
+= _SIZE_OF_UINT32
4423 if not result
== None and len(result
) > 1:
4426 parts
= line
.split()
4429 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4430 "offset of %(cmd_name)s Result %(field_name)s should be "
4433 f
.write((check
.strip() + "\n") % {
4434 'cmd_name': func
.name
,
4438 offset
+= _SIZE_OF_UINT32
4441 def WriteHandlerImplementation(self
, func
, f
):
4442 """Writes the handler implementation for this command."""
4443 if func
.IsUnsafe() and func
.GetInfo('id_mapping'):
4444 code_no_gen
= """ if (!group_->Get%(type)sServiceId(
4445 %(var)s, &%(service_var)s)) {
4446 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4447 return error::kNoError;
4450 code_gen
= """ if (!group_->Get%(type)sServiceId(
4451 %(var)s, &%(service_var)s)) {
4452 if (!group_->bind_generates_resource()) {
4454 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4455 return error::kNoError;
4457 GLuint client_id = %(var)s;
4458 gl%(gen_func)s(1, &%(service_var)s);
4459 Create%(type)s(client_id, %(service_var)s);
4462 gen_func
= func
.GetInfo('gen_func')
4463 for id_type
in func
.GetInfo('id_mapping'):
4464 service_var
= id_type
.lower()
4465 if id_type
== 'Sync':
4466 service_var
= "service_%s" % service_var
4467 f
.write(" GLsync %s = 0;\n" % service_var
)
4468 if id_type
== 'Sampler' and func
.IsType('Bind'):
4469 # No error generated when binding a reserved zero sampler.
4470 args
= [arg
.name
for arg
in func
.GetOriginalArgs()]
4471 f
.write(""" if(%(var)s == 0) {
4473 return error::kNoError;
4474 }""" % { 'var': id_type
.lower(),
4475 'func': func
.GetGLFunctionName(),
4476 'args': ", ".join(args
) })
4477 if gen_func
and id_type
in gen_func
:
4478 f
.write(code_gen
% { 'type': id_type
,
4479 'var': id_type
.lower(),
4480 'service_var': service_var
,
4481 'func': func
.GetGLFunctionName(),
4482 'gen_func': gen_func
})
4484 f
.write(code_no_gen
% { 'type': id_type
,
4485 'var': id_type
.lower(),
4486 'service_var': service_var
,
4487 'func': func
.GetGLFunctionName() })
4489 for arg
in func
.GetOriginalArgs():
4490 if arg
.type == "GLsync":
4491 args
.append("service_%s" % arg
.name
)
4492 elif arg
.name
.endswith("size") and arg
.type == "GLsizei":
4493 args
.append("num_%s" % func
.GetLastOriginalArg().name
)
4494 elif arg
.name
== "length":
4495 args
.append("nullptr")
4497 args
.append(arg
.name
)
4498 f
.write(" %s(%s);\n" %
4499 (func
.GetGLFunctionName(), ", ".join(args
)))
4501 def WriteCmdSizeTest(self
, func
, f
):
4502 """Writes the size test for a command."""
4503 f
.write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4505 def WriteFormatTest(self
, func
, f
):
4506 """Writes a format test for a command."""
4507 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
4508 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4509 (func
.name
, func
.name
))
4510 f
.write(" void* next_cmd = cmd.Set(\n")
4512 args
= func
.GetCmdArgs()
4513 for value
, arg
in enumerate(args
):
4514 f
.write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
4516 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4518 f
.write(" cmd.header.command);\n")
4519 func
.type_handler
.WriteCmdSizeTest(func
, f
)
4520 for value
, arg
in enumerate(args
):
4521 f
.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4522 (arg
.type, value
+ 11, arg
.name
))
4523 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
4524 f
.write(" next_cmd, sizeof(cmd));\n")
4528 def WriteImmediateFormatTest(self
, func
, f
):
4529 """Writes a format test for an immediate version of a command."""
4532 def WriteGetDataSizeCode(self
, func
, f
):
4533 """Writes the code to set data_size used in validation"""
4536 def __WriteIdMapping(self
, func
, f
):
4537 """Writes client side / service side ID mapping."""
4538 if not func
.IsUnsafe() or not func
.GetInfo('id_mapping'):
4540 for id_type
in func
.GetInfo('id_mapping'):
4541 f
.write(" group_->Get%sServiceId(%s, &%s);\n" %
4542 (id_type
, id_type
.lower(), id_type
.lower()))
4544 def WriteImmediateHandlerImplementation (self
, func
, f
):
4545 """Writes the handler impl for the immediate version of a command."""
4546 self
.__WriteIdMapping
(func
, f
)
4547 f
.write(" %s(%s);\n" %
4548 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4550 def WriteBucketHandlerImplementation (self
, func
, f
):
4551 """Writes the handler impl for the bucket version of a command."""
4552 self
.__WriteIdMapping
(func
, f
)
4553 f
.write(" %s(%s);\n" %
4554 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
4556 def WriteServiceHandlerFunctionHeader(self
, func
, f
):
4557 """Writes function header for service implementation handlers."""
4558 f
.write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4559 uint32_t immediate_data_size, const void* cmd_data) {
4560 """ % {'name': func
.name
})
4562 f
.write("""if (!unsafe_es3_apis_enabled())
4563 return error::kUnknownCommand;
4565 f
.write("""const gles2::cmds::%(name)s& c =
4566 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4568 """ % {'name': func
.name
})
4570 def WriteServiceImplementation(self
, func
, f
):
4571 """Writes the service implementation for a command."""
4572 self
.WriteServiceHandlerFunctionHeader(func
, f
)
4573 self
.WriteHandlerExtensionCheck(func
, f
)
4574 self
.WriteHandlerDeferReadWrite(func
, f
);
4575 if len(func
.GetOriginalArgs()) > 0:
4576 last_arg
= func
.GetLastOriginalArg()
4577 all_but_last_arg
= func
.GetOriginalArgs()[:-1]
4578 for arg
in all_but_last_arg
:
4580 self
.WriteGetDataSizeCode(func
, f
)
4581 last_arg
.WriteGetCode(f
)
4582 func
.WriteHandlerValidation(f
)
4583 func
.WriteHandlerImplementation(f
)
4584 f
.write(" return error::kNoError;\n")
4588 def WriteImmediateServiceImplementation(self
, func
, f
):
4589 """Writes the service implementation for an immediate version of command."""
4590 self
.WriteServiceHandlerFunctionHeader(func
, f
)
4591 self
.WriteHandlerExtensionCheck(func
, f
)
4592 self
.WriteHandlerDeferReadWrite(func
, f
);
4593 for arg
in func
.GetOriginalArgs():
4595 self
.WriteGetDataSizeCode(func
, f
)
4597 func
.WriteHandlerValidation(f
)
4598 func
.WriteHandlerImplementation(f
)
4599 f
.write(" return error::kNoError;\n")
4603 def WriteBucketServiceImplementation(self
, func
, f
):
4604 """Writes the service implementation for a bucket version of command."""
4605 self
.WriteServiceHandlerFunctionHeader(func
, f
)
4606 self
.WriteHandlerExtensionCheck(func
, f
)
4607 self
.WriteHandlerDeferReadWrite(func
, f
);
4608 for arg
in func
.GetCmdArgs():
4610 func
.WriteHandlerValidation(f
)
4611 func
.WriteHandlerImplementation(f
)
4612 f
.write(" return error::kNoError;\n")
4616 def WriteHandlerExtensionCheck(self
, func
, f
):
4617 if func
.GetInfo('extension_flag'):
4618 f
.write(" if (!features().%s) {\n" % func
.GetInfo('extension_flag'))
4619 f
.write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4620 " \"function not available\");\n" % func
.original_name
)
4621 f
.write(" return error::kNoError;")
4624 def WriteHandlerDeferReadWrite(self
, func
, f
):
4625 """Writes the code to handle deferring reads or writes."""
4626 defer_draws
= func
.GetInfo('defer_draws')
4627 defer_reads
= func
.GetInfo('defer_reads')
4628 if defer_draws
or defer_reads
:
4629 f
.write(" error::Error error;\n")
4631 f
.write(" error = WillAccessBoundFramebufferForDraw();\n")
4632 f
.write(" if (error != error::kNoError)\n")
4633 f
.write(" return error;\n")
4635 f
.write(" error = WillAccessBoundFramebufferForRead();\n")
4636 f
.write(" if (error != error::kNoError)\n")
4637 f
.write(" return error;\n")
4639 def WriteValidUnitTest(self
, func
, f
, test
, *extras
):
4640 """Writes a valid unit test for the service implementation."""
4641 if func
.GetInfo('expectation') == False:
4642 test
= self
._remove
_expected
_call
_re
.sub('', test
)
4645 arg
.GetValidArg(func
) \
4646 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
4649 arg
.GetValidGLArg(func
) \
4650 for arg
in func
.GetOriginalArgs()
4652 gl_func_name
= func
.GetGLTestFunctionName()
4655 'gl_func_name': gl_func_name
,
4656 'args': ", ".join(arg_strings
),
4657 'gl_args': ", ".join(gl_arg_strings
),
4659 for extra
in extras
:
4662 while (old_test
!= test
):
4665 f
.write(test
% vars)
4667 def WriteInvalidUnitTest(self
, func
, f
, test
, *extras
):
4668 """Writes an invalid unit test for the service implementation."""
4671 for invalid_arg_index
, invalid_arg
in enumerate(func
.GetOriginalArgs()):
4672 # Service implementation does not test constants, as they are not part of
4673 # the call in the service side.
4674 if invalid_arg
.IsConstant():
4677 num_invalid_values
= invalid_arg
.GetNumInvalidValues(func
)
4678 for value_index
in range(0, num_invalid_values
):
4680 parse_result
= "kNoError"
4682 for arg
in func
.GetOriginalArgs():
4683 if arg
.IsConstant():
4685 if invalid_arg
is arg
:
4686 (arg_string
, parse_result
, gl_error
) = arg
.GetInvalidArg(
4689 arg_string
= arg
.GetValidArg(func
)
4690 arg_strings
.append(arg_string
)
4692 for arg
in func
.GetOriginalArgs():
4693 gl_arg_strings
.append("_")
4694 gl_func_name
= func
.GetGLTestFunctionName()
4696 if not gl_error
== None:
4697 gl_error_test
= '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4701 'arg_index': invalid_arg_index
,
4702 'value_index': value_index
,
4703 'gl_func_name': gl_func_name
,
4704 'args': ", ".join(arg_strings
),
4705 'all_but_last_args': ", ".join(arg_strings
[:-1]),
4706 'gl_args': ", ".join(gl_arg_strings
),
4707 'parse_result': parse_result
,
4708 'gl_error_test': gl_error_test
,
4710 for extra
in extras
:
4712 f
.write(test
% vars)
4714 def WriteServiceUnitTest(self
, func
, f
, *extras
):
4715 """Writes the service unit test for a command."""
4717 if func
.name
== 'Enable':
4719 TEST_P(%(test_name)s, %(name)sValidArgs) {
4720 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4721 SpecializedSetup<cmds::%(name)s, 0>(true);
4723 cmd.Init(%(args)s);"""
4724 elif func
.name
== 'Disable':
4726 TEST_P(%(test_name)s, %(name)sValidArgs) {
4727 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4728 SpecializedSetup<cmds::%(name)s, 0>(true);
4730 cmd.Init(%(args)s);"""
4733 TEST_P(%(test_name)s, %(name)sValidArgs) {
4734 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4735 SpecializedSetup<cmds::%(name)s, 0>(true);
4737 cmd.Init(%(args)s);"""
4740 decoder_->set_unsafe_es3_apis_enabled(true);
4741 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4742 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4743 decoder_->set_unsafe_es3_apis_enabled(false);
4744 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4749 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4750 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4753 self
.WriteValidUnitTest(func
, f
, valid_test
, *extras
)
4755 if not func
.IsUnsafe():
4757 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4758 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4759 SpecializedSetup<cmds::%(name)s, 0>(false);
4762 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4765 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, *extras
)
4767 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
4768 """Writes the service unit test for an immediate command."""
4769 f
.write("// TODO(gman): %s\n" % func
.name
)
4771 def WriteImmediateValidationCode(self
, func
, f
):
4772 """Writes the validation code for an immediate version of a command."""
4775 def WriteBucketServiceUnitTest(self
, func
, f
, *extras
):
4776 """Writes the service unit test for a bucket command."""
4777 f
.write("// TODO(gman): %s\n" % func
.name
)
4779 def WriteGLES2ImplementationDeclaration(self
, func
, f
):
4780 """Writes the GLES2 Implemention declaration."""
4781 impl_decl
= func
.GetInfo('impl_decl')
4782 if impl_decl
== None or impl_decl
== True:
4783 f
.write("%s %s(%s) override;\n" %
4784 (func
.return_type
, func
.original_name
,
4785 func
.MakeTypedOriginalArgString("")))
4788 def WriteGLES2CLibImplementation(self
, func
, f
):
4789 f
.write("%s GL_APIENTRY GLES2%s(%s) {\n" %
4790 (func
.return_type
, func
.name
,
4791 func
.MakeTypedOriginalArgString("")))
4792 result_string
= "return "
4793 if func
.return_type
== "void":
4795 f
.write(" %sgles2::GetGLContext()->%s(%s);\n" %
4796 (result_string
, func
.original_name
,
4797 func
.MakeOriginalArgString("")))
4800 def WriteGLES2Header(self
, func
, f
):
4801 """Writes a re-write macro for GLES"""
4802 f
.write("#define gl%s GLES2_GET_FUN(%s)\n" %(func
.name
, func
.name
))
4804 def WriteClientGLCallLog(self
, func
, f
):
4805 """Writes a logging macro for the client side code."""
4807 if len(func
.GetOriginalArgs()):
4810 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4811 (func
.original_name
, comma
, func
.MakeLogArgString()))
4813 def WriteClientGLReturnLog(self
, func
, f
):
4814 """Writes the return value logging code."""
4815 if func
.return_type
!= "void":
4816 f
.write(' GPU_CLIENT_LOG("return:" << result)\n')
4818 def WriteGLES2ImplementationHeader(self
, func
, f
):
4819 """Writes the GLES2 Implemention."""
4820 self
.WriteGLES2ImplementationDeclaration(func
, f
)
4822 def WriteGLES2TraceImplementationHeader(self
, func
, f
):
4823 """Writes the GLES2 Trace Implemention header."""
4824 f
.write("%s %s(%s) override;\n" %
4825 (func
.return_type
, func
.original_name
,
4826 func
.MakeTypedOriginalArgString("")))
4828 def WriteGLES2TraceImplementation(self
, func
, f
):
4829 """Writes the GLES2 Trace Implemention."""
4830 f
.write("%s GLES2TraceImplementation::%s(%s) {\n" %
4831 (func
.return_type
, func
.original_name
,
4832 func
.MakeTypedOriginalArgString("")))
4833 result_string
= "return "
4834 if func
.return_type
== "void":
4836 f
.write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4838 f
.write(" %sgl_->%s(%s);\n" %
4839 (result_string
, func
.name
, func
.MakeOriginalArgString("")))
4843 def WriteGLES2Implementation(self
, func
, f
):
4844 """Writes the GLES2 Implemention."""
4845 impl_func
= func
.GetInfo('impl_func')
4846 impl_decl
= func
.GetInfo('impl_decl')
4847 gen_cmd
= func
.GetInfo('gen_cmd')
4848 if (func
.can_auto_generate
and
4849 (impl_func
== None or impl_func
== True) and
4850 (impl_decl
== None or impl_decl
== True) and
4851 (gen_cmd
== None or gen_cmd
== True)):
4852 f
.write("%s GLES2Implementation::%s(%s) {\n" %
4853 (func
.return_type
, func
.original_name
,
4854 func
.MakeTypedOriginalArgString("")))
4855 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4856 self
.WriteClientGLCallLog(func
, f
)
4857 func
.WriteDestinationInitalizationValidation(f
)
4858 for arg
in func
.GetOriginalArgs():
4859 arg
.WriteClientSideValidationCode(f
, func
)
4860 f
.write(" helper_->%s(%s);\n" %
4861 (func
.name
, func
.MakeHelperArgString("")))
4862 f
.write(" CheckGLError();\n")
4863 self
.WriteClientGLReturnLog(func
, f
)
4867 def WriteGLES2InterfaceHeader(self
, func
, f
):
4868 """Writes the GLES2 Interface."""
4869 f
.write("virtual %s %s(%s) = 0;\n" %
4870 (func
.return_type
, func
.original_name
,
4871 func
.MakeTypedOriginalArgString("")))
4873 def WriteMojoGLES2ImplHeader(self
, func
, f
):
4874 """Writes the Mojo GLES2 implementation header."""
4875 f
.write("%s %s(%s) override;\n" %
4876 (func
.return_type
, func
.original_name
,
4877 func
.MakeTypedOriginalArgString("")))
4879 def WriteMojoGLES2Impl(self
, func
, f
):
4880 """Writes the Mojo GLES2 implementation."""
4881 f
.write("%s MojoGLES2Impl::%s(%s) {\n" %
4882 (func
.return_type
, func
.original_name
,
4883 func
.MakeTypedOriginalArgString("")))
4884 extensions
= ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4885 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4886 "occlusion_query_EXT", "CHROMIUM_image",
4887 "CHROMIUM_copy_texture",
4888 "CHROMIUM_pixel_transfer_buffer_object"]
4889 if func
.IsCoreGLFunction() or func
.GetInfo("extension") in extensions
:
4890 f
.write("MojoGLES2MakeCurrent(context_);");
4891 func_return
= "gl" + func
.original_name
+ "(" + \
4892 func
.MakeOriginalArgString("") + ");"
4893 if func
.return_type
== "void":
4894 f
.write(func_return
);
4896 f
.write("return " + func_return
);
4898 f
.write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4899 func
.original_name
);
4900 if func
.return_type
!= "void":
4901 f
.write("return 0;")
4904 def WriteGLES2InterfaceStub(self
, func
, f
):
4905 """Writes the GLES2 Interface stub declaration."""
4906 f
.write("%s %s(%s) override;\n" %
4907 (func
.return_type
, func
.original_name
,
4908 func
.MakeTypedOriginalArgString("")))
4910 def WriteGLES2InterfaceStubImpl(self
, func
, f
):
4911 """Writes the GLES2 Interface stub declaration."""
4912 args
= func
.GetOriginalArgs()
4913 arg_string
= ", ".join(
4914 ["%s /* %s */" % (arg
.type, arg
.name
) for arg
in args
])
4915 f
.write("%s GLES2InterfaceStub::%s(%s) {\n" %
4916 (func
.return_type
, func
.original_name
, arg_string
))
4917 if func
.return_type
!= "void":
4918 f
.write(" return 0;\n")
4921 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
4922 """Writes the GLES2 Implemention unit test."""
4923 client_test
= func
.GetInfo('client_test')
4924 if (func
.can_auto_generate
and
4925 (client_test
== None or client_test
== True)):
4927 TEST_F(GLES2ImplementationTest, %(name)s) {
4932 expected.cmd.Init(%(cmd_args)s);
4934 gl_->%(name)s(%(args)s);
4935 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4939 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
4943 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
4948 'args': ", ".join(gl_arg_strings
),
4949 'cmd_args': ", ".join(cmd_arg_strings
),
4952 # Test constants for invalid values, as they are not tested by the
4954 constants
= [arg
for arg
in func
.GetOriginalArgs() if arg
.IsConstant()]
4957 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4958 gl_->%(name)s(%(args)s);
4959 EXPECT_TRUE(NoCommandsWritten());
4960 EXPECT_EQ(%(gl_error)s, CheckError());
4963 for invalid_arg
in constants
:
4965 invalid
= invalid_arg
.GetInvalidArg(func
)
4966 for arg
in func
.GetOriginalArgs():
4967 if arg
is invalid_arg
:
4968 gl_arg_strings
.append(invalid
[0])
4970 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
4974 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
4975 'args': ", ".join(gl_arg_strings
),
4976 'gl_error': invalid
[2],
4979 if client_test
!= False:
4980 f
.write("// TODO(zmo): Implement unit test for %s\n" % func
.name
)
4982 def WriteDestinationInitalizationValidation(self
, func
, f
):
4983 """Writes the client side destintion initialization validation."""
4984 for arg
in func
.GetOriginalArgs():
4985 arg
.WriteDestinationInitalizationValidation(f
, func
)
4987 def WriteTraceEvent(self
, func
, f
):
4988 f
.write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4991 def WriteImmediateCmdComputeSize(self
, func
, f
):
4992 """Writes the size computation code for the immediate version of a cmd."""
4993 f
.write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4994 f
.write(" return static_cast<uint32_t>(\n")
4995 f
.write(" sizeof(ValueType) + // NOLINT\n")
4996 f
.write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
5000 def WriteImmediateCmdSetHeader(self
, func
, f
):
5001 """Writes the SetHeader function for the immediate version of a cmd."""
5002 f
.write(" void SetHeader(uint32_t size_in_bytes) {\n")
5003 f
.write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
5007 def WriteImmediateCmdInit(self
, func
, f
):
5008 """Writes the Init function for the immediate version of a command."""
5009 raise NotImplementedError(func
.name
)
5011 def WriteImmediateCmdSet(self
, func
, f
):
5012 """Writes the Set function for the immediate version of a command."""
5013 raise NotImplementedError(func
.name
)
5015 def WriteCmdHelper(self
, func
, f
):
5016 """Writes the cmd helper definition for a cmd."""
5017 code
= """ void %(name)s(%(typed_args)s) {
5018 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
5027 "typed_args": func
.MakeTypedCmdArgString(""),
5028 "args": func
.MakeCmdArgString(""),
5031 def WriteImmediateCmdHelper(self
, func
, f
):
5032 """Writes the cmd helper definition for the immediate version of a cmd."""
5033 code
= """ void %(name)s(%(typed_args)s) {
5034 const uint32_t s = 0; // TODO(gman): compute correct size
5035 gles2::cmds::%(name)s* c =
5036 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
5045 "typed_args": func
.MakeTypedCmdArgString(""),
5046 "args": func
.MakeCmdArgString(""),
5050 class StateSetHandler(TypeHandler
):
5051 """Handler for commands that simply set state."""
5053 def WriteHandlerImplementation(self
, func
, f
):
5054 """Overrriden from TypeHandler."""
5055 state_name
= func
.GetInfo('state')
5056 state
= _STATES
[state_name
]
5057 states
= state
['states']
5058 args
= func
.GetOriginalArgs()
5059 for ndx
,item
in enumerate(states
):
5061 if 'range_checks' in item
:
5062 for range_check
in item
['range_checks']:
5063 code
.append("%s %s" % (args
[ndx
].name
, range_check
['check']))
5064 if 'nan_check' in item
:
5065 # Drivers might generate an INVALID_VALUE error when a value is set
5066 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
5067 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
5068 # Make this behavior consistent within Chromium, and avoid leaking GL
5069 # errors by generating the error in the command buffer instead of
5070 # letting the GL driver generate it.
5071 code
.append("std::isnan(%s)" % args
[ndx
].name
)
5073 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5075 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
5076 ' "%s", "%s out of range");\n' %
5077 (func
.name
, args
[ndx
].name
))
5078 f
.write(" return error::kNoError;\n")
5081 for ndx
,item
in enumerate(states
):
5082 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
5083 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5084 for ndx
,item
in enumerate(states
):
5085 f
.write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
5086 if 'state_flag' in state
:
5087 f
.write(" %s = true;\n" % state
['state_flag'])
5088 if not func
.GetInfo("no_gl"):
5089 for ndx
,item
in enumerate(states
):
5090 if item
.get('cached', False):
5091 f
.write(" state_.%s = %s;\n" %
5092 (CachedStateName(item
), args
[ndx
].name
))
5093 f
.write(" %s(%s);\n" %
5094 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5097 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5098 """Overrriden from TypeHandler."""
5099 TypeHandler
.WriteServiceUnitTest(self
, func
, f
, *extras
)
5100 state_name
= func
.GetInfo('state')
5101 state
= _STATES
[state_name
]
5102 states
= state
['states']
5103 for ndx
,item
in enumerate(states
):
5104 if 'range_checks' in item
:
5105 for check_ndx
, range_check
in enumerate(item
['range_checks']):
5107 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
5108 SpecializedSetup<cmds::%(name)s, 0>(false);
5111 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5112 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5117 arg
.GetValidArg(func
) \
5118 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
5121 arg_strings
[ndx
] = range_check
['test_value']
5125 'check_ndx': check_ndx
,
5126 'args': ", ".join(arg_strings
),
5128 for extra
in extras
:
5130 f
.write(valid_test
% vars)
5131 if 'nan_check' in item
:
5133 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
5134 SpecializedSetup<cmds::%(name)s, 0>(false);
5137 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5138 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5143 arg
.GetValidArg(func
) \
5144 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()
5147 arg_strings
[ndx
] = 'nanf("")'
5151 'args': ", ".join(arg_strings
),
5153 for extra
in extras
:
5155 f
.write(valid_test
% vars)
5158 class StateSetRGBAlphaHandler(TypeHandler
):
5159 """Handler for commands that simply set state that have rgb/alpha."""
5161 def WriteHandlerImplementation(self
, func
, f
):
5162 """Overrriden from TypeHandler."""
5163 state_name
= func
.GetInfo('state')
5164 state
= _STATES
[state_name
]
5165 states
= state
['states']
5166 args
= func
.GetOriginalArgs()
5167 num_args
= len(args
)
5169 for ndx
,item
in enumerate(states
):
5170 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
% num_args
].name
))
5171 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5172 for ndx
, item
in enumerate(states
):
5173 f
.write(" state_.%s = %s;\n" %
5174 (item
['name'], args
[ndx
% num_args
].name
))
5175 if 'state_flag' in state
:
5176 f
.write(" %s = true;\n" % state
['state_flag'])
5177 if not func
.GetInfo("no_gl"):
5178 f
.write(" %s(%s);\n" %
5179 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5183 class StateSetFrontBackSeparateHandler(TypeHandler
):
5184 """Handler for commands that simply set state that have front/back."""
5186 def WriteHandlerImplementation(self
, func
, f
):
5187 """Overrriden from TypeHandler."""
5188 state_name
= func
.GetInfo('state')
5189 state
= _STATES
[state_name
]
5190 states
= state
['states']
5191 args
= func
.GetOriginalArgs()
5193 num_args
= len(args
)
5194 f
.write(" bool changed = false;\n")
5195 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
5196 f
.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5197 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
5199 for ndx
, item
in enumerate(group
):
5200 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
+ 1].name
))
5201 f
.write(" changed |= %s;\n" % " ||\n ".join(code
))
5203 f
.write(" if (changed) {\n")
5204 for group_ndx
, group
in enumerate(Grouper(num_args
- 1, states
)):
5205 f
.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5206 (face
, ('GL_FRONT', 'GL_BACK')[group_ndx
], face
))
5207 for ndx
, item
in enumerate(group
):
5208 f
.write(" state_.%s = %s;\n" %
5209 (item
['name'], args
[ndx
+ 1].name
))
5211 if 'state_flag' in state
:
5212 f
.write(" %s = true;\n" % state
['state_flag'])
5213 if not func
.GetInfo("no_gl"):
5214 f
.write(" %s(%s);\n" %
5215 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5219 class StateSetFrontBackHandler(TypeHandler
):
5220 """Handler for commands that simply set state that set both front/back."""
5222 def WriteHandlerImplementation(self
, func
, f
):
5223 """Overrriden from TypeHandler."""
5224 state_name
= func
.GetInfo('state')
5225 state
= _STATES
[state_name
]
5226 states
= state
['states']
5227 args
= func
.GetOriginalArgs()
5228 num_args
= len(args
)
5230 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
5231 for ndx
, item
in enumerate(group
):
5232 code
.append("state_.%s != %s" % (item
['name'], args
[ndx
].name
))
5233 f
.write(" if (%s) {\n" % " ||\n ".join(code
))
5234 for group_ndx
, group
in enumerate(Grouper(num_args
, states
)):
5235 for ndx
, item
in enumerate(group
):
5236 f
.write(" state_.%s = %s;\n" % (item
['name'], args
[ndx
].name
))
5237 if 'state_flag' in state
:
5238 f
.write(" %s = true;\n" % state
['state_flag'])
5239 if not func
.GetInfo("no_gl"):
5240 f
.write(" %s(%s);\n" %
5241 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5245 class StateSetNamedParameter(TypeHandler
):
5246 """Handler for commands that set a state chosen with an enum parameter."""
5248 def WriteHandlerImplementation(self
, func
, f
):
5249 """Overridden from TypeHandler."""
5250 state_name
= func
.GetInfo('state')
5251 state
= _STATES
[state_name
]
5252 states
= state
['states']
5253 args
= func
.GetOriginalArgs()
5254 num_args
= len(args
)
5255 assert num_args
== 2
5256 f
.write(" switch (%s) {\n" % args
[0].name
)
5257 for state
in states
:
5258 f
.write(" case %s:\n" % state
['enum'])
5259 f
.write(" if (state_.%s != %s) {\n" %
5260 (state
['name'], args
[1].name
))
5261 f
.write(" state_.%s = %s;\n" % (state
['name'], args
[1].name
))
5262 if not func
.GetInfo("no_gl"):
5263 f
.write(" %s(%s);\n" %
5264 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
5266 f
.write(" break;\n")
5267 f
.write(" default:\n")
5268 f
.write(" NOTREACHED();\n")
5272 class CustomHandler(TypeHandler
):
5273 """Handler for commands that are auto-generated but require minor tweaks."""
5275 def WriteServiceImplementation(self
, func
, f
):
5276 """Overrriden from TypeHandler."""
5279 def WriteImmediateServiceImplementation(self
, func
, f
):
5280 """Overrriden from TypeHandler."""
5283 def WriteBucketServiceImplementation(self
, func
, f
):
5284 """Overrriden from TypeHandler."""
5287 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5288 """Overrriden from TypeHandler."""
5289 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5291 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5292 """Overrriden from TypeHandler."""
5293 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5295 def WriteImmediateCmdGetTotalSize(self
, func
, f
):
5296 """Overrriden from TypeHandler."""
5298 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5300 def WriteImmediateCmdInit(self
, func
, f
):
5301 """Overrriden from TypeHandler."""
5302 f
.write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5303 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5304 f
.write(" SetHeader(total_size);\n")
5305 args
= func
.GetCmdArgs()
5307 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5311 def WriteImmediateCmdSet(self
, func
, f
):
5312 """Overrriden from TypeHandler."""
5313 copy_args
= func
.MakeCmdArgString("_", False)
5314 f
.write(" void* Set(void* cmd%s) {\n" %
5315 func
.MakeTypedCmdArgString("_", True))
5316 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5317 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5318 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5319 "cmd, total_size);\n")
5324 class HandWrittenHandler(CustomHandler
):
5325 """Handler for comands where everything must be written by hand."""
5327 def InitFunction(self
, func
):
5328 """Add or adjust anything type specific for this function."""
5329 CustomHandler
.InitFunction(self
, func
)
5330 func
.can_auto_generate
= False
5332 def NeedsDataTransferFunction(self
, func
):
5333 """Overriden from TypeHandler."""
5334 # If specified explicitly, force the data transfer method.
5335 if func
.GetInfo('data_transfer_methods'):
5339 def WriteStruct(self
, func
, f
):
5340 """Overrriden from TypeHandler."""
5343 def WriteDocs(self
, func
, f
):
5344 """Overrriden from TypeHandler."""
5347 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5348 """Overrriden from TypeHandler."""
5349 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5351 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5352 """Overrriden from TypeHandler."""
5353 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5355 def WriteBucketServiceUnitTest(self
, func
, f
, *extras
):
5356 """Overrriden from TypeHandler."""
5357 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5359 def WriteServiceImplementation(self
, func
, f
):
5360 """Overrriden from TypeHandler."""
5363 def WriteImmediateServiceImplementation(self
, func
, f
):
5364 """Overrriden from TypeHandler."""
5367 def WriteBucketServiceImplementation(self
, func
, f
):
5368 """Overrriden from TypeHandler."""
5371 def WriteImmediateCmdHelper(self
, func
, f
):
5372 """Overrriden from TypeHandler."""
5375 def WriteCmdHelper(self
, func
, f
):
5376 """Overrriden from TypeHandler."""
5379 def WriteFormatTest(self
, func
, f
):
5380 """Overrriden from TypeHandler."""
5381 f
.write("// TODO(gman): Write test for %s\n" % func
.name
)
5383 def WriteImmediateFormatTest(self
, func
, f
):
5384 """Overrriden from TypeHandler."""
5385 f
.write("// TODO(gman): Write test for %s\n" % func
.name
)
5388 class ManualHandler(CustomHandler
):
5389 """Handler for commands who's handlers must be written by hand."""
5391 def InitFunction(self
, func
):
5392 """Overrriden from TypeHandler."""
5393 if (func
.name
== 'CompressedTexImage2DBucket' or
5394 func
.name
== 'CompressedTexImage3DBucket'):
5395 func
.cmd_args
= func
.cmd_args
[:-1]
5396 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5398 CustomHandler
.InitFunction(self
, func
)
5400 def WriteServiceImplementation(self
, func
, f
):
5401 """Overrriden from TypeHandler."""
5404 def WriteBucketServiceImplementation(self
, func
, f
):
5405 """Overrriden from TypeHandler."""
5408 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5409 """Overrriden from TypeHandler."""
5410 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5412 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5413 """Overrriden from TypeHandler."""
5414 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5416 def WriteImmediateServiceImplementation(self
, func
, f
):
5417 """Overrriden from TypeHandler."""
5420 def WriteImmediateFormatTest(self
, func
, f
):
5421 """Overrriden from TypeHandler."""
5422 f
.write("// TODO(gman): Implement test for %s\n" % func
.name
)
5424 def WriteGLES2Implementation(self
, func
, f
):
5425 """Overrriden from TypeHandler."""
5426 if func
.GetInfo('impl_func'):
5427 super(ManualHandler
, self
).WriteGLES2Implementation(func
, f
)
5429 def WriteGLES2ImplementationHeader(self
, func
, f
):
5430 """Overrriden from TypeHandler."""
5431 f
.write("%s %s(%s) override;\n" %
5432 (func
.return_type
, func
.original_name
,
5433 func
.MakeTypedOriginalArgString("")))
5436 def WriteImmediateCmdGetTotalSize(self
, func
, f
):
5437 """Overrriden from TypeHandler."""
5438 # TODO(gman): Move this data to _FUNCTION_INFO?
5439 CustomHandler
.WriteImmediateCmdGetTotalSize(self
, func
, f
)
5442 class DataHandler(TypeHandler
):
5443 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5444 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5446 def InitFunction(self
, func
):
5447 """Overrriden from TypeHandler."""
5448 if (func
.name
== 'CompressedTexSubImage2DBucket' or
5449 func
.name
== 'CompressedTexSubImage3DBucket'):
5450 func
.cmd_args
= func
.cmd_args
[:-1]
5451 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
5453 def WriteGetDataSizeCode(self
, func
, f
):
5454 """Overrriden from TypeHandler."""
5455 # TODO(gman): Move this data to _FUNCTION_INFO?
5457 if name
.endswith("Immediate"):
5459 if name
== 'BufferData' or name
== 'BufferSubData':
5460 f
.write(" uint32_t data_size = size;\n")
5461 elif (name
== 'CompressedTexImage2D' or
5462 name
== 'CompressedTexSubImage2D' or
5463 name
== 'CompressedTexImage3D' or
5464 name
== 'CompressedTexSubImage3D'):
5465 f
.write(" uint32_t data_size = imageSize;\n")
5466 elif (name
== 'CompressedTexSubImage2DBucket' or
5467 name
== 'CompressedTexSubImage3DBucket'):
5468 f
.write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5469 f
.write(" uint32_t data_size = bucket->size();\n")
5470 f
.write(" GLsizei imageSize = data_size;\n")
5471 elif name
== 'TexImage2D' or name
== 'TexSubImage2D':
5472 code
= """ uint32_t data_size;
5473 if (!GLES2Util::ComputeImageDataSize(
5474 width, height, format, type, unpack_alignment_, &data_size)) {
5475 return error::kOutOfBounds;
5481 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5483 def WriteImmediateCmdGetTotalSize(self
, func
, f
):
5484 """Overrriden from TypeHandler."""
5487 def WriteImmediateCmdInit(self
, func
, f
):
5488 """Overrriden from TypeHandler."""
5489 f
.write(" void Init(%s) {\n" % func
.MakeTypedCmdArgString("_"))
5490 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5491 f
.write(" SetHeader(total_size);\n")
5492 args
= func
.GetCmdArgs()
5494 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5498 def WriteImmediateCmdSet(self
, func
, f
):
5499 """Overrriden from TypeHandler."""
5500 copy_args
= func
.MakeCmdArgString("_", False)
5501 f
.write(" void* Set(void* cmd%s) {\n" %
5502 func
.MakeTypedCmdArgString("_", True))
5503 self
.WriteImmediateCmdGetTotalSize(func
, f
)
5504 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
5505 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5506 "cmd, total_size);\n")
5510 def WriteImmediateFormatTest(self
, func
, f
):
5511 """Overrriden from TypeHandler."""
5512 # TODO(gman): Remove this exception.
5513 f
.write("// TODO(gman): Implement test for %s\n" % func
.name
)
5516 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5517 """Overrriden from TypeHandler."""
5518 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5520 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5521 """Overrriden from TypeHandler."""
5522 f
.write("// TODO(gman): %s\n\n" % func
.name
)
5524 def WriteBucketServiceImplementation(self
, func
, f
):
5525 """Overrriden from TypeHandler."""
5526 if ((not func
.name
== 'CompressedTexSubImage2DBucket') and
5527 (not func
.name
== 'CompressedTexSubImage3DBucket')):
5528 TypeHandler
.WriteBucketServiceImplemenation(self
, func
, f
)
5531 class BindHandler(TypeHandler
):
5532 """Handler for glBind___ type functions."""
5534 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5535 """Overrriden from TypeHandler."""
5537 if len(func
.GetOriginalArgs()) == 1:
5539 TEST_P(%(test_name)s, %(name)sValidArgs) {
5540 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5541 SpecializedSetup<cmds::%(name)s, 0>(true);
5543 cmd.Init(%(args)s);"""
5546 decoder_->set_unsafe_es3_apis_enabled(true);
5547 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5548 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5549 decoder_->set_unsafe_es3_apis_enabled(false);
5550 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5555 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5556 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5559 if func
.GetInfo("gen_func"):
5561 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5562 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5563 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5564 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5565 SpecializedSetup<cmds::%(name)s, 0>(true);
5567 cmd.Init(kNewClientId);
5568 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5569 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5570 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5573 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5574 'resource_type': func
.GetOriginalArgs()[0].resource_type
,
5575 'gl_gen_func_name': func
.GetInfo("gen_func"),
5579 TEST_P(%(test_name)s, %(name)sValidArgs) {
5580 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5581 SpecializedSetup<cmds::%(name)s, 0>(true);
5583 cmd.Init(%(args)s);"""
5586 decoder_->set_unsafe_es3_apis_enabled(true);
5587 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5588 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5589 decoder_->set_unsafe_es3_apis_enabled(false);
5590 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5595 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5596 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5599 if func
.GetInfo("gen_func"):
5601 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5603 %(gl_func_name)s(%(gl_args_with_new_id)s));
5604 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5605 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5606 SpecializedSetup<cmds::%(name)s, 0>(true);
5608 cmd.Init(%(args_with_new_id)s);"""
5611 decoder_->set_unsafe_es3_apis_enabled(true);
5612 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5613 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5614 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5615 decoder_->set_unsafe_es3_apis_enabled(false);
5616 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5621 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5622 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5623 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5627 gl_args_with_new_id
= []
5628 args_with_new_id
= []
5629 for arg
in func
.GetOriginalArgs():
5630 if hasattr(arg
, 'resource_type'):
5631 gl_args_with_new_id
.append('kNewServiceId')
5632 args_with_new_id
.append('kNewClientId')
5634 gl_args_with_new_id
.append(arg
.GetValidGLArg(func
))
5635 args_with_new_id
.append(arg
.GetValidArg(func
))
5636 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5637 'args_with_new_id': ", ".join(args_with_new_id
),
5638 'gl_args_with_new_id': ", ".join(gl_args_with_new_id
),
5639 'resource_type': func
.GetResourceIdArg().resource_type
,
5640 'gl_gen_func_name': func
.GetInfo("gen_func"),
5644 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5645 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5646 SpecializedSetup<cmds::%(name)s, 0>(false);
5649 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5652 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, *extras
)
5654 def WriteGLES2Implementation(self
, func
, f
):
5655 """Writes the GLES2 Implemention."""
5657 impl_func
= func
.GetInfo('impl_func')
5658 impl_decl
= func
.GetInfo('impl_decl')
5660 if (func
.can_auto_generate
and
5661 (impl_func
== None or impl_func
== True) and
5662 (impl_decl
== None or impl_decl
== True)):
5664 f
.write("%s GLES2Implementation::%s(%s) {\n" %
5665 (func
.return_type
, func
.original_name
,
5666 func
.MakeTypedOriginalArgString("")))
5667 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5668 func
.WriteDestinationInitalizationValidation(f
)
5669 self
.WriteClientGLCallLog(func
, f
)
5670 for arg
in func
.GetOriginalArgs():
5671 arg
.WriteClientSideValidationCode(f
, func
)
5673 code
= """ if (Is%(type)sReservedId(%(id)s)) {
5674 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5677 %(name)sHelper(%(arg_string)s);
5682 name_arg
= func
.GetResourceIdArg()
5685 'arg_string': func
.MakeOriginalArgString(""),
5686 'id': name_arg
.name
,
5687 'type': name_arg
.resource_type
,
5688 'lc_type': name_arg
.resource_type
.lower(),
5691 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
5692 """Overrriden from TypeHandler."""
5693 client_test
= func
.GetInfo('client_test')
5694 if client_test
== False:
5697 TEST_F(GLES2ImplementationTest, %(name)s) {
5702 expected.cmd.Init(%(cmd_args)s);
5704 gl_->%(name)s(%(args)s);
5705 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5706 if not func
.IsUnsafe():
5709 gl_->%(name)s(%(args)s);
5710 EXPECT_TRUE(NoCommandsWritten());"""
5715 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()
5718 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()
5723 'args': ", ".join(gl_arg_strings
),
5724 'cmd_args': ", ".join(cmd_arg_strings
),
5728 class GENnHandler(TypeHandler
):
5729 """Handler for glGen___ type functions."""
5731 def InitFunction(self
, func
):
5732 """Overrriden from TypeHandler."""
5735 def WriteGetDataSizeCode(self
, func
, f
):
5736 """Overrriden from TypeHandler."""
5737 code
= """ uint32_t data_size;
5738 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5739 return error::kOutOfBounds;
5744 def WriteHandlerImplementation (self
, func
, f
):
5745 """Overrriden from TypeHandler."""
5746 f
.write(" if (!%sHelper(n, %s)) {\n"
5747 " return error::kInvalidArguments;\n"
5749 (func
.name
, func
.GetLastOriginalArg().name
))
5751 def WriteImmediateHandlerImplementation(self
, func
, f
):
5752 """Overrriden from TypeHandler."""
5754 f
.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5755 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5756 return error::kInvalidArguments;
5759 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5760 gl%(func_name)s(n, service_ids.get());
5761 for (GLsizei ii = 0; ii < n; ++ii) {
5762 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5764 """ % { 'func_name': func
.original_name
,
5765 'last_arg_name': func
.GetLastOriginalArg().name
,
5766 'resource_name': func
.GetInfo('resource_type') })
5768 f
.write(" if (!%sHelper(n, %s)) {\n"
5769 " return error::kInvalidArguments;\n"
5771 (func
.original_name
, func
.GetLastOriginalArg().name
))
5773 def WriteGLES2Implementation(self
, func
, f
):
5774 """Overrriden from TypeHandler."""
5775 log_code
= (""" GPU_CLIENT_LOG_CODE_BLOCK({
5776 for (GLsizei i = 0; i < n; ++i) {
5777 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5779 });""" % func
.GetOriginalArgs()[1].name
)
5781 'log_code': log_code
,
5782 'return_type': func
.return_type
,
5783 'name': func
.original_name
,
5784 'typed_args': func
.MakeTypedOriginalArgString(""),
5785 'args': func
.MakeOriginalArgString(""),
5786 'resource_types': func
.GetInfo('resource_types'),
5787 'count_name': func
.GetOriginalArgs()[0].name
,
5790 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5792 func
.WriteDestinationInitalizationValidation(f
)
5793 self
.WriteClientGLCallLog(func
, f
)
5794 for arg
in func
.GetOriginalArgs():
5795 arg
.WriteClientSideValidationCode(f
, func
)
5796 not_shared
= func
.GetInfo('not_shared')
5800 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5801 for (GLsizei ii = 0; ii < n; ++ii)
5802 %s[ii] = id_allocator->AllocateID();""" %
5803 (func
.GetInfo('resource_types'), func
.GetOriginalArgs()[1].name
))
5805 alloc_code
= (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5806 MakeIds(this, 0, %(args)s);""" % args
)
5807 args
['alloc_code'] = alloc_code
5809 code
= """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5811 %(name)sHelper(%(args)s);
5812 helper_->%(name)sImmediate(%(args)s);
5813 if (share_group_->bind_generates_resource())
5814 helper_->CommandBufferHelper::Flush();
5820 f
.write(code
% args
)
5822 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
5823 """Overrriden from TypeHandler."""
5825 TEST_F(GLES2ImplementationTest, %(name)s) {
5826 GLuint ids[2] = { 0, };
5828 cmds::%(name)sImmediate gen;
5832 expected.gen.Init(arraysize(ids), &ids[0]);
5833 expected.data[0] = k%(types)sStartId;
5834 expected.data[1] = k%(types)sStartId + 1;
5835 gl_->%(name)s(arraysize(ids), &ids[0]);
5836 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5837 EXPECT_EQ(k%(types)sStartId, ids[0]);
5838 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5843 'types': func
.GetInfo('resource_types'),
5846 def WriteServiceUnitTest(self
, func
, f
, *extras
):
5847 """Overrriden from TypeHandler."""
5849 TEST_P(%(test_name)s, %(name)sValidArgs) {
5850 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5851 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5852 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5853 SpecializedSetup<cmds::%(name)s, 0>(true);
5856 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5857 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5861 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5862 EXPECT_EQ(kNewServiceId, service_id)
5867 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5870 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5871 'resource_name': func
.GetInfo('resource_type'),
5874 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5875 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5876 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5877 SpecializedSetup<cmds::%(name)s, 0>(false);
5880 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5883 self
.WriteValidUnitTest(func
, f
, invalid_test
, {
5884 'resource_name': func
.GetInfo('resource_type').lower(),
5887 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
5888 """Overrriden from TypeHandler."""
5890 TEST_P(%(test_name)s, %(name)sValidArgs) {
5891 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5892 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5893 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5894 GLuint temp = kNewClientId;
5895 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5898 decoder_->set_unsafe_es3_apis_enabled(true);"""
5900 cmd->Init(1, &temp);
5901 EXPECT_EQ(error::kNoError,
5902 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5903 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5907 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5908 EXPECT_EQ(kNewServiceId, service_id);
5909 decoder_->set_unsafe_es3_apis_enabled(false);
5910 EXPECT_EQ(error::kUnknownCommand,
5911 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5916 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5919 self
.WriteValidUnitTest(func
, f
, valid_test
, {
5920 'resource_name': func
.GetInfo('resource_type'),
5923 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5924 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5925 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5926 SpecializedSetup<cmds::%(name)s, 0>(false);
5927 cmd->Init(1, &client_%(resource_name)s_id_);"""
5930 decoder_->set_unsafe_es3_apis_enabled(true);
5931 EXPECT_EQ(error::kInvalidArguments,
5932 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5933 decoder_->set_unsafe_es3_apis_enabled(false);
5938 EXPECT_EQ(error::kInvalidArguments,
5939 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5942 self
.WriteValidUnitTest(func
, f
, invalid_test
, {
5943 'resource_name': func
.GetInfo('resource_type').lower(),
5946 def WriteImmediateCmdComputeSize(self
, func
, f
):
5947 """Overrriden from TypeHandler."""
5948 f
.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5950 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5953 f
.write(" static uint32_t ComputeSize(GLsizei n) {\n")
5954 f
.write(" return static_cast<uint32_t>(\n")
5955 f
.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5959 def WriteImmediateCmdSetHeader(self
, func
, f
):
5960 """Overrriden from TypeHandler."""
5961 f
.write(" void SetHeader(GLsizei n) {\n")
5962 f
.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5966 def WriteImmediateCmdInit(self
, func
, f
):
5967 """Overrriden from TypeHandler."""
5968 last_arg
= func
.GetLastOriginalArg()
5969 f
.write(" void Init(%s, %s _%s) {\n" %
5970 (func
.MakeTypedCmdArgString("_"),
5971 last_arg
.type, last_arg
.name
))
5972 f
.write(" SetHeader(_n);\n")
5973 args
= func
.GetCmdArgs()
5975 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
5976 f
.write(" memcpy(ImmediateDataAddress(this),\n")
5977 f
.write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
5981 def WriteImmediateCmdSet(self
, func
, f
):
5982 """Overrriden from TypeHandler."""
5983 last_arg
= func
.GetLastOriginalArg()
5984 copy_args
= func
.MakeCmdArgString("_", False)
5985 f
.write(" void* Set(void* cmd%s, %s _%s) {\n" %
5986 (func
.MakeTypedCmdArgString("_", True),
5987 last_arg
.type, last_arg
.name
))
5988 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5989 (copy_args
, last_arg
.name
))
5990 f
.write(" const uint32_t size = ComputeSize(_n);\n")
5991 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5996 def WriteImmediateCmdHelper(self
, func
, f
):
5997 """Overrriden from TypeHandler."""
5998 code
= """ void %(name)s(%(typed_args)s) {
5999 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6000 gles2::cmds::%(name)s* c =
6001 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6010 "typed_args": func
.MakeTypedOriginalArgString(""),
6011 "args": func
.MakeOriginalArgString(""),
6014 def WriteImmediateFormatTest(self
, func
, f
):
6015 """Overrriden from TypeHandler."""
6016 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6017 f
.write(" static GLuint ids[] = { 12, 23, 34, };\n")
6018 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6019 (func
.name
, func
.name
))
6020 f
.write(" void* next_cmd = cmd.Set(\n")
6021 f
.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6022 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6024 f
.write(" cmd.header.command);\n")
6025 f
.write(" EXPECT_EQ(sizeof(cmd) +\n")
6026 f
.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6027 f
.write(" cmd.header.size * 4u);\n")
6028 f
.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6029 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
6030 f
.write(" next_cmd, sizeof(cmd) +\n")
6031 f
.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6032 f
.write(" // TODO(gman): Check that ids were inserted;\n")
6037 class CreateHandler(TypeHandler
):
6038 """Handler for glCreate___ type functions."""
6040 def InitFunction(self
, func
):
6041 """Overrriden from TypeHandler."""
6042 func
.AddCmdArg(Argument("client_id", 'uint32_t'))
6044 def __GetResourceType(self
, func
):
6045 if func
.return_type
== "GLsync":
6048 return func
.name
[6:] # Create*
6050 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6051 """Overrriden from TypeHandler."""
6053 TEST_P(%(test_name)s, %(name)sValidArgs) {
6054 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
6055 .WillOnce(Return(%(const_service_id)s));
6056 SpecializedSetup<cmds::%(name)s, 0>(true);
6058 cmd.Init(%(args)s%(comma)skNewClientId);"""
6061 decoder_->set_unsafe_es3_apis_enabled(true);"""
6063 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6064 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6067 %(return_type)s service_id = 0;
6068 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
6069 EXPECT_EQ(%(const_service_id)s, service_id);
6070 decoder_->set_unsafe_es3_apis_enabled(false);
6071 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
6076 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
6081 for arg
in func
.GetOriginalArgs():
6082 if not arg
.IsConstant():
6086 if func
.return_type
== 'GLsync':
6087 id_type_cast
= ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
6088 "<GLsync>(kNewServiceId);\n ")
6089 const_service_id
= "kNewServiceIdGLuint"
6092 const_service_id
= "kNewServiceId"
6093 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6095 'resource_type': self
.__GetResourceType
(func
),
6096 'return_type': func
.return_type
,
6097 'id_type_cast': id_type_cast
,
6098 'const_service_id': const_service_id
,
6101 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6102 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6103 SpecializedSetup<cmds::%(name)s, 0>(false);
6105 cmd.Init(%(args)s%(comma)skNewClientId);
6106 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
6109 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, {
6113 def WriteHandlerImplementation (self
, func
, f
):
6114 """Overrriden from TypeHandler."""
6116 code
= """ uint32_t client_id = c.client_id;
6117 %(return_type)s service_id = 0;
6118 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
6119 return error::kInvalidArguments;
6121 service_id = %(gl_func_name)s(%(gl_args)s);
6123 group_->Add%(resource_name)sId(client_id, service_id);
6127 code
= """ uint32_t client_id = c.client_id;
6128 if (Get%(resource_name)s(client_id)) {
6129 return error::kInvalidArguments;
6131 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
6133 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
6137 'resource_name': self
.__GetResourceType
(func
),
6138 'return_type': func
.return_type
,
6139 'gl_func_name': func
.GetGLFunctionName(),
6140 'gl_args': func
.MakeOriginalArgString(""),
6141 'gl_args_with_comma': func
.MakeOriginalArgString("", True) })
6143 def WriteGLES2Implementation(self
, func
, f
):
6144 """Overrriden from TypeHandler."""
6145 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6146 (func
.return_type
, func
.original_name
,
6147 func
.MakeTypedOriginalArgString("")))
6148 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6149 func
.WriteDestinationInitalizationValidation(f
)
6150 self
.WriteClientGLCallLog(func
, f
)
6151 for arg
in func
.GetOriginalArgs():
6152 arg
.WriteClientSideValidationCode(f
, func
)
6153 f
.write(" GLuint client_id;\n")
6154 if func
.return_type
== "GLsync":
6156 " GetIdHandler(id_namespaces::kSyncs)->\n")
6159 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
6160 f
.write(" MakeIds(this, 0, 1, &client_id);\n")
6161 f
.write(" helper_->%s(%s);\n" %
6162 (func
.name
, func
.MakeCmdArgString("")))
6163 f
.write(' GPU_CLIENT_LOG("returned " << client_id);\n')
6164 f
.write(" CheckGLError();\n")
6165 if func
.return_type
== "GLsync":
6166 f
.write(" return reinterpret_cast<GLsync>(client_id);\n")
6168 f
.write(" return client_id;\n")
6173 class DeleteHandler(TypeHandler
):
6174 """Handler for glDelete___ single resource type functions."""
6176 def WriteServiceImplementation(self
, func
, f
):
6177 """Overrriden from TypeHandler."""
6179 TypeHandler
.WriteServiceImplementation(self
, func
, f
)
6180 # HandleDeleteShader and HandleDeleteProgram are manually written.
6183 def WriteGLES2Implementation(self
, func
, f
):
6184 """Overrriden from TypeHandler."""
6185 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6186 (func
.return_type
, func
.original_name
,
6187 func
.MakeTypedOriginalArgString("")))
6188 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6189 func
.WriteDestinationInitalizationValidation(f
)
6190 self
.WriteClientGLCallLog(func
, f
)
6191 for arg
in func
.GetOriginalArgs():
6192 arg
.WriteClientSideValidationCode(f
, func
)
6194 " GPU_CLIENT_DCHECK(%s != 0);\n" % func
.GetOriginalArgs()[-1].name
)
6195 f
.write(" %sHelper(%s);\n" %
6196 (func
.original_name
, func
.GetOriginalArgs()[-1].name
))
6197 f
.write(" CheckGLError();\n")
6201 def WriteHandlerImplementation (self
, func
, f
):
6202 """Overrriden from TypeHandler."""
6203 assert len(func
.GetOriginalArgs()) == 1
6204 arg
= func
.GetOriginalArgs()[0]
6206 f
.write(""" %(arg_type)s service_id = 0;
6207 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
6208 glDelete%(resource_type)s(service_id);
6209 group_->Remove%(resource_type)sId(%(arg_name)s);
6212 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
6214 """ % { 'resource_type': func
.GetInfo('resource_type'),
6215 'arg_name': arg
.name
,
6216 'arg_type': arg
.type,
6217 'func_name': func
.original_name
})
6219 f
.write(" %sHelper(%s);\n" % (func
.original_name
, arg
.name
))
6221 class DELnHandler(TypeHandler
):
6222 """Handler for glDelete___ type functions."""
6224 def WriteGetDataSizeCode(self
, func
, f
):
6225 """Overrriden from TypeHandler."""
6226 code
= """ uint32_t data_size;
6227 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6228 return error::kOutOfBounds;
6233 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
6234 """Overrriden from TypeHandler."""
6236 TEST_F(GLES2ImplementationTest, %(name)s) {
6237 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6239 cmds::%(name)sImmediate del;
6243 expected.del.Init(arraysize(ids), &ids[0]);
6244 expected.data[0] = k%(types)sStartId;
6245 expected.data[1] = k%(types)sStartId + 1;
6246 gl_->%(name)s(arraysize(ids), &ids[0]);
6247 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6252 'types': func
.GetInfo('resource_types'),
6255 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6256 """Overrriden from TypeHandler."""
6258 TEST_P(%(test_name)s, %(name)sValidArgs) {
6261 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6263 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6264 SpecializedSetup<cmds::%(name)s, 0>(true);
6267 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6268 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6270 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6273 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6274 'resource_name': func
.GetInfo('resource_type').lower(),
6275 'upper_resource_name': func
.GetInfo('resource_type'),
6278 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6279 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6280 SpecializedSetup<cmds::%(name)s, 0>(false);
6283 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6286 self
.WriteValidUnitTest(func
, f
, invalid_test
, *extras
)
6288 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
6289 """Overrriden from TypeHandler."""
6291 TEST_P(%(test_name)s, %(name)sValidArgs) {
6294 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6296 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6297 SpecializedSetup<cmds::%(name)s, 0>(true);
6298 cmd.Init(1, &client_%(resource_name)s_id_);"""
6301 decoder_->set_unsafe_es3_apis_enabled(true);"""
6303 EXPECT_EQ(error::kNoError,
6304 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6305 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6308 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6309 client_%(resource_name)s_id_, NULL));
6310 decoder_->set_unsafe_es3_apis_enabled(false);
6311 EXPECT_EQ(error::kUnknownCommand,
6312 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6318 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6321 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6322 'resource_name': func
.GetInfo('resource_type').lower(),
6323 'upper_resource_name': func
.GetInfo('resource_type'),
6326 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6327 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6328 SpecializedSetup<cmds::%(name)s, 0>(false);
6329 GLuint temp = kInvalidClientId;
6330 cmd.Init(1, &temp);"""
6333 decoder_->set_unsafe_es3_apis_enabled(true);
6334 EXPECT_EQ(error::kNoError,
6335 ExecuteImmediateCmd(cmd, sizeof(temp)));
6336 decoder_->set_unsafe_es3_apis_enabled(false);
6337 EXPECT_EQ(error::kUnknownCommand,
6338 ExecuteImmediateCmd(cmd, sizeof(temp)));
6343 EXPECT_EQ(error::kNoError,
6344 ExecuteImmediateCmd(cmd, sizeof(temp)));
6347 self
.WriteValidUnitTest(func
, f
, invalid_test
, *extras
)
6349 def WriteHandlerImplementation (self
, func
, f
):
6350 """Overrriden from TypeHandler."""
6351 f
.write(" %sHelper(n, %s);\n" %
6352 (func
.name
, func
.GetLastOriginalArg().name
))
6354 def WriteImmediateHandlerImplementation (self
, func
, f
):
6355 """Overrriden from TypeHandler."""
6357 f
.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6358 GLuint service_id = 0;
6359 if (group_->Get%(resource_type)sServiceId(
6360 %(last_arg_name)s[ii], &service_id)) {
6361 glDelete%(resource_type)ss(1, &service_id);
6362 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6365 """ % { 'resource_type': func
.GetInfo('resource_type'),
6366 'last_arg_name': func
.GetLastOriginalArg().name
})
6368 f
.write(" %sHelper(n, %s);\n" %
6369 (func
.original_name
, func
.GetLastOriginalArg().name
))
6371 def WriteGLES2Implementation(self
, func
, f
):
6372 """Overrriden from TypeHandler."""
6373 impl_decl
= func
.GetInfo('impl_decl')
6374 if impl_decl
== None or impl_decl
== True:
6376 'return_type': func
.return_type
,
6377 'name': func
.original_name
,
6378 'typed_args': func
.MakeTypedOriginalArgString(""),
6379 'args': func
.MakeOriginalArgString(""),
6380 'resource_type': func
.GetInfo('resource_type').lower(),
6381 'count_name': func
.GetOriginalArgs()[0].name
,
6384 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6386 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6387 func
.WriteDestinationInitalizationValidation(f
)
6388 self
.WriteClientGLCallLog(func
, f
)
6389 f
.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6390 for (GLsizei i = 0; i < n; ++i) {
6391 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6394 """ % func
.GetOriginalArgs()[1].name
)
6395 f
.write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6396 for (GLsizei i = 0; i < n; ++i) {
6400 """ % func
.GetOriginalArgs()[1].name
)
6401 for arg
in func
.GetOriginalArgs():
6402 arg
.WriteClientSideValidationCode(f
, func
)
6403 code
= """ %(name)sHelper(%(args)s);
6408 f
.write(code
% args
)
6410 def WriteImmediateCmdComputeSize(self
, func
, f
):
6411 """Overrriden from TypeHandler."""
6412 f
.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6414 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6417 f
.write(" static uint32_t ComputeSize(GLsizei n) {\n")
6418 f
.write(" return static_cast<uint32_t>(\n")
6419 f
.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6423 def WriteImmediateCmdSetHeader(self
, func
, f
):
6424 """Overrriden from TypeHandler."""
6425 f
.write(" void SetHeader(GLsizei n) {\n")
6426 f
.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6430 def WriteImmediateCmdInit(self
, func
, f
):
6431 """Overrriden from TypeHandler."""
6432 last_arg
= func
.GetLastOriginalArg()
6433 f
.write(" void Init(%s, %s _%s) {\n" %
6434 (func
.MakeTypedCmdArgString("_"),
6435 last_arg
.type, last_arg
.name
))
6436 f
.write(" SetHeader(_n);\n")
6437 args
= func
.GetCmdArgs()
6439 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
6440 f
.write(" memcpy(ImmediateDataAddress(this),\n")
6441 f
.write(" _%s, ComputeDataSize(_n));\n" % last_arg
.name
)
6445 def WriteImmediateCmdSet(self
, func
, f
):
6446 """Overrriden from TypeHandler."""
6447 last_arg
= func
.GetLastOriginalArg()
6448 copy_args
= func
.MakeCmdArgString("_", False)
6449 f
.write(" void* Set(void* cmd%s, %s _%s) {\n" %
6450 (func
.MakeTypedCmdArgString("_", True),
6451 last_arg
.type, last_arg
.name
))
6452 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6453 (copy_args
, last_arg
.name
))
6454 f
.write(" const uint32_t size = ComputeSize(_n);\n")
6455 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6460 def WriteImmediateCmdHelper(self
, func
, f
):
6461 """Overrriden from TypeHandler."""
6462 code
= """ void %(name)s(%(typed_args)s) {
6463 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6464 gles2::cmds::%(name)s* c =
6465 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6474 "typed_args": func
.MakeTypedOriginalArgString(""),
6475 "args": func
.MakeOriginalArgString(""),
6478 def WriteImmediateFormatTest(self
, func
, f
):
6479 """Overrriden from TypeHandler."""
6480 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
6481 f
.write(" static GLuint ids[] = { 12, 23, 34, };\n")
6482 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6483 (func
.name
, func
.name
))
6484 f
.write(" void* next_cmd = cmd.Set(\n")
6485 f
.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6486 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6488 f
.write(" cmd.header.command);\n")
6489 f
.write(" EXPECT_EQ(sizeof(cmd) +\n")
6490 f
.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6491 f
.write(" cmd.header.size * 4u);\n")
6492 f
.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6493 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
6494 f
.write(" next_cmd, sizeof(cmd) +\n")
6495 f
.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6496 f
.write(" // TODO(gman): Check that ids were inserted;\n")
6501 class GETnHandler(TypeHandler
):
6502 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6504 def NeedsDataTransferFunction(self
, func
):
6505 """Overriden from TypeHandler."""
6508 def WriteServiceImplementation(self
, func
, f
):
6509 """Overrriden from TypeHandler."""
6510 self
.WriteServiceHandlerFunctionHeader(func
, f
)
6511 last_arg
= func
.GetLastOriginalArg()
6512 # All except shm_id and shm_offset.
6513 all_but_last_args
= func
.GetCmdArgs()[:-2]
6514 for arg
in all_but_last_args
:
6517 code
= """ typedef cmds::%(func_name)s::Result Result;
6518 GLsizei num_values = 0;
6519 GetNumValuesReturnedForGLGet(pname, &num_values);
6520 Result* result = GetSharedMemoryAs<Result*>(
6521 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6522 Result::ComputeSize(num_values));
6523 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6526 'last_arg_type': last_arg
.type,
6527 'last_arg_name': last_arg
.name
,
6528 'func_name': func
.name
,
6530 func
.WriteHandlerValidation(f
)
6531 code
= """ // Check that the client initialized the result.
6532 if (result->size != 0) {
6533 return error::kInvalidArguments;
6536 shadowed
= func
.GetInfo('shadowed')
6538 f
.write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func
.name
)
6540 func
.WriteHandlerImplementation(f
)
6542 code
= """ result->SetNumResults(num_values);
6543 return error::kNoError;
6547 code
= """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
6548 if (error == GL_NO_ERROR) {
6549 result->SetNumResults(num_values);
6551 return error::kNoError;
6555 f
.write(code
% {'func_name': func
.name
})
6557 def WriteGLES2Implementation(self
, func
, f
):
6558 """Overrriden from TypeHandler."""
6559 impl_decl
= func
.GetInfo('impl_decl')
6560 if impl_decl
== None or impl_decl
== True:
6561 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6562 (func
.return_type
, func
.original_name
,
6563 func
.MakeTypedOriginalArgString("")))
6564 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6565 func
.WriteDestinationInitalizationValidation(f
)
6566 self
.WriteClientGLCallLog(func
, f
)
6567 for arg
in func
.GetOriginalArgs():
6568 arg
.WriteClientSideValidationCode(f
, func
)
6569 all_but_last_args
= func
.GetOriginalArgs()[:-1]
6571 has_length_arg
= False
6572 for arg
in all_but_last_args
:
6573 if arg
.type == 'GLsync':
6574 args
.append('ToGLuint(%s)' % arg
.name
)
6575 elif arg
.name
.endswith('size') and arg
.type == 'GLsizei':
6577 elif arg
.name
== 'length':
6578 has_length_arg
= True
6581 args
.append(arg
.name
)
6582 arg_string
= ", ".join(args
)
6586 for arg
in func
.GetOriginalArgs() if not arg
.IsConstant()]))
6587 self
.WriteTraceEvent(func
, f
)
6588 code
= """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6591 typedef cmds::%(func_name)s::Result Result;
6592 Result* result = GetResultAs<Result*>();
6596 result->SetNumResults(0);
6597 helper_->%(func_name)s(%(arg_string)s,
6598 GetResultShmId(), GetResultShmOffset());
6600 result->CopyResult(%(last_arg_name)s);
6601 GPU_CLIENT_LOG_CODE_BLOCK({
6602 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6603 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6609 *length = result->GetNumResults();
6616 'func_name': func
.name
,
6617 'arg_string': arg_string
,
6618 'all_arg_string': all_arg_string
,
6619 'last_arg_name': func
.GetLastOriginalArg().name
,
6622 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
6623 """Writes the GLES2 Implemention unit test."""
6625 TEST_F(GLES2ImplementationTest, %(name)s) {
6629 typedef cmds::%(name)s::Result::Type ResultType;
6630 ResultType result = 0;
6632 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6633 sizeof(uint32_t) + sizeof(ResultType));
6634 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6635 EXPECT_CALL(*command_buffer(), OnFlush())
6636 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6637 .RetiresOnSaturation();
6638 gl_->%(name)s(%(args)s, &result);
6639 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6640 EXPECT_EQ(static_cast<ResultType>(1), result);
6643 first_cmd_arg
= func
.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func
)
6644 if not first_cmd_arg
:
6647 first_gl_arg
= func
.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6650 cmd_arg_strings
= [first_cmd_arg
]
6651 for arg
in func
.GetCmdArgs()[1:-2]:
6652 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
6653 gl_arg_strings
= [first_gl_arg
]
6654 for arg
in func
.GetOriginalArgs()[1:-1]:
6655 gl_arg_strings
.append(arg
.GetValidClientSideArg(func
))
6659 'args': ", ".join(gl_arg_strings
),
6660 'cmd_args': ", ".join(cmd_arg_strings
),
6663 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6664 """Overrriden from TypeHandler."""
6666 TEST_P(%(test_name)s, %(name)sValidArgs) {
6667 EXPECT_CALL(*gl_, GetError())
6668 .WillOnce(Return(GL_NO_ERROR))
6669 .WillOnce(Return(GL_NO_ERROR))
6670 .RetiresOnSaturation();
6671 SpecializedSetup<cmds::%(name)s, 0>(true);
6672 typedef cmds::%(name)s::Result Result;
6673 Result* result = static_cast<Result*>(shared_memory_address_);
6674 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6677 cmd.Init(%(cmd_args)s);"""
6680 decoder_->set_unsafe_es3_apis_enabled(true);"""
6682 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6683 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6685 result->GetNumResults());
6686 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6689 decoder_->set_unsafe_es3_apis_enabled(false);
6690 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6695 cmd_arg_strings
= []
6697 for arg
in func
.GetOriginalArgs()[:-1]:
6698 if arg
.name
== 'length':
6699 gl_arg_value
= 'nullptr'
6700 elif arg
.name
.endswith('size'):
6701 gl_arg_value
= ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6703 elif arg
.type == 'GLsync':
6704 gl_arg_value
= 'reinterpret_cast<GLsync>(kServiceSyncId)'
6706 gl_arg_value
= arg
.GetValidGLArg(func
)
6707 gl_arg_strings
.append(gl_arg_value
)
6708 if arg
.name
== 'pname':
6709 valid_pname
= gl_arg_value
6710 if arg
.name
.endswith('size') or arg
.name
== 'length':
6712 if arg
.type == 'GLsync':
6713 arg_value
= 'client_sync_id_'
6715 arg_value
= arg
.GetValidArg(func
)
6716 cmd_arg_strings
.append(arg_value
)
6717 if func
.GetInfo('gl_test_func') == 'glGetIntegerv':
6718 gl_arg_strings
.append("_")
6720 gl_arg_strings
.append("result->GetData()")
6721 cmd_arg_strings
.append("shared_memory_id_")
6722 cmd_arg_strings
.append("shared_memory_offset_")
6724 self
.WriteValidUnitTest(func
, f
, valid_test
, {
6725 'local_gl_args': ", ".join(gl_arg_strings
),
6726 'cmd_args': ", ".join(cmd_arg_strings
),
6727 'valid_pname': valid_pname
,
6730 if not func
.IsUnsafe():
6732 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6733 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6734 SpecializedSetup<cmds::%(name)s, 0>(false);
6735 cmds::%(name)s::Result* result =
6736 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6740 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6741 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6744 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, *extras
)
6746 class ArrayArgTypeHandler(TypeHandler
):
6747 """Base class for type handlers that handle args that are arrays"""
6749 def GetArrayType(self
, func
):
6750 """Returns the type of the element in the element array being PUT to."""
6751 for arg
in func
.GetOriginalArgs():
6753 element_type
= arg
.GetPointedType()
6756 # Special case: array type handler is used for a function that is forwarded
6757 # to the actual array type implementation
6758 element_type
= func
.GetOriginalArgs()[-1].type
6759 assert all(arg
.type == element_type \
6760 for arg
in func
.GetOriginalArgs()[-self
.GetArrayCount(func
):])
6763 def GetArrayCount(self
, func
):
6764 """Returns the count of the elements in the array being PUT to."""
6765 return func
.GetInfo('count')
6767 class PUTHandler(ArrayArgTypeHandler
):
6768 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6770 def WriteServiceUnitTest(self
, func
, f
, *extras
):
6771 """Writes the service unit test for a command."""
6772 expected_call
= "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6773 if func
.GetInfo("first_element_only"):
6775 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()
6777 gl_arg_strings
[-1] = "*" + gl_arg_strings
[-1]
6778 expected_call
= ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6779 ", ".join(gl_arg_strings
))
6781 TEST_P(%(test_name)s, %(name)sValidArgs) {
6782 SpecializedSetup<cmds::%(name)s, 0>(true);
6785 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6787 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6788 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6792 'data_type': self
.GetArrayType(func
),
6793 'data_value': func
.GetInfo('data_value') or '0',
6794 'expected_call': expected_call
,
6796 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
6799 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6800 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6801 SpecializedSetup<cmds::%(name)s, 0>(false);
6804 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6805 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6808 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, extra
, *extras
)
6810 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
6811 """Writes the service unit test for a command."""
6813 TEST_P(%(test_name)s, %(name)sValidArgs) {
6814 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6815 SpecializedSetup<cmds::%(name)s, 0>(true);
6816 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6817 cmd.Init(%(gl_args)s, &temp[0]);
6820 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6821 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6824 decoder_->set_unsafe_es3_apis_enabled(true);"""
6826 EXPECT_EQ(error::kNoError,
6827 ExecuteImmediateCmd(cmd, sizeof(temp)));
6828 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6831 decoder_->set_unsafe_es3_apis_enabled(false);
6832 EXPECT_EQ(error::kUnknownCommand,
6833 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6838 arg
.GetValidGLArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6840 gl_any_strings
= ["_"] * len(gl_arg_strings
)
6843 'data_ref': ("*" if func
.GetInfo('first_element_only') else ""),
6844 'data_type': self
.GetArrayType(func
),
6845 'data_count': self
.GetArrayCount(func
),
6846 'data_value': func
.GetInfo('data_value') or '0',
6847 'gl_args': ", ".join(gl_arg_strings
),
6848 'gl_any_args': ", ".join(gl_any_strings
),
6850 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
6853 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6854 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6857 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6861 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6864 SpecializedSetup<cmds::%(name)s, 0>(false);
6865 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6866 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6869 decoder_->set_unsafe_es3_apis_enabled(true);
6870 EXPECT_EQ(error::%(parse_result)s,
6871 ExecuteImmediateCmd(cmd, sizeof(temp)));
6872 decoder_->set_unsafe_es3_apis_enabled(false);
6877 EXPECT_EQ(error::%(parse_result)s,
6878 ExecuteImmediateCmd(cmd, sizeof(temp)));
6882 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, extra
, *extras
)
6884 def WriteGetDataSizeCode(self
, func
, f
):
6885 """Overrriden from TypeHandler."""
6886 code
= """ uint32_t data_size;
6887 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6888 return error::kOutOfBounds;
6891 f
.write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6892 if func
.IsImmediate():
6893 f
.write(" if (data_size > immediate_data_size) {\n")
6894 f
.write(" return error::kOutOfBounds;\n")
6897 def __NeedsToCalcDataCount(self
, func
):
6898 use_count_func
= func
.GetInfo('use_count_func')
6899 return use_count_func
!= None and use_count_func
!= False
6901 def WriteGLES2Implementation(self
, func
, f
):
6902 """Overrriden from TypeHandler."""
6903 impl_func
= func
.GetInfo('impl_func')
6904 if (impl_func
!= None and impl_func
!= True):
6906 f
.write("%s GLES2Implementation::%s(%s) {\n" %
6907 (func
.return_type
, func
.original_name
,
6908 func
.MakeTypedOriginalArgString("")))
6909 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6910 func
.WriteDestinationInitalizationValidation(f
)
6911 self
.WriteClientGLCallLog(func
, f
)
6913 if self
.__NeedsToCalcDataCount
(func
):
6914 f
.write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6915 (func
.name
, func
.GetOriginalArgs()[0].name
))
6916 f
.write(" DCHECK_LE(count, %du);\n" % self
.GetArrayCount(func
))
6918 f
.write(" size_t count = %d;" % self
.GetArrayCount(func
))
6919 f
.write(" for (size_t ii = 0; ii < count; ++ii)\n")
6920 f
.write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6921 func
.GetLastOriginalArg().name
)
6922 for arg
in func
.GetOriginalArgs():
6923 arg
.WriteClientSideValidationCode(f
, func
)
6924 f
.write(" helper_->%sImmediate(%s);\n" %
6925 (func
.name
, func
.MakeOriginalArgString("")))
6926 f
.write(" CheckGLError();\n")
6930 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
6931 """Writes the GLES2 Implemention unit test."""
6932 client_test
= func
.GetInfo('client_test')
6933 if (client_test
!= None and client_test
!= True):
6936 TEST_F(GLES2ImplementationTest, %(name)s) {
6937 %(type)s data[%(count)d] = {0};
6939 cmds::%(name)sImmediate cmd;
6940 %(type)s data[%(count)d];
6943 for (int jj = 0; jj < %(count)d; ++jj) {
6944 data[jj] = static_cast<%(type)s>(jj);
6947 expected.cmd.Init(%(cmd_args)s, &data[0]);
6948 gl_->%(name)s(%(args)s, &data[0]);
6949 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6953 arg
.GetValidClientSideCmdArg(func
) for arg
in func
.GetCmdArgs()[0:-2]
6956 arg
.GetValidClientSideArg(func
) for arg
in func
.GetOriginalArgs()[0:-1]
6961 'type': self
.GetArrayType(func
),
6962 'count': self
.GetArrayCount(func
),
6963 'args': ", ".join(gl_arg_strings
),
6964 'cmd_args': ", ".join(cmd_arg_strings
),
6967 def WriteImmediateCmdComputeSize(self
, func
, f
):
6968 """Overrriden from TypeHandler."""
6969 f
.write(" static uint32_t ComputeDataSize() {\n")
6970 f
.write(" return static_cast<uint32_t>(\n")
6971 f
.write(" sizeof(%s) * %d);\n" %
6972 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
6975 if self
.__NeedsToCalcDataCount
(func
):
6976 f
.write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6977 (func
.GetOriginalArgs()[0].type,
6978 func
.GetOriginalArgs()[0].name
))
6979 f
.write(" return static_cast<uint32_t>(\n")
6980 f
.write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6981 (self
.GetArrayType(func
), func
.original_name
,
6982 func
.GetOriginalArgs()[0].name
))
6985 f
.write(" static uint32_t ComputeSize() {\n")
6986 f
.write(" return static_cast<uint32_t>(\n")
6988 " sizeof(ValueType) + ComputeDataSize());\n")
6992 def WriteImmediateCmdSetHeader(self
, func
, f
):
6993 """Overrriden from TypeHandler."""
6994 f
.write(" void SetHeader() {\n")
6996 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
7000 def WriteImmediateCmdInit(self
, func
, f
):
7001 """Overrriden from TypeHandler."""
7002 last_arg
= func
.GetLastOriginalArg()
7003 f
.write(" void Init(%s, %s _%s) {\n" %
7004 (func
.MakeTypedCmdArgString("_"),
7005 last_arg
.type, last_arg
.name
))
7006 f
.write(" SetHeader();\n")
7007 args
= func
.GetCmdArgs()
7009 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
7010 f
.write(" memcpy(ImmediateDataAddress(this),\n")
7011 if self
.__NeedsToCalcDataCount
(func
):
7012 f
.write(" _%s, ComputeEffectiveDataSize(%s));" %
7013 (last_arg
.name
, func
.GetOriginalArgs()[0].name
))
7015 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
7016 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
7017 ComputeEffectiveDataSize(%(arg)s);
7018 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
7019 """ % { 'arg': func
.GetOriginalArgs()[0].name
, })
7021 f
.write(" _%s, ComputeDataSize());\n" % last_arg
.name
)
7025 def WriteImmediateCmdSet(self
, func
, f
):
7026 """Overrriden from TypeHandler."""
7027 last_arg
= func
.GetLastOriginalArg()
7028 copy_args
= func
.MakeCmdArgString("_", False)
7029 f
.write(" void* Set(void* cmd%s, %s _%s) {\n" %
7030 (func
.MakeTypedCmdArgString("_", True),
7031 last_arg
.type, last_arg
.name
))
7032 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
7033 (copy_args
, last_arg
.name
))
7034 f
.write(" const uint32_t size = ComputeSize();\n")
7035 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7040 def WriteImmediateCmdHelper(self
, func
, f
):
7041 """Overrriden from TypeHandler."""
7042 code
= """ void %(name)s(%(typed_args)s) {
7043 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
7044 gles2::cmds::%(name)s* c =
7045 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7054 "typed_args": func
.MakeTypedOriginalArgString(""),
7055 "args": func
.MakeOriginalArgString(""),
7058 def WriteImmediateFormatTest(self
, func
, f
):
7059 """Overrriden from TypeHandler."""
7060 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
7061 f
.write(" const int kSomeBaseValueToTestWith = 51;\n")
7062 f
.write(" static %s data[] = {\n" % self
.GetArrayType(func
))
7063 for v
in range(0, self
.GetArrayCount(func
)):
7064 f
.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7065 (self
.GetArrayType(func
), v
))
7067 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7068 (func
.name
, func
.name
))
7069 f
.write(" void* next_cmd = cmd.Set(\n")
7071 args
= func
.GetCmdArgs()
7072 for value
, arg
in enumerate(args
):
7073 f
.write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 11))
7074 f
.write(",\n data);\n")
7075 args
= func
.GetCmdArgs()
7076 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
7078 f
.write(" cmd.header.command);\n")
7079 f
.write(" EXPECT_EQ(sizeof(cmd) +\n")
7080 f
.write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
7081 f
.write(" cmd.header.size * 4u);\n")
7082 for value
, arg
in enumerate(args
):
7083 f
.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7084 (arg
.type, value
+ 11, arg
.name
))
7085 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7086 f
.write(" next_cmd, sizeof(cmd) +\n")
7087 f
.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7088 f
.write(" // TODO(gman): Check that data was inserted;\n")
7093 class PUTnHandler(ArrayArgTypeHandler
):
7094 """Handler for PUTn 'glUniform__v' type functions."""
7096 def WriteServiceUnitTest(self
, func
, f
, *extras
):
7097 """Overridden from TypeHandler."""
7098 ArrayArgTypeHandler
.WriteServiceUnitTest(self
, func
, f
, *extras
)
7101 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
7102 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7103 SpecializedSetup<cmds::%(name)s, 0>(true);
7106 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7107 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7112 for count
, arg
in enumerate(func
.GetOriginalArgs()):
7113 # hardcoded to match unit tests.
7115 # the location of the second element of the 2nd uniform.
7116 # defined in GLES2DecoderBase::SetupShaderForUniform
7117 gl_arg_strings
.append("3")
7118 arg_strings
.append("ProgramManager::MakeFakeLocation(1, 1)")
7120 # the number of elements that gl will be called with.
7121 gl_arg_strings
.append("3")
7122 # the number of elements requested in the command.
7123 arg_strings
.append("5")
7125 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
7126 if not arg
.IsConstant():
7127 arg_strings
.append(arg
.GetValidArg(func
))
7129 'gl_args': ", ".join(gl_arg_strings
),
7130 'args': ", ".join(arg_strings
),
7132 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
7134 def WriteImmediateServiceUnitTest(self
, func
, f
, *extras
):
7135 """Overridden from TypeHandler."""
7137 TEST_P(%(test_name)s, %(name)sValidArgs) {
7138 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7141 %(gl_func_name)s(%(gl_args)s,
7142 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
7143 SpecializedSetup<cmds::%(name)s, 0>(true);
7144 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7145 cmd.Init(%(args)s, &temp[0]);"""
7148 decoder_->set_unsafe_es3_apis_enabled(true);"""
7150 EXPECT_EQ(error::kNoError,
7151 ExecuteImmediateCmd(cmd, sizeof(temp)));
7152 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7155 decoder_->set_unsafe_es3_apis_enabled(false);
7156 EXPECT_EQ(error::kUnknownCommand,
7157 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
7164 for arg
in func
.GetOriginalArgs()[0:-1]:
7165 gl_arg_strings
.append(arg
.GetValidGLArg(func
))
7166 gl_any_strings
.append("_")
7167 if not arg
.IsConstant():
7168 arg_strings
.append(arg
.GetValidArg(func
))
7170 'data_type': self
.GetArrayType(func
),
7171 'data_count': self
.GetArrayCount(func
),
7172 'args': ", ".join(arg_strings
),
7173 'gl_args': ", ".join(gl_arg_strings
),
7174 'gl_any_args': ", ".join(gl_any_strings
),
7176 self
.WriteValidUnitTest(func
, f
, valid_test
, extra
, *extras
)
7179 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7180 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7181 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
7182 SpecializedSetup<cmds::%(name)s, 0>(false);
7183 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7184 cmd.Init(%(all_but_last_args)s, &temp[0]);
7185 EXPECT_EQ(error::%(parse_result)s,
7186 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
7189 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, extra
, *extras
)
7191 def WriteGetDataSizeCode(self
, func
, f
):
7192 """Overrriden from TypeHandler."""
7193 code
= """ uint32_t data_size;
7194 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
7195 return error::kOutOfBounds;
7198 f
.write(code
% (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7199 if func
.IsImmediate():
7200 f
.write(" if (data_size > immediate_data_size) {\n")
7201 f
.write(" return error::kOutOfBounds;\n")
7204 def WriteGLES2Implementation(self
, func
, f
):
7205 """Overrriden from TypeHandler."""
7206 f
.write("%s GLES2Implementation::%s(%s) {\n" %
7207 (func
.return_type
, func
.original_name
,
7208 func
.MakeTypedOriginalArgString("")))
7209 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7210 func
.WriteDestinationInitalizationValidation(f
)
7211 self
.WriteClientGLCallLog(func
, f
)
7212 last_pointer_name
= func
.GetLastOriginalPointerArg().name
7213 f
.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7214 for (GLsizei i = 0; i < count; ++i) {
7216 values_str
= ' << ", " << '.join(
7217 ["%s[%d + i * %d]" % (
7218 last_pointer_name
, ndx
, self
.GetArrayCount(func
)) for ndx
in range(
7219 0, self
.GetArrayCount(func
))])
7220 f
.write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str
)
7221 f
.write(" }\n });\n")
7222 for arg
in func
.GetOriginalArgs():
7223 arg
.WriteClientSideValidationCode(f
, func
)
7224 f
.write(" helper_->%sImmediate(%s);\n" %
7225 (func
.name
, func
.MakeInitString("")))
7226 f
.write(" CheckGLError();\n")
7230 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
7231 """Writes the GLES2 Implemention unit test."""
7233 TEST_F(GLES2ImplementationTest, %(name)s) {
7234 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7236 cmds::%(name)sImmediate cmd;
7237 %(type)s data[%(count_param)d][%(count)d];
7241 for (int ii = 0; ii < %(count_param)d; ++ii) {
7242 for (int jj = 0; jj < %(count)d; ++jj) {
7243 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7246 expected.cmd.Init(%(cmd_args)s);
7247 gl_->%(name)s(%(args)s);
7248 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7251 cmd_arg_strings
= []
7252 for arg
in func
.GetCmdArgs():
7253 if arg
.name
.endswith("_shm_id"):
7254 cmd_arg_strings
.append("&data[0][0]")
7255 elif arg
.name
.endswith("_shm_offset"):
7258 cmd_arg_strings
.append(arg
.GetValidClientSideCmdArg(func
))
7261 for arg
in func
.GetOriginalArgs():
7263 valid_value
= "&data[0][0]"
7265 valid_value
= arg
.GetValidClientSideArg(func
)
7266 gl_arg_strings
.append(valid_value
)
7267 if arg
.name
== "count":
7268 count_param
= int(valid_value
)
7271 'type': self
.GetArrayType(func
),
7272 'count': self
.GetArrayCount(func
),
7273 'args': ", ".join(gl_arg_strings
),
7274 'cmd_args': ", ".join(cmd_arg_strings
),
7275 'count_param': count_param
,
7278 # Test constants for invalid values, as they are not tested by the
7281 arg
for arg
in func
.GetOriginalArgs()[0:-1] if arg
.IsConstant()
7287 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7288 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7289 for (int ii = 0; ii < %(count_param)d; ++ii) {
7290 for (int jj = 0; jj < %(count)d; ++jj) {
7291 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7294 gl_->%(name)s(%(args)s);
7295 EXPECT_TRUE(NoCommandsWritten());
7296 EXPECT_EQ(%(gl_error)s, CheckError());
7299 for invalid_arg
in constants
:
7301 invalid
= invalid_arg
.GetInvalidArg(func
)
7302 for arg
in func
.GetOriginalArgs():
7303 if arg
is invalid_arg
:
7304 gl_arg_strings
.append(invalid
[0])
7305 elif arg
.IsPointer():
7306 gl_arg_strings
.append("&data[0][0]")
7308 valid_value
= arg
.GetValidClientSideArg(func
)
7309 gl_arg_strings
.append(valid_value
)
7310 if arg
.name
== "count":
7311 count_param
= int(valid_value
)
7315 'invalid_index': func
.GetOriginalArgs().index(invalid_arg
),
7316 'type': self
.GetArrayType(func
),
7317 'count': self
.GetArrayCount(func
),
7318 'args': ", ".join(gl_arg_strings
),
7319 'gl_error': invalid
[2],
7320 'count_param': count_param
,
7324 def WriteImmediateCmdComputeSize(self
, func
, f
):
7325 """Overrriden from TypeHandler."""
7326 f
.write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7327 f
.write(" return static_cast<uint32_t>(\n")
7328 f
.write(" sizeof(%s) * %d * count); // NOLINT\n" %
7329 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7332 f
.write(" static uint32_t ComputeSize(GLsizei count) {\n")
7333 f
.write(" return static_cast<uint32_t>(\n")
7335 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7339 def WriteImmediateCmdSetHeader(self
, func
, f
):
7340 """Overrriden from TypeHandler."""
7341 f
.write(" void SetHeader(GLsizei count) {\n")
7343 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7347 def WriteImmediateCmdInit(self
, func
, f
):
7348 """Overrriden from TypeHandler."""
7349 f
.write(" void Init(%s) {\n" %
7350 func
.MakeTypedInitString("_"))
7351 f
.write(" SetHeader(_count);\n")
7352 args
= func
.GetCmdArgs()
7354 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
7355 f
.write(" memcpy(ImmediateDataAddress(this),\n")
7356 pointer_arg
= func
.GetLastOriginalPointerArg()
7357 f
.write(" _%s, ComputeDataSize(_count));\n" % pointer_arg
.name
)
7361 def WriteImmediateCmdSet(self
, func
, f
):
7362 """Overrriden from TypeHandler."""
7363 f
.write(" void* Set(void* cmd%s) {\n" %
7364 func
.MakeTypedInitString("_", True))
7365 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7366 func
.MakeInitString("_"))
7367 f
.write(" const uint32_t size = ComputeSize(_count);\n")
7368 f
.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7373 def WriteImmediateCmdHelper(self
, func
, f
):
7374 """Overrriden from TypeHandler."""
7375 code
= """ void %(name)s(%(typed_args)s) {
7376 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7377 gles2::cmds::%(name)s* c =
7378 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7387 "typed_args": func
.MakeTypedInitString(""),
7388 "args": func
.MakeInitString("")
7391 def WriteImmediateFormatTest(self
, func
, f
):
7392 """Overrriden from TypeHandler."""
7393 args
= func
.GetOriginalArgs()
7396 if arg
.name
== "count":
7397 count_param
= int(arg
.GetValidClientSideCmdArg(func
))
7398 f
.write("TEST_F(GLES2FormatTest, %s) {\n" % func
.name
)
7399 f
.write(" const int kSomeBaseValueToTestWith = 51;\n")
7400 f
.write(" static %s data[] = {\n" % self
.GetArrayType(func
))
7401 for v
in range(0, self
.GetArrayCount(func
) * count_param
):
7402 f
.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7403 (self
.GetArrayType(func
), v
))
7405 f
.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7406 (func
.name
, func
.name
))
7407 f
.write(" const GLsizei kNumElements = %d;\n" % count_param
)
7408 f
.write(" const size_t kExpectedCmdSize =\n")
7409 f
.write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7410 (self
.GetArrayType(func
), self
.GetArrayCount(func
)))
7411 f
.write(" void* next_cmd = cmd.Set(\n")
7413 for value
, arg
in enumerate(args
):
7416 elif arg
.IsConstant():
7419 f
.write(",\n static_cast<%s>(%d)" % (arg
.type, value
+ 1))
7421 f
.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7423 f
.write(" cmd.header.command);\n")
7424 f
.write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7425 for value
, arg
in enumerate(args
):
7426 if arg
.IsPointer() or arg
.IsConstant():
7428 f
.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7429 (arg
.type, value
+ 1, arg
.name
))
7430 f
.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7431 f
.write(" next_cmd, sizeof(cmd) +\n")
7432 f
.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7433 f
.write(" // TODO(gman): Check that data was inserted;\n")
7437 class PUTSTRHandler(ArrayArgTypeHandler
):
7438 """Handler for functions that pass a string array."""
7440 def __GetDataArg(self
, func
):
7441 """Return the argument that points to the 2D char arrays"""
7442 for arg
in func
.GetOriginalArgs():
7443 if arg
.IsPointer2D():
7447 def __GetLengthArg(self
, func
):
7448 """Return the argument that holds length for each char array"""
7449 for arg
in func
.GetOriginalArgs():
7450 if arg
.IsPointer() and not arg
.IsPointer2D():
7454 def WriteGLES2Implementation(self
, func
, f
):
7455 """Overrriden from TypeHandler."""
7456 f
.write("%s GLES2Implementation::%s(%s) {\n" %
7457 (func
.return_type
, func
.original_name
,
7458 func
.MakeTypedOriginalArgString("")))
7459 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7460 func
.WriteDestinationInitalizationValidation(f
)
7461 self
.WriteClientGLCallLog(func
, f
)
7462 data_arg
= self
.__GetDataArg
(func
)
7463 length_arg
= self
.__GetLengthArg
(func
)
7464 log_code_block
= """ GPU_CLIENT_LOG_CODE_BLOCK({
7465 for (GLsizei ii = 0; ii < count; ++ii) {
7466 if (%(data)s[ii]) {"""
7467 if length_arg
== None:
7468 log_code_block
+= """
7469 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7471 log_code_block
+= """
7472 if (%(length)s && %(length)s[ii] >= 0) {
7473 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7474 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7476 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7478 log_code_block
+= """
7480 GPU_CLIENT_LOG(" " << ii << ": NULL");
7485 f
.write(log_code_block
% {
7486 'data': data_arg
.name
,
7487 'length': length_arg
.name
if not length_arg
== None else ''
7489 for arg
in func
.GetOriginalArgs():
7490 arg
.WriteClientSideValidationCode(f
, func
)
7493 for arg
in func
.GetOriginalArgs():
7494 if arg
.name
== 'count' or arg
== self
.__GetLengthArg
(func
):
7496 if arg
== self
.__GetDataArg
(func
):
7497 bucket_args
.append('kResultBucketId')
7499 bucket_args
.append(arg
.name
)
7501 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7504 helper_->%(func_name)sBucket(%(bucket_args)s);
7505 helper_->SetBucketSize(kResultBucketId, 0);
7510 f
.write(code_block
% {
7511 'data': data_arg
.name
,
7512 'length': length_arg
.name
if not length_arg
== None else 'NULL',
7513 'func_name': func
.name
,
7514 'bucket_args': ', '.join(bucket_args
),
7517 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
7518 """Overrriden from TypeHandler."""
7520 TEST_F(GLES2ImplementationTest, %(name)s) {
7521 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7522 const char* kString1 = "happy";
7523 const char* kString2 = "ending";
7524 const size_t kString1Size = ::strlen(kString1) + 1;
7525 const size_t kString2Size = ::strlen(kString2) + 1;
7526 const size_t kHeaderSize = sizeof(GLint) * 3;
7527 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7528 const size_t kPaddedHeaderSize =
7529 transfer_buffer_->RoundToAlignment(kHeaderSize);
7530 const size_t kPaddedString1Size =
7531 transfer_buffer_->RoundToAlignment(kString1Size);
7532 const size_t kPaddedString2Size =
7533 transfer_buffer_->RoundToAlignment(kString2Size);
7535 cmd::SetBucketSize set_bucket_size;
7536 cmd::SetBucketData set_bucket_header;
7537 cmd::SetToken set_token1;
7538 cmd::SetBucketData set_bucket_data1;
7539 cmd::SetToken set_token2;
7540 cmd::SetBucketData set_bucket_data2;
7541 cmd::SetToken set_token3;
7542 cmds::%(name)sBucket cmd_bucket;
7543 cmd::SetBucketSize clear_bucket_size;
7546 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7547 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7548 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7551 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7552 expected.set_bucket_header.Init(
7553 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7554 expected.set_token1.Init(GetNextToken());
7555 expected.set_bucket_data1.Init(
7556 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7557 expected.set_token2.Init(GetNextToken());
7558 expected.set_bucket_data2.Init(
7559 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7561 expected.set_token3.Init(GetNextToken());
7562 expected.cmd_bucket.Init(%(bucket_args)s);
7563 expected.clear_bucket_size.Init(kBucketId, 0);
7564 const char* kStrings[] = { kString1, kString2 };
7565 gl_->%(name)s(%(gl_args)s);
7566 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7571 for arg
in func
.GetOriginalArgs():
7572 if arg
== self
.__GetDataArg
(func
):
7573 gl_args
.append('kStrings')
7574 bucket_args
.append('kBucketId')
7575 elif arg
== self
.__GetLengthArg
(func
):
7576 gl_args
.append('NULL')
7577 elif arg
.name
== 'count':
7580 gl_args
.append(arg
.GetValidClientSideArg(func
))
7581 bucket_args
.append(arg
.GetValidClientSideArg(func
))
7584 'gl_args': ", ".join(gl_args
),
7585 'bucket_args': ", ".join(bucket_args
),
7588 if self
.__GetLengthArg
(func
) == None:
7591 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7592 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7593 const char* kString = "foobar******";
7594 const size_t kStringSize = 6; // We only need "foobar".
7595 const size_t kHeaderSize = sizeof(GLint) * 2;
7596 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7597 const size_t kPaddedHeaderSize =
7598 transfer_buffer_->RoundToAlignment(kHeaderSize);
7599 const size_t kPaddedStringSize =
7600 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7602 cmd::SetBucketSize set_bucket_size;
7603 cmd::SetBucketData set_bucket_header;
7604 cmd::SetToken set_token1;
7605 cmd::SetBucketData set_bucket_data;
7606 cmd::SetToken set_token2;
7607 cmds::ShaderSourceBucket shader_source_bucket;
7608 cmd::SetBucketSize clear_bucket_size;
7611 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7612 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7615 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7616 expected.set_bucket_header.Init(
7617 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7618 expected.set_token1.Init(GetNextToken());
7619 expected.set_bucket_data.Init(
7620 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7621 expected.set_token2.Init(GetNextToken());
7622 expected.shader_source_bucket.Init(%(bucket_args)s);
7623 expected.clear_bucket_size.Init(kBucketId, 0);
7624 const char* kStrings[] = { kString };
7625 const GLint kLength[] = { kStringSize };
7626 gl_->%(name)s(%(gl_args)s);
7627 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7631 for arg
in func
.GetOriginalArgs():
7632 if arg
== self
.__GetDataArg
(func
):
7633 gl_args
.append('kStrings')
7634 elif arg
== self
.__GetLengthArg
(func
):
7635 gl_args
.append('kLength')
7636 elif arg
.name
== 'count':
7639 gl_args
.append(arg
.GetValidClientSideArg(func
))
7642 'gl_args': ", ".join(gl_args
),
7643 'bucket_args': ", ".join(bucket_args
),
7646 def WriteBucketServiceUnitTest(self
, func
, f
, *extras
):
7647 """Overrriden from TypeHandler."""
7649 cmd_args_with_invalid_id
= []
7651 for index
, arg
in enumerate(func
.GetOriginalArgs()):
7652 if arg
== self
.__GetLengthArg
(func
):
7654 elif arg
.name
== 'count':
7656 elif arg
== self
.__GetDataArg
(func
):
7657 cmd_args
.append('kBucketId')
7658 cmd_args_with_invalid_id
.append('kBucketId')
7660 elif index
== 0: # Resource ID arg
7661 cmd_args
.append(arg
.GetValidArg(func
))
7662 cmd_args_with_invalid_id
.append('kInvalidClientId')
7663 gl_args
.append(arg
.GetValidGLArg(func
))
7665 cmd_args
.append(arg
.GetValidArg(func
))
7666 cmd_args_with_invalid_id
.append(arg
.GetValidArg(func
))
7667 gl_args
.append(arg
.GetValidGLArg(func
))
7670 TEST_P(%(test_name)s, %(name)sValidArgs) {
7671 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7672 const uint32 kBucketId = 123;
7673 const char kSource0[] = "hello";
7674 const char* kSource[] = { kSource0 };
7675 const char kValidStrEnd = 0;
7676 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7678 cmd.Init(%(cmd_args)s);
7679 decoder_->set_unsafe_es3_apis_enabled(true);
7680 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7683 decoder_->set_unsafe_es3_apis_enabled(false);
7684 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7689 self
.WriteValidUnitTest(func
, f
, test
, {
7690 'cmd_args': ", ".join(cmd_args
),
7691 'gl_args': ", ".join(gl_args
),
7695 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7696 const uint32 kBucketId = 123;
7697 const char kSource0[] = "hello";
7698 const char* kSource[] = { kSource0 };
7699 const char kValidStrEnd = 0;
7700 decoder_->set_unsafe_es3_apis_enabled(true);
7703 cmd.Init(%(cmd_args)s);
7704 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7705 // Test invalid client.
7706 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7707 cmd.Init(%(cmd_args_with_invalid_id)s);
7708 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7709 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7712 self
.WriteValidUnitTest(func
, f
, test
, {
7713 'cmd_args': ", ".join(cmd_args
),
7714 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id
),
7718 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7719 const uint32 kBucketId = 123;
7720 const char kSource0[] = "hello";
7721 const char* kSource[] = { kSource0 };
7722 const char kValidStrEnd = 0;
7723 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7724 const GLsizei kTests[] = {
7727 std::numeric_limits<GLsizei>::max(),
7730 decoder_->set_unsafe_es3_apis_enabled(true);
7731 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7732 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7734 cmd.Init(%(cmd_args)s);
7735 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7739 self
.WriteValidUnitTest(func
, f
, test
, {
7740 'cmd_args': ", ".join(cmd_args
),
7744 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7745 const uint32 kBucketId = 123;
7746 const char kSource0[] = "hello";
7747 const char* kSource[] = { kSource0 };
7748 const char kInvalidStrEnd = '*';
7749 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7751 cmd.Init(%(cmd_args)s);
7752 decoder_->set_unsafe_es3_apis_enabled(true);
7753 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7756 self
.WriteValidUnitTest(func
, f
, test
, {
7757 'cmd_args': ", ".join(cmd_args
),
7761 class PUTXnHandler(ArrayArgTypeHandler
):
7762 """Handler for glUniform?f functions."""
7764 def WriteHandlerImplementation(self
, func
, f
):
7765 """Overrriden from TypeHandler."""
7766 code
= """ %(type)s temp[%(count)s] = { %(values)s};"""
7769 gl%(name)sv(%(location)s, 1, &temp[0]);
7773 Do%(name)sv(%(location)s, 1, &temp[0]);
7776 args
= func
.GetOriginalArgs()
7777 count
= int(self
.GetArrayCount(func
))
7778 num_args
= len(args
)
7779 for ii
in range(count
):
7780 values
+= "%s, " % args
[len(args
) - count
+ ii
].name
7784 'count': self
.GetArrayCount(func
),
7785 'type': self
.GetArrayType(func
),
7786 'location': args
[0].name
,
7787 'args': func
.MakeOriginalArgString(""),
7791 def WriteServiceUnitTest(self
, func
, f
, *extras
):
7792 """Overrriden from TypeHandler."""
7794 TEST_P(%(test_name)s, %(name)sValidArgs) {
7795 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7796 SpecializedSetup<cmds::%(name)s, 0>(true);
7798 cmd.Init(%(args)s);"""
7801 decoder_->set_unsafe_es3_apis_enabled(true);"""
7803 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7804 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7807 decoder_->set_unsafe_es3_apis_enabled(false);
7808 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7812 args
= func
.GetOriginalArgs()
7813 local_args
= "%s, 1, _" % args
[0].GetValidGLArg(func
)
7814 self
.WriteValidUnitTest(func
, f
, valid_test
, {
7816 'count': self
.GetArrayCount(func
),
7817 'local_args': local_args
,
7821 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7822 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7823 SpecializedSetup<cmds::%(name)s, 0>(false);
7826 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7829 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, {
7830 'name': func
.GetInfo('name'),
7831 'count': self
.GetArrayCount(func
),
7835 class GLcharHandler(CustomHandler
):
7836 """Handler for functions that pass a single string ."""
7838 def WriteImmediateCmdComputeSize(self
, func
, f
):
7839 """Overrriden from TypeHandler."""
7840 f
.write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7841 f
.write(" return static_cast<uint32_t>(\n")
7842 f
.write(" sizeof(ValueType) + data_size); // NOLINT\n")
7845 def WriteImmediateCmdSetHeader(self
, func
, f
):
7846 """Overrriden from TypeHandler."""
7848 void SetHeader(uint32_t data_size) {
7849 header.SetCmdBySize<ValueType>(data_size);
7854 def WriteImmediateCmdInit(self
, func
, f
):
7855 """Overrriden from TypeHandler."""
7856 last_arg
= func
.GetLastOriginalArg()
7857 args
= func
.GetCmdArgs()
7860 set_code
.append(" %s = _%s;" % (arg
.name
, arg
.name
))
7862 void Init(%(typed_args)s, uint32_t _data_size) {
7863 SetHeader(_data_size);
7865 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7870 "typed_args": func
.MakeTypedArgString("_"),
7871 "set_code": "\n".join(set_code
),
7872 "last_arg": last_arg
.name
7875 def WriteImmediateCmdSet(self
, func
, f
):
7876 """Overrriden from TypeHandler."""
7877 last_arg
= func
.GetLastOriginalArg()
7878 f
.write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7879 func
.MakeTypedCmdArgString("_", True))
7880 f
.write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7881 func
.MakeCmdArgString("_"))
7882 f
.write(" return NextImmediateCmdAddress<ValueType>("
7883 "cmd, _data_size);\n")
7887 def WriteImmediateCmdHelper(self
, func
, f
):
7888 """Overrriden from TypeHandler."""
7889 code
= """ void %(name)s(%(typed_args)s) {
7890 const uint32_t data_size = strlen(name);
7891 gles2::cmds::%(name)s* c =
7892 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7894 c->Init(%(args)s, data_size);
7901 "typed_args": func
.MakeTypedOriginalArgString(""),
7902 "args": func
.MakeOriginalArgString(""),
7906 def WriteImmediateFormatTest(self
, func
, f
):
7907 """Overrriden from TypeHandler."""
7910 all_but_last_arg
= func
.GetCmdArgs()[:-1]
7911 for value
, arg
in enumerate(all_but_last_arg
):
7912 init_code
.append(" static_cast<%s>(%d)," % (arg
.type, value
+ 11))
7913 for value
, arg
in enumerate(all_but_last_arg
):
7914 check_code
.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7915 (arg
.type, value
+ 11, arg
.name
))
7917 TEST_F(GLES2FormatTest, %(func_name)s) {
7918 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7919 static const char* const test_str = \"test string\";
7920 void* next_cmd = cmd.Set(
7925 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7926 cmd.header.command);
7927 EXPECT_EQ(sizeof(cmd) +
7928 RoundSizeToMultipleOfEntries(strlen(test_str)),
7929 cmd.header.size * 4u);
7930 EXPECT_EQ(static_cast<char*>(next_cmd),
7931 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7932 RoundSizeToMultipleOfEntries(strlen(test_str)));
7934 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7935 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7938 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7939 sizeof(cmd) + strlen(test_str));
7944 'func_name': func
.name
,
7945 'init_code': "\n".join(init_code
),
7946 'check_code': "\n".join(check_code
),
7950 class GLcharNHandler(CustomHandler
):
7951 """Handler for functions that pass a single string with an optional len."""
7953 def InitFunction(self
, func
):
7954 """Overrriden from TypeHandler."""
7956 func
.AddCmdArg(Argument('bucket_id', 'GLuint'))
7958 def NeedsDataTransferFunction(self
, func
):
7959 """Overriden from TypeHandler."""
7962 def WriteServiceImplementation(self
, func
, f
):
7963 """Overrriden from TypeHandler."""
7964 self
.WriteServiceHandlerFunctionHeader(func
, f
)
7966 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7967 Bucket* bucket = GetBucket(bucket_id);
7968 if (!bucket || bucket->size() == 0) {
7969 return error::kInvalidArguments;
7972 if (!bucket->GetAsString(&str)) {
7973 return error::kInvalidArguments;
7975 %(gl_func_name)s(0, str.c_str());
7976 return error::kNoError;
7981 'gl_func_name': func
.GetGLFunctionName(),
7982 'bucket_id': func
.cmd_args
[0].name
,
7986 class IsHandler(TypeHandler
):
7987 """Handler for glIs____ type and glGetError functions."""
7989 def InitFunction(self
, func
):
7990 """Overrriden from TypeHandler."""
7991 func
.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7992 func
.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7993 if func
.GetInfo('result') == None:
7994 func
.AddInfo('result', ['uint32_t'])
7996 def WriteServiceUnitTest(self
, func
, f
, *extras
):
7997 """Overrriden from TypeHandler."""
7999 TEST_P(%(test_name)s, %(name)sValidArgs) {
8000 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
8001 SpecializedSetup<cmds::%(name)s, 0>(true);
8003 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
8006 decoder_->set_unsafe_es3_apis_enabled(true);"""
8008 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8009 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
8012 decoder_->set_unsafe_es3_apis_enabled(false);
8013 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
8018 if len(func
.GetOriginalArgs()):
8020 self
.WriteValidUnitTest(func
, f
, valid_test
, {
8025 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
8026 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8027 SpecializedSetup<cmds::%(name)s, 0>(false);
8029 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
8030 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
8033 self
.WriteInvalidUnitTest(func
, f
, invalid_test
, {
8038 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
8039 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8040 SpecializedSetup<cmds::%(name)s, 0>(false);"""
8043 decoder_->set_unsafe_es3_apis_enabled(true);"""
8046 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
8047 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
8048 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
8049 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
8052 decoder_->set_unsafe_es3_apis_enabled(true);"""
8056 self
.WriteValidUnitTest(func
, f
, invalid_test
, {
8060 def WriteServiceImplementation(self
, func
, f
):
8061 """Overrriden from TypeHandler."""
8062 self
.WriteServiceHandlerFunctionHeader(func
, f
)
8063 self
.WriteHandlerExtensionCheck(func
, f
)
8064 args
= func
.GetOriginalArgs()
8068 code
= """ typedef cmds::%(func_name)s::Result Result;
8069 Result* result_dst = GetSharedMemoryAs<Result*>(
8070 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
8072 return error::kOutOfBounds;
8075 f
.write(code
% {'func_name': func
.name
})
8076 func
.WriteHandlerValidation(f
)
8078 assert func
.GetInfo('id_mapping')
8079 assert len(func
.GetInfo('id_mapping')) == 1
8080 assert len(args
) == 1
8081 id_type
= func
.GetInfo('id_mapping')[0]
8082 f
.write(" %s service_%s = 0;\n" % (args
[0].type, id_type
.lower()))
8083 f
.write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
8084 (id_type
, id_type
.lower(), id_type
.lower()))
8086 f
.write(" *result_dst = %s(%s);\n" %
8087 (func
.GetGLFunctionName(), func
.MakeOriginalArgString("")))
8088 f
.write(" return error::kNoError;\n")
8092 def WriteGLES2Implementation(self
, func
, f
):
8093 """Overrriden from TypeHandler."""
8094 impl_func
= func
.GetInfo('impl_func')
8095 if impl_func
== None or impl_func
== True:
8096 error_value
= func
.GetInfo("error_value") or "GL_FALSE"
8097 f
.write("%s GLES2Implementation::%s(%s) {\n" %
8098 (func
.return_type
, func
.original_name
,
8099 func
.MakeTypedOriginalArgString("")))
8100 f
.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
8101 self
.WriteTraceEvent(func
, f
)
8102 func
.WriteDestinationInitalizationValidation(f
)
8103 self
.WriteClientGLCallLog(func
, f
)
8104 f
.write(" typedef cmds::%s::Result Result;\n" % func
.name
)
8105 f
.write(" Result* result = GetResultAs<Result*>();\n")
8106 f
.write(" if (!result) {\n")
8107 f
.write(" return %s;\n" % error_value
)
8109 f
.write(" *result = 0;\n")
8110 assert len(func
.GetOriginalArgs()) == 1
8111 id_arg
= func
.GetOriginalArgs()[0]
8112 if id_arg
.type == 'GLsync':
8113 arg_string
= "ToGLuint(%s)" % func
.MakeOriginalArgString("")
8115 arg_string
= func
.MakeOriginalArgString("")
8117 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
8118 (func
.name
, arg_string
))
8119 f
.write(" WaitForCmd();\n")
8120 f
.write(" %s result_value = *result" % func
.return_type
)
8121 if func
.return_type
== "GLboolean":
8123 f
.write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
8124 f
.write(" CheckGLError();\n")
8125 f
.write(" return result_value;\n")
8129 def WriteGLES2ImplementationUnitTest(self
, func
, f
):
8130 """Overrriden from TypeHandler."""
8131 client_test
= func
.GetInfo('client_test')
8132 if client_test
== None or client_test
== True:
8134 TEST_F(GLES2ImplementationTest, %(name)s) {
8140 ExpectedMemoryInfo result1 =
8141 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
8142 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
8144 EXPECT_CALL(*command_buffer(), OnFlush())
8145 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
8146 .RetiresOnSaturation();
8148 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
8149 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
8150 EXPECT_TRUE(result);
8153 args
= func
.GetOriginalArgs()
8154 assert len(args
) == 1
8157 'cmd_id_value': args
[0].GetValidClientSideCmdArg(func
),
8158 'gl_id_value': args
[0].GetValidClientSideArg(func
) })
8161 class STRnHandler(TypeHandler
):
8162 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
8163 GetTranslatedShaderSourceANGLE."""
8165 def InitFunction(self
, func
):
8166 """Overrriden from TypeHandler."""
8167 # remove all but the first cmd args.
8168 cmd_args
= func
.GetCmdArgs()
8170 func
.AddCmdArg(cmd_args
[0])
8171 # add on a bucket id.
8172 func
.AddCmdArg(Argument('bucket_id', 'uint32_t'))
8174 def WriteGLES2Implementation(self
, func
, f
):
8175 """Overrriden from TypeHandler."""
8176 code_1
= """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
8177 GPU_CLIENT_SINGLE_THREAD_CHECK();
8179 code_2
= """ GPU_CLIENT_LOG("[" << GetLogPrefix()
8180 << "] gl%(func_name)s" << "("
8183 << static_cast<void*>(%(arg2)s) << ", "
8184 << static_cast<void*>(%(arg3)s) << ")");
8185 helper_->SetBucketSize(kResultBucketId, 0);
8186 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8188 GLsizei max_size = 0;
8189 if (GetBucketAsString(kResultBucketId, &str)) {
8192 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8193 memcpy(%(dest_name)s, str.c_str(), max_size);
8194 %(dest_name)s[max_size] = '\\0';
8195 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8198 if (%(length_name)s != NULL) {
8199 *%(length_name)s = max_size;
8204 args
= func
.GetOriginalArgs()
8206 'return_type': func
.return_type
,
8207 'func_name': func
.original_name
,
8208 'args': func
.MakeTypedOriginalArgString(""),
8209 'id_name': args
[0].name
,
8210 'bufsize_name': args
[1].name
,
8211 'length_name': args
[2].name
,
8212 'dest_name': args
[3].name
,
8213 'arg0': args
[0].name
,
8214 'arg1': args
[1].name
,
8215 'arg2': args
[2].name
,
8216 'arg3': args
[3].name
,
8218 f
.write(code_1
% str_args
)
8219 func
.WriteDestinationInitalizationValidation(f
)
8220 f
.write(code_2
% str_args
)
8222 def WriteServiceUnitTest(self
, func
, f
, *extras
):
8223 """Overrriden from TypeHandler."""
8225 TEST_P(%(test_name)s, %(name)sValidArgs) {
8226 const char* kInfo = "hello";
8227 const uint32_t kBucketId = 123;
8228 SpecializedSetup<cmds::%(name)s, 0>(true);
8230 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8231 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8232 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8235 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8236 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8237 ASSERT_TRUE(bucket != NULL);
8238 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8239 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8241 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8244 args
= func
.GetOriginalArgs()
8245 id_name
= args
[0].GetValidGLArg(func
)
8246 get_len_func
= func
.GetInfo('get_len_func')
8247 get_len_enum
= func
.GetInfo('get_len_enum')
8250 'get_len_func': get_len_func
,
8251 'get_len_enum': get_len_enum
,
8252 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8253 args
[0].GetValidGLArg(func
),
8254 'args': '%s, kBucketId' % args
[0].GetValidArg(func
),
8255 'expect_len_code': '',
8257 if get_len_func
and get_len_func
[0:2] == 'gl':
8258 sub
['expect_len_code'] = (
8259 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8260 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8261 get_len_func
[2:], id_name
, get_len_enum
)
8262 self
.WriteValidUnitTest(func
, f
, valid_test
, sub
, *extras
)
8265 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8266 const uint32_t kBucketId = 123;
8267 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8270 cmd.Init(kInvalidClientId, kBucketId);
8271 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8272 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8275 self
.WriteValidUnitTest(func
, f
, invalid_test
, *extras
)
8277 def WriteServiceImplementation(self
, func
, f
):
8278 """Overrriden from TypeHandler."""
8281 class NamedType(object):
8282 """A class that represents a type of an argument in a client function.
8284 A type of an argument that is to be passed through in the command buffer
8285 command. Currently used only for the arguments that are specificly named in
8286 the 'cmd_buffer_functions.txt' f, mostly enums.
8289 def __init__(self
, info
):
8290 assert not 'is_complete' in info
or info
['is_complete'] == True
8292 self
.valid
= info
['valid']
8293 if 'invalid' in info
:
8294 self
.invalid
= info
['invalid']
8297 if 'valid_es3' in info
:
8298 self
.valid_es3
= info
['valid_es3']
8301 if 'deprecated_es3' in info
:
8302 self
.deprecated_es3
= info
['deprecated_es3']
8304 self
.deprecated_es3
= []
8307 return self
.info
['type']
8309 def GetInvalidValues(self
):
8312 def GetValidValues(self
):
8315 def GetValidValuesES3(self
):
8316 return self
.valid_es3
8318 def GetDeprecatedValuesES3(self
):
8319 return self
.deprecated_es3
8321 def IsConstant(self
):
8322 if not 'is_complete' in self
.info
:
8325 return len(self
.GetValidValues()) == 1
8327 def GetConstantValue(self
):
8328 return self
.GetValidValues()[0]
8330 class Argument(object):
8331 """A class that represents a function argument."""
8334 'GLenum': 'uint32_t',
8336 'GLintptr': 'int32_t',
8337 'GLsizei': 'int32_t',
8338 'GLsizeiptr': 'int32_t',
8340 'GLclampf': 'float',
8342 need_validation_
= ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8344 def __init__(self
, name
, type):
8346 self
.optional
= type.endswith("Optional*")
8348 type = type[:-9] + "*"
8351 if type in self
.cmd_type_map_
:
8352 self
.cmd_type
= self
.cmd_type_map_
[type]
8354 self
.cmd_type
= 'uint32_t'
8356 def IsPointer(self
):
8357 """Returns true if argument is a pointer."""
8360 def IsPointer2D(self
):
8361 """Returns true if argument is a 2D pointer."""
8364 def IsConstant(self
):
8365 """Returns true if the argument has only one valid value."""
8368 def AddCmdArgs(self
, args
):
8369 """Adds command arguments for this argument to the given list."""
8370 if not self
.IsConstant():
8371 return args
.append(self
)
8373 def AddInitArgs(self
, args
):
8374 """Adds init arguments for this argument to the given list."""
8375 if not self
.IsConstant():
8376 return args
.append(self
)
8378 def GetValidArg(self
, func
):
8379 """Gets a valid value for this argument."""
8380 valid_arg
= func
.GetValidArg(self
)
8381 if valid_arg
!= None:
8384 index
= func
.GetOriginalArgs().index(self
)
8385 return str(index
+ 1)
8387 def GetValidClientSideArg(self
, func
):
8388 """Gets a valid value for this argument."""
8389 valid_arg
= func
.GetValidArg(self
)
8390 if valid_arg
!= None:
8393 if self
.IsPointer():
8395 index
= func
.GetOriginalArgs().index(self
)
8396 if self
.type == 'GLsync':
8397 return ("reinterpret_cast<GLsync>(%d)" % (index
+ 1))
8398 return str(index
+ 1)
8400 def GetValidClientSideCmdArg(self
, func
):
8401 """Gets a valid value for this argument."""
8402 valid_arg
= func
.GetValidArg(self
)
8403 if valid_arg
!= None:
8406 index
= func
.GetOriginalArgs().index(self
)
8407 return str(index
+ 1)
8410 index
= func
.GetCmdArgs().index(self
)
8411 return str(index
+ 1)
8413 def GetValidGLArg(self
, func
):
8414 """Gets a valid GL value for this argument."""
8415 value
= self
.GetValidArg(func
)
8416 if self
.type == 'GLsync':
8417 return ("reinterpret_cast<GLsync>(%s)" % value
)
8420 def GetValidNonCachedClientSideArg(self
, func
):
8421 """Returns a valid value for this argument in a GL call.
8422 Using the value will produce a command buffer service invocation.
8423 Returns None if there is no such value."""
8425 if self
.type == 'GLsync':
8426 return ("reinterpret_cast<GLsync>(%s)" % value
)
8429 def GetValidNonCachedClientSideCmdArg(self
, func
):
8430 """Returns a valid value for this argument in a command buffer command.
8431 Calling the GL function with the value returned by
8432 GetValidNonCachedClientSideArg will result in a command buffer command
8433 that contains the value returned by this function. """
8436 def GetNumInvalidValues(self
, func
):
8437 """returns the number of invalid values to be tested."""
8440 def GetInvalidArg(self
, index
):
8441 """returns an invalid value and expected parse result by index."""
8442 return ("---ERROR0---", "---ERROR2---", None)
8444 def GetLogArg(self
):
8445 """Get argument appropriate for LOG macro."""
8446 if self
.type == 'GLboolean':
8447 return 'GLES2Util::GetStringBool(%s)' % self
.name
8448 if self
.type == 'GLenum':
8449 return 'GLES2Util::GetStringEnum(%s)' % self
.name
8452 def WriteGetCode(self
, f
):
8453 """Writes the code to get an argument from a command structure."""
8454 if self
.type == 'GLsync':
8458 f
.write(" %s %s = static_cast<%s>(c.%s);\n" %
8459 (my_type
, self
.name
, my_type
, self
.name
))
8461 def WriteValidationCode(self
, f
, func
):
8462 """Writes the validation code for an argument."""
8465 def WriteClientSideValidationCode(self
, f
, func
):
8466 """Writes the validation code for an argument."""
8469 def WriteDestinationInitalizationValidation(self
, f
, func
):
8470 """Writes the client side destintion initialization validation."""
8473 def WriteDestinationInitalizationValidatationIfNeeded(self
, f
, func
):
8474 """Writes the client side destintion initialization validation if needed."""
8475 parts
= self
.type.split(" ")
8478 if parts
[0] in self
.need_validation_
:
8480 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8481 ("OPTIONAL_" if self
.optional
else "", self
.type[:-1], self
.name
))
8483 def GetImmediateVersion(self
):
8484 """Gets the immediate version of this argument."""
8487 def GetBucketVersion(self
):
8488 """Gets the bucket version of this argument."""
8492 class BoolArgument(Argument
):
8493 """class for GLboolean"""
8495 def __init__(self
, name
, type):
8496 Argument
.__init
__(self
, name
, 'GLboolean')
8498 def GetValidArg(self
, func
):
8499 """Gets a valid value for this argument."""
8502 def GetValidClientSideArg(self
, func
):
8503 """Gets a valid value for this argument."""
8506 def GetValidClientSideCmdArg(self
, func
):
8507 """Gets a valid value for this argument."""
8510 def GetValidGLArg(self
, func
):
8511 """Gets a valid GL value for this argument."""
8515 class UniformLocationArgument(Argument
):
8516 """class for uniform locations."""
8518 def __init__(self
, name
):
8519 Argument
.__init
__(self
, name
, "GLint")
8521 def WriteGetCode(self
, f
):
8522 """Writes the code to get an argument from a command structure."""
8523 code
= """ %s %s = static_cast<%s>(c.%s);
8525 f
.write(code
% (self
.type, self
.name
, self
.type, self
.name
))
8527 class DataSizeArgument(Argument
):
8528 """class for data_size which Bucket commands do not need."""
8530 def __init__(self
, name
):
8531 Argument
.__init
__(self
, name
, "uint32_t")
8533 def GetBucketVersion(self
):
8537 class SizeArgument(Argument
):
8538 """class for GLsizei and GLsizeiptr."""
8540 def GetNumInvalidValues(self
, func
):
8541 """overridden from Argument."""
8542 if func
.IsImmediate():
8546 def GetInvalidArg(self
, index
):
8547 """overridden from Argument."""
8548 return ("-1", "kNoError", "GL_INVALID_VALUE")
8550 def WriteValidationCode(self
, f
, func
):
8551 """overridden from Argument."""
8554 code
= """ if (%(var_name)s < 0) {
8555 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8556 return error::kNoError;
8560 "var_name": self
.name
,
8561 "func_name": func
.original_name
,
8564 def WriteClientSideValidationCode(self
, f
, func
):
8565 """overridden from Argument."""
8566 code
= """ if (%(var_name)s < 0) {
8567 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8572 "var_name": self
.name
,
8573 "func_name": func
.original_name
,
8577 class SizeNotNegativeArgument(SizeArgument
):
8578 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8580 def __init__(self
, name
, type, gl_type
):
8581 SizeArgument
.__init
__(self
, name
, gl_type
)
8583 def GetInvalidArg(self
, index
):
8584 """overridden from SizeArgument."""
8585 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8587 def WriteValidationCode(self
, f
, func
):
8588 """overridden from SizeArgument."""
8592 class EnumBaseArgument(Argument
):
8593 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8594 ValidatedBoolArgument."""
8596 def __init__(self
, name
, gl_type
, type, gl_error
):
8597 Argument
.__init
__(self
, name
, gl_type
)
8599 self
.gl_error
= gl_error
8600 name
= type[len(gl_type
):]
8601 self
.type_name
= name
8602 self
.named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
8604 def IsConstant(self
):
8605 return self
.named_type
.IsConstant()
8607 def GetConstantValue(self
):
8608 return self
.named_type
.GetConstantValue()
8610 def WriteValidationCode(self
, f
, func
):
8613 if self
.named_type
.IsConstant():
8615 f
.write(" if (!validators_->%s.IsValid(%s)) {\n" %
8616 (ToUnderscore(self
.type_name
), self
.name
))
8617 if self
.gl_error
== "GL_INVALID_ENUM":
8619 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8620 (func
.original_name
, self
.name
, self
.name
))
8623 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8624 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8625 f
.write(" return error::kNoError;\n")
8628 def WriteClientSideValidationCode(self
, f
, func
):
8629 if not self
.named_type
.IsConstant():
8631 f
.write(" if (%s != %s) {" % (self
.name
,
8632 self
.GetConstantValue()))
8634 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8635 (self
.gl_error
, func
.original_name
, self
.name
, self
.gl_error
))
8636 if func
.return_type
== "void":
8637 f
.write(" return;\n")
8639 f
.write(" return %s;\n" % func
.GetErrorReturnString())
8642 def GetValidArg(self
, func
):
8643 valid_arg
= func
.GetValidArg(self
)
8644 if valid_arg
!= None:
8646 valid
= self
.named_type
.GetValidValues()
8650 index
= func
.GetOriginalArgs().index(self
)
8651 return str(index
+ 1)
8653 def GetValidClientSideArg(self
, func
):
8654 """Gets a valid value for this argument."""
8655 return self
.GetValidArg(func
)
8657 def GetValidClientSideCmdArg(self
, func
):
8658 """Gets a valid value for this argument."""
8659 valid_arg
= func
.GetValidArg(self
)
8660 if valid_arg
!= None:
8663 valid
= self
.named_type
.GetValidValues()
8668 index
= func
.GetOriginalArgs().index(self
)
8669 return str(index
+ 1)
8672 index
= func
.GetCmdArgs().index(self
)
8673 return str(index
+ 1)
8675 def GetValidGLArg(self
, func
):
8676 """Gets a valid value for this argument."""
8677 return self
.GetValidArg(func
)
8679 def GetNumInvalidValues(self
, func
):
8680 """returns the number of invalid values to be tested."""
8681 return len(self
.named_type
.GetInvalidValues())
8683 def GetInvalidArg(self
, index
):
8684 """returns an invalid value by index."""
8685 invalid
= self
.named_type
.GetInvalidValues()
8687 num_invalid
= len(invalid
)
8688 if index
>= num_invalid
:
8689 index
= num_invalid
- 1
8690 return (invalid
[index
], "kNoError", self
.gl_error
)
8691 return ("---ERROR1---", "kNoError", self
.gl_error
)
8694 class EnumArgument(EnumBaseArgument
):
8695 """A class that represents a GLenum argument"""
8697 def __init__(self
, name
, type):
8698 EnumBaseArgument
.__init
__(self
, name
, "GLenum", type, "GL_INVALID_ENUM")
8700 def GetLogArg(self
):
8701 """Overridden from Argument."""
8702 return ("GLES2Util::GetString%s(%s)" %
8703 (self
.type_name
, self
.name
))
8706 class IntArgument(EnumBaseArgument
):
8707 """A class for a GLint argument that can only accept specific values.
8709 For example glTexImage2D takes a GLint for its internalformat
8710 argument instead of a GLenum.
8713 def __init__(self
, name
, type):
8714 EnumBaseArgument
.__init
__(self
, name
, "GLint", type, "GL_INVALID_VALUE")
8717 class ValidatedBoolArgument(EnumBaseArgument
):
8718 """A class for a GLboolean argument that can only accept specific values.
8720 For example glUniformMatrix takes a GLboolean for it's transpose but it
8724 def __init__(self
, name
, type):
8725 EnumBaseArgument
.__init
__(self
, name
, "GLboolean", type, "GL_INVALID_VALUE")
8727 def GetLogArg(self
):
8728 """Overridden from Argument."""
8729 return 'GLES2Util::GetStringBool(%s)' % self
.name
8732 class BitFieldArgument(EnumBaseArgument
):
8733 """A class for a GLbitfield argument that can only accept specific values.
8735 For example glFenceSync takes a GLbitfield for its flags argument bit it
8739 def __init__(self
, name
, type):
8740 EnumBaseArgument
.__init
__(self
, name
, "GLbitfield", type,
8744 class ImmediatePointerArgument(Argument
):
8745 """A class that represents an immediate argument to a function.
8747 An immediate argument is one where the data follows the command.
8750 def IsPointer(self
):
8753 def GetPointedType(self
):
8754 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8756 return match
.groupdict()['element_type']
8758 def AddCmdArgs(self
, args
):
8759 """Overridden from Argument."""
8762 def WriteGetCode(self
, f
):
8763 """Overridden from Argument."""
8765 " %s %s = GetImmediateDataAs<%s>(\n" %
8766 (self
.type, self
.name
, self
.type))
8767 f
.write(" c, data_size, immediate_data_size);\n")
8769 def WriteValidationCode(self
, f
, func
):
8770 """Overridden from Argument."""
8773 f
.write(" if (%s == NULL) {\n" % self
.name
)
8774 f
.write(" return error::kOutOfBounds;\n")
8777 def GetImmediateVersion(self
):
8778 """Overridden from Argument."""
8781 def WriteDestinationInitalizationValidation(self
, f
, func
):
8782 """Overridden from Argument."""
8783 self
.WriteDestinationInitalizationValidatationIfNeeded(f
, func
)
8785 def GetLogArg(self
):
8786 """Overridden from Argument."""
8787 return "static_cast<const void*>(%s)" % self
.name
8790 class PointerArgument(Argument
):
8791 """A class that represents a pointer argument to a function."""
8793 def IsPointer(self
):
8794 """Overridden from Argument."""
8797 def IsPointer2D(self
):
8798 """Overridden from Argument."""
8799 return self
.type.count('*') == 2
8801 def GetPointedType(self
):
8802 match
= re
.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self
.type)
8804 return match
.groupdict()['element_type']
8806 def GetValidArg(self
, func
):
8807 """Overridden from Argument."""
8808 return "shared_memory_id_, shared_memory_offset_"
8810 def GetValidGLArg(self
, func
):
8811 """Overridden from Argument."""
8812 return "reinterpret_cast<%s>(shared_memory_address_)" % self
.type
8814 def GetNumInvalidValues(self
, func
):
8815 """Overridden from Argument."""
8818 def GetInvalidArg(self
, index
):
8819 """Overridden from Argument."""
8821 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8823 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8824 "kOutOfBounds", None)
8826 def GetLogArg(self
):
8827 """Overridden from Argument."""
8828 return "static_cast<const void*>(%s)" % self
.name
8830 def AddCmdArgs(self
, args
):
8831 """Overridden from Argument."""
8832 args
.append(Argument("%s_shm_id" % self
.name
, 'uint32_t'))
8833 args
.append(Argument("%s_shm_offset" % self
.name
, 'uint32_t'))
8835 def WriteGetCode(self
, f
):
8836 """Overridden from Argument."""
8838 " %s %s = GetSharedMemoryAs<%s>(\n" %
8839 (self
.type, self
.name
, self
.type))
8841 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8842 (self
.name
, self
.name
))
8844 def WriteValidationCode(self
, f
, func
):
8845 """Overridden from Argument."""
8848 f
.write(" if (%s == NULL) {\n" % self
.name
)
8849 f
.write(" return error::kOutOfBounds;\n")
8852 def GetImmediateVersion(self
):
8853 """Overridden from Argument."""
8854 return ImmediatePointerArgument(self
.name
, self
.type)
8856 def GetBucketVersion(self
):
8857 """Overridden from Argument."""
8858 if self
.type.find('char') >= 0:
8859 if self
.IsPointer2D():
8860 return InputStringArrayBucketArgument(self
.name
, self
.type)
8861 return InputStringBucketArgument(self
.name
, self
.type)
8862 return BucketPointerArgument(self
.name
, self
.type)
8864 def WriteDestinationInitalizationValidation(self
, f
, func
):
8865 """Overridden from Argument."""
8866 self
.WriteDestinationInitalizationValidatationIfNeeded(f
, func
)
8869 class BucketPointerArgument(PointerArgument
):
8870 """A class that represents an bucket argument to a function."""
8872 def AddCmdArgs(self
, args
):
8873 """Overridden from Argument."""
8876 def WriteGetCode(self
, f
):
8877 """Overridden from Argument."""
8879 " %s %s = bucket->GetData(0, data_size);\n" %
8880 (self
.type, self
.name
))
8882 def WriteValidationCode(self
, f
, func
):
8883 """Overridden from Argument."""
8886 def GetImmediateVersion(self
):
8887 """Overridden from Argument."""
8890 def WriteDestinationInitalizationValidation(self
, f
, func
):
8891 """Overridden from Argument."""
8892 self
.WriteDestinationInitalizationValidatationIfNeeded(f
, func
)
8894 def GetLogArg(self
):
8895 """Overridden from Argument."""
8896 return "static_cast<const void*>(%s)" % self
.name
8899 class InputStringBucketArgument(Argument
):
8900 """A string input argument where the string is passed in a bucket."""
8902 def __init__(self
, name
, type):
8903 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8905 def IsPointer(self
):
8906 """Overridden from Argument."""
8909 def IsPointer2D(self
):
8910 """Overridden from Argument."""
8914 class InputStringArrayBucketArgument(Argument
):
8915 """A string array input argument where the strings are passed in a bucket."""
8917 def __init__(self
, name
, type):
8918 Argument
.__init
__(self
, name
+ "_bucket_id", "uint32_t")
8919 self
._original
_name
= name
8921 def WriteGetCode(self
, f
):
8922 """Overridden from Argument."""
8924 Bucket* bucket = GetBucket(c.%(name)s);
8926 return error::kInvalidArguments;
8929 std::vector<char*> strs;
8930 std::vector<GLint> len;
8931 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8932 return error::kInvalidArguments;
8934 const char** %(original_name)s =
8935 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8936 const GLint* length =
8937 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8942 'original_name': self
._original
_name
,
8945 def GetValidArg(self
, func
):
8946 return "kNameBucketId"
8948 def GetValidGLArg(self
, func
):
8951 def IsPointer(self
):
8952 """Overridden from Argument."""
8955 def IsPointer2D(self
):
8956 """Overridden from Argument."""
8960 class ResourceIdArgument(Argument
):
8961 """A class that represents a resource id argument to a function."""
8963 def __init__(self
, name
, type):
8964 match
= re
.match("(GLid\w+)", type)
8965 self
.resource_type
= match
.group(1)[4:]
8966 if self
.resource_type
== "Sync":
8967 type = type.replace(match
.group(1), "GLsync")
8969 type = type.replace(match
.group(1), "GLuint")
8970 Argument
.__init
__(self
, name
, type)
8972 def WriteGetCode(self
, f
):
8973 """Overridden from Argument."""
8974 if self
.type == "GLsync":
8978 f
.write(" %s %s = c.%s;\n" % (my_type
, self
.name
, self
.name
))
8980 def GetValidArg(self
, func
):
8981 return "client_%s_id_" % self
.resource_type
.lower()
8983 def GetValidGLArg(self
, func
):
8984 if self
.resource_type
== "Sync":
8985 return "reinterpret_cast<GLsync>(kService%sId)" % self
.resource_type
8986 return "kService%sId" % self
.resource_type
8989 class ResourceIdBindArgument(Argument
):
8990 """Represents a resource id argument to a bind function."""
8992 def __init__(self
, name
, type):
8993 match
= re
.match("(GLidBind\w+)", type)
8994 self
.resource_type
= match
.group(1)[8:]
8995 type = type.replace(match
.group(1), "GLuint")
8996 Argument
.__init
__(self
, name
, type)
8998 def WriteGetCode(self
, f
):
8999 """Overridden from Argument."""
9000 code
= """ %(type)s %(name)s = c.%(name)s;
9002 f
.write(code
% {'type': self
.type, 'name': self
.name
})
9004 def GetValidArg(self
, func
):
9005 return "client_%s_id_" % self
.resource_type
.lower()
9007 def GetValidGLArg(self
, func
):
9008 return "kService%sId" % self
.resource_type
9011 class ResourceIdZeroArgument(Argument
):
9012 """Represents a resource id argument to a function that can be zero."""
9014 def __init__(self
, name
, type):
9015 match
= re
.match("(GLidZero\w+)", type)
9016 self
.resource_type
= match
.group(1)[8:]
9017 type = type.replace(match
.group(1), "GLuint")
9018 Argument
.__init
__(self
, name
, type)
9020 def WriteGetCode(self
, f
):
9021 """Overridden from Argument."""
9022 f
.write(" %s %s = c.%s;\n" % (self
.type, self
.name
, self
.name
))
9024 def GetValidArg(self
, func
):
9025 return "client_%s_id_" % self
.resource_type
.lower()
9027 def GetValidGLArg(self
, func
):
9028 return "kService%sId" % self
.resource_type
9030 def GetNumInvalidValues(self
, func
):
9031 """returns the number of invalid values to be tested."""
9034 def GetInvalidArg(self
, index
):
9035 """returns an invalid value by index."""
9036 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
9039 class Function(object):
9040 """A class that represents a function."""
9044 'Bind': BindHandler(),
9045 'Create': CreateHandler(),
9046 'Custom': CustomHandler(),
9047 'Data': DataHandler(),
9048 'Delete': DeleteHandler(),
9049 'DELn': DELnHandler(),
9050 'GENn': GENnHandler(),
9051 'GETn': GETnHandler(),
9052 'GLchar': GLcharHandler(),
9053 'GLcharN': GLcharNHandler(),
9054 'HandWritten': HandWrittenHandler(),
9056 'Manual': ManualHandler(),
9057 'PUT': PUTHandler(),
9058 'PUTn': PUTnHandler(),
9059 'PUTSTR': PUTSTRHandler(),
9060 'PUTXn': PUTXnHandler(),
9061 'StateSet': StateSetHandler(),
9062 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
9063 'StateSetFrontBack': StateSetFrontBackHandler(),
9064 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
9065 'StateSetNamedParameter': StateSetNamedParameter(),
9066 'STRn': STRnHandler(),
9069 def __init__(self
, name
, info
):
9071 self
.original_name
= info
['original_name']
9073 self
.original_args
= self
.ParseArgs(info
['original_args'])
9075 if 'cmd_args' in info
:
9076 self
.args_for_cmds
= self
.ParseArgs(info
['cmd_args'])
9078 self
.args_for_cmds
= self
.original_args
[:]
9080 self
.return_type
= info
['return_type']
9081 if self
.return_type
!= 'void':
9082 self
.return_arg
= CreateArg(info
['return_type'] + " result")
9084 self
.return_arg
= None
9086 self
.num_pointer_args
= sum(
9087 [1 for arg
in self
.args_for_cmds
if arg
.IsPointer()])
9088 if self
.num_pointer_args
> 0:
9089 for arg
in reversed(self
.original_args
):
9091 self
.last_original_pointer_arg
= arg
9094 self
.last_original_pointer_arg
= None
9096 self
.type_handler
= self
.type_handlers
[info
['type']]
9097 self
.can_auto_generate
= (self
.num_pointer_args
== 0 and
9098 info
['return_type'] == "void")
9101 def ParseArgs(self
, arg_string
):
9102 """Parses a function arg string."""
9104 parts
= arg_string
.split(',')
9105 for arg_string
in parts
:
9106 arg
= CreateArg(arg_string
)
9111 def IsType(self
, type_name
):
9112 """Returns true if function is a certain type."""
9113 return self
.info
['type'] == type_name
9115 def InitFunction(self
):
9116 """Creates command args and calls the init function for the type handler.
9118 Creates argument lists for command buffer commands, eg. self.cmd_args and
9120 Calls the type function initialization.
9121 Override to create different kind of command buffer command argument lists.
9124 for arg
in self
.args_for_cmds
:
9125 arg
.AddCmdArgs(self
.cmd_args
)
9128 for arg
in self
.args_for_cmds
:
9129 arg
.AddInitArgs(self
.init_args
)
9132 self
.init_args
.append(self
.return_arg
)
9134 self
.type_handler
.InitFunction(self
)
9136 def IsImmediate(self
):
9137 """Returns whether the function is immediate data function or not."""
9141 """Returns whether the function has service side validation or not."""
9142 return self
.GetInfo('unsafe', False)
9144 def GetInfo(self
, name
, default
= None):
9145 """Returns a value from the function info for this function."""
9146 if name
in self
.info
:
9147 return self
.info
[name
]
9150 def GetValidArg(self
, arg
):
9151 """Gets a valid argument value for the parameter arg from the function info
9154 index
= self
.GetOriginalArgs().index(arg
)
9158 valid_args
= self
.GetInfo('valid_args')
9159 if valid_args
and str(index
) in valid_args
:
9160 return valid_args
[str(index
)]
9163 def AddInfo(self
, name
, value
):
9165 self
.info
[name
] = value
9167 def IsExtension(self
):
9168 return self
.GetInfo('extension') or self
.GetInfo('extension_flag')
9170 def IsCoreGLFunction(self
):
9171 return (not self
.IsExtension() and
9172 not self
.GetInfo('pepper_interface') and
9173 not self
.IsUnsafe())
9175 def InPepperInterface(self
, interface
):
9176 ext
= self
.GetInfo('pepper_interface')
9177 if not interface
.GetName():
9178 return self
.IsCoreGLFunction()
9179 return ext
== interface
.GetName()
9181 def InAnyPepperExtension(self
):
9182 return self
.IsCoreGLFunction() or self
.GetInfo('pepper_interface')
9184 def GetErrorReturnString(self
):
9185 if self
.GetInfo("error_return"):
9186 return self
.GetInfo("error_return")
9187 elif self
.return_type
== "GLboolean":
9189 elif "*" in self
.return_type
:
9193 def GetGLFunctionName(self
):
9194 """Gets the function to call to execute GL for this command."""
9195 if self
.GetInfo('decoder_func'):
9196 return self
.GetInfo('decoder_func')
9197 return "gl%s" % self
.original_name
9199 def GetGLTestFunctionName(self
):
9200 gl_func_name
= self
.GetInfo('gl_test_func')
9201 if gl_func_name
== None:
9202 gl_func_name
= self
.GetGLFunctionName()
9203 if gl_func_name
.startswith("gl"):
9204 gl_func_name
= gl_func_name
[2:]
9206 gl_func_name
= self
.original_name
9209 def GetDataTransferMethods(self
):
9210 return self
.GetInfo('data_transfer_methods',
9211 ['immediate' if self
.num_pointer_args
== 1 else 'shm'])
9213 def AddCmdArg(self
, arg
):
9214 """Adds a cmd argument to this function."""
9215 self
.cmd_args
.append(arg
)
9217 def GetCmdArgs(self
):
9218 """Gets the command args for this function."""
9219 return self
.cmd_args
9221 def ClearCmdArgs(self
):
9222 """Clears the command args for this function."""
9225 def GetCmdConstants(self
):
9226 """Gets the constants for this function."""
9227 return [arg
for arg
in self
.args_for_cmds
if arg
.IsConstant()]
9229 def GetInitArgs(self
):
9230 """Gets the init args for this function."""
9231 return self
.init_args
9233 def GetOriginalArgs(self
):
9234 """Gets the original arguments to this function."""
9235 return self
.original_args
9237 def GetLastOriginalArg(self
):
9238 """Gets the last original argument to this function."""
9239 return self
.original_args
[len(self
.original_args
) - 1]
9241 def GetLastOriginalPointerArg(self
):
9242 return self
.last_original_pointer_arg
9244 def GetResourceIdArg(self
):
9245 for arg
in self
.original_args
:
9246 if hasattr(arg
, 'resource_type'):
9250 def _MaybePrependComma(self
, arg_string
, add_comma
):
9251 """Adds a comma if arg_string is not empty and add_comma is true."""
9253 if add_comma
and len(arg_string
):
9255 return "%s%s" % (comma
, arg_string
)
9257 def MakeTypedOriginalArgString(self
, prefix
, add_comma
= False):
9258 """Gets a list of arguments as they are in GL."""
9259 args
= self
.GetOriginalArgs()
9260 arg_string
= ", ".join(
9261 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9262 return self
._MaybePrependComma
(arg_string
, add_comma
)
9264 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9265 """Gets the list of arguments as they are in GL."""
9266 args
= self
.GetOriginalArgs()
9267 arg_string
= separator
.join(
9268 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9269 return self
._MaybePrependComma
(arg_string
, add_comma
)
9271 def MakeHelperArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9272 """Gets a list of GL arguments after removing unneeded arguments."""
9273 args
= self
.GetOriginalArgs()
9274 arg_string
= separator
.join(
9275 ["%s%s" % (prefix
, arg
.name
)
9276 for arg
in args
if not arg
.IsConstant()])
9277 return self
._MaybePrependComma
(arg_string
, add_comma
)
9279 def MakeTypedPepperArgString(self
, prefix
):
9280 """Gets a list of arguments as they need to be for Pepper."""
9281 if self
.GetInfo("pepper_args"):
9282 return self
.GetInfo("pepper_args")
9284 return self
.MakeTypedOriginalArgString(prefix
, False)
9286 def MapCTypeToPepperIdlType(self
, ctype
, is_for_return_type
=False):
9287 """Converts a C type name to the corresponding Pepper IDL type."""
9289 'char*': '[out] str_t',
9290 'const GLchar* const*': '[out] cstr_t',
9291 'const char*': 'cstr_t',
9292 'const void*': 'mem_t',
9293 'void*': '[out] mem_t',
9294 'void**': '[out] mem_ptr_t',
9296 # We use "GLxxx_ptr_t" for "GLxxx*".
9297 matched
= re
.match(r
'(const )?(GL\w+)\*$', ctype
)
9299 idltype
= matched
.group(2) + '_ptr_t'
9300 if not matched
.group(1):
9301 idltype
= '[out] ' + idltype
9302 # If an in/out specifier is not specified yet, prepend [in].
9303 if idltype
[0] != '[':
9304 idltype
= '[in] ' + idltype
9305 # Strip the in/out specifier for a return type.
9306 if is_for_return_type
:
9307 idltype
= re
.sub(r
'\[\w+\] ', '', idltype
)
9310 def MakeTypedPepperIdlArgStrings(self
):
9311 """Gets a list of arguments as they need to be for Pepper IDL."""
9312 args
= self
.GetOriginalArgs()
9313 return ["%s %s" % (self
.MapCTypeToPepperIdlType(arg
.type), arg
.name
)
9316 def GetPepperName(self
):
9317 if self
.GetInfo("pepper_name"):
9318 return self
.GetInfo("pepper_name")
9321 def MakeTypedCmdArgString(self
, prefix
, add_comma
= False):
9322 """Gets a typed list of arguments as they need to be for command buffers."""
9323 args
= self
.GetCmdArgs()
9324 arg_string
= ", ".join(
9325 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9326 return self
._MaybePrependComma
(arg_string
, add_comma
)
9328 def MakeCmdArgString(self
, prefix
, add_comma
= False):
9329 """Gets the list of arguments as they need to be for command buffers."""
9330 args
= self
.GetCmdArgs()
9331 arg_string
= ", ".join(
9332 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9333 return self
._MaybePrependComma
(arg_string
, add_comma
)
9335 def MakeTypedInitString(self
, prefix
, add_comma
= False):
9336 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9337 args
= self
.GetInitArgs()
9338 arg_string
= ", ".join(
9339 ["%s %s%s" % (arg
.type, prefix
, arg
.name
) for arg
in args
])
9340 return self
._MaybePrependComma
(arg_string
, add_comma
)
9342 def MakeInitString(self
, prefix
, add_comma
= False):
9343 """Gets the list of arguments as they need to be for cmd Init/Set."""
9344 args
= self
.GetInitArgs()
9345 arg_string
= ", ".join(
9346 ["%s%s" % (prefix
, arg
.name
) for arg
in args
])
9347 return self
._MaybePrependComma
(arg_string
, add_comma
)
9349 def MakeLogArgString(self
):
9350 """Makes a string of the arguments for the LOG macros"""
9351 args
= self
.GetOriginalArgs()
9352 return ' << ", " << '.join([arg
.GetLogArg() for arg
in args
])
9354 def WriteHandlerValidation(self
, f
):
9355 """Writes validation code for the function."""
9356 for arg
in self
.GetOriginalArgs():
9357 arg
.WriteValidationCode(f
, self
)
9358 self
.WriteValidationCode(f
)
9360 def WriteHandlerImplementation(self
, f
):
9361 """Writes the handler implementation for this command."""
9362 self
.type_handler
.WriteHandlerImplementation(self
, f
)
9364 def WriteValidationCode(self
, f
):
9365 """Writes the validation code for a command."""
9368 def WriteCmdFlag(self
, f
):
9369 """Writes the cmd cmd_flags constant."""
9371 # By default trace only at the highest level 3.
9372 trace_level
= int(self
.GetInfo('trace_level', default
= 3))
9373 if trace_level
not in xrange(0, 4):
9374 raise KeyError("Unhandled trace_level: %d" % trace_level
)
9376 flags
.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level
)
9379 cmd_flags
= ' | '.join(flags
)
9383 f
.write(" static const uint8 cmd_flags = %s;\n" % cmd_flags
)
9386 def WriteCmdArgFlag(self
, f
):
9387 """Writes the cmd kArgFlags constant."""
9388 f
.write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9390 def WriteCmdComputeSize(self
, f
):
9391 """Writes the ComputeSize function for the command."""
9392 f
.write(" static uint32_t ComputeSize() {\n")
9394 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9398 def WriteCmdSetHeader(self
, f
):
9399 """Writes the cmd's SetHeader function."""
9400 f
.write(" void SetHeader() {\n")
9401 f
.write(" header.SetCmd<ValueType>();\n")
9405 def WriteCmdInit(self
, f
):
9406 """Writes the cmd's Init function."""
9407 f
.write(" void Init(%s) {\n" % self
.MakeTypedCmdArgString("_"))
9408 f
.write(" SetHeader();\n")
9409 args
= self
.GetCmdArgs()
9411 f
.write(" %s = _%s;\n" % (arg
.name
, arg
.name
))
9415 def WriteCmdSet(self
, f
):
9416 """Writes the cmd's Set function."""
9417 copy_args
= self
.MakeCmdArgString("_", False)
9418 f
.write(" void* Set(void* cmd%s) {\n" %
9419 self
.MakeTypedCmdArgString("_", True))
9420 f
.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args
)
9421 f
.write(" return NextCmdAddress<ValueType>(cmd);\n")
9425 def WriteStruct(self
, f
):
9426 self
.type_handler
.WriteStruct(self
, f
)
9428 def WriteDocs(self
, f
):
9429 self
.type_handler
.WriteDocs(self
, f
)
9431 def WriteCmdHelper(self
, f
):
9432 """Writes the cmd's helper."""
9433 self
.type_handler
.WriteCmdHelper(self
, f
)
9435 def WriteServiceImplementation(self
, f
):
9436 """Writes the service implementation for a command."""
9437 self
.type_handler
.WriteServiceImplementation(self
, f
)
9439 def WriteServiceUnitTest(self
, f
, *extras
):
9440 """Writes the service implementation for a command."""
9441 self
.type_handler
.WriteServiceUnitTest(self
, f
, *extras
)
9443 def WriteGLES2CLibImplementation(self
, f
):
9444 """Writes the GLES2 C Lib Implemention."""
9445 self
.type_handler
.WriteGLES2CLibImplementation(self
, f
)
9447 def WriteGLES2InterfaceHeader(self
, f
):
9448 """Writes the GLES2 Interface declaration."""
9449 self
.type_handler
.WriteGLES2InterfaceHeader(self
, f
)
9451 def WriteMojoGLES2ImplHeader(self
, f
):
9452 """Writes the Mojo GLES2 implementation header declaration."""
9453 self
.type_handler
.WriteMojoGLES2ImplHeader(self
, f
)
9455 def WriteMojoGLES2Impl(self
, f
):
9456 """Writes the Mojo GLES2 implementation declaration."""
9457 self
.type_handler
.WriteMojoGLES2Impl(self
, f
)
9459 def WriteGLES2InterfaceStub(self
, f
):
9460 """Writes the GLES2 Interface Stub declaration."""
9461 self
.type_handler
.WriteGLES2InterfaceStub(self
, f
)
9463 def WriteGLES2InterfaceStubImpl(self
, f
):
9464 """Writes the GLES2 Interface Stub declaration."""
9465 self
.type_handler
.WriteGLES2InterfaceStubImpl(self
, f
)
9467 def WriteGLES2ImplementationHeader(self
, f
):
9468 """Writes the GLES2 Implemention declaration."""
9469 self
.type_handler
.WriteGLES2ImplementationHeader(self
, f
)
9471 def WriteGLES2Implementation(self
, f
):
9472 """Writes the GLES2 Implemention definition."""
9473 self
.type_handler
.WriteGLES2Implementation(self
, f
)
9475 def WriteGLES2TraceImplementationHeader(self
, f
):
9476 """Writes the GLES2 Trace Implemention declaration."""
9477 self
.type_handler
.WriteGLES2TraceImplementationHeader(self
, f
)
9479 def WriteGLES2TraceImplementation(self
, f
):
9480 """Writes the GLES2 Trace Implemention definition."""
9481 self
.type_handler
.WriteGLES2TraceImplementation(self
, f
)
9483 def WriteGLES2Header(self
, f
):
9484 """Writes the GLES2 Implemention unit test."""
9485 self
.type_handler
.WriteGLES2Header(self
, f
)
9487 def WriteGLES2ImplementationUnitTest(self
, f
):
9488 """Writes the GLES2 Implemention unit test."""
9489 self
.type_handler
.WriteGLES2ImplementationUnitTest(self
, f
)
9491 def WriteDestinationInitalizationValidation(self
, f
):
9492 """Writes the client side destintion initialization validation."""
9493 self
.type_handler
.WriteDestinationInitalizationValidation(self
, f
)
9495 def WriteFormatTest(self
, f
):
9496 """Writes the cmd's format test."""
9497 self
.type_handler
.WriteFormatTest(self
, f
)
9500 class PepperInterface(object):
9501 """A class that represents a function."""
9503 def __init__(self
, info
):
9504 self
.name
= info
["name"]
9505 self
.dev
= info
["dev"]
9510 def GetInterfaceName(self
):
9514 upperint
= "_" + self
.name
.upper()
9517 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint
, dev
)
9519 def GetStructName(self
):
9523 return "PPB_OpenGLES2%s%s" % (self
.name
, dev
)
9526 class ImmediateFunction(Function
):
9527 """A class that represnets an immediate function command."""
9529 def __init__(self
, func
):
9532 "%sImmediate" % func
.name
,
9535 def InitFunction(self
):
9536 # Override args in original_args and args_for_cmds with immediate versions
9539 new_original_args
= []
9540 for arg
in self
.original_args
:
9541 new_arg
= arg
.GetImmediateVersion()
9543 new_original_args
.append(new_arg
)
9544 self
.original_args
= new_original_args
9546 new_args_for_cmds
= []
9547 for arg
in self
.args_for_cmds
:
9548 new_arg
= arg
.GetImmediateVersion()
9550 new_args_for_cmds
.append(new_arg
)
9552 self
.args_for_cmds
= new_args_for_cmds
9554 Function
.InitFunction(self
)
9556 def IsImmediate(self
):
9559 def WriteServiceImplementation(self
, f
):
9560 """Overridden from Function"""
9561 self
.type_handler
.WriteImmediateServiceImplementation(self
, f
)
9563 def WriteHandlerImplementation(self
, f
):
9564 """Overridden from Function"""
9565 self
.type_handler
.WriteImmediateHandlerImplementation(self
, f
)
9567 def WriteServiceUnitTest(self
, f
, *extras
):
9568 """Writes the service implementation for a command."""
9569 self
.type_handler
.WriteImmediateServiceUnitTest(self
, f
, *extras
)
9571 def WriteValidationCode(self
, f
):
9572 """Overridden from Function"""
9573 self
.type_handler
.WriteImmediateValidationCode(self
, f
)
9575 def WriteCmdArgFlag(self
, f
):
9576 """Overridden from Function"""
9577 f
.write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9579 def WriteCmdComputeSize(self
, f
):
9580 """Overridden from Function"""
9581 self
.type_handler
.WriteImmediateCmdComputeSize(self
, f
)
9583 def WriteCmdSetHeader(self
, f
):
9584 """Overridden from Function"""
9585 self
.type_handler
.WriteImmediateCmdSetHeader(self
, f
)
9587 def WriteCmdInit(self
, f
):
9588 """Overridden from Function"""
9589 self
.type_handler
.WriteImmediateCmdInit(self
, f
)
9591 def WriteCmdSet(self
, f
):
9592 """Overridden from Function"""
9593 self
.type_handler
.WriteImmediateCmdSet(self
, f
)
9595 def WriteCmdHelper(self
, f
):
9596 """Overridden from Function"""
9597 self
.type_handler
.WriteImmediateCmdHelper(self
, f
)
9599 def WriteFormatTest(self
, f
):
9600 """Overridden from Function"""
9601 self
.type_handler
.WriteImmediateFormatTest(self
, f
)
9604 class BucketFunction(Function
):
9605 """A class that represnets a bucket version of a function command."""
9607 def __init__(self
, func
):
9610 "%sBucket" % func
.name
,
9613 def InitFunction(self
):
9614 # Override args in original_args and args_for_cmds with bucket versions
9617 new_original_args
= []
9618 for arg
in self
.original_args
:
9619 new_arg
= arg
.GetBucketVersion()
9621 new_original_args
.append(new_arg
)
9622 self
.original_args
= new_original_args
9624 new_args_for_cmds
= []
9625 for arg
in self
.args_for_cmds
:
9626 new_arg
= arg
.GetBucketVersion()
9628 new_args_for_cmds
.append(new_arg
)
9630 self
.args_for_cmds
= new_args_for_cmds
9632 Function
.InitFunction(self
)
9634 def WriteServiceImplementation(self
, f
):
9635 """Overridden from Function"""
9636 self
.type_handler
.WriteBucketServiceImplementation(self
, f
)
9638 def WriteHandlerImplementation(self
, f
):
9639 """Overridden from Function"""
9640 self
.type_handler
.WriteBucketHandlerImplementation(self
, f
)
9642 def WriteServiceUnitTest(self
, f
, *extras
):
9643 """Overridden from Function"""
9644 self
.type_handler
.WriteBucketServiceUnitTest(self
, f
, *extras
)
9646 def MakeOriginalArgString(self
, prefix
, add_comma
= False, separator
= ", "):
9647 """Overridden from Function"""
9648 args
= self
.GetOriginalArgs()
9649 arg_string
= separator
.join(
9650 ["%s%s" % (prefix
, arg
.name
[0:-10] if arg
.name
.endswith("_bucket_id")
9651 else arg
.name
) for arg
in args
])
9652 return super(BucketFunction
, self
)._MaybePrependComma
(arg_string
, add_comma
)
9655 def CreateArg(arg_string
):
9656 """Creates an Argument."""
9657 arg_parts
= arg_string
.split()
9658 if len(arg_parts
) == 1 and arg_parts
[0] == 'void':
9660 # Is this a pointer argument?
9661 elif arg_string
.find('*') >= 0:
9662 return PointerArgument(
9664 " ".join(arg_parts
[0:-1]))
9665 # Is this a resource argument? Must come after pointer check.
9666 elif arg_parts
[0].startswith('GLidBind'):
9667 return ResourceIdBindArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9668 elif arg_parts
[0].startswith('GLidZero'):
9669 return ResourceIdZeroArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9670 elif arg_parts
[0].startswith('GLid'):
9671 return ResourceIdArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9672 elif arg_parts
[0].startswith('GLenum') and len(arg_parts
[0]) > 6:
9673 return EnumArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9674 elif arg_parts
[0].startswith('GLbitfield') and len(arg_parts
[0]) > 10:
9675 return BitFieldArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9676 elif arg_parts
[0].startswith('GLboolean') and len(arg_parts
[0]) > 9:
9677 return ValidatedBoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9678 elif arg_parts
[0].startswith('GLboolean'):
9679 return BoolArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9680 elif arg_parts
[0].startswith('GLintUniformLocation'):
9681 return UniformLocationArgument(arg_parts
[-1])
9682 elif (arg_parts
[0].startswith('GLint') and len(arg_parts
[0]) > 5 and
9683 not arg_parts
[0].startswith('GLintptr')):
9684 return IntArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9685 elif (arg_parts
[0].startswith('GLsizeiNotNegative') or
9686 arg_parts
[0].startswith('GLintptrNotNegative')):
9687 return SizeNotNegativeArgument(arg_parts
[-1],
9688 " ".join(arg_parts
[0:-1]),
9689 arg_parts
[0][0:-11])
9690 elif arg_parts
[0].startswith('GLsize'):
9691 return SizeArgument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9693 return Argument(arg_parts
[-1], " ".join(arg_parts
[0:-1]))
9696 class GLGenerator(object):
9697 """A class to generate GL command buffers."""
9699 _function_re
= re
.compile(r
'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9701 def __init__(self
, verbose
):
9702 self
.original_functions
= []
9704 self
.verbose
= verbose
9706 self
.pepper_interfaces
= []
9707 self
.interface_info
= {}
9708 self
.generated_cpp_filenames
= []
9710 for interface
in _PEPPER_INTERFACES
:
9711 interface
= PepperInterface(interface
)
9712 self
.pepper_interfaces
.append(interface
)
9713 self
.interface_info
[interface
.GetName()] = interface
9715 def AddFunction(self
, func
):
9716 """Adds a function."""
9717 self
.functions
.append(func
)
9719 def GetFunctionInfo(self
, name
):
9720 """Gets a type info for the given function name."""
9721 if name
in _FUNCTION_INFO
:
9722 func_info
= _FUNCTION_INFO
[name
].copy()
9726 if not 'type' in func_info
:
9727 func_info
['type'] = ''
9732 """Prints something if verbose is true."""
9736 def Error(self
, msg
):
9737 """Prints an error."""
9738 print "Error: %s" % msg
9741 def ParseGLH(self
, filename
):
9742 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9743 with
open(filename
, "r") as f
:
9744 functions
= f
.read()
9745 for line
in functions
.splitlines():
9746 match
= self
._function
_re
.match(line
)
9748 func_name
= match
.group(2)[2:]
9749 func_info
= self
.GetFunctionInfo(func_name
)
9750 if func_info
['type'] == 'Noop':
9753 parsed_func_info
= {
9754 'original_name': func_name
,
9755 'original_args': match
.group(3),
9756 'return_type': match
.group(1).strip(),
9759 for k
in parsed_func_info
.keys():
9760 if not k
in func_info
:
9761 func_info
[k
] = parsed_func_info
[k
]
9763 f
= Function(func_name
, func_info
)
9764 self
.original_functions
.append(f
)
9766 #for arg in f.GetOriginalArgs():
9767 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9768 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9770 gen_cmd
= f
.GetInfo('gen_cmd')
9771 if gen_cmd
== True or gen_cmd
== None:
9772 if f
.type_handler
.NeedsDataTransferFunction(f
):
9773 methods
= f
.GetDataTransferMethods()
9774 if 'immediate' in methods
:
9775 self
.AddFunction(ImmediateFunction(f
))
9776 if 'bucket' in methods
:
9777 self
.AddFunction(BucketFunction(f
))
9778 if 'shm' in methods
:
9783 self
.Log("Auto Generated Functions : %d" %
9784 len([f
for f
in self
.functions
if f
.can_auto_generate
or
9785 (not f
.IsType('') and not f
.IsType('Custom') and
9786 not f
.IsType('Todo'))]))
9788 funcs
= [f
for f
in self
.functions
if not f
.can_auto_generate
and
9789 (f
.IsType('') or f
.IsType('Custom') or f
.IsType('Todo'))]
9790 self
.Log("Non Auto Generated Functions: %d" % len(funcs
))
9793 self
.Log(" %-10s %-20s gl%s" % (f
.info
['type'], f
.return_type
, f
.name
))
9795 def WriteCommandIds(self
, filename
):
9796 """Writes the command buffer format"""
9797 with
CHeaderWriter(filename
) as f
:
9798 f
.write("#define GLES2_COMMAND_LIST(OP) \\\n")
9800 for func
in self
.functions
:
9801 f
.write(" %-60s /* %d */ \\\n" %
9802 ("OP(%s)" % func
.name
, id))
9806 f
.write("enum CommandId {\n")
9807 f
.write(" kStartPoint = cmd::kLastCommonId, "
9808 "// All GLES2 commands start after this.\n")
9809 f
.write("#define GLES2_CMD_OP(name) k ## name,\n")
9810 f
.write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9811 f
.write("#undef GLES2_CMD_OP\n")
9812 f
.write(" kNumCommands\n")
9815 self
.generated_cpp_filenames
.append(filename
)
9817 def WriteFormat(self
, filename
):
9818 """Writes the command buffer format"""
9819 with
CHeaderWriter(filename
) as f
:
9820 # Forward declaration of a few enums used in constant argument
9821 # to avoid including GL header files.
9823 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9824 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9827 for enum
in enum_defines
:
9828 f
.write("#define %s %s\n" % (enum
, enum_defines
[enum
]))
9830 for func
in self
.functions
:
9832 #gen_cmd = func.GetInfo('gen_cmd')
9833 #if gen_cmd == True or gen_cmd == None:
9836 self
.generated_cpp_filenames
.append(filename
)
9838 def WriteDocs(self
, filename
):
9839 """Writes the command buffer doc version of the commands"""
9840 with
CHeaderWriter(filename
) as f
:
9841 for func
in self
.functions
:
9843 #gen_cmd = func.GetInfo('gen_cmd')
9844 #if gen_cmd == True or gen_cmd == None:
9847 self
.generated_cpp_filenames
.append(filename
)
9849 def WriteFormatTest(self
, filename
):
9850 """Writes the command buffer format test."""
9851 comment
= ("// This file contains unit tests for gles2 commmands\n"
9852 "// It is included by gles2_cmd_format_test.cc\n\n")
9853 with
CHeaderWriter(filename
, comment
) as f
:
9854 for func
in self
.functions
:
9856 #gen_cmd = func.GetInfo('gen_cmd')
9857 #if gen_cmd == True or gen_cmd == None:
9858 func
.WriteFormatTest(f
)
9859 self
.generated_cpp_filenames
.append(filename
)
9861 def WriteCmdHelperHeader(self
, filename
):
9862 """Writes the gles2 command helper."""
9863 with
CHeaderWriter(filename
) as f
:
9864 for func
in self
.functions
:
9866 #gen_cmd = func.GetInfo('gen_cmd')
9867 #if gen_cmd == True or gen_cmd == None:
9868 func
.WriteCmdHelper(f
)
9869 self
.generated_cpp_filenames
.append(filename
)
9871 def WriteServiceContextStateHeader(self
, filename
):
9872 """Writes the service context state header."""
9873 comment
= "// It is included by context_state.h\n"
9874 with
CHeaderWriter(filename
, comment
) as f
:
9875 f
.write("struct EnableFlags {\n")
9876 f
.write(" EnableFlags();\n")
9877 for capability
in _CAPABILITY_FLAGS
:
9878 f
.write(" bool %s;\n" % capability
['name'])
9879 f
.write(" bool cached_%s;\n" % capability
['name'])
9882 for state_name
in sorted(_STATES
.keys()):
9883 state
= _STATES
[state_name
]
9884 for item
in state
['states']:
9885 if isinstance(item
['default'], list):
9886 f
.write("%s %s[%d];\n" % (item
['type'], item
['name'],
9887 len(item
['default'])))
9889 f
.write("%s %s;\n" % (item
['type'], item
['name']))
9891 if item
.get('cached', False):
9892 if isinstance(item
['default'], list):
9893 f
.write("%s cached_%s[%d];\n" % (item
['type'], item
['name'],
9894 len(item
['default'])))
9896 f
.write("%s cached_%s;\n" % (item
['type'], item
['name']))
9900 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9903 for capability
in _CAPABILITY_FLAGS
:
9906 """ % capability
['name'].upper())
9908 if (enable_flags.cached_%(name)s == enable &&
9909 !ignore_cached_state)
9911 enable_flags.cached_%(name)s = enable;
9926 self
.generated_cpp_filenames
.append(filename
)
9928 def WriteClientContextStateHeader(self
, filename
):
9929 """Writes the client context state header."""
9930 comment
= "// It is included by client_context_state.h\n"
9931 with
CHeaderWriter(filename
, comment
) as f
:
9932 f
.write("struct EnableFlags {\n")
9933 f
.write(" EnableFlags();\n")
9934 for capability
in _CAPABILITY_FLAGS
:
9935 f
.write(" bool %s;\n" % capability
['name'])
9937 self
.generated_cpp_filenames
.append(filename
)
9939 def WriteContextStateGetters(self
, f
, class_name
):
9940 """Writes the state getters."""
9941 for gl_type
in ["GLint", "GLfloat"]:
9943 bool %s::GetStateAs%s(
9944 GLenum pname, %s* params, GLsizei* num_written) const {
9946 """ % (class_name
, gl_type
, gl_type
))
9947 for state_name
in sorted(_STATES
.keys()):
9948 state
= _STATES
[state_name
]
9950 f
.write(" case %s:\n" % state
['enum'])
9951 f
.write(" *num_written = %d;\n" % len(state
['states']))
9952 f
.write(" if (params) {\n")
9953 for ndx
,item
in enumerate(state
['states']):
9954 f
.write(" params[%d] = static_cast<%s>(%s);\n" %
9955 (ndx
, gl_type
, item
['name']))
9957 f
.write(" return true;\n")
9959 for item
in state
['states']:
9960 f
.write(" case %s:\n" % item
['enum'])
9961 if isinstance(item
['default'], list):
9962 item_len
= len(item
['default'])
9963 f
.write(" *num_written = %d;\n" % item_len
)
9964 f
.write(" if (params) {\n")
9965 if item
['type'] == gl_type
:
9966 f
.write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9967 (item
['name'], item
['type'], item_len
))
9969 f
.write(" for (size_t i = 0; i < %s; ++i) {\n" %
9971 f
.write(" params[i] = %s;\n" %
9972 (GetGLGetTypeConversion(gl_type
, item
['type'],
9973 "%s[i]" % item
['name'])))
9976 f
.write(" *num_written = 1;\n")
9977 f
.write(" if (params) {\n")
9978 f
.write(" params[0] = %s;\n" %
9979 (GetGLGetTypeConversion(gl_type
, item
['type'],
9982 f
.write(" return true;\n")
9983 for capability
in _CAPABILITY_FLAGS
:
9984 f
.write(" case GL_%s:\n" % capability
['name'].upper())
9985 f
.write(" *num_written = 1;\n")
9986 f
.write(" if (params) {\n")
9988 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9989 (gl_type
, capability
['name']))
9991 f
.write(" return true;\n")
9992 f
.write(""" default:
9998 def WriteServiceContextStateImpl(self
, filename
):
9999 """Writes the context state service implementation."""
10000 comment
= "// It is included by context_state.cc\n"
10001 with
CHeaderWriter(filename
, comment
) as f
:
10003 for capability
in _CAPABILITY_FLAGS
:
10004 code
.append("%s(%s)" %
10005 (capability
['name'],
10006 ('false', 'true')['default' in capability
]))
10007 code
.append("cached_%s(%s)" %
10008 (capability
['name'],
10009 ('false', 'true')['default' in capability
]))
10010 f
.write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10014 f
.write("void ContextState::Initialize() {\n")
10015 for state_name
in sorted(_STATES
.keys()):
10016 state
= _STATES
[state_name
]
10017 for item
in state
['states']:
10018 if isinstance(item
['default'], list):
10019 for ndx
, value
in enumerate(item
['default']):
10020 f
.write(" %s[%d] = %s;\n" % (item
['name'], ndx
, value
))
10022 f
.write(" %s = %s;\n" % (item
['name'], item
['default']))
10023 if item
.get('cached', False):
10024 if isinstance(item
['default'], list):
10025 for ndx
, value
in enumerate(item
['default']):
10026 f
.write(" cached_%s[%d] = %s;\n" % (item
['name'], ndx
, value
))
10028 f
.write(" cached_%s = %s;\n" % (item
['name'], item
['default']))
10032 void ContextState::InitCapabilities(const ContextState* prev_state) const {
10034 def WriteCapabilities(test_prev
, es3_caps
):
10035 for capability
in _CAPABILITY_FLAGS
:
10036 capability_name
= capability
['name']
10037 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10038 if capability_es3
and not es3_caps
or not capability_es3
and es3_caps
:
10041 f
.write(""" if (prev_state->enable_flags.cached_%s !=
10042 enable_flags.cached_%s) {\n""" %
10043 (capability_name
, capability_name
))
10044 f
.write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
10045 (capability_name
.upper(), capability_name
))
10049 f
.write(" if (prev_state) {")
10050 WriteCapabilities(True, False)
10051 f
.write(" if (feature_info_->IsES3Capable()) {\n")
10052 WriteCapabilities(True, True)
10054 f
.write(" } else {")
10055 WriteCapabilities(False, False)
10056 f
.write(" if (feature_info_->IsES3Capable()) {\n")
10057 WriteCapabilities(False, True)
10062 void ContextState::InitState(const ContextState *prev_state) const {
10065 def WriteStates(test_prev
):
10066 # We need to sort the keys so the expectations match
10067 for state_name
in sorted(_STATES
.keys()):
10068 state
= _STATES
[state_name
]
10069 if state
['type'] == 'FrontBack':
10070 num_states
= len(state
['states'])
10071 for ndx
, group
in enumerate(Grouper(num_states
/ 2,
10076 for place
, item
in enumerate(group
):
10077 item_name
= CachedStateName(item
)
10078 args
.append('%s' % item_name
)
10082 f
.write("(%s != prev_state->%s)" % (item_name
, item_name
))
10086 " gl%s(%s, %s);\n" %
10087 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
],
10089 elif state
['type'] == 'NamedParameter':
10090 for item
in state
['states']:
10091 item_name
= CachedStateName(item
)
10093 if 'extension_flag' in item
:
10094 f
.write(" if (feature_info_->feature_flags().%s) {\n " %
10095 item
['extension_flag'])
10097 if isinstance(item
['default'], list):
10098 f
.write(" if (memcmp(prev_state->%s, %s, "
10099 "sizeof(%s) * %d)) {\n" %
10100 (item_name
, item_name
, item
['type'],
10101 len(item
['default'])))
10103 f
.write(" if (prev_state->%s != %s) {\n " %
10104 (item_name
, item_name
))
10105 if 'gl_version_flag' in item
:
10106 item_name
= item
['gl_version_flag']
10108 if item_name
[0] == '!':
10110 item_name
= item_name
[1:]
10111 f
.write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10112 (inverted
, item_name
))
10113 f
.write(" gl%s(%s, %s);\n" %
10116 if 'enum_set' in item
else item
['enum']),
10118 if 'gl_version_flag' in item
:
10121 if 'extension_flag' in item
:
10124 if 'extension_flag' in item
:
10127 if 'extension_flag' in state
:
10128 f
.write(" if (feature_info_->feature_flags().%s)\n " %
10129 state
['extension_flag'])
10133 for place
, item
in enumerate(state
['states']):
10134 item_name
= CachedStateName(item
)
10135 args
.append('%s' % item_name
)
10139 f
.write("(%s != prev_state->%s)" %
10140 (item_name
, item_name
))
10143 f
.write(" gl%s(%s);\n" % (state
['func'], ", ".join(args
)))
10145 f
.write(" if (prev_state) {")
10147 f
.write(" } else {")
10152 f
.write("""bool ContextState::GetEnabled(GLenum cap) const {
10155 for capability
in _CAPABILITY_FLAGS
:
10156 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10157 f
.write(" return enable_flags.%s;\n" % capability
['name'])
10158 f
.write(""" default:
10164 self
.WriteContextStateGetters(f
, "ContextState")
10165 self
.generated_cpp_filenames
.append(filename
)
10167 def WriteClientContextStateImpl(self
, filename
):
10168 """Writes the context state client side implementation."""
10169 comment
= "// It is included by client_context_state.cc\n"
10170 with
CHeaderWriter(filename
, comment
) as f
:
10172 for capability
in _CAPABILITY_FLAGS
:
10173 code
.append("%s(%s)" %
10174 (capability
['name'],
10175 ('false', 'true')['default' in capability
]))
10177 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10182 bool ClientContextState::SetCapabilityState(
10183 GLenum cap, bool enabled, bool* changed) {
10187 for capability
in _CAPABILITY_FLAGS
:
10188 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10189 f
.write(""" if (enable_flags.%(name)s != enabled) {
10191 enable_flags.%(name)s = enabled;
10195 f
.write(""" default:
10200 f
.write("""bool ClientContextState::GetEnabled(
10201 GLenum cap, bool* enabled) const {
10204 for capability
in _CAPABILITY_FLAGS
:
10205 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10206 f
.write(" *enabled = enable_flags.%s;\n" % capability
['name'])
10207 f
.write(" return true;\n")
10208 f
.write(""" default:
10213 self
.generated_cpp_filenames
.append(filename
)
10215 def WriteServiceImplementation(self
, filename
):
10216 """Writes the service decorder implementation."""
10217 comment
= "// It is included by gles2_cmd_decoder.cc\n"
10218 with
CHeaderWriter(filename
, comment
) as f
:
10219 for func
in self
.functions
:
10221 #gen_cmd = func.GetInfo('gen_cmd')
10222 #if gen_cmd == True or gen_cmd == None:
10223 func
.WriteServiceImplementation(f
)
10226 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10229 for capability
in _CAPABILITY_FLAGS
:
10230 f
.write(" case GL_%s:\n" % capability
['name'].upper())
10231 if 'state_flag' in capability
:
10234 state_.enable_flags.%(name)s = enabled;
10235 if (state_.enable_flags.cached_%(name)s != enabled
10236 || state_.ignore_cached_state) {
10237 %(state_flag)s = true;
10243 state_.enable_flags.%(name)s = enabled;
10244 if (state_.enable_flags.cached_%(name)s != enabled
10245 || state_.ignore_cached_state) {
10246 state_.enable_flags.cached_%(name)s = enabled;
10251 f
.write(""" default:
10257 self
.generated_cpp_filenames
.append(filename
)
10259 def WriteServiceUnitTests(self
, filename_pattern
):
10260 """Writes the service decorder unit tests."""
10261 num_tests
= len(self
.functions
)
10262 FUNCTIONS_PER_FILE
= 98 # hard code this so it doesn't change.
10264 for test_num
in range(0, num_tests
, FUNCTIONS_PER_FILE
):
10266 filename
= filename_pattern
% count
10267 comment
= "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" \
10269 with
CHeaderWriter(filename
, comment
) as f
:
10270 test_name
= 'GLES2DecoderTest%d' % count
10271 end
= test_num
+ FUNCTIONS_PER_FILE
10272 if end
> num_tests
:
10274 for idx
in range(test_num
, end
):
10275 func
= self
.functions
[idx
]
10277 # Do any filtering of the functions here, so that the functions
10278 # will not move between the numbered files if filtering properties
10280 if func
.GetInfo('extension_flag'):
10284 #gen_cmd = func.GetInfo('gen_cmd')
10285 #if gen_cmd == True or gen_cmd == None:
10286 if func
.GetInfo('unit_test') == False:
10287 f
.write("// TODO(gman): %s\n" % func
.name
)
10289 func
.WriteServiceUnitTest(f
, {
10290 'test_name': test_name
10292 self
.generated_cpp_filenames
.append(filename
)
10294 comment
= "// It is included by gles2_cmd_decoder_unittest_base.cc\n"
10295 filename
= filename_pattern
% 0
10296 with
CHeaderWriter(filename
, comment
) as f
:
10298 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10299 bool es3_capable) {""")
10300 for capability
in _CAPABILITY_FLAGS
:
10301 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10302 if not capability_es3
:
10303 f
.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10304 (capability
['name'].upper(),
10305 ('false', 'true')['default' in capability
]))
10307 f
.write(" if (es3_capable) {")
10308 for capability
in _CAPABILITY_FLAGS
:
10309 capability_es3
= 'es3' in capability
and capability
['es3'] == True
10311 f
.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10312 (capability
['name'].upper(),
10313 ('false', 'true')['default' in capability
]))
10317 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10319 # We need to sort the keys so the expectations match
10320 for state_name
in sorted(_STATES
.keys()):
10321 state
= _STATES
[state_name
]
10322 if state
['type'] == 'FrontBack':
10323 num_states
= len(state
['states'])
10324 for ndx
, group
in enumerate(Grouper(num_states
/ 2, state
['states'])):
10327 if 'expected' in item
:
10328 args
.append(item
['expected'])
10330 args
.append(item
['default'])
10332 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10333 (state
['func'], ('GL_FRONT', 'GL_BACK')[ndx
], ", ".join(args
)))
10334 f
.write(" .Times(1)\n")
10335 f
.write(" .RetiresOnSaturation();\n")
10336 elif state
['type'] == 'NamedParameter':
10337 for item
in state
['states']:
10338 if 'extension_flag' in item
:
10339 f
.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10340 item
['extension_flag'])
10342 expect_value
= item
['default']
10343 if isinstance(expect_value
, list):
10344 # TODO: Currently we do not check array values.
10348 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10351 if 'enum_set' in item
else item
['enum']),
10353 f
.write(" .Times(1)\n")
10354 f
.write(" .RetiresOnSaturation();\n")
10355 if 'extension_flag' in item
:
10358 if 'extension_flag' in state
:
10359 f
.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10360 state
['extension_flag'])
10363 for item
in state
['states']:
10364 if 'expected' in item
:
10365 args
.append(item
['expected'])
10367 args
.append(item
['default'])
10368 # TODO: Currently we do not check array values.
10369 args
= ["_" if isinstance(arg
, list) else arg
for arg
in args
]
10370 f
.write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10371 (state
['func'], ", ".join(args
)))
10372 f
.write(" .Times(1)\n")
10373 f
.write(" .RetiresOnSaturation();\n")
10374 if 'extension_flag' in state
:
10377 self
.generated_cpp_filenames
.append(filename
)
10379 def WriteServiceUnitTestsForExtensions(self
, filename
):
10380 """Writes the service decorder unit tests for functions with extension_flag.
10382 The functions are special in that they need a specific unit test
10383 baseclass to turn on the extension.
10385 functions
= [f
for f
in self
.functions
if f
.GetInfo('extension_flag')]
10386 comment
= "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n"
10387 with
CHeaderWriter(filename
, comment
) as f
:
10388 for func
in functions
:
10390 if func
.GetInfo('unit_test') == False:
10391 f
.write("// TODO(gman): %s\n" % func
.name
)
10393 extension
= ToCamelCase(
10394 ToGLExtensionString(func
.GetInfo('extension_flag')))
10395 func
.WriteServiceUnitTest(f
, {
10396 'test_name': 'GLES2DecoderTestWith%s' % extension
10398 self
.generated_cpp_filenames
.append(filename
)
10400 def WriteGLES2Header(self
, filename
):
10401 """Writes the GLES2 header."""
10402 comment
= "// This file contains Chromium-specific GLES2 declarations.\n\n"
10403 with
CHeaderWriter(filename
, comment
) as f
:
10404 for func
in self
.original_functions
:
10405 func
.WriteGLES2Header(f
)
10407 self
.generated_cpp_filenames
.append(filename
)
10409 def WriteGLES2CLibImplementation(self
, filename
):
10410 """Writes the GLES2 c lib implementation."""
10411 comment
= "// These functions emulate GLES2 over command buffers.\n"
10412 with
CHeaderWriter(filename
, comment
) as f
:
10413 for func
in self
.original_functions
:
10414 func
.WriteGLES2CLibImplementation(f
)
10418 extern const NameToFunc g_gles2_function_table[] = {
10420 for func
in self
.original_functions
:
10422 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10423 (func
.name
, func
.name
))
10424 f
.write(""" { NULL, NULL, },
10427 } // namespace gles2
10429 self
.generated_cpp_filenames
.append(filename
)
10431 def WriteGLES2InterfaceHeader(self
, filename
):
10432 """Writes the GLES2 interface header."""
10433 comment
= ("// This file is included by gles2_interface.h to declare the\n"
10434 "// GL api functions.\n")
10435 with
CHeaderWriter(filename
, comment
) as f
:
10436 for func
in self
.original_functions
:
10437 func
.WriteGLES2InterfaceHeader(f
)
10438 self
.generated_cpp_filenames
.append(filename
)
10440 def WriteMojoGLES2ImplHeader(self
, filename
):
10441 """Writes the Mojo GLES2 implementation header."""
10442 comment
= ("// This file is included by gles2_interface.h to declare the\n"
10443 "// GL api functions.\n")
10445 #include "gpu/command_buffer/client/gles2_interface.h"
10446 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10450 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10452 explicit MojoGLES2Impl(MojoGLES2Context context) {
10453 context_ = context;
10455 ~MojoGLES2Impl() override {}
10457 with
CHeaderWriter(filename
, comment
) as f
:
10459 for func
in self
.original_functions
:
10460 func
.WriteMojoGLES2ImplHeader(f
)
10463 MojoGLES2Context context_;
10466 } // namespace mojo
10469 self
.generated_cpp_filenames
.append(filename
)
10471 def WriteMojoGLES2Impl(self
, filename
):
10472 """Writes the Mojo GLES2 implementation."""
10474 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10476 #include "base/logging.h"
10477 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_copy_texture.h"
10478 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_image.h"
10479 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10480 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_pixel_transfer_buffer_object.h"
10481 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10482 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10483 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10484 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10485 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10490 with
CWriter(filename
) as f
:
10492 for func
in self
.original_functions
:
10493 func
.WriteMojoGLES2Impl(f
)
10496 } // namespace mojo
10499 self
.generated_cpp_filenames
.append(filename
)
10501 def WriteGLES2InterfaceStub(self
, filename
):
10502 """Writes the GLES2 interface stub header."""
10503 comment
= "// This file is included by gles2_interface_stub.h.\n"
10504 with
CHeaderWriter(filename
, comment
) as f
:
10505 for func
in self
.original_functions
:
10506 func
.WriteGLES2InterfaceStub(f
)
10507 self
.generated_cpp_filenames
.append(filename
)
10509 def WriteGLES2InterfaceStubImpl(self
, filename
):
10510 """Writes the GLES2 interface header."""
10511 comment
= "// This file is included by gles2_interface_stub.cc.\n"
10512 with
CHeaderWriter(filename
, comment
) as f
:
10513 for func
in self
.original_functions
:
10514 func
.WriteGLES2InterfaceStubImpl(f
)
10515 self
.generated_cpp_filenames
.append(filename
)
10517 def WriteGLES2ImplementationHeader(self
, filename
):
10518 """Writes the GLES2 Implementation header."""
10520 ("// This file is included by gles2_implementation.h to declare the\n"
10521 "// GL api functions.\n")
10522 with
CHeaderWriter(filename
, comment
) as f
:
10523 for func
in self
.original_functions
:
10524 func
.WriteGLES2ImplementationHeader(f
)
10525 self
.generated_cpp_filenames
.append(filename
)
10527 def WriteGLES2Implementation(self
, filename
):
10528 """Writes the GLES2 Implementation."""
10530 ("// This file is included by gles2_implementation.cc to define the\n"
10531 "// GL api functions.\n")
10532 with
CHeaderWriter(filename
, comment
) as f
:
10533 for func
in self
.original_functions
:
10534 func
.WriteGLES2Implementation(f
)
10535 self
.generated_cpp_filenames
.append(filename
)
10537 def WriteGLES2TraceImplementationHeader(self
, filename
):
10538 """Writes the GLES2 Trace Implementation header."""
10539 comment
= "// This file is included by gles2_trace_implementation.h\n"
10540 with
CHeaderWriter(filename
, comment
) as f
:
10541 for func
in self
.original_functions
:
10542 func
.WriteGLES2TraceImplementationHeader(f
)
10543 self
.generated_cpp_filenames
.append(filename
)
10545 def WriteGLES2TraceImplementation(self
, filename
):
10546 """Writes the GLES2 Trace Implementation."""
10547 comment
= "// This file is included by gles2_trace_implementation.cc\n"
10548 with
CHeaderWriter(filename
, comment
) as f
:
10549 for func
in self
.original_functions
:
10550 func
.WriteGLES2TraceImplementation(f
)
10551 self
.generated_cpp_filenames
.append(filename
)
10553 def WriteGLES2ImplementationUnitTests(self
, filename
):
10554 """Writes the GLES2 helper header."""
10556 ("// This file is included by gles2_implementation.h to declare the\n"
10557 "// GL api functions.\n")
10558 with
CHeaderWriter(filename
, comment
) as f
:
10559 for func
in self
.original_functions
:
10560 func
.WriteGLES2ImplementationUnitTest(f
)
10561 self
.generated_cpp_filenames
.append(filename
)
10563 def WriteServiceUtilsHeader(self
, filename
):
10564 """Writes the gles2 auto generated utility header."""
10565 with
CHeaderWriter(filename
) as f
:
10566 for name
in sorted(_NAMED_TYPE_INFO
.keys()):
10567 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10568 if named_type
.IsConstant():
10570 f
.write("ValueValidator<%s> %s;\n" %
10571 (named_type
.GetType(), ToUnderscore(name
)))
10573 self
.generated_cpp_filenames
.append(filename
)
10575 def WriteServiceUtilsImplementation(self
, filename
):
10576 """Writes the gles2 auto generated utility implementation."""
10577 with
CHeaderWriter(filename
) as f
:
10578 names
= sorted(_NAMED_TYPE_INFO
.keys())
10580 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10581 if named_type
.IsConstant():
10583 if named_type
.GetValidValues():
10584 f
.write("static const %s valid_%s_table[] = {\n" %
10585 (named_type
.GetType(), ToUnderscore(name
)))
10586 for value
in named_type
.GetValidValues():
10587 f
.write(" %s,\n" % value
)
10590 if named_type
.GetValidValuesES3():
10591 f
.write("static const %s valid_%s_table_es3[] = {\n" %
10592 (named_type
.GetType(), ToUnderscore(name
)))
10593 for value
in named_type
.GetValidValuesES3():
10594 f
.write(" %s,\n" % value
)
10597 if named_type
.GetDeprecatedValuesES3():
10598 f
.write("static const %s deprecated_%s_table_es3[] = {\n" %
10599 (named_type
.GetType(), ToUnderscore(name
)))
10600 for value
in named_type
.GetDeprecatedValuesES3():
10601 f
.write(" %s,\n" % value
)
10604 f
.write("Validators::Validators()")
10606 for count
, name
in enumerate(names
):
10607 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10608 if named_type
.IsConstant():
10610 if named_type
.GetValidValues():
10611 code
= """%(pre)s%(name)s(
10612 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10614 code
= "%(pre)s%(name)s()"
10616 'name': ToUnderscore(name
),
10623 f
.write("void Validators::UpdateValuesES3() {\n")
10625 named_type
= NamedType(_NAMED_TYPE_INFO
[name
])
10626 if named_type
.GetDeprecatedValuesES3():
10627 code
= """ %(name)s.RemoveValues(
10628 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10631 'name': ToUnderscore(name
),
10633 if named_type
.GetValidValuesES3():
10634 code
= """ %(name)s.AddValues(
10635 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10638 'name': ToUnderscore(name
),
10641 self
.generated_cpp_filenames
.append(filename
)
10643 def WriteCommonUtilsHeader(self
, filename
):
10644 """Writes the gles2 common utility header."""
10645 with
CHeaderWriter(filename
) as f
:
10646 type_infos
= sorted(_NAMED_TYPE_INFO
.keys())
10647 for type_info
in type_infos
:
10648 if _NAMED_TYPE_INFO
[type_info
]['type'] == 'GLenum':
10649 f
.write("static std::string GetString%s(uint32_t value);\n" %
10652 self
.generated_cpp_filenames
.append(filename
)
10654 def WriteCommonUtilsImpl(self
, filename
):
10655 """Writes the gles2 common utility header."""
10656 enum_re
= re
.compile(r
'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10658 for fname
in ['third_party/khronos/GLES2/gl2.h',
10659 'third_party/khronos/GLES2/gl2ext.h',
10660 'third_party/khronos/GLES3/gl3.h',
10661 'gpu/GLES2/gl2chromium.h',
10662 'gpu/GLES2/gl2extchromium.h']:
10663 lines
= open(fname
).readlines()
10665 m
= enum_re
.match(line
)
10669 if len(value
) <= 10:
10670 if not value
in dict:
10672 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10673 elif dict[value
] != name
and (name
.endswith('_CHROMIUM') or
10674 dict[value
].endswith('_CHROMIUM')):
10675 self
.Error("code collision: %s and %s have the same code %s" %
10676 (dict[value
], name
, value
))
10678 with
CHeaderWriter(filename
) as f
:
10679 f
.write("static const GLES2Util::EnumToString "
10680 "enum_to_string_table[] = {\n")
10682 f
.write(' { %s, "%s", },\n' % (value
, dict[value
]))
10685 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10686 enum_to_string_table;
10687 const size_t GLES2Util::enum_to_string_table_len_ =
10688 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10692 enums
= sorted(_NAMED_TYPE_INFO
.keys())
10694 if _NAMED_TYPE_INFO
[enum
]['type'] == 'GLenum':
10695 f
.write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10697 valid_list
= _NAMED_TYPE_INFO
[enum
]['valid']
10698 if 'valid_es3' in _NAMED_TYPE_INFO
[enum
]:
10699 valid_list
= valid_list
+ _NAMED_TYPE_INFO
[enum
]['valid_es3']
10700 assert len(valid_list
) == len(set(valid_list
))
10701 if len(valid_list
) > 0:
10702 f
.write(" static const EnumToString string_table[] = {\n")
10703 for value
in valid_list
:
10704 f
.write(' { %s, "%s" },\n' % (value
, value
))
10706 return GLES2Util::GetQualifiedEnumString(
10707 string_table, arraysize(string_table), value);
10712 f
.write(""" return GLES2Util::GetQualifiedEnumString(
10717 self
.generated_cpp_filenames
.append(filename
)
10719 def WritePepperGLES2Interface(self
, filename
, dev
):
10720 """Writes the Pepper OpenGLES interface definition."""
10721 with
CWriter(filename
) as f
:
10722 f
.write("label Chrome {\n")
10723 f
.write(" M39 = 1.0\n")
10727 # Declare GL types.
10728 f
.write("[version=1.0]\n")
10729 f
.write("describe {\n")
10730 for gltype
in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10731 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10732 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10733 'GLubyte', 'GLuint', 'GLushort']:
10734 f
.write(" %s;\n" % gltype
)
10735 f
.write(" %s_ptr_t;\n" % gltype
)
10738 # C level typedefs.
10739 f
.write("#inline c\n")
10740 f
.write("#include \"ppapi/c/pp_resource.h\"\n")
10742 f
.write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10744 f
.write("\n#ifndef __gl2_h_\n")
10745 for (k
, v
) in _GL_TYPES
.iteritems():
10746 f
.write("typedef %s %s;\n" % (v
, k
))
10747 f
.write("#ifdef _WIN64\n")
10748 for (k
, v
) in _GL_TYPES_64
.iteritems():
10749 f
.write("typedef %s %s;\n" % (v
, k
))
10751 for (k
, v
) in _GL_TYPES_32
.iteritems():
10752 f
.write("typedef %s %s;\n" % (v
, k
))
10753 f
.write("#endif // _WIN64\n")
10754 f
.write("#endif // __gl2_h_\n\n")
10755 f
.write("#endinl\n")
10757 for interface
in self
.pepper_interfaces
:
10758 if interface
.dev
!= dev
:
10760 # Historically, we provide OpenGLES2 interfaces with struct
10761 # namespace. Not to break code which uses the interface as
10762 # "struct OpenGLES2", we put it in struct namespace.
10763 f
.write('\n[macro="%s", force_struct_namespace]\n' %
10764 interface
.GetInterfaceName())
10765 f
.write("interface %s {\n" % interface
.GetStructName())
10766 for func
in self
.original_functions
:
10767 if not func
.InPepperInterface(interface
):
10770 ret_type
= func
.MapCTypeToPepperIdlType(func
.return_type
,
10771 is_for_return_type
=True)
10772 func_prefix
= " %s %s(" % (ret_type
, func
.GetPepperName())
10773 f
.write(func_prefix
)
10774 f
.write("[in] PP_Resource context")
10775 for arg
in func
.MakeTypedPepperIdlArgStrings():
10776 f
.write(",\n" + " " * len(func_prefix
) + arg
)
10780 def WritePepperGLES2Implementation(self
, filename
):
10781 """Writes the Pepper OpenGLES interface implementation."""
10782 with
CWriter(filename
) as f
:
10783 f
.write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10784 f
.write("#include \"base/logging.h\"\n")
10785 f
.write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10786 f
.write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10787 f
.write("#include \"ppapi/thunk/enter.h\"\n\n")
10789 f
.write("namespace ppapi {\n\n")
10790 f
.write("namespace {\n\n")
10792 f
.write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10795 f
.write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10797 f
.write(" DCHECK(enter);\n")
10798 f
.write(" DCHECK(enter->succeeded());\n")
10799 f
.write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10800 "gles2_impl();\n");
10803 for func
in self
.original_functions
:
10804 if not func
.InAnyPepperExtension():
10807 original_arg
= func
.MakeTypedPepperArgString("")
10808 context_arg
= "PP_Resource context_id"
10809 if len(original_arg
):
10810 arg
= context_arg
+ ", " + original_arg
10813 f
.write("%s %s(%s) {\n" %
10814 (func
.return_type
, func
.GetPepperName(), arg
))
10815 f
.write(" Enter3D enter(context_id, true);\n")
10816 f
.write(" if (enter.succeeded()) {\n")
10818 return_str
= "" if func
.return_type
== "void" else "return "
10819 f
.write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10820 (return_str
, func
.original_name
,
10821 func
.MakeOriginalArgString("")))
10823 if func
.return_type
== "void":
10826 f
.write(" else {\n")
10827 f
.write(" return %s;\n" % func
.GetErrorReturnString())
10831 f
.write("} // namespace\n")
10833 for interface
in self
.pepper_interfaces
:
10834 f
.write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10835 (interface
.GetStructName(), interface
.GetName()))
10836 f
.write(" static const struct %s "
10837 "ppb_opengles2 = {\n" % interface
.GetStructName())
10839 f
.write(",\n &".join(
10840 f
.GetPepperName() for f
in self
.original_functions
10841 if f
.InPepperInterface(interface
)))
10845 f
.write(" return &ppb_opengles2;\n")
10848 f
.write("} // namespace ppapi\n")
10849 self
.generated_cpp_filenames
.append(filename
)
10851 def WriteGLES2ToPPAPIBridge(self
, filename
):
10852 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10853 with
CWriter(filename
) as f
:
10854 f
.write("#ifndef GL_GLEXT_PROTOTYPES\n")
10855 f
.write("#define GL_GLEXT_PROTOTYPES\n")
10856 f
.write("#endif\n")
10857 f
.write("#include <GLES2/gl2.h>\n")
10858 f
.write("#include <GLES2/gl2ext.h>\n")
10859 f
.write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10861 for func
in self
.original_functions
:
10862 if not func
.InAnyPepperExtension():
10865 interface
= self
.interface_info
[func
.GetInfo('pepper_interface') or '']
10867 f
.write("%s GL_APIENTRY gl%s(%s) {\n" %
10868 (func
.return_type
, func
.GetPepperName(),
10869 func
.MakeTypedPepperArgString("")))
10870 return_str
= "" if func
.return_type
== "void" else "return "
10871 interface_str
= "glGet%sInterfacePPAPI()" % interface
.GetName()
10872 original_arg
= func
.MakeOriginalArgString("")
10873 context_arg
= "glGetCurrentContextPPAPI()"
10874 if len(original_arg
):
10875 arg
= context_arg
+ ", " + original_arg
10878 if interface
.GetName():
10879 f
.write(" const struct %s* ext = %s;\n" %
10880 (interface
.GetStructName(), interface_str
))
10881 f
.write(" if (ext)\n")
10882 f
.write(" %sext->%s(%s);\n" %
10883 (return_str
, func
.GetPepperName(), arg
))
10885 f
.write(" %s0;\n" % return_str
)
10887 f
.write(" %s%s->%s(%s);\n" %
10888 (return_str
, interface_str
, func
.GetPepperName(), arg
))
10890 self
.generated_cpp_filenames
.append(filename
)
10892 def WriteMojoGLCallVisitor(self
, filename
):
10893 """Provides the GL implementation for mojo"""
10894 with
CWriter(filename
) as f
:
10895 for func
in self
.original_functions
:
10896 if not func
.IsCoreGLFunction():
10898 f
.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10899 (func
.name
, func
.return_type
,
10900 func
.MakeTypedOriginalArgString(""),
10901 func
.MakeOriginalArgString("")))
10902 self
.generated_cpp_filenames
.append(filename
)
10904 def WriteMojoGLCallVisitorForExtension(self
, filename
, extension
):
10905 """Provides the GL implementation for mojo for a particular extension"""
10906 with
CWriter(filename
) as f
:
10907 for func
in self
.original_functions
:
10908 if func
.GetInfo("extension") != extension
:
10910 f
.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10911 (func
.name
, func
.return_type
,
10912 func
.MakeTypedOriginalArgString(""),
10913 func
.MakeOriginalArgString("")))
10914 self
.generated_cpp_filenames
.append(filename
)
10916 def Format(generated_files
):
10917 formatter
= "clang-format"
10918 if platform
.system() == "Windows":
10919 formatter
+= ".bat"
10920 for filename
in generated_files
:
10921 call([formatter
, "-i", "-style=chromium", filename
])
10924 """This is the main function."""
10925 parser
= OptionParser()
10928 help="base directory for resulting files, under chrome/src. default is "
10929 "empty. Use this if you want the result stored under gen.")
10931 "-v", "--verbose", action
="store_true",
10932 help="prints more output.")
10934 (options
, args
) = parser
.parse_args(args
=argv
)
10936 # Add in states and capabilites to GLState
10937 gl_state_valid
= _NAMED_TYPE_INFO
['GLState']['valid']
10938 for state_name
in sorted(_STATES
.keys()):
10939 state
= _STATES
[state_name
]
10940 if 'extension_flag' in state
:
10942 if 'enum' in state
:
10943 if not state
['enum'] in gl_state_valid
:
10944 gl_state_valid
.append(state
['enum'])
10946 for item
in state
['states']:
10947 if 'extension_flag' in item
:
10949 if not item
['enum'] in gl_state_valid
:
10950 gl_state_valid
.append(item
['enum'])
10951 for capability
in _CAPABILITY_FLAGS
:
10952 valid_value
= "GL_%s" % capability
['name'].upper()
10953 if not valid_value
in gl_state_valid
:
10954 gl_state_valid
.append(valid_value
)
10956 # This script lives under gpu/command_buffer, cd to base directory.
10957 os
.chdir(os
.path
.dirname(__file__
) + "/../..")
10958 base_dir
= os
.getcwd()
10959 gen
= GLGenerator(options
.verbose
)
10960 gen
.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10962 # Support generating files under gen/
10963 if options
.output_dir
!= None:
10964 os
.chdir(options
.output_dir
)
10966 gen
.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10967 gen
.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10968 gen
.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10969 gen
.WritePepperGLES2Implementation(
10970 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10972 gen
.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10973 gen
.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10974 gen
.WriteFormatTest(
10975 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10976 gen
.WriteGLES2InterfaceHeader(
10977 "gpu/command_buffer/client/gles2_interface_autogen.h")
10978 gen
.WriteMojoGLES2ImplHeader(
10979 "mojo/gpu/mojo_gles2_impl_autogen.h")
10980 gen
.WriteMojoGLES2Impl(
10981 "mojo/gpu/mojo_gles2_impl_autogen.cc")
10982 gen
.WriteGLES2InterfaceStub(
10983 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10984 gen
.WriteGLES2InterfaceStubImpl(
10985 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10986 gen
.WriteGLES2ImplementationHeader(
10987 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10988 gen
.WriteGLES2Implementation(
10989 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10990 gen
.WriteGLES2ImplementationUnitTests(
10991 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10992 gen
.WriteGLES2TraceImplementationHeader(
10993 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10994 gen
.WriteGLES2TraceImplementation(
10995 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10996 gen
.WriteGLES2CLibImplementation(
10997 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10998 gen
.WriteCmdHelperHeader(
10999 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
11000 gen
.WriteServiceImplementation(
11001 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
11002 gen
.WriteServiceContextStateHeader(
11003 "gpu/command_buffer/service/context_state_autogen.h")
11004 gen
.WriteServiceContextStateImpl(
11005 "gpu/command_buffer/service/context_state_impl_autogen.h")
11006 gen
.WriteClientContextStateHeader(
11007 "gpu/command_buffer/client/client_context_state_autogen.h")
11008 gen
.WriteClientContextStateImpl(
11009 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
11010 gen
.WriteServiceUnitTests(
11011 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
11012 gen
.WriteServiceUnitTestsForExtensions(
11013 "gpu/command_buffer/service/"
11014 "gles2_cmd_decoder_unittest_extensions_autogen.h")
11015 gen
.WriteServiceUtilsHeader(
11016 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
11017 gen
.WriteServiceUtilsImplementation(
11018 "gpu/command_buffer/service/"
11019 "gles2_cmd_validation_implementation_autogen.h")
11020 gen
.WriteCommonUtilsHeader(
11021 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
11022 gen
.WriteCommonUtilsImpl(
11023 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
11024 gen
.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
11025 mojo_gles2_prefix
= ("third_party/mojo/src/mojo/public/c/gles2/"
11026 "gles2_call_visitor")
11027 gen
.WriteMojoGLCallVisitor(mojo_gles2_prefix
+ "_autogen.h")
11028 gen
.WriteMojoGLCallVisitorForExtension(
11029 mojo_gles2_prefix
+ "_chromium_texture_mailbox_autogen.h",
11030 "CHROMIUM_texture_mailbox")
11031 gen
.WriteMojoGLCallVisitorForExtension(
11032 mojo_gles2_prefix
+ "_chromium_sync_point_autogen.h",
11033 "CHROMIUM_sync_point")
11034 gen
.WriteMojoGLCallVisitorForExtension(
11035 mojo_gles2_prefix
+ "_chromium_sub_image_autogen.h",
11036 "CHROMIUM_sub_image")
11037 gen
.WriteMojoGLCallVisitorForExtension(
11038 mojo_gles2_prefix
+ "_chromium_miscellaneous_autogen.h",
11039 "CHROMIUM_miscellaneous")
11040 gen
.WriteMojoGLCallVisitorForExtension(
11041 mojo_gles2_prefix
+ "_occlusion_query_ext_autogen.h",
11042 "occlusion_query_EXT")
11043 gen
.WriteMojoGLCallVisitorForExtension(
11044 mojo_gles2_prefix
+ "_chromium_image_autogen.h",
11046 gen
.WriteMojoGLCallVisitorForExtension(
11047 mojo_gles2_prefix
+ "_chromium_copy_texture_autogen.h",
11048 "CHROMIUM_copy_texture")
11049 gen
.WriteMojoGLCallVisitorForExtension(
11050 mojo_gles2_prefix
+ "_chromium_pixel_transfer_buffer_object_autogen.h",
11051 "CHROMIUM_pixel_transfer_buffer_object")
11053 Format(gen
.generated_cpp_filenames
)
11056 print "%d errors" % gen
.errors
11061 if __name__
== '__main__':
11062 sys
.exit(main(sys
.argv
[1:]))