Rewrite AndroidSyncSettings to be significantly simpler.
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blob8dba53b8b830479ed5e1794de8d30d6e17c797dd
1 #!/usr/bin/env python
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."""
8 import itertools
9 import os
10 import os.path
11 import sys
12 import re
13 import platform
14 from optparse import OptionParser
15 from subprocess import call
17 _SIZE_OF_UINT32 = 4
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.
25 """
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
31 // DO NOT EDIT!
33 """
35 # This string is copied directly out of the gl2.h file from GLES2.0
37 # Edits:
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
45 _GL_TYPES = {
46 'GLenum': 'unsigned int',
47 'GLboolean': 'unsigned char',
48 'GLbitfield': 'unsigned int',
49 'GLbyte': 'signed char',
50 'GLshort': 'short',
51 'GLint': 'int',
52 'GLsizei': 'int',
53 'GLubyte': 'unsigned char',
54 'GLushort': 'unsigned short',
55 'GLuint': 'unsigned int',
56 'GLfloat': 'float',
57 'GLclampf': 'float',
58 'GLvoid': 'void',
59 'GLfixed': 'int',
60 'GLclampx': 'int'
63 _GL_TYPES_32 = {
64 'GLintptr': 'long int',
65 'GLsizeiptr': 'long int'
68 _GL_TYPES_64 = {
69 'GLintptr': 'long long int',
70 'GLsizeiptr': 'long long int'
73 # Capabilites selected with glEnable
74 _CAPABILITY_FLAGS = [
75 {'name': 'blend'},
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'},
87 _STATES = {
88 'ClearColor': {
89 'type': 'Normal',
90 'func': 'ClearColor',
91 'enum': 'GL_COLOR_CLEAR_VALUE',
92 'states': [
93 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
94 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
95 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
99 'ClearDepthf': {
100 'type': 'Normal',
101 'func': 'ClearDepth',
102 'enum': 'GL_DEPTH_CLEAR_VALUE',
103 'states': [
104 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
107 'ColorMask': {
108 'type': 'Normal',
109 'func': 'ColorMask',
110 'enum': 'GL_COLOR_WRITEMASK',
111 'states': [
113 'name': 'color_mask_red',
114 'type': 'GLboolean',
115 'default': 'true',
116 'cached': True
119 'name': 'color_mask_green',
120 'type': 'GLboolean',
121 'default': 'true',
122 'cached': True
125 'name': 'color_mask_blue',
126 'type': 'GLboolean',
127 'default': 'true',
128 'cached': True
131 'name': 'color_mask_alpha',
132 'type': 'GLboolean',
133 'default': 'true',
134 'cached': True
137 'state_flag': 'framebuffer_state_.clear_state_dirty',
139 'ClearStencil': {
140 'type': 'Normal',
141 'func': 'ClearStencil',
142 'enum': 'GL_STENCIL_CLEAR_VALUE',
143 'states': [
144 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
147 'BlendColor': {
148 'type': 'Normal',
149 'func': 'BlendColor',
150 'enum': 'GL_BLEND_COLOR',
151 'states': [
152 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
153 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
154 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
155 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
158 'BlendEquation': {
159 'type': 'SrcDst',
160 'func': 'BlendEquationSeparate',
161 'states': [
163 'name': 'blend_equation_rgb',
164 'type': 'GLenum',
165 'enum': 'GL_BLEND_EQUATION_RGB',
166 'default': 'GL_FUNC_ADD',
169 'name': 'blend_equation_alpha',
170 'type': 'GLenum',
171 'enum': 'GL_BLEND_EQUATION_ALPHA',
172 'default': 'GL_FUNC_ADD',
176 'BlendFunc': {
177 'type': 'SrcDst',
178 'func': 'BlendFuncSeparate',
179 'states': [
181 'name': 'blend_source_rgb',
182 'type': 'GLenum',
183 'enum': 'GL_BLEND_SRC_RGB',
184 'default': 'GL_ONE',
187 'name': 'blend_dest_rgb',
188 'type': 'GLenum',
189 'enum': 'GL_BLEND_DST_RGB',
190 'default': 'GL_ZERO',
193 'name': 'blend_source_alpha',
194 'type': 'GLenum',
195 'enum': 'GL_BLEND_SRC_ALPHA',
196 'default': 'GL_ONE',
199 'name': 'blend_dest_alpha',
200 'type': 'GLenum',
201 'enum': 'GL_BLEND_DST_ALPHA',
202 'default': 'GL_ZERO',
206 'PolygonOffset': {
207 'type': 'Normal',
208 'func': 'PolygonOffset',
209 'states': [
211 'name': 'polygon_offset_factor',
212 'type': 'GLfloat',
213 'enum': 'GL_POLYGON_OFFSET_FACTOR',
214 'default': '0.0f',
217 'name': 'polygon_offset_units',
218 'type': 'GLfloat',
219 'enum': 'GL_POLYGON_OFFSET_UNITS',
220 'default': '0.0f',
224 'CullFace': {
225 'type': 'Normal',
226 'func': 'CullFace',
227 'enum': 'GL_CULL_FACE_MODE',
228 'states': [
230 'name': 'cull_mode',
231 'type': 'GLenum',
232 'default': 'GL_BACK',
236 'FrontFace': {
237 'type': 'Normal',
238 'func': 'FrontFace',
239 'enum': 'GL_FRONT_FACE',
240 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
242 'DepthFunc': {
243 'type': 'Normal',
244 'func': 'DepthFunc',
245 'enum': 'GL_DEPTH_FUNC',
246 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
248 'DepthRange': {
249 'type': 'Normal',
250 'func': 'DepthRange',
251 'enum': 'GL_DEPTH_RANGE',
252 'states': [
253 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
254 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
257 'SampleCoverage': {
258 'type': 'Normal',
259 'func': 'SampleCoverage',
260 'states': [
262 'name': 'sample_coverage_value',
263 'type': 'GLclampf',
264 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
265 'default': '1.0f',
268 'name': 'sample_coverage_invert',
269 'type': 'GLboolean',
270 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
271 'default': 'false',
275 'StencilMask': {
276 'type': 'FrontBack',
277 'func': 'StencilMaskSeparate',
278 'state_flag': 'framebuffer_state_.clear_state_dirty',
279 'states': [
281 'name': 'stencil_front_writemask',
282 'type': 'GLuint',
283 'enum': 'GL_STENCIL_WRITEMASK',
284 'default': '0xFFFFFFFFU',
285 'cached': True,
288 'name': 'stencil_back_writemask',
289 'type': 'GLuint',
290 'enum': 'GL_STENCIL_BACK_WRITEMASK',
291 'default': '0xFFFFFFFFU',
292 'cached': True,
296 'StencilOp': {
297 'type': 'FrontBack',
298 'func': 'StencilOpSeparate',
299 'states': [
301 'name': 'stencil_front_fail_op',
302 'type': 'GLenum',
303 'enum': 'GL_STENCIL_FAIL',
304 'default': 'GL_KEEP',
307 'name': 'stencil_front_z_fail_op',
308 'type': 'GLenum',
309 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
310 'default': 'GL_KEEP',
313 'name': 'stencil_front_z_pass_op',
314 'type': 'GLenum',
315 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
316 'default': 'GL_KEEP',
319 'name': 'stencil_back_fail_op',
320 'type': 'GLenum',
321 'enum': 'GL_STENCIL_BACK_FAIL',
322 'default': 'GL_KEEP',
325 'name': 'stencil_back_z_fail_op',
326 'type': 'GLenum',
327 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
328 'default': 'GL_KEEP',
331 'name': 'stencil_back_z_pass_op',
332 'type': 'GLenum',
333 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
334 'default': 'GL_KEEP',
338 'StencilFunc': {
339 'type': 'FrontBack',
340 'func': 'StencilFuncSeparate',
341 'states': [
343 'name': 'stencil_front_func',
344 'type': 'GLenum',
345 'enum': 'GL_STENCIL_FUNC',
346 'default': 'GL_ALWAYS',
349 'name': 'stencil_front_ref',
350 'type': 'GLint',
351 'enum': 'GL_STENCIL_REF',
352 'default': '0',
355 'name': 'stencil_front_mask',
356 'type': 'GLuint',
357 'enum': 'GL_STENCIL_VALUE_MASK',
358 'default': '0xFFFFFFFFU',
361 'name': 'stencil_back_func',
362 'type': 'GLenum',
363 'enum': 'GL_STENCIL_BACK_FUNC',
364 'default': 'GL_ALWAYS',
367 'name': 'stencil_back_ref',
368 'type': 'GLint',
369 'enum': 'GL_STENCIL_BACK_REF',
370 'default': '0',
373 'name': 'stencil_back_mask',
374 'type': 'GLuint',
375 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
376 'default': '0xFFFFFFFFU',
380 'Hint': {
381 'type': 'NamedParameter',
382 'func': 'Hint',
383 'states': [
385 'name': 'hint_generate_mipmap',
386 'type': 'GLenum',
387 'enum': 'GL_GENERATE_MIPMAP_HINT',
388 'default': 'GL_DONT_CARE'
391 'name': 'hint_fragment_shader_derivative',
392 'type': 'GLenum',
393 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
394 'default': 'GL_DONT_CARE',
395 'extension_flag': 'oes_standard_derivatives'
399 'PixelStore': {
400 'type': 'NamedParameter',
401 'func': 'PixelStorei',
402 'states': [
404 'name': 'pack_alignment',
405 'type': 'GLint',
406 'enum': 'GL_PACK_ALIGNMENT',
407 'default': '4'
410 'name': 'unpack_alignment',
411 'type': 'GLint',
412 'enum': 'GL_UNPACK_ALIGNMENT',
413 'default': '4'
417 # TODO: Consider implemenenting these states
418 # GL_ACTIVE_TEXTURE
419 'LineWidth': {
420 'type': 'Normal',
421 'func': 'LineWidth',
422 'enum': 'GL_LINE_WIDTH',
423 'states': [
425 'name': 'line_width',
426 'type': 'GLfloat',
427 'default': '1.0f',
428 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
429 'nan_check': True,
432 'DepthMask': {
433 'type': 'Normal',
434 'func': 'DepthMask',
435 'enum': 'GL_DEPTH_WRITEMASK',
436 'states': [
438 'name': 'depth_mask',
439 'type': 'GLboolean',
440 'default': 'true',
441 'cached': True
444 'state_flag': 'framebuffer_state_.clear_state_dirty',
446 'Scissor': {
447 'type': 'Normal',
448 'func': 'Scissor',
449 'enum': 'GL_SCISSOR_BOX',
450 'states': [
451 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
453 'name': 'scissor_x',
454 'type': 'GLint',
455 'default': '0',
456 'expected': 'kViewportX',
459 'name': 'scissor_y',
460 'type': 'GLint',
461 'default': '0',
462 'expected': 'kViewportY',
465 'name': 'scissor_width',
466 'type': 'GLsizei',
467 'default': '1',
468 'expected': 'kViewportWidth',
471 'name': 'scissor_height',
472 'type': 'GLsizei',
473 'default': '1',
474 'expected': 'kViewportHeight',
478 'Viewport': {
479 'type': 'Normal',
480 'func': 'Viewport',
481 'enum': 'GL_VIEWPORT',
482 'states': [
483 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
485 'name': 'viewport_x',
486 'type': 'GLint',
487 'default': '0',
488 'expected': 'kViewportX',
491 'name': 'viewport_y',
492 'type': 'GLint',
493 'default': '0',
494 'expected': 'kViewportY',
497 'name': 'viewport_width',
498 'type': 'GLsizei',
499 'default': '1',
500 'expected': 'kViewportWidth',
503 'name': 'viewport_height',
504 'type': 'GLsizei',
505 'default': '1',
506 'expected': 'kViewportHeight',
510 'MatrixValuesCHROMIUM': {
511 'type': 'NamedParameter',
512 'func': 'MatrixLoadfEXT',
513 'states': [
514 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
515 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
516 'name': 'modelview_matrix',
517 'type': 'GLfloat',
518 'default': [
519 '1.0f', '0.0f','0.0f','0.0f',
520 '0.0f', '1.0f','0.0f','0.0f',
521 '0.0f', '0.0f','1.0f','0.0f',
522 '0.0f', '0.0f','0.0f','1.0f',
524 'extension_flag': 'chromium_path_rendering',
526 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
527 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
528 'name': 'projection_matrix',
529 'type': 'GLfloat',
530 'default': [
531 '1.0f', '0.0f','0.0f','0.0f',
532 '0.0f', '1.0f','0.0f','0.0f',
533 '0.0f', '0.0f','1.0f','0.0f',
534 '0.0f', '0.0f','0.0f','1.0f',
536 'extension_flag': 'chromium_path_rendering',
542 # Named type info object represents a named type that is used in OpenGL call
543 # arguments. Each named type defines a set of valid OpenGL call arguments. The
544 # named types are used in 'cmd_buffer_functions.txt'.
545 # type: The actual GL type of the named type.
546 # valid: The list of values that are valid for both the client and the service.
547 # invalid: Examples of invalid values for the type. At least these values
548 # should be tested to be invalid.
549 # is_complete: The list of valid values of type are final and will not be
550 # modified during runtime.
551 _NAMED_TYPE_INFO = {
552 'BlitFilter': {
553 'type': 'GLenum',
554 'valid': [
555 'GL_NEAREST',
556 'GL_LINEAR',
558 'invalid': [
559 'GL_LINEAR_MIPMAP_LINEAR',
562 'FrameBufferTarget': {
563 'type': 'GLenum',
564 'valid': [
565 'GL_FRAMEBUFFER',
567 'invalid': [
568 'GL_DRAW_FRAMEBUFFER' ,
569 'GL_READ_FRAMEBUFFER' ,
572 'RenderBufferTarget': {
573 'type': 'GLenum',
574 'valid': [
575 'GL_RENDERBUFFER',
577 'invalid': [
578 'GL_FRAMEBUFFER',
581 'BufferTarget': {
582 'type': 'GLenum',
583 'valid': [
584 'GL_ARRAY_BUFFER',
585 'GL_ELEMENT_ARRAY_BUFFER',
587 'invalid': [
588 'GL_RENDERBUFFER',
591 'IndexedBufferTarget': {
592 'type': 'GLenum',
593 'valid': [
594 'GL_TRANSFORM_FEEDBACK_BUFFER',
595 'GL_UNIFORM_BUFFER',
597 'invalid': [
598 'GL_RENDERBUFFER',
601 'Bufferiv': {
602 'type': 'GLenum',
603 'valid': [
604 'GL_COLOR',
605 'GL_STENCIL',
607 'invalid': [
608 'GL_RENDERBUFFER',
611 'Bufferuiv': {
612 'type': 'GLenum',
613 'valid': [
614 'GL_COLOR',
616 'invalid': [
617 'GL_RENDERBUFFER',
620 'Bufferfv': {
621 'type': 'GLenum',
622 'valid': [
623 'GL_COLOR',
624 'GL_DEPTH',
626 'invalid': [
627 'GL_RENDERBUFFER',
630 'Bufferfi': {
631 'type': 'GLenum',
632 'valid': [
633 'GL_DEPTH_STENCIL',
635 'invalid': [
636 'GL_RENDERBUFFER',
639 'BufferUsage': {
640 'type': 'GLenum',
641 'valid': [
642 'GL_STREAM_DRAW',
643 'GL_STATIC_DRAW',
644 'GL_DYNAMIC_DRAW',
646 'invalid': [
647 'GL_STATIC_READ',
650 'CompressedTextureFormat': {
651 'type': 'GLenum',
652 'valid': [
655 'GLState': {
656 'type': 'GLenum',
657 'valid': [
658 # NOTE: State an Capability entries added later.
659 'GL_ACTIVE_TEXTURE',
660 'GL_ALIASED_LINE_WIDTH_RANGE',
661 'GL_ALIASED_POINT_SIZE_RANGE',
662 'GL_ALPHA_BITS',
663 'GL_ARRAY_BUFFER_BINDING',
664 'GL_BLUE_BITS',
665 'GL_COMPRESSED_TEXTURE_FORMATS',
666 'GL_CURRENT_PROGRAM',
667 'GL_DEPTH_BITS',
668 'GL_DEPTH_RANGE',
669 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
670 'GL_FRAMEBUFFER_BINDING',
671 'GL_GENERATE_MIPMAP_HINT',
672 'GL_GREEN_BITS',
673 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
674 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
675 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
676 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
677 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
678 'GL_MAX_RENDERBUFFER_SIZE',
679 'GL_MAX_TEXTURE_IMAGE_UNITS',
680 'GL_MAX_TEXTURE_SIZE',
681 'GL_MAX_VARYING_VECTORS',
682 'GL_MAX_VERTEX_ATTRIBS',
683 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
684 'GL_MAX_VERTEX_UNIFORM_VECTORS',
685 'GL_MAX_VIEWPORT_DIMS',
686 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
687 'GL_NUM_SHADER_BINARY_FORMATS',
688 'GL_PACK_ALIGNMENT',
689 'GL_RED_BITS',
690 'GL_RENDERBUFFER_BINDING',
691 'GL_SAMPLE_BUFFERS',
692 'GL_SAMPLE_COVERAGE_INVERT',
693 'GL_SAMPLE_COVERAGE_VALUE',
694 'GL_SAMPLES',
695 'GL_SCISSOR_BOX',
696 'GL_SHADER_BINARY_FORMATS',
697 'GL_SHADER_COMPILER',
698 'GL_SUBPIXEL_BITS',
699 'GL_STENCIL_BITS',
700 'GL_TEXTURE_BINDING_2D',
701 'GL_TEXTURE_BINDING_CUBE_MAP',
702 'GL_UNPACK_ALIGNMENT',
703 'GL_UNPACK_FLIP_Y_CHROMIUM',
704 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
705 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
706 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
707 # we can add this because we emulate it if the driver does not support it.
708 'GL_VERTEX_ARRAY_BINDING_OES',
709 'GL_VIEWPORT',
711 'invalid': [
712 'GL_FOG_HINT',
715 'GetTexParamTarget': {
716 'type': 'GLenum',
717 'valid': [
718 'GL_TEXTURE_2D',
719 'GL_TEXTURE_CUBE_MAP',
721 'invalid': [
722 'GL_PROXY_TEXTURE_CUBE_MAP',
725 'TextureTarget': {
726 'type': 'GLenum',
727 'valid': [
728 'GL_TEXTURE_2D',
729 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
730 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
731 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
732 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
733 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
734 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
736 'invalid': [
737 'GL_PROXY_TEXTURE_CUBE_MAP',
740 'Texture3DTarget': {
741 'type': 'GLenum',
742 'valid': [
743 'GL_TEXTURE_3D',
744 'GL_TEXTURE_2D_ARRAY',
746 'invalid': [
747 'GL_TEXTURE_2D',
750 'TextureBindTarget': {
751 'type': 'GLenum',
752 'valid': [
753 'GL_TEXTURE_2D',
754 'GL_TEXTURE_CUBE_MAP',
756 'invalid': [
757 'GL_TEXTURE_1D',
758 'GL_TEXTURE_3D',
761 'TransformFeedbackBindTarget': {
762 'type': 'GLenum',
763 'valid': [
764 'GL_TRANSFORM_FEEDBACK',
766 'invalid': [
767 'GL_TEXTURE_2D',
770 'TransformFeedbackPrimitiveMode': {
771 'type': 'GLenum',
772 'valid': [
773 'GL_POINTS',
774 'GL_LINES',
775 'GL_TRIANGLES',
777 'invalid': [
778 'GL_LINE_LOOP',
781 'ShaderType': {
782 'type': 'GLenum',
783 'valid': [
784 'GL_VERTEX_SHADER',
785 'GL_FRAGMENT_SHADER',
787 'invalid': [
788 'GL_GEOMETRY_SHADER',
791 'FaceType': {
792 'type': 'GLenum',
793 'valid': [
794 'GL_FRONT',
795 'GL_BACK',
796 'GL_FRONT_AND_BACK',
799 'FaceMode': {
800 'type': 'GLenum',
801 'valid': [
802 'GL_CW',
803 'GL_CCW',
806 'CmpFunction': {
807 'type': 'GLenum',
808 'valid': [
809 'GL_NEVER',
810 'GL_LESS',
811 'GL_EQUAL',
812 'GL_LEQUAL',
813 'GL_GREATER',
814 'GL_NOTEQUAL',
815 'GL_GEQUAL',
816 'GL_ALWAYS',
819 'Equation': {
820 'type': 'GLenum',
821 'valid': [
822 'GL_FUNC_ADD',
823 'GL_FUNC_SUBTRACT',
824 'GL_FUNC_REVERSE_SUBTRACT',
826 'invalid': [
827 'GL_MIN',
828 'GL_MAX',
831 'SrcBlendFactor': {
832 'type': 'GLenum',
833 'valid': [
834 'GL_ZERO',
835 'GL_ONE',
836 'GL_SRC_COLOR',
837 'GL_ONE_MINUS_SRC_COLOR',
838 'GL_DST_COLOR',
839 'GL_ONE_MINUS_DST_COLOR',
840 'GL_SRC_ALPHA',
841 'GL_ONE_MINUS_SRC_ALPHA',
842 'GL_DST_ALPHA',
843 'GL_ONE_MINUS_DST_ALPHA',
844 'GL_CONSTANT_COLOR',
845 'GL_ONE_MINUS_CONSTANT_COLOR',
846 'GL_CONSTANT_ALPHA',
847 'GL_ONE_MINUS_CONSTANT_ALPHA',
848 'GL_SRC_ALPHA_SATURATE',
851 'DstBlendFactor': {
852 'type': 'GLenum',
853 'valid': [
854 'GL_ZERO',
855 'GL_ONE',
856 'GL_SRC_COLOR',
857 'GL_ONE_MINUS_SRC_COLOR',
858 'GL_DST_COLOR',
859 'GL_ONE_MINUS_DST_COLOR',
860 'GL_SRC_ALPHA',
861 'GL_ONE_MINUS_SRC_ALPHA',
862 'GL_DST_ALPHA',
863 'GL_ONE_MINUS_DST_ALPHA',
864 'GL_CONSTANT_COLOR',
865 'GL_ONE_MINUS_CONSTANT_COLOR',
866 'GL_CONSTANT_ALPHA',
867 'GL_ONE_MINUS_CONSTANT_ALPHA',
870 'Capability': {
871 'type': 'GLenum',
872 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS],
873 'invalid': [
874 'GL_CLIP_PLANE0',
875 'GL_POINT_SPRITE',
878 'DrawMode': {
879 'type': 'GLenum',
880 'valid': [
881 'GL_POINTS',
882 'GL_LINE_STRIP',
883 'GL_LINE_LOOP',
884 'GL_LINES',
885 'GL_TRIANGLE_STRIP',
886 'GL_TRIANGLE_FAN',
887 'GL_TRIANGLES',
889 'invalid': [
890 'GL_QUADS',
891 'GL_POLYGON',
894 'IndexType': {
895 'type': 'GLenum',
896 'valid': [
897 'GL_UNSIGNED_BYTE',
898 'GL_UNSIGNED_SHORT',
900 'invalid': [
901 'GL_UNSIGNED_INT',
902 'GL_INT',
905 'GetMaxIndexType': {
906 'type': 'GLenum',
907 'valid': [
908 'GL_UNSIGNED_BYTE',
909 'GL_UNSIGNED_SHORT',
910 'GL_UNSIGNED_INT',
912 'invalid': [
913 'GL_INT',
916 'Attachment': {
917 'type': 'GLenum',
918 'valid': [
919 'GL_COLOR_ATTACHMENT0',
920 'GL_DEPTH_ATTACHMENT',
921 'GL_STENCIL_ATTACHMENT',
924 'BackbufferAttachment': {
925 'type': 'GLenum',
926 'valid': [
927 'GL_COLOR_EXT',
928 'GL_DEPTH_EXT',
929 'GL_STENCIL_EXT',
932 'BufferParameter': {
933 'type': 'GLenum',
934 'valid': [
935 'GL_BUFFER_SIZE',
936 'GL_BUFFER_USAGE',
938 'invalid': [
939 'GL_PIXEL_PACK_BUFFER',
942 'BufferMode': {
943 'type': 'GLenum',
944 'valid': [
945 'GL_INTERLEAVED_ATTRIBS',
946 'GL_SEPARATE_ATTRIBS',
948 'invalid': [
949 'GL_PIXEL_PACK_BUFFER',
952 'FrameBufferParameter': {
953 'type': 'GLenum',
954 'valid': [
955 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
956 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
957 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
958 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
961 'MatrixMode': {
962 'type': 'GLenum',
963 'valid': [
964 'GL_PATH_PROJECTION_CHROMIUM',
965 'GL_PATH_MODELVIEW_CHROMIUM',
968 'ProgramParameter': {
969 'type': 'GLenum',
970 'valid': [
971 'GL_DELETE_STATUS',
972 'GL_LINK_STATUS',
973 'GL_VALIDATE_STATUS',
974 'GL_INFO_LOG_LENGTH',
975 'GL_ATTACHED_SHADERS',
976 'GL_ACTIVE_ATTRIBUTES',
977 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
978 'GL_ACTIVE_UNIFORMS',
979 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
982 'QueryObjectParameter': {
983 'type': 'GLenum',
984 'valid': [
985 'GL_QUERY_RESULT_EXT',
986 'GL_QUERY_RESULT_AVAILABLE_EXT',
989 'QueryParameter': {
990 'type': 'GLenum',
991 'valid': [
992 'GL_CURRENT_QUERY_EXT',
995 'QueryTarget': {
996 'type': 'GLenum',
997 'valid': [
998 'GL_ANY_SAMPLES_PASSED_EXT',
999 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1000 'GL_COMMANDS_ISSUED_CHROMIUM',
1001 'GL_LATENCY_QUERY_CHROMIUM',
1002 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1003 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1004 'GL_COMMANDS_COMPLETED_CHROMIUM',
1007 'RenderBufferParameter': {
1008 'type': 'GLenum',
1009 'valid': [
1010 'GL_RENDERBUFFER_RED_SIZE',
1011 'GL_RENDERBUFFER_GREEN_SIZE',
1012 'GL_RENDERBUFFER_BLUE_SIZE',
1013 'GL_RENDERBUFFER_ALPHA_SIZE',
1014 'GL_RENDERBUFFER_DEPTH_SIZE',
1015 'GL_RENDERBUFFER_STENCIL_SIZE',
1016 'GL_RENDERBUFFER_WIDTH',
1017 'GL_RENDERBUFFER_HEIGHT',
1018 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1021 'SamplerParameter': {
1022 'type': 'GLenum',
1023 'valid': [
1024 'GL_TEXTURE_MAG_FILTER',
1025 'GL_TEXTURE_MIN_FILTER',
1026 'GL_TEXTURE_MIN_LOD',
1027 'GL_TEXTURE_MAX_LOD',
1028 'GL_TEXTURE_WRAP_S',
1029 'GL_TEXTURE_WRAP_T',
1030 'GL_TEXTURE_WRAP_R',
1031 'GL_TEXTURE_COMPARE_MODE',
1032 'GL_TEXTURE_COMPARE_FUNC',
1034 'invalid': [
1035 'GL_GENERATE_MIPMAP',
1038 'ShaderParameter': {
1039 'type': 'GLenum',
1040 'valid': [
1041 'GL_SHADER_TYPE',
1042 'GL_DELETE_STATUS',
1043 'GL_COMPILE_STATUS',
1044 'GL_INFO_LOG_LENGTH',
1045 'GL_SHADER_SOURCE_LENGTH',
1046 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1049 'ShaderPrecision': {
1050 'type': 'GLenum',
1051 'valid': [
1052 'GL_LOW_FLOAT',
1053 'GL_MEDIUM_FLOAT',
1054 'GL_HIGH_FLOAT',
1055 'GL_LOW_INT',
1056 'GL_MEDIUM_INT',
1057 'GL_HIGH_INT',
1060 'StringType': {
1061 'type': 'GLenum',
1062 'valid': [
1063 'GL_VENDOR',
1064 'GL_RENDERER',
1065 'GL_VERSION',
1066 'GL_SHADING_LANGUAGE_VERSION',
1067 'GL_EXTENSIONS',
1070 'TextureParameter': {
1071 'type': 'GLenum',
1072 'valid': [
1073 'GL_TEXTURE_MAG_FILTER',
1074 'GL_TEXTURE_MIN_FILTER',
1075 'GL_TEXTURE_POOL_CHROMIUM',
1076 'GL_TEXTURE_WRAP_S',
1077 'GL_TEXTURE_WRAP_T',
1079 'invalid': [
1080 'GL_GENERATE_MIPMAP',
1083 'TexturePool': {
1084 'type': 'GLenum',
1085 'valid': [
1086 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1087 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1090 'TextureWrapMode': {
1091 'type': 'GLenum',
1092 'valid': [
1093 'GL_CLAMP_TO_EDGE',
1094 'GL_MIRRORED_REPEAT',
1095 'GL_REPEAT',
1098 'TextureMinFilterMode': {
1099 'type': 'GLenum',
1100 'valid': [
1101 'GL_NEAREST',
1102 'GL_LINEAR',
1103 'GL_NEAREST_MIPMAP_NEAREST',
1104 'GL_LINEAR_MIPMAP_NEAREST',
1105 'GL_NEAREST_MIPMAP_LINEAR',
1106 'GL_LINEAR_MIPMAP_LINEAR',
1109 'TextureMagFilterMode': {
1110 'type': 'GLenum',
1111 'valid': [
1112 'GL_NEAREST',
1113 'GL_LINEAR',
1116 'TextureUsage': {
1117 'type': 'GLenum',
1118 'valid': [
1119 'GL_NONE',
1120 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1123 'VertexAttribute': {
1124 'type': 'GLenum',
1125 'valid': [
1126 # some enum that the decoder actually passes through to GL needs
1127 # to be the first listed here since it's used in unit tests.
1128 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1129 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1130 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1131 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1132 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1133 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1134 'GL_CURRENT_VERTEX_ATTRIB',
1137 'VertexPointer': {
1138 'type': 'GLenum',
1139 'valid': [
1140 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1143 'HintTarget': {
1144 'type': 'GLenum',
1145 'valid': [
1146 'GL_GENERATE_MIPMAP_HINT',
1148 'invalid': [
1149 'GL_PERSPECTIVE_CORRECTION_HINT',
1152 'HintMode': {
1153 'type': 'GLenum',
1154 'valid': [
1155 'GL_FASTEST',
1156 'GL_NICEST',
1157 'GL_DONT_CARE',
1160 'PixelStore': {
1161 'type': 'GLenum',
1162 'valid': [
1163 'GL_PACK_ALIGNMENT',
1164 'GL_UNPACK_ALIGNMENT',
1165 'GL_UNPACK_FLIP_Y_CHROMIUM',
1166 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
1167 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
1169 'invalid': [
1170 'GL_PACK_SWAP_BYTES',
1171 'GL_UNPACK_SWAP_BYTES',
1174 'PixelStoreAlignment': {
1175 'type': 'GLint',
1176 'valid': [
1177 '1',
1178 '2',
1179 '4',
1180 '8',
1182 'invalid': [
1183 '3',
1184 '9',
1187 'ReadPixelFormat': {
1188 'type': 'GLenum',
1189 'valid': [
1190 'GL_ALPHA',
1191 'GL_RGB',
1192 'GL_RGBA',
1195 'PixelType': {
1196 'type': 'GLenum',
1197 'valid': [
1198 'GL_UNSIGNED_BYTE',
1199 'GL_UNSIGNED_SHORT_5_6_5',
1200 'GL_UNSIGNED_SHORT_4_4_4_4',
1201 'GL_UNSIGNED_SHORT_5_5_5_1',
1203 'invalid': [
1204 'GL_SHORT',
1205 'GL_INT',
1208 'ReadPixelType': {
1209 'type': 'GLenum',
1210 'valid': [
1211 'GL_UNSIGNED_BYTE',
1212 'GL_UNSIGNED_SHORT_5_6_5',
1213 'GL_UNSIGNED_SHORT_4_4_4_4',
1214 'GL_UNSIGNED_SHORT_5_5_5_1',
1216 'invalid': [
1217 'GL_SHORT',
1218 'GL_INT',
1221 'RenderBufferFormat': {
1222 'type': 'GLenum',
1223 'valid': [
1224 'GL_RGBA4',
1225 'GL_RGB565',
1226 'GL_RGB5_A1',
1227 'GL_DEPTH_COMPONENT16',
1228 'GL_STENCIL_INDEX8',
1231 'ShaderBinaryFormat': {
1232 'type': 'GLenum',
1233 'valid': [
1236 'StencilOp': {
1237 'type': 'GLenum',
1238 'valid': [
1239 'GL_KEEP',
1240 'GL_ZERO',
1241 'GL_REPLACE',
1242 'GL_INCR',
1243 'GL_INCR_WRAP',
1244 'GL_DECR',
1245 'GL_DECR_WRAP',
1246 'GL_INVERT',
1249 'TextureFormat': {
1250 'type': 'GLenum',
1251 'valid': [
1252 'GL_ALPHA',
1253 'GL_LUMINANCE',
1254 'GL_LUMINANCE_ALPHA',
1255 'GL_RGB',
1256 'GL_RGBA',
1258 'invalid': [
1259 'GL_BGRA',
1260 'GL_BGR',
1263 'TextureInternalFormat': {
1264 'type': 'GLenum',
1265 'valid': [
1266 'GL_ALPHA',
1267 'GL_LUMINANCE',
1268 'GL_LUMINANCE_ALPHA',
1269 'GL_RGB',
1270 'GL_RGBA',
1272 'invalid': [
1273 'GL_BGRA',
1274 'GL_BGR',
1277 'TextureInternalFormatStorage': {
1278 'type': 'GLenum',
1279 'valid': [
1280 'GL_RGB565',
1281 'GL_RGBA4',
1282 'GL_RGB5_A1',
1283 'GL_ALPHA8_EXT',
1284 'GL_LUMINANCE8_EXT',
1285 'GL_LUMINANCE8_ALPHA8_EXT',
1286 'GL_RGB8_OES',
1287 'GL_RGBA8_OES',
1290 'ImageInternalFormat': {
1291 'type': 'GLenum',
1292 'valid': [
1293 'GL_RGB',
1294 'GL_RGBA',
1297 'ImageUsage': {
1298 'type': 'GLenum',
1299 'valid': [
1300 'GL_MAP_CHROMIUM',
1301 'GL_SCANOUT_CHROMIUM'
1304 'ValueBufferTarget': {
1305 'type': 'GLenum',
1306 'valid': [
1307 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1310 'SubscriptionTarget': {
1311 'type': 'GLenum',
1312 'valid': [
1313 'GL_MOUSE_POSITION_CHROMIUM',
1316 'UniformParameter': {
1317 'type': 'GLenum',
1318 'valid': [
1319 'GL_UNIFORM_SIZE',
1320 'GL_UNIFORM_TYPE',
1321 'GL_UNIFORM_NAME_LENGTH',
1322 'GL_UNIFORM_BLOCK_INDEX',
1323 'GL_UNIFORM_OFFSET',
1324 'GL_UNIFORM_ARRAY_STRIDE',
1325 'GL_UNIFORM_MATRIX_STRIDE',
1326 'GL_UNIFORM_IS_ROW_MAJOR',
1328 'invalid': [
1329 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1332 'UniformBlockParameter': {
1333 'type': 'GLenum',
1334 'valid': [
1335 'GL_UNIFORM_BLOCK_BINDING',
1336 'GL_UNIFORM_BLOCK_DATA_SIZE',
1337 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1338 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1339 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1340 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1341 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1343 'invalid': [
1344 'GL_NEAREST',
1347 'VertexAttribType': {
1348 'type': 'GLenum',
1349 'valid': [
1350 'GL_BYTE',
1351 'GL_UNSIGNED_BYTE',
1352 'GL_SHORT',
1353 'GL_UNSIGNED_SHORT',
1354 # 'GL_FIXED', // This is not available on Desktop GL.
1355 'GL_FLOAT',
1357 'invalid': [
1358 'GL_DOUBLE',
1361 'TextureBorder': {
1362 'type': 'GLint',
1363 'is_complete': True,
1364 'valid': [
1365 '0',
1367 'invalid': [
1368 '1',
1371 'VertexAttribSize': {
1372 'type': 'GLint',
1373 'valid': [
1374 '1',
1375 '2',
1376 '3',
1377 '4',
1379 'invalid': [
1380 '0',
1381 '5',
1384 'ZeroOnly': {
1385 'type': 'GLint',
1386 'is_complete': True,
1387 'valid': [
1388 '0',
1390 'invalid': [
1391 '1',
1394 'FalseOnly': {
1395 'type': 'GLboolean',
1396 'is_complete': True,
1397 'valid': [
1398 'false',
1400 'invalid': [
1401 'true',
1404 'ResetStatus': {
1405 'type': 'GLenum',
1406 'valid': [
1407 'GL_GUILTY_CONTEXT_RESET_ARB',
1408 'GL_INNOCENT_CONTEXT_RESET_ARB',
1409 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1412 'SyncCondition': {
1413 'type': 'GLenum',
1414 'is_complete': True,
1415 'valid': [
1416 'GL_SYNC_GPU_COMMANDS_COMPLETE',
1418 'invalid': [
1419 '0',
1422 'SyncFlags': {
1423 'type': 'GLbitfield',
1424 'is_complete': True,
1425 'valid': [
1426 '0',
1428 'invalid': [
1429 '1',
1432 'SyncFlushFlags': {
1433 'type': 'GLbitfield',
1434 'valid': [
1435 'GL_SYNC_FLUSH_COMMANDS_BIT',
1436 '0',
1438 'invalid': [
1439 '0xFFFFFFFF',
1442 'SyncParameter': {
1443 'type': 'GLenum',
1444 'valid': [
1445 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
1446 'GL_OBJECT_TYPE',
1447 'GL_SYNC_CONDITION',
1448 'GL_SYNC_FLAGS',
1450 'invalid': [
1451 'GL_SYNC_FENCE',
1456 # This table specifies the different pepper interfaces that are supported for
1457 # GL commands. 'dev' is true if it's a dev interface.
1458 _PEPPER_INTERFACES = [
1459 {'name': '', 'dev': False},
1460 {'name': 'InstancedArrays', 'dev': False},
1461 {'name': 'FramebufferBlit', 'dev': False},
1462 {'name': 'FramebufferMultisample', 'dev': False},
1463 {'name': 'ChromiumEnableFeature', 'dev': False},
1464 {'name': 'ChromiumMapSub', 'dev': False},
1465 {'name': 'Query', 'dev': False},
1466 {'name': 'VertexArrayObject', 'dev': False},
1467 {'name': 'DrawBuffers', 'dev': True},
1470 # A function info object specifies the type and other special data for the
1471 # command that will be generated. A base function info object is generated by
1472 # parsing the "cmd_buffer_functions.txt", one for each function in the
1473 # file. These function info objects can be augmented and their values can be
1474 # overridden by adding an object to the table below.
1476 # Must match function names specified in "cmd_buffer_functions.txt".
1478 # cmd_comment: A comment added to the cmd format.
1479 # type: defines which handler will be used to generate code.
1480 # decoder_func: defines which function to call in the decoder to execute the
1481 # corresponding GL command. If not specified the GL command will
1482 # be called directly.
1483 # gl_test_func: GL function that is expected to be called when testing.
1484 # cmd_args: The arguments to use for the command. This overrides generating
1485 # them based on the GL function arguments.
1486 # gen_cmd: Whether or not this function geneates a command. Default = True.
1487 # data_transfer_methods: Array of methods that are used for transfering the
1488 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1489 # The default is 'immediate' if the command has one pointer
1490 # argument, otherwise 'shm'. One command is generated for each
1491 # transfer method. Affects only commands which are not of type
1492 # 'HandWritten', 'GETn' or 'GLcharN'.
1493 # Note: the command arguments that affect this are the final args,
1494 # taking cmd_args override into consideration.
1495 # impl_func: Whether or not to generate the GLES2Implementation part of this
1496 # command.
1497 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1498 # for this command.
1499 # needs_size: If True a data_size field is added to the command.
1500 # count: The number of units per element. For PUTn or PUT types.
1501 # use_count_func: If True the actual data count needs to be computed; the count
1502 # argument specifies the maximum count.
1503 # unit_test: If False no service side unit test will be generated.
1504 # client_test: If False no client side unit test will be generated.
1505 # expectation: If False the unit test will have no expected calls.
1506 # gen_func: Name of function that generates GL resource for corresponding
1507 # bind function.
1508 # states: array of states that get set by this function corresponding to
1509 # the given arguments
1510 # state_flag: name of flag that is set to true when function is called.
1511 # no_gl: no GL function is called.
1512 # valid_args: A dictionary of argument indices to args to use in unit tests
1513 # when they can not be automatically determined.
1514 # pepper_interface: The pepper interface that is used for this extension
1515 # pepper_name: The name of the function as exposed to pepper.
1516 # pepper_args: A string representing the argument list (what would appear in
1517 # C/C++ between the parentheses for the function declaration)
1518 # that the Pepper API expects for this function. Use this only if
1519 # the stable Pepper API differs from the GLES2 argument list.
1520 # invalid_test: False if no invalid test needed.
1521 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1522 # first_element_only: For PUT types, True if only the first element of an
1523 # array is used and we end up calling the single value
1524 # corresponding function. eg. TexParameteriv -> TexParameteri
1525 # extension: Function is an extension to GL and should not be exposed to
1526 # pepper unless pepper_interface is defined.
1527 # extension_flag: Function is an extension and should be enabled only when
1528 # the corresponding feature info flag is enabled. Implies
1529 # 'extension': True.
1530 # not_shared: For GENn types, True if objects can't be shared between contexts
1531 # unsafe: True = no validation is implemented on the service side and the
1532 # command is only available with --enable-unsafe-es3-apis.
1533 # id_mapping: A list of resource type names whose client side IDs need to be
1534 # mapped to service side IDs. This is only used for unsafe APIs.
1536 _FUNCTION_INFO = {
1537 'ActiveTexture': {
1538 'decoder_func': 'DoActiveTexture',
1539 'unit_test': False,
1540 'impl_func': False,
1541 'client_test': False,
1543 'AttachShader': {'decoder_func': 'DoAttachShader'},
1544 'BindAttribLocation': {
1545 'type': 'GLchar',
1546 'data_transfer_methods': ['bucket'],
1547 'needs_size': True,
1549 'BindBuffer': {
1550 'type': 'Bind',
1551 'decoder_func': 'DoBindBuffer',
1552 'gen_func': 'GenBuffersARB',
1554 'BindBufferBase': {
1555 'type': 'Bind',
1556 'id_mapping': [ 'Buffer' ],
1557 'gen_func': 'GenBuffersARB',
1558 'unsafe': True,
1560 'BindBufferRange': {
1561 'type': 'Bind',
1562 'id_mapping': [ 'Buffer' ],
1563 'gen_func': 'GenBuffersARB',
1564 'valid_args': {
1565 '3': '4',
1566 '4': '4'
1568 'unsafe': True,
1570 'BindFramebuffer': {
1571 'type': 'Bind',
1572 'decoder_func': 'DoBindFramebuffer',
1573 'gl_test_func': 'glBindFramebufferEXT',
1574 'gen_func': 'GenFramebuffersEXT',
1575 'trace_level': 1,
1577 'BindRenderbuffer': {
1578 'type': 'Bind',
1579 'decoder_func': 'DoBindRenderbuffer',
1580 'gl_test_func': 'glBindRenderbufferEXT',
1581 'gen_func': 'GenRenderbuffersEXT',
1583 'BindSampler': {
1584 'type': 'Bind',
1585 'id_mapping': [ 'Sampler' ],
1586 'unsafe': True,
1588 'BindTexture': {
1589 'type': 'Bind',
1590 'decoder_func': 'DoBindTexture',
1591 'gen_func': 'GenTextures',
1592 # TODO(gman): remove this once client side caching works.
1593 'client_test': False,
1594 'trace_level': 1,
1596 'BindTransformFeedback': {
1597 'type': 'Bind',
1598 'id_mapping': [ 'TransformFeedback' ],
1599 'unsafe': True,
1601 'BlitFramebufferCHROMIUM': {
1602 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1603 'unit_test': False,
1604 'extension_flag': 'chromium_framebuffer_multisample',
1605 'pepper_interface': 'FramebufferBlit',
1606 'pepper_name': 'BlitFramebufferEXT',
1607 'defer_reads': True,
1608 'defer_draws': True,
1609 'trace_level': 1,
1611 'BufferData': {
1612 'type': 'Manual',
1613 'data_transfer_methods': ['shm'],
1614 'client_test': False,
1616 'BufferSubData': {
1617 'type': 'Data',
1618 'client_test': False,
1619 'decoder_func': 'DoBufferSubData',
1620 'data_transfer_methods': ['shm'],
1622 'CheckFramebufferStatus': {
1623 'type': 'Is',
1624 'decoder_func': 'DoCheckFramebufferStatus',
1625 'gl_test_func': 'glCheckFramebufferStatusEXT',
1626 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1627 'result': ['GLenum'],
1629 'Clear': {
1630 'decoder_func': 'DoClear',
1631 'defer_draws': True,
1632 'trace_level': 1,
1634 'ClearBufferiv': {
1635 'type': 'PUT',
1636 'use_count_func': True,
1637 'count': 4,
1638 'unsafe': True,
1640 'ClearBufferuiv': {
1641 'type': 'PUT',
1642 'count': 4,
1643 'unsafe': True,
1645 'ClearBufferfv': {
1646 'type': 'PUT',
1647 'use_count_func': True,
1648 'count': 4,
1649 'unsafe': True,
1651 'ClearBufferfi': {
1652 'unsafe': True,
1654 'ClearColor': {
1655 'type': 'StateSet',
1656 'state': 'ClearColor',
1658 'ClearDepthf': {
1659 'type': 'StateSet',
1660 'state': 'ClearDepthf',
1661 'decoder_func': 'glClearDepth',
1662 'gl_test_func': 'glClearDepth',
1663 'valid_args': {
1664 '0': '0.5f'
1667 'ClientWaitSync': {
1668 'type': 'Custom',
1669 'data_transfer_methods': ['shm'],
1670 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
1671 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
1672 'unsafe': True,
1673 'result': ['GLenum'],
1675 'ColorMask': {
1676 'type': 'StateSet',
1677 'state': 'ColorMask',
1678 'no_gl': True,
1679 'expectation': False,
1681 'ConsumeTextureCHROMIUM': {
1682 'decoder_func': 'DoConsumeTextureCHROMIUM',
1683 'impl_func': False,
1684 'type': 'PUT',
1685 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1686 'unit_test': False,
1687 'client_test': False,
1688 'extension': "CHROMIUM_texture_mailbox",
1689 'chromium': True,
1690 'trace_level': 1,
1692 'CopyBufferSubData': {
1693 'unsafe': True,
1695 'CreateAndConsumeTextureCHROMIUM': {
1696 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
1697 'impl_func': False,
1698 'type': 'HandWritten',
1699 'data_transfer_methods': ['immediate'],
1700 'unit_test': False,
1701 'client_test': False,
1702 'extension': "CHROMIUM_texture_mailbox",
1703 'chromium': True,
1705 'GenValuebuffersCHROMIUM': {
1706 'type': 'GENn',
1707 'gl_test_func': 'glGenValuebuffersCHROMIUM',
1708 'resource_type': 'Valuebuffer',
1709 'resource_types': 'Valuebuffers',
1710 'unit_test': False,
1711 'extension': True,
1712 'chromium': True,
1714 'DeleteValuebuffersCHROMIUM': {
1715 'type': 'DELn',
1716 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
1717 'resource_type': 'Valuebuffer',
1718 'resource_types': 'Valuebuffers',
1719 'unit_test': False,
1720 'extension': True,
1721 'chromium': True,
1723 'IsValuebufferCHROMIUM': {
1724 'type': 'Is',
1725 'decoder_func': 'DoIsValuebufferCHROMIUM',
1726 'expectation': False,
1727 'extension': True,
1728 'chromium': True,
1730 'BindValuebufferCHROMIUM': {
1731 'type': 'Bind',
1732 'decoder_func': 'DoBindValueBufferCHROMIUM',
1733 'gen_func': 'GenValueBuffersCHROMIUM',
1734 'unit_test': False,
1735 'extension': True,
1736 'chromium': True,
1738 'SubscribeValueCHROMIUM': {
1739 'decoder_func': 'DoSubscribeValueCHROMIUM',
1740 'unit_test': False,
1741 'extension': True,
1742 'chromium': True,
1744 'PopulateSubscribedValuesCHROMIUM': {
1745 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
1746 'unit_test': False,
1747 'extension': True,
1748 'chromium': True,
1750 'UniformValuebufferCHROMIUM': {
1751 'decoder_func': 'DoUniformValueBufferCHROMIUM',
1752 'unit_test': False,
1753 'extension': True,
1754 'chromium': True,
1756 'ClearStencil': {
1757 'type': 'StateSet',
1758 'state': 'ClearStencil',
1760 'EnableFeatureCHROMIUM': {
1761 'type': 'Custom',
1762 'data_transfer_methods': ['shm'],
1763 'decoder_func': 'DoEnableFeatureCHROMIUM',
1764 'expectation': False,
1765 'cmd_args': 'GLuint bucket_id, GLint* result',
1766 'result': ['GLint'],
1767 'extension': True,
1768 'chromium': True,
1769 'pepper_interface': 'ChromiumEnableFeature',
1771 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1772 'CompressedTexImage2D': {
1773 'type': 'Manual',
1774 'data_transfer_methods': ['bucket', 'shm'],
1776 'CompressedTexSubImage2D': {
1777 'type': 'Data',
1778 'data_transfer_methods': ['bucket', 'shm'],
1779 'decoder_func': 'DoCompressedTexSubImage2D',
1781 'CopyTexImage2D': {
1782 'decoder_func': 'DoCopyTexImage2D',
1783 'unit_test': False,
1784 'defer_reads': True,
1786 'CopyTexSubImage2D': {
1787 'decoder_func': 'DoCopyTexSubImage2D',
1788 'defer_reads': True,
1790 'CopyTexSubImage3D': {
1791 'defer_reads': True,
1792 'unsafe': True,
1794 'CreateImageCHROMIUM': {
1795 'type': 'Manual',
1796 'cmd_args':
1797 'ClientBuffer buffer, GLsizei width, GLsizei height, '
1798 'GLenum internalformat',
1799 'result': ['GLuint'],
1800 'client_test': False,
1801 'gen_cmd': False,
1802 'expectation': False,
1803 'extension': True,
1804 'chromium': True,
1806 'DestroyImageCHROMIUM': {
1807 'type': 'Manual',
1808 'client_test': False,
1809 'gen_cmd': False,
1810 'extension': True,
1811 'chromium': True,
1813 'CreateGpuMemoryBufferImageCHROMIUM': {
1814 'type': 'Manual',
1815 'cmd_args':
1816 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
1817 'result': ['GLuint'],
1818 'client_test': False,
1819 'gen_cmd': False,
1820 'expectation': False,
1821 'extension': True,
1822 'chromium': True,
1824 'CreateProgram': {
1825 'type': 'Create',
1826 'client_test': False,
1828 'CreateShader': {
1829 'type': 'Create',
1830 'client_test': False,
1832 'BlendColor': {
1833 'type': 'StateSet',
1834 'state': 'BlendColor',
1836 'BlendEquation': {
1837 'type': 'StateSetRGBAlpha',
1838 'state': 'BlendEquation',
1839 'valid_args': {
1840 '0': 'GL_FUNC_SUBTRACT'
1843 'BlendEquationSeparate': {
1844 'type': 'StateSet',
1845 'state': 'BlendEquation',
1846 'valid_args': {
1847 '0': 'GL_FUNC_SUBTRACT'
1850 'BlendFunc': {
1851 'type': 'StateSetRGBAlpha',
1852 'state': 'BlendFunc',
1854 'BlendFuncSeparate': {
1855 'type': 'StateSet',
1856 'state': 'BlendFunc',
1858 'BlendBarrierKHR': {
1859 'gl_test_func': 'glBlendBarrierKHR',
1860 'extension': True,
1861 'extension_flag': 'blend_equation_advanced',
1862 'client_test': False,
1864 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1865 'StencilFunc': {
1866 'type': 'StateSetFrontBack',
1867 'state': 'StencilFunc',
1869 'StencilFuncSeparate': {
1870 'type': 'StateSetFrontBackSeparate',
1871 'state': 'StencilFunc',
1873 'StencilOp': {
1874 'type': 'StateSetFrontBack',
1875 'state': 'StencilOp',
1876 'valid_args': {
1877 '1': 'GL_INCR'
1880 'StencilOpSeparate': {
1881 'type': 'StateSetFrontBackSeparate',
1882 'state': 'StencilOp',
1883 'valid_args': {
1884 '1': 'GL_INCR'
1887 'Hint': {
1888 'type': 'StateSetNamedParameter',
1889 'state': 'Hint',
1891 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1892 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1893 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1894 'LineWidth': {
1895 'type': 'StateSet',
1896 'state': 'LineWidth',
1897 'valid_args': {
1898 '0': '0.5f'
1901 'PolygonOffset': {
1902 'type': 'StateSet',
1903 'state': 'PolygonOffset',
1905 'DeleteBuffers': {
1906 'type': 'DELn',
1907 'gl_test_func': 'glDeleteBuffersARB',
1908 'resource_type': 'Buffer',
1909 'resource_types': 'Buffers',
1911 'DeleteFramebuffers': {
1912 'type': 'DELn',
1913 'gl_test_func': 'glDeleteFramebuffersEXT',
1914 'resource_type': 'Framebuffer',
1915 'resource_types': 'Framebuffers',
1917 'DeleteProgram': { 'type': 'Delete' },
1918 'DeleteRenderbuffers': {
1919 'type': 'DELn',
1920 'gl_test_func': 'glDeleteRenderbuffersEXT',
1921 'resource_type': 'Renderbuffer',
1922 'resource_types': 'Renderbuffers',
1924 'DeleteSamplers': {
1925 'type': 'DELn',
1926 'resource_type': 'Sampler',
1927 'resource_types': 'Samplers',
1928 'unsafe': True,
1930 'DeleteShader': { 'type': 'Delete' },
1931 'DeleteSync': {
1932 'type': 'Delete',
1933 'cmd_args': 'GLuint sync',
1934 'resource_type': 'Sync',
1935 'unsafe': True,
1937 'DeleteTextures': {
1938 'type': 'DELn',
1939 'resource_type': 'Texture',
1940 'resource_types': 'Textures',
1942 'DeleteTransformFeedbacks': {
1943 'type': 'DELn',
1944 'resource_type': 'TransformFeedback',
1945 'resource_types': 'TransformFeedbacks',
1946 'unsafe': True,
1948 'DepthRangef': {
1949 'decoder_func': 'DoDepthRangef',
1950 'gl_test_func': 'glDepthRange',
1952 'DepthMask': {
1953 'type': 'StateSet',
1954 'state': 'DepthMask',
1955 'no_gl': True,
1956 'expectation': False,
1958 'DetachShader': {'decoder_func': 'DoDetachShader'},
1959 'Disable': {
1960 'decoder_func': 'DoDisable',
1961 'impl_func': False,
1962 'client_test': False,
1964 'DisableVertexAttribArray': {
1965 'decoder_func': 'DoDisableVertexAttribArray',
1966 'impl_decl': False,
1968 'DrawArrays': {
1969 'type': 'Manual',
1970 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1971 'defer_draws': True,
1972 'trace_level': 2,
1974 'DrawElements': {
1975 'type': 'Manual',
1976 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1977 'GLenumIndexType type, GLuint index_offset',
1978 'client_test': False,
1979 'defer_draws': True,
1980 'trace_level': 2,
1982 'Enable': {
1983 'decoder_func': 'DoEnable',
1984 'impl_func': False,
1985 'client_test': False,
1987 'EnableVertexAttribArray': {
1988 'decoder_func': 'DoEnableVertexAttribArray',
1989 'impl_decl': False,
1991 'FenceSync': {
1992 'type': 'Create',
1993 'client_test': False,
1994 'unsafe': True,
1996 'Finish': {
1997 'impl_func': False,
1998 'client_test': False,
1999 'decoder_func': 'DoFinish',
2000 'defer_reads': True,
2002 'Flush': {
2003 'impl_func': False,
2004 'decoder_func': 'DoFlush',
2006 'FramebufferRenderbuffer': {
2007 'decoder_func': 'DoFramebufferRenderbuffer',
2008 'gl_test_func': 'glFramebufferRenderbufferEXT',
2010 'FramebufferTexture2D': {
2011 'decoder_func': 'DoFramebufferTexture2D',
2012 'gl_test_func': 'glFramebufferTexture2DEXT',
2013 'trace_level': 1,
2015 'FramebufferTexture2DMultisampleEXT': {
2016 'decoder_func': 'DoFramebufferTexture2DMultisample',
2017 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2018 'expectation': False,
2019 'unit_test': False,
2020 'extension_flag': 'multisampled_render_to_texture',
2021 'trace_level': 1,
2023 'FramebufferTextureLayer': {
2024 'decoder_func': 'DoFramebufferTextureLayer',
2025 'unsafe': True,
2027 'GenerateMipmap': {
2028 'decoder_func': 'DoGenerateMipmap',
2029 'gl_test_func': 'glGenerateMipmapEXT',
2031 'GenBuffers': {
2032 'type': 'GENn',
2033 'gl_test_func': 'glGenBuffersARB',
2034 'resource_type': 'Buffer',
2035 'resource_types': 'Buffers',
2037 'GenMailboxCHROMIUM': {
2038 'type': 'HandWritten',
2039 'impl_func': False,
2040 'extension': "CHROMIUM_texture_mailbox",
2041 'chromium': True,
2043 'GenFramebuffers': {
2044 'type': 'GENn',
2045 'gl_test_func': 'glGenFramebuffersEXT',
2046 'resource_type': 'Framebuffer',
2047 'resource_types': 'Framebuffers',
2049 'GenRenderbuffers': {
2050 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2051 'resource_type': 'Renderbuffer',
2052 'resource_types': 'Renderbuffers',
2054 'GenSamplers': {
2055 'type': 'GENn',
2056 'gl_test_func': 'glGenSamplers',
2057 'resource_type': 'Sampler',
2058 'resource_types': 'Samplers',
2059 'unsafe': True,
2061 'GenTextures': {
2062 'type': 'GENn',
2063 'gl_test_func': 'glGenTextures',
2064 'resource_type': 'Texture',
2065 'resource_types': 'Textures',
2067 'GenTransformFeedbacks': {
2068 'type': 'GENn',
2069 'gl_test_func': 'glGenTransformFeedbacks',
2070 'resource_type': 'TransformFeedback',
2071 'resource_types': 'TransformFeedbacks',
2072 'unsafe': True,
2074 'GetActiveAttrib': {
2075 'type': 'Custom',
2076 'data_transfer_methods': ['shm'],
2077 'cmd_args':
2078 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2079 'void* result',
2080 'result': [
2081 'int32_t success',
2082 'int32_t size',
2083 'uint32_t type',
2086 'GetActiveUniform': {
2087 'type': 'Custom',
2088 'data_transfer_methods': ['shm'],
2089 'cmd_args':
2090 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2091 'void* result',
2092 'result': [
2093 'int32_t success',
2094 'int32_t size',
2095 'uint32_t type',
2098 'GetActiveUniformBlockiv': {
2099 'type': 'Custom',
2100 'data_transfer_methods': ['shm'],
2101 'result': ['SizedResult<GLint>'],
2102 'unsafe': True,
2104 'GetActiveUniformBlockName': {
2105 'type': 'Custom',
2106 'data_transfer_methods': ['shm'],
2107 'cmd_args':
2108 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2109 'void* result',
2110 'result': ['int32_t'],
2111 'unsafe': True,
2113 'GetActiveUniformsiv': {
2114 'type': 'Custom',
2115 'data_transfer_methods': ['shm'],
2116 'cmd_args':
2117 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2118 'GLint* params',
2119 'result': ['SizedResult<GLint>'],
2120 'unsafe': True,
2122 'GetAttachedShaders': {
2123 'type': 'Custom',
2124 'data_transfer_methods': ['shm'],
2125 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2126 'result': ['SizedResult<GLuint>'],
2128 'GetAttribLocation': {
2129 'type': 'Custom',
2130 'data_transfer_methods': ['shm'],
2131 'cmd_args':
2132 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2133 'result': ['GLint'],
2134 'error_return': -1,
2136 'GetFragDataLocation': {
2137 'type': 'Custom',
2138 'data_transfer_methods': ['shm'],
2139 'cmd_args':
2140 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2141 'result': ['GLint'],
2142 'error_return': -1,
2143 'unsafe': True,
2145 'GetBooleanv': {
2146 'type': 'GETn',
2147 'result': ['SizedResult<GLboolean>'],
2148 'decoder_func': 'DoGetBooleanv',
2149 'gl_test_func': 'glGetBooleanv',
2151 'GetBufferParameteriv': {
2152 'type': 'GETn',
2153 'result': ['SizedResult<GLint>'],
2154 'decoder_func': 'DoGetBufferParameteriv',
2155 'expectation': False,
2156 'shadowed': True,
2158 'GetError': {
2159 'type': 'Is',
2160 'decoder_func': 'GetErrorState()->GetGLError',
2161 'impl_func': False,
2162 'result': ['GLenum'],
2163 'client_test': False,
2165 'GetFloatv': {
2166 'type': 'GETn',
2167 'result': ['SizedResult<GLfloat>'],
2168 'decoder_func': 'DoGetFloatv',
2169 'gl_test_func': 'glGetFloatv',
2171 'GetFramebufferAttachmentParameteriv': {
2172 'type': 'GETn',
2173 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2174 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2175 'result': ['SizedResult<GLint>'],
2177 'GetIntegerv': {
2178 'type': 'GETn',
2179 'result': ['SizedResult<GLint>'],
2180 'decoder_func': 'DoGetIntegerv',
2181 'client_test': False,
2183 'GetInternalformativ': {
2184 'type': 'GETn',
2185 'result': ['SizedResult<GLint>'],
2186 'unsafe': True,
2188 'GetMaxValueInBufferCHROMIUM': {
2189 'type': 'Is',
2190 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2191 'result': ['GLuint'],
2192 'unit_test': False,
2193 'client_test': False,
2194 'extension': True,
2195 'chromium': True,
2196 'impl_func': False,
2198 'GetProgramiv': {
2199 'type': 'GETn',
2200 'decoder_func': 'DoGetProgramiv',
2201 'result': ['SizedResult<GLint>'],
2202 'expectation': False,
2204 'GetProgramInfoCHROMIUM': {
2205 'type': 'Custom',
2206 'expectation': False,
2207 'impl_func': False,
2208 'extension': True,
2209 'chromium': True,
2210 'client_test': False,
2211 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2212 'result': [
2213 'uint32_t link_status',
2214 'uint32_t num_attribs',
2215 'uint32_t num_uniforms',
2218 'GetProgramInfoLog': {
2219 'type': 'STRn',
2220 'expectation': False,
2222 'GetRenderbufferParameteriv': {
2223 'type': 'GETn',
2224 'decoder_func': 'DoGetRenderbufferParameteriv',
2225 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2226 'result': ['SizedResult<GLint>'],
2228 'GetSamplerParameterfv': {
2229 'type': 'GETn',
2230 'result': ['SizedResult<GLfloat>'],
2231 'id_mapping': [ 'Sampler' ],
2232 'unsafe': True,
2234 'GetSamplerParameteriv': {
2235 'type': 'GETn',
2236 'result': ['SizedResult<GLint>'],
2237 'id_mapping': [ 'Sampler' ],
2238 'unsafe': True,
2240 'GetShaderiv': {
2241 'type': 'GETn',
2242 'decoder_func': 'DoGetShaderiv',
2243 'result': ['SizedResult<GLint>'],
2245 'GetShaderInfoLog': {
2246 'type': 'STRn',
2247 'get_len_func': 'glGetShaderiv',
2248 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2249 'unit_test': False,
2251 'GetShaderPrecisionFormat': {
2252 'type': 'Custom',
2253 'data_transfer_methods': ['shm'],
2254 'cmd_args':
2255 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2256 'void* result',
2257 'result': [
2258 'int32_t success',
2259 'int32_t min_range',
2260 'int32_t max_range',
2261 'int32_t precision',
2264 'GetShaderSource': {
2265 'type': 'STRn',
2266 'get_len_func': 'DoGetShaderiv',
2267 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2268 'unit_test': False,
2269 'client_test': False,
2271 'GetString': {
2272 'type': 'Custom',
2273 'client_test': False,
2274 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2276 'GetSynciv': {
2277 'type': 'GETn',
2278 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2279 'result': ['SizedResult<GLint>'],
2280 'id_mapping': ['Sync'],
2281 'unsafe': True,
2283 'GetTexParameterfv': {
2284 'type': 'GETn',
2285 'decoder_func': 'DoGetTexParameterfv',
2286 'result': ['SizedResult<GLfloat>']
2288 'GetTexParameteriv': {
2289 'type': 'GETn',
2290 'decoder_func': 'DoGetTexParameteriv',
2291 'result': ['SizedResult<GLint>']
2293 'GetTranslatedShaderSourceANGLE': {
2294 'type': 'STRn',
2295 'get_len_func': 'DoGetShaderiv',
2296 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2297 'unit_test': False,
2298 'extension': True,
2300 'GetUniformBlockIndex': {
2301 'type': 'Custom',
2302 'data_transfer_methods': ['shm'],
2303 'cmd_args':
2304 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2305 'result': ['GLuint'],
2306 'error_return': 'GL_INVALID_INDEX',
2307 'unsafe': True,
2309 'GetUniformBlocksCHROMIUM': {
2310 'type': 'Custom',
2311 'expectation': False,
2312 'impl_func': False,
2313 'extension': True,
2314 'chromium': True,
2315 'client_test': False,
2316 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2317 'result': ['uint32_t'],
2318 'unsafe': True,
2320 'GetUniformsES3CHROMIUM': {
2321 'type': 'Custom',
2322 'expectation': False,
2323 'impl_func': False,
2324 'extension': True,
2325 'chromium': True,
2326 'client_test': False,
2327 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2328 'result': ['uint32_t'],
2329 'unsafe': True,
2331 'GetTransformFeedbackVarying': {
2332 'type': 'Custom',
2333 'data_transfer_methods': ['shm'],
2334 'cmd_args':
2335 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2336 'void* result',
2337 'result': [
2338 'int32_t success',
2339 'int32_t size',
2340 'uint32_t type',
2342 'unsafe': True,
2344 'GetTransformFeedbackVaryingsCHROMIUM': {
2345 'type': 'Custom',
2346 'expectation': False,
2347 'impl_func': False,
2348 'extension': True,
2349 'chromium': True,
2350 'client_test': False,
2351 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2352 'result': ['uint32_t'],
2353 'unsafe': True,
2355 'GetUniformfv': {
2356 'type': 'Custom',
2357 'data_transfer_methods': ['shm'],
2358 'result': ['SizedResult<GLfloat>'],
2360 'GetUniformiv': {
2361 'type': 'Custom',
2362 'data_transfer_methods': ['shm'],
2363 'result': ['SizedResult<GLint>'],
2365 'GetUniformIndices': {
2366 'type': 'Custom',
2367 'data_transfer_methods': ['shm'],
2368 'result': ['SizedResult<GLuint>'],
2369 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
2370 'GLuint* indices',
2371 'unsafe': True,
2373 'GetUniformLocation': {
2374 'type': 'Custom',
2375 'data_transfer_methods': ['shm'],
2376 'cmd_args':
2377 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2378 'result': ['GLint'],
2379 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
2381 'GetVertexAttribfv': {
2382 'type': 'GETn',
2383 'result': ['SizedResult<GLfloat>'],
2384 'impl_decl': False,
2385 'decoder_func': 'DoGetVertexAttribfv',
2386 'expectation': False,
2387 'client_test': False,
2389 'GetVertexAttribiv': {
2390 'type': 'GETn',
2391 'result': ['SizedResult<GLint>'],
2392 'impl_decl': False,
2393 'decoder_func': 'DoGetVertexAttribiv',
2394 'expectation': False,
2395 'client_test': False,
2397 'GetVertexAttribPointerv': {
2398 'type': 'Custom',
2399 'data_transfer_methods': ['shm'],
2400 'result': ['SizedResult<GLuint>'],
2401 'client_test': False,
2403 'InvalidateFramebuffer': {
2404 'type': 'PUTn',
2405 'count': 1,
2406 'client_test': False,
2407 'unit_test': False,
2408 'unsafe': True,
2410 'InvalidateSubFramebuffer': {
2411 'type': 'PUTn',
2412 'count': 1,
2413 'client_test': False,
2414 'unit_test': False,
2415 'unsafe': True,
2417 'IsBuffer': {
2418 'type': 'Is',
2419 'decoder_func': 'DoIsBuffer',
2420 'expectation': False,
2422 'IsEnabled': {
2423 'type': 'Is',
2424 'decoder_func': 'DoIsEnabled',
2425 'client_test': False,
2426 'impl_func': False,
2427 'expectation': False,
2429 'IsFramebuffer': {
2430 'type': 'Is',
2431 'decoder_func': 'DoIsFramebuffer',
2432 'expectation': False,
2434 'IsProgram': {
2435 'type': 'Is',
2436 'decoder_func': 'DoIsProgram',
2437 'expectation': False,
2439 'IsRenderbuffer': {
2440 'type': 'Is',
2441 'decoder_func': 'DoIsRenderbuffer',
2442 'expectation': False,
2444 'IsShader': {
2445 'type': 'Is',
2446 'decoder_func': 'DoIsShader',
2447 'expectation': False,
2449 'IsSampler': {
2450 'type': 'Is',
2451 'id_mapping': [ 'Sampler' ],
2452 'expectation': False,
2453 'unsafe': True,
2455 'IsSync': {
2456 'type': 'Is',
2457 'id_mapping': [ 'Sync' ],
2458 'cmd_args': 'GLuint sync',
2459 'expectation': False,
2460 'unsafe': True,
2462 'IsTexture': {
2463 'type': 'Is',
2464 'decoder_func': 'DoIsTexture',
2465 'expectation': False,
2467 'IsTransformFeedback': {
2468 'type': 'Is',
2469 'id_mapping': [ 'TransformFeedback' ],
2470 'expectation': False,
2471 'unsafe': True,
2473 'LinkProgram': {
2474 'decoder_func': 'DoLinkProgram',
2475 'impl_func': False,
2477 'MapBufferCHROMIUM': {
2478 'gen_cmd': False,
2479 'extension': True,
2480 'chromium': True,
2481 'client_test': False,
2483 'MapBufferSubDataCHROMIUM': {
2484 'gen_cmd': False,
2485 'extension': True,
2486 'chromium': True,
2487 'client_test': False,
2488 'pepper_interface': 'ChromiumMapSub',
2490 'MapTexSubImage2DCHROMIUM': {
2491 'gen_cmd': False,
2492 'extension': True,
2493 'chromium': True,
2494 'client_test': False,
2495 'pepper_interface': 'ChromiumMapSub',
2497 'PauseTransformFeedback': {
2498 'unsafe': True,
2500 'PixelStorei': {'type': 'Manual'},
2501 'PostSubBufferCHROMIUM': {
2502 'type': 'Custom',
2503 'impl_func': False,
2504 'unit_test': False,
2505 'client_test': False,
2506 'extension': True,
2507 'chromium': True,
2509 'ProduceTextureCHROMIUM': {
2510 'decoder_func': 'DoProduceTextureCHROMIUM',
2511 'impl_func': False,
2512 'type': 'PUT',
2513 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2514 'unit_test': False,
2515 'client_test': False,
2516 'extension': "CHROMIUM_texture_mailbox",
2517 'chromium': True,
2518 'trace_level': 1,
2520 'ProduceTextureDirectCHROMIUM': {
2521 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
2522 'impl_func': False,
2523 'type': 'PUT',
2524 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2525 'unit_test': False,
2526 'client_test': False,
2527 'extension': "CHROMIUM_texture_mailbox",
2528 'chromium': True,
2529 'trace_level': 1,
2531 'RenderbufferStorage': {
2532 'decoder_func': 'DoRenderbufferStorage',
2533 'gl_test_func': 'glRenderbufferStorageEXT',
2534 'expectation': False,
2536 'RenderbufferStorageMultisampleCHROMIUM': {
2537 'cmd_comment':
2538 '// GL_CHROMIUM_framebuffer_multisample\n',
2539 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
2540 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
2541 'expectation': False,
2542 'unit_test': False,
2543 'extension_flag': 'chromium_framebuffer_multisample',
2544 'pepper_interface': 'FramebufferMultisample',
2545 'pepper_name': 'RenderbufferStorageMultisampleEXT',
2547 'RenderbufferStorageMultisampleEXT': {
2548 'cmd_comment':
2549 '// GL_EXT_multisampled_render_to_texture\n',
2550 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
2551 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
2552 'expectation': False,
2553 'unit_test': False,
2554 'extension_flag': 'multisampled_render_to_texture',
2556 'ReadBuffer': {
2557 'unsafe': True,
2559 'ReadPixels': {
2560 'cmd_comment':
2561 '// ReadPixels has the result separated from the pixel buffer so that\n'
2562 '// it is easier to specify the result going to some specific place\n'
2563 '// that exactly fits the rectangle of pixels.\n',
2564 'type': 'Custom',
2565 'data_transfer_methods': ['shm'],
2566 'impl_func': False,
2567 'client_test': False,
2568 'cmd_args':
2569 'GLint x, GLint y, GLsizei width, GLsizei height, '
2570 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
2571 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
2572 'uint32_t result_shm_id, uint32_t result_shm_offset, '
2573 'GLboolean async',
2574 'result': ['uint32_t'],
2575 'defer_reads': True,
2577 'ReleaseShaderCompiler': {
2578 'decoder_func': 'DoReleaseShaderCompiler',
2579 'unit_test': False,
2581 'ResumeTransformFeedback': {
2582 'unsafe': True,
2584 'SamplerParameterf': {
2585 'valid_args': {
2586 '2': 'GL_NEAREST'
2588 'id_mapping': [ 'Sampler' ],
2589 'unsafe': True,
2591 'SamplerParameterfv': {
2592 'type': 'PUT',
2593 'data_value': 'GL_NEAREST',
2594 'count': 1,
2595 'gl_test_func': 'glSamplerParameterf',
2596 'decoder_func': 'DoSamplerParameterfv',
2597 'first_element_only': True,
2598 'id_mapping': [ 'Sampler' ],
2599 'unsafe': True,
2601 'SamplerParameteri': {
2602 'valid_args': {
2603 '2': 'GL_NEAREST'
2605 'id_mapping': [ 'Sampler' ],
2606 'unsafe': True,
2608 'SamplerParameteriv': {
2609 'type': 'PUT',
2610 'data_value': 'GL_NEAREST',
2611 'count': 1,
2612 'gl_test_func': 'glSamplerParameteri',
2613 'decoder_func': 'DoSamplerParameteriv',
2614 'first_element_only': True,
2615 'unsafe': True,
2617 'ShaderBinary': {
2618 'type': 'Custom',
2619 'client_test': False,
2621 'ShaderSource': {
2622 'type': 'PUTSTR',
2623 'decoder_func': 'DoShaderSource',
2624 'expectation': False,
2625 'data_transfer_methods': ['bucket'],
2626 'cmd_args':
2627 'GLuint shader, const char** str',
2628 'pepper_args':
2629 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2631 'StencilMask': {
2632 'type': 'StateSetFrontBack',
2633 'state': 'StencilMask',
2634 'no_gl': True,
2635 'expectation': False,
2637 'StencilMaskSeparate': {
2638 'type': 'StateSetFrontBackSeparate',
2639 'state': 'StencilMask',
2640 'no_gl': True,
2641 'expectation': False,
2643 'SwapBuffers': {
2644 'impl_func': False,
2645 'decoder_func': 'DoSwapBuffers',
2646 'unit_test': False,
2647 'client_test': False,
2648 'extension': True,
2649 'trace_level': 1,
2651 'SwapInterval': {
2652 'impl_func': False,
2653 'decoder_func': 'DoSwapInterval',
2654 'unit_test': False,
2655 'client_test': False,
2656 'extension': True,
2657 'trace_level': 1,
2659 'TexImage2D': {
2660 'type': 'Manual',
2661 'data_transfer_methods': ['shm'],
2662 'client_test': False,
2664 'TexImage3D': {
2665 'type': 'Manual',
2666 'data_transfer_methods': ['shm'],
2667 'client_test': False,
2668 'unsafe': True,
2670 'TexParameterf': {
2671 'decoder_func': 'DoTexParameterf',
2672 'valid_args': {
2673 '2': 'GL_NEAREST'
2676 'TexParameteri': {
2677 'decoder_func': 'DoTexParameteri',
2678 'valid_args': {
2679 '2': 'GL_NEAREST'
2682 'TexParameterfv': {
2683 'type': 'PUT',
2684 'data_value': 'GL_NEAREST',
2685 'count': 1,
2686 'decoder_func': 'DoTexParameterfv',
2687 'gl_test_func': 'glTexParameterf',
2688 'first_element_only': True,
2690 'TexParameteriv': {
2691 'type': 'PUT',
2692 'data_value': 'GL_NEAREST',
2693 'count': 1,
2694 'decoder_func': 'DoTexParameteriv',
2695 'gl_test_func': 'glTexParameteri',
2696 'first_element_only': True,
2698 'TexStorage3D': {
2699 'unsafe': True,
2701 'TexSubImage2D': {
2702 'type': 'Manual',
2703 'data_transfer_methods': ['shm'],
2704 'client_test': False,
2705 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2706 'GLint xoffset, GLint yoffset, '
2707 'GLsizei width, GLsizei height, '
2708 'GLenumTextureFormat format, GLenumPixelType type, '
2709 'const void* pixels, GLboolean internal'
2711 'TexSubImage3D': {
2712 'type': 'Manual',
2713 'data_transfer_methods': ['shm'],
2714 'client_test': False,
2715 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2716 'GLint xoffset, GLint yoffset, GLint zoffset, '
2717 'GLsizei width, GLsizei height, GLsizei depth, '
2718 'GLenumTextureFormat format, GLenumPixelType type, '
2719 'const void* pixels, GLboolean internal',
2720 'unsafe': True,
2722 'TransformFeedbackVaryings': {
2723 'type': 'PUTSTR',
2724 'data_transfer_methods': ['bucket'],
2725 'decoder_func': 'DoTransformFeedbackVaryings',
2726 'cmd_args':
2727 'GLuint program, const char** varyings, GLenum buffermode',
2728 'unsafe': True,
2730 'Uniform1f': {'type': 'PUTXn', 'count': 1},
2731 'Uniform1fv': {
2732 'type': 'PUTn',
2733 'count': 1,
2734 'decoder_func': 'DoUniform1fv',
2736 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2737 'Uniform1iv': {
2738 'type': 'PUTn',
2739 'count': 1,
2740 'decoder_func': 'DoUniform1iv',
2741 'unit_test': False,
2743 'Uniform1ui': {
2744 'type': 'PUTXn',
2745 'count': 1,
2746 'unsafe': True,
2748 'Uniform1uiv': {
2749 'type': 'PUTn',
2750 'count': 1,
2751 'unsafe': True,
2753 'Uniform2i': {'type': 'PUTXn', 'count': 2},
2754 'Uniform2f': {'type': 'PUTXn', 'count': 2},
2755 'Uniform2fv': {
2756 'type': 'PUTn',
2757 'count': 2,
2758 'decoder_func': 'DoUniform2fv',
2760 'Uniform2iv': {
2761 'type': 'PUTn',
2762 'count': 2,
2763 'decoder_func': 'DoUniform2iv',
2765 'Uniform2ui': {
2766 'type': 'PUTXn',
2767 'count': 2,
2768 'unsafe': True,
2770 'Uniform2uiv': {
2771 'type': 'PUTn',
2772 'count': 2,
2773 'unsafe': True,
2775 'Uniform3i': {'type': 'PUTXn', 'count': 3},
2776 'Uniform3f': {'type': 'PUTXn', 'count': 3},
2777 'Uniform3fv': {
2778 'type': 'PUTn',
2779 'count': 3,
2780 'decoder_func': 'DoUniform3fv',
2782 'Uniform3iv': {
2783 'type': 'PUTn',
2784 'count': 3,
2785 'decoder_func': 'DoUniform3iv',
2787 'Uniform3ui': {
2788 'type': 'PUTXn',
2789 'count': 3,
2790 'unsafe': True,
2792 'Uniform3uiv': {
2793 'type': 'PUTn',
2794 'count': 3,
2795 'unsafe': True,
2797 'Uniform4i': {'type': 'PUTXn', 'count': 4},
2798 'Uniform4f': {'type': 'PUTXn', 'count': 4},
2799 'Uniform4fv': {
2800 'type': 'PUTn',
2801 'count': 4,
2802 'decoder_func': 'DoUniform4fv',
2804 'Uniform4iv': {
2805 'type': 'PUTn',
2806 'count': 4,
2807 'decoder_func': 'DoUniform4iv',
2809 'Uniform4ui': {
2810 'type': 'PUTXn',
2811 'count': 4,
2812 'unsafe': True,
2814 'Uniform4uiv': {
2815 'type': 'PUTn',
2816 'count': 4,
2817 'unsafe': True,
2819 'UniformMatrix2fv': {
2820 'type': 'PUTn',
2821 'count': 4,
2822 'decoder_func': 'DoUniformMatrix2fv',
2824 'UniformMatrix2x3fv': {
2825 'type': 'PUTn',
2826 'count': 6,
2827 'unsafe': True,
2829 'UniformMatrix2x4fv': {
2830 'type': 'PUTn',
2831 'count': 8,
2832 'unsafe': True,
2834 'UniformMatrix3fv': {
2835 'type': 'PUTn',
2836 'count': 9,
2837 'decoder_func': 'DoUniformMatrix3fv',
2839 'UniformMatrix3x2fv': {
2840 'type': 'PUTn',
2841 'count': 6,
2842 'unsafe': True,
2844 'UniformMatrix3x4fv': {
2845 'type': 'PUTn',
2846 'count': 12,
2847 'unsafe': True,
2849 'UniformMatrix4fv': {
2850 'type': 'PUTn',
2851 'count': 16,
2852 'decoder_func': 'DoUniformMatrix4fv',
2854 'UniformMatrix4x2fv': {
2855 'type': 'PUTn',
2856 'count': 8,
2857 'unsafe': True,
2859 'UniformMatrix4x3fv': {
2860 'type': 'PUTn',
2861 'count': 12,
2862 'unsafe': True,
2864 'UniformBlockBinding': {
2865 'type': 'Custom',
2866 'impl_func': False,
2867 'unsafe': True,
2869 'UnmapBufferCHROMIUM': {
2870 'gen_cmd': False,
2871 'extension': True,
2872 'chromium': True,
2873 'client_test': False,
2875 'UnmapBufferSubDataCHROMIUM': {
2876 'gen_cmd': False,
2877 'extension': True,
2878 'chromium': True,
2879 'client_test': False,
2880 'pepper_interface': 'ChromiumMapSub',
2882 'UnmapTexSubImage2DCHROMIUM': {
2883 'gen_cmd': False,
2884 'extension': True,
2885 'chromium': True,
2886 'client_test': False,
2887 'pepper_interface': 'ChromiumMapSub',
2889 'UseProgram': {
2890 'type': 'Bind',
2891 'decoder_func': 'DoUseProgram',
2893 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2894 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2895 'VertexAttrib1fv': {
2896 'type': 'PUT',
2897 'count': 1,
2898 'decoder_func': 'DoVertexAttrib1fv',
2900 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2901 'VertexAttrib2fv': {
2902 'type': 'PUT',
2903 'count': 2,
2904 'decoder_func': 'DoVertexAttrib2fv',
2906 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2907 'VertexAttrib3fv': {
2908 'type': 'PUT',
2909 'count': 3,
2910 'decoder_func': 'DoVertexAttrib3fv',
2912 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2913 'VertexAttrib4fv': {
2914 'type': 'PUT',
2915 'count': 4,
2916 'decoder_func': 'DoVertexAttrib4fv',
2918 'VertexAttribI4i': {
2919 'unsafe': True,
2921 'VertexAttribI4iv': {
2922 'type': 'PUT',
2923 'count': 4,
2924 'unsafe': True,
2926 'VertexAttribI4ui': {
2927 'unsafe': True,
2929 'VertexAttribI4uiv': {
2930 'type': 'PUT',
2931 'count': 4,
2932 'unsafe': True,
2934 'VertexAttribIPointer': {
2935 'type': 'Manual',
2936 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2937 'GLenumVertexAttribType type, GLsizei stride, '
2938 'GLuint offset',
2939 'client_test': False,
2940 'unsafe': True,
2942 'VertexAttribPointer': {
2943 'type': 'Manual',
2944 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2945 'GLenumVertexAttribType type, GLboolean normalized, '
2946 'GLsizei stride, GLuint offset',
2947 'client_test': False,
2949 'WaitSync': {
2950 'type': 'Custom',
2951 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2952 'GLuint timeout_0, GLuint timeout_1',
2953 'impl_func': False,
2954 'client_test': False,
2955 'unsafe': True,
2957 'Scissor': {
2958 'type': 'StateSet',
2959 'state': 'Scissor',
2961 'Viewport': {
2962 'decoder_func': 'DoViewport',
2964 'ResizeCHROMIUM': {
2965 'type': 'Custom',
2966 'impl_func': False,
2967 'unit_test': False,
2968 'extension': True,
2969 'chromium': True,
2971 'GetRequestableExtensionsCHROMIUM': {
2972 'type': 'Custom',
2973 'impl_func': False,
2974 'cmd_args': 'uint32_t bucket_id',
2975 'extension': True,
2976 'chromium': True,
2978 'RequestExtensionCHROMIUM': {
2979 'type': 'Custom',
2980 'impl_func': False,
2981 'client_test': False,
2982 'cmd_args': 'uint32_t bucket_id',
2983 'extension': True,
2984 'chromium': True,
2986 'RateLimitOffscreenContextCHROMIUM': {
2987 'gen_cmd': False,
2988 'extension': True,
2989 'chromium': True,
2990 'client_test': False,
2992 'CreateStreamTextureCHROMIUM': {
2993 'type': 'HandWritten',
2994 'impl_func': False,
2995 'gen_cmd': False,
2996 'extension': True,
2997 'chromium': True,
2999 'TexImageIOSurface2DCHROMIUM': {
3000 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3001 'unit_test': False,
3002 'extension': True,
3003 'chromium': True,
3005 'CopyTextureCHROMIUM': {
3006 'decoder_func': 'DoCopyTextureCHROMIUM',
3007 'unit_test': False,
3008 'extension': True,
3009 'chromium': True,
3011 'TexStorage2DEXT': {
3012 'unit_test': False,
3013 'extension': True,
3014 'decoder_func': 'DoTexStorage2DEXT',
3016 'DrawArraysInstancedANGLE': {
3017 'type': 'Manual',
3018 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3019 'GLsizei primcount',
3020 'extension': True,
3021 'unit_test': False,
3022 'pepper_interface': 'InstancedArrays',
3023 'defer_draws': True,
3025 'DrawBuffersEXT': {
3026 'type': 'PUTn',
3027 'decoder_func': 'DoDrawBuffersEXT',
3028 'count': 1,
3029 'client_test': False,
3030 'unit_test': False,
3031 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3032 # work without.
3033 'extension': True,
3034 'pepper_interface': 'DrawBuffers',
3036 'DrawElementsInstancedANGLE': {
3037 'type': 'Manual',
3038 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3039 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3040 'extension': True,
3041 'unit_test': False,
3042 'client_test': False,
3043 'pepper_interface': 'InstancedArrays',
3044 'defer_draws': True,
3046 'VertexAttribDivisorANGLE': {
3047 'type': 'Manual',
3048 'cmd_args': 'GLuint index, GLuint divisor',
3049 'extension': True,
3050 'unit_test': False,
3051 'pepper_interface': 'InstancedArrays',
3053 'GenQueriesEXT': {
3054 'type': 'GENn',
3055 'gl_test_func': 'glGenQueriesARB',
3056 'resource_type': 'Query',
3057 'resource_types': 'Queries',
3058 'unit_test': False,
3059 'pepper_interface': 'Query',
3060 'not_shared': 'True',
3062 'DeleteQueriesEXT': {
3063 'type': 'DELn',
3064 'gl_test_func': 'glDeleteQueriesARB',
3065 'resource_type': 'Query',
3066 'resource_types': 'Queries',
3067 'unit_test': False,
3068 'pepper_interface': 'Query',
3070 'IsQueryEXT': {
3071 'gen_cmd': False,
3072 'client_test': False,
3073 'pepper_interface': 'Query',
3075 'BeginQueryEXT': {
3076 'type': 'Manual',
3077 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3078 'data_transfer_methods': ['shm'],
3079 'gl_test_func': 'glBeginQuery',
3080 'pepper_interface': 'Query',
3082 'BeginTransformFeedback': {
3083 'unsafe': True,
3085 'EndQueryEXT': {
3086 'type': 'Manual',
3087 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3088 'gl_test_func': 'glEndnQuery',
3089 'client_test': False,
3090 'pepper_interface': 'Query',
3092 'EndTransformFeedback': {
3093 'unsafe': True,
3095 'GetQueryivEXT': {
3096 'gen_cmd': False,
3097 'client_test': False,
3098 'gl_test_func': 'glGetQueryiv',
3099 'pepper_interface': 'Query',
3101 'GetQueryObjectuivEXT': {
3102 'gen_cmd': False,
3103 'client_test': False,
3104 'gl_test_func': 'glGetQueryObjectuiv',
3105 'pepper_interface': 'Query',
3107 'BindUniformLocationCHROMIUM': {
3108 'type': 'GLchar',
3109 'extension': True,
3110 'data_transfer_methods': ['bucket'],
3111 'needs_size': True,
3112 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3114 'InsertEventMarkerEXT': {
3115 'type': 'GLcharN',
3116 'decoder_func': 'DoInsertEventMarkerEXT',
3117 'expectation': False,
3118 'extension': True,
3120 'PushGroupMarkerEXT': {
3121 'type': 'GLcharN',
3122 'decoder_func': 'DoPushGroupMarkerEXT',
3123 'expectation': False,
3124 'extension': True,
3126 'PopGroupMarkerEXT': {
3127 'decoder_func': 'DoPopGroupMarkerEXT',
3128 'expectation': False,
3129 'extension': True,
3130 'impl_func': False,
3133 'GenVertexArraysOES': {
3134 'type': 'GENn',
3135 'extension': True,
3136 'gl_test_func': 'glGenVertexArraysOES',
3137 'resource_type': 'VertexArray',
3138 'resource_types': 'VertexArrays',
3139 'unit_test': False,
3140 'pepper_interface': 'VertexArrayObject',
3142 'BindVertexArrayOES': {
3143 'type': 'Bind',
3144 'extension': True,
3145 'gl_test_func': 'glBindVertexArrayOES',
3146 'decoder_func': 'DoBindVertexArrayOES',
3147 'gen_func': 'GenVertexArraysOES',
3148 'unit_test': False,
3149 'client_test': False,
3150 'pepper_interface': 'VertexArrayObject',
3152 'DeleteVertexArraysOES': {
3153 'type': 'DELn',
3154 'extension': True,
3155 'gl_test_func': 'glDeleteVertexArraysOES',
3156 'resource_type': 'VertexArray',
3157 'resource_types': 'VertexArrays',
3158 'unit_test': False,
3159 'pepper_interface': 'VertexArrayObject',
3161 'IsVertexArrayOES': {
3162 'type': 'Is',
3163 'extension': True,
3164 'gl_test_func': 'glIsVertexArrayOES',
3165 'decoder_func': 'DoIsVertexArrayOES',
3166 'expectation': False,
3167 'unit_test': False,
3168 'pepper_interface': 'VertexArrayObject',
3170 'BindTexImage2DCHROMIUM': {
3171 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3172 'unit_test': False,
3173 'extension': True,
3174 'chromium': True,
3176 'ReleaseTexImage2DCHROMIUM': {
3177 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3178 'unit_test': False,
3179 'extension': True,
3180 'chromium': True,
3182 'ShallowFinishCHROMIUM': {
3183 'impl_func': False,
3184 'gen_cmd': False,
3185 'extension': True,
3186 'chromium': True,
3187 'client_test': False,
3189 'ShallowFlushCHROMIUM': {
3190 'impl_func': False,
3191 'gen_cmd': False,
3192 'extension': True,
3193 'chromium': True,
3194 'client_test': False,
3196 'OrderingBarrierCHROMIUM': {
3197 'impl_func': False,
3198 'gen_cmd': False,
3199 'extension': True,
3200 'chromium': True,
3201 'client_test': False,
3203 'TraceBeginCHROMIUM': {
3204 'type': 'Custom',
3205 'impl_func': False,
3206 'client_test': False,
3207 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3208 'extension': True,
3209 'chromium': True,
3211 'TraceEndCHROMIUM': {
3212 'impl_func': False,
3213 'client_test': False,
3214 'decoder_func': 'DoTraceEndCHROMIUM',
3215 'unit_test': False,
3216 'extension': True,
3217 'chromium': True,
3219 'AsyncTexImage2DCHROMIUM': {
3220 'type': 'Manual',
3221 'data_transfer_methods': ['shm'],
3222 'client_test': False,
3223 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3224 'GLintTextureInternalFormat internalformat, '
3225 'GLsizei width, GLsizei height, '
3226 'GLintTextureBorder border, '
3227 'GLenumTextureFormat format, GLenumPixelType type, '
3228 'const void* pixels, '
3229 'uint32_t async_upload_token, '
3230 'void* sync_data',
3231 'extension': True,
3232 'chromium': True,
3234 'AsyncTexSubImage2DCHROMIUM': {
3235 'type': 'Manual',
3236 'data_transfer_methods': ['shm'],
3237 'client_test': False,
3238 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3239 'GLint xoffset, GLint yoffset, '
3240 'GLsizei width, GLsizei height, '
3241 'GLenumTextureFormat format, GLenumPixelType type, '
3242 'const void* data, '
3243 'uint32_t async_upload_token, '
3244 'void* sync_data',
3245 'extension': True,
3246 'chromium': True,
3248 'WaitAsyncTexImage2DCHROMIUM': {
3249 'type': 'Manual',
3250 'client_test': False,
3251 'extension': True,
3252 'chromium': True,
3254 'WaitAllAsyncTexImage2DCHROMIUM': {
3255 'type': 'Manual',
3256 'client_test': False,
3257 'extension': True,
3258 'chromium': True,
3260 'DiscardFramebufferEXT': {
3261 'type': 'PUTn',
3262 'count': 1,
3263 'decoder_func': 'DoDiscardFramebufferEXT',
3264 'unit_test': False,
3265 'client_test': False,
3266 'extension_flag': 'ext_discard_framebuffer',
3268 'LoseContextCHROMIUM': {
3269 'decoder_func': 'DoLoseContextCHROMIUM',
3270 'unit_test': False,
3271 'extension': True,
3272 'chromium': True,
3274 'InsertSyncPointCHROMIUM': {
3275 'type': 'HandWritten',
3276 'impl_func': False,
3277 'extension': "CHROMIUM_sync_point",
3278 'chromium': True,
3280 'WaitSyncPointCHROMIUM': {
3281 'type': 'Custom',
3282 'impl_func': True,
3283 'extension': "CHROMIUM_sync_point",
3284 'chromium': True,
3285 'trace_level': 1,
3287 'DiscardBackbufferCHROMIUM': {
3288 'type': 'Custom',
3289 'impl_func': True,
3290 'extension': True,
3291 'chromium': True,
3293 'ScheduleOverlayPlaneCHROMIUM': {
3294 'type': 'Custom',
3295 'impl_func': True,
3296 'unit_test': False,
3297 'client_test': False,
3298 'extension': True,
3299 'chromium': True,
3301 'MatrixLoadfCHROMIUM': {
3302 'type': 'PUT',
3303 'count': 16,
3304 'data_type': 'GLfloat',
3305 'decoder_func': 'DoMatrixLoadfCHROMIUM',
3306 'gl_test_func': 'glMatrixLoadfEXT',
3307 'chromium': True,
3308 'extension': True,
3309 'extension_flag': 'chromium_path_rendering',
3311 'MatrixLoadIdentityCHROMIUM': {
3312 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
3313 'gl_test_func': 'glMatrixLoadIdentityEXT',
3314 'chromium': True,
3315 'extension': True,
3316 'extension_flag': 'chromium_path_rendering',
3321 def Grouper(n, iterable, fillvalue=None):
3322 """Collect data into fixed-length chunks or blocks"""
3323 args = [iter(iterable)] * n
3324 return itertools.izip_longest(fillvalue=fillvalue, *args)
3327 def SplitWords(input_string):
3328 """Transforms a input_string into a list of lower-case components.
3330 Args:
3331 input_string: the input string.
3333 Returns:
3334 a list of lower-case words.
3336 if input_string.find('_') > -1:
3337 # 'some_TEXT_' -> 'some text'
3338 return input_string.replace('_', ' ').strip().lower().split()
3339 else:
3340 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
3341 # mixed case.
3342 # look for capitalization to cut input_strings
3343 # 'SomeText' -> 'Some Text'
3344 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
3345 # 'Vector3' -> 'Vector 3'
3346 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
3347 return input_string.lower().split()
3350 def Lower(words):
3351 """Makes a lower-case identifier from words.
3353 Args:
3354 words: a list of lower-case words.
3356 Returns:
3357 the lower-case identifier.
3359 return '_'.join(words)
3362 def ToUnderscore(input_string):
3363 """converts CamelCase to camel_case."""
3364 words = SplitWords(input_string)
3365 return Lower(words)
3367 def CachedStateName(item):
3368 if item.get('cached', False):
3369 return 'cached_' + item['name']
3370 return item['name']
3372 def ToGLExtensionString(extension_flag):
3373 """Returns GL-type extension string of a extension flag."""
3374 if extension_flag == "oes_compressed_etc1_rgb8_texture":
3375 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
3376 # unfortunate.
3377 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
3378 'egl', 'atc', 'etc1', 'angle']
3379 parts = extension_flag.split('_')
3380 return "_".join(
3381 [part.upper() if part in uppercase_words else part for part in parts])
3383 def ToCamelCase(input_string):
3384 """converts ABC_underscore_case to ABCUnderscoreCase."""
3385 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
3387 def GetGLGetTypeConversion(result_type, value_type, value):
3388 """Makes a gl compatible type conversion string for accessing state variables.
3390 Useful when accessing state variables through glGetXXX calls.
3391 glGet documetation (for example, the manual pages):
3392 [...] If glGetIntegerv is called, [...] most floating-point values are
3393 rounded to the nearest integer value. [...]
3395 Args:
3396 result_type: the gl type to be obtained
3397 value_type: the GL type of the state variable
3398 value: the name of the state variable
3400 Returns:
3401 String that converts the state variable to desired GL type according to GL
3402 rules.
3405 if result_type == 'GLint':
3406 if value_type == 'GLfloat':
3407 return 'static_cast<GLint>(round(%s))' % value
3408 return 'static_cast<%s>(%s)' % (result_type, value)
3410 class CWriter(object):
3411 """Writes to a file formatting it for Google's style guidelines."""
3413 def __init__(self, filename):
3414 self.filename = filename
3415 self.content = []
3417 def Write(self, string):
3418 """Writes a string to a file spliting if it's > 80 characters."""
3419 lines = string.splitlines()
3420 num_lines = len(lines)
3421 for ii in range(0, num_lines):
3422 self.content.append(lines[ii])
3423 if ii < (num_lines - 1) or string[-1] == '\n':
3424 self.content.append('\n')
3426 def Close(self):
3427 """Close the file."""
3428 content = "".join(self.content)
3429 write_file = True
3430 if os.path.exists(self.filename):
3431 old_file = open(self.filename, "rb");
3432 old_content = old_file.read()
3433 old_file.close();
3434 if content == old_content:
3435 write_file = False
3436 if write_file:
3437 file = open(self.filename, "wb")
3438 file.write(content)
3439 file.close()
3442 class CHeaderWriter(CWriter):
3443 """Writes a C Header file."""
3445 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
3447 def __init__(self, filename, file_comment = None):
3448 CWriter.__init__(self, filename)
3450 base = os.path.abspath(filename)
3451 while os.path.basename(base) != 'src':
3452 new_base = os.path.dirname(base)
3453 assert new_base != base # Prevent infinite loop.
3454 base = new_base
3456 hpath = os.path.relpath(filename, base)
3457 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
3459 self.Write(_LICENSE)
3460 self.Write(_DO_NOT_EDIT_WARNING)
3461 if not file_comment == None:
3462 self.Write(file_comment)
3463 self.Write("#ifndef %s\n" % self.guard)
3464 self.Write("#define %s\n\n" % self.guard)
3466 def Close(self):
3467 self.Write("#endif // %s\n\n" % self.guard)
3468 CWriter.Close(self)
3470 class TypeHandler(object):
3471 """This class emits code for a particular type of function."""
3473 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
3475 def __init__(self):
3476 pass
3478 def InitFunction(self, func):
3479 """Add or adjust anything type specific for this function."""
3480 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
3481 func.AddCmdArg(DataSizeArgument('data_size'))
3483 def NeedsDataTransferFunction(self, func):
3484 """Overriden from TypeHandler."""
3485 return func.num_pointer_args >= 1
3487 def WriteStruct(self, func, file):
3488 """Writes a structure that matches the arguments to a function."""
3489 comment = func.GetInfo('cmd_comment')
3490 if not comment == None:
3491 file.Write(comment)
3492 file.Write("struct %s {\n" % func.name)
3493 file.Write(" typedef %s ValueType;\n" % func.name)
3494 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
3495 func.WriteCmdArgFlag(file)
3496 func.WriteCmdFlag(file)
3497 file.Write("\n")
3498 result = func.GetInfo('result')
3499 if not result == None:
3500 if len(result) == 1:
3501 file.Write(" typedef %s Result;\n\n" % result[0])
3502 else:
3503 file.Write(" struct Result {\n")
3504 for line in result:
3505 file.Write(" %s;\n" % line)
3506 file.Write(" };\n\n")
3508 func.WriteCmdComputeSize(file)
3509 func.WriteCmdSetHeader(file)
3510 func.WriteCmdInit(file)
3511 func.WriteCmdSet(file)
3513 file.Write(" gpu::CommandHeader header;\n")
3514 args = func.GetCmdArgs()
3515 for arg in args:
3516 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
3518 consts = func.GetCmdConstants()
3519 for const in consts:
3520 file.Write(" static const %s %s = %s;\n" %
3521 (const.cmd_type, const.name, const.GetConstantValue()))
3523 file.Write("};\n")
3524 file.Write("\n")
3526 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
3527 file.Write("static_assert(sizeof(%s) == %d,\n" % (func.name, size))
3528 file.Write(" \"size of %s should be %d\");\n" %
3529 (func.name, size))
3530 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func.name)
3531 file.Write(" \"offset of %s header should be 0\");\n" %
3532 func.name)
3533 offset = _SIZE_OF_COMMAND_HEADER
3534 for arg in args:
3535 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
3536 (func.name, arg.name, offset))
3537 file.Write(" \"offset of %s %s should be %d\");\n" %
3538 (func.name, arg.name, offset))
3539 offset += _SIZE_OF_UINT32
3540 if not result == None and len(result) > 1:
3541 offset = 0;
3542 for line in result:
3543 parts = line.split()
3544 name = parts[-1]
3545 check = """
3546 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
3547 "offset of %(cmd_name)s Result %(field_name)s should be "
3548 "%(offset)d");
3550 file.Write((check.strip() + "\n") % {
3551 'cmd_name': func.name,
3552 'field_name': name,
3553 'offset': offset,
3555 offset += _SIZE_OF_UINT32
3556 file.Write("\n")
3558 def WriteHandlerImplementation(self, func, file):
3559 """Writes the handler implementation for this command."""
3560 if func.IsUnsafe() and func.GetInfo('id_mapping'):
3561 code_no_gen = """ if (!group_->Get%(type)sServiceId(
3562 %(var)s, &%(service_var)s)) {
3563 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3564 return error::kNoError;
3567 code_gen = """ if (!group_->Get%(type)sServiceId(
3568 %(var)s, &%(service_var)s)) {
3569 if (!group_->bind_generates_resource()) {
3570 LOCAL_SET_GL_ERROR(
3571 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3572 return error::kNoError;
3574 GLuint client_id = %(var)s;
3575 gl%(gen_func)s(1, &%(service_var)s);
3576 Create%(type)s(client_id, %(service_var)s);
3579 gen_func = func.GetInfo('gen_func')
3580 for id_type in func.GetInfo('id_mapping'):
3581 service_var = id_type.lower()
3582 if id_type == 'Sync':
3583 service_var = "service_%s" % service_var
3584 file.Write(" GLsync %s = 0;\n" % service_var)
3585 if gen_func and id_type in gen_func:
3586 file.Write(code_gen % { 'type': id_type,
3587 'var': id_type.lower(),
3588 'service_var': service_var,
3589 'func': func.GetGLFunctionName(),
3590 'gen_func': gen_func })
3591 else:
3592 file.Write(code_no_gen % { 'type': id_type,
3593 'var': id_type.lower(),
3594 'service_var': service_var,
3595 'func': func.GetGLFunctionName() })
3596 args = []
3597 for arg in func.GetOriginalArgs():
3598 if arg.type == "GLsync":
3599 args.append("service_%s" % arg.name)
3600 elif arg.name.endswith("size") and arg.type == "GLsizei":
3601 args.append("num_%s" % func.GetLastOriginalArg().name)
3602 elif arg.name == "length":
3603 args.append("nullptr")
3604 else:
3605 args.append(arg.name)
3606 file.Write(" %s(%s);\n" %
3607 (func.GetGLFunctionName(), ", ".join(args)))
3609 def WriteCmdSizeTest(self, func, file):
3610 """Writes the size test for a command."""
3611 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3613 def WriteFormatTest(self, func, file):
3614 """Writes a format test for a command."""
3615 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
3616 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
3617 (func.name, func.name))
3618 file.Write(" void* next_cmd = cmd.Set(\n")
3619 file.Write(" &cmd")
3620 args = func.GetCmdArgs()
3621 for value, arg in enumerate(args):
3622 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
3623 file.Write(");\n")
3624 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
3625 func.name)
3626 file.Write(" cmd.header.command);\n")
3627 func.type_handler.WriteCmdSizeTest(func, file)
3628 for value, arg in enumerate(args):
3629 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
3630 (arg.type, value + 11, arg.name))
3631 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
3632 file.Write(" next_cmd, sizeof(cmd));\n")
3633 file.Write("}\n")
3634 file.Write("\n")
3636 def WriteImmediateFormatTest(self, func, file):
3637 """Writes a format test for an immediate version of a command."""
3638 pass
3640 def WriteBucketFormatTest(self, func, file):
3641 """Writes a format test for a bucket version of a command."""
3642 pass
3644 def WriteGetDataSizeCode(self, func, file):
3645 """Writes the code to set data_size used in validation"""
3646 pass
3648 def WriteImmediateCmdSizeTest(self, func, file):
3649 """Writes a size test for an immediate version of a command."""
3650 file.Write(" // TODO(gman): Compute correct size.\n")
3651 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3653 def __WriteIdMapping(self, func, file):
3654 """Writes client side / service side ID mapping."""
3655 if not func.IsUnsafe() or not func.GetInfo('id_mapping'):
3656 return
3657 for id_type in func.GetInfo('id_mapping'):
3658 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
3659 (id_type, id_type.lower(), id_type.lower()))
3661 def WriteImmediateHandlerImplementation (self, func, file):
3662 """Writes the handler impl for the immediate version of a command."""
3663 self.__WriteIdMapping(func, file)
3664 file.Write(" %s(%s);\n" %
3665 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3667 def WriteBucketHandlerImplementation (self, func, file):
3668 """Writes the handler impl for the bucket version of a command."""
3669 self.__WriteIdMapping(func, file)
3670 file.Write(" %s(%s);\n" %
3671 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3673 def WriteServiceHandlerFunctionHeader(self, func, file):
3674 """Writes function header for service implementation handlers."""
3675 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
3676 uint32_t immediate_data_size, const void* cmd_data) {
3677 """ % {'name': func.name})
3678 if func.IsUnsafe():
3679 file.Write("""if (!unsafe_es3_apis_enabled())
3680 return error::kUnknownCommand;
3681 """)
3682 file.Write("""const gles2::cmds::%(name)s& c =
3683 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
3684 (void)c;
3685 """ % {'name': func.name})
3687 def WriteServiceImplementation(self, func, file):
3688 """Writes the service implementation for a command."""
3689 self.WriteServiceHandlerFunctionHeader(func, file)
3690 self.WriteHandlerExtensionCheck(func, file)
3691 self.WriteHandlerDeferReadWrite(func, file);
3692 if len(func.GetOriginalArgs()) > 0:
3693 last_arg = func.GetLastOriginalArg()
3694 all_but_last_arg = func.GetOriginalArgs()[:-1]
3695 for arg in all_but_last_arg:
3696 arg.WriteGetCode(file)
3697 self.WriteGetDataSizeCode(func, file)
3698 last_arg.WriteGetCode(file)
3699 func.WriteHandlerValidation(file)
3700 func.WriteHandlerImplementation(file)
3701 file.Write(" return error::kNoError;\n")
3702 file.Write("}\n")
3703 file.Write("\n")
3705 def WriteImmediateServiceImplementation(self, func, file):
3706 """Writes the service implementation for an immediate version of command."""
3707 self.WriteServiceHandlerFunctionHeader(func, file)
3708 self.WriteHandlerExtensionCheck(func, file)
3709 self.WriteHandlerDeferReadWrite(func, file);
3710 for arg in func.GetOriginalArgs():
3711 if arg.IsPointer():
3712 self.WriteGetDataSizeCode(func, file)
3713 arg.WriteGetCode(file)
3714 func.WriteHandlerValidation(file)
3715 func.WriteHandlerImplementation(file)
3716 file.Write(" return error::kNoError;\n")
3717 file.Write("}\n")
3718 file.Write("\n")
3720 def WriteBucketServiceImplementation(self, func, file):
3721 """Writes the service implementation for a bucket version of command."""
3722 self.WriteServiceHandlerFunctionHeader(func, file)
3723 self.WriteHandlerExtensionCheck(func, file)
3724 self.WriteHandlerDeferReadWrite(func, file);
3725 for arg in func.GetCmdArgs():
3726 arg.WriteGetCode(file)
3727 func.WriteHandlerValidation(file)
3728 func.WriteHandlerImplementation(file)
3729 file.Write(" return error::kNoError;\n")
3730 file.Write("}\n")
3731 file.Write("\n")
3733 def WriteHandlerExtensionCheck(self, func, file):
3734 if func.GetInfo('extension_flag'):
3735 file.Write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
3736 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
3737 " \"function not available\");\n" % func.original_name)
3738 file.Write(" return error::kNoError;")
3739 file.Write(" }\n\n")
3741 def WriteHandlerDeferReadWrite(self, func, file):
3742 """Writes the code to handle deferring reads or writes."""
3743 defer_draws = func.GetInfo('defer_draws')
3744 defer_reads = func.GetInfo('defer_reads')
3745 if defer_draws or defer_reads:
3746 file.Write(" error::Error error;\n")
3747 if defer_draws:
3748 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
3749 file.Write(" if (error != error::kNoError)\n")
3750 file.Write(" return error;\n")
3751 if defer_reads:
3752 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
3753 file.Write(" if (error != error::kNoError)\n")
3754 file.Write(" return error;\n")
3756 def WriteValidUnitTest(self, func, file, test, *extras):
3757 """Writes a valid unit test for the service implementation."""
3758 if func.GetInfo('expectation') == False:
3759 test = self._remove_expected_call_re.sub('', test)
3760 name = func.name
3761 arg_strings = [
3762 arg.GetValidArg(func) \
3763 for arg in func.GetOriginalArgs() if not arg.IsConstant()
3765 gl_arg_strings = [
3766 arg.GetValidGLArg(func) \
3767 for arg in func.GetOriginalArgs()
3769 gl_func_name = func.GetGLTestFunctionName()
3770 vars = {
3771 'name':name,
3772 'gl_func_name': gl_func_name,
3773 'args': ", ".join(arg_strings),
3774 'gl_args': ", ".join(gl_arg_strings),
3776 for extra in extras:
3777 vars.update(extra)
3778 old_test = ""
3779 while (old_test != test):
3780 old_test = test
3781 test = test % vars
3782 file.Write(test % vars)
3784 def WriteInvalidUnitTest(self, func, file, test, *extras):
3785 """Writes an invalid unit test for the service implementation."""
3786 if func.IsUnsafe():
3787 return
3788 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
3789 # Service implementation does not test constants, as they are not part of
3790 # the call in the service side.
3791 if invalid_arg.IsConstant():
3792 continue
3794 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
3795 for value_index in range(0, num_invalid_values):
3796 arg_strings = []
3797 parse_result = "kNoError"
3798 gl_error = None
3799 for arg in func.GetOriginalArgs():
3800 if arg.IsConstant():
3801 continue
3802 if invalid_arg is arg:
3803 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
3804 value_index)
3805 else:
3806 arg_string = arg.GetValidArg(func)
3807 arg_strings.append(arg_string)
3808 gl_arg_strings = []
3809 for arg in func.GetOriginalArgs():
3810 gl_arg_strings.append("_")
3811 gl_func_name = func.GetGLTestFunctionName()
3812 gl_error_test = ''
3813 if not gl_error == None:
3814 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
3816 vars = {
3817 'name': func.name,
3818 'arg_index': invalid_arg_index,
3819 'value_index': value_index,
3820 'gl_func_name': gl_func_name,
3821 'args': ", ".join(arg_strings),
3822 'all_but_last_args': ", ".join(arg_strings[:-1]),
3823 'gl_args': ", ".join(gl_arg_strings),
3824 'parse_result': parse_result,
3825 'gl_error_test': gl_error_test,
3827 for extra in extras:
3828 vars.update(extra)
3829 file.Write(test % vars)
3831 def WriteServiceUnitTest(self, func, file, *extras):
3832 """Writes the service unit test for a command."""
3834 if func.name == 'Enable':
3835 valid_test = """
3836 TEST_P(%(test_name)s, %(name)sValidArgs) {
3837 SetupExpectationsForEnableDisable(%(gl_args)s, true);
3838 SpecializedSetup<cmds::%(name)s, 0>(true);
3839 cmds::%(name)s cmd;
3840 cmd.Init(%(args)s);"""
3841 elif func.name == 'Disable':
3842 valid_test = """
3843 TEST_P(%(test_name)s, %(name)sValidArgs) {
3844 SetupExpectationsForEnableDisable(%(gl_args)s, false);
3845 SpecializedSetup<cmds::%(name)s, 0>(true);
3846 cmds::%(name)s cmd;
3847 cmd.Init(%(args)s);"""
3848 else:
3849 valid_test = """
3850 TEST_P(%(test_name)s, %(name)sValidArgs) {
3851 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3852 SpecializedSetup<cmds::%(name)s, 0>(true);
3853 cmds::%(name)s cmd;
3854 cmd.Init(%(args)s);"""
3855 if func.IsUnsafe():
3856 valid_test += """
3857 decoder_->set_unsafe_es3_apis_enabled(true);
3858 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3859 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3860 decoder_->set_unsafe_es3_apis_enabled(false);
3861 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
3864 else:
3865 valid_test += """
3866 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3867 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3870 self.WriteValidUnitTest(func, file, valid_test, *extras)
3872 if not func.IsUnsafe():
3873 invalid_test = """
3874 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3875 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3876 SpecializedSetup<cmds::%(name)s, 0>(false);
3877 cmds::%(name)s cmd;
3878 cmd.Init(%(args)s);
3879 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3882 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
3884 def WriteImmediateServiceUnitTest(self, func, file, *extras):
3885 """Writes the service unit test for an immediate command."""
3886 file.Write("// TODO(gman): %s\n" % func.name)
3888 def WriteImmediateValidationCode(self, func, file):
3889 """Writes the validation code for an immediate version of a command."""
3890 pass
3892 def WriteBucketServiceUnitTest(self, func, file, *extras):
3893 """Writes the service unit test for a bucket command."""
3894 file.Write("// TODO(gman): %s\n" % func.name)
3896 def WriteBucketValidationCode(self, func, file):
3897 """Writes the validation code for a bucket version of a command."""
3898 file.Write("// TODO(gman): %s\n" % func.name)
3900 def WriteGLES2ImplementationDeclaration(self, func, file):
3901 """Writes the GLES2 Implemention declaration."""
3902 impl_decl = func.GetInfo('impl_decl')
3903 if impl_decl == None or impl_decl == True:
3904 file.Write("%s %s(%s) override;\n" %
3905 (func.return_type, func.original_name,
3906 func.MakeTypedOriginalArgString("")))
3907 file.Write("\n")
3909 def WriteGLES2CLibImplementation(self, func, file):
3910 file.Write("%s GLES2%s(%s) {\n" %
3911 (func.return_type, func.name,
3912 func.MakeTypedOriginalArgString("")))
3913 result_string = "return "
3914 if func.return_type == "void":
3915 result_string = ""
3916 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3917 (result_string, func.original_name,
3918 func.MakeOriginalArgString("")))
3919 file.Write("}\n")
3921 def WriteGLES2Header(self, func, file):
3922 """Writes a re-write macro for GLES"""
3923 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
3925 def WriteClientGLCallLog(self, func, file):
3926 """Writes a logging macro for the client side code."""
3927 comma = ""
3928 if len(func.GetOriginalArgs()):
3929 comma = " << "
3930 file.Write(
3931 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3932 (func.original_name, comma, func.MakeLogArgString()))
3934 def WriteClientGLReturnLog(self, func, file):
3935 """Writes the return value logging code."""
3936 if func.return_type != "void":
3937 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3939 def WriteGLES2ImplementationHeader(self, func, file):
3940 """Writes the GLES2 Implemention."""
3941 self.WriteGLES2ImplementationDeclaration(func, file)
3943 def WriteGLES2TraceImplementationHeader(self, func, file):
3944 """Writes the GLES2 Trace Implemention header."""
3945 file.Write("%s %s(%s) override;\n" %
3946 (func.return_type, func.original_name,
3947 func.MakeTypedOriginalArgString("")))
3949 def WriteGLES2TraceImplementation(self, func, file):
3950 """Writes the GLES2 Trace Implemention."""
3951 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3952 (func.return_type, func.original_name,
3953 func.MakeTypedOriginalArgString("")))
3954 result_string = "return "
3955 if func.return_type == "void":
3956 result_string = ""
3957 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3958 func.name)
3959 file.Write(" %sgl_->%s(%s);\n" %
3960 (result_string, func.name, func.MakeOriginalArgString("")))
3961 file.Write("}\n")
3962 file.Write("\n")
3964 def WriteGLES2Implementation(self, func, file):
3965 """Writes the GLES2 Implemention."""
3966 impl_func = func.GetInfo('impl_func')
3967 impl_decl = func.GetInfo('impl_decl')
3968 gen_cmd = func.GetInfo('gen_cmd')
3969 if (func.can_auto_generate and
3970 (impl_func == None or impl_func == True) and
3971 (impl_decl == None or impl_decl == True) and
3972 (gen_cmd == None or gen_cmd == True)):
3973 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3974 (func.return_type, func.original_name,
3975 func.MakeTypedOriginalArgString("")))
3976 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3977 self.WriteClientGLCallLog(func, file)
3978 func.WriteDestinationInitalizationValidation(file)
3979 for arg in func.GetOriginalArgs():
3980 arg.WriteClientSideValidationCode(file, func)
3981 file.Write(" helper_->%s(%s);\n" %
3982 (func.name, func.MakeHelperArgString("")))
3983 file.Write(" CheckGLError();\n")
3984 self.WriteClientGLReturnLog(func, file)
3985 file.Write("}\n")
3986 file.Write("\n")
3988 def WriteGLES2InterfaceHeader(self, func, file):
3989 """Writes the GLES2 Interface."""
3990 file.Write("virtual %s %s(%s) = 0;\n" %
3991 (func.return_type, func.original_name,
3992 func.MakeTypedOriginalArgString("")))
3994 def WriteGLES2InterfaceStub(self, func, file):
3995 """Writes the GLES2 Interface stub declaration."""
3996 file.Write("%s %s(%s) override;\n" %
3997 (func.return_type, func.original_name,
3998 func.MakeTypedOriginalArgString("")))
4000 def WriteGLES2InterfaceStubImpl(self, func, file):
4001 """Writes the GLES2 Interface stub declaration."""
4002 args = func.GetOriginalArgs()
4003 arg_string = ", ".join(
4004 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
4005 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
4006 (func.return_type, func.original_name, arg_string))
4007 if func.return_type != "void":
4008 file.Write(" return 0;\n")
4009 file.Write("}\n")
4011 def WriteGLES2ImplementationUnitTest(self, func, file):
4012 """Writes the GLES2 Implemention unit test."""
4013 client_test = func.GetInfo('client_test')
4014 if (func.can_auto_generate and
4015 (client_test == None or client_test == True)):
4016 code = """
4017 TEST_F(GLES2ImplementationTest, %(name)s) {
4018 struct Cmds {
4019 cmds::%(name)s cmd;
4021 Cmds expected;
4022 expected.cmd.Init(%(cmd_args)s);
4024 gl_->%(name)s(%(args)s);
4025 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4028 cmd_arg_strings = [
4029 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4032 gl_arg_strings = [
4033 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4036 file.Write(code % {
4037 'name': func.name,
4038 'args': ", ".join(gl_arg_strings),
4039 'cmd_args': ", ".join(cmd_arg_strings),
4042 # Test constants for invalid values, as they are not tested by the
4043 # service.
4044 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
4045 if constants:
4046 code = """
4047 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4048 gl_->%(name)s(%(args)s);
4049 EXPECT_TRUE(NoCommandsWritten());
4050 EXPECT_EQ(%(gl_error)s, CheckError());
4053 for invalid_arg in constants:
4054 gl_arg_strings = []
4055 invalid = invalid_arg.GetInvalidArg(func)
4056 for arg in func.GetOriginalArgs():
4057 if arg is invalid_arg:
4058 gl_arg_strings.append(invalid[0])
4059 else:
4060 gl_arg_strings.append(arg.GetValidClientSideArg(func))
4062 file.Write(code % {
4063 'name': func.name,
4064 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
4065 'args': ", ".join(gl_arg_strings),
4066 'gl_error': invalid[2],
4068 else:
4069 if client_test != False:
4070 file.Write("// TODO(zmo): Implement unit test for %s\n" % func.name)
4072 def WriteDestinationInitalizationValidation(self, func, file):
4073 """Writes the client side destintion initialization validation."""
4074 for arg in func.GetOriginalArgs():
4075 arg.WriteDestinationInitalizationValidation(file, func)
4077 def WriteTraceEvent(self, func, file):
4078 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4079 func.original_name)
4081 def WriteImmediateCmdComputeSize(self, func, file):
4082 """Writes the size computation code for the immediate version of a cmd."""
4083 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4084 file.Write(" return static_cast<uint32_t>(\n")
4085 file.Write(" sizeof(ValueType) + // NOLINT\n")
4086 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4087 file.Write(" }\n")
4088 file.Write("\n")
4090 def WriteImmediateCmdSetHeader(self, func, file):
4091 """Writes the SetHeader function for the immediate version of a cmd."""
4092 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
4093 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4094 file.Write(" }\n")
4095 file.Write("\n")
4097 def WriteImmediateCmdInit(self, func, file):
4098 """Writes the Init function for the immediate version of a command."""
4099 raise NotImplementedError(func.name)
4101 def WriteImmediateCmdSet(self, func, file):
4102 """Writes the Set function for the immediate version of a command."""
4103 raise NotImplementedError(func.name)
4105 def WriteCmdHelper(self, func, file):
4106 """Writes the cmd helper definition for a cmd."""
4107 code = """ void %(name)s(%(typed_args)s) {
4108 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4109 if (c) {
4110 c->Init(%(args)s);
4115 file.Write(code % {
4116 "name": func.name,
4117 "typed_args": func.MakeTypedCmdArgString(""),
4118 "args": func.MakeCmdArgString(""),
4121 def WriteImmediateCmdHelper(self, func, file):
4122 """Writes the cmd helper definition for the immediate version of a cmd."""
4123 code = """ void %(name)s(%(typed_args)s) {
4124 const uint32_t s = 0; // TODO(gman): compute correct size
4125 gles2::cmds::%(name)s* c =
4126 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4127 if (c) {
4128 c->Init(%(args)s);
4133 file.Write(code % {
4134 "name": func.name,
4135 "typed_args": func.MakeTypedCmdArgString(""),
4136 "args": func.MakeCmdArgString(""),
4140 class StateSetHandler(TypeHandler):
4141 """Handler for commands that simply set state."""
4143 def __init__(self):
4144 TypeHandler.__init__(self)
4146 def WriteHandlerImplementation(self, func, file):
4147 """Overrriden from TypeHandler."""
4148 state_name = func.GetInfo('state')
4149 state = _STATES[state_name]
4150 states = state['states']
4151 args = func.GetOriginalArgs()
4152 for ndx,item in enumerate(states):
4153 code = []
4154 if 'range_checks' in item:
4155 for range_check in item['range_checks']:
4156 code.append("%s %s" % (args[ndx].name, range_check['check']))
4157 if 'nan_check' in item:
4158 # Drivers might generate an INVALID_VALUE error when a value is set
4159 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
4160 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
4161 # Make this behavior consistent within Chromium, and avoid leaking GL
4162 # errors by generating the error in the command buffer instead of
4163 # letting the GL driver generate it.
4164 code.append("base::IsNaN(%s)" % args[ndx].name)
4165 if len(code):
4166 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4167 file.Write(
4168 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
4169 ' "%s", "%s out of range");\n' %
4170 (func.name, args[ndx].name))
4171 file.Write(" return error::kNoError;\n")
4172 file.Write(" }\n")
4173 code = []
4174 for ndx,item in enumerate(states):
4175 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
4176 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4177 for ndx,item in enumerate(states):
4178 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
4179 if 'state_flag' in state:
4180 file.Write(" %s = true;\n" % state['state_flag'])
4181 if not func.GetInfo("no_gl"):
4182 for ndx,item in enumerate(states):
4183 if item.get('cached', False):
4184 file.Write(" state_.%s = %s;\n" %
4185 (CachedStateName(item), args[ndx].name))
4186 file.Write(" %s(%s);\n" %
4187 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4188 file.Write(" }\n")
4190 def WriteServiceUnitTest(self, func, file, *extras):
4191 """Overrriden from TypeHandler."""
4192 TypeHandler.WriteServiceUnitTest(self, func, file, *extras)
4193 state_name = func.GetInfo('state')
4194 state = _STATES[state_name]
4195 states = state['states']
4196 for ndx,item in enumerate(states):
4197 if 'range_checks' in item:
4198 for check_ndx, range_check in enumerate(item['range_checks']):
4199 valid_test = """
4200 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
4201 SpecializedSetup<cmds::%(name)s, 0>(false);
4202 cmds::%(name)s cmd;
4203 cmd.Init(%(args)s);
4204 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4205 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4208 name = func.name
4209 arg_strings = [
4210 arg.GetValidArg(func) \
4211 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4214 arg_strings[ndx] = range_check['test_value']
4215 vars = {
4216 'name': name,
4217 'ndx': ndx,
4218 'check_ndx': check_ndx,
4219 'args': ", ".join(arg_strings),
4221 for extra in extras:
4222 vars.update(extra)
4223 file.Write(valid_test % vars)
4224 if 'nan_check' in item:
4225 valid_test = """
4226 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
4227 SpecializedSetup<cmds::%(name)s, 0>(false);
4228 cmds::%(name)s cmd;
4229 cmd.Init(%(args)s);
4230 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4231 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4234 name = func.name
4235 arg_strings = [
4236 arg.GetValidArg(func) \
4237 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4240 arg_strings[ndx] = 'nanf("")'
4241 vars = {
4242 'name': name,
4243 'ndx': ndx,
4244 'args': ", ".join(arg_strings),
4246 for extra in extras:
4247 vars.update(extra)
4248 file.Write(valid_test % vars)
4251 class StateSetRGBAlphaHandler(TypeHandler):
4252 """Handler for commands that simply set state that have rgb/alpha."""
4254 def __init__(self):
4255 TypeHandler.__init__(self)
4257 def WriteHandlerImplementation(self, func, file):
4258 """Overrriden from TypeHandler."""
4259 state_name = func.GetInfo('state')
4260 state = _STATES[state_name]
4261 states = state['states']
4262 args = func.GetOriginalArgs()
4263 num_args = len(args)
4264 code = []
4265 for ndx,item in enumerate(states):
4266 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
4267 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4268 for ndx, item in enumerate(states):
4269 file.Write(" state_.%s = %s;\n" %
4270 (item['name'], args[ndx % num_args].name))
4271 if 'state_flag' in state:
4272 file.Write(" %s = true;\n" % state['state_flag'])
4273 if not func.GetInfo("no_gl"):
4274 file.Write(" %s(%s);\n" %
4275 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4276 file.Write(" }\n")
4279 class StateSetFrontBackSeparateHandler(TypeHandler):
4280 """Handler for commands that simply set state that have front/back."""
4282 def __init__(self):
4283 TypeHandler.__init__(self)
4285 def WriteHandlerImplementation(self, func, file):
4286 """Overrriden from TypeHandler."""
4287 state_name = func.GetInfo('state')
4288 state = _STATES[state_name]
4289 states = state['states']
4290 args = func.GetOriginalArgs()
4291 face = args[0].name
4292 num_args = len(args)
4293 file.Write(" bool changed = false;\n")
4294 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4295 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4296 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4297 code = []
4298 for ndx, item in enumerate(group):
4299 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
4300 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
4301 file.Write(" }\n")
4302 file.Write(" if (changed) {\n")
4303 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4304 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4305 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4306 for ndx, item in enumerate(group):
4307 file.Write(" state_.%s = %s;\n" %
4308 (item['name'], args[ndx + 1].name))
4309 file.Write(" }\n")
4310 if 'state_flag' in state:
4311 file.Write(" %s = true;\n" % state['state_flag'])
4312 if not func.GetInfo("no_gl"):
4313 file.Write(" %s(%s);\n" %
4314 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4315 file.Write(" }\n")
4318 class StateSetFrontBackHandler(TypeHandler):
4319 """Handler for commands that simply set state that set both front/back."""
4321 def __init__(self):
4322 TypeHandler.__init__(self)
4324 def WriteHandlerImplementation(self, func, file):
4325 """Overrriden from TypeHandler."""
4326 state_name = func.GetInfo('state')
4327 state = _STATES[state_name]
4328 states = state['states']
4329 args = func.GetOriginalArgs()
4330 num_args = len(args)
4331 code = []
4332 for group_ndx, group in enumerate(Grouper(num_args, states)):
4333 for ndx, item in enumerate(group):
4334 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
4335 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4336 for group_ndx, group in enumerate(Grouper(num_args, states)):
4337 for ndx, item in enumerate(group):
4338 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
4339 if 'state_flag' in state:
4340 file.Write(" %s = true;\n" % state['state_flag'])
4341 if not func.GetInfo("no_gl"):
4342 file.Write(" %s(%s);\n" %
4343 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4344 file.Write(" }\n")
4347 class StateSetNamedParameter(TypeHandler):
4348 """Handler for commands that set a state chosen with an enum parameter."""
4350 def __init__(self):
4351 TypeHandler.__init__(self)
4353 def WriteHandlerImplementation(self, func, file):
4354 """Overridden from TypeHandler."""
4355 state_name = func.GetInfo('state')
4356 state = _STATES[state_name]
4357 states = state['states']
4358 args = func.GetOriginalArgs()
4359 num_args = len(args)
4360 assert num_args == 2
4361 file.Write(" switch (%s) {\n" % args[0].name)
4362 for state in states:
4363 file.Write(" case %s:\n" % state['enum'])
4364 file.Write(" if (state_.%s != %s) {\n" %
4365 (state['name'], args[1].name))
4366 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
4367 if not func.GetInfo("no_gl"):
4368 file.Write(" %s(%s);\n" %
4369 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4370 file.Write(" }\n")
4371 file.Write(" break;\n")
4372 file.Write(" default:\n")
4373 file.Write(" NOTREACHED();\n")
4374 file.Write(" }\n")
4377 class CustomHandler(TypeHandler):
4378 """Handler for commands that are auto-generated but require minor tweaks."""
4380 def __init__(self):
4381 TypeHandler.__init__(self)
4383 def WriteServiceImplementation(self, func, file):
4384 """Overrriden from TypeHandler."""
4385 pass
4387 def WriteImmediateServiceImplementation(self, func, file):
4388 """Overrriden from TypeHandler."""
4389 pass
4391 def WriteBucketServiceImplementation(self, func, file):
4392 """Overrriden from TypeHandler."""
4393 pass
4395 def WriteServiceUnitTest(self, func, file, *extras):
4396 """Overrriden from TypeHandler."""
4397 file.Write("// TODO(gman): %s\n\n" % func.name)
4399 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4400 """Overrriden from TypeHandler."""
4401 file.Write("// TODO(gman): %s\n\n" % func.name)
4403 def WriteImmediateCmdGetTotalSize(self, func, file):
4404 """Overrriden from TypeHandler."""
4405 file.Write(
4406 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
4408 def WriteImmediateCmdInit(self, func, file):
4409 """Overrriden from TypeHandler."""
4410 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
4411 self.WriteImmediateCmdGetTotalSize(func, file)
4412 file.Write(" SetHeader(total_size);\n")
4413 args = func.GetCmdArgs()
4414 for arg in args:
4415 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4416 file.Write(" }\n")
4417 file.Write("\n")
4419 def WriteImmediateCmdSet(self, func, file):
4420 """Overrriden from TypeHandler."""
4421 copy_args = func.MakeCmdArgString("_", False)
4422 file.Write(" void* Set(void* cmd%s) {\n" %
4423 func.MakeTypedCmdArgString("_", True))
4424 self.WriteImmediateCmdGetTotalSize(func, file)
4425 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
4426 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4427 "cmd, total_size);\n")
4428 file.Write(" }\n")
4429 file.Write("\n")
4432 class TodoHandler(CustomHandler):
4433 """Handle for commands that are not yet implemented."""
4435 def NeedsDataTransferFunction(self, func):
4436 """Overriden from TypeHandler."""
4437 return False
4439 def WriteImmediateFormatTest(self, func, file):
4440 """Overrriden from TypeHandler."""
4441 pass
4443 def WriteGLES2ImplementationUnitTest(self, func, file):
4444 """Overrriden from TypeHandler."""
4445 pass
4447 def WriteGLES2Implementation(self, func, file):
4448 """Overrriden from TypeHandler."""
4449 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4450 (func.return_type, func.original_name,
4451 func.MakeTypedOriginalArgString("")))
4452 file.Write(" // TODO: for now this is a no-op\n")
4453 file.Write(
4454 " SetGLError("
4455 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4456 func.name)
4457 if func.return_type != "void":
4458 file.Write(" return 0;\n")
4459 file.Write("}\n")
4460 file.Write("\n")
4462 def WriteServiceImplementation(self, func, file):
4463 """Overrriden from TypeHandler."""
4464 self.WriteServiceHandlerFunctionHeader(func, file)
4465 file.Write(" // TODO: for now this is a no-op\n")
4466 file.Write(
4467 " LOCAL_SET_GL_ERROR("
4468 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4469 func.name)
4470 file.Write(" return error::kNoError;\n")
4471 file.Write("}\n")
4472 file.Write("\n")
4475 class HandWrittenHandler(CustomHandler):
4476 """Handler for comands where everything must be written by hand."""
4478 def InitFunction(self, func):
4479 """Add or adjust anything type specific for this function."""
4480 CustomHandler.InitFunction(self, func)
4481 func.can_auto_generate = False
4483 def NeedsDataTransferFunction(self, func):
4484 """Overriden from TypeHandler."""
4485 # If specified explicitly, force the data transfer method.
4486 if func.GetInfo('data_transfer_methods'):
4487 return True
4488 return False
4490 def WriteStruct(self, func, file):
4491 """Overrriden from TypeHandler."""
4492 pass
4494 def WriteDocs(self, func, file):
4495 """Overrriden from TypeHandler."""
4496 pass
4498 def WriteServiceUnitTest(self, func, file, *extras):
4499 """Overrriden from TypeHandler."""
4500 file.Write("// TODO(gman): %s\n\n" % func.name)
4502 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4503 """Overrriden from TypeHandler."""
4504 file.Write("// TODO(gman): %s\n\n" % func.name)
4506 def WriteBucketServiceUnitTest(self, func, file, *extras):
4507 """Overrriden from TypeHandler."""
4508 file.Write("// TODO(gman): %s\n\n" % func.name)
4510 def WriteServiceImplementation(self, func, file):
4511 """Overrriden from TypeHandler."""
4512 pass
4514 def WriteImmediateServiceImplementation(self, func, file):
4515 """Overrriden from TypeHandler."""
4516 pass
4518 def WriteBucketServiceImplementation(self, func, file):
4519 """Overrriden from TypeHandler."""
4520 pass
4522 def WriteImmediateCmdHelper(self, func, file):
4523 """Overrriden from TypeHandler."""
4524 pass
4526 def WriteCmdHelper(self, func, file):
4527 """Overrriden from TypeHandler."""
4528 pass
4530 def WriteFormatTest(self, func, file):
4531 """Overrriden from TypeHandler."""
4532 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4534 def WriteImmediateFormatTest(self, func, file):
4535 """Overrriden from TypeHandler."""
4536 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4538 def WriteBucketFormatTest(self, func, file):
4539 """Overrriden from TypeHandler."""
4540 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4544 class ManualHandler(CustomHandler):
4545 """Handler for commands who's handlers must be written by hand."""
4547 def __init__(self):
4548 CustomHandler.__init__(self)
4550 def InitFunction(self, func):
4551 """Overrriden from TypeHandler."""
4552 if (func.name == 'CompressedTexImage2DBucket'):
4553 func.cmd_args = func.cmd_args[:-1]
4554 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
4555 else:
4556 CustomHandler.InitFunction(self, func)
4558 def WriteServiceImplementation(self, func, file):
4559 """Overrriden from TypeHandler."""
4560 pass
4562 def WriteBucketServiceImplementation(self, func, file):
4563 """Overrriden from TypeHandler."""
4564 pass
4566 def WriteServiceUnitTest(self, func, file, *extras):
4567 """Overrriden from TypeHandler."""
4568 file.Write("// TODO(gman): %s\n\n" % func.name)
4570 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4571 """Overrriden from TypeHandler."""
4572 file.Write("// TODO(gman): %s\n\n" % func.name)
4574 def WriteImmediateServiceImplementation(self, func, file):
4575 """Overrriden from TypeHandler."""
4576 pass
4578 def WriteImmediateFormatTest(self, func, file):
4579 """Overrriden from TypeHandler."""
4580 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
4582 def WriteGLES2Implementation(self, func, file):
4583 """Overrriden from TypeHandler."""
4584 if func.GetInfo('impl_func'):
4585 super(ManualHandler, self).WriteGLES2Implementation(func, file)
4587 def WriteGLES2ImplementationHeader(self, func, file):
4588 """Overrriden from TypeHandler."""
4589 file.Write("%s %s(%s) override;\n" %
4590 (func.return_type, func.original_name,
4591 func.MakeTypedOriginalArgString("")))
4592 file.Write("\n")
4594 def WriteImmediateCmdGetTotalSize(self, func, file):
4595 """Overrriden from TypeHandler."""
4596 # TODO(gman): Move this data to _FUNCTION_INFO?
4597 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
4600 class DataHandler(TypeHandler):
4601 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
4602 glCompressedTexImage2D, glCompressedTexImageSub2D."""
4603 def __init__(self):
4604 TypeHandler.__init__(self)
4606 def InitFunction(self, func):
4607 """Overrriden from TypeHandler."""
4608 if func.name == 'CompressedTexSubImage2DBucket':
4609 func.cmd_args = func.cmd_args[:-1]
4610 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
4612 def WriteGetDataSizeCode(self, func, file):
4613 """Overrriden from TypeHandler."""
4614 # TODO(gman): Move this data to _FUNCTION_INFO?
4615 name = func.name
4616 if name.endswith("Immediate"):
4617 name = name[0:-9]
4618 if name == 'BufferData' or name == 'BufferSubData':
4619 file.Write(" uint32_t data_size = size;\n")
4620 elif (name == 'CompressedTexImage2D' or
4621 name == 'CompressedTexSubImage2D'):
4622 file.Write(" uint32_t data_size = imageSize;\n")
4623 elif (name == 'CompressedTexSubImage2DBucket'):
4624 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
4625 file.Write(" uint32_t data_size = bucket->size();\n")
4626 file.Write(" GLsizei imageSize = data_size;\n")
4627 elif name == 'TexImage2D' or name == 'TexSubImage2D':
4628 code = """ uint32_t data_size;
4629 if (!GLES2Util::ComputeImageDataSize(
4630 width, height, format, type, unpack_alignment_, &data_size)) {
4631 return error::kOutOfBounds;
4634 file.Write(code)
4635 else:
4636 file.Write(
4637 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
4639 def WriteImmediateCmdGetTotalSize(self, func, file):
4640 """Overrriden from TypeHandler."""
4641 pass
4643 def WriteImmediateCmdSizeTest(self, func, file):
4644 """Overrriden from TypeHandler."""
4645 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
4647 def WriteImmediateCmdInit(self, func, file):
4648 """Overrriden from TypeHandler."""
4649 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
4650 self.WriteImmediateCmdGetTotalSize(func, file)
4651 file.Write(" SetHeader(total_size);\n")
4652 args = func.GetCmdArgs()
4653 for arg in args:
4654 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4655 file.Write(" }\n")
4656 file.Write("\n")
4658 def WriteImmediateCmdSet(self, func, file):
4659 """Overrriden from TypeHandler."""
4660 copy_args = func.MakeCmdArgString("_", False)
4661 file.Write(" void* Set(void* cmd%s) {\n" %
4662 func.MakeTypedCmdArgString("_", True))
4663 self.WriteImmediateCmdGetTotalSize(func, file)
4664 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
4665 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4666 "cmd, total_size);\n")
4667 file.Write(" }\n")
4668 file.Write("\n")
4670 def WriteImmediateFormatTest(self, func, file):
4671 """Overrriden from TypeHandler."""
4672 # TODO(gman): Remove this exception.
4673 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
4674 return
4676 def WriteServiceUnitTest(self, func, file, *extras):
4677 """Overrriden from TypeHandler."""
4678 file.Write("// TODO(gman): %s\n\n" % func.name)
4680 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4681 """Overrriden from TypeHandler."""
4682 file.Write("// TODO(gman): %s\n\n" % func.name)
4684 def WriteBucketServiceImplementation(self, func, file):
4685 """Overrriden from TypeHandler."""
4686 if not func.name == 'CompressedTexSubImage2DBucket':
4687 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
4690 class BindHandler(TypeHandler):
4691 """Handler for glBind___ type functions."""
4693 def __init__(self):
4694 TypeHandler.__init__(self)
4696 def WriteServiceUnitTest(self, func, file, *extras):
4697 """Overrriden from TypeHandler."""
4699 if len(func.GetOriginalArgs()) == 1:
4700 valid_test = """
4701 TEST_P(%(test_name)s, %(name)sValidArgs) {
4702 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4703 SpecializedSetup<cmds::%(name)s, 0>(true);
4704 cmds::%(name)s cmd;
4705 cmd.Init(%(args)s);"""
4706 if func.IsUnsafe():
4707 valid_test += """
4708 decoder_->set_unsafe_es3_apis_enabled(true);
4709 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4710 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4711 decoder_->set_unsafe_es3_apis_enabled(false);
4712 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4715 else:
4716 valid_test += """
4717 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4718 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4721 if func.GetInfo("gen_func"):
4722 valid_test += """
4723 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
4724 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
4725 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
4726 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4727 SpecializedSetup<cmds::%(name)s, 0>(true);
4728 cmds::%(name)s cmd;
4729 cmd.Init(kNewClientId);
4730 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4731 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4732 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4735 self.WriteValidUnitTest(func, file, valid_test, {
4736 'resource_type': func.GetOriginalArgs()[0].resource_type,
4737 'gl_gen_func_name': func.GetInfo("gen_func"),
4738 }, *extras)
4739 else:
4740 valid_test = """
4741 TEST_P(%(test_name)s, %(name)sValidArgs) {
4742 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4743 SpecializedSetup<cmds::%(name)s, 0>(true);
4744 cmds::%(name)s cmd;
4745 cmd.Init(%(args)s);"""
4746 if func.IsUnsafe():
4747 valid_test += """
4748 decoder_->set_unsafe_es3_apis_enabled(true);
4749 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4750 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4751 decoder_->set_unsafe_es3_apis_enabled(false);
4752 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4755 else:
4756 valid_test += """
4757 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4758 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4761 if func.GetInfo("gen_func"):
4762 valid_test += """
4763 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
4764 EXPECT_CALL(*gl_,
4765 %(gl_func_name)s(%(gl_args_with_new_id)s));
4766 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
4767 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4768 SpecializedSetup<cmds::%(name)s, 0>(true);
4769 cmds::%(name)s cmd;
4770 cmd.Init(%(args_with_new_id)s);"""
4771 if func.IsUnsafe():
4772 valid_test += """
4773 decoder_->set_unsafe_es3_apis_enabled(true);
4774 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4775 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4776 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4777 decoder_->set_unsafe_es3_apis_enabled(false);
4778 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4781 else:
4782 valid_test += """
4783 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4784 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4785 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4789 gl_args_with_new_id = []
4790 args_with_new_id = []
4791 for arg in func.GetOriginalArgs():
4792 if hasattr(arg, 'resource_type'):
4793 gl_args_with_new_id.append('kNewServiceId')
4794 args_with_new_id.append('kNewClientId')
4795 else:
4796 gl_args_with_new_id.append(arg.GetValidGLArg(func))
4797 args_with_new_id.append(arg.GetValidArg(func))
4798 self.WriteValidUnitTest(func, file, valid_test, {
4799 'args_with_new_id': ", ".join(args_with_new_id),
4800 'gl_args_with_new_id': ", ".join(gl_args_with_new_id),
4801 'resource_type': func.GetResourceIdArg().resource_type,
4802 'gl_gen_func_name': func.GetInfo("gen_func"),
4803 }, *extras)
4805 invalid_test = """
4806 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4807 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4808 SpecializedSetup<cmds::%(name)s, 0>(false);
4809 cmds::%(name)s cmd;
4810 cmd.Init(%(args)s);
4811 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4814 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
4816 def WriteGLES2Implementation(self, func, file):
4817 """Writes the GLES2 Implemention."""
4819 impl_func = func.GetInfo('impl_func')
4820 impl_decl = func.GetInfo('impl_decl')
4822 if (func.can_auto_generate and
4823 (impl_func == None or impl_func == True) and
4824 (impl_decl == None or impl_decl == True)):
4826 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4827 (func.return_type, func.original_name,
4828 func.MakeTypedOriginalArgString("")))
4829 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4830 func.WriteDestinationInitalizationValidation(file)
4831 self.WriteClientGLCallLog(func, file)
4832 for arg in func.GetOriginalArgs():
4833 arg.WriteClientSideValidationCode(file, func)
4835 code = """ if (Is%(type)sReservedId(%(id)s)) {
4836 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
4837 return;
4839 %(name)sHelper(%(arg_string)s);
4840 CheckGLError();
4844 name_arg = func.GetResourceIdArg()
4845 file.Write(code % {
4846 'name': func.name,
4847 'arg_string': func.MakeOriginalArgString(""),
4848 'id': name_arg.name,
4849 'type': name_arg.resource_type,
4850 'lc_type': name_arg.resource_type.lower(),
4853 def WriteGLES2ImplementationUnitTest(self, func, file):
4854 """Overrriden from TypeHandler."""
4855 client_test = func.GetInfo('client_test')
4856 if client_test == False:
4857 return
4858 code = """
4859 TEST_F(GLES2ImplementationTest, %(name)s) {
4860 struct Cmds {
4861 cmds::%(name)s cmd;
4863 Cmds expected;
4864 expected.cmd.Init(%(cmd_args)s);
4866 gl_->%(name)s(%(args)s);
4867 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
4868 if not func.IsUnsafe():
4869 code += """
4870 ClearCommands();
4871 gl_->%(name)s(%(args)s);
4872 EXPECT_TRUE(NoCommandsWritten());"""
4873 code += """
4876 cmd_arg_strings = [
4877 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4879 gl_arg_strings = [
4880 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4883 file.Write(code % {
4884 'name': func.name,
4885 'args': ", ".join(gl_arg_strings),
4886 'cmd_args': ", ".join(cmd_arg_strings),
4890 class GENnHandler(TypeHandler):
4891 """Handler for glGen___ type functions."""
4893 def __init__(self):
4894 TypeHandler.__init__(self)
4896 def InitFunction(self, func):
4897 """Overrriden from TypeHandler."""
4898 pass
4900 def WriteGetDataSizeCode(self, func, file):
4901 """Overrriden from TypeHandler."""
4902 code = """ uint32_t data_size;
4903 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4904 return error::kOutOfBounds;
4907 file.Write(code)
4909 def WriteHandlerImplementation (self, func, file):
4910 """Overrriden from TypeHandler."""
4911 file.Write(" if (!%sHelper(n, %s)) {\n"
4912 " return error::kInvalidArguments;\n"
4913 " }\n" %
4914 (func.name, func.GetLastOriginalArg().name))
4916 def WriteImmediateHandlerImplementation(self, func, file):
4917 """Overrriden from TypeHandler."""
4918 if func.IsUnsafe():
4919 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
4920 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
4921 return error::kInvalidArguments;
4924 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
4925 gl%(func_name)s(n, service_ids.get());
4926 for (GLsizei ii = 0; ii < n; ++ii) {
4927 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
4929 """ % { 'func_name': func.original_name,
4930 'last_arg_name': func.GetLastOriginalArg().name,
4931 'resource_name': func.GetInfo('resource_type') })
4932 else:
4933 file.Write(" if (!%sHelper(n, %s)) {\n"
4934 " return error::kInvalidArguments;\n"
4935 " }\n" %
4936 (func.original_name, func.GetLastOriginalArg().name))
4938 def WriteGLES2Implementation(self, func, file):
4939 """Overrriden from TypeHandler."""
4940 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
4941 for (GLsizei i = 0; i < n; ++i) {
4942 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4944 });""" % func.GetOriginalArgs()[1].name)
4945 args = {
4946 'log_code': log_code,
4947 'return_type': func.return_type,
4948 'name': func.original_name,
4949 'typed_args': func.MakeTypedOriginalArgString(""),
4950 'args': func.MakeOriginalArgString(""),
4951 'resource_types': func.GetInfo('resource_types'),
4952 'count_name': func.GetOriginalArgs()[0].name,
4954 file.Write(
4955 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4956 args)
4957 func.WriteDestinationInitalizationValidation(file)
4958 self.WriteClientGLCallLog(func, file)
4959 for arg in func.GetOriginalArgs():
4960 arg.WriteClientSideValidationCode(file, func)
4961 not_shared = func.GetInfo('not_shared')
4962 if not_shared:
4963 alloc_code = (
4965 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
4966 for (GLsizei ii = 0; ii < n; ++ii)
4967 %s[ii] = id_allocator->AllocateID();""" %
4968 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
4969 else:
4970 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
4971 MakeIds(this, 0, %(args)s);""" % args)
4972 args['alloc_code'] = alloc_code
4974 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
4975 %(alloc_code)s
4976 %(name)sHelper(%(args)s);
4977 helper_->%(name)sImmediate(%(args)s);
4978 if (share_group_->bind_generates_resource())
4979 helper_->CommandBufferHelper::Flush();
4980 %(log_code)s
4981 CheckGLError();
4985 file.Write(code % args)
4987 def WriteGLES2ImplementationUnitTest(self, func, file):
4988 """Overrriden from TypeHandler."""
4989 code = """
4990 TEST_F(GLES2ImplementationTest, %(name)s) {
4991 GLuint ids[2] = { 0, };
4992 struct Cmds {
4993 cmds::%(name)sImmediate gen;
4994 GLuint data[2];
4996 Cmds expected;
4997 expected.gen.Init(arraysize(ids), &ids[0]);
4998 expected.data[0] = k%(types)sStartId;
4999 expected.data[1] = k%(types)sStartId + 1;
5000 gl_->%(name)s(arraysize(ids), &ids[0]);
5001 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5002 EXPECT_EQ(k%(types)sStartId, ids[0]);
5003 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5006 file.Write(code % {
5007 'name': func.name,
5008 'types': func.GetInfo('resource_types'),
5011 def WriteServiceUnitTest(self, func, file, *extras):
5012 """Overrriden from TypeHandler."""
5013 valid_test = """
5014 TEST_P(%(test_name)s, %(name)sValidArgs) {
5015 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5016 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5017 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5018 SpecializedSetup<cmds::%(name)s, 0>(true);
5019 cmds::%(name)s cmd;
5020 cmd.Init(%(args)s);
5021 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5022 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5023 if func.IsUnsafe():
5024 valid_test += """
5025 GLuint service_id;
5026 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5027 EXPECT_EQ(kNewServiceId, service_id)
5030 else:
5031 valid_test += """
5032 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5035 self.WriteValidUnitTest(func, file, valid_test, {
5036 'resource_name': func.GetInfo('resource_type'),
5037 }, *extras)
5038 invalid_test = """
5039 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5040 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5041 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5042 SpecializedSetup<cmds::%(name)s, 0>(false);
5043 cmds::%(name)s cmd;
5044 cmd.Init(%(args)s);
5045 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5048 self.WriteValidUnitTest(func, file, invalid_test, {
5049 'resource_name': func.GetInfo('resource_type').lower(),
5050 }, *extras)
5052 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5053 """Overrriden from TypeHandler."""
5054 valid_test = """
5055 TEST_P(%(test_name)s, %(name)sValidArgs) {
5056 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5057 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5058 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5059 GLuint temp = kNewClientId;
5060 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5061 if func.IsUnsafe():
5062 valid_test += """
5063 decoder_->set_unsafe_es3_apis_enabled(true);"""
5064 valid_test += """
5065 cmd->Init(1, &temp);
5066 EXPECT_EQ(error::kNoError,
5067 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5068 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5069 if func.IsUnsafe():
5070 valid_test += """
5071 GLuint service_id;
5072 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5073 EXPECT_EQ(kNewServiceId, service_id);
5074 decoder_->set_unsafe_es3_apis_enabled(false);
5075 EXPECT_EQ(error::kUnknownCommand,
5076 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5079 else:
5080 valid_test += """
5081 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5084 self.WriteValidUnitTest(func, file, valid_test, {
5085 'resource_name': func.GetInfo('resource_type'),
5086 }, *extras)
5087 invalid_test = """
5088 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5089 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5090 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5091 SpecializedSetup<cmds::%(name)s, 0>(false);
5092 cmd->Init(1, &client_%(resource_name)s_id_);"""
5093 if func.IsUnsafe():
5094 invalid_test += """
5095 decoder_->set_unsafe_es3_apis_enabled(true);
5096 EXPECT_EQ(error::kInvalidArguments,
5097 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5098 decoder_->set_unsafe_es3_apis_enabled(false);
5101 else:
5102 invalid_test += """
5103 EXPECT_EQ(error::kInvalidArguments,
5104 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5107 self.WriteValidUnitTest(func, file, invalid_test, {
5108 'resource_name': func.GetInfo('resource_type').lower(),
5109 }, *extras)
5111 def WriteImmediateCmdComputeSize(self, func, file):
5112 """Overrriden from TypeHandler."""
5113 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5114 file.Write(
5115 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5116 file.Write(" }\n")
5117 file.Write("\n")
5118 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5119 file.Write(" return static_cast<uint32_t>(\n")
5120 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5121 file.Write(" }\n")
5122 file.Write("\n")
5124 def WriteImmediateCmdSetHeader(self, func, file):
5125 """Overrriden from TypeHandler."""
5126 file.Write(" void SetHeader(GLsizei n) {\n")
5127 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5128 file.Write(" }\n")
5129 file.Write("\n")
5131 def WriteImmediateCmdInit(self, func, file):
5132 """Overrriden from TypeHandler."""
5133 last_arg = func.GetLastOriginalArg()
5134 file.Write(" void Init(%s, %s _%s) {\n" %
5135 (func.MakeTypedCmdArgString("_"),
5136 last_arg.type, last_arg.name))
5137 file.Write(" SetHeader(_n);\n")
5138 args = func.GetCmdArgs()
5139 for arg in args:
5140 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5141 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5142 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5143 file.Write(" }\n")
5144 file.Write("\n")
5146 def WriteImmediateCmdSet(self, func, file):
5147 """Overrriden from TypeHandler."""
5148 last_arg = func.GetLastOriginalArg()
5149 copy_args = func.MakeCmdArgString("_", False)
5150 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5151 (func.MakeTypedCmdArgString("_", True),
5152 last_arg.type, last_arg.name))
5153 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5154 (copy_args, last_arg.name))
5155 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5156 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5157 "cmd, size);\n")
5158 file.Write(" }\n")
5159 file.Write("\n")
5161 def WriteImmediateCmdHelper(self, func, file):
5162 """Overrriden from TypeHandler."""
5163 code = """ void %(name)s(%(typed_args)s) {
5164 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5165 gles2::cmds::%(name)s* c =
5166 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5167 if (c) {
5168 c->Init(%(args)s);
5173 file.Write(code % {
5174 "name": func.name,
5175 "typed_args": func.MakeTypedOriginalArgString(""),
5176 "args": func.MakeOriginalArgString(""),
5179 def WriteImmediateFormatTest(self, func, file):
5180 """Overrriden from TypeHandler."""
5181 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5182 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5183 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5184 (func.name, func.name))
5185 file.Write(" void* next_cmd = cmd.Set(\n")
5186 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5187 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5188 func.name)
5189 file.Write(" cmd.header.command);\n")
5190 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5191 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5192 file.Write(" cmd.header.size * 4u);\n")
5193 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5194 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5195 file.Write(" next_cmd, sizeof(cmd) +\n")
5196 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5197 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5198 file.Write("}\n")
5199 file.Write("\n")
5202 class CreateHandler(TypeHandler):
5203 """Handler for glCreate___ type functions."""
5205 def __init__(self):
5206 TypeHandler.__init__(self)
5208 def InitFunction(self, func):
5209 """Overrriden from TypeHandler."""
5210 func.AddCmdArg(Argument("client_id", 'uint32_t'))
5212 def __GetResourceType(self, func):
5213 if func.return_type == "GLsync":
5214 return "Sync"
5215 else:
5216 return func.name[6:] # Create*
5218 def WriteServiceUnitTest(self, func, file, *extras):
5219 """Overrriden from TypeHandler."""
5220 valid_test = """
5221 TEST_P(%(test_name)s, %(name)sValidArgs) {
5222 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5223 .WillOnce(Return(%(const_service_id)s));
5224 SpecializedSetup<cmds::%(name)s, 0>(true);
5225 cmds::%(name)s cmd;
5226 cmd.Init(%(args)s%(comma)skNewClientId);"""
5227 if func.IsUnsafe():
5228 valid_test += """
5229 decoder_->set_unsafe_es3_apis_enabled(true);"""
5230 valid_test += """
5231 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5232 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5233 if func.IsUnsafe():
5234 valid_test += """
5235 %(return_type)s service_id = 0;
5236 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
5237 EXPECT_EQ(%(const_service_id)s, service_id);
5238 decoder_->set_unsafe_es3_apis_enabled(false);
5239 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5242 else:
5243 valid_test += """
5244 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
5247 comma = ""
5248 cmd_arg_count = 0
5249 for arg in func.GetOriginalArgs():
5250 if not arg.IsConstant():
5251 cmd_arg_count += 1
5252 if cmd_arg_count:
5253 comma = ", "
5254 if func.return_type == 'GLsync':
5255 id_type_cast = ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
5256 "<GLsync>(kNewServiceId);\n ")
5257 const_service_id = "kNewServiceIdGLuint"
5258 else:
5259 id_type_cast = ""
5260 const_service_id = "kNewServiceId"
5261 self.WriteValidUnitTest(func, file, valid_test, {
5262 'comma': comma,
5263 'resource_type': self.__GetResourceType(func),
5264 'return_type': func.return_type,
5265 'id_type_cast': id_type_cast,
5266 'const_service_id': const_service_id,
5267 }, *extras)
5268 invalid_test = """
5269 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5270 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5271 SpecializedSetup<cmds::%(name)s, 0>(false);
5272 cmds::%(name)s cmd;
5273 cmd.Init(%(args)s%(comma)skNewClientId);
5274 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
5277 self.WriteInvalidUnitTest(func, file, invalid_test, {
5278 'comma': comma,
5279 }, *extras)
5281 def WriteHandlerImplementation (self, func, file):
5282 """Overrriden from TypeHandler."""
5283 if func.IsUnsafe():
5284 code = """ uint32_t client_id = c.client_id;
5285 %(return_type)s service_id = 0;
5286 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
5287 return error::kInvalidArguments;
5289 service_id = %(gl_func_name)s(%(gl_args)s);
5290 if (service_id) {
5291 group_->Add%(resource_name)sId(client_id, service_id);
5294 else:
5295 code = """ uint32_t client_id = c.client_id;
5296 if (Get%(resource_name)s(client_id)) {
5297 return error::kInvalidArguments;
5299 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
5300 if (service_id) {
5301 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
5304 file.Write(code % {
5305 'resource_name': self.__GetResourceType(func),
5306 'return_type': func.return_type,
5307 'gl_func_name': func.GetGLFunctionName(),
5308 'gl_args': func.MakeOriginalArgString(""),
5309 'gl_args_with_comma': func.MakeOriginalArgString("", True) })
5311 def WriteGLES2Implementation(self, func, file):
5312 """Overrriden from TypeHandler."""
5313 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5314 (func.return_type, func.original_name,
5315 func.MakeTypedOriginalArgString("")))
5316 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5317 func.WriteDestinationInitalizationValidation(file)
5318 self.WriteClientGLCallLog(func, file)
5319 for arg in func.GetOriginalArgs():
5320 arg.WriteClientSideValidationCode(file, func)
5321 file.Write(" GLuint client_id;\n")
5322 if func.return_type == "GLsync":
5323 file.Write(
5324 " GetIdHandler(id_namespaces::kSyncs)->\n")
5325 else:
5326 file.Write(
5327 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
5328 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
5329 file.Write(" helper_->%s(%s);\n" %
5330 (func.name, func.MakeCmdArgString("")))
5331 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
5332 file.Write(" CheckGLError();\n")
5333 if func.return_type == "GLsync":
5334 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
5335 else:
5336 file.Write(" return client_id;\n")
5337 file.Write("}\n")
5338 file.Write("\n")
5341 class DeleteHandler(TypeHandler):
5342 """Handler for glDelete___ single resource type functions."""
5344 def __init__(self):
5345 TypeHandler.__init__(self)
5347 def WriteServiceImplementation(self, func, file):
5348 """Overrriden from TypeHandler."""
5349 if func.IsUnsafe():
5350 TypeHandler.WriteServiceImplementation(self, func, file)
5351 # HandleDeleteShader and HandleDeleteProgram are manually written.
5352 pass
5354 def WriteGLES2Implementation(self, func, file):
5355 """Overrriden from TypeHandler."""
5356 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5357 (func.return_type, func.original_name,
5358 func.MakeTypedOriginalArgString("")))
5359 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5360 func.WriteDestinationInitalizationValidation(file)
5361 self.WriteClientGLCallLog(func, file)
5362 for arg in func.GetOriginalArgs():
5363 arg.WriteClientSideValidationCode(file, func)
5364 file.Write(
5365 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
5366 file.Write(" %sHelper(%s);\n" %
5367 (func.original_name, func.GetOriginalArgs()[-1].name))
5368 file.Write(" CheckGLError();\n")
5369 file.Write("}\n")
5370 file.Write("\n")
5372 def WriteHandlerImplementation (self, func, file):
5373 """Overrriden from TypeHandler."""
5374 assert len(func.GetOriginalArgs()) == 1
5375 arg = func.GetOriginalArgs()[0]
5376 if func.IsUnsafe():
5377 file.Write(""" %(arg_type)s service_id = 0;
5378 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
5379 glDelete%(resource_type)s(service_id);
5380 group_->Remove%(resource_type)sId(%(arg_name)s);
5381 } else {
5382 LOCAL_SET_GL_ERROR(
5383 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
5385 """ % { 'resource_type': func.GetInfo('resource_type'),
5386 'arg_name': arg.name,
5387 'arg_type': arg.type,
5388 'func_name': func.original_name })
5389 else:
5390 file.Write(" %sHelper(%s);\n" % (func.original_name, arg.name))
5392 class DELnHandler(TypeHandler):
5393 """Handler for glDelete___ type functions."""
5395 def __init__(self):
5396 TypeHandler.__init__(self)
5398 def WriteGetDataSizeCode(self, func, file):
5399 """Overrriden from TypeHandler."""
5400 code = """ uint32_t data_size;
5401 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5402 return error::kOutOfBounds;
5405 file.Write(code)
5407 def WriteGLES2ImplementationUnitTest(self, func, file):
5408 """Overrriden from TypeHandler."""
5409 code = """
5410 TEST_F(GLES2ImplementationTest, %(name)s) {
5411 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
5412 struct Cmds {
5413 cmds::%(name)sImmediate del;
5414 GLuint data[2];
5416 Cmds expected;
5417 expected.del.Init(arraysize(ids), &ids[0]);
5418 expected.data[0] = k%(types)sStartId;
5419 expected.data[1] = k%(types)sStartId + 1;
5420 gl_->%(name)s(arraysize(ids), &ids[0]);
5421 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5424 file.Write(code % {
5425 'name': func.name,
5426 'types': func.GetInfo('resource_types'),
5429 def WriteServiceUnitTest(self, func, file, *extras):
5430 """Overrriden from TypeHandler."""
5431 valid_test = """
5432 TEST_P(%(test_name)s, %(name)sValidArgs) {
5433 EXPECT_CALL(
5434 *gl_,
5435 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5436 .Times(1);
5437 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5438 SpecializedSetup<cmds::%(name)s, 0>(true);
5439 cmds::%(name)s cmd;
5440 cmd.Init(%(args)s);
5441 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5442 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5443 EXPECT_TRUE(
5444 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5447 self.WriteValidUnitTest(func, file, valid_test, {
5448 'resource_name': func.GetInfo('resource_type').lower(),
5449 'upper_resource_name': func.GetInfo('resource_type'),
5450 }, *extras)
5451 invalid_test = """
5452 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5453 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
5454 SpecializedSetup<cmds::%(name)s, 0>(false);
5455 cmds::%(name)s cmd;
5456 cmd.Init(%(args)s);
5457 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5460 self.WriteValidUnitTest(func, file, invalid_test, *extras)
5462 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5463 """Overrriden from TypeHandler."""
5464 valid_test = """
5465 TEST_P(%(test_name)s, %(name)sValidArgs) {
5466 EXPECT_CALL(
5467 *gl_,
5468 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5469 .Times(1);
5470 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5471 SpecializedSetup<cmds::%(name)s, 0>(true);
5472 cmd.Init(1, &client_%(resource_name)s_id_);"""
5473 if func.IsUnsafe():
5474 valid_test += """
5475 decoder_->set_unsafe_es3_apis_enabled(true);"""
5476 valid_test += """
5477 EXPECT_EQ(error::kNoError,
5478 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5479 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5480 if func.IsUnsafe():
5481 valid_test += """
5482 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
5483 client_%(resource_name)s_id_, NULL));
5484 decoder_->set_unsafe_es3_apis_enabled(false);
5485 EXPECT_EQ(error::kUnknownCommand,
5486 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5489 else:
5490 valid_test += """
5491 EXPECT_TRUE(
5492 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5495 self.WriteValidUnitTest(func, file, valid_test, {
5496 'resource_name': func.GetInfo('resource_type').lower(),
5497 'upper_resource_name': func.GetInfo('resource_type'),
5498 }, *extras)
5499 invalid_test = """
5500 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5501 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5502 SpecializedSetup<cmds::%(name)s, 0>(false);
5503 GLuint temp = kInvalidClientId;
5504 cmd.Init(1, &temp);"""
5505 if func.IsUnsafe():
5506 invalid_test += """
5507 decoder_->set_unsafe_es3_apis_enabled(true);
5508 EXPECT_EQ(error::kNoError,
5509 ExecuteImmediateCmd(cmd, sizeof(temp)));
5510 decoder_->set_unsafe_es3_apis_enabled(false);
5511 EXPECT_EQ(error::kUnknownCommand,
5512 ExecuteImmediateCmd(cmd, sizeof(temp)));
5515 else:
5516 invalid_test += """
5517 EXPECT_EQ(error::kNoError,
5518 ExecuteImmediateCmd(cmd, sizeof(temp)));
5521 self.WriteValidUnitTest(func, file, invalid_test, *extras)
5523 def WriteHandlerImplementation (self, func, file):
5524 """Overrriden from TypeHandler."""
5525 file.Write(" %sHelper(n, %s);\n" %
5526 (func.name, func.GetLastOriginalArg().name))
5528 def WriteImmediateHandlerImplementation (self, func, file):
5529 """Overrriden from TypeHandler."""
5530 if func.IsUnsafe():
5531 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5532 GLuint service_id = 0;
5533 if (group_->Get%(resource_type)sServiceId(
5534 %(last_arg_name)s[ii], &service_id)) {
5535 glDelete%(resource_type)ss(1, &service_id);
5536 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
5539 """ % { 'resource_type': func.GetInfo('resource_type'),
5540 'last_arg_name': func.GetLastOriginalArg().name })
5541 else:
5542 file.Write(" %sHelper(n, %s);\n" %
5543 (func.original_name, func.GetLastOriginalArg().name))
5545 def WriteGLES2Implementation(self, func, file):
5546 """Overrriden from TypeHandler."""
5547 impl_decl = func.GetInfo('impl_decl')
5548 if impl_decl == None or impl_decl == True:
5549 args = {
5550 'return_type': func.return_type,
5551 'name': func.original_name,
5552 'typed_args': func.MakeTypedOriginalArgString(""),
5553 'args': func.MakeOriginalArgString(""),
5554 'resource_type': func.GetInfo('resource_type').lower(),
5555 'count_name': func.GetOriginalArgs()[0].name,
5557 file.Write(
5558 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5559 args)
5560 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5561 func.WriteDestinationInitalizationValidation(file)
5562 self.WriteClientGLCallLog(func, file)
5563 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5564 for (GLsizei i = 0; i < n; ++i) {
5565 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5568 """ % func.GetOriginalArgs()[1].name)
5569 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
5570 for (GLsizei i = 0; i < n; ++i) {
5571 DCHECK(%s[i] != 0);
5574 """ % func.GetOriginalArgs()[1].name)
5575 for arg in func.GetOriginalArgs():
5576 arg.WriteClientSideValidationCode(file, func)
5577 code = """ %(name)sHelper(%(args)s);
5578 CheckGLError();
5582 file.Write(code % args)
5584 def WriteImmediateCmdComputeSize(self, func, file):
5585 """Overrriden from TypeHandler."""
5586 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5587 file.Write(
5588 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5589 file.Write(" }\n")
5590 file.Write("\n")
5591 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5592 file.Write(" return static_cast<uint32_t>(\n")
5593 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5594 file.Write(" }\n")
5595 file.Write("\n")
5597 def WriteImmediateCmdSetHeader(self, func, file):
5598 """Overrriden from TypeHandler."""
5599 file.Write(" void SetHeader(GLsizei n) {\n")
5600 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5601 file.Write(" }\n")
5602 file.Write("\n")
5604 def WriteImmediateCmdInit(self, func, file):
5605 """Overrriden from TypeHandler."""
5606 last_arg = func.GetLastOriginalArg()
5607 file.Write(" void Init(%s, %s _%s) {\n" %
5608 (func.MakeTypedCmdArgString("_"),
5609 last_arg.type, last_arg.name))
5610 file.Write(" SetHeader(_n);\n")
5611 args = func.GetCmdArgs()
5612 for arg in args:
5613 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5614 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5615 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5616 file.Write(" }\n")
5617 file.Write("\n")
5619 def WriteImmediateCmdSet(self, func, file):
5620 """Overrriden from TypeHandler."""
5621 last_arg = func.GetLastOriginalArg()
5622 copy_args = func.MakeCmdArgString("_", False)
5623 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5624 (func.MakeTypedCmdArgString("_", True),
5625 last_arg.type, last_arg.name))
5626 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5627 (copy_args, last_arg.name))
5628 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5629 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5630 "cmd, size);\n")
5631 file.Write(" }\n")
5632 file.Write("\n")
5634 def WriteImmediateCmdHelper(self, func, file):
5635 """Overrriden from TypeHandler."""
5636 code = """ void %(name)s(%(typed_args)s) {
5637 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5638 gles2::cmds::%(name)s* c =
5639 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5640 if (c) {
5641 c->Init(%(args)s);
5646 file.Write(code % {
5647 "name": func.name,
5648 "typed_args": func.MakeTypedOriginalArgString(""),
5649 "args": func.MakeOriginalArgString(""),
5652 def WriteImmediateFormatTest(self, func, file):
5653 """Overrriden from TypeHandler."""
5654 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5655 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5656 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5657 (func.name, func.name))
5658 file.Write(" void* next_cmd = cmd.Set(\n")
5659 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5660 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5661 func.name)
5662 file.Write(" cmd.header.command);\n")
5663 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5664 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5665 file.Write(" cmd.header.size * 4u);\n")
5666 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5667 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5668 file.Write(" next_cmd, sizeof(cmd) +\n")
5669 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5670 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5671 file.Write("}\n")
5672 file.Write("\n")
5675 class GETnHandler(TypeHandler):
5676 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
5678 def __init__(self):
5679 TypeHandler.__init__(self)
5681 def NeedsDataTransferFunction(self, func):
5682 """Overriden from TypeHandler."""
5683 return False
5685 def WriteServiceImplementation(self, func, file):
5686 """Overrriden from TypeHandler."""
5687 self.WriteServiceHandlerFunctionHeader(func, file)
5688 last_arg = func.GetLastOriginalArg()
5689 # All except shm_id and shm_offset.
5690 all_but_last_args = func.GetCmdArgs()[:-2]
5691 for arg in all_but_last_args:
5692 arg.WriteGetCode(file)
5694 code = """ typedef cmds::%(func_name)s::Result Result;
5695 GLsizei num_values = 0;
5696 GetNumValuesReturnedForGLGet(pname, &num_values);
5697 Result* result = GetSharedMemoryAs<Result*>(
5698 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
5699 Result::ComputeSize(num_values));
5700 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
5702 file.Write(code % {
5703 'last_arg_type': last_arg.type,
5704 'last_arg_name': last_arg.name,
5705 'func_name': func.name,
5707 func.WriteHandlerValidation(file)
5708 code = """ // Check that the client initialized the result.
5709 if (result->size != 0) {
5710 return error::kInvalidArguments;
5713 shadowed = func.GetInfo('shadowed')
5714 if not shadowed:
5715 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
5716 file.Write(code)
5717 func.WriteHandlerImplementation(file)
5718 if shadowed:
5719 code = """ result->SetNumResults(num_values);
5720 return error::kNoError;
5723 else:
5724 code = """ GLenum error = glGetError();
5725 if (error == GL_NO_ERROR) {
5726 result->SetNumResults(num_values);
5727 } else {
5728 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
5730 return error::kNoError;
5734 file.Write(code % {'func_name': func.name})
5736 def WriteGLES2Implementation(self, func, file):
5737 """Overrriden from TypeHandler."""
5738 impl_decl = func.GetInfo('impl_decl')
5739 if impl_decl == None or impl_decl == True:
5740 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5741 (func.return_type, func.original_name,
5742 func.MakeTypedOriginalArgString("")))
5743 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5744 func.WriteDestinationInitalizationValidation(file)
5745 self.WriteClientGLCallLog(func, file)
5746 for arg in func.GetOriginalArgs():
5747 arg.WriteClientSideValidationCode(file, func)
5748 all_but_last_args = func.GetOriginalArgs()[:-1]
5749 args = []
5750 has_length_arg = False
5751 for arg in all_but_last_args:
5752 if arg.type == 'GLsync':
5753 args.append('ToGLuint(%s)' % arg.name)
5754 elif arg.name.endswith('size') and arg.type == 'GLsizei':
5755 continue
5756 elif arg.name == 'length':
5757 has_length_arg = True
5758 continue
5759 else:
5760 args.append(arg.name)
5761 arg_string = ", ".join(args)
5762 all_arg_string = (
5763 ", ".join([
5764 "%s" % arg.name
5765 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
5766 self.WriteTraceEvent(func, file)
5767 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
5768 return;
5770 typedef cmds::%(func_name)s::Result Result;
5771 Result* result = GetResultAs<Result*>();
5772 if (!result) {
5773 return;
5775 result->SetNumResults(0);
5776 helper_->%(func_name)s(%(arg_string)s,
5777 GetResultShmId(), GetResultShmOffset());
5778 WaitForCmd();
5779 result->CopyResult(%(last_arg_name)s);
5780 GPU_CLIENT_LOG_CODE_BLOCK({
5781 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
5782 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
5784 });"""
5785 if has_length_arg:
5786 code += """
5787 if (length) {
5788 *length = result->GetNumResults();
5789 }"""
5790 code += """
5791 CheckGLError();
5794 file.Write(code % {
5795 'func_name': func.name,
5796 'arg_string': arg_string,
5797 'all_arg_string': all_arg_string,
5798 'last_arg_name': func.GetLastOriginalArg().name,
5801 def WriteGLES2ImplementationUnitTest(self, func, file):
5802 """Writes the GLES2 Implemention unit test."""
5803 code = """
5804 TEST_F(GLES2ImplementationTest, %(name)s) {
5805 struct Cmds {
5806 cmds::%(name)s cmd;
5808 typedef cmds::%(name)s::Result Result;
5809 Result::Type result = 0;
5810 Cmds expected;
5811 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
5812 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
5813 EXPECT_CALL(*command_buffer(), OnFlush())
5814 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
5815 .RetiresOnSaturation();
5816 gl_->%(name)s(%(args)s, &result);
5817 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5818 EXPECT_EQ(static_cast<Result::Type>(1), result);
5821 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
5822 if not first_cmd_arg:
5823 return
5825 first_gl_arg = func.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
5826 func)
5828 cmd_arg_strings = [first_cmd_arg]
5829 for arg in func.GetCmdArgs()[1:-2]:
5830 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
5831 gl_arg_strings = [first_gl_arg]
5832 for arg in func.GetOriginalArgs()[1:-1]:
5833 gl_arg_strings.append(arg.GetValidClientSideArg(func))
5835 file.Write(code % {
5836 'name': func.name,
5837 'args': ", ".join(gl_arg_strings),
5838 'cmd_args': ", ".join(cmd_arg_strings),
5841 def WriteServiceUnitTest(self, func, file, *extras):
5842 """Overrriden from TypeHandler."""
5843 valid_test = """
5844 TEST_P(%(test_name)s, %(name)sValidArgs) {
5845 EXPECT_CALL(*gl_, GetError())
5846 .WillOnce(Return(GL_NO_ERROR))
5847 .WillOnce(Return(GL_NO_ERROR))
5848 .RetiresOnSaturation();
5849 SpecializedSetup<cmds::%(name)s, 0>(true);
5850 typedef cmds::%(name)s::Result Result;
5851 Result* result = static_cast<Result*>(shared_memory_address_);
5852 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
5853 result->size = 0;
5854 cmds::%(name)s cmd;
5855 cmd.Init(%(cmd_args)s);"""
5856 if func.IsUnsafe():
5857 valid_test += """
5858 decoder_->set_unsafe_es3_apis_enabled(true);"""
5859 valid_test += """
5860 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5861 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
5862 %(valid_pname)s),
5863 result->GetNumResults());
5864 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5865 if func.IsUnsafe():
5866 valid_test += """
5867 decoder_->set_unsafe_es3_apis_enabled(false);
5868 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
5869 valid_test += """
5872 gl_arg_strings = []
5873 cmd_arg_strings = []
5874 valid_pname = ''
5875 for arg in func.GetOriginalArgs()[:-1]:
5876 if arg.name == 'length':
5877 gl_arg_value = 'nullptr'
5878 elif arg.name.endswith('size'):
5879 gl_arg_value = ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
5880 valid_pname)
5881 elif arg.type == 'GLsync':
5882 gl_arg_value = 'reinterpret_cast<GLsync>(kServiceSyncId)'
5883 else:
5884 gl_arg_value = arg.GetValidGLArg(func)
5885 gl_arg_strings.append(gl_arg_value)
5886 if arg.name == 'pname':
5887 valid_pname = gl_arg_value
5888 if arg.name.endswith('size') or arg.name == 'length':
5889 continue
5890 if arg.type == 'GLsync':
5891 arg_value = 'client_sync_id_'
5892 else:
5893 arg_value = arg.GetValidArg(func)
5894 cmd_arg_strings.append(arg_value)
5895 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
5896 gl_arg_strings.append("_")
5897 else:
5898 gl_arg_strings.append("result->GetData()")
5899 cmd_arg_strings.append("shared_memory_id_")
5900 cmd_arg_strings.append("shared_memory_offset_")
5902 self.WriteValidUnitTest(func, file, valid_test, {
5903 'local_gl_args': ", ".join(gl_arg_strings),
5904 'cmd_args': ", ".join(cmd_arg_strings),
5905 'valid_pname': valid_pname,
5906 }, *extras)
5908 if not func.IsUnsafe():
5909 invalid_test = """
5910 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5911 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5912 SpecializedSetup<cmds::%(name)s, 0>(false);
5913 cmds::%(name)s::Result* result =
5914 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
5915 result->size = 0;
5916 cmds::%(name)s cmd;
5917 cmd.Init(%(args)s);
5918 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
5919 EXPECT_EQ(0u, result->size);%(gl_error_test)s
5922 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
5924 class ArrayArgTypeHandler(TypeHandler):
5925 """Base class for type handlers that handle args that are arrays"""
5927 def __init__(self):
5928 TypeHandler.__init__(self)
5930 def GetArrayType(self, func):
5931 """Returns the type of the element in the element array being PUT to."""
5932 for arg in func.GetOriginalArgs():
5933 if arg.IsPointer():
5934 element_type = arg.GetPointedType()
5935 return element_type
5937 # Special case: array type handler is used for a function that is forwarded
5938 # to the actual array type implementation
5939 element_type = func.GetOriginalArgs()[-1].type
5940 assert all(arg.type == element_type \
5941 for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
5942 return element_type
5944 def GetArrayCount(self, func):
5945 """Returns the count of the elements in the array being PUT to."""
5946 return func.GetInfo('count')
5948 class PUTHandler(ArrayArgTypeHandler):
5949 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
5951 def __init__(self):
5952 ArrayArgTypeHandler.__init__(self)
5954 def WriteServiceUnitTest(self, func, file, *extras):
5955 """Writes the service unit test for a command."""
5956 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
5957 if func.GetInfo("first_element_only"):
5958 gl_arg_strings = [
5959 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
5961 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
5962 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
5963 ", ".join(gl_arg_strings))
5964 valid_test = """
5965 TEST_P(%(test_name)s, %(name)sValidArgs) {
5966 SpecializedSetup<cmds::%(name)s, 0>(true);
5967 cmds::%(name)s cmd;
5968 cmd.Init(%(args)s);
5969 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
5970 %(expected_call)s
5971 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5972 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5975 extra = {
5976 'data_type': self.GetArrayType(func),
5977 'data_value': func.GetInfo('data_value') or '0',
5978 'expected_call': expected_call,
5980 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
5982 invalid_test = """
5983 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5984 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5985 SpecializedSetup<cmds::%(name)s, 0>(false);
5986 cmds::%(name)s cmd;
5987 cmd.Init(%(args)s);
5988 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
5989 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5992 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
5994 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5995 """Writes the service unit test for a command."""
5996 valid_test = """
5997 TEST_P(%(test_name)s, %(name)sValidArgs) {
5998 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5999 SpecializedSetup<cmds::%(name)s, 0>(true);
6000 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6001 cmd.Init(%(gl_args)s, &temp[0]);
6002 EXPECT_CALL(
6003 *gl_,
6004 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6005 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6006 if func.IsUnsafe():
6007 valid_test += """
6008 decoder_->set_unsafe_es3_apis_enabled(true);"""
6009 valid_test += """
6010 EXPECT_EQ(error::kNoError,
6011 ExecuteImmediateCmd(cmd, sizeof(temp)));
6012 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6013 if func.IsUnsafe():
6014 valid_test += """
6015 decoder_->set_unsafe_es3_apis_enabled(false);
6016 EXPECT_EQ(error::kUnknownCommand,
6017 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6018 valid_test += """
6021 gl_arg_strings = [
6022 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
6024 gl_any_strings = ["_"] * len(gl_arg_strings)
6026 extra = {
6027 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
6028 'data_type': self.GetArrayType(func),
6029 'data_count': self.GetArrayCount(func),
6030 'data_value': func.GetInfo('data_value') or '0',
6031 'gl_args': ", ".join(gl_arg_strings),
6032 'gl_any_args': ", ".join(gl_any_strings),
6034 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6036 invalid_test = """
6037 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6038 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6039 if func.IsUnsafe():
6040 invalid_test += """
6041 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6043 else:
6044 invalid_test += """
6045 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6047 invalid_test += """
6048 SpecializedSetup<cmds::%(name)s, 0>(false);
6049 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6050 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6051 if func.IsUnsafe():
6052 invalid_test += """
6053 decoder_->set_unsafe_es3_apis_enabled(true);
6054 EXPECT_EQ(error::%(parse_result)s,
6055 ExecuteImmediateCmd(cmd, sizeof(temp)));
6056 decoder_->set_unsafe_es3_apis_enabled(false);
6059 else:
6060 invalid_test += """
6061 EXPECT_EQ(error::%(parse_result)s,
6062 ExecuteImmediateCmd(cmd, sizeof(temp)));
6063 %(gl_error_test)s
6066 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6068 def WriteGetDataSizeCode(self, func, file):
6069 """Overrriden from TypeHandler."""
6070 code = """ uint32_t data_size;
6071 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6072 return error::kOutOfBounds;
6075 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6076 if func.IsImmediate():
6077 file.Write(" if (data_size > immediate_data_size) {\n")
6078 file.Write(" return error::kOutOfBounds;\n")
6079 file.Write(" }\n")
6081 def __NeedsToCalcDataCount(self, func):
6082 use_count_func = func.GetInfo('use_count_func')
6083 return use_count_func != None and use_count_func != False
6085 def WriteGLES2Implementation(self, func, file):
6086 """Overrriden from TypeHandler."""
6087 impl_func = func.GetInfo('impl_func')
6088 if (impl_func != None and impl_func != True):
6089 return;
6090 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6091 (func.return_type, func.original_name,
6092 func.MakeTypedOriginalArgString("")))
6093 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6094 func.WriteDestinationInitalizationValidation(file)
6095 self.WriteClientGLCallLog(func, file)
6097 if self.__NeedsToCalcDataCount(func):
6098 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6099 (func.name, func.GetOriginalArgs()[0].name))
6100 file.Write(" DCHECK_LE(count, %du);\n" % self.GetArrayCount(func))
6101 else:
6102 file.Write(" size_t count = %d;" % self.GetArrayCount(func))
6103 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
6104 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6105 func.GetLastOriginalArg().name)
6106 for arg in func.GetOriginalArgs():
6107 arg.WriteClientSideValidationCode(file, func)
6108 file.Write(" helper_->%sImmediate(%s);\n" %
6109 (func.name, func.MakeOriginalArgString("")))
6110 file.Write(" CheckGLError();\n")
6111 file.Write("}\n")
6112 file.Write("\n")
6114 def WriteGLES2ImplementationUnitTest(self, func, file):
6115 """Writes the GLES2 Implemention unit test."""
6116 client_test = func.GetInfo('client_test')
6117 if (client_test != None and client_test != True):
6118 return;
6119 code = """
6120 TEST_F(GLES2ImplementationTest, %(name)s) {
6121 %(type)s data[%(count)d] = {0};
6122 struct Cmds {
6123 cmds::%(name)sImmediate cmd;
6124 %(type)s data[%(count)d];
6127 for (int jj = 0; jj < %(count)d; ++jj) {
6128 data[jj] = static_cast<%(type)s>(jj);
6130 Cmds expected;
6131 expected.cmd.Init(%(cmd_args)s, &data[0]);
6132 gl_->%(name)s(%(args)s, &data[0]);
6133 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6136 cmd_arg_strings = [
6137 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
6139 gl_arg_strings = [
6140 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
6143 file.Write(code % {
6144 'name': func.name,
6145 'type': self.GetArrayType(func),
6146 'count': self.GetArrayCount(func),
6147 'args': ", ".join(gl_arg_strings),
6148 'cmd_args': ", ".join(cmd_arg_strings),
6151 def WriteImmediateCmdComputeSize(self, func, file):
6152 """Overrriden from TypeHandler."""
6153 file.Write(" static uint32_t ComputeDataSize() {\n")
6154 file.Write(" return static_cast<uint32_t>(\n")
6155 file.Write(" sizeof(%s) * %d);\n" %
6156 (self.GetArrayType(func), self.GetArrayCount(func)))
6157 file.Write(" }\n")
6158 file.Write("\n")
6159 if self.__NeedsToCalcDataCount(func):
6160 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6161 (func.GetOriginalArgs()[0].type,
6162 func.GetOriginalArgs()[0].name))
6163 file.Write(" return static_cast<uint32_t>(\n")
6164 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6165 (self.GetArrayType(func), func.original_name,
6166 func.GetOriginalArgs()[0].name))
6167 file.Write(" }\n")
6168 file.Write("\n")
6169 file.Write(" static uint32_t ComputeSize() {\n")
6170 file.Write(" return static_cast<uint32_t>(\n")
6171 file.Write(
6172 " sizeof(ValueType) + ComputeDataSize());\n")
6173 file.Write(" }\n")
6174 file.Write("\n")
6176 def WriteImmediateCmdSetHeader(self, func, file):
6177 """Overrriden from TypeHandler."""
6178 file.Write(" void SetHeader() {\n")
6179 file.Write(
6180 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6181 file.Write(" }\n")
6182 file.Write("\n")
6184 def WriteImmediateCmdInit(self, func, file):
6185 """Overrriden from TypeHandler."""
6186 last_arg = func.GetLastOriginalArg()
6187 file.Write(" void Init(%s, %s _%s) {\n" %
6188 (func.MakeTypedCmdArgString("_"),
6189 last_arg.type, last_arg.name))
6190 file.Write(" SetHeader();\n")
6191 args = func.GetCmdArgs()
6192 for arg in args:
6193 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6194 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6195 if self.__NeedsToCalcDataCount(func):
6196 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
6197 (last_arg.name, func.GetOriginalArgs()[0].name))
6198 file.Write("""
6199 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6200 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6201 ComputeEffectiveDataSize(%(arg)s);
6202 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6203 """ % { 'arg': func.GetOriginalArgs()[0].name, })
6204 else:
6205 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
6206 file.Write(" }\n")
6207 file.Write("\n")
6209 def WriteImmediateCmdSet(self, func, file):
6210 """Overrriden from TypeHandler."""
6211 last_arg = func.GetLastOriginalArg()
6212 copy_args = func.MakeCmdArgString("_", False)
6213 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6214 (func.MakeTypedCmdArgString("_", True),
6215 last_arg.type, last_arg.name))
6216 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6217 (copy_args, last_arg.name))
6218 file.Write(" const uint32_t size = ComputeSize();\n")
6219 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6220 "cmd, size);\n")
6221 file.Write(" }\n")
6222 file.Write("\n")
6224 def WriteImmediateCmdHelper(self, func, file):
6225 """Overrriden from TypeHandler."""
6226 code = """ void %(name)s(%(typed_args)s) {
6227 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
6228 gles2::cmds::%(name)s* c =
6229 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6230 if (c) {
6231 c->Init(%(args)s);
6236 file.Write(code % {
6237 "name": func.name,
6238 "typed_args": func.MakeTypedOriginalArgString(""),
6239 "args": func.MakeOriginalArgString(""),
6242 def WriteImmediateFormatTest(self, func, file):
6243 """Overrriden from TypeHandler."""
6244 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6245 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6246 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
6247 for v in range(0, self.GetArrayCount(func)):
6248 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6249 (self.GetArrayType(func), v))
6250 file.Write(" };\n")
6251 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6252 (func.name, func.name))
6253 file.Write(" void* next_cmd = cmd.Set(\n")
6254 file.Write(" &cmd")
6255 args = func.GetCmdArgs()
6256 for value, arg in enumerate(args):
6257 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
6258 file.Write(",\n data);\n")
6259 args = func.GetCmdArgs()
6260 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
6261 % func.name)
6262 file.Write(" cmd.header.command);\n")
6263 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6264 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
6265 file.Write(" cmd.header.size * 4u);\n")
6266 for value, arg in enumerate(args):
6267 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6268 (arg.type, value + 11, arg.name))
6269 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6270 file.Write(" next_cmd, sizeof(cmd) +\n")
6271 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6272 file.Write(" // TODO(gman): Check that data was inserted;\n")
6273 file.Write("}\n")
6274 file.Write("\n")
6277 class PUTnHandler(ArrayArgTypeHandler):
6278 """Handler for PUTn 'glUniform__v' type functions."""
6280 def __init__(self):
6281 ArrayArgTypeHandler.__init__(self)
6283 def WriteServiceUnitTest(self, func, file, *extras):
6284 """Overridden from TypeHandler."""
6285 ArrayArgTypeHandler.WriteServiceUnitTest(self, func, file, *extras)
6287 valid_test = """
6288 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
6289 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6290 SpecializedSetup<cmds::%(name)s, 0>(true);
6291 cmds::%(name)s cmd;
6292 cmd.Init(%(args)s);
6293 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6294 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6297 gl_arg_strings = []
6298 arg_strings = []
6299 for count, arg in enumerate(func.GetOriginalArgs()):
6300 # hardcoded to match unit tests.
6301 if count == 0:
6302 # the location of the second element of the 2nd uniform.
6303 # defined in GLES2DecoderBase::SetupShaderForUniform
6304 gl_arg_strings.append("3")
6305 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
6306 elif count == 1:
6307 # the number of elements that gl will be called with.
6308 gl_arg_strings.append("3")
6309 # the number of elements requested in the command.
6310 arg_strings.append("5")
6311 else:
6312 gl_arg_strings.append(arg.GetValidGLArg(func))
6313 if not arg.IsConstant():
6314 arg_strings.append(arg.GetValidArg(func))
6315 extra = {
6316 'gl_args': ", ".join(gl_arg_strings),
6317 'args': ", ".join(arg_strings),
6319 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6321 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6322 """Overridden from TypeHandler."""
6323 valid_test = """
6324 TEST_P(%(test_name)s, %(name)sValidArgs) {
6325 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6326 EXPECT_CALL(
6327 *gl_,
6328 %(gl_func_name)s(%(gl_args)s,
6329 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
6330 SpecializedSetup<cmds::%(name)s, 0>(true);
6331 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6332 cmd.Init(%(args)s, &temp[0]);"""
6333 if func.IsUnsafe():
6334 valid_test += """
6335 decoder_->set_unsafe_es3_apis_enabled(true);"""
6336 valid_test += """
6337 EXPECT_EQ(error::kNoError,
6338 ExecuteImmediateCmd(cmd, sizeof(temp)));
6339 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6340 if func.IsUnsafe():
6341 valid_test += """
6342 decoder_->set_unsafe_es3_apis_enabled(false);
6343 EXPECT_EQ(error::kUnknownCommand,
6344 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6345 valid_test += """
6348 gl_arg_strings = []
6349 gl_any_strings = []
6350 arg_strings = []
6351 for arg in func.GetOriginalArgs()[0:-1]:
6352 gl_arg_strings.append(arg.GetValidGLArg(func))
6353 gl_any_strings.append("_")
6354 if not arg.IsConstant():
6355 arg_strings.append(arg.GetValidArg(func))
6356 extra = {
6357 'data_type': self.GetArrayType(func),
6358 'data_count': self.GetArrayCount(func),
6359 'args': ", ".join(arg_strings),
6360 'gl_args': ", ".join(gl_arg_strings),
6361 'gl_any_args': ", ".join(gl_any_strings),
6363 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6365 invalid_test = """
6366 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6367 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6368 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6369 SpecializedSetup<cmds::%(name)s, 0>(false);
6370 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6371 cmd.Init(%(all_but_last_args)s, &temp[0]);
6372 EXPECT_EQ(error::%(parse_result)s,
6373 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
6376 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6378 def WriteGetDataSizeCode(self, func, file):
6379 """Overrriden from TypeHandler."""
6380 code = """ uint32_t data_size;
6381 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
6382 return error::kOutOfBounds;
6385 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6386 if func.IsImmediate():
6387 file.Write(" if (data_size > immediate_data_size) {\n")
6388 file.Write(" return error::kOutOfBounds;\n")
6389 file.Write(" }\n")
6391 def WriteGLES2Implementation(self, func, file):
6392 """Overrriden from TypeHandler."""
6393 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6394 (func.return_type, func.original_name,
6395 func.MakeTypedOriginalArgString("")))
6396 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6397 func.WriteDestinationInitalizationValidation(file)
6398 self.WriteClientGLCallLog(func, file)
6399 last_pointer_name = func.GetLastOriginalPointerArg().name
6400 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6401 for (GLsizei i = 0; i < count; ++i) {
6402 """)
6403 values_str = ' << ", " << '.join(
6404 ["%s[%d + i * %d]" % (
6405 last_pointer_name, ndx, self.GetArrayCount(func)) for ndx in range(
6406 0, self.GetArrayCount(func))])
6407 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
6408 file.Write(" }\n });\n")
6409 for arg in func.GetOriginalArgs():
6410 arg.WriteClientSideValidationCode(file, func)
6411 file.Write(" helper_->%sImmediate(%s);\n" %
6412 (func.name, func.MakeInitString("")))
6413 file.Write(" CheckGLError();\n")
6414 file.Write("}\n")
6415 file.Write("\n")
6417 def WriteGLES2ImplementationUnitTest(self, func, file):
6418 """Writes the GLES2 Implemention unit test."""
6419 code = """
6420 TEST_F(GLES2ImplementationTest, %(name)s) {
6421 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6422 struct Cmds {
6423 cmds::%(name)sImmediate cmd;
6424 %(type)s data[%(count_param)d][%(count)d];
6427 Cmds expected;
6428 for (int ii = 0; ii < %(count_param)d; ++ii) {
6429 for (int jj = 0; jj < %(count)d; ++jj) {
6430 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6433 expected.cmd.Init(%(cmd_args)s);
6434 gl_->%(name)s(%(args)s);
6435 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6438 cmd_arg_strings = []
6439 for arg in func.GetCmdArgs():
6440 if arg.name.endswith("_shm_id"):
6441 cmd_arg_strings.append("&data[0][0]")
6442 elif arg.name.endswith("_shm_offset"):
6443 continue
6444 else:
6445 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6446 gl_arg_strings = []
6447 count_param = 0
6448 for arg in func.GetOriginalArgs():
6449 if arg.IsPointer():
6450 valid_value = "&data[0][0]"
6451 else:
6452 valid_value = arg.GetValidClientSideArg(func)
6453 gl_arg_strings.append(valid_value)
6454 if arg.name == "count":
6455 count_param = int(valid_value)
6456 file.Write(code % {
6457 'name': func.name,
6458 'type': self.GetArrayType(func),
6459 'count': self.GetArrayCount(func),
6460 'args': ", ".join(gl_arg_strings),
6461 'cmd_args': ", ".join(cmd_arg_strings),
6462 'count_param': count_param,
6465 # Test constants for invalid values, as they are not tested by the
6466 # service.
6467 constants = [
6468 arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
6470 if not constants:
6471 return
6473 code = """
6474 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
6475 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6476 for (int ii = 0; ii < %(count_param)d; ++ii) {
6477 for (int jj = 0; jj < %(count)d; ++jj) {
6478 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6481 gl_->%(name)s(%(args)s);
6482 EXPECT_TRUE(NoCommandsWritten());
6483 EXPECT_EQ(%(gl_error)s, CheckError());
6486 for invalid_arg in constants:
6487 gl_arg_strings = []
6488 invalid = invalid_arg.GetInvalidArg(func)
6489 for arg in func.GetOriginalArgs():
6490 if arg is invalid_arg:
6491 gl_arg_strings.append(invalid[0])
6492 elif arg.IsPointer():
6493 gl_arg_strings.append("&data[0][0]")
6494 else:
6495 valid_value = arg.GetValidClientSideArg(func)
6496 gl_arg_strings.append(valid_value)
6497 if arg.name == "count":
6498 count_param = int(valid_value)
6500 file.Write(code % {
6501 'name': func.name,
6502 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
6503 'type': self.GetArrayType(func),
6504 'count': self.GetArrayCount(func),
6505 'args': ", ".join(gl_arg_strings),
6506 'gl_error': invalid[2],
6507 'count_param': count_param,
6511 def WriteImmediateCmdComputeSize(self, func, file):
6512 """Overrriden from TypeHandler."""
6513 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
6514 file.Write(" return static_cast<uint32_t>(\n")
6515 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
6516 (self.GetArrayType(func), self.GetArrayCount(func)))
6517 file.Write(" }\n")
6518 file.Write("\n")
6519 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
6520 file.Write(" return static_cast<uint32_t>(\n")
6521 file.Write(
6522 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
6523 file.Write(" }\n")
6524 file.Write("\n")
6526 def WriteImmediateCmdSetHeader(self, func, file):
6527 """Overrriden from TypeHandler."""
6528 file.Write(" void SetHeader(GLsizei count) {\n")
6529 file.Write(
6530 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
6531 file.Write(" }\n")
6532 file.Write("\n")
6534 def WriteImmediateCmdInit(self, func, file):
6535 """Overrriden from TypeHandler."""
6536 file.Write(" void Init(%s) {\n" %
6537 func.MakeTypedInitString("_"))
6538 file.Write(" SetHeader(_count);\n")
6539 args = func.GetCmdArgs()
6540 for arg in args:
6541 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6542 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6543 pointer_arg = func.GetLastOriginalPointerArg()
6544 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg.name)
6545 file.Write(" }\n")
6546 file.Write("\n")
6548 def WriteImmediateCmdSet(self, func, file):
6549 """Overrriden from TypeHandler."""
6550 file.Write(" void* Set(void* cmd%s) {\n" %
6551 func.MakeTypedInitString("_", True))
6552 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
6553 func.MakeInitString("_"))
6554 file.Write(" const uint32_t size = ComputeSize(_count);\n")
6555 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6556 "cmd, size);\n")
6557 file.Write(" }\n")
6558 file.Write("\n")
6560 def WriteImmediateCmdHelper(self, func, file):
6561 """Overrriden from TypeHandler."""
6562 code = """ void %(name)s(%(typed_args)s) {
6563 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
6564 gles2::cmds::%(name)s* c =
6565 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6566 if (c) {
6567 c->Init(%(args)s);
6572 file.Write(code % {
6573 "name": func.name,
6574 "typed_args": func.MakeTypedInitString(""),
6575 "args": func.MakeInitString("")
6578 def WriteImmediateFormatTest(self, func, file):
6579 """Overrriden from TypeHandler."""
6580 args = func.GetOriginalArgs()
6581 count_param = 0
6582 for arg in args:
6583 if arg.name == "count":
6584 count_param = int(arg.GetValidClientSideCmdArg(func))
6585 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6586 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6587 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
6588 for v in range(0, self.GetArrayCount(func) * count_param):
6589 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6590 (self.GetArrayType(func), v))
6591 file.Write(" };\n")
6592 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6593 (func.name, func.name))
6594 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
6595 file.Write(" const size_t kExpectedCmdSize =\n")
6596 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
6597 (self.GetArrayType(func), self.GetArrayCount(func)))
6598 file.Write(" void* next_cmd = cmd.Set(\n")
6599 file.Write(" &cmd")
6600 for value, arg in enumerate(args):
6601 if arg.IsPointer():
6602 file.Write(",\n data")
6603 elif arg.IsConstant():
6604 continue
6605 else:
6606 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
6607 file.Write(");\n")
6608 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6609 func.name)
6610 file.Write(" cmd.header.command);\n")
6611 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
6612 for value, arg in enumerate(args):
6613 if arg.IsPointer() or arg.IsConstant():
6614 continue
6615 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6616 (arg.type, value + 1, arg.name))
6617 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6618 file.Write(" next_cmd, sizeof(cmd) +\n")
6619 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6620 file.Write(" // TODO(gman): Check that data was inserted;\n")
6621 file.Write("}\n")
6622 file.Write("\n")
6624 class PUTSTRHandler(ArrayArgTypeHandler):
6625 """Handler for functions that pass a string array."""
6627 def __init__(self):
6628 ArrayArgTypeHandler.__init__(self)
6630 def __GetDataArg(self, func):
6631 """Return the argument that points to the 2D char arrays"""
6632 for arg in func.GetOriginalArgs():
6633 if arg.IsPointer2D():
6634 return arg
6635 return None
6637 def __GetLengthArg(self, func):
6638 """Return the argument that holds length for each char array"""
6639 for arg in func.GetOriginalArgs():
6640 if arg.IsPointer() and not arg.IsPointer2D():
6641 return arg
6642 return None
6644 def WriteGLES2Implementation(self, func, file):
6645 """Overrriden from TypeHandler."""
6646 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6647 (func.return_type, func.original_name,
6648 func.MakeTypedOriginalArgString("")))
6649 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6650 func.WriteDestinationInitalizationValidation(file)
6651 self.WriteClientGLCallLog(func, file)
6652 data_arg = self.__GetDataArg(func)
6653 length_arg = self.__GetLengthArg(func)
6654 log_code_block = """ GPU_CLIENT_LOG_CODE_BLOCK({
6655 for (GLsizei ii = 0; ii < count; ++ii) {
6656 if (%(data)s[ii]) {"""
6657 if length_arg == None:
6658 log_code_block += """
6659 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
6660 else:
6661 log_code_block += """
6662 if (%(length)s && %(length)s[ii] >= 0) {
6663 const std::string my_str(%(data)s[ii], %(length)s[ii]);
6664 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
6665 } else {
6666 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
6667 }"""
6668 log_code_block += """
6669 } else {
6670 GPU_CLIENT_LOG(" " << ii << ": NULL");
6675 file.Write(log_code_block % {
6676 'data': data_arg.name,
6677 'length': length_arg.name if not length_arg == None else ''
6679 for arg in func.GetOriginalArgs():
6680 arg.WriteClientSideValidationCode(file, func)
6682 bucket_args = []
6683 for arg in func.GetOriginalArgs():
6684 if arg.name == 'count' or arg == self.__GetLengthArg(func):
6685 continue
6686 if arg == self.__GetDataArg(func):
6687 bucket_args.append('kResultBucketId')
6688 else:
6689 bucket_args.append(arg.name)
6690 code_block = """
6691 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
6692 return;
6694 helper_->%(func_name)sBucket(%(bucket_args)s);
6695 helper_->SetBucketSize(kResultBucketId, 0);
6696 CheckGLError();
6700 file.Write(code_block % {
6701 'data': data_arg.name,
6702 'length': length_arg.name if not length_arg == None else 'NULL',
6703 'func_name': func.name,
6704 'bucket_args': ', '.join(bucket_args),
6707 def WriteGLES2ImplementationUnitTest(self, func, file):
6708 """Overrriden from TypeHandler."""
6709 code = """
6710 TEST_F(GLES2ImplementationTest, %(name)s) {
6711 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
6712 const char* kString1 = "happy";
6713 const char* kString2 = "ending";
6714 const size_t kString1Size = ::strlen(kString1) + 1;
6715 const size_t kString2Size = ::strlen(kString2) + 1;
6716 const size_t kHeaderSize = sizeof(GLint) * 3;
6717 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
6718 const size_t kPaddedHeaderSize =
6719 transfer_buffer_->RoundToAlignment(kHeaderSize);
6720 const size_t kPaddedString1Size =
6721 transfer_buffer_->RoundToAlignment(kString1Size);
6722 const size_t kPaddedString2Size =
6723 transfer_buffer_->RoundToAlignment(kString2Size);
6724 struct Cmds {
6725 cmd::SetBucketSize set_bucket_size;
6726 cmd::SetBucketData set_bucket_header;
6727 cmd::SetToken set_token1;
6728 cmd::SetBucketData set_bucket_data1;
6729 cmd::SetToken set_token2;
6730 cmd::SetBucketData set_bucket_data2;
6731 cmd::SetToken set_token3;
6732 cmds::%(name)sBucket cmd_bucket;
6733 cmd::SetBucketSize clear_bucket_size;
6736 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
6737 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
6738 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
6740 Cmds expected;
6741 expected.set_bucket_size.Init(kBucketId, kSourceSize);
6742 expected.set_bucket_header.Init(
6743 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
6744 expected.set_token1.Init(GetNextToken());
6745 expected.set_bucket_data1.Init(
6746 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
6747 expected.set_token2.Init(GetNextToken());
6748 expected.set_bucket_data2.Init(
6749 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
6750 mem2.offset);
6751 expected.set_token3.Init(GetNextToken());
6752 expected.cmd_bucket.Init(%(bucket_args)s);
6753 expected.clear_bucket_size.Init(kBucketId, 0);
6754 const char* kStrings[] = { kString1, kString2 };
6755 gl_->%(name)s(%(gl_args)s);
6756 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6759 gl_args = []
6760 bucket_args = []
6761 for arg in func.GetOriginalArgs():
6762 if arg == self.__GetDataArg(func):
6763 gl_args.append('kStrings')
6764 bucket_args.append('kBucketId')
6765 elif arg == self.__GetLengthArg(func):
6766 gl_args.append('NULL')
6767 elif arg.name == 'count':
6768 gl_args.append('2')
6769 else:
6770 gl_args.append(arg.GetValidClientSideArg(func))
6771 bucket_args.append(arg.GetValidClientSideArg(func))
6772 file.Write(code % {
6773 'name': func.name,
6774 'gl_args': ", ".join(gl_args),
6775 'bucket_args': ", ".join(bucket_args),
6778 if self.__GetLengthArg(func) == None:
6779 return
6780 code = """
6781 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
6782 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
6783 const char* kString = "foobar******";
6784 const size_t kStringSize = 6; // We only need "foobar".
6785 const size_t kHeaderSize = sizeof(GLint) * 2;
6786 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
6787 const size_t kPaddedHeaderSize =
6788 transfer_buffer_->RoundToAlignment(kHeaderSize);
6789 const size_t kPaddedStringSize =
6790 transfer_buffer_->RoundToAlignment(kStringSize + 1);
6791 struct Cmds {
6792 cmd::SetBucketSize set_bucket_size;
6793 cmd::SetBucketData set_bucket_header;
6794 cmd::SetToken set_token1;
6795 cmd::SetBucketData set_bucket_data;
6796 cmd::SetToken set_token2;
6797 cmds::ShaderSourceBucket shader_source_bucket;
6798 cmd::SetBucketSize clear_bucket_size;
6801 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
6802 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
6804 Cmds expected;
6805 expected.set_bucket_size.Init(kBucketId, kSourceSize);
6806 expected.set_bucket_header.Init(
6807 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
6808 expected.set_token1.Init(GetNextToken());
6809 expected.set_bucket_data.Init(
6810 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
6811 expected.set_token2.Init(GetNextToken());
6812 expected.shader_source_bucket.Init(%(bucket_args)s);
6813 expected.clear_bucket_size.Init(kBucketId, 0);
6814 const char* kStrings[] = { kString };
6815 const GLint kLength[] = { kStringSize };
6816 gl_->%(name)s(%(gl_args)s);
6817 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6820 gl_args = []
6821 for arg in func.GetOriginalArgs():
6822 if arg == self.__GetDataArg(func):
6823 gl_args.append('kStrings')
6824 elif arg == self.__GetLengthArg(func):
6825 gl_args.append('kLength')
6826 elif arg.name == 'count':
6827 gl_args.append('1')
6828 else:
6829 gl_args.append(arg.GetValidClientSideArg(func))
6830 file.Write(code % {
6831 'name': func.name,
6832 'gl_args': ", ".join(gl_args),
6833 'bucket_args': ", ".join(bucket_args),
6836 def WriteBucketServiceUnitTest(self, func, file, *extras):
6837 """Overrriden from TypeHandler."""
6838 cmd_args = []
6839 cmd_args_with_invalid_id = []
6840 gl_args = []
6841 for index, arg in enumerate(func.GetOriginalArgs()):
6842 if arg == self.__GetLengthArg(func):
6843 gl_args.append('_')
6844 elif arg.name == 'count':
6845 gl_args.append('1')
6846 elif arg == self.__GetDataArg(func):
6847 cmd_args.append('kBucketId')
6848 cmd_args_with_invalid_id.append('kBucketId')
6849 gl_args.append('_')
6850 elif index == 0: # Resource ID arg
6851 cmd_args.append(arg.GetValidArg(func))
6852 cmd_args_with_invalid_id.append('kInvalidClientId')
6853 gl_args.append(arg.GetValidGLArg(func))
6854 else:
6855 cmd_args.append(arg.GetValidArg(func))
6856 cmd_args_with_invalid_id.append(arg.GetValidArg(func))
6857 gl_args.append(arg.GetValidGLArg(func))
6859 test = """
6860 TEST_P(%(test_name)s, %(name)sValidArgs) {
6861 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6862 const uint32 kBucketId = 123;
6863 const char kSource0[] = "hello";
6864 const char* kSource[] = { kSource0 };
6865 const char kValidStrEnd = 0;
6866 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
6867 cmds::%(name)s cmd;
6868 cmd.Init(%(cmd_args)s);
6869 decoder_->set_unsafe_es3_apis_enabled(true);
6870 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
6871 if func.IsUnsafe():
6872 test += """
6873 decoder_->set_unsafe_es3_apis_enabled(false);
6874 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
6876 test += """
6879 self.WriteValidUnitTest(func, file, test, {
6880 'cmd_args': ", ".join(cmd_args),
6881 'gl_args': ", ".join(gl_args),
6882 }, *extras)
6884 test = """
6885 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6886 const uint32 kBucketId = 123;
6887 const char kSource0[] = "hello";
6888 const char* kSource[] = { kSource0 };
6889 const char kValidStrEnd = 0;
6890 decoder_->set_unsafe_es3_apis_enabled(true);
6891 cmds::%(name)s cmd;
6892 // Test no bucket.
6893 cmd.Init(%(cmd_args)s);
6894 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
6895 // Test invalid client.
6896 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
6897 cmd.Init(%(cmd_args_with_invalid_id)s);
6898 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6899 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
6902 self.WriteValidUnitTest(func, file, test, {
6903 'cmd_args': ", ".join(cmd_args),
6904 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id),
6905 }, *extras)
6907 test = """
6908 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
6909 const uint32 kBucketId = 123;
6910 const char kSource0[] = "hello";
6911 const char* kSource[] = { kSource0 };
6912 const char kValidStrEnd = 0;
6913 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
6914 const GLsizei kTests[] = {
6915 kCount + 1,
6917 std::numeric_limits<GLsizei>::max(),
6920 decoder_->set_unsafe_es3_apis_enabled(true);
6921 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
6922 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
6923 cmds::%(name)s cmd;
6924 cmd.Init(%(cmd_args)s);
6925 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
6929 self.WriteValidUnitTest(func, file, test, {
6930 'cmd_args': ", ".join(cmd_args),
6931 }, *extras)
6933 test = """
6934 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
6935 const uint32 kBucketId = 123;
6936 const char kSource0[] = "hello";
6937 const char* kSource[] = { kSource0 };
6938 const char kInvalidStrEnd = '*';
6939 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
6940 cmds::%(name)s cmd;
6941 cmd.Init(%(cmd_args)s);
6942 decoder_->set_unsafe_es3_apis_enabled(true);
6943 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
6946 self.WriteValidUnitTest(func, file, test, {
6947 'cmd_args': ", ".join(cmd_args),
6948 }, *extras)
6951 class PUTXnHandler(ArrayArgTypeHandler):
6952 """Handler for glUniform?f functions."""
6953 def __init__(self):
6954 ArrayArgTypeHandler.__init__(self)
6956 def WriteHandlerImplementation(self, func, file):
6957 """Overrriden from TypeHandler."""
6958 code = """ %(type)s temp[%(count)s] = { %(values)s};"""
6959 if func.IsUnsafe():
6960 code += """
6961 gl%(name)sv(%(location)s, 1, &temp[0]);
6963 else:
6964 code += """
6965 Do%(name)sv(%(location)s, 1, &temp[0]);
6967 values = ""
6968 args = func.GetOriginalArgs()
6969 count = int(self.GetArrayCount(func))
6970 num_args = len(args)
6971 for ii in range(count):
6972 values += "%s, " % args[len(args) - count + ii].name
6974 file.Write(code % {
6975 'name': func.name,
6976 'count': self.GetArrayCount(func),
6977 'type': self.GetArrayType(func),
6978 'location': args[0].name,
6979 'args': func.MakeOriginalArgString(""),
6980 'values': values,
6983 def WriteServiceUnitTest(self, func, file, *extras):
6984 """Overrriden from TypeHandler."""
6985 valid_test = """
6986 TEST_P(%(test_name)s, %(name)sValidArgs) {
6987 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
6988 SpecializedSetup<cmds::%(name)s, 0>(true);
6989 cmds::%(name)s cmd;
6990 cmd.Init(%(args)s);"""
6991 if func.IsUnsafe():
6992 valid_test += """
6993 decoder_->set_unsafe_es3_apis_enabled(true);"""
6994 valid_test += """
6995 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6996 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6997 if func.IsUnsafe():
6998 valid_test += """
6999 decoder_->set_unsafe_es3_apis_enabled(false);
7000 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7001 valid_test += """
7004 args = func.GetOriginalArgs()
7005 local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
7006 self.WriteValidUnitTest(func, file, valid_test, {
7007 'name': func.name,
7008 'count': self.GetArrayCount(func),
7009 'local_args': local_args,
7010 }, *extras)
7012 invalid_test = """
7013 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7014 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7015 SpecializedSetup<cmds::%(name)s, 0>(false);
7016 cmds::%(name)s cmd;
7017 cmd.Init(%(args)s);
7018 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7021 self.WriteInvalidUnitTest(func, file, invalid_test, {
7022 'name': func.GetInfo('name'),
7023 'count': self.GetArrayCount(func),
7027 class GLcharHandler(CustomHandler):
7028 """Handler for functions that pass a single string ."""
7030 def __init__(self):
7031 CustomHandler.__init__(self)
7033 def WriteImmediateCmdComputeSize(self, func, file):
7034 """Overrriden from TypeHandler."""
7035 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7036 file.Write(" return static_cast<uint32_t>(\n")
7037 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
7038 file.Write(" }\n")
7040 def WriteImmediateCmdSetHeader(self, func, file):
7041 """Overrriden from TypeHandler."""
7042 code = """
7043 void SetHeader(uint32_t data_size) {
7044 header.SetCmdBySize<ValueType>(data_size);
7047 file.Write(code)
7049 def WriteImmediateCmdInit(self, func, file):
7050 """Overrriden from TypeHandler."""
7051 last_arg = func.GetLastOriginalArg()
7052 args = func.GetCmdArgs()
7053 set_code = []
7054 for arg in args:
7055 set_code.append(" %s = _%s;" % (arg.name, arg.name))
7056 code = """
7057 void Init(%(typed_args)s, uint32_t _data_size) {
7058 SetHeader(_data_size);
7059 %(set_code)s
7060 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7064 file.Write(code % {
7065 "typed_args": func.MakeTypedArgString("_"),
7066 "set_code": "\n".join(set_code),
7067 "last_arg": last_arg.name
7070 def WriteImmediateCmdSet(self, func, file):
7071 """Overrriden from TypeHandler."""
7072 last_arg = func.GetLastOriginalArg()
7073 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7074 func.MakeTypedCmdArgString("_", True))
7075 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7076 func.MakeCmdArgString("_"))
7077 file.Write(" return NextImmediateCmdAddress<ValueType>("
7078 "cmd, _data_size);\n")
7079 file.Write(" }\n")
7080 file.Write("\n")
7082 def WriteImmediateCmdHelper(self, func, file):
7083 """Overrriden from TypeHandler."""
7084 code = """ void %(name)s(%(typed_args)s) {
7085 const uint32_t data_size = strlen(name);
7086 gles2::cmds::%(name)s* c =
7087 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7088 if (c) {
7089 c->Init(%(args)s, data_size);
7094 file.Write(code % {
7095 "name": func.name,
7096 "typed_args": func.MakeTypedOriginalArgString(""),
7097 "args": func.MakeOriginalArgString(""),
7101 def WriteImmediateFormatTest(self, func, file):
7102 """Overrriden from TypeHandler."""
7103 init_code = []
7104 check_code = []
7105 all_but_last_arg = func.GetCmdArgs()[:-1]
7106 for value, arg in enumerate(all_but_last_arg):
7107 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
7108 for value, arg in enumerate(all_but_last_arg):
7109 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7110 (arg.type, value + 11, arg.name))
7111 code = """
7112 TEST_F(GLES2FormatTest, %(func_name)s) {
7113 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7114 static const char* const test_str = \"test string\";
7115 void* next_cmd = cmd.Set(
7116 &cmd,
7117 %(init_code)s
7118 test_str,
7119 strlen(test_str));
7120 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7121 cmd.header.command);
7122 EXPECT_EQ(sizeof(cmd) +
7123 RoundSizeToMultipleOfEntries(strlen(test_str)),
7124 cmd.header.size * 4u);
7125 EXPECT_EQ(static_cast<char*>(next_cmd),
7126 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7127 RoundSizeToMultipleOfEntries(strlen(test_str)));
7128 %(check_code)s
7129 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7130 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7131 CheckBytesWritten(
7132 next_cmd,
7133 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7134 sizeof(cmd) + strlen(test_str));
7138 file.Write(code % {
7139 'func_name': func.name,
7140 'init_code': "\n".join(init_code),
7141 'check_code': "\n".join(check_code),
7145 class GLcharNHandler(CustomHandler):
7146 """Handler for functions that pass a single string with an optional len."""
7148 def __init__(self):
7149 CustomHandler.__init__(self)
7151 def InitFunction(self, func):
7152 """Overrriden from TypeHandler."""
7153 func.cmd_args = []
7154 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
7156 def NeedsDataTransferFunction(self, func):
7157 """Overriden from TypeHandler."""
7158 return False
7160 def AddBucketFunction(self, generator, func):
7161 """Overrriden from TypeHandler."""
7162 pass
7164 def WriteServiceImplementation(self, func, file):
7165 """Overrriden from TypeHandler."""
7166 self.WriteServiceHandlerFunctionHeader(func, file)
7167 file.Write("""
7168 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7169 Bucket* bucket = GetBucket(bucket_id);
7170 if (!bucket || bucket->size() == 0) {
7171 return error::kInvalidArguments;
7173 std::string str;
7174 if (!bucket->GetAsString(&str)) {
7175 return error::kInvalidArguments;
7177 %(gl_func_name)s(0, str.c_str());
7178 return error::kNoError;
7181 """ % {
7182 'name': func.name,
7183 'gl_func_name': func.GetGLFunctionName(),
7184 'bucket_id': func.cmd_args[0].name,
7188 class IsHandler(TypeHandler):
7189 """Handler for glIs____ type and glGetError functions."""
7191 def __init__(self):
7192 TypeHandler.__init__(self)
7194 def InitFunction(self, func):
7195 """Overrriden from TypeHandler."""
7196 func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7197 func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7198 if func.GetInfo('result') == None:
7199 func.AddInfo('result', ['uint32_t'])
7201 def WriteServiceUnitTest(self, func, file, *extras):
7202 """Overrriden from TypeHandler."""
7203 valid_test = """
7204 TEST_P(%(test_name)s, %(name)sValidArgs) {
7205 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7206 SpecializedSetup<cmds::%(name)s, 0>(true);
7207 cmds::%(name)s cmd;
7208 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7209 if func.IsUnsafe():
7210 valid_test += """
7211 decoder_->set_unsafe_es3_apis_enabled(true);"""
7212 valid_test += """
7213 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7214 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7215 if func.IsUnsafe():
7216 valid_test += """
7217 decoder_->set_unsafe_es3_apis_enabled(false);
7218 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7219 valid_test += """
7222 comma = ""
7223 if len(func.GetOriginalArgs()):
7224 comma =", "
7225 self.WriteValidUnitTest(func, file, valid_test, {
7226 'comma': comma,
7227 }, *extras)
7229 invalid_test = """
7230 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7231 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7232 SpecializedSetup<cmds::%(name)s, 0>(false);
7233 cmds::%(name)s cmd;
7234 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7235 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7238 self.WriteInvalidUnitTest(func, file, invalid_test, {
7239 'comma': comma,
7240 }, *extras)
7242 invalid_test = """
7243 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
7244 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7245 SpecializedSetup<cmds::%(name)s, 0>(false);"""
7246 if func.IsUnsafe():
7247 invalid_test += """
7248 decoder_->set_unsafe_es3_apis_enabled(true);"""
7249 invalid_test += """
7250 cmds::%(name)s cmd;
7251 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
7252 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
7253 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
7254 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
7255 if func.IsUnsafe():
7256 invalid_test += """
7257 decoder_->set_unsafe_es3_apis_enabled(true);"""
7258 invalid_test += """
7261 self.WriteValidUnitTest(func, file, invalid_test, {
7262 'comma': comma,
7263 }, *extras)
7265 def WriteServiceImplementation(self, func, file):
7266 """Overrriden from TypeHandler."""
7267 self.WriteServiceHandlerFunctionHeader(func, file)
7268 args = func.GetOriginalArgs()
7269 for arg in args:
7270 arg.WriteGetCode(file)
7272 code = """ typedef cmds::%(func_name)s::Result Result;
7273 Result* result_dst = GetSharedMemoryAs<Result*>(
7274 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
7275 if (!result_dst) {
7276 return error::kOutOfBounds;
7279 file.Write(code % {'func_name': func.name})
7280 func.WriteHandlerValidation(file)
7281 if func.IsUnsafe():
7282 assert func.GetInfo('id_mapping')
7283 assert len(func.GetInfo('id_mapping')) == 1
7284 assert len(args) == 1
7285 id_type = func.GetInfo('id_mapping')[0]
7286 file.Write(" %s service_%s = 0;\n" % (args[0].type, id_type.lower()))
7287 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
7288 (id_type, id_type.lower(), id_type.lower()))
7289 else:
7290 file.Write(" *result_dst = %s(%s);\n" %
7291 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
7292 file.Write(" return error::kNoError;\n")
7293 file.Write("}\n")
7294 file.Write("\n")
7296 def WriteGLES2Implementation(self, func, file):
7297 """Overrriden from TypeHandler."""
7298 impl_func = func.GetInfo('impl_func')
7299 if impl_func == None or impl_func == True:
7300 error_value = func.GetInfo("error_value") or "GL_FALSE"
7301 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7302 (func.return_type, func.original_name,
7303 func.MakeTypedOriginalArgString("")))
7304 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7305 self.WriteTraceEvent(func, file)
7306 func.WriteDestinationInitalizationValidation(file)
7307 self.WriteClientGLCallLog(func, file)
7308 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
7309 file.Write(" Result* result = GetResultAs<Result*>();\n")
7310 file.Write(" if (!result) {\n")
7311 file.Write(" return %s;\n" % error_value)
7312 file.Write(" }\n")
7313 file.Write(" *result = 0;\n")
7314 assert len(func.GetOriginalArgs()) == 1
7315 id_arg = func.GetOriginalArgs()[0]
7316 if id_arg.type == 'GLsync':
7317 arg_string = "ToGLuint(%s)" % func.MakeOriginalArgString("")
7318 else:
7319 arg_string = func.MakeOriginalArgString("")
7320 file.Write(
7321 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
7322 (func.name, arg_string))
7323 file.Write(" WaitForCmd();\n")
7324 file.Write(" %s result_value = *result" % func.return_type)
7325 if func.return_type == "GLboolean":
7326 file.Write(" != 0")
7327 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
7328 file.Write(" CheckGLError();\n")
7329 file.Write(" return result_value;\n")
7330 file.Write("}\n")
7331 file.Write("\n")
7333 def WriteGLES2ImplementationUnitTest(self, func, file):
7334 """Overrriden from TypeHandler."""
7335 client_test = func.GetInfo('client_test')
7336 if client_test == None or client_test == True:
7337 code = """
7338 TEST_F(GLES2ImplementationTest, %(name)s) {
7339 struct Cmds {
7340 cmds::%(name)s cmd;
7343 Cmds expected;
7344 ExpectedMemoryInfo result1 =
7345 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
7346 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
7348 EXPECT_CALL(*command_buffer(), OnFlush())
7349 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
7350 .RetiresOnSaturation();
7352 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
7353 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7354 EXPECT_TRUE(result);
7357 args = func.GetOriginalArgs()
7358 assert len(args) == 1
7359 file.Write(code % {
7360 'name': func.name,
7361 'cmd_id_value': args[0].GetValidClientSideCmdArg(func),
7362 'gl_id_value': args[0].GetValidClientSideArg(func) })
7365 class STRnHandler(TypeHandler):
7366 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
7367 GetTranslatedShaderSourceANGLE."""
7369 def __init__(self):
7370 TypeHandler.__init__(self)
7372 def InitFunction(self, func):
7373 """Overrriden from TypeHandler."""
7374 # remove all but the first cmd args.
7375 cmd_args = func.GetCmdArgs()
7376 func.ClearCmdArgs()
7377 func.AddCmdArg(cmd_args[0])
7378 # add on a bucket id.
7379 func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
7381 def WriteGLES2Implementation(self, func, file):
7382 """Overrriden from TypeHandler."""
7383 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
7384 GPU_CLIENT_SINGLE_THREAD_CHECK();
7386 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
7387 << "] gl%(func_name)s" << "("
7388 << %(arg0)s << ", "
7389 << %(arg1)s << ", "
7390 << static_cast<void*>(%(arg2)s) << ", "
7391 << static_cast<void*>(%(arg3)s) << ")");
7392 helper_->SetBucketSize(kResultBucketId, 0);
7393 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
7394 std::string str;
7395 GLsizei max_size = 0;
7396 if (GetBucketAsString(kResultBucketId, &str)) {
7397 if (bufsize > 0) {
7398 max_size =
7399 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
7400 memcpy(%(dest_name)s, str.c_str(), max_size);
7401 %(dest_name)s[max_size] = '\\0';
7402 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
7405 if (%(length_name)s != NULL) {
7406 *%(length_name)s = max_size;
7408 CheckGLError();
7411 args = func.GetOriginalArgs()
7412 str_args = {
7413 'return_type': func.return_type,
7414 'func_name': func.original_name,
7415 'args': func.MakeTypedOriginalArgString(""),
7416 'id_name': args[0].name,
7417 'bufsize_name': args[1].name,
7418 'length_name': args[2].name,
7419 'dest_name': args[3].name,
7420 'arg0': args[0].name,
7421 'arg1': args[1].name,
7422 'arg2': args[2].name,
7423 'arg3': args[3].name,
7425 file.Write(code_1 % str_args)
7426 func.WriteDestinationInitalizationValidation(file)
7427 file.Write(code_2 % str_args)
7429 def WriteServiceUnitTest(self, func, file, *extras):
7430 """Overrriden from TypeHandler."""
7431 valid_test = """
7432 TEST_P(%(test_name)s, %(name)sValidArgs) {
7433 const char* kInfo = "hello";
7434 const uint32_t kBucketId = 123;
7435 SpecializedSetup<cmds::%(name)s, 0>(true);
7436 %(expect_len_code)s
7437 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
7438 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
7439 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
7440 cmds::%(name)s cmd;
7441 cmd.Init(%(args)s);
7442 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7443 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
7444 ASSERT_TRUE(bucket != NULL);
7445 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
7446 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
7447 bucket->size()));
7448 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7451 args = func.GetOriginalArgs()
7452 id_name = args[0].GetValidGLArg(func)
7453 get_len_func = func.GetInfo('get_len_func')
7454 get_len_enum = func.GetInfo('get_len_enum')
7455 sub = {
7456 'id_name': id_name,
7457 'get_len_func': get_len_func,
7458 'get_len_enum': get_len_enum,
7459 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
7460 args[0].GetValidGLArg(func),
7461 'args': '%s, kBucketId' % args[0].GetValidArg(func),
7462 'expect_len_code': '',
7464 if get_len_func and get_len_func[0:2] == 'gl':
7465 sub['expect_len_code'] = (
7466 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
7467 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
7468 get_len_func[2:], id_name, get_len_enum)
7469 self.WriteValidUnitTest(func, file, valid_test, sub, *extras)
7471 invalid_test = """
7472 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7473 const uint32_t kBucketId = 123;
7474 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
7475 .Times(0);
7476 cmds::%(name)s cmd;
7477 cmd.Init(kInvalidClientId, kBucketId);
7478 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7479 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7482 self.WriteValidUnitTest(func, file, invalid_test, *extras)
7484 def WriteServiceImplementation(self, func, file):
7485 """Overrriden from TypeHandler."""
7486 pass
7488 class NamedType(object):
7489 """A class that represents a type of an argument in a client function.
7491 A type of an argument that is to be passed through in the command buffer
7492 command. Currently used only for the arguments that are specificly named in
7493 the 'cmd_buffer_functions.txt' file, mostly enums.
7496 def __init__(self, info):
7497 assert not 'is_complete' in info or info['is_complete'] == True
7498 self.info = info
7499 self.valid = info['valid']
7500 if 'invalid' in info:
7501 self.invalid = info['invalid']
7502 else:
7503 self.invalid = []
7505 def GetType(self):
7506 return self.info['type']
7508 def GetInvalidValues(self):
7509 return self.invalid
7511 def GetValidValues(self):
7512 return self.valid
7514 def IsConstant(self):
7515 if not 'is_complete' in self.info:
7516 return False
7518 return len(self.GetValidValues()) == 1
7520 def GetConstantValue(self):
7521 return self.GetValidValues()[0]
7523 class Argument(object):
7524 """A class that represents a function argument."""
7526 cmd_type_map_ = {
7527 'GLenum': 'uint32_t',
7528 'GLint': 'int32_t',
7529 'GLintptr': 'int32_t',
7530 'GLsizei': 'int32_t',
7531 'GLsizeiptr': 'int32_t',
7532 'GLfloat': 'float',
7533 'GLclampf': 'float',
7535 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
7537 def __init__(self, name, type):
7538 self.name = name
7539 self.optional = type.endswith("Optional*")
7540 if self.optional:
7541 type = type[:-9] + "*"
7542 self.type = type
7544 if type in self.cmd_type_map_:
7545 self.cmd_type = self.cmd_type_map_[type]
7546 else:
7547 self.cmd_type = 'uint32_t'
7549 def IsPointer(self):
7550 """Returns true if argument is a pointer."""
7551 return False
7553 def IsPointer2D(self):
7554 """Returns true if argument is a 2D pointer."""
7555 return False
7557 def IsConstant(self):
7558 """Returns true if the argument has only one valid value."""
7559 return False
7561 def AddCmdArgs(self, args):
7562 """Adds command arguments for this argument to the given list."""
7563 if not self.IsConstant():
7564 return args.append(self)
7566 def AddInitArgs(self, args):
7567 """Adds init arguments for this argument to the given list."""
7568 if not self.IsConstant():
7569 return args.append(self)
7571 def GetValidArg(self, func):
7572 """Gets a valid value for this argument."""
7573 valid_arg = func.GetValidArg(self)
7574 if valid_arg != None:
7575 return valid_arg
7577 index = func.GetOriginalArgs().index(self)
7578 return str(index + 1)
7580 def GetValidClientSideArg(self, func):
7581 """Gets a valid value for this argument."""
7582 valid_arg = func.GetValidArg(self)
7583 if valid_arg != None:
7584 return valid_arg
7586 if self.IsPointer():
7587 return 'nullptr'
7588 index = func.GetOriginalArgs().index(self)
7589 if self.type == 'GLsync':
7590 return ("reinterpret_cast<GLsync>(%d)" % (index + 1))
7591 return str(index + 1)
7593 def GetValidClientSideCmdArg(self, func):
7594 """Gets a valid value for this argument."""
7595 valid_arg = func.GetValidArg(self)
7596 if valid_arg != None:
7597 return valid_arg
7598 try:
7599 index = func.GetOriginalArgs().index(self)
7600 return str(index + 1)
7601 except ValueError:
7602 pass
7603 index = func.GetCmdArgs().index(self)
7604 return str(index + 1)
7606 def GetValidGLArg(self, func):
7607 """Gets a valid GL value for this argument."""
7608 value = self.GetValidArg(func)
7609 if self.type == 'GLsync':
7610 return ("reinterpret_cast<GLsync>(%s)" % value)
7611 return value
7613 def GetValidNonCachedClientSideArg(self, func):
7614 """Returns a valid value for this argument in a GL call.
7615 Using the value will produce a command buffer service invocation.
7616 Returns None if there is no such value."""
7617 value = '123'
7618 if self.type == 'GLsync':
7619 return ("reinterpret_cast<GLsync>(%s)" % value)
7620 return value
7622 def GetValidNonCachedClientSideCmdArg(self, func):
7623 """Returns a valid value for this argument in a command buffer command.
7624 Calling the GL function with the value returned by
7625 GetValidNonCachedClientSideArg will result in a command buffer command
7626 that contains the value returned by this function. """
7627 return '123'
7629 def GetNumInvalidValues(self, func):
7630 """returns the number of invalid values to be tested."""
7631 return 0
7633 def GetInvalidArg(self, index):
7634 """returns an invalid value and expected parse result by index."""
7635 return ("---ERROR0---", "---ERROR2---", None)
7637 def GetLogArg(self):
7638 """Get argument appropriate for LOG macro."""
7639 if self.type == 'GLboolean':
7640 return 'GLES2Util::GetStringBool(%s)' % self.name
7641 if self.type == 'GLenum':
7642 return 'GLES2Util::GetStringEnum(%s)' % self.name
7643 return self.name
7645 def WriteGetCode(self, file):
7646 """Writes the code to get an argument from a command structure."""
7647 if self.type == 'GLsync':
7648 my_type = 'GLuint'
7649 else:
7650 my_type = self.type
7651 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
7652 (my_type, self.name, my_type, self.name))
7654 def WriteValidationCode(self, file, func):
7655 """Writes the validation code for an argument."""
7656 pass
7658 def WriteClientSideValidationCode(self, file, func):
7659 """Writes the validation code for an argument."""
7660 pass
7662 def WriteDestinationInitalizationValidation(self, file, func):
7663 """Writes the client side destintion initialization validation."""
7664 pass
7666 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
7667 """Writes the client side destintion initialization validation if needed."""
7668 parts = self.type.split(" ")
7669 if len(parts) > 1:
7670 return
7671 if parts[0] in self.need_validation_:
7672 file.Write(
7673 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
7674 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
7677 def WriteGetAddress(self, file):
7678 """Writes the code to get the address this argument refers to."""
7679 pass
7681 def GetImmediateVersion(self):
7682 """Gets the immediate version of this argument."""
7683 return self
7685 def GetBucketVersion(self):
7686 """Gets the bucket version of this argument."""
7687 return self
7690 class BoolArgument(Argument):
7691 """class for GLboolean"""
7693 def __init__(self, name, type):
7694 Argument.__init__(self, name, 'GLboolean')
7696 def GetValidArg(self, func):
7697 """Gets a valid value for this argument."""
7698 return 'true'
7700 def GetValidClientSideArg(self, func):
7701 """Gets a valid value for this argument."""
7702 return 'true'
7704 def GetValidClientSideCmdArg(self, func):
7705 """Gets a valid value for this argument."""
7706 return 'true'
7708 def GetValidGLArg(self, func):
7709 """Gets a valid GL value for this argument."""
7710 return 'true'
7713 class UniformLocationArgument(Argument):
7714 """class for uniform locations."""
7716 def __init__(self, name):
7717 Argument.__init__(self, name, "GLint")
7719 def WriteGetCode(self, file):
7720 """Writes the code to get an argument from a command structure."""
7721 code = """ %s %s = static_cast<%s>(c.%s);
7723 file.Write(code % (self.type, self.name, self.type, self.name))
7725 class DataSizeArgument(Argument):
7726 """class for data_size which Bucket commands do not need."""
7728 def __init__(self, name):
7729 Argument.__init__(self, name, "uint32_t")
7731 def GetBucketVersion(self):
7732 return None
7735 class SizeArgument(Argument):
7736 """class for GLsizei and GLsizeiptr."""
7738 def __init__(self, name, type):
7739 Argument.__init__(self, name, type)
7741 def GetNumInvalidValues(self, func):
7742 """overridden from Argument."""
7743 if func.IsImmediate():
7744 return 0
7745 return 1
7747 def GetInvalidArg(self, index):
7748 """overridden from Argument."""
7749 return ("-1", "kNoError", "GL_INVALID_VALUE")
7751 def WriteValidationCode(self, file, func):
7752 """overridden from Argument."""
7753 if func.IsUnsafe():
7754 return
7755 code = """ if (%(var_name)s < 0) {
7756 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
7757 return error::kNoError;
7760 file.Write(code % {
7761 "var_name": self.name,
7762 "func_name": func.original_name,
7765 def WriteClientSideValidationCode(self, file, func):
7766 """overridden from Argument."""
7767 code = """ if (%(var_name)s < 0) {
7768 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
7769 return;
7772 file.Write(code % {
7773 "var_name": self.name,
7774 "func_name": func.original_name,
7778 class SizeNotNegativeArgument(SizeArgument):
7779 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
7781 def __init__(self, name, type, gl_type):
7782 SizeArgument.__init__(self, name, gl_type)
7784 def GetInvalidArg(self, index):
7785 """overridden from SizeArgument."""
7786 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
7788 def WriteValidationCode(self, file, func):
7789 """overridden from SizeArgument."""
7790 pass
7793 class EnumBaseArgument(Argument):
7794 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
7795 ValidatedBoolArgument."""
7797 def __init__(self, name, gl_type, type, gl_error):
7798 Argument.__init__(self, name, gl_type)
7800 self.local_type = type
7801 self.gl_error = gl_error
7802 name = type[len(gl_type):]
7803 self.type_name = name
7804 self.named_type = NamedType(_NAMED_TYPE_INFO[name])
7806 def IsConstant(self):
7807 return self.named_type.IsConstant()
7809 def GetConstantValue(self):
7810 return self.named_type.GetConstantValue()
7812 def WriteValidationCode(self, file, func):
7813 if func.IsUnsafe():
7814 return
7815 if self.named_type.IsConstant():
7816 return
7817 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
7818 (ToUnderscore(self.type_name), self.name))
7819 if self.gl_error == "GL_INVALID_ENUM":
7820 file.Write(
7821 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
7822 (func.original_name, self.name, self.name))
7823 else:
7824 file.Write(
7825 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
7826 (self.gl_error, func.original_name, self.name, self.gl_error))
7827 file.Write(" return error::kNoError;\n")
7828 file.Write(" }\n")
7830 def WriteClientSideValidationCode(self, file, func):
7831 if not self.named_type.IsConstant():
7832 return
7833 file.Write(" if (%s != %s) {" % (self.name,
7834 self.GetConstantValue()))
7835 file.Write(
7836 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
7837 (self.gl_error, func.original_name, self.name, self.gl_error))
7838 if func.return_type == "void":
7839 file.Write(" return;\n")
7840 else:
7841 file.Write(" return %s;\n" % func.GetErrorReturnString())
7842 file.Write(" }\n")
7844 def GetValidArg(self, func):
7845 valid_arg = func.GetValidArg(self)
7846 if valid_arg != None:
7847 return valid_arg
7848 valid = self.named_type.GetValidValues()
7849 if valid:
7850 num_valid = len(valid)
7851 return valid[0]
7853 index = func.GetOriginalArgs().index(self)
7854 return str(index + 1)
7856 def GetValidClientSideArg(self, func):
7857 """Gets a valid value for this argument."""
7858 return self.GetValidArg(func)
7860 def GetValidClientSideCmdArg(self, func):
7861 """Gets a valid value for this argument."""
7862 valid_arg = func.GetValidArg(self)
7863 if valid_arg != None:
7864 return valid_arg
7866 valid = self.named_type.GetValidValues()
7867 if valid:
7868 num_valid = len(valid)
7869 return valid[0]
7871 try:
7872 index = func.GetOriginalArgs().index(self)
7873 return str(index + 1)
7874 except ValueError:
7875 pass
7876 index = func.GetCmdArgs().index(self)
7877 return str(index + 1)
7879 def GetValidGLArg(self, func):
7880 """Gets a valid value for this argument."""
7881 return self.GetValidArg(func)
7883 def GetNumInvalidValues(self, func):
7884 """returns the number of invalid values to be tested."""
7885 return len(self.named_type.GetInvalidValues())
7887 def GetInvalidArg(self, index):
7888 """returns an invalid value by index."""
7889 invalid = self.named_type.GetInvalidValues()
7890 if invalid:
7891 num_invalid = len(invalid)
7892 if index >= num_invalid:
7893 index = num_invalid - 1
7894 return (invalid[index], "kNoError", self.gl_error)
7895 return ("---ERROR1---", "kNoError", self.gl_error)
7898 class EnumArgument(EnumBaseArgument):
7899 """A class that represents a GLenum argument"""
7901 def __init__(self, name, type):
7902 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
7904 def GetLogArg(self):
7905 """Overridden from Argument."""
7906 return ("GLES2Util::GetString%s(%s)" %
7907 (self.type_name, self.name))
7910 class IntArgument(EnumBaseArgument):
7911 """A class for a GLint argument that can only accept specific values.
7913 For example glTexImage2D takes a GLint for its internalformat
7914 argument instead of a GLenum.
7917 def __init__(self, name, type):
7918 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
7921 class ValidatedBoolArgument(EnumBaseArgument):
7922 """A class for a GLboolean argument that can only accept specific values.
7924 For example glUniformMatrix takes a GLboolean for it's transpose but it
7925 must be false.
7928 def __init__(self, name, type):
7929 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
7931 def GetLogArg(self):
7932 """Overridden from Argument."""
7933 return 'GLES2Util::GetStringBool(%s)' % self.name
7936 class BitFieldArgument(EnumBaseArgument):
7937 """A class for a GLbitfield argument that can only accept specific values.
7939 For example glFenceSync takes a GLbitfield for its flags argument bit it
7940 must be 0.
7943 def __init__(self, name, type):
7944 EnumBaseArgument.__init__(self, name, "GLbitfield", type,
7945 "GL_INVALID_VALUE")
7948 class ImmediatePointerArgument(Argument):
7949 """A class that represents an immediate argument to a function.
7951 An immediate argument is one where the data follows the command.
7954 def __init__(self, name, type):
7955 Argument.__init__(self, name, type)
7957 def IsPointer(self):
7958 return True
7960 def GetPointedType(self):
7961 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
7962 assert match
7963 return match.groupdict()['element_type']
7965 def AddCmdArgs(self, args):
7966 """Overridden from Argument."""
7967 pass
7969 def WriteGetCode(self, file):
7970 """Overridden from Argument."""
7971 file.Write(
7972 " %s %s = GetImmediateDataAs<%s>(\n" %
7973 (self.type, self.name, self.type))
7974 file.Write(" c, data_size, immediate_data_size);\n")
7976 def WriteValidationCode(self, file, func):
7977 """Overridden from Argument."""
7978 if self.optional:
7979 return
7980 file.Write(" if (%s == NULL) {\n" % self.name)
7981 file.Write(" return error::kOutOfBounds;\n")
7982 file.Write(" }\n")
7984 def GetImmediateVersion(self):
7985 """Overridden from Argument."""
7986 return None
7988 def WriteDestinationInitalizationValidation(self, file, func):
7989 """Overridden from Argument."""
7990 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
7992 def GetLogArg(self):
7993 """Overridden from Argument."""
7994 return "static_cast<const void*>(%s)" % self.name
7997 class PointerArgument(Argument):
7998 """A class that represents a pointer argument to a function."""
8000 def __init__(self, name, type):
8001 Argument.__init__(self, name, type)
8003 def IsPointer(self):
8004 """Overridden from Argument."""
8005 return True
8007 def IsPointer2D(self):
8008 """Overridden from Argument."""
8009 return self.type.count('*') == 2
8011 def GetPointedType(self):
8012 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8013 assert match
8014 return match.groupdict()['element_type']
8016 def GetValidArg(self, func):
8017 """Overridden from Argument."""
8018 return "shared_memory_id_, shared_memory_offset_"
8020 def GetValidGLArg(self, func):
8021 """Overridden from Argument."""
8022 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
8024 def GetNumInvalidValues(self, func):
8025 """Overridden from Argument."""
8026 return 2
8028 def GetInvalidArg(self, index):
8029 """Overridden from Argument."""
8030 if index == 0:
8031 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8032 else:
8033 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8034 "kOutOfBounds", None)
8036 def GetLogArg(self):
8037 """Overridden from Argument."""
8038 return "static_cast<const void*>(%s)" % self.name
8040 def AddCmdArgs(self, args):
8041 """Overridden from Argument."""
8042 args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
8043 args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
8045 def WriteGetCode(self, file):
8046 """Overridden from Argument."""
8047 file.Write(
8048 " %s %s = GetSharedMemoryAs<%s>(\n" %
8049 (self.type, self.name, self.type))
8050 file.Write(
8051 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8052 (self.name, self.name))
8054 def WriteGetAddress(self, file):
8055 """Overridden from Argument."""
8056 file.Write(
8057 " %s %s = GetSharedMemoryAs<%s>(\n" %
8058 (self.type, self.name, self.type))
8059 file.Write(
8060 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8061 (self.name, self.name, self.name))
8063 def WriteValidationCode(self, file, func):
8064 """Overridden from Argument."""
8065 if self.optional:
8066 return
8067 file.Write(" if (%s == NULL) {\n" % self.name)
8068 file.Write(" return error::kOutOfBounds;\n")
8069 file.Write(" }\n")
8071 def GetImmediateVersion(self):
8072 """Overridden from Argument."""
8073 return ImmediatePointerArgument(self.name, self.type)
8075 def GetBucketVersion(self):
8076 """Overridden from Argument."""
8077 if self.type.find('char') >= 0:
8078 if self.IsPointer2D():
8079 return InputStringArrayBucketArgument(self.name, self.type)
8080 return InputStringBucketArgument(self.name, self.type)
8081 return BucketPointerArgument(self.name, self.type)
8083 def WriteDestinationInitalizationValidation(self, file, func):
8084 """Overridden from Argument."""
8085 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8088 class BucketPointerArgument(PointerArgument):
8089 """A class that represents an bucket argument to a function."""
8091 def __init__(self, name, type):
8092 Argument.__init__(self, name, type)
8094 def AddCmdArgs(self, args):
8095 """Overridden from Argument."""
8096 pass
8098 def WriteGetCode(self, file):
8099 """Overridden from Argument."""
8100 file.Write(
8101 " %s %s = bucket->GetData(0, data_size);\n" %
8102 (self.type, self.name))
8104 def WriteValidationCode(self, file, func):
8105 """Overridden from Argument."""
8106 pass
8108 def GetImmediateVersion(self):
8109 """Overridden from Argument."""
8110 return None
8112 def WriteDestinationInitalizationValidation(self, file, func):
8113 """Overridden from Argument."""
8114 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8116 def GetLogArg(self):
8117 """Overridden from Argument."""
8118 return "static_cast<const void*>(%s)" % self.name
8121 class InputStringBucketArgument(Argument):
8122 """A string input argument where the string is passed in a bucket."""
8124 def __init__(self, name, type):
8125 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8127 def IsPointer(self):
8128 """Overridden from Argument."""
8129 return True
8131 def IsPointer2D(self):
8132 """Overridden from Argument."""
8133 return False
8136 class InputStringArrayBucketArgument(Argument):
8137 """A string array input argument where the strings are passed in a bucket."""
8139 def __init__(self, name, type):
8140 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8141 self._original_name = name
8143 def WriteGetCode(self, file):
8144 """Overridden from Argument."""
8145 code = """
8146 Bucket* bucket = GetBucket(c.%(name)s);
8147 if (!bucket) {
8148 return error::kInvalidArguments;
8150 GLsizei count = 0;
8151 std::vector<char*> strs;
8152 std::vector<GLint> len;
8153 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8154 return error::kInvalidArguments;
8156 const char** %(original_name)s =
8157 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8158 const GLint* length =
8159 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8160 (void)length;
8162 file.Write(code % {
8163 'name': self.name,
8164 'original_name': self._original_name,
8167 def GetValidArg(self, func):
8168 return "kNameBucketId"
8170 def GetValidGLArg(self, func):
8171 return "_"
8173 def IsPointer(self):
8174 """Overridden from Argument."""
8175 return True
8177 def IsPointer2D(self):
8178 """Overridden from Argument."""
8179 return True
8182 class ResourceIdArgument(Argument):
8183 """A class that represents a resource id argument to a function."""
8185 def __init__(self, name, type):
8186 match = re.match("(GLid\w+)", type)
8187 self.resource_type = match.group(1)[4:]
8188 if self.resource_type == "Sync":
8189 type = type.replace(match.group(1), "GLsync")
8190 else:
8191 type = type.replace(match.group(1), "GLuint")
8192 Argument.__init__(self, name, type)
8194 def WriteGetCode(self, file):
8195 """Overridden from Argument."""
8196 if self.type == "GLsync":
8197 my_type = "GLuint"
8198 else:
8199 my_type = self.type
8200 file.Write(" %s %s = c.%s;\n" % (my_type, self.name, self.name))
8202 def GetValidArg(self, func):
8203 return "client_%s_id_" % self.resource_type.lower()
8205 def GetValidGLArg(self, func):
8206 if self.resource_type == "Sync":
8207 return "reinterpret_cast<GLsync>(kService%sId)" % self.resource_type
8208 return "kService%sId" % self.resource_type
8211 class ResourceIdBindArgument(Argument):
8212 """Represents a resource id argument to a bind function."""
8214 def __init__(self, name, type):
8215 match = re.match("(GLidBind\w+)", type)
8216 self.resource_type = match.group(1)[8:]
8217 type = type.replace(match.group(1), "GLuint")
8218 Argument.__init__(self, name, type)
8220 def WriteGetCode(self, file):
8221 """Overridden from Argument."""
8222 code = """ %(type)s %(name)s = c.%(name)s;
8224 file.Write(code % {'type': self.type, 'name': self.name})
8226 def GetValidArg(self, func):
8227 return "client_%s_id_" % self.resource_type.lower()
8229 def GetValidGLArg(self, func):
8230 return "kService%sId" % self.resource_type
8233 class ResourceIdZeroArgument(Argument):
8234 """Represents a resource id argument to a function that can be zero."""
8236 def __init__(self, name, type):
8237 match = re.match("(GLidZero\w+)", type)
8238 self.resource_type = match.group(1)[8:]
8239 type = type.replace(match.group(1), "GLuint")
8240 Argument.__init__(self, name, type)
8242 def WriteGetCode(self, file):
8243 """Overridden from Argument."""
8244 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
8246 def GetValidArg(self, func):
8247 return "client_%s_id_" % self.resource_type.lower()
8249 def GetValidGLArg(self, func):
8250 return "kService%sId" % self.resource_type
8252 def GetNumInvalidValues(self, func):
8253 """returns the number of invalid values to be tested."""
8254 return 1
8256 def GetInvalidArg(self, index):
8257 """returns an invalid value by index."""
8258 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
8261 class Function(object):
8262 """A class that represents a function."""
8264 type_handlers = {
8265 '': TypeHandler(),
8266 'Bind': BindHandler(),
8267 'Create': CreateHandler(),
8268 'Custom': CustomHandler(),
8269 'Data': DataHandler(),
8270 'Delete': DeleteHandler(),
8271 'DELn': DELnHandler(),
8272 'GENn': GENnHandler(),
8273 'GETn': GETnHandler(),
8274 'GLchar': GLcharHandler(),
8275 'GLcharN': GLcharNHandler(),
8276 'HandWritten': HandWrittenHandler(),
8277 'Is': IsHandler(),
8278 'Manual': ManualHandler(),
8279 'PUT': PUTHandler(),
8280 'PUTn': PUTnHandler(),
8281 'PUTSTR': PUTSTRHandler(),
8282 'PUTXn': PUTXnHandler(),
8283 'StateSet': StateSetHandler(),
8284 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
8285 'StateSetFrontBack': StateSetFrontBackHandler(),
8286 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
8287 'StateSetNamedParameter': StateSetNamedParameter(),
8288 'STRn': STRnHandler(),
8289 'Todo': TodoHandler(),
8292 def __init__(self, name, info):
8293 self.name = name
8294 self.original_name = info['original_name']
8296 self.original_args = self.ParseArgs(info['original_args'])
8298 if 'cmd_args' in info:
8299 self.args_for_cmds = self.ParseArgs(info['cmd_args'])
8300 else:
8301 self.args_for_cmds = self.original_args[:]
8303 self.return_type = info['return_type']
8304 if self.return_type != 'void':
8305 self.return_arg = CreateArg(info['return_type'] + " result")
8306 else:
8307 self.return_arg = None
8309 self.num_pointer_args = sum(
8310 [1 for arg in self.args_for_cmds if arg.IsPointer()])
8311 if self.num_pointer_args > 0:
8312 for arg in reversed(self.original_args):
8313 if arg.IsPointer():
8314 self.last_original_pointer_arg = arg
8315 break
8316 else:
8317 self.last_original_pointer_arg = None
8318 self.info = info
8319 self.type_handler = self.type_handlers[info['type']]
8320 self.can_auto_generate = (self.num_pointer_args == 0 and
8321 info['return_type'] == "void")
8322 self.InitFunction()
8324 def ParseArgs(self, arg_string):
8325 """Parses a function arg string."""
8326 args = []
8327 parts = arg_string.split(',')
8328 for arg_string in parts:
8329 arg = CreateArg(arg_string)
8330 if arg:
8331 args.append(arg)
8332 return args
8334 def IsType(self, type_name):
8335 """Returns true if function is a certain type."""
8336 return self.info['type'] == type_name
8338 def InitFunction(self):
8339 """Creates command args and calls the init function for the type handler.
8341 Creates argument lists for command buffer commands, eg. self.cmd_args and
8342 self.init_args.
8343 Calls the type function initialization.
8344 Override to create different kind of command buffer command argument lists.
8346 self.cmd_args = []
8347 for arg in self.args_for_cmds:
8348 arg.AddCmdArgs(self.cmd_args)
8350 self.init_args = []
8351 for arg in self.args_for_cmds:
8352 arg.AddInitArgs(self.init_args)
8354 if self.return_arg:
8355 self.init_args.append(self.return_arg)
8357 self.type_handler.InitFunction(self)
8359 def IsImmediate(self):
8360 """Returns whether the function is immediate data function or not."""
8361 return False
8363 def IsUnsafe(self):
8364 """Returns whether the function has service side validation or not."""
8365 return self.GetInfo('unsafe', False)
8367 def GetInfo(self, name, default = None):
8368 """Returns a value from the function info for this function."""
8369 if name in self.info:
8370 return self.info[name]
8371 return default
8373 def GetValidArg(self, arg):
8374 """Gets a valid argument value for the parameter arg from the function info
8375 if one exists."""
8376 try:
8377 index = self.GetOriginalArgs().index(arg)
8378 except ValueError:
8379 return None
8381 valid_args = self.GetInfo('valid_args')
8382 if valid_args and str(index) in valid_args:
8383 return valid_args[str(index)]
8384 return None
8386 def AddInfo(self, name, value):
8387 """Adds an info."""
8388 self.info[name] = value
8390 def IsExtension(self):
8391 return self.GetInfo('extension') or self.GetInfo('extension_flag')
8393 def IsCoreGLFunction(self):
8394 return (not self.IsExtension() and
8395 not self.GetInfo('pepper_interface') and
8396 not self.IsUnsafe())
8398 def InPepperInterface(self, interface):
8399 ext = self.GetInfo('pepper_interface')
8400 if not interface.GetName():
8401 return self.IsCoreGLFunction()
8402 return ext == interface.GetName()
8404 def InAnyPepperExtension(self):
8405 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
8407 def GetErrorReturnString(self):
8408 if self.GetInfo("error_return"):
8409 return self.GetInfo("error_return")
8410 elif self.return_type == "GLboolean":
8411 return "GL_FALSE"
8412 elif "*" in self.return_type:
8413 return "NULL"
8414 return "0"
8416 def GetGLFunctionName(self):
8417 """Gets the function to call to execute GL for this command."""
8418 if self.GetInfo('decoder_func'):
8419 return self.GetInfo('decoder_func')
8420 return "gl%s" % self.original_name
8422 def GetGLTestFunctionName(self):
8423 gl_func_name = self.GetInfo('gl_test_func')
8424 if gl_func_name == None:
8425 gl_func_name = self.GetGLFunctionName()
8426 if gl_func_name.startswith("gl"):
8427 gl_func_name = gl_func_name[2:]
8428 else:
8429 gl_func_name = self.original_name
8430 return gl_func_name
8432 def GetDataTransferMethods(self):
8433 return self.GetInfo('data_transfer_methods',
8434 ['immediate' if self.num_pointer_args == 1 else 'shm'])
8436 def AddCmdArg(self, arg):
8437 """Adds a cmd argument to this function."""
8438 self.cmd_args.append(arg)
8440 def GetCmdArgs(self):
8441 """Gets the command args for this function."""
8442 return self.cmd_args
8444 def ClearCmdArgs(self):
8445 """Clears the command args for this function."""
8446 self.cmd_args = []
8448 def GetCmdConstants(self):
8449 """Gets the constants for this function."""
8450 return [arg for arg in self.args_for_cmds if arg.IsConstant()]
8452 def GetInitArgs(self):
8453 """Gets the init args for this function."""
8454 return self.init_args
8456 def GetOriginalArgs(self):
8457 """Gets the original arguments to this function."""
8458 return self.original_args
8460 def GetLastOriginalArg(self):
8461 """Gets the last original argument to this function."""
8462 return self.original_args[len(self.original_args) - 1]
8464 def GetLastOriginalPointerArg(self):
8465 return self.last_original_pointer_arg
8467 def GetResourceIdArg(self):
8468 for arg in self.original_args:
8469 if hasattr(arg, 'resource_type'):
8470 return arg
8471 return None
8473 def _MaybePrependComma(self, arg_string, add_comma):
8474 """Adds a comma if arg_string is not empty and add_comma is true."""
8475 comma = ""
8476 if add_comma and len(arg_string):
8477 comma = ", "
8478 return "%s%s" % (comma, arg_string)
8480 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
8481 """Gets a list of arguments as they are in GL."""
8482 args = self.GetOriginalArgs()
8483 arg_string = ", ".join(
8484 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8485 return self._MaybePrependComma(arg_string, add_comma)
8487 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
8488 """Gets the list of arguments as they are in GL."""
8489 args = self.GetOriginalArgs()
8490 arg_string = separator.join(
8491 ["%s%s" % (prefix, arg.name) for arg in args])
8492 return self._MaybePrependComma(arg_string, add_comma)
8494 def MakeTypedHelperArgString(self, prefix, add_comma = False):
8495 """Gets a list of typed GL arguments after removing unneeded arguments."""
8496 args = self.GetOriginalArgs()
8497 arg_string = ", ".join(
8498 ["%s %s%s" % (
8499 arg.type,
8500 prefix,
8501 arg.name,
8502 ) for arg in args if not arg.IsConstant()])
8503 return self._MaybePrependComma(arg_string, add_comma)
8505 def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
8506 """Gets a list of GL arguments after removing unneeded arguments."""
8507 args = self.GetOriginalArgs()
8508 arg_string = separator.join(
8509 ["%s%s" % (prefix, arg.name)
8510 for arg in args if not arg.IsConstant()])
8511 return self._MaybePrependComma(arg_string, add_comma)
8513 def MakeTypedPepperArgString(self, prefix):
8514 """Gets a list of arguments as they need to be for Pepper."""
8515 if self.GetInfo("pepper_args"):
8516 return self.GetInfo("pepper_args")
8517 else:
8518 return self.MakeTypedOriginalArgString(prefix, False)
8520 def MapCTypeToPepperIdlType(self, ctype, is_for_return_type=False):
8521 """Converts a C type name to the corresponding Pepper IDL type."""
8522 idltype = {
8523 'char*': '[out] str_t',
8524 'const GLchar* const*': '[out] cstr_t',
8525 'const char*': 'cstr_t',
8526 'const void*': 'mem_t',
8527 'void*': '[out] mem_t',
8528 'void**': '[out] mem_ptr_t',
8529 }.get(ctype, ctype)
8530 # We use "GLxxx_ptr_t" for "GLxxx*".
8531 matched = re.match(r'(const )?(GL\w+)\*$', ctype)
8532 if matched:
8533 idltype = matched.group(2) + '_ptr_t'
8534 if not matched.group(1):
8535 idltype = '[out] ' + idltype
8536 # If an in/out specifier is not specified yet, prepend [in].
8537 if idltype[0] != '[':
8538 idltype = '[in] ' + idltype
8539 # Strip the in/out specifier for a return type.
8540 if is_for_return_type:
8541 idltype = re.sub(r'\[\w+\] ', '', idltype)
8542 return idltype
8544 def MakeTypedPepperIdlArgStrings(self):
8545 """Gets a list of arguments as they need to be for Pepper IDL."""
8546 args = self.GetOriginalArgs()
8547 return ["%s %s" % (self.MapCTypeToPepperIdlType(arg.type), arg.name)
8548 for arg in args]
8550 def GetPepperName(self):
8551 if self.GetInfo("pepper_name"):
8552 return self.GetInfo("pepper_name")
8553 return self.name
8555 def MakeTypedCmdArgString(self, prefix, add_comma = False):
8556 """Gets a typed list of arguments as they need to be for command buffers."""
8557 args = self.GetCmdArgs()
8558 arg_string = ", ".join(
8559 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8560 return self._MaybePrependComma(arg_string, add_comma)
8562 def MakeCmdArgString(self, prefix, add_comma = False):
8563 """Gets the list of arguments as they need to be for command buffers."""
8564 args = self.GetCmdArgs()
8565 arg_string = ", ".join(
8566 ["%s%s" % (prefix, arg.name) for arg in args])
8567 return self._MaybePrependComma(arg_string, add_comma)
8569 def MakeTypedInitString(self, prefix, add_comma = False):
8570 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
8571 args = self.GetInitArgs()
8572 arg_string = ", ".join(
8573 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8574 return self._MaybePrependComma(arg_string, add_comma)
8576 def MakeInitString(self, prefix, add_comma = False):
8577 """Gets the list of arguments as they need to be for cmd Init/Set."""
8578 args = self.GetInitArgs()
8579 arg_string = ", ".join(
8580 ["%s%s" % (prefix, arg.name) for arg in args])
8581 return self._MaybePrependComma(arg_string, add_comma)
8583 def MakeLogArgString(self):
8584 """Makes a string of the arguments for the LOG macros"""
8585 args = self.GetOriginalArgs()
8586 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
8588 def WriteCommandDescription(self, file):
8589 """Writes a description of the command."""
8590 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
8592 def WriteHandlerValidation(self, file):
8593 """Writes validation code for the function."""
8594 for arg in self.GetOriginalArgs():
8595 arg.WriteValidationCode(file, self)
8596 self.WriteValidationCode(file)
8598 def WriteHandlerImplementation(self, file):
8599 """Writes the handler implementation for this command."""
8600 self.type_handler.WriteHandlerImplementation(self, file)
8602 def WriteValidationCode(self, file):
8603 """Writes the validation code for a command."""
8604 pass
8606 def WriteCmdFlag(self, file):
8607 """Writes the cmd cmd_flags constant."""
8608 flags = []
8609 # By default trace only at the highest level 3.
8610 trace_level = int(self.GetInfo('trace_level', default = 3))
8611 if trace_level not in xrange(0, 4):
8612 raise KeyError("Unhandled trace_level: %d" % trace_level)
8614 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
8616 if len(flags) > 0:
8617 cmd_flags = ' | '.join(flags)
8618 else:
8619 cmd_flags = 0
8621 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
8624 def WriteCmdArgFlag(self, file):
8625 """Writes the cmd kArgFlags constant."""
8626 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
8628 def WriteCmdComputeSize(self, file):
8629 """Writes the ComputeSize function for the command."""
8630 file.Write(" static uint32_t ComputeSize() {\n")
8631 file.Write(
8632 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
8633 file.Write(" }\n")
8634 file.Write("\n")
8636 def WriteCmdSetHeader(self, file):
8637 """Writes the cmd's SetHeader function."""
8638 file.Write(" void SetHeader() {\n")
8639 file.Write(" header.SetCmd<ValueType>();\n")
8640 file.Write(" }\n")
8641 file.Write("\n")
8643 def WriteCmdInit(self, file):
8644 """Writes the cmd's Init function."""
8645 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
8646 file.Write(" SetHeader();\n")
8647 args = self.GetCmdArgs()
8648 for arg in args:
8649 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
8650 file.Write(" }\n")
8651 file.Write("\n")
8653 def WriteCmdSet(self, file):
8654 """Writes the cmd's Set function."""
8655 copy_args = self.MakeCmdArgString("_", False)
8656 file.Write(" void* Set(void* cmd%s) {\n" %
8657 self.MakeTypedCmdArgString("_", True))
8658 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
8659 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
8660 file.Write(" }\n")
8661 file.Write("\n")
8663 def WriteStruct(self, file):
8664 self.type_handler.WriteStruct(self, file)
8666 def WriteDocs(self, file):
8667 self.type_handler.WriteDocs(self, file)
8669 def WriteCmdHelper(self, file):
8670 """Writes the cmd's helper."""
8671 self.type_handler.WriteCmdHelper(self, file)
8673 def WriteServiceImplementation(self, file):
8674 """Writes the service implementation for a command."""
8675 self.type_handler.WriteServiceImplementation(self, file)
8677 def WriteServiceUnitTest(self, file, *extras):
8678 """Writes the service implementation for a command."""
8679 self.type_handler.WriteServiceUnitTest(self, file, *extras)
8681 def WriteGLES2CLibImplementation(self, file):
8682 """Writes the GLES2 C Lib Implemention."""
8683 self.type_handler.WriteGLES2CLibImplementation(self, file)
8685 def WriteGLES2InterfaceHeader(self, file):
8686 """Writes the GLES2 Interface declaration."""
8687 self.type_handler.WriteGLES2InterfaceHeader(self, file)
8689 def WriteGLES2InterfaceStub(self, file):
8690 """Writes the GLES2 Interface Stub declaration."""
8691 self.type_handler.WriteGLES2InterfaceStub(self, file)
8693 def WriteGLES2InterfaceStubImpl(self, file):
8694 """Writes the GLES2 Interface Stub declaration."""
8695 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
8697 def WriteGLES2ImplementationHeader(self, file):
8698 """Writes the GLES2 Implemention declaration."""
8699 self.type_handler.WriteGLES2ImplementationHeader(self, file)
8701 def WriteGLES2Implementation(self, file):
8702 """Writes the GLES2 Implemention definition."""
8703 self.type_handler.WriteGLES2Implementation(self, file)
8705 def WriteGLES2TraceImplementationHeader(self, file):
8706 """Writes the GLES2 Trace Implemention declaration."""
8707 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
8709 def WriteGLES2TraceImplementation(self, file):
8710 """Writes the GLES2 Trace Implemention definition."""
8711 self.type_handler.WriteGLES2TraceImplementation(self, file)
8713 def WriteGLES2Header(self, file):
8714 """Writes the GLES2 Implemention unit test."""
8715 self.type_handler.WriteGLES2Header(self, file)
8717 def WriteGLES2ImplementationUnitTest(self, file):
8718 """Writes the GLES2 Implemention unit test."""
8719 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
8721 def WriteDestinationInitalizationValidation(self, file):
8722 """Writes the client side destintion initialization validation."""
8723 self.type_handler.WriteDestinationInitalizationValidation(self, file)
8725 def WriteFormatTest(self, file):
8726 """Writes the cmd's format test."""
8727 self.type_handler.WriteFormatTest(self, file)
8730 class PepperInterface(object):
8731 """A class that represents a function."""
8733 def __init__(self, info):
8734 self.name = info["name"]
8735 self.dev = info["dev"]
8737 def GetName(self):
8738 return self.name
8740 def GetInterfaceName(self):
8741 upperint = ""
8742 dev = ""
8743 if self.name:
8744 upperint = "_" + self.name.upper()
8745 if self.dev:
8746 dev = "_DEV"
8747 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
8749 def GetInterfaceString(self):
8750 dev = ""
8751 if self.dev:
8752 dev = "(Dev)"
8753 return "PPB_OpenGLES2%s%s" % (self.name, dev)
8755 def GetStructName(self):
8756 dev = ""
8757 if self.dev:
8758 dev = "_Dev"
8759 return "PPB_OpenGLES2%s%s" % (self.name, dev)
8762 class ImmediateFunction(Function):
8763 """A class that represnets an immediate function command."""
8765 def __init__(self, func):
8766 Function.__init__(
8767 self,
8768 "%sImmediate" % func.name,
8769 func.info)
8771 def InitFunction(self):
8772 # Override args in original_args and args_for_cmds with immediate versions
8773 # of the args.
8775 new_original_args = []
8776 for arg in self.original_args:
8777 new_arg = arg.GetImmediateVersion()
8778 if new_arg:
8779 new_original_args.append(new_arg)
8780 self.original_args = new_original_args
8782 new_args_for_cmds = []
8783 for arg in self.args_for_cmds:
8784 new_arg = arg.GetImmediateVersion()
8785 if new_arg:
8786 new_args_for_cmds.append(new_arg)
8788 self.args_for_cmds = new_args_for_cmds
8790 Function.InitFunction(self)
8792 def IsImmediate(self):
8793 return True
8795 def WriteCommandDescription(self, file):
8796 """Overridden from Function"""
8797 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
8798 self.original_name)
8800 def WriteServiceImplementation(self, file):
8801 """Overridden from Function"""
8802 self.type_handler.WriteImmediateServiceImplementation(self, file)
8804 def WriteHandlerImplementation(self, file):
8805 """Overridden from Function"""
8806 self.type_handler.WriteImmediateHandlerImplementation(self, file)
8808 def WriteServiceUnitTest(self, file, *extras):
8809 """Writes the service implementation for a command."""
8810 self.type_handler.WriteImmediateServiceUnitTest(self, file, *extras)
8812 def WriteValidationCode(self, file):
8813 """Overridden from Function"""
8814 self.type_handler.WriteImmediateValidationCode(self, file)
8816 def WriteCmdArgFlag(self, file):
8817 """Overridden from Function"""
8818 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
8820 def WriteCmdComputeSize(self, file):
8821 """Overridden from Function"""
8822 self.type_handler.WriteImmediateCmdComputeSize(self, file)
8824 def WriteCmdSetHeader(self, file):
8825 """Overridden from Function"""
8826 self.type_handler.WriteImmediateCmdSetHeader(self, file)
8828 def WriteCmdInit(self, file):
8829 """Overridden from Function"""
8830 self.type_handler.WriteImmediateCmdInit(self, file)
8832 def WriteCmdSet(self, file):
8833 """Overridden from Function"""
8834 self.type_handler.WriteImmediateCmdSet(self, file)
8836 def WriteCmdHelper(self, file):
8837 """Overridden from Function"""
8838 self.type_handler.WriteImmediateCmdHelper(self, file)
8840 def WriteFormatTest(self, file):
8841 """Overridden from Function"""
8842 self.type_handler.WriteImmediateFormatTest(self, file)
8845 class BucketFunction(Function):
8846 """A class that represnets a bucket version of a function command."""
8848 def __init__(self, func):
8849 Function.__init__(
8850 self,
8851 "%sBucket" % func.name,
8852 func.info)
8854 def InitFunction(self):
8855 # Override args in original_args and args_for_cmds with bucket versions
8856 # of the args.
8858 new_original_args = []
8859 for arg in self.original_args:
8860 new_arg = arg.GetBucketVersion()
8861 if new_arg:
8862 new_original_args.append(new_arg)
8863 self.original_args = new_original_args
8865 new_args_for_cmds = []
8866 for arg in self.args_for_cmds:
8867 new_arg = arg.GetBucketVersion()
8868 if new_arg:
8869 new_args_for_cmds.append(new_arg)
8871 self.args_for_cmds = new_args_for_cmds
8873 Function.InitFunction(self)
8875 def WriteCommandDescription(self, file):
8876 """Overridden from Function"""
8877 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
8878 self.original_name)
8880 def WriteServiceImplementation(self, file):
8881 """Overridden from Function"""
8882 self.type_handler.WriteBucketServiceImplementation(self, file)
8884 def WriteHandlerImplementation(self, file):
8885 """Overridden from Function"""
8886 self.type_handler.WriteBucketHandlerImplementation(self, file)
8888 def WriteServiceUnitTest(self, file, *extras):
8889 """Overridden from Function"""
8890 self.type_handler.WriteBucketServiceUnitTest(self, file, *extras)
8892 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
8893 """Overridden from Function"""
8894 args = self.GetOriginalArgs()
8895 arg_string = separator.join(
8896 ["%s%s" % (prefix, arg.name[0:-10] if arg.name.endswith("_bucket_id")
8897 else arg.name) for arg in args])
8898 return super(BucketFunction, self)._MaybePrependComma(arg_string, add_comma)
8901 def CreateArg(arg_string):
8902 """Creates an Argument."""
8903 arg_parts = arg_string.split()
8904 if len(arg_parts) == 1 and arg_parts[0] == 'void':
8905 return None
8906 # Is this a pointer argument?
8907 elif arg_string.find('*') >= 0:
8908 return PointerArgument(
8909 arg_parts[-1],
8910 " ".join(arg_parts[0:-1]))
8911 # Is this a resource argument? Must come after pointer check.
8912 elif arg_parts[0].startswith('GLidBind'):
8913 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8914 elif arg_parts[0].startswith('GLidZero'):
8915 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8916 elif arg_parts[0].startswith('GLid'):
8917 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8918 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
8919 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8920 elif arg_parts[0].startswith('GLbitfield') and len(arg_parts[0]) > 10:
8921 return BitFieldArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8922 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
8923 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8924 elif arg_parts[0].startswith('GLboolean'):
8925 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8926 elif arg_parts[0].startswith('GLintUniformLocation'):
8927 return UniformLocationArgument(arg_parts[-1])
8928 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
8929 not arg_parts[0].startswith('GLintptr')):
8930 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8931 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
8932 arg_parts[0].startswith('GLintptrNotNegative')):
8933 return SizeNotNegativeArgument(arg_parts[-1],
8934 " ".join(arg_parts[0:-1]),
8935 arg_parts[0][0:-11])
8936 elif arg_parts[0].startswith('GLsize'):
8937 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8938 else:
8939 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8942 class GLGenerator(object):
8943 """A class to generate GL command buffers."""
8945 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
8947 def __init__(self, verbose):
8948 self.original_functions = []
8949 self.functions = []
8950 self.verbose = verbose
8951 self.errors = 0
8952 self.pepper_interfaces = []
8953 self.interface_info = {}
8954 self.generated_cpp_filenames = []
8956 for interface in _PEPPER_INTERFACES:
8957 interface = PepperInterface(interface)
8958 self.pepper_interfaces.append(interface)
8959 self.interface_info[interface.GetName()] = interface
8961 def AddFunction(self, func):
8962 """Adds a function."""
8963 self.functions.append(func)
8965 def GetFunctionInfo(self, name):
8966 """Gets a type info for the given function name."""
8967 if name in _FUNCTION_INFO:
8968 func_info = _FUNCTION_INFO[name].copy()
8969 else:
8970 func_info = {}
8972 if not 'type' in func_info:
8973 func_info['type'] = ''
8975 return func_info
8977 def Log(self, msg):
8978 """Prints something if verbose is true."""
8979 if self.verbose:
8980 print msg
8982 def Error(self, msg):
8983 """Prints an error."""
8984 print "Error: %s" % msg
8985 self.errors += 1
8987 def WriteLicense(self, file):
8988 """Writes the license."""
8989 file.Write(_LICENSE)
8991 def WriteNamespaceOpen(self, file):
8992 """Writes the code for the namespace."""
8993 file.Write("namespace gpu {\n")
8994 file.Write("namespace gles2 {\n")
8995 file.Write("\n")
8997 def WriteNamespaceClose(self, file):
8998 """Writes the code to close the namespace."""
8999 file.Write("} // namespace gles2\n")
9000 file.Write("} // namespace gpu\n")
9001 file.Write("\n")
9003 def ParseGLH(self, filename):
9004 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9005 f = open(filename, "r")
9006 functions = f.read()
9007 f.close()
9008 for line in functions.splitlines():
9009 match = self._function_re.match(line)
9010 if match:
9011 func_name = match.group(2)[2:]
9012 func_info = self.GetFunctionInfo(func_name)
9013 if func_info['type'] == 'Noop':
9014 continue
9016 parsed_func_info = {
9017 'original_name': func_name,
9018 'original_args': match.group(3),
9019 'return_type': match.group(1).strip(),
9022 for k in parsed_func_info.keys():
9023 if not k in func_info:
9024 func_info[k] = parsed_func_info[k]
9026 f = Function(func_name, func_info)
9027 self.original_functions.append(f)
9029 #for arg in f.GetOriginalArgs():
9030 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9031 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9033 gen_cmd = f.GetInfo('gen_cmd')
9034 if gen_cmd == True or gen_cmd == None:
9035 if f.type_handler.NeedsDataTransferFunction(f):
9036 methods = f.GetDataTransferMethods()
9037 if 'immediate' in methods:
9038 self.AddFunction(ImmediateFunction(f))
9039 if 'bucket' in methods:
9040 self.AddFunction(BucketFunction(f))
9041 if 'shm' in methods:
9042 self.AddFunction(f)
9043 else:
9044 self.AddFunction(f)
9046 self.Log("Auto Generated Functions : %d" %
9047 len([f for f in self.functions if f.can_auto_generate or
9048 (not f.IsType('') and not f.IsType('Custom') and
9049 not f.IsType('Todo'))]))
9051 funcs = [f for f in self.functions if not f.can_auto_generate and
9052 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
9053 self.Log("Non Auto Generated Functions: %d" % len(funcs))
9055 for f in funcs:
9056 self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
9058 def WriteCommandIds(self, filename):
9059 """Writes the command buffer format"""
9060 file = CHeaderWriter(filename)
9061 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
9062 id = 256
9063 for func in self.functions:
9064 file.Write(" %-60s /* %d */ \\\n" %
9065 ("OP(%s)" % func.name, id))
9066 id += 1
9067 file.Write("\n")
9069 file.Write("enum CommandId {\n")
9070 file.Write(" kStartPoint = cmd::kLastCommonId, "
9071 "// All GLES2 commands start after this.\n")
9072 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
9073 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9074 file.Write("#undef GLES2_CMD_OP\n")
9075 file.Write(" kNumCommands\n")
9076 file.Write("};\n")
9077 file.Write("\n")
9078 file.Close()
9079 self.generated_cpp_filenames.append(file.filename)
9081 def WriteFormat(self, filename):
9082 """Writes the command buffer format"""
9083 file = CHeaderWriter(filename)
9084 # Forward declaration of a few enums used in constant argument
9085 # to avoid including GL header files.
9086 enum_defines = {
9087 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9088 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9090 file.Write('\n')
9091 for enum in enum_defines:
9092 file.Write("#define %s %s\n" % (enum, enum_defines[enum]))
9093 file.Write('\n')
9094 for func in self.functions:
9095 if True:
9096 #gen_cmd = func.GetInfo('gen_cmd')
9097 #if gen_cmd == True or gen_cmd == None:
9098 func.WriteStruct(file)
9099 file.Write("\n")
9100 file.Close()
9101 self.generated_cpp_filenames.append(file.filename)
9103 def WriteDocs(self, filename):
9104 """Writes the command buffer doc version of the commands"""
9105 file = CWriter(filename)
9106 for func in self.functions:
9107 if True:
9108 #gen_cmd = func.GetInfo('gen_cmd')
9109 #if gen_cmd == True or gen_cmd == None:
9110 func.WriteDocs(file)
9111 file.Write("\n")
9112 file.Close()
9113 self.generated_cpp_filenames.append(file.filename)
9115 def WriteFormatTest(self, filename):
9116 """Writes the command buffer format test."""
9117 file = CHeaderWriter(
9118 filename,
9119 "// This file contains unit tests for gles2 commmands\n"
9120 "// It is included by gles2_cmd_format_test.cc\n"
9121 "\n")
9123 for func in self.functions:
9124 if True:
9125 #gen_cmd = func.GetInfo('gen_cmd')
9126 #if gen_cmd == True or gen_cmd == None:
9127 func.WriteFormatTest(file)
9129 file.Close()
9130 self.generated_cpp_filenames.append(file.filename)
9132 def WriteCmdHelperHeader(self, filename):
9133 """Writes the gles2 command helper."""
9134 file = CHeaderWriter(filename)
9136 for func in self.functions:
9137 if True:
9138 #gen_cmd = func.GetInfo('gen_cmd')
9139 #if gen_cmd == True or gen_cmd == None:
9140 func.WriteCmdHelper(file)
9142 file.Close()
9143 self.generated_cpp_filenames.append(file.filename)
9145 def WriteServiceContextStateHeader(self, filename):
9146 """Writes the service context state header."""
9147 file = CHeaderWriter(
9148 filename,
9149 "// It is included by context_state.h\n")
9150 file.Write("struct EnableFlags {\n")
9151 file.Write(" EnableFlags();\n")
9152 for capability in _CAPABILITY_FLAGS:
9153 file.Write(" bool %s;\n" % capability['name'])
9154 file.Write(" bool cached_%s;\n" % capability['name'])
9155 file.Write("};\n\n")
9157 for state_name in sorted(_STATES.keys()):
9158 state = _STATES[state_name]
9159 for item in state['states']:
9160 if isinstance(item['default'], list):
9161 file.Write("%s %s[%d];\n" % (item['type'], item['name'],
9162 len(item['default'])))
9163 else:
9164 file.Write("%s %s;\n" % (item['type'], item['name']))
9166 if item.get('cached', False):
9167 if isinstance(item['default'], list):
9168 file.Write("%s cached_%s[%d];\n" % (item['type'], item['name'],
9169 len(item['default'])))
9170 else:
9171 file.Write("%s cached_%s;\n" % (item['type'], item['name']))
9173 file.Write("\n")
9175 file.Write("""
9176 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9177 switch (cap) {
9178 """)
9179 for capability in _CAPABILITY_FLAGS:
9180 file.Write("""\
9181 case GL_%s:
9182 """ % capability['name'].upper())
9183 file.Write("""\
9184 if (enable_flags.cached_%(name)s == enable &&
9185 !ignore_cached_state)
9186 return;
9187 enable_flags.cached_%(name)s = enable;
9188 break;
9189 """ % capability)
9191 file.Write("""\
9192 default:
9193 NOTREACHED();
9194 return;
9196 if (enable)
9197 glEnable(cap);
9198 else
9199 glDisable(cap);
9201 """)
9203 file.Close()
9204 self.generated_cpp_filenames.append(file.filename)
9206 def WriteClientContextStateHeader(self, filename):
9207 """Writes the client context state header."""
9208 file = CHeaderWriter(
9209 filename,
9210 "// It is included by client_context_state.h\n")
9211 file.Write("struct EnableFlags {\n")
9212 file.Write(" EnableFlags();\n")
9213 for capability in _CAPABILITY_FLAGS:
9214 file.Write(" bool %s;\n" % capability['name'])
9215 file.Write("};\n\n")
9217 file.Close()
9218 self.generated_cpp_filenames.append(file.filename)
9220 def WriteContextStateGetters(self, file, class_name):
9221 """Writes the state getters."""
9222 for gl_type in ["GLint", "GLfloat"]:
9223 file.Write("""
9224 bool %s::GetStateAs%s(
9225 GLenum pname, %s* params, GLsizei* num_written) const {
9226 switch (pname) {
9227 """ % (class_name, gl_type, gl_type))
9228 for state_name in sorted(_STATES.keys()):
9229 state = _STATES[state_name]
9230 if 'enum' in state:
9231 file.Write(" case %s:\n" % state['enum'])
9232 file.Write(" *num_written = %d;\n" % len(state['states']))
9233 file.Write(" if (params) {\n")
9234 for ndx,item in enumerate(state['states']):
9235 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
9236 (ndx, gl_type, item['name']))
9237 file.Write(" }\n")
9238 file.Write(" return true;\n")
9239 else:
9240 for item in state['states']:
9241 file.Write(" case %s:\n" % item['enum'])
9242 if isinstance(item['default'], list):
9243 item_len = len(item['default'])
9244 file.Write(" *num_written = %d;\n" % item_len)
9245 file.Write(" if (params) {\n")
9246 if item['type'] == gl_type:
9247 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9248 (item['name'], item['type'], item_len))
9249 else:
9250 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
9251 item_len)
9252 file.Write(" params[i] = %s;\n" %
9253 (GetGLGetTypeConversion(gl_type, item['type'],
9254 "%s[i]" % item['name'])))
9255 file.Write(" }\n");
9256 else:
9257 file.Write(" *num_written = 1;\n")
9258 file.Write(" if (params) {\n")
9259 file.Write(" params[0] = %s;\n" %
9260 (GetGLGetTypeConversion(gl_type, item['type'],
9261 item['name'])))
9262 file.Write(" }\n")
9263 file.Write(" return true;\n")
9264 for capability in _CAPABILITY_FLAGS:
9265 file.Write(" case GL_%s:\n" % capability['name'].upper())
9266 file.Write(" *num_written = 1;\n")
9267 file.Write(" if (params) {\n")
9268 file.Write(
9269 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9270 (gl_type, capability['name']))
9271 file.Write(" }\n")
9272 file.Write(" return true;\n")
9273 file.Write(""" default:
9274 return false;
9277 """)
9279 def WriteServiceContextStateImpl(self, filename):
9280 """Writes the context state service implementation."""
9281 file = CHeaderWriter(
9282 filename,
9283 "// It is included by context_state.cc\n")
9284 code = []
9285 for capability in _CAPABILITY_FLAGS:
9286 code.append("%s(%s)" %
9287 (capability['name'],
9288 ('false', 'true')['default' in capability]))
9289 code.append("cached_%s(%s)" %
9290 (capability['name'],
9291 ('false', 'true')['default' in capability]))
9292 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9293 ",\n ".join(code))
9294 file.Write("\n")
9296 file.Write("void ContextState::Initialize() {\n")
9297 for state_name in sorted(_STATES.keys()):
9298 state = _STATES[state_name]
9299 for item in state['states']:
9300 if isinstance(item['default'], list):
9301 for ndx, value in enumerate(item['default']):
9302 file.Write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
9303 else:
9304 file.Write(" %s = %s;\n" % (item['name'], item['default']))
9305 if item.get('cached', False):
9306 if isinstance(item['default'], list):
9307 for ndx, value in enumerate(item['default']):
9308 file.Write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
9309 else:
9310 file.Write(" cached_%s = %s;\n" % (item['name'], item['default']))
9311 file.Write("}\n")
9313 file.Write("""
9314 void ContextState::InitCapabilities(const ContextState* prev_state) const {
9315 """)
9316 def WriteCapabilities(test_prev):
9317 for capability in _CAPABILITY_FLAGS:
9318 capability_name = capability['name']
9319 if test_prev:
9320 file.Write(""" if (prev_state->enable_flags.cached_%s !=
9321 enable_flags.cached_%s)\n""" %
9322 (capability_name, capability_name))
9323 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
9324 (capability_name.upper(), capability_name))
9326 file.Write(" if (prev_state) {")
9327 WriteCapabilities(True)
9328 file.Write(" } else {")
9329 WriteCapabilities(False)
9330 file.Write(" }")
9332 file.Write("""}
9334 void ContextState::InitState(const ContextState *prev_state) const {
9335 """)
9337 def WriteStates(test_prev):
9338 # We need to sort the keys so the expectations match
9339 for state_name in sorted(_STATES.keys()):
9340 state = _STATES[state_name]
9341 if state['type'] == 'FrontBack':
9342 num_states = len(state['states'])
9343 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
9344 if test_prev:
9345 file.Write(" if (")
9346 args = []
9347 for place, item in enumerate(group):
9348 item_name = CachedStateName(item)
9349 args.append('%s' % item_name)
9350 if test_prev:
9351 if place > 0:
9352 file.Write(' ||\n')
9353 file.Write("(%s != prev_state->%s)" % (item_name, item_name))
9354 if test_prev:
9355 file.Write(")\n")
9356 file.Write(
9357 " gl%s(%s, %s);\n" %
9358 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
9359 elif state['type'] == 'NamedParameter':
9360 for item in state['states']:
9361 item_name = CachedStateName(item)
9363 if 'extension_flag' in item:
9364 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
9365 item['extension_flag'])
9366 if test_prev:
9367 if isinstance(item['default'], list):
9368 file.Write(" if (memcmp(prev_state->%s, %s, "
9369 "sizeof(%s) * %d)) {\n" %
9370 (item_name, item_name, item['type'],
9371 len(item['default'])))
9372 else:
9373 file.Write(" if (prev_state->%s != %s) {\n " %
9374 (item_name, item_name))
9375 file.Write(" gl%s(%s, %s);\n" %
9376 (state['func'],
9377 (item['enum_set']
9378 if 'enum_set' in item else item['enum']),
9379 item['name']))
9380 if test_prev:
9381 if 'extension_flag' in item:
9382 file.Write(" ")
9383 file.Write(" }")
9384 if 'extension_flag' in item:
9385 file.Write(" }")
9386 else:
9387 if 'extension_flag' in state:
9388 file.Write(" if (feature_info_->feature_flags().%s)\n " %
9389 state['extension_flag'])
9390 if test_prev:
9391 file.Write(" if (")
9392 args = []
9393 for place, item in enumerate(state['states']):
9394 item_name = CachedStateName(item)
9395 args.append('%s' % item_name)
9396 if test_prev:
9397 if place > 0:
9398 file.Write(' ||\n')
9399 file.Write("(%s != prev_state->%s)" %
9400 (item_name, item_name))
9401 if test_prev:
9402 file.Write(" )\n")
9403 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
9405 file.Write(" if (prev_state) {")
9406 WriteStates(True)
9407 file.Write(" } else {")
9408 WriteStates(False)
9409 file.Write(" }")
9410 file.Write("}\n")
9412 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
9413 switch (cap) {
9414 """)
9415 for capability in _CAPABILITY_FLAGS:
9416 file.Write(" case GL_%s:\n" % capability['name'].upper())
9417 file.Write(" return enable_flags.%s;\n" % capability['name'])
9418 file.Write(""" default:
9419 NOTREACHED();
9420 return false;
9423 """)
9425 self.WriteContextStateGetters(file, "ContextState")
9426 file.Close()
9427 self.generated_cpp_filenames.append(file.filename)
9429 def WriteClientContextStateImpl(self, filename):
9430 """Writes the context state client side implementation."""
9431 file = CHeaderWriter(
9432 filename,
9433 "// It is included by client_context_state.cc\n")
9434 code = []
9435 for capability in _CAPABILITY_FLAGS:
9436 code.append("%s(%s)" %
9437 (capability['name'],
9438 ('false', 'true')['default' in capability]))
9439 file.Write(
9440 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9441 ",\n ".join(code))
9442 file.Write("\n")
9444 file.Write("""
9445 bool ClientContextState::SetCapabilityState(
9446 GLenum cap, bool enabled, bool* changed) {
9447 *changed = false;
9448 switch (cap) {
9449 """)
9450 for capability in _CAPABILITY_FLAGS:
9451 file.Write(" case GL_%s:\n" % capability['name'].upper())
9452 file.Write(""" if (enable_flags.%(name)s != enabled) {
9453 *changed = true;
9454 enable_flags.%(name)s = enabled;
9456 return true;
9457 """ % capability)
9458 file.Write(""" default:
9459 return false;
9462 """)
9463 file.Write("""bool ClientContextState::GetEnabled(
9464 GLenum cap, bool* enabled) const {
9465 switch (cap) {
9466 """)
9467 for capability in _CAPABILITY_FLAGS:
9468 file.Write(" case GL_%s:\n" % capability['name'].upper())
9469 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
9470 file.Write(" return true;\n")
9471 file.Write(""" default:
9472 return false;
9475 """)
9476 file.Close()
9477 self.generated_cpp_filenames.append(file.filename)
9479 def WriteServiceImplementation(self, filename):
9480 """Writes the service decorder implementation."""
9481 file = CHeaderWriter(
9482 filename,
9483 "// It is included by gles2_cmd_decoder.cc\n")
9485 for func in self.functions:
9486 if True:
9487 #gen_cmd = func.GetInfo('gen_cmd')
9488 #if gen_cmd == True or gen_cmd == None:
9489 func.WriteServiceImplementation(file)
9491 file.Write("""
9492 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
9493 switch (cap) {
9494 """)
9495 for capability in _CAPABILITY_FLAGS:
9496 file.Write(" case GL_%s:\n" % capability['name'].upper())
9497 if 'state_flag' in capability:
9499 file.Write("""\
9500 state_.enable_flags.%(name)s = enabled;
9501 if (state_.enable_flags.cached_%(name)s != enabled
9502 || state_.ignore_cached_state) {
9503 %(state_flag)s = true;
9505 return false;
9506 """ % capability)
9507 else:
9508 file.Write("""\
9509 state_.enable_flags.%(name)s = enabled;
9510 if (state_.enable_flags.cached_%(name)s != enabled
9511 || state_.ignore_cached_state) {
9512 state_.enable_flags.cached_%(name)s = enabled;
9513 return true;
9515 return false;
9516 """ % capability)
9517 file.Write(""" default:
9518 NOTREACHED();
9519 return false;
9522 """)
9523 file.Close()
9524 self.generated_cpp_filenames.append(file.filename)
9526 def WriteServiceUnitTests(self, filename):
9527 """Writes the service decorder unit tests."""
9528 num_tests = len(self.functions)
9529 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
9530 count = 0
9531 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
9532 count += 1
9533 name = filename % count
9534 file = CHeaderWriter(
9535 name,
9536 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
9537 test_name = 'GLES2DecoderTest%d' % count
9538 end = test_num + FUNCTIONS_PER_FILE
9539 if end > num_tests:
9540 end = num_tests
9541 for idx in range(test_num, end):
9542 func = self.functions[idx]
9544 # Do any filtering of the functions here, so that the functions
9545 # will not move between the numbered files if filtering properties
9546 # are changed.
9547 if func.GetInfo('extension_flag'):
9548 continue
9550 if True:
9551 #gen_cmd = func.GetInfo('gen_cmd')
9552 #if gen_cmd == True or gen_cmd == None:
9553 if func.GetInfo('unit_test') == False:
9554 file.Write("// TODO(gman): %s\n" % func.name)
9555 else:
9556 func.WriteServiceUnitTest(file, {
9557 'test_name': test_name
9559 file.Close()
9560 self.generated_cpp_filenames.append(file.filename)
9561 file = CHeaderWriter(
9562 filename % 0,
9563 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
9564 file.Write(
9565 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
9566 """)
9567 for capability in _CAPABILITY_FLAGS:
9568 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
9569 (capability['name'].upper(),
9570 ('false', 'true')['default' in capability]))
9571 file.Write("""}
9573 void GLES2DecoderTestBase::SetupInitStateExpectations() {
9574 """)
9576 # We need to sort the keys so the expectations match
9577 for state_name in sorted(_STATES.keys()):
9578 state = _STATES[state_name]
9579 if state['type'] == 'FrontBack':
9580 num_states = len(state['states'])
9581 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
9582 args = []
9583 for item in group:
9584 if 'expected' in item:
9585 args.append(item['expected'])
9586 else:
9587 args.append(item['default'])
9588 file.Write(
9589 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
9590 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
9591 file.Write(" .Times(1)\n")
9592 file.Write(" .RetiresOnSaturation();\n")
9593 elif state['type'] == 'NamedParameter':
9594 for item in state['states']:
9595 if 'extension_flag' in item:
9596 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
9597 item['extension_flag'])
9598 file.Write(" ")
9599 expect_value = item['default']
9600 if isinstance(expect_value, list):
9601 # TODO: Currently we do not check array values.
9602 expect_value = "_"
9604 file.Write(
9605 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
9606 (state['func'],
9607 (item['enum_set']
9608 if 'enum_set' in item else item['enum']),
9609 expect_value))
9610 file.Write(" .Times(1)\n")
9611 file.Write(" .RetiresOnSaturation();\n")
9612 if 'extension_flag' in item:
9613 file.Write(" }\n")
9614 else:
9615 if 'extension_flag' in state:
9616 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
9617 state['extension_flag'])
9618 file.Write(" ")
9619 args = []
9620 for item in state['states']:
9621 if 'expected' in item:
9622 args.append(item['expected'])
9623 else:
9624 args.append(item['default'])
9625 # TODO: Currently we do not check array values.
9626 args = ["_" if isinstance(arg, list) else arg for arg in args]
9627 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
9628 (state['func'], ", ".join(args)))
9629 file.Write(" .Times(1)\n")
9630 file.Write(" .RetiresOnSaturation();\n")
9631 if 'extension_flag' in state:
9632 file.Write(" }\n")
9633 file.Write("""}
9634 """)
9635 file.Close()
9636 self.generated_cpp_filenames.append(file.filename)
9638 def WriteServiceUnitTestsForExtensions(self, filename):
9639 """Writes the service decorder unit tests for functions with extension_flag.
9641 The functions are special in that they need a specific unit test
9642 baseclass to turn on the extension.
9644 functions = [f for f in self.functions if f.GetInfo('extension_flag')]
9645 file = CHeaderWriter(
9646 filename,
9647 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
9648 for func in functions:
9649 if True:
9650 if func.GetInfo('unit_test') == False:
9651 file.Write("// TODO(gman): %s\n" % func.name)
9652 else:
9653 extension = ToCamelCase(
9654 ToGLExtensionString(func.GetInfo('extension_flag')))
9655 func.WriteServiceUnitTest(file, {
9656 'test_name': 'GLES2DecoderTestWith%s' % extension
9659 file.Close()
9660 self.generated_cpp_filenames.append(file.filename)
9662 def WriteGLES2Header(self, filename):
9663 """Writes the GLES2 header."""
9664 file = CHeaderWriter(
9665 filename,
9666 "// This file contains Chromium-specific GLES2 declarations.\n\n")
9668 for func in self.original_functions:
9669 func.WriteGLES2Header(file)
9671 file.Write("\n")
9672 file.Close()
9673 self.generated_cpp_filenames.append(file.filename)
9675 def WriteGLES2CLibImplementation(self, filename):
9676 """Writes the GLES2 c lib implementation."""
9677 file = CHeaderWriter(
9678 filename,
9679 "// These functions emulate GLES2 over command buffers.\n")
9681 for func in self.original_functions:
9682 func.WriteGLES2CLibImplementation(file)
9684 file.Write("""
9685 namespace gles2 {
9687 extern const NameToFunc g_gles2_function_table[] = {
9688 """)
9689 for func in self.original_functions:
9690 file.Write(
9691 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
9692 (func.name, func.name))
9693 file.Write(""" { NULL, NULL, },
9696 } // namespace gles2
9697 """)
9698 file.Close()
9699 self.generated_cpp_filenames.append(file.filename)
9701 def WriteGLES2InterfaceHeader(self, filename):
9702 """Writes the GLES2 interface header."""
9703 file = CHeaderWriter(
9704 filename,
9705 "// This file is included by gles2_interface.h to declare the\n"
9706 "// GL api functions.\n")
9707 for func in self.original_functions:
9708 func.WriteGLES2InterfaceHeader(file)
9709 file.Close()
9710 self.generated_cpp_filenames.append(file.filename)
9712 def WriteGLES2InterfaceStub(self, filename):
9713 """Writes the GLES2 interface stub header."""
9714 file = CHeaderWriter(
9715 filename,
9716 "// This file is included by gles2_interface_stub.h.\n")
9717 for func in self.original_functions:
9718 func.WriteGLES2InterfaceStub(file)
9719 file.Close()
9720 self.generated_cpp_filenames.append(file.filename)
9722 def WriteGLES2InterfaceStubImpl(self, filename):
9723 """Writes the GLES2 interface header."""
9724 file = CHeaderWriter(
9725 filename,
9726 "// This file is included by gles2_interface_stub.cc.\n")
9727 for func in self.original_functions:
9728 func.WriteGLES2InterfaceStubImpl(file)
9729 file.Close()
9730 self.generated_cpp_filenames.append(file.filename)
9732 def WriteGLES2ImplementationHeader(self, filename):
9733 """Writes the GLES2 Implementation header."""
9734 file = CHeaderWriter(
9735 filename,
9736 "// This file is included by gles2_implementation.h to declare the\n"
9737 "// GL api functions.\n")
9738 for func in self.original_functions:
9739 func.WriteGLES2ImplementationHeader(file)
9740 file.Close()
9741 self.generated_cpp_filenames.append(file.filename)
9743 def WriteGLES2Implementation(self, filename):
9744 """Writes the GLES2 Implementation."""
9745 file = CHeaderWriter(
9746 filename,
9747 "// This file is included by gles2_implementation.cc to define the\n"
9748 "// GL api functions.\n")
9749 for func in self.original_functions:
9750 func.WriteGLES2Implementation(file)
9751 file.Close()
9752 self.generated_cpp_filenames.append(file.filename)
9754 def WriteGLES2TraceImplementationHeader(self, filename):
9755 """Writes the GLES2 Trace Implementation header."""
9756 file = CHeaderWriter(
9757 filename,
9758 "// This file is included by gles2_trace_implementation.h\n")
9759 for func in self.original_functions:
9760 func.WriteGLES2TraceImplementationHeader(file)
9761 file.Close()
9762 self.generated_cpp_filenames.append(file.filename)
9764 def WriteGLES2TraceImplementation(self, filename):
9765 """Writes the GLES2 Trace Implementation."""
9766 file = CHeaderWriter(
9767 filename,
9768 "// This file is included by gles2_trace_implementation.cc\n")
9769 for func in self.original_functions:
9770 func.WriteGLES2TraceImplementation(file)
9771 file.Close()
9772 self.generated_cpp_filenames.append(file.filename)
9774 def WriteGLES2ImplementationUnitTests(self, filename):
9775 """Writes the GLES2 helper header."""
9776 file = CHeaderWriter(
9777 filename,
9778 "// This file is included by gles2_implementation.h to declare the\n"
9779 "// GL api functions.\n")
9780 for func in self.original_functions:
9781 func.WriteGLES2ImplementationUnitTest(file)
9782 file.Close()
9783 self.generated_cpp_filenames.append(file.filename)
9785 def WriteServiceUtilsHeader(self, filename):
9786 """Writes the gles2 auto generated utility header."""
9787 file = CHeaderWriter(filename)
9788 for name in sorted(_NAMED_TYPE_INFO.keys()):
9789 named_type = NamedType(_NAMED_TYPE_INFO[name])
9790 if named_type.IsConstant():
9791 continue
9792 file.Write("ValueValidator<%s> %s;\n" %
9793 (named_type.GetType(), ToUnderscore(name)))
9794 file.Write("\n")
9795 file.Close()
9796 self.generated_cpp_filenames.append(file.filename)
9798 def WriteServiceUtilsImplementation(self, filename):
9799 """Writes the gles2 auto generated utility implementation."""
9800 file = CHeaderWriter(filename)
9801 names = sorted(_NAMED_TYPE_INFO.keys())
9802 for name in names:
9803 named_type = NamedType(_NAMED_TYPE_INFO[name])
9804 if named_type.IsConstant():
9805 continue
9806 if named_type.GetValidValues():
9807 file.Write("static const %s valid_%s_table[] = {\n" %
9808 (named_type.GetType(), ToUnderscore(name)))
9809 for value in named_type.GetValidValues():
9810 file.Write(" %s,\n" % value)
9811 file.Write("};\n")
9812 file.Write("\n")
9813 file.Write("Validators::Validators()")
9814 pre = ' : '
9815 for count, name in enumerate(names):
9816 named_type = NamedType(_NAMED_TYPE_INFO[name])
9817 if named_type.IsConstant():
9818 continue
9819 if named_type.GetValidValues():
9820 code = """%(pre)s%(name)s(
9821 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
9822 else:
9823 code = "%(pre)s%(name)s()"
9824 file.Write(code % {
9825 'name': ToUnderscore(name),
9826 'pre': pre,
9828 pre = ',\n '
9829 file.Write(" {\n");
9830 file.Write("}\n\n");
9831 file.Close()
9832 self.generated_cpp_filenames.append(file.filename)
9834 def WriteCommonUtilsHeader(self, filename):
9835 """Writes the gles2 common utility header."""
9836 file = CHeaderWriter(filename)
9837 type_infos = sorted(_NAMED_TYPE_INFO.keys())
9838 for type_info in type_infos:
9839 if _NAMED_TYPE_INFO[type_info]['type'] == 'GLenum':
9840 file.Write("static std::string GetString%s(uint32_t value);\n" %
9841 type_info)
9842 file.Write("\n")
9843 file.Close()
9844 self.generated_cpp_filenames.append(file.filename)
9846 def WriteCommonUtilsImpl(self, filename):
9847 """Writes the gles2 common utility header."""
9848 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
9849 dict = {}
9850 for fname in ['third_party/khronos/GLES2/gl2.h',
9851 'third_party/khronos/GLES2/gl2ext.h',
9852 'third_party/khronos/GLES3/gl3.h',
9853 'gpu/GLES2/gl2chromium.h',
9854 'gpu/GLES2/gl2extchromium.h']:
9855 lines = open(fname).readlines()
9856 for line in lines:
9857 m = enum_re.match(line)
9858 if m:
9859 name = m.group(1)
9860 value = m.group(2)
9861 if len(value) <= 10:
9862 if not value in dict:
9863 dict[value] = name
9864 # check our own _CHROMIUM macro conflicts with khronos GL headers.
9865 elif dict[value] != name and (name.endswith('_CHROMIUM') or
9866 dict[value].endswith('_CHROMIUM')):
9867 self.Error("code collision: %s and %s have the same code %s" %
9868 (dict[value], name, value))
9870 file = CHeaderWriter(filename)
9871 file.Write("static const GLES2Util::EnumToString "
9872 "enum_to_string_table[] = {\n")
9873 for value in dict:
9874 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
9875 file.Write("""};
9877 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
9878 enum_to_string_table;
9879 const size_t GLES2Util::enum_to_string_table_len_ =
9880 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
9882 """)
9884 enums = sorted(_NAMED_TYPE_INFO.keys())
9885 for enum in enums:
9886 if _NAMED_TYPE_INFO[enum]['type'] == 'GLenum':
9887 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
9888 enum)
9889 if len(_NAMED_TYPE_INFO[enum]['valid']) > 0:
9890 file.Write(" static const EnumToString string_table[] = {\n")
9891 for value in _NAMED_TYPE_INFO[enum]['valid']:
9892 file.Write(' { %s, "%s" },\n' % (value, value))
9893 file.Write(""" };
9894 return GLES2Util::GetQualifiedEnumString(
9895 string_table, arraysize(string_table), value);
9898 """)
9899 else:
9900 file.Write(""" return GLES2Util::GetQualifiedEnumString(
9901 NULL, 0, value);
9904 """)
9905 file.Close()
9906 self.generated_cpp_filenames.append(file.filename)
9908 def WritePepperGLES2Interface(self, filename, dev):
9909 """Writes the Pepper OpenGLES interface definition."""
9910 file = CWriter(filename)
9911 file.Write(_LICENSE)
9912 file.Write(_DO_NOT_EDIT_WARNING)
9914 file.Write("label Chrome {\n")
9915 file.Write(" M39 = 1.0\n")
9916 file.Write("};\n\n")
9918 if not dev:
9919 # Declare GL types.
9920 file.Write("[version=1.0]\n")
9921 file.Write("describe {\n")
9922 for gltype in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
9923 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
9924 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
9925 'GLubyte', 'GLuint', 'GLushort']:
9926 file.Write(" %s;\n" % gltype)
9927 file.Write(" %s_ptr_t;\n" % gltype)
9928 file.Write("};\n\n")
9930 # C level typedefs.
9931 file.Write("#inline c\n")
9932 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
9933 if dev:
9934 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
9935 else:
9936 file.Write("\n#ifndef __gl2_h_\n")
9937 for (k, v) in _GL_TYPES.iteritems():
9938 file.Write("typedef %s %s;\n" % (v, k))
9939 file.Write("#ifdef _WIN64\n")
9940 for (k, v) in _GL_TYPES_64.iteritems():
9941 file.Write("typedef %s %s;\n" % (v, k))
9942 file.Write("#else\n")
9943 for (k, v) in _GL_TYPES_32.iteritems():
9944 file.Write("typedef %s %s;\n" % (v, k))
9945 file.Write("#endif // _WIN64\n")
9946 file.Write("#endif // __gl2_h_\n\n")
9947 file.Write("#endinl\n")
9949 for interface in self.pepper_interfaces:
9950 if interface.dev != dev:
9951 continue
9952 # Historically, we provide OpenGLES2 interfaces with struct
9953 # namespace. Not to break code which uses the interface as
9954 # "struct OpenGLES2", we put it in struct namespace.
9955 file.Write('\n[macro="%s", force_struct_namespace]\n' %
9956 interface.GetInterfaceName())
9957 file.Write("interface %s {\n" % interface.GetStructName())
9958 for func in self.original_functions:
9959 if not func.InPepperInterface(interface):
9960 continue
9962 ret_type = func.MapCTypeToPepperIdlType(func.return_type,
9963 is_for_return_type=True)
9964 func_prefix = " %s %s(" % (ret_type, func.GetPepperName())
9965 file.Write(func_prefix)
9966 file.Write("[in] PP_Resource context")
9967 for arg in func.MakeTypedPepperIdlArgStrings():
9968 file.Write(",\n" + " " * len(func_prefix) + arg)
9969 file.Write(");\n")
9970 file.Write("};\n\n")
9973 file.Close()
9975 def WritePepperGLES2Implementation(self, filename):
9976 """Writes the Pepper OpenGLES interface implementation."""
9978 file = CWriter(filename)
9979 file.Write(_LICENSE)
9980 file.Write(_DO_NOT_EDIT_WARNING)
9982 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
9983 file.Write("#include \"base/logging.h\"\n")
9984 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
9985 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
9986 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
9988 file.Write("namespace ppapi {\n\n")
9989 file.Write("namespace {\n\n")
9991 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
9992 " Enter3D;\n\n")
9994 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
9995 " enter) {\n")
9996 file.Write(" DCHECK(enter);\n")
9997 file.Write(" DCHECK(enter->succeeded());\n")
9998 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
9999 "gles2_impl();\n");
10000 file.Write("}\n\n");
10002 for func in self.original_functions:
10003 if not func.InAnyPepperExtension():
10004 continue
10006 original_arg = func.MakeTypedPepperArgString("")
10007 context_arg = "PP_Resource context_id"
10008 if len(original_arg):
10009 arg = context_arg + ", " + original_arg
10010 else:
10011 arg = context_arg
10012 file.Write("%s %s(%s) {\n" %
10013 (func.return_type, func.GetPepperName(), arg))
10014 file.Write(" Enter3D enter(context_id, true);\n")
10015 file.Write(" if (enter.succeeded()) {\n")
10017 return_str = "" if func.return_type == "void" else "return "
10018 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10019 (return_str, func.original_name,
10020 func.MakeOriginalArgString("")))
10021 file.Write(" }")
10022 if func.return_type == "void":
10023 file.Write("\n")
10024 else:
10025 file.Write(" else {\n")
10026 file.Write(" return %s;\n" % func.GetErrorReturnString())
10027 file.Write(" }\n")
10028 file.Write("}\n\n")
10030 file.Write("} // namespace\n")
10032 for interface in self.pepper_interfaces:
10033 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10034 (interface.GetStructName(), interface.GetName()))
10035 file.Write(" static const struct %s "
10036 "ppb_opengles2 = {\n" % interface.GetStructName())
10037 file.Write(" &")
10038 file.Write(",\n &".join(
10039 f.GetPepperName() for f in self.original_functions
10040 if f.InPepperInterface(interface)))
10041 file.Write("\n")
10043 file.Write(" };\n")
10044 file.Write(" return &ppb_opengles2;\n")
10045 file.Write("}\n")
10047 file.Write("} // namespace ppapi\n")
10048 file.Close()
10049 self.generated_cpp_filenames.append(file.filename)
10051 def WriteGLES2ToPPAPIBridge(self, filename):
10052 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10054 file = CWriter(filename)
10055 file.Write(_LICENSE)
10056 file.Write(_DO_NOT_EDIT_WARNING)
10058 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
10059 file.Write("#define GL_GLEXT_PROTOTYPES\n")
10060 file.Write("#endif\n")
10061 file.Write("#include <GLES2/gl2.h>\n")
10062 file.Write("#include <GLES2/gl2ext.h>\n")
10063 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10065 for func in self.original_functions:
10066 if not func.InAnyPepperExtension():
10067 continue
10069 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
10071 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
10072 (func.return_type, func.GetPepperName(),
10073 func.MakeTypedPepperArgString("")))
10074 return_str = "" if func.return_type == "void" else "return "
10075 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
10076 original_arg = func.MakeOriginalArgString("")
10077 context_arg = "glGetCurrentContextPPAPI()"
10078 if len(original_arg):
10079 arg = context_arg + ", " + original_arg
10080 else:
10081 arg = context_arg
10082 if interface.GetName():
10083 file.Write(" const struct %s* ext = %s;\n" %
10084 (interface.GetStructName(), interface_str))
10085 file.Write(" if (ext)\n")
10086 file.Write(" %sext->%s(%s);\n" %
10087 (return_str, func.GetPepperName(), arg))
10088 if return_str:
10089 file.Write(" %s0;\n" % return_str)
10090 else:
10091 file.Write(" %s%s->%s(%s);\n" %
10092 (return_str, interface_str, func.GetPepperName(), arg))
10093 file.Write("}\n\n")
10094 file.Close()
10095 self.generated_cpp_filenames.append(file.filename)
10097 def WriteMojoGLCallVisitor(self, filename):
10098 """Provides the GL implementation for mojo"""
10099 file = CWriter(filename)
10100 file.Write(_LICENSE)
10101 file.Write(_DO_NOT_EDIT_WARNING)
10103 for func in self.original_functions:
10104 if not func.IsCoreGLFunction():
10105 continue
10106 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10107 (func.name, func.return_type,
10108 func.MakeTypedOriginalArgString(""),
10109 func.MakeOriginalArgString("")))
10111 file.Close()
10112 self.generated_cpp_filenames.append(file.filename)
10114 def WriteMojoGLCallVisitorForExtension(self, filename, extension):
10115 """Provides the GL implementation for mojo for a particular extension"""
10116 file = CWriter(filename)
10117 file.Write(_LICENSE)
10118 file.Write(_DO_NOT_EDIT_WARNING)
10120 for func in self.original_functions:
10121 if func.GetInfo("extension") != extension:
10122 continue
10123 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10124 (func.name, func.return_type,
10125 func.MakeTypedOriginalArgString(""),
10126 func.MakeOriginalArgString("")))
10128 file.Close()
10129 self.generated_cpp_filenames.append(file.filename)
10131 def Format(generated_files):
10132 formatter = "clang-format"
10133 if platform.system() == "Windows":
10134 formatter += ".bat"
10135 for filename in generated_files:
10136 call([formatter, "-i", "-style=chromium", filename])
10138 def main(argv):
10139 """This is the main function."""
10140 parser = OptionParser()
10141 parser.add_option(
10142 "--output-dir",
10143 help="base directory for resulting files, under chrome/src. default is "
10144 "empty. Use this if you want the result stored under gen.")
10145 parser.add_option(
10146 "-v", "--verbose", action="store_true",
10147 help="prints more output.")
10149 (options, args) = parser.parse_args(args=argv)
10151 # Add in states and capabilites to GLState
10152 gl_state_valid = _NAMED_TYPE_INFO['GLState']['valid']
10153 for state_name in sorted(_STATES.keys()):
10154 state = _STATES[state_name]
10155 if 'extension_flag' in state:
10156 continue
10157 if 'enum' in state:
10158 if not state['enum'] in gl_state_valid:
10159 gl_state_valid.append(state['enum'])
10160 else:
10161 for item in state['states']:
10162 if 'extension_flag' in item:
10163 continue
10164 if not item['enum'] in gl_state_valid:
10165 gl_state_valid.append(item['enum'])
10166 for capability in _CAPABILITY_FLAGS:
10167 valid_value = "GL_%s" % capability['name'].upper()
10168 if not valid_value in gl_state_valid:
10169 gl_state_valid.append(valid_value)
10171 # This script lives under gpu/command_buffer, cd to base directory.
10172 os.chdir(os.path.dirname(__file__) + "/../..")
10173 base_dir = os.getcwd()
10174 gen = GLGenerator(options.verbose)
10175 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10177 # Support generating files under gen/
10178 if options.output_dir != None:
10179 os.chdir(options.output_dir)
10181 gen.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10182 gen.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10183 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10184 gen.WritePepperGLES2Implementation(
10185 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10186 os.chdir(base_dir)
10187 gen.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10188 gen.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10189 gen.WriteFormatTest(
10190 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10191 gen.WriteGLES2InterfaceHeader(
10192 "gpu/command_buffer/client/gles2_interface_autogen.h")
10193 gen.WriteGLES2InterfaceStub(
10194 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10195 gen.WriteGLES2InterfaceStubImpl(
10196 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10197 gen.WriteGLES2ImplementationHeader(
10198 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10199 gen.WriteGLES2Implementation(
10200 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10201 gen.WriteGLES2ImplementationUnitTests(
10202 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10203 gen.WriteGLES2TraceImplementationHeader(
10204 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10205 gen.WriteGLES2TraceImplementation(
10206 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10207 gen.WriteGLES2CLibImplementation(
10208 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10209 gen.WriteCmdHelperHeader(
10210 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
10211 gen.WriteServiceImplementation(
10212 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
10213 gen.WriteServiceContextStateHeader(
10214 "gpu/command_buffer/service/context_state_autogen.h")
10215 gen.WriteServiceContextStateImpl(
10216 "gpu/command_buffer/service/context_state_impl_autogen.h")
10217 gen.WriteClientContextStateHeader(
10218 "gpu/command_buffer/client/client_context_state_autogen.h")
10219 gen.WriteClientContextStateImpl(
10220 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
10221 gen.WriteServiceUnitTests(
10222 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
10223 gen.WriteServiceUnitTestsForExtensions(
10224 "gpu/command_buffer/service/"
10225 "gles2_cmd_decoder_unittest_extensions_autogen.h")
10226 gen.WriteServiceUtilsHeader(
10227 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
10228 gen.WriteServiceUtilsImplementation(
10229 "gpu/command_buffer/service/"
10230 "gles2_cmd_validation_implementation_autogen.h")
10231 gen.WriteCommonUtilsHeader(
10232 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
10233 gen.WriteCommonUtilsImpl(
10234 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
10235 gen.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
10236 mojo_gles2_prefix = ("third_party/mojo/src/mojo/public/c/gles2/"
10237 "gles2_call_visitor")
10238 gen.WriteMojoGLCallVisitor(mojo_gles2_prefix + "_autogen.h")
10239 gen.WriteMojoGLCallVisitorForExtension(
10240 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
10241 "CHROMIUM_texture_mailbox")
10242 gen.WriteMojoGLCallVisitorForExtension(
10243 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
10244 "CHROMIUM_sync_point")
10246 Format(gen.generated_cpp_filenames)
10248 if gen.errors > 0:
10249 print "%d errors" % gen.errors
10250 return 1
10251 return 0
10254 if __name__ == '__main__':
10255 sys.exit(main(sys.argv[1:]))