Delete chrome.mediaGalleriesPrivate because the functionality unique to it has since...
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blob922c1f9488ae28991361e313a3fd3e92d75b142d
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 'FrameBufferParameter': {
943 'type': 'GLenum',
944 'valid': [
945 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
946 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
947 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
948 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
951 'MatrixMode': {
952 'type': 'GLenum',
953 'valid': [
954 'GL_PATH_PROJECTION_CHROMIUM',
955 'GL_PATH_MODELVIEW_CHROMIUM',
958 'ProgramParameter': {
959 'type': 'GLenum',
960 'valid': [
961 'GL_DELETE_STATUS',
962 'GL_LINK_STATUS',
963 'GL_VALIDATE_STATUS',
964 'GL_INFO_LOG_LENGTH',
965 'GL_ATTACHED_SHADERS',
966 'GL_ACTIVE_ATTRIBUTES',
967 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
968 'GL_ACTIVE_UNIFORMS',
969 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
972 'QueryObjectParameter': {
973 'type': 'GLenum',
974 'valid': [
975 'GL_QUERY_RESULT_EXT',
976 'GL_QUERY_RESULT_AVAILABLE_EXT',
979 'QueryParameter': {
980 'type': 'GLenum',
981 'valid': [
982 'GL_CURRENT_QUERY_EXT',
985 'QueryTarget': {
986 'type': 'GLenum',
987 'valid': [
988 'GL_ANY_SAMPLES_PASSED_EXT',
989 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
990 'GL_COMMANDS_ISSUED_CHROMIUM',
991 'GL_LATENCY_QUERY_CHROMIUM',
992 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
993 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
994 'GL_COMMANDS_COMPLETED_CHROMIUM',
997 'RenderBufferParameter': {
998 'type': 'GLenum',
999 'valid': [
1000 'GL_RENDERBUFFER_RED_SIZE',
1001 'GL_RENDERBUFFER_GREEN_SIZE',
1002 'GL_RENDERBUFFER_BLUE_SIZE',
1003 'GL_RENDERBUFFER_ALPHA_SIZE',
1004 'GL_RENDERBUFFER_DEPTH_SIZE',
1005 'GL_RENDERBUFFER_STENCIL_SIZE',
1006 'GL_RENDERBUFFER_WIDTH',
1007 'GL_RENDERBUFFER_HEIGHT',
1008 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1011 'SamplerParameter': {
1012 'type': 'GLenum',
1013 'valid': [
1014 'GL_TEXTURE_MAG_FILTER',
1015 'GL_TEXTURE_MIN_FILTER',
1016 'GL_TEXTURE_MIN_LOD',
1017 'GL_TEXTURE_MAX_LOD',
1018 'GL_TEXTURE_WRAP_S',
1019 'GL_TEXTURE_WRAP_T',
1020 'GL_TEXTURE_WRAP_R',
1021 'GL_TEXTURE_COMPARE_MODE',
1022 'GL_TEXTURE_COMPARE_FUNC',
1024 'invalid': [
1025 'GL_GENERATE_MIPMAP',
1028 'ShaderParameter': {
1029 'type': 'GLenum',
1030 'valid': [
1031 'GL_SHADER_TYPE',
1032 'GL_DELETE_STATUS',
1033 'GL_COMPILE_STATUS',
1034 'GL_INFO_LOG_LENGTH',
1035 'GL_SHADER_SOURCE_LENGTH',
1036 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1039 'ShaderPrecision': {
1040 'type': 'GLenum',
1041 'valid': [
1042 'GL_LOW_FLOAT',
1043 'GL_MEDIUM_FLOAT',
1044 'GL_HIGH_FLOAT',
1045 'GL_LOW_INT',
1046 'GL_MEDIUM_INT',
1047 'GL_HIGH_INT',
1050 'StringType': {
1051 'type': 'GLenum',
1052 'valid': [
1053 'GL_VENDOR',
1054 'GL_RENDERER',
1055 'GL_VERSION',
1056 'GL_SHADING_LANGUAGE_VERSION',
1057 'GL_EXTENSIONS',
1060 'TextureParameter': {
1061 'type': 'GLenum',
1062 'valid': [
1063 'GL_TEXTURE_MAG_FILTER',
1064 'GL_TEXTURE_MIN_FILTER',
1065 'GL_TEXTURE_POOL_CHROMIUM',
1066 'GL_TEXTURE_WRAP_S',
1067 'GL_TEXTURE_WRAP_T',
1069 'invalid': [
1070 'GL_GENERATE_MIPMAP',
1073 'TexturePool': {
1074 'type': 'GLenum',
1075 'valid': [
1076 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1077 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1080 'TextureWrapMode': {
1081 'type': 'GLenum',
1082 'valid': [
1083 'GL_CLAMP_TO_EDGE',
1084 'GL_MIRRORED_REPEAT',
1085 'GL_REPEAT',
1088 'TextureMinFilterMode': {
1089 'type': 'GLenum',
1090 'valid': [
1091 'GL_NEAREST',
1092 'GL_LINEAR',
1093 'GL_NEAREST_MIPMAP_NEAREST',
1094 'GL_LINEAR_MIPMAP_NEAREST',
1095 'GL_NEAREST_MIPMAP_LINEAR',
1096 'GL_LINEAR_MIPMAP_LINEAR',
1099 'TextureMagFilterMode': {
1100 'type': 'GLenum',
1101 'valid': [
1102 'GL_NEAREST',
1103 'GL_LINEAR',
1106 'TextureUsage': {
1107 'type': 'GLenum',
1108 'valid': [
1109 'GL_NONE',
1110 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1113 'VertexAttribute': {
1114 'type': 'GLenum',
1115 'valid': [
1116 # some enum that the decoder actually passes through to GL needs
1117 # to be the first listed here since it's used in unit tests.
1118 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1119 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1120 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1121 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1122 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1123 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1124 'GL_CURRENT_VERTEX_ATTRIB',
1127 'VertexPointer': {
1128 'type': 'GLenum',
1129 'valid': [
1130 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1133 'HintTarget': {
1134 'type': 'GLenum',
1135 'valid': [
1136 'GL_GENERATE_MIPMAP_HINT',
1138 'invalid': [
1139 'GL_PERSPECTIVE_CORRECTION_HINT',
1142 'HintMode': {
1143 'type': 'GLenum',
1144 'valid': [
1145 'GL_FASTEST',
1146 'GL_NICEST',
1147 'GL_DONT_CARE',
1150 'PixelStore': {
1151 'type': 'GLenum',
1152 'valid': [
1153 'GL_PACK_ALIGNMENT',
1154 'GL_UNPACK_ALIGNMENT',
1155 'GL_UNPACK_FLIP_Y_CHROMIUM',
1156 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
1157 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
1159 'invalid': [
1160 'GL_PACK_SWAP_BYTES',
1161 'GL_UNPACK_SWAP_BYTES',
1164 'PixelStoreAlignment': {
1165 'type': 'GLint',
1166 'valid': [
1167 '1',
1168 '2',
1169 '4',
1170 '8',
1172 'invalid': [
1173 '3',
1174 '9',
1177 'ReadPixelFormat': {
1178 'type': 'GLenum',
1179 'valid': [
1180 'GL_ALPHA',
1181 'GL_RGB',
1182 'GL_RGBA',
1185 'PixelType': {
1186 'type': 'GLenum',
1187 'valid': [
1188 'GL_UNSIGNED_BYTE',
1189 'GL_UNSIGNED_SHORT_5_6_5',
1190 'GL_UNSIGNED_SHORT_4_4_4_4',
1191 'GL_UNSIGNED_SHORT_5_5_5_1',
1193 'invalid': [
1194 'GL_SHORT',
1195 'GL_INT',
1198 'ReadPixelType': {
1199 'type': 'GLenum',
1200 'valid': [
1201 'GL_UNSIGNED_BYTE',
1202 'GL_UNSIGNED_SHORT_5_6_5',
1203 'GL_UNSIGNED_SHORT_4_4_4_4',
1204 'GL_UNSIGNED_SHORT_5_5_5_1',
1206 'invalid': [
1207 'GL_SHORT',
1208 'GL_INT',
1211 'RenderBufferFormat': {
1212 'type': 'GLenum',
1213 'valid': [
1214 'GL_RGBA4',
1215 'GL_RGB565',
1216 'GL_RGB5_A1',
1217 'GL_DEPTH_COMPONENT16',
1218 'GL_STENCIL_INDEX8',
1221 'ShaderBinaryFormat': {
1222 'type': 'GLenum',
1223 'valid': [
1226 'StencilOp': {
1227 'type': 'GLenum',
1228 'valid': [
1229 'GL_KEEP',
1230 'GL_ZERO',
1231 'GL_REPLACE',
1232 'GL_INCR',
1233 'GL_INCR_WRAP',
1234 'GL_DECR',
1235 'GL_DECR_WRAP',
1236 'GL_INVERT',
1239 'TextureFormat': {
1240 'type': 'GLenum',
1241 'valid': [
1242 'GL_ALPHA',
1243 'GL_LUMINANCE',
1244 'GL_LUMINANCE_ALPHA',
1245 'GL_RGB',
1246 'GL_RGBA',
1248 'invalid': [
1249 'GL_BGRA',
1250 'GL_BGR',
1253 'TextureInternalFormat': {
1254 'type': 'GLenum',
1255 'valid': [
1256 'GL_ALPHA',
1257 'GL_LUMINANCE',
1258 'GL_LUMINANCE_ALPHA',
1259 'GL_RGB',
1260 'GL_RGBA',
1262 'invalid': [
1263 'GL_BGRA',
1264 'GL_BGR',
1267 'TextureInternalFormatStorage': {
1268 'type': 'GLenum',
1269 'valid': [
1270 'GL_RGB565',
1271 'GL_RGBA4',
1272 'GL_RGB5_A1',
1273 'GL_ALPHA8_EXT',
1274 'GL_LUMINANCE8_EXT',
1275 'GL_LUMINANCE8_ALPHA8_EXT',
1276 'GL_RGB8_OES',
1277 'GL_RGBA8_OES',
1280 'ImageInternalFormat': {
1281 'type': 'GLenum',
1282 'valid': [
1283 'GL_RGB',
1284 'GL_RGBA',
1287 'ImageUsage': {
1288 'type': 'GLenum',
1289 'valid': [
1290 'GL_MAP_CHROMIUM',
1291 'GL_SCANOUT_CHROMIUM'
1294 'ValueBufferTarget': {
1295 'type': 'GLenum',
1296 'valid': [
1297 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1300 'SubscriptionTarget': {
1301 'type': 'GLenum',
1302 'valid': [
1303 'GL_MOUSE_POSITION_CHROMIUM',
1306 'VertexAttribType': {
1307 'type': 'GLenum',
1308 'valid': [
1309 'GL_BYTE',
1310 'GL_UNSIGNED_BYTE',
1311 'GL_SHORT',
1312 'GL_UNSIGNED_SHORT',
1313 # 'GL_FIXED', // This is not available on Desktop GL.
1314 'GL_FLOAT',
1316 'invalid': [
1317 'GL_DOUBLE',
1320 'TextureBorder': {
1321 'type': 'GLint',
1322 'is_complete': True,
1323 'valid': [
1324 '0',
1326 'invalid': [
1327 '1',
1330 'VertexAttribSize': {
1331 'type': 'GLint',
1332 'valid': [
1333 '1',
1334 '2',
1335 '3',
1336 '4',
1338 'invalid': [
1339 '0',
1340 '5',
1343 'ZeroOnly': {
1344 'type': 'GLint',
1345 'is_complete': True,
1346 'valid': [
1347 '0',
1349 'invalid': [
1350 '1',
1353 'FalseOnly': {
1354 'type': 'GLboolean',
1355 'is_complete': True,
1356 'valid': [
1357 'false',
1359 'invalid': [
1360 'true',
1363 'ResetStatus': {
1364 'type': 'GLenum',
1365 'valid': [
1366 'GL_GUILTY_CONTEXT_RESET_ARB',
1367 'GL_INNOCENT_CONTEXT_RESET_ARB',
1368 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1371 'SyncCondition': {
1372 'type': 'GLenum',
1373 'is_complete': True,
1374 'valid': [
1375 #TODO(zmo): avoid using the direct number.
1376 '0x9117', # GL_SYNC_GPU_COMMANDS_COMPLETE
1378 'invalid': [
1379 '0',
1382 'SyncFlags': {
1383 'type': 'GLbitfield',
1384 'is_complete': True,
1385 'valid': [
1386 '0',
1388 'invalid': [
1389 '1',
1394 # This table specifies the different pepper interfaces that are supported for
1395 # GL commands. 'dev' is true if it's a dev interface.
1396 _PEPPER_INTERFACES = [
1397 {'name': '', 'dev': False},
1398 {'name': 'InstancedArrays', 'dev': False},
1399 {'name': 'FramebufferBlit', 'dev': False},
1400 {'name': 'FramebufferMultisample', 'dev': False},
1401 {'name': 'ChromiumEnableFeature', 'dev': False},
1402 {'name': 'ChromiumMapSub', 'dev': False},
1403 {'name': 'Query', 'dev': False},
1404 {'name': 'VertexArrayObject', 'dev': False},
1405 {'name': 'DrawBuffers', 'dev': True},
1408 # A function info object specifies the type and other special data for the
1409 # command that will be generated. A base function info object is generated by
1410 # parsing the "cmd_buffer_functions.txt", one for each function in the
1411 # file. These function info objects can be augmented and their values can be
1412 # overridden by adding an object to the table below.
1414 # Must match function names specified in "cmd_buffer_functions.txt".
1416 # cmd_comment: A comment added to the cmd format.
1417 # type: defines which handler will be used to generate code.
1418 # decoder_func: defines which function to call in the decoder to execute the
1419 # corresponding GL command. If not specified the GL command will
1420 # be called directly.
1421 # gl_test_func: GL function that is expected to be called when testing.
1422 # cmd_args: The arguments to use for the command. This overrides generating
1423 # them based on the GL function arguments.
1424 # gen_cmd: Whether or not this function geneates a command. Default = True.
1425 # data_transfer_methods: Array of methods that are used for transfering the
1426 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1427 # The default is 'immediate' if the command has one pointer
1428 # argument, otherwise 'shm'. One command is generated for each
1429 # transfer method. Affects only commands which are not of type
1430 # 'HandWritten', 'GETn' or 'GLcharN'.
1431 # Note: the command arguments that affect this are the final args,
1432 # taking cmd_args override into consideration.
1433 # impl_func: Whether or not to generate the GLES2Implementation part of this
1434 # command.
1435 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1436 # for this command.
1437 # needs_size: If True a data_size field is added to the command.
1438 # count: The number of units per element. For PUTn or PUT types.
1439 # use_count_func: If True the actual data count needs to be computed; the count
1440 # argument specifies the maximum count.
1441 # unit_test: If False no service side unit test will be generated.
1442 # client_test: If False no client side unit test will be generated.
1443 # expectation: If False the unit test will have no expected calls.
1444 # gen_func: Name of function that generates GL resource for corresponding
1445 # bind function.
1446 # states: array of states that get set by this function corresponding to
1447 # the given arguments
1448 # state_flag: name of flag that is set to true when function is called.
1449 # no_gl: no GL function is called.
1450 # valid_args: A dictionary of argument indices to args to use in unit tests
1451 # when they can not be automatically determined.
1452 # pepper_interface: The pepper interface that is used for this extension
1453 # pepper_name: The name of the function as exposed to pepper.
1454 # pepper_args: A string representing the argument list (what would appear in
1455 # C/C++ between the parentheses for the function declaration)
1456 # that the Pepper API expects for this function. Use this only if
1457 # the stable Pepper API differs from the GLES2 argument list.
1458 # invalid_test: False if no invalid test needed.
1459 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1460 # first_element_only: For PUT types, True if only the first element of an
1461 # array is used and we end up calling the single value
1462 # corresponding function. eg. TexParameteriv -> TexParameteri
1463 # extension: Function is an extension to GL and should not be exposed to
1464 # pepper unless pepper_interface is defined.
1465 # extension_flag: Function is an extension and should be enabled only when
1466 # the corresponding feature info flag is enabled. Implies
1467 # 'extension': True.
1468 # not_shared: For GENn types, True if objects can't be shared between contexts
1469 # unsafe: True = no validation is implemented on the service side and the
1470 # command is only available with --enable-unsafe-es3-apis.
1471 # id_mapping: A list of resource type names whose client side IDs need to be
1472 # mapped to service side IDs. This is only used for unsafe APIs.
1474 _FUNCTION_INFO = {
1475 'ActiveTexture': {
1476 'decoder_func': 'DoActiveTexture',
1477 'unit_test': False,
1478 'impl_func': False,
1479 'client_test': False,
1481 'AttachShader': {'decoder_func': 'DoAttachShader'},
1482 'BindAttribLocation': {
1483 'type': 'GLchar',
1484 'data_transfer_methods': ['bucket'],
1485 'needs_size': True,
1487 'BindBuffer': {
1488 'type': 'Bind',
1489 'decoder_func': 'DoBindBuffer',
1490 'gen_func': 'GenBuffersARB',
1492 'BindBufferBase': {
1493 'type': 'Bind',
1494 'id_mapping': [ 'Buffer' ],
1495 'gen_func': 'GenBuffersARB',
1496 'unsafe': True,
1498 'BindBufferRange': {
1499 'type': 'Bind',
1500 'id_mapping': [ 'Buffer' ],
1501 'gen_func': 'GenBuffersARB',
1502 'unsafe': True,
1504 'BindFramebuffer': {
1505 'type': 'Bind',
1506 'decoder_func': 'DoBindFramebuffer',
1507 'gl_test_func': 'glBindFramebufferEXT',
1508 'gen_func': 'GenFramebuffersEXT',
1509 'trace_level': 1,
1511 'BindRenderbuffer': {
1512 'type': 'Bind',
1513 'decoder_func': 'DoBindRenderbuffer',
1514 'gl_test_func': 'glBindRenderbufferEXT',
1515 'gen_func': 'GenRenderbuffersEXT',
1517 'BindSampler': {
1518 'type': 'Bind',
1519 'id_mapping': [ 'Sampler' ],
1520 'unsafe': True,
1522 'BindTexture': {
1523 'type': 'Bind',
1524 'decoder_func': 'DoBindTexture',
1525 'gen_func': 'GenTextures',
1526 # TODO(gman): remove this once client side caching works.
1527 'client_test': False,
1528 'trace_level': 1,
1530 'BindTransformFeedback': {
1531 'type': 'Bind',
1532 'id_mapping': [ 'TransformFeedback' ],
1533 'unsafe': True,
1535 'BlitFramebufferCHROMIUM': {
1536 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1537 'unit_test': False,
1538 'extension_flag': 'chromium_framebuffer_multisample',
1539 'pepper_interface': 'FramebufferBlit',
1540 'pepper_name': 'BlitFramebufferEXT',
1541 'defer_reads': True,
1542 'defer_draws': True,
1543 'trace_level': 1,
1545 'BufferData': {
1546 'type': 'Manual',
1547 'data_transfer_methods': ['shm'],
1548 'client_test': False,
1550 'BufferSubData': {
1551 'type': 'Data',
1552 'client_test': False,
1553 'decoder_func': 'DoBufferSubData',
1554 'data_transfer_methods': ['shm'],
1556 'CheckFramebufferStatus': {
1557 'type': 'Is',
1558 'decoder_func': 'DoCheckFramebufferStatus',
1559 'gl_test_func': 'glCheckFramebufferStatusEXT',
1560 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1561 'result': ['GLenum'],
1563 'Clear': {
1564 'decoder_func': 'DoClear',
1565 'defer_draws': True,
1566 'trace_level': 1,
1568 'ClearBufferiv': {
1569 'type': 'PUT',
1570 'use_count_func': True,
1571 'count': 4,
1572 'unsafe': True,
1574 'ClearBufferuiv': {
1575 'type': 'PUT',
1576 'count': 4,
1577 'unsafe': True,
1579 'ClearBufferfv': {
1580 'type': 'PUT',
1581 'use_count_func': True,
1582 'count': 4,
1583 'unsafe': True,
1585 'ClearBufferfi': {
1586 'unsafe': True,
1588 'ClearColor': {
1589 'type': 'StateSet',
1590 'state': 'ClearColor',
1592 'ClearDepthf': {
1593 'type': 'StateSet',
1594 'state': 'ClearDepthf',
1595 'decoder_func': 'glClearDepth',
1596 'gl_test_func': 'glClearDepth',
1597 'valid_args': {
1598 '0': '0.5f'
1601 'ColorMask': {
1602 'type': 'StateSet',
1603 'state': 'ColorMask',
1604 'no_gl': True,
1605 'expectation': False,
1607 'ConsumeTextureCHROMIUM': {
1608 'decoder_func': 'DoConsumeTextureCHROMIUM',
1609 'impl_func': False,
1610 'type': 'PUT',
1611 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1612 'unit_test': False,
1613 'client_test': False,
1614 'extension': "CHROMIUM_texture_mailbox",
1615 'chromium': True,
1616 'trace_level': 1,
1618 'CopyBufferSubData': {
1619 'unsafe': True,
1621 'CreateAndConsumeTextureCHROMIUM': {
1622 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
1623 'impl_func': False,
1624 'type': 'HandWritten',
1625 'data_transfer_methods': ['immediate'],
1626 'unit_test': False,
1627 'client_test': False,
1628 'extension': "CHROMIUM_texture_mailbox",
1629 'chromium': True,
1631 'GenValuebuffersCHROMIUM': {
1632 'type': 'GENn',
1633 'gl_test_func': 'glGenValuebuffersCHROMIUM',
1634 'resource_type': 'Valuebuffer',
1635 'resource_types': 'Valuebuffers',
1636 'unit_test': False,
1637 'extension': True,
1638 'chromium': True,
1640 'DeleteValuebuffersCHROMIUM': {
1641 'type': 'DELn',
1642 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
1643 'resource_type': 'Valuebuffer',
1644 'resource_types': 'Valuebuffers',
1645 'unit_test': False,
1646 'extension': True,
1647 'chromium': True,
1649 'IsValuebufferCHROMIUM': {
1650 'type': 'Is',
1651 'decoder_func': 'DoIsValuebufferCHROMIUM',
1652 'expectation': False,
1653 'extension': True,
1654 'chromium': True,
1656 'BindValuebufferCHROMIUM': {
1657 'type': 'Bind',
1658 'decoder_func': 'DoBindValueBufferCHROMIUM',
1659 'gen_func': 'GenValueBuffersCHROMIUM',
1660 'unit_test': False,
1661 'extension': True,
1662 'chromium': True,
1664 'SubscribeValueCHROMIUM': {
1665 'decoder_func': 'DoSubscribeValueCHROMIUM',
1666 'unit_test': False,
1667 'extension': True,
1668 'chromium': True,
1670 'PopulateSubscribedValuesCHROMIUM': {
1671 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
1672 'unit_test': False,
1673 'extension': True,
1674 'chromium': True,
1676 'UniformValuebufferCHROMIUM': {
1677 'decoder_func': 'DoUniformValueBufferCHROMIUM',
1678 'unit_test': False,
1679 'extension': True,
1680 'chromium': True,
1682 'ClearStencil': {
1683 'type': 'StateSet',
1684 'state': 'ClearStencil',
1686 'EnableFeatureCHROMIUM': {
1687 'type': 'Custom',
1688 'data_transfer_methods': ['shm'],
1689 'decoder_func': 'DoEnableFeatureCHROMIUM',
1690 'expectation': False,
1691 'cmd_args': 'GLuint bucket_id, GLint* result',
1692 'result': ['GLint'],
1693 'extension': True,
1694 'chromium': True,
1695 'pepper_interface': 'ChromiumEnableFeature',
1697 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1698 'CompressedTexImage2D': {
1699 'type': 'Manual',
1700 'data_transfer_methods': ['bucket', 'shm'],
1702 'CompressedTexSubImage2D': {
1703 'type': 'Data',
1704 'data_transfer_methods': ['bucket', 'shm'],
1705 'decoder_func': 'DoCompressedTexSubImage2D',
1707 'CopyTexImage2D': {
1708 'decoder_func': 'DoCopyTexImage2D',
1709 'unit_test': False,
1710 'defer_reads': True,
1712 'CopyTexSubImage2D': {
1713 'decoder_func': 'DoCopyTexSubImage2D',
1714 'defer_reads': True,
1716 'CreateImageCHROMIUM': {
1717 'type': 'Manual',
1718 'cmd_args':
1719 'ClientBuffer buffer, GLsizei width, GLsizei height, '
1720 'GLenum internalformat',
1721 'result': ['GLuint'],
1722 'client_test': False,
1723 'gen_cmd': False,
1724 'expectation': False,
1725 'extension': True,
1726 'chromium': True,
1728 'DestroyImageCHROMIUM': {
1729 'type': 'Manual',
1730 'client_test': False,
1731 'gen_cmd': False,
1732 'extension': True,
1733 'chromium': True,
1735 'CreateGpuMemoryBufferImageCHROMIUM': {
1736 'type': 'Manual',
1737 'cmd_args':
1738 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
1739 'result': ['GLuint'],
1740 'client_test': False,
1741 'gen_cmd': False,
1742 'expectation': False,
1743 'extension': True,
1744 'chromium': True,
1746 'CreateProgram': {
1747 'type': 'Create',
1748 'client_test': False,
1750 'CreateShader': {
1751 'type': 'Create',
1752 'client_test': False,
1754 'BlendColor': {
1755 'type': 'StateSet',
1756 'state': 'BlendColor',
1758 'BlendEquation': {
1759 'type': 'StateSetRGBAlpha',
1760 'state': 'BlendEquation',
1761 'valid_args': {
1762 '0': 'GL_FUNC_SUBTRACT'
1765 'BlendEquationSeparate': {
1766 'type': 'StateSet',
1767 'state': 'BlendEquation',
1768 'valid_args': {
1769 '0': 'GL_FUNC_SUBTRACT'
1772 'BlendFunc': {
1773 'type': 'StateSetRGBAlpha',
1774 'state': 'BlendFunc',
1776 'BlendFuncSeparate': {
1777 'type': 'StateSet',
1778 'state': 'BlendFunc',
1780 'BlendBarrierKHR': {
1781 'gl_test_func': 'glBlendBarrierKHR',
1782 'extension': True,
1783 'extension_flag': 'blend_equation_advanced',
1784 'client_test': False,
1786 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
1787 'StencilFunc': {
1788 'type': 'StateSetFrontBack',
1789 'state': 'StencilFunc',
1791 'StencilFuncSeparate': {
1792 'type': 'StateSetFrontBackSeparate',
1793 'state': 'StencilFunc',
1795 'StencilOp': {
1796 'type': 'StateSetFrontBack',
1797 'state': 'StencilOp',
1798 'valid_args': {
1799 '1': 'GL_INCR'
1802 'StencilOpSeparate': {
1803 'type': 'StateSetFrontBackSeparate',
1804 'state': 'StencilOp',
1805 'valid_args': {
1806 '1': 'GL_INCR'
1809 'Hint': {
1810 'type': 'StateSetNamedParameter',
1811 'state': 'Hint',
1813 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
1814 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
1815 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
1816 'LineWidth': {
1817 'type': 'StateSet',
1818 'state': 'LineWidth',
1819 'valid_args': {
1820 '0': '0.5f'
1823 'PolygonOffset': {
1824 'type': 'StateSet',
1825 'state': 'PolygonOffset',
1827 'DeleteBuffers': {
1828 'type': 'DELn',
1829 'gl_test_func': 'glDeleteBuffersARB',
1830 'resource_type': 'Buffer',
1831 'resource_types': 'Buffers',
1833 'DeleteFramebuffers': {
1834 'type': 'DELn',
1835 'gl_test_func': 'glDeleteFramebuffersEXT',
1836 'resource_type': 'Framebuffer',
1837 'resource_types': 'Framebuffers',
1839 'DeleteProgram': { 'type': 'Delete' },
1840 'DeleteRenderbuffers': {
1841 'type': 'DELn',
1842 'gl_test_func': 'glDeleteRenderbuffersEXT',
1843 'resource_type': 'Renderbuffer',
1844 'resource_types': 'Renderbuffers',
1846 'DeleteSamplers': {
1847 'type': 'DELn',
1848 'resource_type': 'Sampler',
1849 'resource_types': 'Samplers',
1850 'unsafe': True,
1852 'DeleteShader': { 'type': 'Delete' },
1853 'DeleteSync': {
1854 'type': 'Delete',
1855 'cmd_args': 'GLuint sync',
1856 'resource_type': 'Sync',
1857 'unsafe': True,
1859 'DeleteTextures': {
1860 'type': 'DELn',
1861 'resource_type': 'Texture',
1862 'resource_types': 'Textures',
1864 'DeleteTransformFeedbacks': {
1865 'type': 'DELn',
1866 'resource_type': 'TransformFeedback',
1867 'resource_types': 'TransformFeedbacks',
1868 'unsafe': True,
1870 'DepthRangef': {
1871 'decoder_func': 'DoDepthRangef',
1872 'gl_test_func': 'glDepthRange',
1874 'DepthMask': {
1875 'type': 'StateSet',
1876 'state': 'DepthMask',
1877 'no_gl': True,
1878 'expectation': False,
1880 'DetachShader': {'decoder_func': 'DoDetachShader'},
1881 'Disable': {
1882 'decoder_func': 'DoDisable',
1883 'impl_func': False,
1884 'client_test': False,
1886 'DisableVertexAttribArray': {
1887 'decoder_func': 'DoDisableVertexAttribArray',
1888 'impl_decl': False,
1890 'DrawArrays': {
1891 'type': 'Manual',
1892 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
1893 'defer_draws': True,
1894 'trace_level': 2,
1896 'DrawElements': {
1897 'type': 'Manual',
1898 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
1899 'GLenumIndexType type, GLuint index_offset',
1900 'client_test': False,
1901 'defer_draws': True,
1902 'trace_level': 2,
1904 'Enable': {
1905 'decoder_func': 'DoEnable',
1906 'impl_func': False,
1907 'client_test': False,
1909 'EnableVertexAttribArray': {
1910 'decoder_func': 'DoEnableVertexAttribArray',
1911 'impl_decl': False,
1913 'FenceSync': {
1914 'type': 'Create',
1915 'client_test': False,
1916 'unsafe': True,
1918 'Finish': {
1919 'impl_func': False,
1920 'client_test': False,
1921 'decoder_func': 'DoFinish',
1922 'defer_reads': True,
1924 'Flush': {
1925 'impl_func': False,
1926 'decoder_func': 'DoFlush',
1928 'FramebufferRenderbuffer': {
1929 'decoder_func': 'DoFramebufferRenderbuffer',
1930 'gl_test_func': 'glFramebufferRenderbufferEXT',
1932 'FramebufferTexture2D': {
1933 'decoder_func': 'DoFramebufferTexture2D',
1934 'gl_test_func': 'glFramebufferTexture2DEXT',
1935 'trace_level': 1,
1937 'FramebufferTexture2DMultisampleEXT': {
1938 'decoder_func': 'DoFramebufferTexture2DMultisample',
1939 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
1940 'expectation': False,
1941 'unit_test': False,
1942 'extension_flag': 'multisampled_render_to_texture',
1943 'trace_level': 1,
1945 'FramebufferTextureLayer': {
1946 'decoder_func': 'DoFramebufferTextureLayer',
1947 'unsafe': True,
1949 'GenerateMipmap': {
1950 'decoder_func': 'DoGenerateMipmap',
1951 'gl_test_func': 'glGenerateMipmapEXT',
1953 'GenBuffers': {
1954 'type': 'GENn',
1955 'gl_test_func': 'glGenBuffersARB',
1956 'resource_type': 'Buffer',
1957 'resource_types': 'Buffers',
1959 'GenMailboxCHROMIUM': {
1960 'type': 'HandWritten',
1961 'impl_func': False,
1962 'extension': "CHROMIUM_texture_mailbox",
1963 'chromium': True,
1965 'GenFramebuffers': {
1966 'type': 'GENn',
1967 'gl_test_func': 'glGenFramebuffersEXT',
1968 'resource_type': 'Framebuffer',
1969 'resource_types': 'Framebuffers',
1971 'GenRenderbuffers': {
1972 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
1973 'resource_type': 'Renderbuffer',
1974 'resource_types': 'Renderbuffers',
1976 'GenSamplers': {
1977 'type': 'GENn',
1978 'gl_test_func': 'glGenSamplers',
1979 'resource_type': 'Sampler',
1980 'resource_types': 'Samplers',
1981 'unsafe': True,
1983 'GenTextures': {
1984 'type': 'GENn',
1985 'gl_test_func': 'glGenTextures',
1986 'resource_type': 'Texture',
1987 'resource_types': 'Textures',
1989 'GenTransformFeedbacks': {
1990 'type': 'GENn',
1991 'gl_test_func': 'glGenTransformFeedbacks',
1992 'resource_type': 'TransformFeedback',
1993 'resource_types': 'TransformFeedbacks',
1994 'unsafe': True,
1996 'GetActiveAttrib': {
1997 'type': 'Custom',
1998 'data_transfer_methods': ['shm'],
1999 'cmd_args':
2000 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2001 'void* result',
2002 'result': [
2003 'int32_t success',
2004 'int32_t size',
2005 'uint32_t type',
2008 'GetActiveUniform': {
2009 'type': 'Custom',
2010 'data_transfer_methods': ['shm'],
2011 'cmd_args':
2012 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2013 'void* result',
2014 'result': [
2015 'int32_t success',
2016 'int32_t size',
2017 'uint32_t type',
2020 'GetAttachedShaders': {
2021 'type': 'Custom',
2022 'data_transfer_methods': ['shm'],
2023 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2024 'result': ['SizedResult<GLuint>'],
2026 'GetAttribLocation': {
2027 'type': 'Custom',
2028 'data_transfer_methods': ['shm'],
2029 'cmd_args':
2030 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2031 'result': ['GLint'],
2032 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml
2034 'GetBooleanv': {
2035 'type': 'GETn',
2036 'result': ['SizedResult<GLboolean>'],
2037 'decoder_func': 'DoGetBooleanv',
2038 'gl_test_func': 'glGetBooleanv',
2040 'GetBufferParameteriv': {
2041 'type': 'GETn',
2042 'result': ['SizedResult<GLint>'],
2043 'decoder_func': 'DoGetBufferParameteriv',
2044 'expectation': False,
2045 'shadowed': True,
2047 'GetError': {
2048 'type': 'Is',
2049 'decoder_func': 'GetErrorState()->GetGLError',
2050 'impl_func': False,
2051 'result': ['GLenum'],
2052 'client_test': False,
2054 'GetFloatv': {
2055 'type': 'GETn',
2056 'result': ['SizedResult<GLfloat>'],
2057 'decoder_func': 'DoGetFloatv',
2058 'gl_test_func': 'glGetFloatv',
2060 'GetFramebufferAttachmentParameteriv': {
2061 'type': 'GETn',
2062 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2063 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2064 'result': ['SizedResult<GLint>'],
2066 'GetIntegerv': {
2067 'type': 'GETn',
2068 'result': ['SizedResult<GLint>'],
2069 'decoder_func': 'DoGetIntegerv',
2070 'client_test': False,
2072 'GetInternalformativ': {
2073 'type': 'GETn',
2074 'result': ['SizedResult<GLint>'],
2075 'unsafe': True,
2077 'GetMaxValueInBufferCHROMIUM': {
2078 'type': 'Is',
2079 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2080 'result': ['GLuint'],
2081 'unit_test': False,
2082 'client_test': False,
2083 'extension': True,
2084 'chromium': True,
2085 'impl_func': False,
2087 'GetProgramiv': {
2088 'type': 'GETn',
2089 'decoder_func': 'DoGetProgramiv',
2090 'result': ['SizedResult<GLint>'],
2091 'expectation': False,
2093 'GetProgramInfoCHROMIUM': {
2094 'type': 'Custom',
2095 'expectation': False,
2096 'impl_func': False,
2097 'extension': True,
2098 'chromium': True,
2099 'client_test': False,
2100 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2101 'result': [
2102 'uint32_t link_status',
2103 'uint32_t num_attribs',
2104 'uint32_t num_uniforms',
2107 'GetProgramInfoLog': {
2108 'type': 'STRn',
2109 'expectation': False,
2111 'GetRenderbufferParameteriv': {
2112 'type': 'GETn',
2113 'decoder_func': 'DoGetRenderbufferParameteriv',
2114 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2115 'result': ['SizedResult<GLint>'],
2117 'GetSamplerParameterfv': {
2118 'type': 'GETn',
2119 'result': ['SizedResult<GLfloat>'],
2120 'id_mapping': [ 'Sampler' ],
2121 'unsafe': True,
2123 'GetSamplerParameteriv': {
2124 'type': 'GETn',
2125 'result': ['SizedResult<GLint>'],
2126 'id_mapping': [ 'Sampler' ],
2127 'unsafe': True,
2129 'GetShaderiv': {
2130 'type': 'GETn',
2131 'decoder_func': 'DoGetShaderiv',
2132 'result': ['SizedResult<GLint>'],
2134 'GetShaderInfoLog': {
2135 'type': 'STRn',
2136 'get_len_func': 'glGetShaderiv',
2137 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2138 'unit_test': False,
2140 'GetShaderPrecisionFormat': {
2141 'type': 'Custom',
2142 'data_transfer_methods': ['shm'],
2143 'cmd_args':
2144 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2145 'void* result',
2146 'result': [
2147 'int32_t success',
2148 'int32_t min_range',
2149 'int32_t max_range',
2150 'int32_t precision',
2153 'GetShaderSource': {
2154 'type': 'STRn',
2155 'get_len_func': 'DoGetShaderiv',
2156 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2157 'unit_test': False,
2158 'client_test': False,
2160 'GetString': {
2161 'type': 'Custom',
2162 'client_test': False,
2163 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2165 'GetTexParameterfv': {
2166 'type': 'GETn',
2167 'decoder_func': 'DoGetTexParameterfv',
2168 'result': ['SizedResult<GLfloat>']
2170 'GetTexParameteriv': {
2171 'type': 'GETn',
2172 'decoder_func': 'DoGetTexParameteriv',
2173 'result': ['SizedResult<GLint>']
2175 'GetTranslatedShaderSourceANGLE': {
2176 'type': 'STRn',
2177 'get_len_func': 'DoGetShaderiv',
2178 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2179 'unit_test': False,
2180 'extension': True,
2182 'GetUniformfv': {
2183 'type': 'Custom',
2184 'data_transfer_methods': ['shm'],
2185 'result': ['SizedResult<GLfloat>'],
2187 'GetUniformiv': {
2188 'type': 'Custom',
2189 'data_transfer_methods': ['shm'],
2190 'result': ['SizedResult<GLint>'],
2192 'GetUniformLocation': {
2193 'type': 'Custom',
2194 'data_transfer_methods': ['shm'],
2195 'cmd_args':
2196 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2197 'result': ['GLint'],
2198 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
2200 'GetVertexAttribfv': {
2201 'type': 'GETn',
2202 'result': ['SizedResult<GLfloat>'],
2203 'impl_decl': False,
2204 'decoder_func': 'DoGetVertexAttribfv',
2205 'expectation': False,
2206 'client_test': False,
2208 'GetVertexAttribiv': {
2209 'type': 'GETn',
2210 'result': ['SizedResult<GLint>'],
2211 'impl_decl': False,
2212 'decoder_func': 'DoGetVertexAttribiv',
2213 'expectation': False,
2214 'client_test': False,
2216 'GetVertexAttribPointerv': {
2217 'type': 'Custom',
2218 'data_transfer_methods': ['shm'],
2219 'result': ['SizedResult<GLuint>'],
2220 'client_test': False,
2222 'InvalidateFramebuffer': {
2223 'type': 'PUTn',
2224 'count': 1,
2225 'client_test': False,
2226 'unit_test': False,
2227 'unsafe': True,
2229 'InvalidateSubFramebuffer': {
2230 'type': 'PUTn',
2231 'count': 1,
2232 'client_test': False,
2233 'unit_test': False,
2234 'unsafe': True,
2236 'IsBuffer': {
2237 'type': 'Is',
2238 'decoder_func': 'DoIsBuffer',
2239 'expectation': False,
2241 'IsEnabled': {
2242 'type': 'Is',
2243 'decoder_func': 'DoIsEnabled',
2244 'client_test': False,
2245 'impl_func': False,
2246 'expectation': False,
2248 'IsFramebuffer': {
2249 'type': 'Is',
2250 'decoder_func': 'DoIsFramebuffer',
2251 'expectation': False,
2253 'IsProgram': {
2254 'type': 'Is',
2255 'decoder_func': 'DoIsProgram',
2256 'expectation': False,
2258 'IsRenderbuffer': {
2259 'type': 'Is',
2260 'decoder_func': 'DoIsRenderbuffer',
2261 'expectation': False,
2263 'IsShader': {
2264 'type': 'Is',
2265 'decoder_func': 'DoIsShader',
2266 'expectation': False,
2268 'IsSampler': {
2269 'type': 'Is',
2270 'id_mapping': [ 'Sampler' ],
2271 'expectation': False,
2272 'unsafe': True,
2274 'IsSync': {
2275 'type': 'Is',
2276 'id_mapping': [ 'Sync' ],
2277 'cmd_args': 'GLuint sync',
2278 'expectation': False,
2279 'unsafe': True,
2281 'IsTexture': {
2282 'type': 'Is',
2283 'decoder_func': 'DoIsTexture',
2284 'expectation': False,
2286 'IsTransformFeedback': {
2287 'type': 'Is',
2288 'id_mapping': [ 'TransformFeedback' ],
2289 'expectation': False,
2290 'unsafe': True,
2292 'LinkProgram': {
2293 'decoder_func': 'DoLinkProgram',
2294 'impl_func': False,
2296 'MapBufferCHROMIUM': {
2297 'gen_cmd': False,
2298 'extension': True,
2299 'chromium': True,
2300 'client_test': False,
2302 'MapBufferSubDataCHROMIUM': {
2303 'gen_cmd': False,
2304 'extension': True,
2305 'chromium': True,
2306 'client_test': False,
2307 'pepper_interface': 'ChromiumMapSub',
2309 'MapTexSubImage2DCHROMIUM': {
2310 'gen_cmd': False,
2311 'extension': True,
2312 'chromium': True,
2313 'client_test': False,
2314 'pepper_interface': 'ChromiumMapSub',
2316 'PauseTransformFeedback': {
2317 'unsafe': True,
2319 'PixelStorei': {'type': 'Manual'},
2320 'PostSubBufferCHROMIUM': {
2321 'type': 'Custom',
2322 'impl_func': False,
2323 'unit_test': False,
2324 'client_test': False,
2325 'extension': True,
2326 'chromium': True,
2328 'ProduceTextureCHROMIUM': {
2329 'decoder_func': 'DoProduceTextureCHROMIUM',
2330 'impl_func': False,
2331 'type': 'PUT',
2332 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2333 'unit_test': False,
2334 'client_test': False,
2335 'extension': "CHROMIUM_texture_mailbox",
2336 'chromium': True,
2337 'trace_level': 1,
2339 'ProduceTextureDirectCHROMIUM': {
2340 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
2341 'impl_func': False,
2342 'type': 'PUT',
2343 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2344 'unit_test': False,
2345 'client_test': False,
2346 'extension': "CHROMIUM_texture_mailbox",
2347 'chromium': True,
2348 'trace_level': 1,
2350 'RenderbufferStorage': {
2351 'decoder_func': 'DoRenderbufferStorage',
2352 'gl_test_func': 'glRenderbufferStorageEXT',
2353 'expectation': False,
2355 'RenderbufferStorageMultisampleCHROMIUM': {
2356 'cmd_comment':
2357 '// GL_CHROMIUM_framebuffer_multisample\n',
2358 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
2359 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
2360 'expectation': False,
2361 'unit_test': False,
2362 'extension_flag': 'chromium_framebuffer_multisample',
2363 'pepper_interface': 'FramebufferMultisample',
2364 'pepper_name': 'RenderbufferStorageMultisampleEXT',
2366 'RenderbufferStorageMultisampleEXT': {
2367 'cmd_comment':
2368 '// GL_EXT_multisampled_render_to_texture\n',
2369 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
2370 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
2371 'expectation': False,
2372 'unit_test': False,
2373 'extension_flag': 'multisampled_render_to_texture',
2375 'ReadBuffer': {
2376 'unsafe': True,
2378 'ReadPixels': {
2379 'cmd_comment':
2380 '// ReadPixels has the result separated from the pixel buffer so that\n'
2381 '// it is easier to specify the result going to some specific place\n'
2382 '// that exactly fits the rectangle of pixels.\n',
2383 'type': 'Custom',
2384 'data_transfer_methods': ['shm'],
2385 'impl_func': False,
2386 'client_test': False,
2387 'cmd_args':
2388 'GLint x, GLint y, GLsizei width, GLsizei height, '
2389 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
2390 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
2391 'uint32_t result_shm_id, uint32_t result_shm_offset, '
2392 'GLboolean async',
2393 'result': ['uint32_t'],
2394 'defer_reads': True,
2396 'ReleaseShaderCompiler': {
2397 'decoder_func': 'DoReleaseShaderCompiler',
2398 'unit_test': False,
2400 'ResumeTransformFeedback': {
2401 'unsafe': True,
2403 'SamplerParameterf': {
2404 'valid_args': {
2405 '2': 'GL_NEAREST'
2407 'id_mapping': [ 'Sampler' ],
2408 'unsafe': True,
2410 'SamplerParameterfv': {
2411 'type': 'PUT',
2412 'data_value': 'GL_NEAREST',
2413 'count': 1,
2414 'gl_test_func': 'glSamplerParameterf',
2415 'decoder_func': 'DoSamplerParameterfv',
2416 'first_element_only': True,
2417 'id_mapping': [ 'Sampler' ],
2418 'unsafe': True,
2420 'SamplerParameteri': {
2421 'valid_args': {
2422 '2': 'GL_NEAREST'
2424 'id_mapping': [ 'Sampler' ],
2425 'unsafe': True,
2427 'SamplerParameteriv': {
2428 'type': 'PUT',
2429 'data_value': 'GL_NEAREST',
2430 'count': 1,
2431 'gl_test_func': 'glSamplerParameteri',
2432 'decoder_func': 'DoSamplerParameteriv',
2433 'first_element_only': True,
2434 'unsafe': True,
2436 'ShaderBinary': {
2437 'type': 'Custom',
2438 'client_test': False,
2440 'ShaderSource': {
2441 'type': 'PUTSTR',
2442 'decoder_func': 'DoShaderSource',
2443 'data_transfer_methods': ['bucket'],
2444 'client_test': False,
2445 'cmd_args':
2446 'GLuint shader, const char** str',
2447 'pepper_args':
2448 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2450 'StencilMask': {
2451 'type': 'StateSetFrontBack',
2452 'state': 'StencilMask',
2453 'no_gl': True,
2454 'expectation': False,
2456 'StencilMaskSeparate': {
2457 'type': 'StateSetFrontBackSeparate',
2458 'state': 'StencilMask',
2459 'no_gl': True,
2460 'expectation': False,
2462 'SwapBuffers': {
2463 'impl_func': False,
2464 'decoder_func': 'DoSwapBuffers',
2465 'unit_test': False,
2466 'client_test': False,
2467 'extension': True,
2468 'trace_level': 1,
2470 'SwapInterval': {
2471 'impl_func': False,
2472 'decoder_func': 'DoSwapInterval',
2473 'unit_test': False,
2474 'client_test': False,
2475 'extension': True,
2476 'trace_level': 1,
2478 'TexImage2D': {
2479 'type': 'Manual',
2480 'data_transfer_methods': ['shm'],
2481 'client_test': False,
2483 'TexImage3D': {
2484 'type': 'Manual',
2485 'data_transfer_methods': ['shm'],
2486 'client_test': False,
2487 'unsafe': True,
2489 'TexParameterf': {
2490 'decoder_func': 'DoTexParameterf',
2491 'valid_args': {
2492 '2': 'GL_NEAREST'
2495 'TexParameteri': {
2496 'decoder_func': 'DoTexParameteri',
2497 'valid_args': {
2498 '2': 'GL_NEAREST'
2501 'TexParameterfv': {
2502 'type': 'PUT',
2503 'data_value': 'GL_NEAREST',
2504 'count': 1,
2505 'decoder_func': 'DoTexParameterfv',
2506 'gl_test_func': 'glTexParameterf',
2507 'first_element_only': True,
2509 'TexParameteriv': {
2510 'type': 'PUT',
2511 'data_value': 'GL_NEAREST',
2512 'count': 1,
2513 'decoder_func': 'DoTexParameteriv',
2514 'gl_test_func': 'glTexParameteri',
2515 'first_element_only': True,
2517 'TexStorage3D': {
2518 'unsafe': True,
2520 'TexSubImage2D': {
2521 'type': 'Manual',
2522 'data_transfer_methods': ['shm'],
2523 'client_test': False,
2524 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2525 'GLint xoffset, GLint yoffset, '
2526 'GLsizei width, GLsizei height, '
2527 'GLenumTextureFormat format, GLenumPixelType type, '
2528 'const void* pixels, GLboolean internal'
2530 'TexSubImage3D': {
2531 'type': 'Manual',
2532 'data_transfer_methods': ['shm'],
2533 'client_test': False,
2534 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2535 'GLint xoffset, GLint yoffset, GLint zoffset, '
2536 'GLsizei width, GLsizei height, GLsizei depth, '
2537 'GLenumTextureFormat format, GLenumPixelType type, '
2538 'const void* pixels, GLboolean internal',
2539 'unsafe': True,
2541 'Uniform1f': {'type': 'PUTXn', 'count': 1},
2542 'Uniform1fv': {
2543 'type': 'PUTn',
2544 'count': 1,
2545 'decoder_func': 'DoUniform1fv',
2547 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2548 'Uniform1iv': {
2549 'type': 'PUTn',
2550 'count': 1,
2551 'decoder_func': 'DoUniform1iv',
2552 'unit_test': False,
2554 'Uniform1ui': {
2555 'type': 'PUTXn',
2556 'count': 1,
2557 'unsafe': True,
2559 'Uniform1uiv': {
2560 'type': 'PUTn',
2561 'count': 1,
2562 'unsafe': True,
2564 'Uniform2i': {'type': 'PUTXn', 'count': 2},
2565 'Uniform2f': {'type': 'PUTXn', 'count': 2},
2566 'Uniform2fv': {
2567 'type': 'PUTn',
2568 'count': 2,
2569 'decoder_func': 'DoUniform2fv',
2571 'Uniform2iv': {
2572 'type': 'PUTn',
2573 'count': 2,
2574 'decoder_func': 'DoUniform2iv',
2576 'Uniform2ui': {
2577 'type': 'PUTXn',
2578 'count': 2,
2579 'unsafe': True,
2581 'Uniform2uiv': {
2582 'type': 'PUTn',
2583 'count': 2,
2584 'unsafe': True,
2586 'Uniform3i': {'type': 'PUTXn', 'count': 3},
2587 'Uniform3f': {'type': 'PUTXn', 'count': 3},
2588 'Uniform3fv': {
2589 'type': 'PUTn',
2590 'count': 3,
2591 'decoder_func': 'DoUniform3fv',
2593 'Uniform3iv': {
2594 'type': 'PUTn',
2595 'count': 3,
2596 'decoder_func': 'DoUniform3iv',
2598 'Uniform3ui': {
2599 'type': 'PUTXn',
2600 'count': 3,
2601 'unsafe': True,
2603 'Uniform3uiv': {
2604 'type': 'PUTn',
2605 'count': 3,
2606 'unsafe': True,
2608 'Uniform4i': {'type': 'PUTXn', 'count': 4},
2609 'Uniform4f': {'type': 'PUTXn', 'count': 4},
2610 'Uniform4fv': {
2611 'type': 'PUTn',
2612 'count': 4,
2613 'decoder_func': 'DoUniform4fv',
2615 'Uniform4iv': {
2616 'type': 'PUTn',
2617 'count': 4,
2618 'decoder_func': 'DoUniform4iv',
2620 'Uniform4ui': {
2621 'type': 'PUTXn',
2622 'count': 4,
2623 'unsafe': True,
2625 'Uniform4uiv': {
2626 'type': 'PUTn',
2627 'count': 4,
2628 'unsafe': True,
2630 'UniformMatrix2fv': {
2631 'type': 'PUTn',
2632 'count': 4,
2633 'decoder_func': 'DoUniformMatrix2fv',
2635 'UniformMatrix2x3fv': {
2636 'type': 'PUTn',
2637 'count': 6,
2638 'unsafe': True,
2640 'UniformMatrix2x4fv': {
2641 'type': 'PUTn',
2642 'count': 8,
2643 'unsafe': True,
2645 'UniformMatrix3fv': {
2646 'type': 'PUTn',
2647 'count': 9,
2648 'decoder_func': 'DoUniformMatrix3fv',
2650 'UniformMatrix3x2fv': {
2651 'type': 'PUTn',
2652 'count': 6,
2653 'unsafe': True,
2655 'UniformMatrix3x4fv': {
2656 'type': 'PUTn',
2657 'count': 12,
2658 'unsafe': True,
2660 'UniformMatrix4fv': {
2661 'type': 'PUTn',
2662 'count': 16,
2663 'decoder_func': 'DoUniformMatrix4fv',
2665 'UniformMatrix4x2fv': {
2666 'type': 'PUTn',
2667 'count': 8,
2668 'unsafe': True,
2670 'UniformMatrix4x3fv': {
2671 'type': 'PUTn',
2672 'count': 12,
2673 'unsafe': True,
2675 'UnmapBufferCHROMIUM': {
2676 'gen_cmd': False,
2677 'extension': True,
2678 'chromium': True,
2679 'client_test': False,
2681 'UnmapBufferSubDataCHROMIUM': {
2682 'gen_cmd': False,
2683 'extension': True,
2684 'chromium': True,
2685 'client_test': False,
2686 'pepper_interface': 'ChromiumMapSub',
2688 'UnmapTexSubImage2DCHROMIUM': {
2689 'gen_cmd': False,
2690 'extension': True,
2691 'chromium': True,
2692 'client_test': False,
2693 'pepper_interface': 'ChromiumMapSub',
2695 'UseProgram': {
2696 'type': 'Bind',
2697 'decoder_func': 'DoUseProgram',
2699 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
2700 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
2701 'VertexAttrib1fv': {
2702 'type': 'PUT',
2703 'count': 1,
2704 'decoder_func': 'DoVertexAttrib1fv',
2706 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
2707 'VertexAttrib2fv': {
2708 'type': 'PUT',
2709 'count': 2,
2710 'decoder_func': 'DoVertexAttrib2fv',
2712 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
2713 'VertexAttrib3fv': {
2714 'type': 'PUT',
2715 'count': 3,
2716 'decoder_func': 'DoVertexAttrib3fv',
2718 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
2719 'VertexAttrib4fv': {
2720 'type': 'PUT',
2721 'count': 4,
2722 'decoder_func': 'DoVertexAttrib4fv',
2724 'VertexAttribI4i': {
2725 'unsafe': True,
2727 'VertexAttribI4iv': {
2728 'type': 'PUT',
2729 'count': 4,
2730 'unsafe': True,
2732 'VertexAttribI4ui': {
2733 'unsafe': True,
2735 'VertexAttribI4uiv': {
2736 'type': 'PUT',
2737 'count': 4,
2738 'unsafe': True,
2740 'VertexAttribIPointer': {
2741 'type': 'Manual',
2742 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2743 'GLenumVertexAttribType type, GLsizei stride, '
2744 'GLuint offset',
2745 'client_test': False,
2746 'unsafe': True,
2748 'VertexAttribPointer': {
2749 'type': 'Manual',
2750 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
2751 'GLenumVertexAttribType type, GLboolean normalized, '
2752 'GLsizei stride, GLuint offset',
2753 'client_test': False,
2755 'Scissor': {
2756 'type': 'StateSet',
2757 'state': 'Scissor',
2759 'Viewport': {
2760 'decoder_func': 'DoViewport',
2762 'ResizeCHROMIUM': {
2763 'type': 'Custom',
2764 'impl_func': False,
2765 'unit_test': False,
2766 'extension': True,
2767 'chromium': True,
2769 'GetRequestableExtensionsCHROMIUM': {
2770 'type': 'Custom',
2771 'impl_func': False,
2772 'cmd_args': 'uint32_t bucket_id',
2773 'extension': True,
2774 'chromium': True,
2776 'RequestExtensionCHROMIUM': {
2777 'type': 'Custom',
2778 'impl_func': False,
2779 'client_test': False,
2780 'cmd_args': 'uint32_t bucket_id',
2781 'extension': True,
2782 'chromium': True,
2784 'RateLimitOffscreenContextCHROMIUM': {
2785 'gen_cmd': False,
2786 'extension': True,
2787 'chromium': True,
2788 'client_test': False,
2790 'CreateStreamTextureCHROMIUM': {
2791 'type': 'HandWritten',
2792 'impl_func': False,
2793 'gen_cmd': False,
2794 'extension': True,
2795 'chromium': True,
2797 'TexImageIOSurface2DCHROMIUM': {
2798 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
2799 'unit_test': False,
2800 'extension': True,
2801 'chromium': True,
2803 'CopyTextureCHROMIUM': {
2804 'decoder_func': 'DoCopyTextureCHROMIUM',
2805 'unit_test': False,
2806 'extension': True,
2807 'chromium': True,
2809 'TexStorage2DEXT': {
2810 'unit_test': False,
2811 'extension': True,
2812 'decoder_func': 'DoTexStorage2DEXT',
2814 'DrawArraysInstancedANGLE': {
2815 'type': 'Manual',
2816 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
2817 'GLsizei primcount',
2818 'extension': True,
2819 'unit_test': False,
2820 'pepper_interface': 'InstancedArrays',
2821 'defer_draws': True,
2823 'DrawBuffersEXT': {
2824 'type': 'PUTn',
2825 'decoder_func': 'DoDrawBuffersEXT',
2826 'count': 1,
2827 'client_test': False,
2828 'unit_test': False,
2829 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
2830 # work without.
2831 'extension': True,
2832 'pepper_interface': 'DrawBuffers',
2834 'DrawElementsInstancedANGLE': {
2835 'type': 'Manual',
2836 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2837 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
2838 'extension': True,
2839 'unit_test': False,
2840 'client_test': False,
2841 'pepper_interface': 'InstancedArrays',
2842 'defer_draws': True,
2844 'VertexAttribDivisorANGLE': {
2845 'type': 'Manual',
2846 'cmd_args': 'GLuint index, GLuint divisor',
2847 'extension': True,
2848 'unit_test': False,
2849 'pepper_interface': 'InstancedArrays',
2851 'GenQueriesEXT': {
2852 'type': 'GENn',
2853 'gl_test_func': 'glGenQueriesARB',
2854 'resource_type': 'Query',
2855 'resource_types': 'Queries',
2856 'unit_test': False,
2857 'pepper_interface': 'Query',
2858 'not_shared': 'True',
2860 'DeleteQueriesEXT': {
2861 'type': 'DELn',
2862 'gl_test_func': 'glDeleteQueriesARB',
2863 'resource_type': 'Query',
2864 'resource_types': 'Queries',
2865 'unit_test': False,
2866 'pepper_interface': 'Query',
2868 'IsQueryEXT': {
2869 'gen_cmd': False,
2870 'client_test': False,
2871 'pepper_interface': 'Query',
2873 'BeginQueryEXT': {
2874 'type': 'Manual',
2875 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
2876 'data_transfer_methods': ['shm'],
2877 'gl_test_func': 'glBeginQuery',
2878 'pepper_interface': 'Query',
2880 'BeginTransformFeedback': {
2881 'unsafe': True,
2883 'EndQueryEXT': {
2884 'type': 'Manual',
2885 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
2886 'gl_test_func': 'glEndnQuery',
2887 'client_test': False,
2888 'pepper_interface': 'Query',
2890 'EndTransformFeedback': {
2891 'unsafe': True,
2893 'GetQueryivEXT': {
2894 'gen_cmd': False,
2895 'client_test': False,
2896 'gl_test_func': 'glGetQueryiv',
2897 'pepper_interface': 'Query',
2899 'GetQueryObjectuivEXT': {
2900 'gen_cmd': False,
2901 'client_test': False,
2902 'gl_test_func': 'glGetQueryObjectuiv',
2903 'pepper_interface': 'Query',
2905 'BindUniformLocationCHROMIUM': {
2906 'type': 'GLchar',
2907 'extension': True,
2908 'data_transfer_methods': ['bucket'],
2909 'needs_size': True,
2910 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
2912 'InsertEventMarkerEXT': {
2913 'type': 'GLcharN',
2914 'decoder_func': 'DoInsertEventMarkerEXT',
2915 'expectation': False,
2916 'extension': True,
2918 'PushGroupMarkerEXT': {
2919 'type': 'GLcharN',
2920 'decoder_func': 'DoPushGroupMarkerEXT',
2921 'expectation': False,
2922 'extension': True,
2924 'PopGroupMarkerEXT': {
2925 'decoder_func': 'DoPopGroupMarkerEXT',
2926 'expectation': False,
2927 'extension': True,
2928 'impl_func': False,
2931 'GenVertexArraysOES': {
2932 'type': 'GENn',
2933 'extension': True,
2934 'gl_test_func': 'glGenVertexArraysOES',
2935 'resource_type': 'VertexArray',
2936 'resource_types': 'VertexArrays',
2937 'unit_test': False,
2938 'pepper_interface': 'VertexArrayObject',
2940 'BindVertexArrayOES': {
2941 'type': 'Bind',
2942 'extension': True,
2943 'gl_test_func': 'glBindVertexArrayOES',
2944 'decoder_func': 'DoBindVertexArrayOES',
2945 'gen_func': 'GenVertexArraysOES',
2946 'unit_test': False,
2947 'client_test': False,
2948 'pepper_interface': 'VertexArrayObject',
2950 'DeleteVertexArraysOES': {
2951 'type': 'DELn',
2952 'extension': True,
2953 'gl_test_func': 'glDeleteVertexArraysOES',
2954 'resource_type': 'VertexArray',
2955 'resource_types': 'VertexArrays',
2956 'unit_test': False,
2957 'pepper_interface': 'VertexArrayObject',
2959 'IsVertexArrayOES': {
2960 'type': 'Is',
2961 'extension': True,
2962 'gl_test_func': 'glIsVertexArrayOES',
2963 'decoder_func': 'DoIsVertexArrayOES',
2964 'expectation': False,
2965 'unit_test': False,
2966 'pepper_interface': 'VertexArrayObject',
2968 'BindTexImage2DCHROMIUM': {
2969 'decoder_func': 'DoBindTexImage2DCHROMIUM',
2970 'unit_test': False,
2971 'extension': True,
2972 'chromium': True,
2974 'ReleaseTexImage2DCHROMIUM': {
2975 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
2976 'unit_test': False,
2977 'extension': True,
2978 'chromium': True,
2980 'ShallowFinishCHROMIUM': {
2981 'impl_func': False,
2982 'gen_cmd': False,
2983 'extension': True,
2984 'chromium': True,
2985 'client_test': False,
2987 'ShallowFlushCHROMIUM': {
2988 'impl_func': False,
2989 'gen_cmd': False,
2990 'extension': True,
2991 'chromium': True,
2992 'client_test': False,
2994 'TraceBeginCHROMIUM': {
2995 'type': 'Custom',
2996 'impl_func': False,
2997 'client_test': False,
2998 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
2999 'extension': True,
3000 'chromium': True,
3002 'TraceEndCHROMIUM': {
3003 'impl_func': False,
3004 'client_test': False,
3005 'decoder_func': 'DoTraceEndCHROMIUM',
3006 'unit_test': False,
3007 'extension': True,
3008 'chromium': True,
3010 'AsyncTexImage2DCHROMIUM': {
3011 'type': 'Manual',
3012 'data_transfer_methods': ['shm'],
3013 'client_test': False,
3014 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3015 'GLintTextureInternalFormat internalformat, '
3016 'GLsizei width, GLsizei height, '
3017 'GLintTextureBorder border, '
3018 'GLenumTextureFormat format, GLenumPixelType type, '
3019 'const void* pixels, '
3020 'uint32_t async_upload_token, '
3021 'void* sync_data',
3022 'extension': True,
3023 'chromium': True,
3025 'AsyncTexSubImage2DCHROMIUM': {
3026 'type': 'Manual',
3027 'data_transfer_methods': ['shm'],
3028 'client_test': False,
3029 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3030 'GLint xoffset, GLint yoffset, '
3031 'GLsizei width, GLsizei height, '
3032 'GLenumTextureFormat format, GLenumPixelType type, '
3033 'const void* data, '
3034 'uint32_t async_upload_token, '
3035 'void* sync_data',
3036 'extension': True,
3037 'chromium': True,
3039 'WaitAsyncTexImage2DCHROMIUM': {
3040 'type': 'Manual',
3041 'client_test': False,
3042 'extension': True,
3043 'chromium': True,
3045 'WaitAllAsyncTexImage2DCHROMIUM': {
3046 'type': 'Manual',
3047 'client_test': False,
3048 'extension': True,
3049 'chromium': True,
3051 'DiscardFramebufferEXT': {
3052 'type': 'PUTn',
3053 'count': 1,
3054 'decoder_func': 'DoDiscardFramebufferEXT',
3055 'unit_test': False,
3056 'client_test': False,
3057 'extension_flag': 'ext_discard_framebuffer',
3059 'LoseContextCHROMIUM': {
3060 'decoder_func': 'DoLoseContextCHROMIUM',
3061 'unit_test': False,
3062 'extension': True,
3063 'chromium': True,
3065 'InsertSyncPointCHROMIUM': {
3066 'type': 'HandWritten',
3067 'impl_func': False,
3068 'extension': "CHROMIUM_sync_point",
3069 'chromium': True,
3071 'WaitSyncPointCHROMIUM': {
3072 'type': 'Custom',
3073 'impl_func': True,
3074 'extension': "CHROMIUM_sync_point",
3075 'chromium': True,
3076 'trace_level': 1,
3078 'DiscardBackbufferCHROMIUM': {
3079 'type': 'Custom',
3080 'impl_func': True,
3081 'extension': True,
3082 'chromium': True,
3084 'ScheduleOverlayPlaneCHROMIUM': {
3085 'type': 'Custom',
3086 'impl_func': True,
3087 'unit_test': False,
3088 'client_test': False,
3089 'extension': True,
3090 'chromium': True,
3092 'MatrixLoadfCHROMIUM': {
3093 'type': 'PUT',
3094 'count': 16,
3095 'data_type': 'GLfloat',
3096 'decoder_func': 'DoMatrixLoadfCHROMIUM',
3097 'gl_test_func': 'glMatrixLoadfEXT',
3098 'chromium': True,
3099 'extension': True,
3100 'extension_flag': 'chromium_path_rendering',
3102 'MatrixLoadIdentityCHROMIUM': {
3103 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
3104 'gl_test_func': 'glMatrixLoadIdentityEXT',
3105 'chromium': True,
3106 'extension': True,
3107 'extension_flag': 'chromium_path_rendering',
3112 def Grouper(n, iterable, fillvalue=None):
3113 """Collect data into fixed-length chunks or blocks"""
3114 args = [iter(iterable)] * n
3115 return itertools.izip_longest(fillvalue=fillvalue, *args)
3118 def SplitWords(input_string):
3119 """Transforms a input_string into a list of lower-case components.
3121 Args:
3122 input_string: the input string.
3124 Returns:
3125 a list of lower-case words.
3127 if input_string.find('_') > -1:
3128 # 'some_TEXT_' -> 'some text'
3129 return input_string.replace('_', ' ').strip().lower().split()
3130 else:
3131 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
3132 # mixed case.
3133 # look for capitalization to cut input_strings
3134 # 'SomeText' -> 'Some Text'
3135 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
3136 # 'Vector3' -> 'Vector 3'
3137 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
3138 return input_string.lower().split()
3141 def Lower(words):
3142 """Makes a lower-case identifier from words.
3144 Args:
3145 words: a list of lower-case words.
3147 Returns:
3148 the lower-case identifier.
3150 return '_'.join(words)
3153 def ToUnderscore(input_string):
3154 """converts CamelCase to camel_case."""
3155 words = SplitWords(input_string)
3156 return Lower(words)
3158 def CachedStateName(item):
3159 if item.get('cached', False):
3160 return 'cached_' + item['name']
3161 return item['name']
3163 def ToGLExtensionString(extension_flag):
3164 """Returns GL-type extension string of a extension flag."""
3165 if extension_flag == "oes_compressed_etc1_rgb8_texture":
3166 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
3167 # unfortunate.
3168 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
3169 'egl', 'atc', 'etc1', 'angle']
3170 parts = extension_flag.split('_')
3171 return "_".join(
3172 [part.upper() if part in uppercase_words else part for part in parts])
3174 def ToCamelCase(input_string):
3175 """converts ABC_underscore_case to ABCUnderscoreCase."""
3176 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
3178 def GetGLGetTypeConversion(result_type, value_type, value):
3179 """Makes a gl compatible type conversion string for accessing state variables.
3181 Useful when accessing state variables through glGetXXX calls.
3182 glGet documetation (for example, the manual pages):
3183 [...] If glGetIntegerv is called, [...] most floating-point values are
3184 rounded to the nearest integer value. [...]
3186 Args:
3187 result_type: the gl type to be obtained
3188 value_type: the GL type of the state variable
3189 value: the name of the state variable
3191 Returns:
3192 String that converts the state variable to desired GL type according to GL
3193 rules.
3196 if result_type == 'GLint':
3197 if value_type == 'GLfloat':
3198 return 'static_cast<GLint>(round(%s))' % value
3199 return 'static_cast<%s>(%s)' % (result_type, value)
3201 class CWriter(object):
3202 """Writes to a file formatting it for Google's style guidelines."""
3204 def __init__(self, filename):
3205 self.filename = filename
3206 self.content = []
3208 def Write(self, string):
3209 """Writes a string to a file spliting if it's > 80 characters."""
3210 lines = string.splitlines()
3211 num_lines = len(lines)
3212 for ii in range(0, num_lines):
3213 self.content.append(lines[ii])
3214 if ii < (num_lines - 1) or string[-1] == '\n':
3215 self.content.append('\n')
3217 def Close(self):
3218 """Close the file."""
3219 content = "".join(self.content)
3220 write_file = True
3221 if os.path.exists(self.filename):
3222 old_file = open(self.filename, "rb");
3223 old_content = old_file.read()
3224 old_file.close();
3225 if content == old_content:
3226 write_file = False
3227 if write_file:
3228 file = open(self.filename, "wb")
3229 file.write(content)
3230 file.close()
3233 class CHeaderWriter(CWriter):
3234 """Writes a C Header file."""
3236 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
3238 def __init__(self, filename, file_comment = None):
3239 CWriter.__init__(self, filename)
3241 base = os.path.abspath(filename)
3242 while os.path.basename(base) != 'src':
3243 new_base = os.path.dirname(base)
3244 assert new_base != base # Prevent infinite loop.
3245 base = new_base
3247 hpath = os.path.relpath(filename, base)
3248 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
3250 self.Write(_LICENSE)
3251 self.Write(_DO_NOT_EDIT_WARNING)
3252 if not file_comment == None:
3253 self.Write(file_comment)
3254 self.Write("#ifndef %s\n" % self.guard)
3255 self.Write("#define %s\n\n" % self.guard)
3257 def Close(self):
3258 self.Write("#endif // %s\n\n" % self.guard)
3259 CWriter.Close(self)
3261 class TypeHandler(object):
3262 """This class emits code for a particular type of function."""
3264 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
3266 def __init__(self):
3267 pass
3269 def InitFunction(self, func):
3270 """Add or adjust anything type specific for this function."""
3271 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
3272 func.AddCmdArg(DataSizeArgument('data_size'))
3274 def NeedsDataTransferFunction(self, func):
3275 """Overriden from TypeHandler."""
3276 return func.num_pointer_args >= 1
3278 def WriteStruct(self, func, file):
3279 """Writes a structure that matches the arguments to a function."""
3280 comment = func.GetInfo('cmd_comment')
3281 if not comment == None:
3282 file.Write(comment)
3283 file.Write("struct %s {\n" % func.name)
3284 file.Write(" typedef %s ValueType;\n" % func.name)
3285 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
3286 func.WriteCmdArgFlag(file)
3287 func.WriteCmdFlag(file)
3288 file.Write("\n")
3289 result = func.GetInfo('result')
3290 if not result == None:
3291 if len(result) == 1:
3292 file.Write(" typedef %s Result;\n\n" % result[0])
3293 else:
3294 file.Write(" struct Result {\n")
3295 for line in result:
3296 file.Write(" %s;\n" % line)
3297 file.Write(" };\n\n")
3299 func.WriteCmdComputeSize(file)
3300 func.WriteCmdSetHeader(file)
3301 func.WriteCmdInit(file)
3302 func.WriteCmdSet(file)
3304 file.Write(" gpu::CommandHeader header;\n")
3305 args = func.GetCmdArgs()
3306 for arg in args:
3307 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
3309 consts = func.GetCmdConstants()
3310 for const in consts:
3311 file.Write(" static const %s %s = %s;\n" %
3312 (const.cmd_type, const.name, const.GetConstantValue()))
3314 file.Write("};\n")
3315 file.Write("\n")
3317 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
3318 file.Write("static_assert(sizeof(%s) == %d,\n" % (func.name, size))
3319 file.Write(" \"size of %s should be %d\");\n" %
3320 (func.name, size))
3321 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func.name)
3322 file.Write(" \"offset of %s header should be 0\");\n" %
3323 func.name)
3324 offset = _SIZE_OF_COMMAND_HEADER
3325 for arg in args:
3326 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
3327 (func.name, arg.name, offset))
3328 file.Write(" \"offset of %s %s should be %d\");\n" %
3329 (func.name, arg.name, offset))
3330 offset += _SIZE_OF_UINT32
3331 if not result == None and len(result) > 1:
3332 offset = 0;
3333 for line in result:
3334 parts = line.split()
3335 name = parts[-1]
3336 check = """
3337 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
3338 "offset of %(cmd_name)s Result %(field_name)s should be "
3339 "%(offset)d");
3341 file.Write((check.strip() + "\n") % {
3342 'cmd_name': func.name,
3343 'field_name': name,
3344 'offset': offset,
3346 offset += _SIZE_OF_UINT32
3347 file.Write("\n")
3349 def WriteHandlerImplementation(self, func, file):
3350 """Writes the handler implementation for this command."""
3351 if func.IsUnsafe() and func.GetInfo('id_mapping'):
3352 code_no_gen = """ if (!group_->Get%(type)sServiceId(%(var)s, &%(var)s)) {
3353 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3354 return error::kNoError;
3357 code_gen = """ if (!group_->Get%(type)sServiceId(%(var)s, &%(var)s)) {
3358 if (!group_->bind_generates_resource()) {
3359 LOCAL_SET_GL_ERROR(
3360 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3361 return error::kNoError;
3363 GLuint client_id = %(var)s;
3364 gl%(gen_func)s(1, &%(var)s);
3365 Create%(type)s(client_id, %(var)s);
3368 gen_func = func.GetInfo('gen_func')
3369 for id_type in func.GetInfo('id_mapping'):
3370 if gen_func and id_type in gen_func:
3371 file.Write(code_gen % { 'type': id_type,
3372 'var': id_type.lower(),
3373 'func': func.GetGLFunctionName(),
3374 'gen_func': gen_func })
3375 else:
3376 file.Write(code_no_gen % { 'type': id_type,
3377 'var': id_type.lower(),
3378 'func': func.GetGLFunctionName() })
3379 file.Write(" %s(%s);\n" %
3380 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3382 def WriteCmdSizeTest(self, func, file):
3383 """Writes the size test for a command."""
3384 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3386 def WriteFormatTest(self, func, file):
3387 """Writes a format test for a command."""
3388 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
3389 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
3390 (func.name, func.name))
3391 file.Write(" void* next_cmd = cmd.Set(\n")
3392 file.Write(" &cmd")
3393 args = func.GetCmdArgs()
3394 for value, arg in enumerate(args):
3395 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
3396 file.Write(");\n")
3397 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
3398 func.name)
3399 file.Write(" cmd.header.command);\n")
3400 func.type_handler.WriteCmdSizeTest(func, file)
3401 for value, arg in enumerate(args):
3402 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
3403 (arg.type, value + 11, arg.name))
3404 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
3405 file.Write(" next_cmd, sizeof(cmd));\n")
3406 file.Write("}\n")
3407 file.Write("\n")
3409 def WriteImmediateFormatTest(self, func, file):
3410 """Writes a format test for an immediate version of a command."""
3411 pass
3413 def WriteBucketFormatTest(self, func, file):
3414 """Writes a format test for a bucket version of a command."""
3415 pass
3417 def WriteGetDataSizeCode(self, func, file):
3418 """Writes the code to set data_size used in validation"""
3419 pass
3421 def WriteImmediateCmdSizeTest(self, func, file):
3422 """Writes a size test for an immediate version of a command."""
3423 file.Write(" // TODO(gman): Compute correct size.\n")
3424 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3426 def __WriteIdMapping(self, func, file):
3427 """Writes client side / service side ID mapping."""
3428 if not func.IsUnsafe() or not func.GetInfo('id_mapping'):
3429 return
3430 for id_type in func.GetInfo('id_mapping'):
3431 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
3432 (id_type, id_type.lower(), id_type.lower()))
3434 def WriteImmediateHandlerImplementation (self, func, file):
3435 """Writes the handler impl for the immediate version of a command."""
3436 self.__WriteIdMapping(func, file)
3437 file.Write(" %s(%s);\n" %
3438 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3440 def WriteBucketHandlerImplementation (self, func, file):
3441 """Writes the handler impl for the bucket version of a command."""
3442 self.__WriteIdMapping(func, file)
3443 file.Write(" %s(%s);\n" %
3444 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3446 def WriteServiceHandlerFunctionHeader(self, func, file):
3447 """Writes function header for service implementation handlers."""
3448 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
3449 uint32_t immediate_data_size, const void* cmd_data) {
3450 """ % {'name': func.name})
3451 if func.IsUnsafe():
3452 file.Write("""if (!unsafe_es3_apis_enabled())
3453 return error::kUnknownCommand;
3454 """)
3455 file.Write("""const gles2::cmds::%(name)s& c =
3456 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
3457 (void)c;
3458 """ % {'name': func.name})
3460 def WriteServiceImplementation(self, func, file):
3461 """Writes the service implementation for a command."""
3462 self.WriteServiceHandlerFunctionHeader(func, file)
3463 self.WriteHandlerExtensionCheck(func, file)
3464 self.WriteHandlerDeferReadWrite(func, file);
3465 if len(func.GetOriginalArgs()) > 0:
3466 last_arg = func.GetLastOriginalArg()
3467 all_but_last_arg = func.GetOriginalArgs()[:-1]
3468 for arg in all_but_last_arg:
3469 arg.WriteGetCode(file)
3470 self.WriteGetDataSizeCode(func, file)
3471 last_arg.WriteGetCode(file)
3472 func.WriteHandlerValidation(file)
3473 func.WriteHandlerImplementation(file)
3474 file.Write(" return error::kNoError;\n")
3475 file.Write("}\n")
3476 file.Write("\n")
3478 def WriteImmediateServiceImplementation(self, func, file):
3479 """Writes the service implementation for an immediate version of command."""
3480 self.WriteServiceHandlerFunctionHeader(func, file)
3481 self.WriteHandlerExtensionCheck(func, file)
3482 self.WriteHandlerDeferReadWrite(func, file);
3483 for arg in func.GetOriginalArgs():
3484 if arg.IsPointer():
3485 self.WriteGetDataSizeCode(func, file)
3486 arg.WriteGetCode(file)
3487 func.WriteHandlerValidation(file)
3488 func.WriteHandlerImplementation(file)
3489 file.Write(" return error::kNoError;\n")
3490 file.Write("}\n")
3491 file.Write("\n")
3493 def WriteBucketServiceImplementation(self, func, file):
3494 """Writes the service implementation for a bucket version of command."""
3495 self.WriteServiceHandlerFunctionHeader(func, file)
3496 self.WriteHandlerExtensionCheck(func, file)
3497 self.WriteHandlerDeferReadWrite(func, file);
3498 for arg in func.GetCmdArgs():
3499 arg.WriteGetCode(file)
3500 func.WriteHandlerValidation(file)
3501 func.WriteHandlerImplementation(file)
3502 file.Write(" return error::kNoError;\n")
3503 file.Write("}\n")
3504 file.Write("\n")
3506 def WriteHandlerExtensionCheck(self, func, file):
3507 if func.GetInfo('extension_flag'):
3508 file.Write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
3509 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
3510 " \"function not available\");\n" % func.original_name)
3511 file.Write(" return error::kNoError;")
3512 file.Write(" }\n\n")
3514 def WriteHandlerDeferReadWrite(self, func, file):
3515 """Writes the code to handle deferring reads or writes."""
3516 defer_draws = func.GetInfo('defer_draws')
3517 defer_reads = func.GetInfo('defer_reads')
3518 if defer_draws or defer_reads:
3519 file.Write(" error::Error error;\n")
3520 if defer_draws:
3521 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
3522 file.Write(" if (error != error::kNoError)\n")
3523 file.Write(" return error;\n")
3524 if defer_reads:
3525 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
3526 file.Write(" if (error != error::kNoError)\n")
3527 file.Write(" return error;\n")
3529 def WriteValidUnitTest(self, func, file, test, *extras):
3530 """Writes a valid unit test for the service implementation."""
3531 if func.GetInfo('expectation') == False:
3532 test = self._remove_expected_call_re.sub('', test)
3533 name = func.name
3534 arg_strings = [
3535 arg.GetValidArg(func) \
3536 for arg in func.GetOriginalArgs() if not arg.IsConstant()
3538 gl_arg_strings = [
3539 arg.GetValidGLArg(func) \
3540 for arg in func.GetOriginalArgs()
3542 gl_func_name = func.GetGLTestFunctionName()
3543 vars = {
3544 'name':name,
3545 'gl_func_name': gl_func_name,
3546 'args': ", ".join(arg_strings),
3547 'gl_args': ", ".join(gl_arg_strings),
3549 for extra in extras:
3550 vars.update(extra)
3551 old_test = ""
3552 while (old_test != test):
3553 old_test = test
3554 test = test % vars
3555 file.Write(test % vars)
3557 def WriteInvalidUnitTest(self, func, file, test, *extras):
3558 """Writes an invalid unit test for the service implementation."""
3559 if func.IsUnsafe():
3560 return
3561 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
3562 # Service implementation does not test constants, as they are not part of
3563 # the call in the service side.
3564 if invalid_arg.IsConstant():
3565 continue
3567 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
3568 for value_index in range(0, num_invalid_values):
3569 arg_strings = []
3570 parse_result = "kNoError"
3571 gl_error = None
3572 for arg in func.GetOriginalArgs():
3573 if arg.IsConstant():
3574 continue
3575 if invalid_arg is arg:
3576 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
3577 value_index)
3578 else:
3579 arg_string = arg.GetValidArg(func)
3580 arg_strings.append(arg_string)
3581 gl_arg_strings = []
3582 for arg in func.GetOriginalArgs():
3583 gl_arg_strings.append("_")
3584 gl_func_name = func.GetGLTestFunctionName()
3585 gl_error_test = ''
3586 if not gl_error == None:
3587 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
3589 vars = {
3590 'name': func.name,
3591 'arg_index': invalid_arg_index,
3592 'value_index': value_index,
3593 'gl_func_name': gl_func_name,
3594 'args': ", ".join(arg_strings),
3595 'all_but_last_args': ", ".join(arg_strings[:-1]),
3596 'gl_args': ", ".join(gl_arg_strings),
3597 'parse_result': parse_result,
3598 'gl_error_test': gl_error_test,
3600 for extra in extras:
3601 vars.update(extra)
3602 file.Write(test % vars)
3604 def WriteServiceUnitTest(self, func, file, *extras):
3605 """Writes the service unit test for a command."""
3607 if func.name == 'Enable':
3608 valid_test = """
3609 TEST_P(%(test_name)s, %(name)sValidArgs) {
3610 SetupExpectationsForEnableDisable(%(gl_args)s, true);
3611 SpecializedSetup<cmds::%(name)s, 0>(true);
3612 cmds::%(name)s cmd;
3613 cmd.Init(%(args)s);"""
3614 elif func.name == 'Disable':
3615 valid_test = """
3616 TEST_P(%(test_name)s, %(name)sValidArgs) {
3617 SetupExpectationsForEnableDisable(%(gl_args)s, false);
3618 SpecializedSetup<cmds::%(name)s, 0>(true);
3619 cmds::%(name)s cmd;
3620 cmd.Init(%(args)s);"""
3621 else:
3622 valid_test = """
3623 TEST_P(%(test_name)s, %(name)sValidArgs) {
3624 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
3625 SpecializedSetup<cmds::%(name)s, 0>(true);
3626 cmds::%(name)s cmd;
3627 cmd.Init(%(args)s);"""
3628 if func.IsUnsafe():
3629 valid_test += """
3630 decoder_->set_unsafe_es3_apis_enabled(true);
3631 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3632 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3633 decoder_->set_unsafe_es3_apis_enabled(false);
3634 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
3637 else:
3638 valid_test += """
3639 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3640 EXPECT_EQ(GL_NO_ERROR, GetGLError());
3643 self.WriteValidUnitTest(func, file, valid_test, *extras)
3645 if not func.IsUnsafe():
3646 invalid_test = """
3647 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
3648 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
3649 SpecializedSetup<cmds::%(name)s, 0>(false);
3650 cmds::%(name)s cmd;
3651 cmd.Init(%(args)s);
3652 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
3655 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
3657 def WriteImmediateServiceUnitTest(self, func, file, *extras):
3658 """Writes the service unit test for an immediate command."""
3659 file.Write("// TODO(gman): %s\n" % func.name)
3661 def WriteImmediateValidationCode(self, func, file):
3662 """Writes the validation code for an immediate version of a command."""
3663 pass
3665 def WriteBucketServiceUnitTest(self, func, file, *extras):
3666 """Writes the service unit test for a bucket command."""
3667 file.Write("// TODO(gman): %s\n" % func.name)
3669 def WriteBucketValidationCode(self, func, file):
3670 """Writes the validation code for a bucket version of a command."""
3671 file.Write("// TODO(gman): %s\n" % func.name)
3673 def WriteGLES2ImplementationDeclaration(self, func, file):
3674 """Writes the GLES2 Implemention declaration."""
3675 impl_decl = func.GetInfo('impl_decl')
3676 if impl_decl == None or impl_decl == True:
3677 file.Write("%s %s(%s) override;\n" %
3678 (func.return_type, func.original_name,
3679 func.MakeTypedOriginalArgString("")))
3680 file.Write("\n")
3682 def WriteGLES2CLibImplementation(self, func, file):
3683 file.Write("%s GLES2%s(%s) {\n" %
3684 (func.return_type, func.name,
3685 func.MakeTypedOriginalArgString("")))
3686 result_string = "return "
3687 if func.return_type == "void":
3688 result_string = ""
3689 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
3690 (result_string, func.original_name,
3691 func.MakeOriginalArgString("")))
3692 file.Write("}\n")
3694 def WriteGLES2Header(self, func, file):
3695 """Writes a re-write macro for GLES"""
3696 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
3698 def WriteClientGLCallLog(self, func, file):
3699 """Writes a logging macro for the client side code."""
3700 comma = ""
3701 if len(func.GetOriginalArgs()):
3702 comma = " << "
3703 file.Write(
3704 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
3705 (func.original_name, comma, func.MakeLogArgString()))
3707 def WriteClientGLReturnLog(self, func, file):
3708 """Writes the return value logging code."""
3709 if func.return_type != "void":
3710 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
3712 def WriteGLES2ImplementationHeader(self, func, file):
3713 """Writes the GLES2 Implemention."""
3714 self.WriteGLES2ImplementationDeclaration(func, file)
3716 def WriteGLES2TraceImplementationHeader(self, func, file):
3717 """Writes the GLES2 Trace Implemention header."""
3718 file.Write("%s %s(%s) override;\n" %
3719 (func.return_type, func.original_name,
3720 func.MakeTypedOriginalArgString("")))
3722 def WriteGLES2TraceImplementation(self, func, file):
3723 """Writes the GLES2 Trace Implemention."""
3724 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
3725 (func.return_type, func.original_name,
3726 func.MakeTypedOriginalArgString("")))
3727 result_string = "return "
3728 if func.return_type == "void":
3729 result_string = ""
3730 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
3731 func.name)
3732 file.Write(" %sgl_->%s(%s);\n" %
3733 (result_string, func.name, func.MakeOriginalArgString("")))
3734 file.Write("}\n")
3735 file.Write("\n")
3737 def WriteGLES2Implementation(self, func, file):
3738 """Writes the GLES2 Implemention."""
3739 impl_func = func.GetInfo('impl_func')
3740 impl_decl = func.GetInfo('impl_decl')
3741 gen_cmd = func.GetInfo('gen_cmd')
3742 if (func.can_auto_generate and
3743 (impl_func == None or impl_func == True) and
3744 (impl_decl == None or impl_decl == True) and
3745 (gen_cmd == None or gen_cmd == True)):
3746 file.Write("%s GLES2Implementation::%s(%s) {\n" %
3747 (func.return_type, func.original_name,
3748 func.MakeTypedOriginalArgString("")))
3749 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
3750 self.WriteClientGLCallLog(func, file)
3751 func.WriteDestinationInitalizationValidation(file)
3752 for arg in func.GetOriginalArgs():
3753 arg.WriteClientSideValidationCode(file, func)
3754 file.Write(" helper_->%s(%s);\n" %
3755 (func.name, func.MakeHelperArgString("")))
3756 file.Write(" CheckGLError();\n")
3757 self.WriteClientGLReturnLog(func, file)
3758 file.Write("}\n")
3759 file.Write("\n")
3761 def WriteGLES2InterfaceHeader(self, func, file):
3762 """Writes the GLES2 Interface."""
3763 file.Write("virtual %s %s(%s) = 0;\n" %
3764 (func.return_type, func.original_name,
3765 func.MakeTypedOriginalArgString("")))
3767 def WriteGLES2InterfaceStub(self, func, file):
3768 """Writes the GLES2 Interface stub declaration."""
3769 file.Write("%s %s(%s) override;\n" %
3770 (func.return_type, func.original_name,
3771 func.MakeTypedOriginalArgString("")))
3773 def WriteGLES2InterfaceStubImpl(self, func, file):
3774 """Writes the GLES2 Interface stub declaration."""
3775 args = func.GetOriginalArgs()
3776 arg_string = ", ".join(
3777 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
3778 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
3779 (func.return_type, func.original_name, arg_string))
3780 if func.return_type != "void":
3781 file.Write(" return 0;\n")
3782 file.Write("}\n")
3784 def WriteGLES2ImplementationUnitTest(self, func, file):
3785 """Writes the GLES2 Implemention unit test."""
3786 client_test = func.GetInfo('client_test')
3787 if (func.can_auto_generate and
3788 (client_test == None or client_test == True)):
3789 code = """
3790 TEST_F(GLES2ImplementationTest, %(name)s) {
3791 struct Cmds {
3792 cmds::%(name)s cmd;
3794 Cmds expected;
3795 expected.cmd.Init(%(cmd_args)s);
3797 gl_->%(name)s(%(args)s);
3798 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
3801 cmd_arg_strings = [
3802 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
3805 gl_arg_strings = [
3806 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
3809 file.Write(code % {
3810 'name': func.name,
3811 'args': ", ".join(gl_arg_strings),
3812 'cmd_args': ", ".join(cmd_arg_strings),
3815 # Test constants for invalid values, as they are not tested by the
3816 # service.
3817 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
3818 if constants:
3819 code = """
3820 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
3821 gl_->%(name)s(%(args)s);
3822 EXPECT_TRUE(NoCommandsWritten());
3823 EXPECT_EQ(%(gl_error)s, CheckError());
3826 for invalid_arg in constants:
3827 gl_arg_strings = []
3828 invalid = invalid_arg.GetInvalidArg(func)
3829 for arg in func.GetOriginalArgs():
3830 if arg is invalid_arg:
3831 gl_arg_strings.append(invalid[0])
3832 else:
3833 gl_arg_strings.append(arg.GetValidClientSideArg(func))
3835 file.Write(code % {
3836 'name': func.name,
3837 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
3838 'args': ", ".join(gl_arg_strings),
3839 'gl_error': invalid[2],
3841 else:
3842 if client_test != False:
3843 file.Write("// TODO: Implement unit test for %s\n" % func.name)
3845 def WriteDestinationInitalizationValidation(self, func, file):
3846 """Writes the client side destintion initialization validation."""
3847 for arg in func.GetOriginalArgs():
3848 arg.WriteDestinationInitalizationValidation(file, func)
3850 def WriteTraceEvent(self, func, file):
3851 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
3852 func.original_name)
3854 def WriteImmediateCmdComputeSize(self, func, file):
3855 """Writes the size computation code for the immediate version of a cmd."""
3856 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
3857 file.Write(" return static_cast<uint32_t>(\n")
3858 file.Write(" sizeof(ValueType) + // NOLINT\n")
3859 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
3860 file.Write(" }\n")
3861 file.Write("\n")
3863 def WriteImmediateCmdSetHeader(self, func, file):
3864 """Writes the SetHeader function for the immediate version of a cmd."""
3865 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
3866 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
3867 file.Write(" }\n")
3868 file.Write("\n")
3870 def WriteImmediateCmdInit(self, func, file):
3871 """Writes the Init function for the immediate version of a command."""
3872 raise NotImplementedError(func.name)
3874 def WriteImmediateCmdSet(self, func, file):
3875 """Writes the Set function for the immediate version of a command."""
3876 raise NotImplementedError(func.name)
3878 def WriteCmdHelper(self, func, file):
3879 """Writes the cmd helper definition for a cmd."""
3880 code = """ void %(name)s(%(typed_args)s) {
3881 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
3882 if (c) {
3883 c->Init(%(args)s);
3888 file.Write(code % {
3889 "name": func.name,
3890 "typed_args": func.MakeTypedCmdArgString(""),
3891 "args": func.MakeCmdArgString(""),
3894 def WriteImmediateCmdHelper(self, func, file):
3895 """Writes the cmd helper definition for the immediate version of a cmd."""
3896 code = """ void %(name)s(%(typed_args)s) {
3897 const uint32_t s = 0; // TODO(gman): compute correct size
3898 gles2::cmds::%(name)s* c =
3899 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
3900 if (c) {
3901 c->Init(%(args)s);
3906 file.Write(code % {
3907 "name": func.name,
3908 "typed_args": func.MakeTypedCmdArgString(""),
3909 "args": func.MakeCmdArgString(""),
3913 class StateSetHandler(TypeHandler):
3914 """Handler for commands that simply set state."""
3916 def __init__(self):
3917 TypeHandler.__init__(self)
3919 def WriteHandlerImplementation(self, func, file):
3920 """Overrriden from TypeHandler."""
3921 state_name = func.GetInfo('state')
3922 state = _STATES[state_name]
3923 states = state['states']
3924 args = func.GetOriginalArgs()
3925 for ndx,item in enumerate(states):
3926 code = []
3927 if 'range_checks' in item:
3928 for range_check in item['range_checks']:
3929 code.append("%s %s" % (args[ndx].name, range_check['check']))
3930 if 'nan_check' in item:
3931 # Drivers might generate an INVALID_VALUE error when a value is set
3932 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
3933 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
3934 # Make this behavior consistent within Chromium, and avoid leaking GL
3935 # errors by generating the error in the command buffer instead of
3936 # letting the GL driver generate it.
3937 code.append("base::IsNaN(%s)" % args[ndx].name)
3938 if len(code):
3939 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3940 file.Write(
3941 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
3942 ' "%s", "%s out of range");\n' %
3943 (func.name, args[ndx].name))
3944 file.Write(" return error::kNoError;\n")
3945 file.Write(" }\n")
3946 code = []
3947 for ndx,item in enumerate(states):
3948 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
3949 file.Write(" if (%s) {\n" % " ||\n ".join(code))
3950 for ndx,item in enumerate(states):
3951 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
3952 if 'state_flag' in state:
3953 file.Write(" %s = true;\n" % state['state_flag'])
3954 if not func.GetInfo("no_gl"):
3955 for ndx,item in enumerate(states):
3956 if item.get('cached', False):
3957 file.Write(" state_.%s = %s;\n" %
3958 (CachedStateName(item), args[ndx].name))
3959 file.Write(" %s(%s);\n" %
3960 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3961 file.Write(" }\n")
3963 def WriteServiceUnitTest(self, func, file, *extras):
3964 """Overrriden from TypeHandler."""
3965 TypeHandler.WriteServiceUnitTest(self, func, file, *extras)
3966 state_name = func.GetInfo('state')
3967 state = _STATES[state_name]
3968 states = state['states']
3969 for ndx,item in enumerate(states):
3970 if 'range_checks' in item:
3971 for check_ndx, range_check in enumerate(item['range_checks']):
3972 valid_test = """
3973 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
3974 SpecializedSetup<cmds::%(name)s, 0>(false);
3975 cmds::%(name)s cmd;
3976 cmd.Init(%(args)s);
3977 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
3978 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
3981 name = func.name
3982 arg_strings = [
3983 arg.GetValidArg(func) \
3984 for arg in func.GetOriginalArgs() if not arg.IsConstant()
3987 arg_strings[ndx] = range_check['test_value']
3988 vars = {
3989 'name': name,
3990 'ndx': ndx,
3991 'check_ndx': check_ndx,
3992 'args': ", ".join(arg_strings),
3994 for extra in extras:
3995 vars.update(extra)
3996 file.Write(valid_test % vars)
3997 if 'nan_check' in item:
3998 valid_test = """
3999 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
4000 SpecializedSetup<cmds::%(name)s, 0>(false);
4001 cmds::%(name)s cmd;
4002 cmd.Init(%(args)s);
4003 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4004 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4007 name = func.name
4008 arg_strings = [
4009 arg.GetValidArg(func) \
4010 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4013 arg_strings[ndx] = 'nanf("")'
4014 vars = {
4015 'name': name,
4016 'ndx': ndx,
4017 'args': ", ".join(arg_strings),
4019 for extra in extras:
4020 vars.update(extra)
4021 file.Write(valid_test % vars)
4024 class StateSetRGBAlphaHandler(TypeHandler):
4025 """Handler for commands that simply set state that have rgb/alpha."""
4027 def __init__(self):
4028 TypeHandler.__init__(self)
4030 def WriteHandlerImplementation(self, func, file):
4031 """Overrriden from TypeHandler."""
4032 state_name = func.GetInfo('state')
4033 state = _STATES[state_name]
4034 states = state['states']
4035 args = func.GetOriginalArgs()
4036 num_args = len(args)
4037 code = []
4038 for ndx,item in enumerate(states):
4039 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
4040 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4041 for ndx, item in enumerate(states):
4042 file.Write(" state_.%s = %s;\n" %
4043 (item['name'], args[ndx % num_args].name))
4044 if 'state_flag' in state:
4045 file.Write(" %s = true;\n" % state['state_flag'])
4046 if not func.GetInfo("no_gl"):
4047 file.Write(" %s(%s);\n" %
4048 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4049 file.Write(" }\n")
4052 class StateSetFrontBackSeparateHandler(TypeHandler):
4053 """Handler for commands that simply set state that have front/back."""
4055 def __init__(self):
4056 TypeHandler.__init__(self)
4058 def WriteHandlerImplementation(self, func, file):
4059 """Overrriden from TypeHandler."""
4060 state_name = func.GetInfo('state')
4061 state = _STATES[state_name]
4062 states = state['states']
4063 args = func.GetOriginalArgs()
4064 face = args[0].name
4065 num_args = len(args)
4066 file.Write(" bool changed = false;\n")
4067 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4068 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4069 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4070 code = []
4071 for ndx, item in enumerate(group):
4072 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
4073 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
4074 file.Write(" }\n")
4075 file.Write(" if (changed) {\n")
4076 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4077 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4078 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4079 for ndx, item in enumerate(group):
4080 file.Write(" state_.%s = %s;\n" %
4081 (item['name'], args[ndx + 1].name))
4082 file.Write(" }\n")
4083 if 'state_flag' in state:
4084 file.Write(" %s = true;\n" % state['state_flag'])
4085 if not func.GetInfo("no_gl"):
4086 file.Write(" %s(%s);\n" %
4087 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4088 file.Write(" }\n")
4091 class StateSetFrontBackHandler(TypeHandler):
4092 """Handler for commands that simply set state that set both front/back."""
4094 def __init__(self):
4095 TypeHandler.__init__(self)
4097 def WriteHandlerImplementation(self, func, file):
4098 """Overrriden from TypeHandler."""
4099 state_name = func.GetInfo('state')
4100 state = _STATES[state_name]
4101 states = state['states']
4102 args = func.GetOriginalArgs()
4103 num_args = len(args)
4104 code = []
4105 for group_ndx, group in enumerate(Grouper(num_args, states)):
4106 for ndx, item in enumerate(group):
4107 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
4108 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4109 for group_ndx, group in enumerate(Grouper(num_args, states)):
4110 for ndx, item in enumerate(group):
4111 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
4112 if 'state_flag' in state:
4113 file.Write(" %s = true;\n" % state['state_flag'])
4114 if not func.GetInfo("no_gl"):
4115 file.Write(" %s(%s);\n" %
4116 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4117 file.Write(" }\n")
4120 class StateSetNamedParameter(TypeHandler):
4121 """Handler for commands that set a state chosen with an enum parameter."""
4123 def __init__(self):
4124 TypeHandler.__init__(self)
4126 def WriteHandlerImplementation(self, func, file):
4127 """Overridden from TypeHandler."""
4128 state_name = func.GetInfo('state')
4129 state = _STATES[state_name]
4130 states = state['states']
4131 args = func.GetOriginalArgs()
4132 num_args = len(args)
4133 assert num_args == 2
4134 file.Write(" switch (%s) {\n" % args[0].name)
4135 for state in states:
4136 file.Write(" case %s:\n" % state['enum'])
4137 file.Write(" if (state_.%s != %s) {\n" %
4138 (state['name'], args[1].name))
4139 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
4140 if not func.GetInfo("no_gl"):
4141 file.Write(" %s(%s);\n" %
4142 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4143 file.Write(" }\n")
4144 file.Write(" break;\n")
4145 file.Write(" default:\n")
4146 file.Write(" NOTREACHED();\n")
4147 file.Write(" }\n")
4150 class CustomHandler(TypeHandler):
4151 """Handler for commands that are auto-generated but require minor tweaks."""
4153 def __init__(self):
4154 TypeHandler.__init__(self)
4156 def WriteServiceImplementation(self, func, file):
4157 """Overrriden from TypeHandler."""
4158 pass
4160 def WriteImmediateServiceImplementation(self, func, file):
4161 """Overrriden from TypeHandler."""
4162 pass
4164 def WriteBucketServiceImplementation(self, func, file):
4165 """Overrriden from TypeHandler."""
4166 pass
4168 def WriteServiceUnitTest(self, func, file, *extras):
4169 """Overrriden from TypeHandler."""
4170 file.Write("// TODO(gman): %s\n\n" % func.name)
4172 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4173 """Overrriden from TypeHandler."""
4174 file.Write("// TODO(gman): %s\n\n" % func.name)
4176 def WriteImmediateCmdGetTotalSize(self, func, file):
4177 """Overrriden from TypeHandler."""
4178 file.Write(
4179 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
4181 def WriteImmediateCmdInit(self, func, file):
4182 """Overrriden from TypeHandler."""
4183 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
4184 self.WriteImmediateCmdGetTotalSize(func, file)
4185 file.Write(" SetHeader(total_size);\n")
4186 args = func.GetCmdArgs()
4187 for arg in args:
4188 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4189 file.Write(" }\n")
4190 file.Write("\n")
4192 def WriteImmediateCmdSet(self, func, file):
4193 """Overrriden from TypeHandler."""
4194 copy_args = func.MakeCmdArgString("_", False)
4195 file.Write(" void* Set(void* cmd%s) {\n" %
4196 func.MakeTypedCmdArgString("_", True))
4197 self.WriteImmediateCmdGetTotalSize(func, file)
4198 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
4199 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4200 "cmd, total_size);\n")
4201 file.Write(" }\n")
4202 file.Write("\n")
4205 class TodoHandler(CustomHandler):
4206 """Handle for commands that are not yet implemented."""
4208 def NeedsDataTransferFunction(self, func):
4209 """Overriden from TypeHandler."""
4210 return False
4212 def WriteImmediateFormatTest(self, func, file):
4213 """Overrriden from TypeHandler."""
4214 pass
4216 def WriteGLES2ImplementationUnitTest(self, func, file):
4217 """Overrriden from TypeHandler."""
4218 pass
4220 def WriteGLES2Implementation(self, func, file):
4221 """Overrriden from TypeHandler."""
4222 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4223 (func.return_type, func.original_name,
4224 func.MakeTypedOriginalArgString("")))
4225 file.Write(" // TODO: for now this is a no-op\n")
4226 file.Write(
4227 " SetGLError("
4228 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4229 func.name)
4230 if func.return_type != "void":
4231 file.Write(" return 0;\n")
4232 file.Write("}\n")
4233 file.Write("\n")
4235 def WriteServiceImplementation(self, func, file):
4236 """Overrriden from TypeHandler."""
4237 self.WriteServiceHandlerFunctionHeader(func, file)
4238 file.Write(" // TODO: for now this is a no-op\n")
4239 file.Write(
4240 " LOCAL_SET_GL_ERROR("
4241 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4242 func.name)
4243 file.Write(" return error::kNoError;\n")
4244 file.Write("}\n")
4245 file.Write("\n")
4248 class HandWrittenHandler(CustomHandler):
4249 """Handler for comands where everything must be written by hand."""
4251 def InitFunction(self, func):
4252 """Add or adjust anything type specific for this function."""
4253 CustomHandler.InitFunction(self, func)
4254 func.can_auto_generate = False
4256 def NeedsDataTransferFunction(self, func):
4257 """Overriden from TypeHandler."""
4258 # If specified explicitly, force the data transfer method.
4259 if func.GetInfo('data_transfer_methods'):
4260 return True
4261 return False
4263 def WriteStruct(self, func, file):
4264 """Overrriden from TypeHandler."""
4265 pass
4267 def WriteDocs(self, func, file):
4268 """Overrriden from TypeHandler."""
4269 pass
4271 def WriteServiceUnitTest(self, func, file, *extras):
4272 """Overrriden from TypeHandler."""
4273 file.Write("// TODO(gman): %s\n\n" % func.name)
4275 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4276 """Overrriden from TypeHandler."""
4277 file.Write("// TODO(gman): %s\n\n" % func.name)
4279 def WriteBucketServiceUnitTest(self, func, file, *extras):
4280 """Overrriden from TypeHandler."""
4281 file.Write("// TODO(gman): %s\n\n" % func.name)
4283 def WriteServiceImplementation(self, func, file):
4284 """Overrriden from TypeHandler."""
4285 pass
4287 def WriteImmediateServiceImplementation(self, func, file):
4288 """Overrriden from TypeHandler."""
4289 pass
4291 def WriteBucketServiceImplementation(self, func, file):
4292 """Overrriden from TypeHandler."""
4293 pass
4295 def WriteImmediateCmdHelper(self, func, file):
4296 """Overrriden from TypeHandler."""
4297 pass
4299 def WriteCmdHelper(self, func, file):
4300 """Overrriden from TypeHandler."""
4301 pass
4303 def WriteFormatTest(self, func, file):
4304 """Overrriden from TypeHandler."""
4305 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4307 def WriteImmediateFormatTest(self, func, file):
4308 """Overrriden from TypeHandler."""
4309 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4311 def WriteBucketFormatTest(self, func, file):
4312 """Overrriden from TypeHandler."""
4313 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4317 class ManualHandler(CustomHandler):
4318 """Handler for commands who's handlers must be written by hand."""
4320 def __init__(self):
4321 CustomHandler.__init__(self)
4323 def InitFunction(self, func):
4324 """Overrriden from TypeHandler."""
4325 if (func.name == 'CompressedTexImage2DBucket'):
4326 func.cmd_args = func.cmd_args[:-1]
4327 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
4328 else:
4329 CustomHandler.InitFunction(self, func)
4331 def WriteServiceImplementation(self, func, file):
4332 """Overrriden from TypeHandler."""
4333 pass
4335 def WriteBucketServiceImplementation(self, func, file):
4336 """Overrriden from TypeHandler."""
4337 pass
4339 def WriteServiceUnitTest(self, func, file, *extras):
4340 """Overrriden from TypeHandler."""
4341 file.Write("// TODO(gman): %s\n\n" % func.name)
4343 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4344 """Overrriden from TypeHandler."""
4345 file.Write("// TODO(gman): %s\n\n" % func.name)
4347 def WriteImmediateServiceImplementation(self, func, file):
4348 """Overrriden from TypeHandler."""
4349 pass
4351 def WriteImmediateFormatTest(self, func, file):
4352 """Overrriden from TypeHandler."""
4353 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
4355 def WriteGLES2Implementation(self, func, file):
4356 """Overrriden from TypeHandler."""
4357 if func.GetInfo('impl_func'):
4358 super(ManualHandler, self).WriteGLES2Implementation(func, file)
4360 def WriteGLES2ImplementationHeader(self, func, file):
4361 """Overrriden from TypeHandler."""
4362 file.Write("%s %s(%s) override;\n" %
4363 (func.return_type, func.original_name,
4364 func.MakeTypedOriginalArgString("")))
4365 file.Write("\n")
4367 def WriteImmediateCmdGetTotalSize(self, func, file):
4368 """Overrriden from TypeHandler."""
4369 # TODO(gman): Move this data to _FUNCTION_INFO?
4370 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
4373 class DataHandler(TypeHandler):
4374 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
4375 glCompressedTexImage2D, glCompressedTexImageSub2D."""
4376 def __init__(self):
4377 TypeHandler.__init__(self)
4379 def InitFunction(self, func):
4380 """Overrriden from TypeHandler."""
4381 if func.name == 'CompressedTexSubImage2DBucket':
4382 func.cmd_args = func.cmd_args[:-1]
4383 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
4385 def WriteGetDataSizeCode(self, func, file):
4386 """Overrriden from TypeHandler."""
4387 # TODO(gman): Move this data to _FUNCTION_INFO?
4388 name = func.name
4389 if name.endswith("Immediate"):
4390 name = name[0:-9]
4391 if name == 'BufferData' or name == 'BufferSubData':
4392 file.Write(" uint32_t data_size = size;\n")
4393 elif (name == 'CompressedTexImage2D' or
4394 name == 'CompressedTexSubImage2D'):
4395 file.Write(" uint32_t data_size = imageSize;\n")
4396 elif (name == 'CompressedTexSubImage2DBucket'):
4397 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
4398 file.Write(" uint32_t data_size = bucket->size();\n")
4399 file.Write(" GLsizei imageSize = data_size;\n")
4400 elif name == 'TexImage2D' or name == 'TexSubImage2D':
4401 code = """ uint32_t data_size;
4402 if (!GLES2Util::ComputeImageDataSize(
4403 width, height, format, type, unpack_alignment_, &data_size)) {
4404 return error::kOutOfBounds;
4407 file.Write(code)
4408 else:
4409 file.Write(
4410 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
4412 def WriteImmediateCmdGetTotalSize(self, func, file):
4413 """Overrriden from TypeHandler."""
4414 pass
4416 def WriteImmediateCmdSizeTest(self, func, file):
4417 """Overrriden from TypeHandler."""
4418 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
4420 def WriteImmediateCmdInit(self, func, file):
4421 """Overrriden from TypeHandler."""
4422 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
4423 self.WriteImmediateCmdGetTotalSize(func, file)
4424 file.Write(" SetHeader(total_size);\n")
4425 args = func.GetCmdArgs()
4426 for arg in args:
4427 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4428 file.Write(" }\n")
4429 file.Write("\n")
4431 def WriteImmediateCmdSet(self, func, file):
4432 """Overrriden from TypeHandler."""
4433 copy_args = func.MakeCmdArgString("_", False)
4434 file.Write(" void* Set(void* cmd%s) {\n" %
4435 func.MakeTypedCmdArgString("_", True))
4436 self.WriteImmediateCmdGetTotalSize(func, file)
4437 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
4438 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4439 "cmd, total_size);\n")
4440 file.Write(" }\n")
4441 file.Write("\n")
4443 def WriteImmediateFormatTest(self, func, file):
4444 """Overrriden from TypeHandler."""
4445 # TODO(gman): Remove this exception.
4446 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
4447 return
4449 def WriteServiceUnitTest(self, func, file, *extras):
4450 """Overrriden from TypeHandler."""
4451 file.Write("// TODO(gman): %s\n\n" % func.name)
4453 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4454 """Overrriden from TypeHandler."""
4455 file.Write("// TODO(gman): %s\n\n" % func.name)
4457 def WriteBucketServiceImplementation(self, func, file):
4458 """Overrriden from TypeHandler."""
4459 if not func.name == 'CompressedTexSubImage2DBucket':
4460 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
4463 class BindHandler(TypeHandler):
4464 """Handler for glBind___ type functions."""
4466 def __init__(self):
4467 TypeHandler.__init__(self)
4469 def WriteServiceUnitTest(self, func, file, *extras):
4470 """Overrriden from TypeHandler."""
4472 if len(func.GetOriginalArgs()) == 1:
4473 valid_test = """
4474 TEST_P(%(test_name)s, %(name)sValidArgs) {
4475 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4476 SpecializedSetup<cmds::%(name)s, 0>(true);
4477 cmds::%(name)s cmd;
4478 cmd.Init(%(args)s);"""
4479 if func.IsUnsafe():
4480 valid_test += """
4481 decoder_->set_unsafe_es3_apis_enabled(true);
4482 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4483 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4484 decoder_->set_unsafe_es3_apis_enabled(false);
4485 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4488 else:
4489 valid_test += """
4490 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4491 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4494 if func.GetInfo("gen_func"):
4495 valid_test += """
4496 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
4497 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
4498 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
4499 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4500 SpecializedSetup<cmds::%(name)s, 0>(true);
4501 cmds::%(name)s cmd;
4502 cmd.Init(kNewClientId);
4503 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4504 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4505 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4508 self.WriteValidUnitTest(func, file, valid_test, {
4509 'resource_type': func.GetOriginalArgs()[0].resource_type,
4510 'gl_gen_func_name': func.GetInfo("gen_func"),
4511 }, *extras)
4512 else:
4513 valid_test = """
4514 TEST_P(%(test_name)s, %(name)sValidArgs) {
4515 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4516 SpecializedSetup<cmds::%(name)s, 0>(true);
4517 cmds::%(name)s cmd;
4518 cmd.Init(%(args)s);"""
4519 if func.IsUnsafe():
4520 valid_test += """
4521 decoder_->set_unsafe_es3_apis_enabled(true);
4522 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4523 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4524 decoder_->set_unsafe_es3_apis_enabled(false);
4525 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4528 else:
4529 valid_test += """
4530 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4531 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4534 if func.GetInfo("gen_func"):
4535 valid_test += """
4536 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
4537 EXPECT_CALL(*gl_,
4538 %(gl_func_name)s(%(gl_args_with_new_id)s));
4539 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
4540 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4541 SpecializedSetup<cmds::%(name)s, 0>(true);
4542 cmds::%(name)s cmd;
4543 cmd.Init(%(args_with_new_id)s);"""
4544 if func.IsUnsafe():
4545 valid_test += """
4546 decoder_->set_unsafe_es3_apis_enabled(true);
4547 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4548 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4549 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4550 decoder_->set_unsafe_es3_apis_enabled(false);
4551 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4554 else:
4555 valid_test += """
4556 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4557 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4558 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4562 gl_args_with_new_id = []
4563 args_with_new_id = []
4564 for arg in func.GetOriginalArgs():
4565 if hasattr(arg, 'resource_type'):
4566 gl_args_with_new_id.append('kNewServiceId')
4567 args_with_new_id.append('kNewClientId')
4568 else:
4569 gl_args_with_new_id.append(arg.GetValidGLArg(func))
4570 args_with_new_id.append(arg.GetValidArg(func))
4571 self.WriteValidUnitTest(func, file, valid_test, {
4572 'args_with_new_id': ", ".join(args_with_new_id),
4573 'gl_args_with_new_id': ", ".join(gl_args_with_new_id),
4574 'resource_type': func.GetResourceIdArg().resource_type,
4575 'gl_gen_func_name': func.GetInfo("gen_func"),
4576 }, *extras)
4578 invalid_test = """
4579 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4580 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4581 SpecializedSetup<cmds::%(name)s, 0>(false);
4582 cmds::%(name)s cmd;
4583 cmd.Init(%(args)s);
4584 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4587 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
4589 def WriteGLES2Implementation(self, func, file):
4590 """Writes the GLES2 Implemention."""
4592 impl_func = func.GetInfo('impl_func')
4593 impl_decl = func.GetInfo('impl_decl')
4595 if (func.can_auto_generate and
4596 (impl_func == None or impl_func == True) and
4597 (impl_decl == None or impl_decl == True)):
4599 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4600 (func.return_type, func.original_name,
4601 func.MakeTypedOriginalArgString("")))
4602 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4603 func.WriteDestinationInitalizationValidation(file)
4604 self.WriteClientGLCallLog(func, file)
4605 for arg in func.GetOriginalArgs():
4606 arg.WriteClientSideValidationCode(file, func)
4608 code = """ if (Is%(type)sReservedId(%(id)s)) {
4609 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
4610 return;
4612 %(name)sHelper(%(arg_string)s);
4613 CheckGLError();
4617 name_arg = func.GetResourceIdArg()
4618 file.Write(code % {
4619 'name': func.name,
4620 'arg_string': func.MakeOriginalArgString(""),
4621 'id': name_arg.name,
4622 'type': name_arg.resource_type,
4623 'lc_type': name_arg.resource_type.lower(),
4626 def WriteGLES2ImplementationUnitTest(self, func, file):
4627 """Overrriden from TypeHandler."""
4628 client_test = func.GetInfo('client_test')
4629 if client_test == False:
4630 return
4631 code = """
4632 TEST_F(GLES2ImplementationTest, %(name)s) {
4633 struct Cmds {
4634 cmds::%(name)s cmd;
4636 Cmds expected;
4637 expected.cmd.Init(%(cmd_args)s);
4639 gl_->%(name)s(%(args)s);
4640 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
4641 if not func.IsUnsafe():
4642 code += """
4643 ClearCommands();
4644 gl_->%(name)s(%(args)s);
4645 EXPECT_TRUE(NoCommandsWritten());"""
4646 code += """
4649 cmd_arg_strings = [
4650 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4652 gl_arg_strings = [
4653 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4656 file.Write(code % {
4657 'name': func.name,
4658 'args': ", ".join(gl_arg_strings),
4659 'cmd_args': ", ".join(cmd_arg_strings),
4663 class GENnHandler(TypeHandler):
4664 """Handler for glGen___ type functions."""
4666 def __init__(self):
4667 TypeHandler.__init__(self)
4669 def InitFunction(self, func):
4670 """Overrriden from TypeHandler."""
4671 pass
4673 def WriteGetDataSizeCode(self, func, file):
4674 """Overrriden from TypeHandler."""
4675 code = """ uint32_t data_size;
4676 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
4677 return error::kOutOfBounds;
4680 file.Write(code)
4682 def WriteHandlerImplementation (self, func, file):
4683 """Overrriden from TypeHandler."""
4684 file.Write(" if (!%sHelper(n, %s)) {\n"
4685 " return error::kInvalidArguments;\n"
4686 " }\n" %
4687 (func.name, func.GetLastOriginalArg().name))
4689 def WriteImmediateHandlerImplementation(self, func, file):
4690 """Overrriden from TypeHandler."""
4691 if func.IsUnsafe():
4692 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
4693 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
4694 return error::kInvalidArguments;
4697 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
4698 gl%(func_name)s(n, service_ids.get());
4699 for (GLsizei ii = 0; ii < n; ++ii) {
4700 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
4702 """ % { 'func_name': func.original_name,
4703 'last_arg_name': func.GetLastOriginalArg().name,
4704 'resource_name': func.GetInfo('resource_type') })
4705 else:
4706 file.Write(" if (!%sHelper(n, %s)) {\n"
4707 " return error::kInvalidArguments;\n"
4708 " }\n" %
4709 (func.original_name, func.GetLastOriginalArg().name))
4711 def WriteGLES2Implementation(self, func, file):
4712 """Overrriden from TypeHandler."""
4713 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
4714 for (GLsizei i = 0; i < n; ++i) {
4715 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
4717 });""" % func.GetOriginalArgs()[1].name)
4718 args = {
4719 'log_code': log_code,
4720 'return_type': func.return_type,
4721 'name': func.original_name,
4722 'typed_args': func.MakeTypedOriginalArgString(""),
4723 'args': func.MakeOriginalArgString(""),
4724 'resource_types': func.GetInfo('resource_types'),
4725 'count_name': func.GetOriginalArgs()[0].name,
4727 file.Write(
4728 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
4729 args)
4730 func.WriteDestinationInitalizationValidation(file)
4731 self.WriteClientGLCallLog(func, file)
4732 for arg in func.GetOriginalArgs():
4733 arg.WriteClientSideValidationCode(file, func)
4734 not_shared = func.GetInfo('not_shared')
4735 if not_shared:
4736 alloc_code = (
4738 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
4739 for (GLsizei ii = 0; ii < n; ++ii)
4740 %s[ii] = id_allocator->AllocateID();""" %
4741 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
4742 else:
4743 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
4744 MakeIds(this, 0, %(args)s);""" % args)
4745 args['alloc_code'] = alloc_code
4747 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
4748 %(alloc_code)s
4749 %(name)sHelper(%(args)s);
4750 helper_->%(name)sImmediate(%(args)s);
4751 if (share_group_->bind_generates_resource())
4752 helper_->CommandBufferHelper::Flush();
4753 %(log_code)s
4754 CheckGLError();
4758 file.Write(code % args)
4760 def WriteGLES2ImplementationUnitTest(self, func, file):
4761 """Overrriden from TypeHandler."""
4762 code = """
4763 TEST_F(GLES2ImplementationTest, %(name)s) {
4764 GLuint ids[2] = { 0, };
4765 struct Cmds {
4766 cmds::%(name)sImmediate gen;
4767 GLuint data[2];
4769 Cmds expected;
4770 expected.gen.Init(arraysize(ids), &ids[0]);
4771 expected.data[0] = k%(types)sStartId;
4772 expected.data[1] = k%(types)sStartId + 1;
4773 gl_->%(name)s(arraysize(ids), &ids[0]);
4774 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4775 EXPECT_EQ(k%(types)sStartId, ids[0]);
4776 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
4779 file.Write(code % {
4780 'name': func.name,
4781 'types': func.GetInfo('resource_types'),
4784 def WriteServiceUnitTest(self, func, file, *extras):
4785 """Overrriden from TypeHandler."""
4786 valid_test = """
4787 TEST_P(%(test_name)s, %(name)sValidArgs) {
4788 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4789 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4790 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
4791 SpecializedSetup<cmds::%(name)s, 0>(true);
4792 cmds::%(name)s cmd;
4793 cmd.Init(%(args)s);
4794 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4795 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
4796 if func.IsUnsafe():
4797 valid_test += """
4798 GLuint service_id;
4799 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
4800 EXPECT_EQ(kNewServiceId, service_id)
4803 else:
4804 valid_test += """
4805 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
4808 self.WriteValidUnitTest(func, file, valid_test, {
4809 'resource_name': func.GetInfo('resource_type'),
4810 }, *extras)
4811 invalid_test = """
4812 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4813 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4814 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
4815 SpecializedSetup<cmds::%(name)s, 0>(false);
4816 cmds::%(name)s cmd;
4817 cmd.Init(%(args)s);
4818 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
4821 self.WriteValidUnitTest(func, file, invalid_test, {
4822 'resource_name': func.GetInfo('resource_type').lower(),
4823 }, *extras)
4825 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4826 """Overrriden from TypeHandler."""
4827 valid_test = """
4828 TEST_P(%(test_name)s, %(name)sValidArgs) {
4829 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
4830 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4831 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4832 GLuint temp = kNewClientId;
4833 SpecializedSetup<cmds::%(name)s, 0>(true);"""
4834 if func.IsUnsafe():
4835 valid_test += """
4836 decoder_->set_unsafe_es3_apis_enabled(true);"""
4837 valid_test += """
4838 cmd->Init(1, &temp);
4839 EXPECT_EQ(error::kNoError,
4840 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4841 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
4842 if func.IsUnsafe():
4843 valid_test += """
4844 GLuint service_id;
4845 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
4846 EXPECT_EQ(kNewServiceId, service_id);
4847 decoder_->set_unsafe_es3_apis_enabled(false);
4848 EXPECT_EQ(error::kUnknownCommand,
4849 ExecuteImmediateCmd(*cmd, sizeof(temp)));
4852 else:
4853 valid_test += """
4854 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
4857 self.WriteValidUnitTest(func, file, valid_test, {
4858 'resource_name': func.GetInfo('resource_type'),
4859 }, *extras)
4860 invalid_test = """
4861 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
4862 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
4863 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
4864 SpecializedSetup<cmds::%(name)s, 0>(false);
4865 cmd->Init(1, &client_%(resource_name)s_id_);"""
4866 if func.IsUnsafe():
4867 invalid_test += """
4868 decoder_->set_unsafe_es3_apis_enabled(true);
4869 EXPECT_EQ(error::kInvalidArguments,
4870 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4871 decoder_->set_unsafe_es3_apis_enabled(false);
4874 else:
4875 invalid_test += """
4876 EXPECT_EQ(error::kInvalidArguments,
4877 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
4880 self.WriteValidUnitTest(func, file, invalid_test, {
4881 'resource_name': func.GetInfo('resource_type').lower(),
4882 }, *extras)
4884 def WriteImmediateCmdComputeSize(self, func, file):
4885 """Overrriden from TypeHandler."""
4886 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
4887 file.Write(
4888 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
4889 file.Write(" }\n")
4890 file.Write("\n")
4891 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
4892 file.Write(" return static_cast<uint32_t>(\n")
4893 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
4894 file.Write(" }\n")
4895 file.Write("\n")
4897 def WriteImmediateCmdSetHeader(self, func, file):
4898 """Overrriden from TypeHandler."""
4899 file.Write(" void SetHeader(GLsizei n) {\n")
4900 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
4901 file.Write(" }\n")
4902 file.Write("\n")
4904 def WriteImmediateCmdInit(self, func, file):
4905 """Overrriden from TypeHandler."""
4906 last_arg = func.GetLastOriginalArg()
4907 file.Write(" void Init(%s, %s _%s) {\n" %
4908 (func.MakeTypedCmdArgString("_"),
4909 last_arg.type, last_arg.name))
4910 file.Write(" SetHeader(_n);\n")
4911 args = func.GetCmdArgs()
4912 for arg in args:
4913 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4914 file.Write(" memcpy(ImmediateDataAddress(this),\n")
4915 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
4916 file.Write(" }\n")
4917 file.Write("\n")
4919 def WriteImmediateCmdSet(self, func, file):
4920 """Overrriden from TypeHandler."""
4921 last_arg = func.GetLastOriginalArg()
4922 copy_args = func.MakeCmdArgString("_", False)
4923 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
4924 (func.MakeTypedCmdArgString("_", True),
4925 last_arg.type, last_arg.name))
4926 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
4927 (copy_args, last_arg.name))
4928 file.Write(" const uint32_t size = ComputeSize(_n);\n")
4929 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4930 "cmd, size);\n")
4931 file.Write(" }\n")
4932 file.Write("\n")
4934 def WriteImmediateCmdHelper(self, func, file):
4935 """Overrriden from TypeHandler."""
4936 code = """ void %(name)s(%(typed_args)s) {
4937 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
4938 gles2::cmds::%(name)s* c =
4939 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
4940 if (c) {
4941 c->Init(%(args)s);
4946 file.Write(code % {
4947 "name": func.name,
4948 "typed_args": func.MakeTypedOriginalArgString(""),
4949 "args": func.MakeOriginalArgString(""),
4952 def WriteImmediateFormatTest(self, func, file):
4953 """Overrriden from TypeHandler."""
4954 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4955 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
4956 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4957 (func.name, func.name))
4958 file.Write(" void* next_cmd = cmd.Set(\n")
4959 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
4960 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4961 func.name)
4962 file.Write(" cmd.header.command);\n")
4963 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
4964 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
4965 file.Write(" cmd.header.size * 4u);\n")
4966 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
4967 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
4968 file.Write(" next_cmd, sizeof(cmd) +\n")
4969 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
4970 file.Write(" // TODO(gman): Check that ids were inserted;\n")
4971 file.Write("}\n")
4972 file.Write("\n")
4975 class CreateHandler(TypeHandler):
4976 """Handler for glCreate___ type functions."""
4978 def __init__(self):
4979 TypeHandler.__init__(self)
4981 def InitFunction(self, func):
4982 """Overrriden from TypeHandler."""
4983 func.AddCmdArg(Argument("client_id", 'uint32_t'))
4985 def __GetResourceType(self, func):
4986 if func.return_type == "GLsync":
4987 return "Sync"
4988 else:
4989 return func.name[6:] # Create*
4991 def WriteServiceUnitTest(self, func, file, *extras):
4992 """Overrriden from TypeHandler."""
4993 valid_test = """
4994 TEST_P(%(test_name)s, %(name)sValidArgs) {
4995 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
4996 .WillOnce(Return(%(const_service_id)s));
4997 SpecializedSetup<cmds::%(name)s, 0>(true);
4998 cmds::%(name)s cmd;
4999 cmd.Init(%(args)s%(comma)skNewClientId);"""
5000 if func.IsUnsafe():
5001 valid_test += """
5002 decoder_->set_unsafe_es3_apis_enabled(true);"""
5003 valid_test += """
5004 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5005 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5006 if func.IsUnsafe():
5007 valid_test += """
5008 %(return_type)s service_id = 0;
5009 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
5010 EXPECT_EQ(%(const_service_id)s, service_id);
5011 decoder_->set_unsafe_es3_apis_enabled(false);
5012 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5015 else:
5016 valid_test += """
5017 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
5020 comma = ""
5021 cmd_arg_count = 0
5022 for arg in func.GetOriginalArgs():
5023 if not arg.IsConstant():
5024 cmd_arg_count += 1
5025 if cmd_arg_count:
5026 comma = ", "
5027 if func.return_type == 'GLsync':
5028 id_type_cast = ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
5029 "<GLsync>(kNewServiceId);\n ")
5030 const_service_id = "kNewServiceIdGLuint"
5031 else:
5032 id_type_cast = ""
5033 const_service_id = "kNewServiceId"
5034 self.WriteValidUnitTest(func, file, valid_test, {
5035 'comma': comma,
5036 'resource_type': self.__GetResourceType(func),
5037 'return_type': func.return_type,
5038 'id_type_cast': id_type_cast,
5039 'const_service_id': const_service_id,
5040 }, *extras)
5041 invalid_test = """
5042 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5043 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5044 SpecializedSetup<cmds::%(name)s, 0>(false);
5045 cmds::%(name)s cmd;
5046 cmd.Init(%(args)s%(comma)skNewClientId);
5047 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
5050 self.WriteInvalidUnitTest(func, file, invalid_test, {
5051 'comma': comma,
5052 }, *extras)
5054 def WriteHandlerImplementation (self, func, file):
5055 """Overrriden from TypeHandler."""
5056 if func.IsUnsafe():
5057 code = """ uint32_t client_id = c.client_id;
5058 %(return_type)s service_id = 0;
5059 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
5060 return error::kInvalidArguments;
5062 service_id = %(gl_func_name)s(%(gl_args)s);
5063 if (service_id) {
5064 group_->Add%(resource_name)sId(client_id, service_id);
5067 else:
5068 code = """ uint32_t client_id = c.client_id;
5069 if (Get%(resource_name)s(client_id)) {
5070 return error::kInvalidArguments;
5072 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
5073 if (service_id) {
5074 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
5077 file.Write(code % {
5078 'resource_name': self.__GetResourceType(func),
5079 'return_type': func.return_type,
5080 'gl_func_name': func.GetGLFunctionName(),
5081 'gl_args': func.MakeOriginalArgString(""),
5082 'gl_args_with_comma': func.MakeOriginalArgString("", True) })
5084 def WriteGLES2Implementation(self, func, file):
5085 """Overrriden from TypeHandler."""
5086 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5087 (func.return_type, func.original_name,
5088 func.MakeTypedOriginalArgString("")))
5089 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5090 func.WriteDestinationInitalizationValidation(file)
5091 self.WriteClientGLCallLog(func, file)
5092 for arg in func.GetOriginalArgs():
5093 arg.WriteClientSideValidationCode(file, func)
5094 file.Write(" GLuint client_id;\n")
5095 if func.return_type == "GLsync":
5096 file.Write(
5097 " GetIdHandler(id_namespaces::kSyncs)->\n")
5098 else:
5099 file.Write(
5100 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
5101 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
5102 file.Write(" helper_->%s(%s);\n" %
5103 (func.name, func.MakeCmdArgString("")))
5104 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
5105 file.Write(" CheckGLError();\n")
5106 if func.return_type == "GLsync":
5107 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
5108 else:
5109 file.Write(" return client_id;\n")
5110 file.Write("}\n")
5111 file.Write("\n")
5114 class DeleteHandler(TypeHandler):
5115 """Handler for glDelete___ single resource type functions."""
5117 def __init__(self):
5118 TypeHandler.__init__(self)
5120 def WriteServiceImplementation(self, func, file):
5121 """Overrriden from TypeHandler."""
5122 if func.IsUnsafe():
5123 TypeHandler.WriteServiceImplementation(self, func, file)
5124 # HandleDeleteShader and HandleDeleteProgram are manually written.
5125 pass
5127 def WriteGLES2Implementation(self, func, file):
5128 """Overrriden from TypeHandler."""
5129 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5130 (func.return_type, func.original_name,
5131 func.MakeTypedOriginalArgString("")))
5132 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5133 func.WriteDestinationInitalizationValidation(file)
5134 self.WriteClientGLCallLog(func, file)
5135 for arg in func.GetOriginalArgs():
5136 arg.WriteClientSideValidationCode(file, func)
5137 file.Write(
5138 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
5139 file.Write(" %sHelper(%s);\n" %
5140 (func.original_name, func.GetOriginalArgs()[-1].name))
5141 file.Write(" CheckGLError();\n")
5142 file.Write("}\n")
5143 file.Write("\n")
5145 def WriteHandlerImplementation (self, func, file):
5146 """Overrriden from TypeHandler."""
5147 assert len(func.GetOriginalArgs()) == 1
5148 arg = func.GetOriginalArgs()[0]
5149 if func.IsUnsafe():
5150 file.Write(""" %(arg_type)s service_id = 0;
5151 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
5152 glDelete%(resource_type)s(service_id);
5153 group_->Remove%(resource_type)sId(%(arg_name)s);
5154 } else {
5155 LOCAL_SET_GL_ERROR(
5156 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
5158 """ % { 'resource_type': func.GetInfo('resource_type'),
5159 'arg_name': arg.name,
5160 'arg_type': arg.type,
5161 'func_name': func.original_name })
5162 else:
5163 file.Write(" %sHelper(%s);\n" % (func.original_name, arg.name))
5165 class DELnHandler(TypeHandler):
5166 """Handler for glDelete___ type functions."""
5168 def __init__(self):
5169 TypeHandler.__init__(self)
5171 def WriteGetDataSizeCode(self, func, file):
5172 """Overrriden from TypeHandler."""
5173 code = """ uint32_t data_size;
5174 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5175 return error::kOutOfBounds;
5178 file.Write(code)
5180 def WriteGLES2ImplementationUnitTest(self, func, file):
5181 """Overrriden from TypeHandler."""
5182 code = """
5183 TEST_F(GLES2ImplementationTest, %(name)s) {
5184 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
5185 struct Cmds {
5186 cmds::%(name)sImmediate del;
5187 GLuint data[2];
5189 Cmds expected;
5190 expected.del.Init(arraysize(ids), &ids[0]);
5191 expected.data[0] = k%(types)sStartId;
5192 expected.data[1] = k%(types)sStartId + 1;
5193 gl_->%(name)s(arraysize(ids), &ids[0]);
5194 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5197 file.Write(code % {
5198 'name': func.name,
5199 'types': func.GetInfo('resource_types'),
5202 def WriteServiceUnitTest(self, func, file, *extras):
5203 """Overrriden from TypeHandler."""
5204 valid_test = """
5205 TEST_P(%(test_name)s, %(name)sValidArgs) {
5206 EXPECT_CALL(
5207 *gl_,
5208 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5209 .Times(1);
5210 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5211 SpecializedSetup<cmds::%(name)s, 0>(true);
5212 cmds::%(name)s cmd;
5213 cmd.Init(%(args)s);
5214 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5215 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5216 EXPECT_TRUE(
5217 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5220 self.WriteValidUnitTest(func, file, valid_test, {
5221 'resource_name': func.GetInfo('resource_type').lower(),
5222 'upper_resource_name': func.GetInfo('resource_type'),
5223 }, *extras)
5224 invalid_test = """
5225 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5226 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
5227 SpecializedSetup<cmds::%(name)s, 0>(false);
5228 cmds::%(name)s cmd;
5229 cmd.Init(%(args)s);
5230 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5233 self.WriteValidUnitTest(func, file, invalid_test, *extras)
5235 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5236 """Overrriden from TypeHandler."""
5237 valid_test = """
5238 TEST_P(%(test_name)s, %(name)sValidArgs) {
5239 EXPECT_CALL(
5240 *gl_,
5241 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5242 .Times(1);
5243 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5244 SpecializedSetup<cmds::%(name)s, 0>(true);
5245 cmd.Init(1, &client_%(resource_name)s_id_);"""
5246 if func.IsUnsafe():
5247 valid_test += """
5248 decoder_->set_unsafe_es3_apis_enabled(true);"""
5249 valid_test += """
5250 EXPECT_EQ(error::kNoError,
5251 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5252 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5253 if func.IsUnsafe():
5254 valid_test += """
5255 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
5256 client_%(resource_name)s_id_, NULL));
5257 decoder_->set_unsafe_es3_apis_enabled(false);
5258 EXPECT_EQ(error::kUnknownCommand,
5259 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5262 else:
5263 valid_test += """
5264 EXPECT_TRUE(
5265 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5268 self.WriteValidUnitTest(func, file, valid_test, {
5269 'resource_name': func.GetInfo('resource_type').lower(),
5270 'upper_resource_name': func.GetInfo('resource_type'),
5271 }, *extras)
5272 invalid_test = """
5273 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5274 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5275 SpecializedSetup<cmds::%(name)s, 0>(false);
5276 GLuint temp = kInvalidClientId;
5277 cmd.Init(1, &temp);"""
5278 if func.IsUnsafe():
5279 invalid_test += """
5280 decoder_->set_unsafe_es3_apis_enabled(true);
5281 EXPECT_EQ(error::kNoError,
5282 ExecuteImmediateCmd(cmd, sizeof(temp)));
5283 decoder_->set_unsafe_es3_apis_enabled(false);
5284 EXPECT_EQ(error::kUnknownCommand,
5285 ExecuteImmediateCmd(cmd, sizeof(temp)));
5288 else:
5289 invalid_test += """
5290 EXPECT_EQ(error::kNoError,
5291 ExecuteImmediateCmd(cmd, sizeof(temp)));
5294 self.WriteValidUnitTest(func, file, invalid_test, *extras)
5296 def WriteHandlerImplementation (self, func, file):
5297 """Overrriden from TypeHandler."""
5298 file.Write(" %sHelper(n, %s);\n" %
5299 (func.name, func.GetLastOriginalArg().name))
5301 def WriteImmediateHandlerImplementation (self, func, file):
5302 """Overrriden from TypeHandler."""
5303 if func.IsUnsafe():
5304 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5305 GLuint service_id = 0;
5306 if (group_->Get%(resource_type)sServiceId(
5307 %(last_arg_name)s[ii], &service_id)) {
5308 glDelete%(resource_type)ss(1, &service_id);
5309 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
5312 """ % { 'resource_type': func.GetInfo('resource_type'),
5313 'last_arg_name': func.GetLastOriginalArg().name })
5314 else:
5315 file.Write(" %sHelper(n, %s);\n" %
5316 (func.original_name, func.GetLastOriginalArg().name))
5318 def WriteGLES2Implementation(self, func, file):
5319 """Overrriden from TypeHandler."""
5320 impl_decl = func.GetInfo('impl_decl')
5321 if impl_decl == None or impl_decl == True:
5322 args = {
5323 'return_type': func.return_type,
5324 'name': func.original_name,
5325 'typed_args': func.MakeTypedOriginalArgString(""),
5326 'args': func.MakeOriginalArgString(""),
5327 'resource_type': func.GetInfo('resource_type').lower(),
5328 'count_name': func.GetOriginalArgs()[0].name,
5330 file.Write(
5331 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5332 args)
5333 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5334 func.WriteDestinationInitalizationValidation(file)
5335 self.WriteClientGLCallLog(func, file)
5336 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5337 for (GLsizei i = 0; i < n; ++i) {
5338 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5341 """ % func.GetOriginalArgs()[1].name)
5342 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
5343 for (GLsizei i = 0; i < n; ++i) {
5344 DCHECK(%s[i] != 0);
5347 """ % func.GetOriginalArgs()[1].name)
5348 for arg in func.GetOriginalArgs():
5349 arg.WriteClientSideValidationCode(file, func)
5350 code = """ %(name)sHelper(%(args)s);
5351 CheckGLError();
5355 file.Write(code % args)
5357 def WriteImmediateCmdComputeSize(self, func, file):
5358 """Overrriden from TypeHandler."""
5359 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5360 file.Write(
5361 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5362 file.Write(" }\n")
5363 file.Write("\n")
5364 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5365 file.Write(" return static_cast<uint32_t>(\n")
5366 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5367 file.Write(" }\n")
5368 file.Write("\n")
5370 def WriteImmediateCmdSetHeader(self, func, file):
5371 """Overrriden from TypeHandler."""
5372 file.Write(" void SetHeader(GLsizei n) {\n")
5373 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5374 file.Write(" }\n")
5375 file.Write("\n")
5377 def WriteImmediateCmdInit(self, func, file):
5378 """Overrriden from TypeHandler."""
5379 last_arg = func.GetLastOriginalArg()
5380 file.Write(" void Init(%s, %s _%s) {\n" %
5381 (func.MakeTypedCmdArgString("_"),
5382 last_arg.type, last_arg.name))
5383 file.Write(" SetHeader(_n);\n")
5384 args = func.GetCmdArgs()
5385 for arg in args:
5386 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5387 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5388 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5389 file.Write(" }\n")
5390 file.Write("\n")
5392 def WriteImmediateCmdSet(self, func, file):
5393 """Overrriden from TypeHandler."""
5394 last_arg = func.GetLastOriginalArg()
5395 copy_args = func.MakeCmdArgString("_", False)
5396 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5397 (func.MakeTypedCmdArgString("_", True),
5398 last_arg.type, last_arg.name))
5399 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5400 (copy_args, last_arg.name))
5401 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5402 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5403 "cmd, size);\n")
5404 file.Write(" }\n")
5405 file.Write("\n")
5407 def WriteImmediateCmdHelper(self, func, file):
5408 """Overrriden from TypeHandler."""
5409 code = """ void %(name)s(%(typed_args)s) {
5410 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5411 gles2::cmds::%(name)s* c =
5412 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5413 if (c) {
5414 c->Init(%(args)s);
5419 file.Write(code % {
5420 "name": func.name,
5421 "typed_args": func.MakeTypedOriginalArgString(""),
5422 "args": func.MakeOriginalArgString(""),
5425 def WriteImmediateFormatTest(self, func, file):
5426 """Overrriden from TypeHandler."""
5427 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5428 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5429 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5430 (func.name, func.name))
5431 file.Write(" void* next_cmd = cmd.Set(\n")
5432 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5433 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5434 func.name)
5435 file.Write(" cmd.header.command);\n")
5436 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5437 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5438 file.Write(" cmd.header.size * 4u);\n")
5439 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5440 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5441 file.Write(" next_cmd, sizeof(cmd) +\n")
5442 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5443 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5444 file.Write("}\n")
5445 file.Write("\n")
5448 class GETnHandler(TypeHandler):
5449 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
5451 def __init__(self):
5452 TypeHandler.__init__(self)
5454 def NeedsDataTransferFunction(self, func):
5455 """Overriden from TypeHandler."""
5456 return False
5458 def WriteServiceImplementation(self, func, file):
5459 """Overrriden from TypeHandler."""
5460 self.WriteServiceHandlerFunctionHeader(func, file)
5461 last_arg = func.GetLastOriginalArg()
5463 all_but_last_args = func.GetOriginalArgs()[:-1]
5464 for arg in all_but_last_args:
5465 arg.WriteGetCode(file)
5467 code = """ typedef cmds::%(func_name)s::Result Result;
5468 GLsizei num_values = 0;
5469 GetNumValuesReturnedForGLGet(pname, &num_values);
5470 Result* result = GetSharedMemoryAs<Result*>(
5471 c.params_shm_id, c.params_shm_offset, Result::ComputeSize(num_values));
5472 %(last_arg_type)s params = result ? result->GetData() : NULL;
5474 file.Write(code % {
5475 'last_arg_type': last_arg.type,
5476 'func_name': func.name,
5478 func.WriteHandlerValidation(file)
5479 code = """ // Check that the client initialized the result.
5480 if (result->size != 0) {
5481 return error::kInvalidArguments;
5484 shadowed = func.GetInfo('shadowed')
5485 if not shadowed:
5486 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
5487 file.Write(code)
5488 func.WriteHandlerImplementation(file)
5489 if shadowed:
5490 code = """ result->SetNumResults(num_values);
5491 return error::kNoError;
5494 else:
5495 code = """ GLenum error = glGetError();
5496 if (error == GL_NO_ERROR) {
5497 result->SetNumResults(num_values);
5498 } else {
5499 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
5501 return error::kNoError;
5505 file.Write(code % {'func_name': func.name})
5507 def WriteGLES2Implementation(self, func, file):
5508 """Overrriden from TypeHandler."""
5509 impl_decl = func.GetInfo('impl_decl')
5510 if impl_decl == None or impl_decl == True:
5511 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5512 (func.return_type, func.original_name,
5513 func.MakeTypedOriginalArgString("")))
5514 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5515 func.WriteDestinationInitalizationValidation(file)
5516 self.WriteClientGLCallLog(func, file)
5517 for arg in func.GetOriginalArgs():
5518 arg.WriteClientSideValidationCode(file, func)
5519 all_but_last_args = func.GetOriginalArgs()[:-1]
5520 arg_string = (
5521 ", ".join(["%s" % arg.name for arg in all_but_last_args]))
5522 all_arg_string = (
5523 ", ".join([
5524 "%s" % arg.name
5525 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
5526 self.WriteTraceEvent(func, file)
5527 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
5528 return;
5530 typedef cmds::%(func_name)s::Result Result;
5531 Result* result = GetResultAs<Result*>();
5532 if (!result) {
5533 return;
5535 result->SetNumResults(0);
5536 helper_->%(func_name)s(%(arg_string)s,
5537 GetResultShmId(), GetResultShmOffset());
5538 WaitForCmd();
5539 result->CopyResult(params);
5540 GPU_CLIENT_LOG_CODE_BLOCK({
5541 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
5542 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
5545 CheckGLError();
5548 file.Write(code % {
5549 'func_name': func.name,
5550 'arg_string': arg_string,
5551 'all_arg_string': all_arg_string,
5554 def WriteGLES2ImplementationUnitTest(self, func, file):
5555 """Writes the GLES2 Implemention unit test."""
5556 code = """
5557 TEST_F(GLES2ImplementationTest, %(name)s) {
5558 struct Cmds {
5559 cmds::%(name)s cmd;
5561 typedef cmds::%(name)s::Result Result;
5562 Result::Type result = 0;
5563 Cmds expected;
5564 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
5565 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
5566 EXPECT_CALL(*command_buffer(), OnFlush())
5567 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
5568 .RetiresOnSaturation();
5569 gl_->%(name)s(%(args)s, &result);
5570 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5571 EXPECT_EQ(static_cast<Result::Type>(1), result);
5574 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
5575 if not first_cmd_arg:
5576 return
5578 first_gl_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideArg(func)
5579 cmd_arg_strings = [first_cmd_arg]
5580 for arg in func.GetCmdArgs()[1:-2]:
5581 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
5582 gl_arg_strings = [first_gl_arg]
5583 for arg in func.GetOriginalArgs()[1:-1]:
5584 gl_arg_strings.append(arg.GetValidClientSideArg(func))
5586 file.Write(code % {
5587 'name': func.name,
5588 'args': ", ".join(gl_arg_strings),
5589 'cmd_args': ", ".join(cmd_arg_strings),
5592 def WriteServiceUnitTest(self, func, file, *extras):
5593 """Overrriden from TypeHandler."""
5594 valid_test = """
5595 TEST_P(%(test_name)s, %(name)sValidArgs) {
5596 EXPECT_CALL(*gl_, GetError())
5597 .WillOnce(Return(GL_NO_ERROR))
5598 .WillOnce(Return(GL_NO_ERROR))
5599 .RetiresOnSaturation();
5600 SpecializedSetup<cmds::%(name)s, 0>(true);
5601 typedef cmds::%(name)s::Result Result;
5602 Result* result = static_cast<Result*>(shared_memory_address_);
5603 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
5604 result->size = 0;
5605 cmds::%(name)s cmd;
5606 cmd.Init(%(args)s);"""
5607 if func.IsUnsafe():
5608 valid_test += """
5609 decoder_->set_unsafe_es3_apis_enabled(true);"""
5610 valid_test += """
5611 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5612 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
5613 %(valid_pname)s),
5614 result->GetNumResults());
5615 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5616 if func.IsUnsafe():
5617 valid_test += """
5618 decoder_->set_unsafe_es3_apis_enabled(false);
5619 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
5620 valid_test += """
5623 gl_arg_strings = []
5624 valid_pname = ''
5625 for arg in func.GetOriginalArgs()[:-1]:
5626 arg_value = arg.GetValidGLArg(func)
5627 gl_arg_strings.append(arg_value)
5628 if arg.name == 'pname':
5629 valid_pname = arg_value
5630 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
5631 gl_arg_strings.append("_")
5632 else:
5633 gl_arg_strings.append("result->GetData()")
5635 self.WriteValidUnitTest(func, file, valid_test, {
5636 'local_gl_args': ", ".join(gl_arg_strings),
5637 'valid_pname': valid_pname,
5638 }, *extras)
5640 if not func.IsUnsafe():
5641 invalid_test = """
5642 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5643 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5644 SpecializedSetup<cmds::%(name)s, 0>(false);
5645 cmds::%(name)s::Result* result =
5646 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
5647 result->size = 0;
5648 cmds::%(name)s cmd;
5649 cmd.Init(%(args)s);
5650 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
5651 EXPECT_EQ(0u, result->size);%(gl_error_test)s
5654 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
5656 class ArrayArgTypeHandler(TypeHandler):
5657 """Base class for type handlers that handle args that are arrays"""
5659 def __init__(self):
5660 TypeHandler.__init__(self)
5662 def GetArrayType(self, func):
5663 """Returns the type of the element in the element array being PUT to."""
5664 for arg in func.GetOriginalArgs():
5665 if arg.IsPointer():
5666 element_type = arg.GetPointedType()
5667 return element_type
5669 # Special case: array type handler is used for a function that is forwarded
5670 # to the actual array type implementation
5671 element_type = func.GetOriginalArgs()[-1].type
5672 assert all(arg.type == element_type \
5673 for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
5674 return element_type
5676 def GetArrayCount(self, func):
5677 """Returns the count of the elements in the array being PUT to."""
5678 return func.GetInfo('count')
5680 class PUTHandler(ArrayArgTypeHandler):
5681 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
5683 def __init__(self):
5684 ArrayArgTypeHandler.__init__(self)
5686 def WriteServiceUnitTest(self, func, file, *extras):
5687 """Writes the service unit test for a command."""
5688 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
5689 if func.GetInfo("first_element_only"):
5690 gl_arg_strings = [
5691 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
5693 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
5694 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
5695 ", ".join(gl_arg_strings))
5696 valid_test = """
5697 TEST_P(%(test_name)s, %(name)sValidArgs) {
5698 SpecializedSetup<cmds::%(name)s, 0>(true);
5699 cmds::%(name)s cmd;
5700 cmd.Init(%(args)s);
5701 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
5702 %(expected_call)s
5703 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5704 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5707 extra = {
5708 'data_type': self.GetArrayType(func),
5709 'data_value': func.GetInfo('data_value') or '0',
5710 'expected_call': expected_call,
5712 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
5714 invalid_test = """
5715 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5716 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5717 SpecializedSetup<cmds::%(name)s, 0>(false);
5718 cmds::%(name)s cmd;
5719 cmd.Init(%(args)s);
5720 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
5721 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5724 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
5726 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5727 """Writes the service unit test for a command."""
5728 valid_test = """
5729 TEST_P(%(test_name)s, %(name)sValidArgs) {
5730 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5731 SpecializedSetup<cmds::%(name)s, 0>(true);
5732 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
5733 cmd.Init(%(gl_args)s, &temp[0]);
5734 EXPECT_CALL(
5735 *gl_,
5736 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
5737 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
5738 if func.IsUnsafe():
5739 valid_test += """
5740 decoder_->set_unsafe_es3_apis_enabled(true);"""
5741 valid_test += """
5742 EXPECT_EQ(error::kNoError,
5743 ExecuteImmediateCmd(cmd, sizeof(temp)));
5744 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5745 if func.IsUnsafe():
5746 valid_test += """
5747 decoder_->set_unsafe_es3_apis_enabled(false);
5748 EXPECT_EQ(error::kUnknownCommand,
5749 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
5750 valid_test += """
5753 gl_arg_strings = [
5754 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
5756 gl_any_strings = ["_"] * len(gl_arg_strings)
5758 extra = {
5759 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
5760 'data_type': self.GetArrayType(func),
5761 'data_count': self.GetArrayCount(func),
5762 'data_value': func.GetInfo('data_value') or '0',
5763 'gl_args': ", ".join(gl_arg_strings),
5764 'gl_any_args': ", ".join(gl_any_strings),
5766 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
5768 invalid_test = """
5769 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5770 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
5771 if func.IsUnsafe():
5772 invalid_test += """
5773 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
5775 else:
5776 invalid_test += """
5777 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
5779 invalid_test += """
5780 SpecializedSetup<cmds::%(name)s, 0>(false);
5781 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
5782 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
5783 if func.IsUnsafe():
5784 invalid_test += """
5785 decoder_->set_unsafe_es3_apis_enabled(true);
5786 EXPECT_EQ(error::%(parse_result)s,
5787 ExecuteImmediateCmd(cmd, sizeof(temp)));
5788 decoder_->set_unsafe_es3_apis_enabled(false);
5791 else:
5792 invalid_test += """
5793 EXPECT_EQ(error::%(parse_result)s,
5794 ExecuteImmediateCmd(cmd, sizeof(temp)));
5795 %(gl_error_test)s
5798 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
5800 def WriteGetDataSizeCode(self, func, file):
5801 """Overrriden from TypeHandler."""
5802 code = """ uint32_t data_size;
5803 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
5804 return error::kOutOfBounds;
5807 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
5808 if func.IsImmediate():
5809 file.Write(" if (data_size > immediate_data_size) {\n")
5810 file.Write(" return error::kOutOfBounds;\n")
5811 file.Write(" }\n")
5813 def __NeedsToCalcDataCount(self, func):
5814 use_count_func = func.GetInfo('use_count_func')
5815 return use_count_func != None and use_count_func != False
5817 def WriteGLES2Implementation(self, func, file):
5818 """Overrriden from TypeHandler."""
5819 impl_func = func.GetInfo('impl_func')
5820 if (impl_func != None and impl_func != True):
5821 return;
5822 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5823 (func.return_type, func.original_name,
5824 func.MakeTypedOriginalArgString("")))
5825 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5826 func.WriteDestinationInitalizationValidation(file)
5827 self.WriteClientGLCallLog(func, file)
5829 if self.__NeedsToCalcDataCount(func):
5830 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
5831 (func.name, func.GetOriginalArgs()[0].name))
5832 file.Write(" DCHECK_LE(count, %du);\n" % self.GetArrayCount(func))
5833 else:
5834 file.Write(" size_t count = %d;" % self.GetArrayCount(func))
5835 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
5836 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
5837 func.GetLastOriginalArg().name)
5838 for arg in func.GetOriginalArgs():
5839 arg.WriteClientSideValidationCode(file, func)
5840 file.Write(" helper_->%sImmediate(%s);\n" %
5841 (func.name, func.MakeOriginalArgString("")))
5842 file.Write(" CheckGLError();\n")
5843 file.Write("}\n")
5844 file.Write("\n")
5846 def WriteGLES2ImplementationUnitTest(self, func, file):
5847 """Writes the GLES2 Implemention unit test."""
5848 client_test = func.GetInfo('client_test')
5849 if (client_test != None and client_test != True):
5850 return;
5851 code = """
5852 TEST_F(GLES2ImplementationTest, %(name)s) {
5853 %(type)s data[%(count)d] = {0};
5854 struct Cmds {
5855 cmds::%(name)sImmediate cmd;
5856 %(type)s data[%(count)d];
5859 for (int jj = 0; jj < %(count)d; ++jj) {
5860 data[jj] = static_cast<%(type)s>(jj);
5862 Cmds expected;
5863 expected.cmd.Init(%(cmd_args)s, &data[0]);
5864 gl_->%(name)s(%(args)s, &data[0]);
5865 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5868 cmd_arg_strings = [
5869 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
5871 gl_arg_strings = [
5872 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
5875 file.Write(code % {
5876 'name': func.name,
5877 'type': self.GetArrayType(func),
5878 'count': self.GetArrayCount(func),
5879 'args': ", ".join(gl_arg_strings),
5880 'cmd_args': ", ".join(cmd_arg_strings),
5883 def WriteImmediateCmdComputeSize(self, func, file):
5884 """Overrriden from TypeHandler."""
5885 file.Write(" static uint32_t ComputeDataSize() {\n")
5886 file.Write(" return static_cast<uint32_t>(\n")
5887 file.Write(" sizeof(%s) * %d);\n" %
5888 (self.GetArrayType(func), self.GetArrayCount(func)))
5889 file.Write(" }\n")
5890 file.Write("\n")
5891 if self.__NeedsToCalcDataCount(func):
5892 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
5893 (func.GetOriginalArgs()[0].type,
5894 func.GetOriginalArgs()[0].name))
5895 file.Write(" return static_cast<uint32_t>(\n")
5896 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
5897 (self.GetArrayType(func), func.original_name,
5898 func.GetOriginalArgs()[0].name))
5899 file.Write(" }\n")
5900 file.Write("\n")
5901 file.Write(" static uint32_t ComputeSize() {\n")
5902 file.Write(" return static_cast<uint32_t>(\n")
5903 file.Write(
5904 " sizeof(ValueType) + ComputeDataSize());\n")
5905 file.Write(" }\n")
5906 file.Write("\n")
5908 def WriteImmediateCmdSetHeader(self, func, file):
5909 """Overrriden from TypeHandler."""
5910 file.Write(" void SetHeader() {\n")
5911 file.Write(
5912 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
5913 file.Write(" }\n")
5914 file.Write("\n")
5916 def WriteImmediateCmdInit(self, func, file):
5917 """Overrriden from TypeHandler."""
5918 last_arg = func.GetLastOriginalArg()
5919 file.Write(" void Init(%s, %s _%s) {\n" %
5920 (func.MakeTypedCmdArgString("_"),
5921 last_arg.type, last_arg.name))
5922 file.Write(" SetHeader();\n")
5923 args = func.GetCmdArgs()
5924 for arg in args:
5925 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5926 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5927 if self.__NeedsToCalcDataCount(func):
5928 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
5929 (last_arg.name, func.GetOriginalArgs()[0].name))
5930 file.Write("""
5931 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
5932 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
5933 ComputeEffectiveDataSize(%(arg)s);
5934 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
5935 """ % { 'arg': func.GetOriginalArgs()[0].name, })
5936 else:
5937 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
5938 file.Write(" }\n")
5939 file.Write("\n")
5941 def WriteImmediateCmdSet(self, func, file):
5942 """Overrriden from TypeHandler."""
5943 last_arg = func.GetLastOriginalArg()
5944 copy_args = func.MakeCmdArgString("_", False)
5945 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5946 (func.MakeTypedCmdArgString("_", True),
5947 last_arg.type, last_arg.name))
5948 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5949 (copy_args, last_arg.name))
5950 file.Write(" const uint32_t size = ComputeSize();\n")
5951 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5952 "cmd, size);\n")
5953 file.Write(" }\n")
5954 file.Write("\n")
5956 def WriteImmediateCmdHelper(self, func, file):
5957 """Overrriden from TypeHandler."""
5958 code = """ void %(name)s(%(typed_args)s) {
5959 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
5960 gles2::cmds::%(name)s* c =
5961 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5962 if (c) {
5963 c->Init(%(args)s);
5968 file.Write(code % {
5969 "name": func.name,
5970 "typed_args": func.MakeTypedOriginalArgString(""),
5971 "args": func.MakeOriginalArgString(""),
5974 def WriteImmediateFormatTest(self, func, file):
5975 """Overrriden from TypeHandler."""
5976 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5977 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
5978 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
5979 for v in range(0, self.GetArrayCount(func)):
5980 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
5981 (self.GetArrayType(func), v))
5982 file.Write(" };\n")
5983 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5984 (func.name, func.name))
5985 file.Write(" void* next_cmd = cmd.Set(\n")
5986 file.Write(" &cmd")
5987 args = func.GetCmdArgs()
5988 for value, arg in enumerate(args):
5989 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
5990 file.Write(",\n data);\n")
5991 args = func.GetCmdArgs()
5992 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
5993 % func.name)
5994 file.Write(" cmd.header.command);\n")
5995 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5996 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
5997 file.Write(" cmd.header.size * 4u);\n")
5998 for value, arg in enumerate(args):
5999 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6000 (arg.type, value + 11, arg.name))
6001 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6002 file.Write(" next_cmd, sizeof(cmd) +\n")
6003 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6004 file.Write(" // TODO(gman): Check that data was inserted;\n")
6005 file.Write("}\n")
6006 file.Write("\n")
6009 class PUTnHandler(ArrayArgTypeHandler):
6010 """Handler for PUTn 'glUniform__v' type functions."""
6012 def __init__(self):
6013 ArrayArgTypeHandler.__init__(self)
6015 def WriteServiceUnitTest(self, func, file, *extras):
6016 """Overridden from TypeHandler."""
6017 ArrayArgTypeHandler.WriteServiceUnitTest(self, func, file, *extras)
6019 valid_test = """
6020 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
6021 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6022 SpecializedSetup<cmds::%(name)s, 0>(true);
6023 cmds::%(name)s cmd;
6024 cmd.Init(%(args)s);
6025 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6026 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6029 gl_arg_strings = []
6030 arg_strings = []
6031 for count, arg in enumerate(func.GetOriginalArgs()):
6032 # hardcoded to match unit tests.
6033 if count == 0:
6034 # the location of the second element of the 2nd uniform.
6035 # defined in GLES2DecoderBase::SetupShaderForUniform
6036 gl_arg_strings.append("3")
6037 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
6038 elif count == 1:
6039 # the number of elements that gl will be called with.
6040 gl_arg_strings.append("3")
6041 # the number of elements requested in the command.
6042 arg_strings.append("5")
6043 else:
6044 gl_arg_strings.append(arg.GetValidGLArg(func))
6045 if not arg.IsConstant():
6046 arg_strings.append(arg.GetValidArg(func))
6047 extra = {
6048 'gl_args': ", ".join(gl_arg_strings),
6049 'args': ", ".join(arg_strings),
6051 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6053 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6054 """Overridden from TypeHandler."""
6055 valid_test = """
6056 TEST_P(%(test_name)s, %(name)sValidArgs) {
6057 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6058 EXPECT_CALL(
6059 *gl_,
6060 %(gl_func_name)s(%(gl_args)s,
6061 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
6062 SpecializedSetup<cmds::%(name)s, 0>(true);
6063 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6064 cmd.Init(%(args)s, &temp[0]);"""
6065 if func.IsUnsafe():
6066 valid_test += """
6067 decoder_->set_unsafe_es3_apis_enabled(true);"""
6068 valid_test += """
6069 EXPECT_EQ(error::kNoError,
6070 ExecuteImmediateCmd(cmd, sizeof(temp)));
6071 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6072 if func.IsUnsafe():
6073 valid_test += """
6074 decoder_->set_unsafe_es3_apis_enabled(false);
6075 EXPECT_EQ(error::kUnknownCommand,
6076 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6077 valid_test += """
6080 gl_arg_strings = []
6081 gl_any_strings = []
6082 arg_strings = []
6083 for arg in func.GetOriginalArgs()[0:-1]:
6084 gl_arg_strings.append(arg.GetValidGLArg(func))
6085 gl_any_strings.append("_")
6086 if not arg.IsConstant():
6087 arg_strings.append(arg.GetValidArg(func))
6088 extra = {
6089 'data_type': self.GetArrayType(func),
6090 'data_count': self.GetArrayCount(func),
6091 'args': ", ".join(arg_strings),
6092 'gl_args': ", ".join(gl_arg_strings),
6093 'gl_any_args': ", ".join(gl_any_strings),
6095 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6097 invalid_test = """
6098 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6099 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6100 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6101 SpecializedSetup<cmds::%(name)s, 0>(false);
6102 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6103 cmd.Init(%(all_but_last_args)s, &temp[0]);
6104 EXPECT_EQ(error::%(parse_result)s,
6105 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
6108 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6110 def WriteGetDataSizeCode(self, func, file):
6111 """Overrriden from TypeHandler."""
6112 code = """ uint32_t data_size;
6113 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
6114 return error::kOutOfBounds;
6117 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6118 if func.IsImmediate():
6119 file.Write(" if (data_size > immediate_data_size) {\n")
6120 file.Write(" return error::kOutOfBounds;\n")
6121 file.Write(" }\n")
6123 def WriteGLES2Implementation(self, func, file):
6124 """Overrriden from TypeHandler."""
6125 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6126 (func.return_type, func.original_name,
6127 func.MakeTypedOriginalArgString("")))
6128 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6129 func.WriteDestinationInitalizationValidation(file)
6130 self.WriteClientGLCallLog(func, file)
6131 last_pointer_name = func.GetLastOriginalPointerArg().name
6132 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6133 for (GLsizei i = 0; i < count; ++i) {
6134 """)
6135 values_str = ' << ", " << '.join(
6136 ["%s[%d + i * %d]" % (
6137 last_pointer_name, ndx, self.GetArrayCount(func)) for ndx in range(
6138 0, self.GetArrayCount(func))])
6139 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
6140 file.Write(" }\n });\n")
6141 for arg in func.GetOriginalArgs():
6142 arg.WriteClientSideValidationCode(file, func)
6143 file.Write(" helper_->%sImmediate(%s);\n" %
6144 (func.name, func.MakeInitString("")))
6145 file.Write(" CheckGLError();\n")
6146 file.Write("}\n")
6147 file.Write("\n")
6149 def WriteGLES2ImplementationUnitTest(self, func, file):
6150 """Writes the GLES2 Implemention unit test."""
6151 code = """
6152 TEST_F(GLES2ImplementationTest, %(name)s) {
6153 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6154 struct Cmds {
6155 cmds::%(name)sImmediate cmd;
6156 %(type)s data[%(count_param)d][%(count)d];
6159 Cmds expected;
6160 for (int ii = 0; ii < %(count_param)d; ++ii) {
6161 for (int jj = 0; jj < %(count)d; ++jj) {
6162 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6165 expected.cmd.Init(%(cmd_args)s);
6166 gl_->%(name)s(%(args)s);
6167 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6170 cmd_arg_strings = []
6171 for arg in func.GetCmdArgs():
6172 if arg.name.endswith("_shm_id"):
6173 cmd_arg_strings.append("&data[0][0]")
6174 elif arg.name.endswith("_shm_offset"):
6175 continue
6176 else:
6177 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6178 gl_arg_strings = []
6179 count_param = 0
6180 for arg in func.GetOriginalArgs():
6181 if arg.IsPointer():
6182 valid_value = "&data[0][0]"
6183 else:
6184 valid_value = arg.GetValidClientSideArg(func)
6185 gl_arg_strings.append(valid_value)
6186 if arg.name == "count":
6187 count_param = int(valid_value)
6188 file.Write(code % {
6189 'name': func.name,
6190 'type': self.GetArrayType(func),
6191 'count': self.GetArrayCount(func),
6192 'args': ", ".join(gl_arg_strings),
6193 'cmd_args': ", ".join(cmd_arg_strings),
6194 'count_param': count_param,
6197 # Test constants for invalid values, as they are not tested by the
6198 # service.
6199 constants = [
6200 arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
6202 if not constants:
6203 return
6205 code = """
6206 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
6207 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6208 for (int ii = 0; ii < %(count_param)d; ++ii) {
6209 for (int jj = 0; jj < %(count)d; ++jj) {
6210 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6213 gl_->%(name)s(%(args)s);
6214 EXPECT_TRUE(NoCommandsWritten());
6215 EXPECT_EQ(%(gl_error)s, CheckError());
6218 for invalid_arg in constants:
6219 gl_arg_strings = []
6220 invalid = invalid_arg.GetInvalidArg(func)
6221 for arg in func.GetOriginalArgs():
6222 if arg is invalid_arg:
6223 gl_arg_strings.append(invalid[0])
6224 elif arg.IsPointer():
6225 gl_arg_strings.append("&data[0][0]")
6226 else:
6227 valid_value = arg.GetValidClientSideArg(func)
6228 gl_arg_strings.append(valid_value)
6229 if arg.name == "count":
6230 count_param = int(valid_value)
6232 file.Write(code % {
6233 'name': func.name,
6234 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
6235 'type': self.GetArrayType(func),
6236 'count': self.GetArrayCount(func),
6237 'args': ", ".join(gl_arg_strings),
6238 'gl_error': invalid[2],
6239 'count_param': count_param,
6243 def WriteImmediateCmdComputeSize(self, func, file):
6244 """Overrriden from TypeHandler."""
6245 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
6246 file.Write(" return static_cast<uint32_t>(\n")
6247 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
6248 (self.GetArrayType(func), self.GetArrayCount(func)))
6249 file.Write(" }\n")
6250 file.Write("\n")
6251 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
6252 file.Write(" return static_cast<uint32_t>(\n")
6253 file.Write(
6254 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
6255 file.Write(" }\n")
6256 file.Write("\n")
6258 def WriteImmediateCmdSetHeader(self, func, file):
6259 """Overrriden from TypeHandler."""
6260 file.Write(" void SetHeader(GLsizei count) {\n")
6261 file.Write(
6262 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
6263 file.Write(" }\n")
6264 file.Write("\n")
6266 def WriteImmediateCmdInit(self, func, file):
6267 """Overrriden from TypeHandler."""
6268 file.Write(" void Init(%s) {\n" %
6269 func.MakeTypedInitString("_"))
6270 file.Write(" SetHeader(_count);\n")
6271 args = func.GetCmdArgs()
6272 for arg in args:
6273 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6274 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6275 pointer_arg = func.GetLastOriginalPointerArg()
6276 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg.name)
6277 file.Write(" }\n")
6278 file.Write("\n")
6280 def WriteImmediateCmdSet(self, func, file):
6281 """Overrriden from TypeHandler."""
6282 file.Write(" void* Set(void* cmd%s) {\n" %
6283 func.MakeTypedInitString("_", True))
6284 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
6285 func.MakeInitString("_"))
6286 file.Write(" const uint32_t size = ComputeSize(_count);\n")
6287 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6288 "cmd, size);\n")
6289 file.Write(" }\n")
6290 file.Write("\n")
6292 def WriteImmediateCmdHelper(self, func, file):
6293 """Overrriden from TypeHandler."""
6294 code = """ void %(name)s(%(typed_args)s) {
6295 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
6296 gles2::cmds::%(name)s* c =
6297 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6298 if (c) {
6299 c->Init(%(args)s);
6304 file.Write(code % {
6305 "name": func.name,
6306 "typed_args": func.MakeTypedInitString(""),
6307 "args": func.MakeInitString("")
6310 def WriteImmediateFormatTest(self, func, file):
6311 """Overrriden from TypeHandler."""
6312 args = func.GetOriginalArgs()
6313 count_param = 0
6314 for arg in args:
6315 if arg.name == "count":
6316 count_param = int(arg.GetValidClientSideCmdArg(func))
6317 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6318 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6319 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
6320 for v in range(0, self.GetArrayCount(func) * count_param):
6321 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6322 (self.GetArrayType(func), v))
6323 file.Write(" };\n")
6324 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6325 (func.name, func.name))
6326 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
6327 file.Write(" const size_t kExpectedCmdSize =\n")
6328 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
6329 (self.GetArrayType(func), self.GetArrayCount(func)))
6330 file.Write(" void* next_cmd = cmd.Set(\n")
6331 file.Write(" &cmd")
6332 for value, arg in enumerate(args):
6333 if arg.IsPointer():
6334 file.Write(",\n data")
6335 elif arg.IsConstant():
6336 continue
6337 else:
6338 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
6339 file.Write(");\n")
6340 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6341 func.name)
6342 file.Write(" cmd.header.command);\n")
6343 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
6344 for value, arg in enumerate(args):
6345 if arg.IsPointer() or arg.IsConstant():
6346 continue
6347 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6348 (arg.type, value + 1, arg.name))
6349 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6350 file.Write(" next_cmd, sizeof(cmd) +\n")
6351 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6352 file.Write(" // TODO(gman): Check that data was inserted;\n")
6353 file.Write("}\n")
6354 file.Write("\n")
6356 class PUTSTRHandler(ArrayArgTypeHandler):
6357 """Handler for functions that pass a string array."""
6359 def __init__(self):
6360 ArrayArgTypeHandler.__init__(self)
6362 def __GetDataArg(self, func):
6363 """Return the argument that points to the 2D char arrays"""
6364 for arg in func.GetOriginalArgs():
6365 if arg.IsPointer2D():
6366 return arg
6367 return None
6369 def __GetLengthArg(self, func):
6370 """Return the argument that holds length for each char array"""
6371 for arg in func.GetOriginalArgs():
6372 if arg.IsPointer() and not arg.IsPointer2D():
6373 return arg
6374 return None
6376 def WriteGLES2Implementation(self, func, file):
6377 """Overrriden from TypeHandler."""
6378 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6379 (func.return_type, func.original_name,
6380 func.MakeTypedOriginalArgString("")))
6381 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6382 func.WriteDestinationInitalizationValidation(file)
6383 self.WriteClientGLCallLog(func, file)
6384 data_arg = self.__GetDataArg(func)
6385 length_arg = self.__GetLengthArg(func)
6386 log_code_block = """ GPU_CLIENT_LOG_CODE_BLOCK({
6387 for (GLsizei ii = 0; ii < count; ++ii) {
6388 if (%(data)s[ii]) {"""
6389 if length_arg == None:
6390 log_code_block += """
6391 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
6392 else:
6393 log_code_block += """
6394 if (%(length)s && %(length)s[ii] >= 0) {
6395 const std::string my_str(%(data)s[ii], %(length)s[ii]);
6396 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
6397 } else {
6398 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
6399 }"""
6400 log_code_block += """
6401 } else {
6402 GPU_CLIENT_LOG(" " << ii << ": NULL");
6407 file.Write(log_code_block % {
6408 'data': data_arg.name,
6409 'length': length_arg.name if not length_arg == None else ''
6411 for arg in func.GetOriginalArgs():
6412 arg.WriteClientSideValidationCode(file, func)
6413 size_code_block = """ // Compute the total size.
6414 base::CheckedNumeric<size_t> total_size = count;
6415 total_size += 1;
6416 total_size *= sizeof(GLint);
6417 if (!total_size.IsValid()) {
6418 SetGLError(GL_INVALID_VALUE, "glShaderSource", "overflow");
6419 return;
6421 size_t header_size = total_size.ValueOrDefault(0);
6422 std::vector<GLint> header(count + 1);
6423 header[0] = static_cast<GLint>(count);
6424 for (GLsizei ii = 0; ii < count; ++ii) {
6425 GLint len = 0;
6426 if (%(data)s[ii]) {"""
6427 if length_arg == None:
6428 size_code_block += """
6429 len = base::static_cast<GLint>(strlen(%(data)s[ii]));"""
6430 else:
6431 size_code_block += """
6432 len = (%(length)s && %(length)s[ii] >= 0) ?
6433 %(length)s[ii] : base::checked_cast<GLint>(strlen(%(data)s[ii]));"""
6434 size_code_block += """
6436 total_size += len;
6437 total_size += 1; // NULL at the end of each char array.
6438 if (!total_size.IsValid()) {
6439 SetGLError(GL_INVALID_VALUE, "glShaderSource", "overflow");
6440 return;
6442 header[ii + 1] = len;
6445 file.Write(size_code_block % {
6446 'data': data_arg.name,
6447 'length': length_arg.name if not length_arg == None else ''
6449 data_code_block = """ // Pack data into a bucket on the service.
6450 helper_->SetBucketSize(kResultBucketId, total_size.ValueOrDefault(0));
6451 size_t offset = 0;
6452 for (GLsizei ii = 0; ii <= count; ++ii) {
6453 const char* src = (ii == 0) ? reinterpret_cast<const char*>(&header[0]) :
6454 %(data)s[ii - 1];
6455 base::CheckedNumeric<size_t> checked_size = (ii == 0) ? header_size :
6456 static_cast<size_t>(header[ii]);
6457 if (ii > 0) {
6458 checked_size += 1; // NULL in the end.
6460 if (!checked_size.IsValid()) {
6461 SetGLError(GL_INVALID_VALUE, "glShaderSource", "overflow");
6462 return;
6464 size_t size = checked_size.ValueOrDefault(0);
6465 while (size) {
6466 ScopedTransferBufferPtr buffer(size, helper_, transfer_buffer_);
6467 if (!buffer.valid() || buffer.size() == 0) {
6468 SetGLError(GL_OUT_OF_MEMORY, "glShaderSource", "too large");
6469 return;
6471 size_t copy_size = buffer.size();
6472 if (ii > 0 && buffer.size() == size)
6473 --copy_size;
6474 if (copy_size)
6475 memcpy(buffer.address(), src, copy_size);
6476 if (copy_size < buffer.size()) {
6477 // Append NULL in the end.
6478 DCHECK(copy_size + 1 == buffer.size());
6479 char* str = reinterpret_cast<char*>(buffer.address());
6480 str[copy_size] = 0;
6482 helper_->SetBucketData(kResultBucketId, offset, buffer.size(),
6483 buffer.shm_id(), buffer.offset());
6484 offset += buffer.size();
6485 src += buffer.size();
6486 size -= buffer.size();
6489 DCHECK_EQ(total_size.ValueOrDefault(0), offset);
6491 file.Write(data_code_block % {
6492 'data': data_arg.name,
6493 'length': length_arg.name if not length_arg == None else ''
6495 bucket_cmd_arg_string = ""
6496 for arg in func.GetCmdArgs()[0:-2]:
6497 if bucket_cmd_arg_string:
6498 bucket_cmd_arg_string += ", "
6499 bucket_cmd_arg_string += arg.name
6500 if bucket_cmd_arg_string:
6501 bucket_cmd_arg_string += ", "
6502 bucket_cmd_arg_string += 'kResultBucketId'
6503 file.Write(" helper_->%sBucket(%s);\n" %
6504 (func.name, bucket_cmd_arg_string))
6505 file.Write(" helper_->SetBucketSize(kResultBucketId, 0);");
6506 file.Write(" CheckGLError();\n")
6507 file.Write("}\n")
6508 file.Write("\n")
6511 class PUTXnHandler(ArrayArgTypeHandler):
6512 """Handler for glUniform?f functions."""
6513 def __init__(self):
6514 ArrayArgTypeHandler.__init__(self)
6516 def WriteHandlerImplementation(self, func, file):
6517 """Overrriden from TypeHandler."""
6518 code = """ %(type)s temp[%(count)s] = { %(values)s};"""
6519 if func.IsUnsafe():
6520 code += """
6521 gl%(name)sv(%(location)s, 1, &temp[0]);
6523 else:
6524 code += """
6525 Do%(name)sv(%(location)s, 1, &temp[0]);
6527 values = ""
6528 args = func.GetOriginalArgs()
6529 count = int(self.GetArrayCount(func))
6530 num_args = len(args)
6531 for ii in range(count):
6532 values += "%s, " % args[len(args) - count + ii].name
6534 file.Write(code % {
6535 'name': func.name,
6536 'count': self.GetArrayCount(func),
6537 'type': self.GetArrayType(func),
6538 'location': args[0].name,
6539 'args': func.MakeOriginalArgString(""),
6540 'values': values,
6543 def WriteServiceUnitTest(self, func, file, *extras):
6544 """Overrriden from TypeHandler."""
6545 valid_test = """
6546 TEST_P(%(test_name)s, %(name)sValidArgs) {
6547 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
6548 SpecializedSetup<cmds::%(name)s, 0>(true);
6549 cmds::%(name)s cmd;
6550 cmd.Init(%(args)s);"""
6551 if func.IsUnsafe():
6552 valid_test += """
6553 decoder_->set_unsafe_es3_apis_enabled(true);"""
6554 valid_test += """
6555 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6556 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6557 if func.IsUnsafe():
6558 valid_test += """
6559 decoder_->set_unsafe_es3_apis_enabled(false);
6560 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6561 valid_test += """
6564 args = func.GetOriginalArgs()
6565 local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
6566 self.WriteValidUnitTest(func, file, valid_test, {
6567 'name': func.name,
6568 'count': self.GetArrayCount(func),
6569 'local_args': local_args,
6570 }, *extras)
6572 invalid_test = """
6573 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6574 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
6575 SpecializedSetup<cmds::%(name)s, 0>(false);
6576 cmds::%(name)s cmd;
6577 cmd.Init(%(args)s);
6578 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6581 self.WriteInvalidUnitTest(func, file, invalid_test, {
6582 'name': func.GetInfo('name'),
6583 'count': self.GetArrayCount(func),
6587 class GLcharHandler(CustomHandler):
6588 """Handler for functions that pass a single string ."""
6590 def __init__(self):
6591 CustomHandler.__init__(self)
6593 def WriteImmediateCmdComputeSize(self, func, file):
6594 """Overrriden from TypeHandler."""
6595 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
6596 file.Write(" return static_cast<uint32_t>(\n")
6597 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
6598 file.Write(" }\n")
6600 def WriteImmediateCmdSetHeader(self, func, file):
6601 """Overrriden from TypeHandler."""
6602 code = """
6603 void SetHeader(uint32_t data_size) {
6604 header.SetCmdBySize<ValueType>(data_size);
6607 file.Write(code)
6609 def WriteImmediateCmdInit(self, func, file):
6610 """Overrriden from TypeHandler."""
6611 last_arg = func.GetLastOriginalArg()
6612 args = func.GetCmdArgs()
6613 set_code = []
6614 for arg in args:
6615 set_code.append(" %s = _%s;" % (arg.name, arg.name))
6616 code = """
6617 void Init(%(typed_args)s, uint32_t _data_size) {
6618 SetHeader(_data_size);
6619 %(set_code)s
6620 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
6624 file.Write(code % {
6625 "typed_args": func.MakeTypedArgString("_"),
6626 "set_code": "\n".join(set_code),
6627 "last_arg": last_arg.name
6630 def WriteImmediateCmdSet(self, func, file):
6631 """Overrriden from TypeHandler."""
6632 last_arg = func.GetLastOriginalArg()
6633 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
6634 func.MakeTypedCmdArgString("_", True))
6635 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
6636 func.MakeCmdArgString("_"))
6637 file.Write(" return NextImmediateCmdAddress<ValueType>("
6638 "cmd, _data_size);\n")
6639 file.Write(" }\n")
6640 file.Write("\n")
6642 def WriteImmediateCmdHelper(self, func, file):
6643 """Overrriden from TypeHandler."""
6644 code = """ void %(name)s(%(typed_args)s) {
6645 const uint32_t data_size = strlen(name);
6646 gles2::cmds::%(name)s* c =
6647 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
6648 if (c) {
6649 c->Init(%(args)s, data_size);
6654 file.Write(code % {
6655 "name": func.name,
6656 "typed_args": func.MakeTypedOriginalArgString(""),
6657 "args": func.MakeOriginalArgString(""),
6661 def WriteImmediateFormatTest(self, func, file):
6662 """Overrriden from TypeHandler."""
6663 init_code = []
6664 check_code = []
6665 all_but_last_arg = func.GetCmdArgs()[:-1]
6666 for value, arg in enumerate(all_but_last_arg):
6667 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
6668 for value, arg in enumerate(all_but_last_arg):
6669 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
6670 (arg.type, value + 11, arg.name))
6671 code = """
6672 TEST_F(GLES2FormatTest, %(func_name)s) {
6673 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
6674 static const char* const test_str = \"test string\";
6675 void* next_cmd = cmd.Set(
6676 &cmd,
6677 %(init_code)s
6678 test_str,
6679 strlen(test_str));
6680 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
6681 cmd.header.command);
6682 EXPECT_EQ(sizeof(cmd) +
6683 RoundSizeToMultipleOfEntries(strlen(test_str)),
6684 cmd.header.size * 4u);
6685 EXPECT_EQ(static_cast<char*>(next_cmd),
6686 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
6687 RoundSizeToMultipleOfEntries(strlen(test_str)));
6688 %(check_code)s
6689 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
6690 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
6691 CheckBytesWritten(
6692 next_cmd,
6693 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
6694 sizeof(cmd) + strlen(test_str));
6698 file.Write(code % {
6699 'func_name': func.name,
6700 'init_code': "\n".join(init_code),
6701 'check_code': "\n".join(check_code),
6705 class GLcharNHandler(CustomHandler):
6706 """Handler for functions that pass a single string with an optional len."""
6708 def __init__(self):
6709 CustomHandler.__init__(self)
6711 def InitFunction(self, func):
6712 """Overrriden from TypeHandler."""
6713 func.cmd_args = []
6714 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
6716 def NeedsDataTransferFunction(self, func):
6717 """Overriden from TypeHandler."""
6718 return False
6720 def AddBucketFunction(self, generator, func):
6721 """Overrriden from TypeHandler."""
6722 pass
6724 def WriteServiceImplementation(self, func, file):
6725 """Overrriden from TypeHandler."""
6726 self.WriteServiceHandlerFunctionHeader(func, file)
6727 file.Write("""
6728 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
6729 Bucket* bucket = GetBucket(bucket_id);
6730 if (!bucket || bucket->size() == 0) {
6731 return error::kInvalidArguments;
6733 std::string str;
6734 if (!bucket->GetAsString(&str)) {
6735 return error::kInvalidArguments;
6737 %(gl_func_name)s(0, str.c_str());
6738 return error::kNoError;
6741 """ % {
6742 'name': func.name,
6743 'gl_func_name': func.GetGLFunctionName(),
6744 'bucket_id': func.cmd_args[0].name,
6748 class IsHandler(TypeHandler):
6749 """Handler for glIs____ type and glGetError functions."""
6751 def __init__(self):
6752 TypeHandler.__init__(self)
6754 def InitFunction(self, func):
6755 """Overrriden from TypeHandler."""
6756 func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
6757 func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
6758 if func.GetInfo('result') == None:
6759 func.AddInfo('result', ['uint32_t'])
6761 def WriteServiceUnitTest(self, func, file, *extras):
6762 """Overrriden from TypeHandler."""
6763 valid_test = """
6764 TEST_P(%(test_name)s, %(name)sValidArgs) {
6765 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6766 SpecializedSetup<cmds::%(name)s, 0>(true);
6767 cmds::%(name)s cmd;
6768 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
6769 if func.IsUnsafe():
6770 valid_test += """
6771 decoder_->set_unsafe_es3_apis_enabled(true);"""
6772 valid_test += """
6773 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6774 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6775 if func.IsUnsafe():
6776 valid_test += """
6777 decoder_->set_unsafe_es3_apis_enabled(false);
6778 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6779 valid_test += """
6782 comma = ""
6783 if len(func.GetOriginalArgs()):
6784 comma =", "
6785 self.WriteValidUnitTest(func, file, valid_test, {
6786 'comma': comma,
6787 }, *extras)
6789 invalid_test = """
6790 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6791 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6792 SpecializedSetup<cmds::%(name)s, 0>(false);
6793 cmds::%(name)s cmd;
6794 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
6795 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6798 self.WriteInvalidUnitTest(func, file, invalid_test, {
6799 'comma': comma,
6800 }, *extras)
6802 invalid_test = """
6803 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
6804 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6805 SpecializedSetup<cmds::%(name)s, 0>(false);"""
6806 if func.IsUnsafe():
6807 invalid_test += """
6808 decoder_->set_unsafe_es3_apis_enabled(true);"""
6809 invalid_test += """
6810 cmds::%(name)s cmd;
6811 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
6812 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
6813 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
6814 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
6815 if func.IsUnsafe():
6816 invalid_test += """
6817 decoder_->set_unsafe_es3_apis_enabled(true);"""
6818 invalid_test += """
6821 self.WriteValidUnitTest(func, file, invalid_test, {
6822 'comma': comma,
6823 }, *extras)
6825 def WriteServiceImplementation(self, func, file):
6826 """Overrriden from TypeHandler."""
6827 self.WriteServiceHandlerFunctionHeader(func, file)
6828 args = func.GetOriginalArgs()
6829 for arg in args:
6830 arg.WriteGetCode(file)
6832 code = """ typedef cmds::%(func_name)s::Result Result;
6833 Result* result_dst = GetSharedMemoryAs<Result*>(
6834 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
6835 if (!result_dst) {
6836 return error::kOutOfBounds;
6839 file.Write(code % {'func_name': func.name})
6840 func.WriteHandlerValidation(file)
6841 if func.IsUnsafe():
6842 assert func.GetInfo('id_mapping')
6843 assert len(func.GetInfo('id_mapping')) == 1
6844 assert len(args) == 1
6845 id_type = func.GetInfo('id_mapping')[0]
6846 file.Write(" %s service_%s = 0;\n" % (args[0].type, id_type.lower()))
6847 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
6848 (id_type, id_type.lower(), id_type.lower()))
6849 else:
6850 file.Write(" *result_dst = %s(%s);\n" %
6851 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
6852 file.Write(" return error::kNoError;\n")
6853 file.Write("}\n")
6854 file.Write("\n")
6856 def WriteGLES2Implementation(self, func, file):
6857 """Overrriden from TypeHandler."""
6858 impl_func = func.GetInfo('impl_func')
6859 if impl_func == None or impl_func == True:
6860 error_value = func.GetInfo("error_value") or "GL_FALSE"
6861 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6862 (func.return_type, func.original_name,
6863 func.MakeTypedOriginalArgString("")))
6864 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6865 self.WriteTraceEvent(func, file)
6866 func.WriteDestinationInitalizationValidation(file)
6867 self.WriteClientGLCallLog(func, file)
6868 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
6869 file.Write(" Result* result = GetResultAs<Result*>();\n")
6870 file.Write(" if (!result) {\n")
6871 file.Write(" return %s;\n" % error_value)
6872 file.Write(" }\n")
6873 file.Write(" *result = 0;\n")
6874 assert len(func.GetOriginalArgs()) == 1
6875 id_arg = func.GetOriginalArgs()[0]
6876 if id_arg.type == 'GLsync':
6877 arg_string = "ToGLuint(%s)" % func.MakeOriginalArgString("")
6878 else:
6879 arg_string = func.MakeOriginalArgString("")
6880 file.Write(
6881 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
6882 (func.name, arg_string))
6883 file.Write(" WaitForCmd();\n")
6884 file.Write(" %s result_value = *result" % func.return_type)
6885 if func.return_type == "GLboolean":
6886 file.Write(" != 0")
6887 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
6888 file.Write(" CheckGLError();\n")
6889 file.Write(" return result_value;\n")
6890 file.Write("}\n")
6891 file.Write("\n")
6893 def WriteGLES2ImplementationUnitTest(self, func, file):
6894 """Overrriden from TypeHandler."""
6895 client_test = func.GetInfo('client_test')
6896 if client_test == None or client_test == True:
6897 code = """
6898 TEST_F(GLES2ImplementationTest, %(name)s) {
6899 struct Cmds {
6900 cmds::%(name)s cmd;
6903 Cmds expected;
6904 ExpectedMemoryInfo result1 =
6905 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
6906 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
6908 EXPECT_CALL(*command_buffer(), OnFlush())
6909 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
6910 .RetiresOnSaturation();
6912 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
6913 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6914 EXPECT_TRUE(result);
6917 args = func.GetOriginalArgs()
6918 assert len(args) == 1
6919 file.Write(code % {
6920 'name': func.name,
6921 'cmd_id_value': args[0].GetValidClientSideCmdArg(func),
6922 'gl_id_value': args[0].GetValidClientSideArg(func) })
6925 class STRnHandler(TypeHandler):
6926 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
6927 GetTranslatedShaderSourceANGLE."""
6929 def __init__(self):
6930 TypeHandler.__init__(self)
6932 def InitFunction(self, func):
6933 """Overrriden from TypeHandler."""
6934 # remove all but the first cmd args.
6935 cmd_args = func.GetCmdArgs()
6936 func.ClearCmdArgs()
6937 func.AddCmdArg(cmd_args[0])
6938 # add on a bucket id.
6939 func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
6941 def WriteGLES2Implementation(self, func, file):
6942 """Overrriden from TypeHandler."""
6943 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
6944 GPU_CLIENT_SINGLE_THREAD_CHECK();
6946 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
6947 << "] gl%(func_name)s" << "("
6948 << %(arg0)s << ", "
6949 << %(arg1)s << ", "
6950 << static_cast<void*>(%(arg2)s) << ", "
6951 << static_cast<void*>(%(arg3)s) << ")");
6952 helper_->SetBucketSize(kResultBucketId, 0);
6953 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
6954 std::string str;
6955 GLsizei max_size = 0;
6956 if (GetBucketAsString(kResultBucketId, &str)) {
6957 if (bufsize > 0) {
6958 max_size =
6959 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
6960 memcpy(%(dest_name)s, str.c_str(), max_size);
6961 %(dest_name)s[max_size] = '\\0';
6962 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
6965 if (%(length_name)s != NULL) {
6966 *%(length_name)s = max_size;
6968 CheckGLError();
6971 args = func.GetOriginalArgs()
6972 str_args = {
6973 'return_type': func.return_type,
6974 'func_name': func.original_name,
6975 'args': func.MakeTypedOriginalArgString(""),
6976 'id_name': args[0].name,
6977 'bufsize_name': args[1].name,
6978 'length_name': args[2].name,
6979 'dest_name': args[3].name,
6980 'arg0': args[0].name,
6981 'arg1': args[1].name,
6982 'arg2': args[2].name,
6983 'arg3': args[3].name,
6985 file.Write(code_1 % str_args)
6986 func.WriteDestinationInitalizationValidation(file)
6987 file.Write(code_2 % str_args)
6989 def WriteServiceUnitTest(self, func, file, *extras):
6990 """Overrriden from TypeHandler."""
6991 valid_test = """
6992 TEST_P(%(test_name)s, %(name)sValidArgs) {
6993 const char* kInfo = "hello";
6994 const uint32_t kBucketId = 123;
6995 SpecializedSetup<cmds::%(name)s, 0>(true);
6996 %(expect_len_code)s
6997 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
6998 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
6999 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
7000 cmds::%(name)s cmd;
7001 cmd.Init(%(args)s);
7002 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7003 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
7004 ASSERT_TRUE(bucket != NULL);
7005 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
7006 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
7007 bucket->size()));
7008 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7011 args = func.GetOriginalArgs()
7012 id_name = args[0].GetValidGLArg(func)
7013 get_len_func = func.GetInfo('get_len_func')
7014 get_len_enum = func.GetInfo('get_len_enum')
7015 sub = {
7016 'id_name': id_name,
7017 'get_len_func': get_len_func,
7018 'get_len_enum': get_len_enum,
7019 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
7020 args[0].GetValidGLArg(func),
7021 'args': '%s, kBucketId' % args[0].GetValidArg(func),
7022 'expect_len_code': '',
7024 if get_len_func and get_len_func[0:2] == 'gl':
7025 sub['expect_len_code'] = (
7026 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
7027 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
7028 get_len_func[2:], id_name, get_len_enum)
7029 self.WriteValidUnitTest(func, file, valid_test, sub, *extras)
7031 invalid_test = """
7032 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7033 const uint32_t kBucketId = 123;
7034 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
7035 .Times(0);
7036 cmds::%(name)s cmd;
7037 cmd.Init(kInvalidClientId, kBucketId);
7038 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7039 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7042 self.WriteValidUnitTest(func, file, invalid_test, *extras)
7044 def WriteServiceImplementation(self, func, file):
7045 """Overrriden from TypeHandler."""
7046 pass
7048 class NamedType(object):
7049 """A class that represents a type of an argument in a client function.
7051 A type of an argument that is to be passed through in the command buffer
7052 command. Currently used only for the arguments that are specificly named in
7053 the 'cmd_buffer_functions.txt' file, mostly enums.
7056 def __init__(self, info):
7057 assert not 'is_complete' in info or info['is_complete'] == True
7058 self.info = info
7059 self.valid = info['valid']
7060 if 'invalid' in info:
7061 self.invalid = info['invalid']
7062 else:
7063 self.invalid = []
7065 def GetType(self):
7066 return self.info['type']
7068 def GetInvalidValues(self):
7069 return self.invalid
7071 def GetValidValues(self):
7072 return self.valid
7074 def IsConstant(self):
7075 if not 'is_complete' in self.info:
7076 return False
7078 return len(self.GetValidValues()) == 1
7080 def GetConstantValue(self):
7081 return self.GetValidValues()[0]
7083 class Argument(object):
7084 """A class that represents a function argument."""
7086 cmd_type_map_ = {
7087 'GLenum': 'uint32_t',
7088 'GLint': 'int32_t',
7089 'GLintptr': 'int32_t',
7090 'GLsizei': 'int32_t',
7091 'GLsizeiptr': 'int32_t',
7092 'GLfloat': 'float',
7093 'GLclampf': 'float',
7095 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
7097 def __init__(self, name, type):
7098 self.name = name
7099 self.optional = type.endswith("Optional*")
7100 if self.optional:
7101 type = type[:-9] + "*"
7102 self.type = type
7104 if type in self.cmd_type_map_:
7105 self.cmd_type = self.cmd_type_map_[type]
7106 else:
7107 self.cmd_type = 'uint32_t'
7109 def IsPointer(self):
7110 """Returns true if argument is a pointer."""
7111 return False
7113 def IsPointer2D(self):
7114 """Returns true if argument is a 2D pointer."""
7115 return False
7117 def IsConstant(self):
7118 """Returns true if the argument has only one valid value."""
7119 return False
7121 def AddCmdArgs(self, args):
7122 """Adds command arguments for this argument to the given list."""
7123 if not self.IsConstant():
7124 return args.append(self)
7126 def AddInitArgs(self, args):
7127 """Adds init arguments for this argument to the given list."""
7128 if not self.IsConstant():
7129 return args.append(self)
7131 def GetValidArg(self, func):
7132 """Gets a valid value for this argument."""
7133 valid_arg = func.GetValidArg(self)
7134 if valid_arg != None:
7135 return valid_arg
7137 index = func.GetOriginalArgs().index(self)
7138 return str(index + 1)
7140 def GetValidClientSideArg(self, func):
7141 """Gets a valid value for this argument."""
7142 valid_arg = func.GetValidArg(self)
7143 if valid_arg != None:
7144 return valid_arg
7146 index = func.GetOriginalArgs().index(self)
7147 if self.type == 'GLsync':
7148 return ("reinterpret_cast<GLsync>(%d)" % (index + 1))
7149 return str(index + 1)
7151 def GetValidClientSideCmdArg(self, func):
7152 """Gets a valid value for this argument."""
7153 valid_arg = func.GetValidArg(self)
7154 if valid_arg != None:
7155 return valid_arg
7156 try:
7157 index = func.GetOriginalArgs().index(self)
7158 return str(index + 1)
7159 except ValueError:
7160 pass
7161 index = func.GetCmdArgs().index(self)
7162 return str(index + 1)
7164 def GetValidGLArg(self, func):
7165 """Gets a valid GL value for this argument."""
7166 value = self.GetValidArg(func)
7167 if self.type == 'GLsync':
7168 return ("reinterpret_cast<GLsync>(%s)" % value)
7169 return value
7171 def GetValidNonCachedClientSideArg(self, func):
7172 """Returns a valid value for this argument in a GL call.
7173 Using the value will produce a command buffer service invocation.
7174 Returns None if there is no such value."""
7175 return '123'
7177 def GetValidNonCachedClientSideCmdArg(self, func):
7178 """Returns a valid value for this argument in a command buffer command.
7179 Calling the GL function with the value returned by
7180 GetValidNonCachedClientSideArg will result in a command buffer command
7181 that contains the value returned by this function. """
7182 return '123'
7184 def GetNumInvalidValues(self, func):
7185 """returns the number of invalid values to be tested."""
7186 return 0
7188 def GetInvalidArg(self, index):
7189 """returns an invalid value and expected parse result by index."""
7190 return ("---ERROR0---", "---ERROR2---", None)
7192 def GetLogArg(self):
7193 """Get argument appropriate for LOG macro."""
7194 if self.type == 'GLboolean':
7195 return 'GLES2Util::GetStringBool(%s)' % self.name
7196 if self.type == 'GLenum':
7197 return 'GLES2Util::GetStringEnum(%s)' % self.name
7198 return self.name
7200 def WriteGetCode(self, file):
7201 """Writes the code to get an argument from a command structure."""
7202 if self.type == 'GLsync':
7203 my_type = 'GLuint'
7204 else:
7205 my_type = self.type
7206 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
7207 (my_type, self.name, my_type, self.name))
7209 def WriteValidationCode(self, file, func):
7210 """Writes the validation code for an argument."""
7211 pass
7213 def WriteClientSideValidationCode(self, file, func):
7214 """Writes the validation code for an argument."""
7215 pass
7217 def WriteDestinationInitalizationValidation(self, file, func):
7218 """Writes the client side destintion initialization validation."""
7219 pass
7221 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
7222 """Writes the client side destintion initialization validation if needed."""
7223 parts = self.type.split(" ")
7224 if len(parts) > 1:
7225 return
7226 if parts[0] in self.need_validation_:
7227 file.Write(
7228 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
7229 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
7232 def WriteGetAddress(self, file):
7233 """Writes the code to get the address this argument refers to."""
7234 pass
7236 def GetImmediateVersion(self):
7237 """Gets the immediate version of this argument."""
7238 return self
7240 def GetBucketVersion(self):
7241 """Gets the bucket version of this argument."""
7242 return self
7245 class BoolArgument(Argument):
7246 """class for GLboolean"""
7248 def __init__(self, name, type):
7249 Argument.__init__(self, name, 'GLboolean')
7251 def GetValidArg(self, func):
7252 """Gets a valid value for this argument."""
7253 return 'true'
7255 def GetValidClientSideArg(self, func):
7256 """Gets a valid value for this argument."""
7257 return 'true'
7259 def GetValidClientSideCmdArg(self, func):
7260 """Gets a valid value for this argument."""
7261 return 'true'
7263 def GetValidGLArg(self, func):
7264 """Gets a valid GL value for this argument."""
7265 return 'true'
7268 class UniformLocationArgument(Argument):
7269 """class for uniform locations."""
7271 def __init__(self, name):
7272 Argument.__init__(self, name, "GLint")
7274 def WriteGetCode(self, file):
7275 """Writes the code to get an argument from a command structure."""
7276 code = """ %s %s = static_cast<%s>(c.%s);
7278 file.Write(code % (self.type, self.name, self.type, self.name))
7280 class DataSizeArgument(Argument):
7281 """class for data_size which Bucket commands do not need."""
7283 def __init__(self, name):
7284 Argument.__init__(self, name, "uint32_t")
7286 def GetBucketVersion(self):
7287 return None
7290 class SizeArgument(Argument):
7291 """class for GLsizei and GLsizeiptr."""
7293 def __init__(self, name, type):
7294 Argument.__init__(self, name, type)
7296 def GetNumInvalidValues(self, func):
7297 """overridden from Argument."""
7298 if func.IsImmediate():
7299 return 0
7300 return 1
7302 def GetInvalidArg(self, index):
7303 """overridden from Argument."""
7304 return ("-1", "kNoError", "GL_INVALID_VALUE")
7306 def WriteValidationCode(self, file, func):
7307 """overridden from Argument."""
7308 file.Write(" if (%s < 0) {\n" % self.name)
7309 file.Write(
7310 " LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
7311 (func.original_name, self.name))
7312 file.Write(" return error::kNoError;\n")
7313 file.Write(" }\n")
7315 def WriteClientSideValidationCode(self, file, func):
7316 """overridden from Argument."""
7317 file.Write(" if (%s < 0) {\n" % self.name)
7318 file.Write(
7319 " SetGLError(GL_INVALID_VALUE, \"gl%s\", \"%s < 0\");\n" %
7320 (func.original_name, self.name))
7321 file.Write(" return;\n")
7322 file.Write(" }\n")
7325 class SizeNotNegativeArgument(SizeArgument):
7326 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
7328 def __init__(self, name, type, gl_type):
7329 SizeArgument.__init__(self, name, gl_type)
7331 def GetInvalidArg(self, index):
7332 """overridden from SizeArgument."""
7333 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
7335 def WriteValidationCode(self, file, func):
7336 """overridden from SizeArgument."""
7337 pass
7340 class EnumBaseArgument(Argument):
7341 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
7342 ValidatedBoolArgument."""
7344 def __init__(self, name, gl_type, type, gl_error):
7345 Argument.__init__(self, name, gl_type)
7347 self.local_type = type
7348 self.gl_error = gl_error
7349 name = type[len(gl_type):]
7350 self.type_name = name
7351 self.named_type = NamedType(_NAMED_TYPE_INFO[name])
7353 def IsConstant(self):
7354 return self.named_type.IsConstant()
7356 def GetConstantValue(self):
7357 return self.named_type.GetConstantValue()
7359 def WriteValidationCode(self, file, func):
7360 if func.IsUnsafe():
7361 return
7362 if self.named_type.IsConstant():
7363 return
7364 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
7365 (ToUnderscore(self.type_name), self.name))
7366 if self.gl_error == "GL_INVALID_ENUM":
7367 file.Write(
7368 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
7369 (func.original_name, self.name, self.name))
7370 else:
7371 file.Write(
7372 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
7373 (self.gl_error, func.original_name, self.name, self.gl_error))
7374 file.Write(" return error::kNoError;\n")
7375 file.Write(" }\n")
7377 def WriteClientSideValidationCode(self, file, func):
7378 if not self.named_type.IsConstant():
7379 return
7380 file.Write(" if (%s != %s) {" % (self.name,
7381 self.GetConstantValue()))
7382 file.Write(
7383 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
7384 (self.gl_error, func.original_name, self.name, self.gl_error))
7385 if func.return_type == "void":
7386 file.Write(" return;\n")
7387 else:
7388 file.Write(" return %s;\n" % func.GetErrorReturnString())
7389 file.Write(" }\n")
7391 def GetValidArg(self, func):
7392 valid_arg = func.GetValidArg(self)
7393 if valid_arg != None:
7394 return valid_arg
7395 valid = self.named_type.GetValidValues()
7396 if valid:
7397 num_valid = len(valid)
7398 return valid[0]
7400 index = func.GetOriginalArgs().index(self)
7401 return str(index + 1)
7403 def GetValidClientSideArg(self, func):
7404 """Gets a valid value for this argument."""
7405 return self.GetValidArg(func)
7407 def GetValidClientSideCmdArg(self, func):
7408 """Gets a valid value for this argument."""
7409 valid_arg = func.GetValidArg(self)
7410 if valid_arg != None:
7411 return valid_arg
7413 valid = self.named_type.GetValidValues()
7414 if valid:
7415 num_valid = len(valid)
7416 return valid[0]
7418 try:
7419 index = func.GetOriginalArgs().index(self)
7420 return str(index + 1)
7421 except ValueError:
7422 pass
7423 index = func.GetCmdArgs().index(self)
7424 return str(index + 1)
7426 def GetValidGLArg(self, func):
7427 """Gets a valid value for this argument."""
7428 return self.GetValidArg(func)
7430 def GetNumInvalidValues(self, func):
7431 """returns the number of invalid values to be tested."""
7432 return len(self.named_type.GetInvalidValues())
7434 def GetInvalidArg(self, index):
7435 """returns an invalid value by index."""
7436 invalid = self.named_type.GetInvalidValues()
7437 if invalid:
7438 num_invalid = len(invalid)
7439 if index >= num_invalid:
7440 index = num_invalid - 1
7441 return (invalid[index], "kNoError", self.gl_error)
7442 return ("---ERROR1---", "kNoError", self.gl_error)
7445 class EnumArgument(EnumBaseArgument):
7446 """A class that represents a GLenum argument"""
7448 def __init__(self, name, type):
7449 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
7451 def GetLogArg(self):
7452 """Overridden from Argument."""
7453 return ("GLES2Util::GetString%s(%s)" %
7454 (self.type_name, self.name))
7457 class IntArgument(EnumBaseArgument):
7458 """A class for a GLint argument that can only accept specific values.
7460 For example glTexImage2D takes a GLint for its internalformat
7461 argument instead of a GLenum.
7464 def __init__(self, name, type):
7465 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
7468 class ValidatedBoolArgument(EnumBaseArgument):
7469 """A class for a GLboolean argument that can only accept specific values.
7471 For example glUniformMatrix takes a GLboolean for it's transpose but it
7472 must be false.
7475 def __init__(self, name, type):
7476 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
7478 def GetLogArg(self):
7479 """Overridden from Argument."""
7480 return 'GLES2Util::GetStringBool(%s)' % self.name
7483 class BitFieldArgument(EnumBaseArgument):
7484 """A class for a GLbitfield argument that can only accept specific values.
7486 For example glFenceSync takes a GLbitfield for its flags argument bit it
7487 must be 0.
7490 def __init__(self, name, type):
7491 EnumBaseArgument.__init__(self, name, "GLbitfield", type,
7492 "GL_INVALID_VALUE")
7495 class ImmediatePointerArgument(Argument):
7496 """A class that represents an immediate argument to a function.
7498 An immediate argument is one where the data follows the command.
7501 def __init__(self, name, type):
7502 Argument.__init__(self, name, type)
7504 def IsPointer(self):
7505 return True
7507 def GetPointedType(self):
7508 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
7509 assert match
7510 return match.groupdict()['element_type']
7512 def AddCmdArgs(self, args):
7513 """Overridden from Argument."""
7514 pass
7516 def WriteGetCode(self, file):
7517 """Overridden from Argument."""
7518 file.Write(
7519 " %s %s = GetImmediateDataAs<%s>(\n" %
7520 (self.type, self.name, self.type))
7521 file.Write(" c, data_size, immediate_data_size);\n")
7523 def WriteValidationCode(self, file, func):
7524 """Overridden from Argument."""
7525 file.Write(" if (%s == NULL) {\n" % self.name)
7526 file.Write(" return error::kOutOfBounds;\n")
7527 file.Write(" }\n")
7529 def GetImmediateVersion(self):
7530 """Overridden from Argument."""
7531 return None
7533 def WriteDestinationInitalizationValidation(self, file, func):
7534 """Overridden from Argument."""
7535 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
7537 def GetLogArg(self):
7538 """Overridden from Argument."""
7539 return "static_cast<const void*>(%s)" % self.name
7542 class BucketPointerArgument(Argument):
7543 """A class that represents an bucket argument to a function."""
7545 def __init__(self, name, type):
7546 Argument.__init__(self, name, type)
7548 def AddCmdArgs(self, args):
7549 """Overridden from Argument."""
7550 pass
7552 def WriteGetCode(self, file):
7553 """Overridden from Argument."""
7554 file.Write(
7555 " %s %s = bucket->GetData(0, data_size);\n" %
7556 (self.type, self.name))
7558 def WriteValidationCode(self, file, func):
7559 """Overridden from Argument."""
7560 pass
7562 def GetImmediateVersion(self):
7563 """Overridden from Argument."""
7564 return None
7566 def WriteDestinationInitalizationValidation(self, file, func):
7567 """Overridden from Argument."""
7568 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
7570 def GetLogArg(self):
7571 """Overridden from Argument."""
7572 return "static_cast<const void*>(%s)" % self.name
7575 class PointerArgument(Argument):
7576 """A class that represents a pointer argument to a function."""
7578 def __init__(self, name, type):
7579 Argument.__init__(self, name, type)
7581 def IsPointer(self):
7582 """Returns true if argument is a pointer."""
7583 return True
7585 def IsPointer2D(self):
7586 """Returns true if argument is a 2D pointer."""
7587 return self.type.count('*') == 2
7589 def GetPointedType(self):
7590 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
7591 assert match
7592 return match.groupdict()['element_type']
7594 def GetValidArg(self, func):
7595 """Overridden from Argument."""
7596 return "shared_memory_id_, shared_memory_offset_"
7598 def GetValidGLArg(self, func):
7599 """Overridden from Argument."""
7600 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
7602 def GetNumInvalidValues(self, func):
7603 """Overridden from Argument."""
7604 return 2
7606 def GetInvalidArg(self, index):
7607 """Overridden from Argument."""
7608 if index == 0:
7609 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
7610 else:
7611 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
7612 "kOutOfBounds", None)
7614 def GetLogArg(self):
7615 """Overridden from Argument."""
7616 return "static_cast<const void*>(%s)" % self.name
7618 def AddCmdArgs(self, args):
7619 """Overridden from Argument."""
7620 args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
7621 args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
7623 def WriteGetCode(self, file):
7624 """Overridden from Argument."""
7625 file.Write(
7626 " %s %s = GetSharedMemoryAs<%s>(\n" %
7627 (self.type, self.name, self.type))
7628 file.Write(
7629 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
7630 (self.name, self.name))
7632 def WriteGetAddress(self, file):
7633 """Overridden from Argument."""
7634 file.Write(
7635 " %s %s = GetSharedMemoryAs<%s>(\n" %
7636 (self.type, self.name, self.type))
7637 file.Write(
7638 " %s_shm_id, %s_shm_offset, %s_size);\n" %
7639 (self.name, self.name, self.name))
7641 def WriteValidationCode(self, file, func):
7642 """Overridden from Argument."""
7643 file.Write(" if (%s == NULL) {\n" % self.name)
7644 file.Write(" return error::kOutOfBounds;\n")
7645 file.Write(" }\n")
7647 def GetImmediateVersion(self):
7648 """Overridden from Argument."""
7649 return ImmediatePointerArgument(self.name, self.type)
7651 def GetBucketVersion(self):
7652 """Overridden from Argument."""
7653 if self.type.find('char') >= 0:
7654 if self.IsPointer2D():
7655 return InputStringArrayBucketArgument(self.name, self.type)
7656 return InputStringBucketArgument(self.name, self.type)
7657 return BucketPointerArgument(self.name, self.type)
7659 def WriteDestinationInitalizationValidation(self, file, func):
7660 """Overridden from Argument."""
7661 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
7664 class InputStringBucketArgument(Argument):
7665 """A string input argument where the string is passed in a bucket."""
7667 def __init__(self, name, type):
7668 Argument.__init__(self, name + "_bucket_id", "uint32_t")
7671 class InputStringArrayBucketArgument(Argument):
7672 """A string array input argument where the strings are passed in a bucket."""
7674 def __init__(self, name, type):
7675 Argument.__init__(self, name + "_bucket_id", "uint32_t")
7676 self._original_name = name
7678 def WriteGetCode(self, file):
7679 """Overridden from Argument."""
7680 code = """
7681 const size_t kMinBucketSize = sizeof(GLint);
7682 // Each string has at least |length| in the header and a NUL character.
7683 const size_t kMinStringSize = sizeof(GLint) + 1;
7684 Bucket* bucket = GetBucket(c.%(name)s);
7685 if (!bucket) {
7686 return error::kInvalidArguments;
7688 const size_t bucket_size = bucket->size();
7689 if (bucket_size < kMinBucketSize) {
7690 return error::kInvalidArguments;
7692 const char* bucket_data = bucket->GetDataAs<const char*>(0, bucket_size);
7693 const GLint* header = reinterpret_cast<const GLint*>(bucket_data);
7694 GLsizei count = static_cast<GLsizei>(header[0]);
7695 if (count < 0) {
7696 return error::kInvalidArguments;
7698 const size_t max_count = (bucket_size - kMinBucketSize) / kMinStringSize;
7699 if (max_count < static_cast<size_t>(count)) {
7700 return error::kInvalidArguments;
7702 const GLint* length = header + 1;
7703 scoped_ptr<const char*[]> strs;
7704 if (count > 0)
7705 strs.reset(new const char*[count]);
7706 const char** %(original_name)s = strs.get();
7707 base::CheckedNumeric<size_t> total_size = sizeof(GLint);
7708 total_size *= count + 1; // Header size.
7709 if (!total_size.IsValid())
7710 return error::kInvalidArguments;
7711 for (GLsizei ii = 0; ii < count; ++ii) {
7712 %(original_name)s[ii] = bucket_data + total_size.ValueOrDefault(0);
7713 total_size += length[ii];
7714 total_size += 1; // NUL char at the end of each char array.
7715 if (!total_size.IsValid() || total_size.ValueOrDefault(0) > bucket_size ||
7716 %(original_name)s[ii][length[ii]] != 0) {
7717 return error::kInvalidArguments;
7720 if (total_size.ValueOrDefault(0) != bucket_size) {
7721 return error::kInvalidArguments;
7724 file.Write(code % {
7725 'name': self.name,
7726 'original_name': self._original_name,
7729 def GetValidArg(self, func):
7730 return "kNameBucketId"
7732 def GetValidGLArg(self, func):
7733 return "_"
7736 class ResourceIdArgument(Argument):
7737 """A class that represents a resource id argument to a function."""
7739 def __init__(self, name, type):
7740 match = re.match("(GLid\w+)", type)
7741 self.resource_type = match.group(1)[4:]
7742 if self.resource_type == "Sync":
7743 type = type.replace(match.group(1), "GLsync")
7744 else:
7745 type = type.replace(match.group(1), "GLuint")
7746 Argument.__init__(self, name, type)
7748 def WriteGetCode(self, file):
7749 """Overridden from Argument."""
7750 if self.type == "GLsync":
7751 my_type = "GLuint"
7752 else:
7753 my_type = self.type
7754 file.Write(" %s %s = c.%s;\n" % (my_type, self.name, self.name))
7756 def GetValidArg(self, func):
7757 return "client_%s_id_" % self.resource_type.lower()
7759 def GetValidGLArg(self, func):
7760 if self.resource_type == "Sync":
7761 return "reinterpret_cast<GLsync>(kService%sId)" % self.resource_type
7762 return "kService%sId" % self.resource_type
7765 class ResourceIdBindArgument(Argument):
7766 """Represents a resource id argument to a bind function."""
7768 def __init__(self, name, type):
7769 match = re.match("(GLidBind\w+)", type)
7770 self.resource_type = match.group(1)[8:]
7771 type = type.replace(match.group(1), "GLuint")
7772 Argument.__init__(self, name, type)
7774 def WriteGetCode(self, file):
7775 """Overridden from Argument."""
7776 code = """ %(type)s %(name)s = c.%(name)s;
7778 file.Write(code % {'type': self.type, 'name': self.name})
7780 def GetValidArg(self, func):
7781 return "client_%s_id_" % self.resource_type.lower()
7783 def GetValidGLArg(self, func):
7784 return "kService%sId" % self.resource_type
7787 class ResourceIdZeroArgument(Argument):
7788 """Represents a resource id argument to a function that can be zero."""
7790 def __init__(self, name, type):
7791 match = re.match("(GLidZero\w+)", type)
7792 self.resource_type = match.group(1)[8:]
7793 type = type.replace(match.group(1), "GLuint")
7794 Argument.__init__(self, name, type)
7796 def WriteGetCode(self, file):
7797 """Overridden from Argument."""
7798 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
7800 def GetValidArg(self, func):
7801 return "client_%s_id_" % self.resource_type.lower()
7803 def GetValidGLArg(self, func):
7804 return "kService%sId" % self.resource_type
7806 def GetNumInvalidValues(self, func):
7807 """returns the number of invalid values to be tested."""
7808 return 1
7810 def GetInvalidArg(self, index):
7811 """returns an invalid value by index."""
7812 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
7815 class Function(object):
7816 """A class that represents a function."""
7818 type_handlers = {
7819 '': TypeHandler(),
7820 'Bind': BindHandler(),
7821 'Create': CreateHandler(),
7822 'Custom': CustomHandler(),
7823 'Data': DataHandler(),
7824 'Delete': DeleteHandler(),
7825 'DELn': DELnHandler(),
7826 'GENn': GENnHandler(),
7827 'GETn': GETnHandler(),
7828 'GLchar': GLcharHandler(),
7829 'GLcharN': GLcharNHandler(),
7830 'HandWritten': HandWrittenHandler(),
7831 'Is': IsHandler(),
7832 'Manual': ManualHandler(),
7833 'PUT': PUTHandler(),
7834 'PUTn': PUTnHandler(),
7835 'PUTSTR': PUTSTRHandler(),
7836 'PUTXn': PUTXnHandler(),
7837 'StateSet': StateSetHandler(),
7838 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
7839 'StateSetFrontBack': StateSetFrontBackHandler(),
7840 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
7841 'StateSetNamedParameter': StateSetNamedParameter(),
7842 'STRn': STRnHandler(),
7843 'Todo': TodoHandler(),
7846 def __init__(self, name, info):
7847 self.name = name
7848 self.original_name = info['original_name']
7850 self.original_args = self.ParseArgs(info['original_args'])
7852 if 'cmd_args' in info:
7853 self.args_for_cmds = self.ParseArgs(info['cmd_args'])
7854 else:
7855 self.args_for_cmds = self.original_args[:]
7857 self.return_type = info['return_type']
7858 if self.return_type != 'void':
7859 self.return_arg = CreateArg(info['return_type'] + " result")
7860 else:
7861 self.return_arg = None
7863 self.num_pointer_args = sum(
7864 [1 for arg in self.args_for_cmds if arg.IsPointer()])
7865 if self.num_pointer_args > 0:
7866 for arg in reversed(self.original_args):
7867 if arg.IsPointer():
7868 self.last_original_pointer_arg = arg
7869 break
7870 else:
7871 self.last_original_pointer_arg = None
7872 self.info = info
7873 self.type_handler = self.type_handlers[info['type']]
7874 self.can_auto_generate = (self.num_pointer_args == 0 and
7875 info['return_type'] == "void")
7876 self.InitFunction()
7878 def ParseArgs(self, arg_string):
7879 """Parses a function arg string."""
7880 args = []
7881 parts = arg_string.split(',')
7882 for arg_string in parts:
7883 arg = CreateArg(arg_string)
7884 if arg:
7885 args.append(arg)
7886 return args
7888 def IsType(self, type_name):
7889 """Returns true if function is a certain type."""
7890 return self.info['type'] == type_name
7892 def InitFunction(self):
7893 """Creates command args and calls the init function for the type handler.
7895 Creates argument lists for command buffer commands, eg. self.cmd_args and
7896 self.init_args.
7897 Calls the type function initialization.
7898 Override to create different kind of command buffer command argument lists.
7900 self.cmd_args = []
7901 for arg in self.args_for_cmds:
7902 arg.AddCmdArgs(self.cmd_args)
7904 self.init_args = []
7905 for arg in self.args_for_cmds:
7906 arg.AddInitArgs(self.init_args)
7908 if self.return_arg:
7909 self.init_args.append(self.return_arg)
7911 self.type_handler.InitFunction(self)
7913 def IsImmediate(self):
7914 """Returns whether the function is immediate data function or not."""
7915 return False
7917 def IsUnsafe(self):
7918 """Returns whether the function has service side validation or not."""
7919 return self.GetInfo('unsafe', False)
7921 def GetInfo(self, name, default = None):
7922 """Returns a value from the function info for this function."""
7923 if name in self.info:
7924 return self.info[name]
7925 return default
7927 def GetValidArg(self, arg):
7928 """Gets a valid argument value for the parameter arg from the function info
7929 if one exists."""
7930 try:
7931 index = self.GetOriginalArgs().index(arg)
7932 except ValueError:
7933 return None
7935 valid_args = self.GetInfo('valid_args')
7936 if valid_args and str(index) in valid_args:
7937 return valid_args[str(index)]
7938 return None
7940 def AddInfo(self, name, value):
7941 """Adds an info."""
7942 self.info[name] = value
7944 def IsExtension(self):
7945 return self.GetInfo('extension') or self.GetInfo('extension_flag')
7947 def IsCoreGLFunction(self):
7948 return (not self.IsExtension() and
7949 not self.GetInfo('pepper_interface') and
7950 not self.IsUnsafe())
7952 def InPepperInterface(self, interface):
7953 ext = self.GetInfo('pepper_interface')
7954 if not interface.GetName():
7955 return self.IsCoreGLFunction()
7956 return ext == interface.GetName()
7958 def InAnyPepperExtension(self):
7959 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
7961 def GetErrorReturnString(self):
7962 if self.GetInfo("error_return"):
7963 return self.GetInfo("error_return")
7964 elif self.return_type == "GLboolean":
7965 return "GL_FALSE"
7966 elif "*" in self.return_type:
7967 return "NULL"
7968 return "0"
7970 def GetGLFunctionName(self):
7971 """Gets the function to call to execute GL for this command."""
7972 if self.GetInfo('decoder_func'):
7973 return self.GetInfo('decoder_func')
7974 return "gl%s" % self.original_name
7976 def GetGLTestFunctionName(self):
7977 gl_func_name = self.GetInfo('gl_test_func')
7978 if gl_func_name == None:
7979 gl_func_name = self.GetGLFunctionName()
7980 if gl_func_name.startswith("gl"):
7981 gl_func_name = gl_func_name[2:]
7982 else:
7983 gl_func_name = self.original_name
7984 return gl_func_name
7986 def GetDataTransferMethods(self):
7987 return self.GetInfo('data_transfer_methods',
7988 ['immediate' if self.num_pointer_args == 1 else 'shm'])
7990 def AddCmdArg(self, arg):
7991 """Adds a cmd argument to this function."""
7992 self.cmd_args.append(arg)
7994 def GetCmdArgs(self):
7995 """Gets the command args for this function."""
7996 return self.cmd_args
7998 def ClearCmdArgs(self):
7999 """Clears the command args for this function."""
8000 self.cmd_args = []
8002 def GetCmdConstants(self):
8003 """Gets the constants for this function."""
8004 return [arg for arg in self.args_for_cmds if arg.IsConstant()]
8006 def GetInitArgs(self):
8007 """Gets the init args for this function."""
8008 return self.init_args
8010 def GetOriginalArgs(self):
8011 """Gets the original arguments to this function."""
8012 return self.original_args
8014 def GetLastOriginalArg(self):
8015 """Gets the last original argument to this function."""
8016 return self.original_args[len(self.original_args) - 1]
8018 def GetLastOriginalPointerArg(self):
8019 return self.last_original_pointer_arg
8021 def GetResourceIdArg(self):
8022 for arg in self.original_args:
8023 if hasattr(arg, 'resource_type'):
8024 return arg
8025 return None
8027 def _MaybePrependComma(self, arg_string, add_comma):
8028 """Adds a comma if arg_string is not empty and add_comma is true."""
8029 comma = ""
8030 if add_comma and len(arg_string):
8031 comma = ", "
8032 return "%s%s" % (comma, arg_string)
8034 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
8035 """Gets a list of arguments as they are in GL."""
8036 args = self.GetOriginalArgs()
8037 arg_string = ", ".join(
8038 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8039 return self._MaybePrependComma(arg_string, add_comma)
8041 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
8042 """Gets the list of arguments as they are in GL."""
8043 args = self.GetOriginalArgs()
8044 arg_string = separator.join(
8045 ["%s%s" % (prefix, arg.name) for arg in args])
8046 return self._MaybePrependComma(arg_string, add_comma)
8048 def MakeTypedHelperArgString(self, prefix, add_comma = False):
8049 """Gets a list of typed GL arguments after removing unneeded arguments."""
8050 args = self.GetOriginalArgs()
8051 arg_string = ", ".join(
8052 ["%s %s%s" % (
8053 arg.type,
8054 prefix,
8055 arg.name,
8056 ) for arg in args if not arg.IsConstant()])
8057 return self._MaybePrependComma(arg_string, add_comma)
8059 def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
8060 """Gets a list of GL arguments after removing unneeded arguments."""
8061 args = self.GetOriginalArgs()
8062 arg_string = separator.join(
8063 ["%s%s" % (prefix, arg.name)
8064 for arg in args if not arg.IsConstant()])
8065 return self._MaybePrependComma(arg_string, add_comma)
8067 def MakeTypedPepperArgString(self, prefix):
8068 """Gets a list of arguments as they need to be for Pepper."""
8069 if self.GetInfo("pepper_args"):
8070 return self.GetInfo("pepper_args")
8071 else:
8072 return self.MakeTypedOriginalArgString(prefix, False)
8074 def MapCTypeToPepperIdlType(self, ctype, is_for_return_type=False):
8075 """Converts a C type name to the corresponding Pepper IDL type."""
8076 idltype = {
8077 'char*': '[out] str_t',
8078 'const GLchar* const*': '[out] cstr_t',
8079 'const char*': 'cstr_t',
8080 'const void*': 'mem_t',
8081 'void*': '[out] mem_t',
8082 'void**': '[out] mem_ptr_t',
8083 }.get(ctype, ctype)
8084 # We use "GLxxx_ptr_t" for "GLxxx*".
8085 matched = re.match(r'(const )?(GL\w+)\*$', ctype)
8086 if matched:
8087 idltype = matched.group(2) + '_ptr_t'
8088 if not matched.group(1):
8089 idltype = '[out] ' + idltype
8090 # If an in/out specifier is not specified yet, prepend [in].
8091 if idltype[0] != '[':
8092 idltype = '[in] ' + idltype
8093 # Strip the in/out specifier for a return type.
8094 if is_for_return_type:
8095 idltype = re.sub(r'\[\w+\] ', '', idltype)
8096 return idltype
8098 def MakeTypedPepperIdlArgStrings(self):
8099 """Gets a list of arguments as they need to be for Pepper IDL."""
8100 args = self.GetOriginalArgs()
8101 return ["%s %s" % (self.MapCTypeToPepperIdlType(arg.type), arg.name)
8102 for arg in args]
8104 def GetPepperName(self):
8105 if self.GetInfo("pepper_name"):
8106 return self.GetInfo("pepper_name")
8107 return self.name
8109 def MakeTypedCmdArgString(self, prefix, add_comma = False):
8110 """Gets a typed list of arguments as they need to be for command buffers."""
8111 args = self.GetCmdArgs()
8112 arg_string = ", ".join(
8113 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8114 return self._MaybePrependComma(arg_string, add_comma)
8116 def MakeCmdArgString(self, prefix, add_comma = False):
8117 """Gets the list of arguments as they need to be for command buffers."""
8118 args = self.GetCmdArgs()
8119 arg_string = ", ".join(
8120 ["%s%s" % (prefix, arg.name) for arg in args])
8121 return self._MaybePrependComma(arg_string, add_comma)
8123 def MakeTypedInitString(self, prefix, add_comma = False):
8124 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
8125 args = self.GetInitArgs()
8126 arg_string = ", ".join(
8127 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8128 return self._MaybePrependComma(arg_string, add_comma)
8130 def MakeInitString(self, prefix, add_comma = False):
8131 """Gets the list of arguments as they need to be for cmd Init/Set."""
8132 args = self.GetInitArgs()
8133 arg_string = ", ".join(
8134 ["%s%s" % (prefix, arg.name) for arg in args])
8135 return self._MaybePrependComma(arg_string, add_comma)
8137 def MakeLogArgString(self):
8138 """Makes a string of the arguments for the LOG macros"""
8139 args = self.GetOriginalArgs()
8140 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
8142 def WriteCommandDescription(self, file):
8143 """Writes a description of the command."""
8144 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
8146 def WriteHandlerValidation(self, file):
8147 """Writes validation code for the function."""
8148 for arg in self.GetOriginalArgs():
8149 arg.WriteValidationCode(file, self)
8150 self.WriteValidationCode(file)
8152 def WriteHandlerImplementation(self, file):
8153 """Writes the handler implementation for this command."""
8154 self.type_handler.WriteHandlerImplementation(self, file)
8156 def WriteValidationCode(self, file):
8157 """Writes the validation code for a command."""
8158 pass
8160 def WriteCmdFlag(self, file):
8161 """Writes the cmd cmd_flags constant."""
8162 flags = []
8163 # By default trace only at the highest level 3.
8164 trace_level = int(self.GetInfo('trace_level', default = 3))
8165 if trace_level not in xrange(0, 4):
8166 raise KeyError("Unhandled trace_level: %d" % trace_level)
8168 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
8170 if len(flags) > 0:
8171 cmd_flags = ' | '.join(flags)
8172 else:
8173 cmd_flags = 0
8175 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
8178 def WriteCmdArgFlag(self, file):
8179 """Writes the cmd kArgFlags constant."""
8180 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
8182 def WriteCmdComputeSize(self, file):
8183 """Writes the ComputeSize function for the command."""
8184 file.Write(" static uint32_t ComputeSize() {\n")
8185 file.Write(
8186 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
8187 file.Write(" }\n")
8188 file.Write("\n")
8190 def WriteCmdSetHeader(self, file):
8191 """Writes the cmd's SetHeader function."""
8192 file.Write(" void SetHeader() {\n")
8193 file.Write(" header.SetCmd<ValueType>();\n")
8194 file.Write(" }\n")
8195 file.Write("\n")
8197 def WriteCmdInit(self, file):
8198 """Writes the cmd's Init function."""
8199 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
8200 file.Write(" SetHeader();\n")
8201 args = self.GetCmdArgs()
8202 for arg in args:
8203 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
8204 file.Write(" }\n")
8205 file.Write("\n")
8207 def WriteCmdSet(self, file):
8208 """Writes the cmd's Set function."""
8209 copy_args = self.MakeCmdArgString("_", False)
8210 file.Write(" void* Set(void* cmd%s) {\n" %
8211 self.MakeTypedCmdArgString("_", True))
8212 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
8213 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
8214 file.Write(" }\n")
8215 file.Write("\n")
8217 def WriteStruct(self, file):
8218 self.type_handler.WriteStruct(self, file)
8220 def WriteDocs(self, file):
8221 self.type_handler.WriteDocs(self, file)
8223 def WriteCmdHelper(self, file):
8224 """Writes the cmd's helper."""
8225 self.type_handler.WriteCmdHelper(self, file)
8227 def WriteServiceImplementation(self, file):
8228 """Writes the service implementation for a command."""
8229 self.type_handler.WriteServiceImplementation(self, file)
8231 def WriteServiceUnitTest(self, file, *extras):
8232 """Writes the service implementation for a command."""
8233 self.type_handler.WriteServiceUnitTest(self, file, *extras)
8235 def WriteGLES2CLibImplementation(self, file):
8236 """Writes the GLES2 C Lib Implemention."""
8237 self.type_handler.WriteGLES2CLibImplementation(self, file)
8239 def WriteGLES2InterfaceHeader(self, file):
8240 """Writes the GLES2 Interface declaration."""
8241 self.type_handler.WriteGLES2InterfaceHeader(self, file)
8243 def WriteGLES2InterfaceStub(self, file):
8244 """Writes the GLES2 Interface Stub declaration."""
8245 self.type_handler.WriteGLES2InterfaceStub(self, file)
8247 def WriteGLES2InterfaceStubImpl(self, file):
8248 """Writes the GLES2 Interface Stub declaration."""
8249 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
8251 def WriteGLES2ImplementationHeader(self, file):
8252 """Writes the GLES2 Implemention declaration."""
8253 self.type_handler.WriteGLES2ImplementationHeader(self, file)
8255 def WriteGLES2Implementation(self, file):
8256 """Writes the GLES2 Implemention definition."""
8257 self.type_handler.WriteGLES2Implementation(self, file)
8259 def WriteGLES2TraceImplementationHeader(self, file):
8260 """Writes the GLES2 Trace Implemention declaration."""
8261 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
8263 def WriteGLES2TraceImplementation(self, file):
8264 """Writes the GLES2 Trace Implemention definition."""
8265 self.type_handler.WriteGLES2TraceImplementation(self, file)
8267 def WriteGLES2Header(self, file):
8268 """Writes the GLES2 Implemention unit test."""
8269 self.type_handler.WriteGLES2Header(self, file)
8271 def WriteGLES2ImplementationUnitTest(self, file):
8272 """Writes the GLES2 Implemention unit test."""
8273 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
8275 def WriteDestinationInitalizationValidation(self, file):
8276 """Writes the client side destintion initialization validation."""
8277 self.type_handler.WriteDestinationInitalizationValidation(self, file)
8279 def WriteFormatTest(self, file):
8280 """Writes the cmd's format test."""
8281 self.type_handler.WriteFormatTest(self, file)
8284 class PepperInterface(object):
8285 """A class that represents a function."""
8287 def __init__(self, info):
8288 self.name = info["name"]
8289 self.dev = info["dev"]
8291 def GetName(self):
8292 return self.name
8294 def GetInterfaceName(self):
8295 upperint = ""
8296 dev = ""
8297 if self.name:
8298 upperint = "_" + self.name.upper()
8299 if self.dev:
8300 dev = "_DEV"
8301 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
8303 def GetInterfaceString(self):
8304 dev = ""
8305 if self.dev:
8306 dev = "(Dev)"
8307 return "PPB_OpenGLES2%s%s" % (self.name, dev)
8309 def GetStructName(self):
8310 dev = ""
8311 if self.dev:
8312 dev = "_Dev"
8313 return "PPB_OpenGLES2%s%s" % (self.name, dev)
8316 class ImmediateFunction(Function):
8317 """A class that represnets an immediate function command."""
8319 def __init__(self, func):
8320 Function.__init__(
8321 self,
8322 "%sImmediate" % func.name,
8323 func.info)
8325 def InitFunction(self):
8326 # Override args in original_args and args_for_cmds with immediate versions
8327 # of the args.
8329 new_original_args = []
8330 for arg in self.original_args:
8331 new_arg = arg.GetImmediateVersion()
8332 if new_arg:
8333 new_original_args.append(new_arg)
8334 self.original_args = new_original_args
8336 new_args_for_cmds = []
8337 for arg in self.args_for_cmds:
8338 new_arg = arg.GetImmediateVersion()
8339 if new_arg:
8340 new_args_for_cmds.append(new_arg)
8342 self.args_for_cmds = new_args_for_cmds
8344 Function.InitFunction(self)
8346 def IsImmediate(self):
8347 return True
8349 def WriteCommandDescription(self, file):
8350 """Overridden from Function"""
8351 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
8352 self.original_name)
8354 def WriteServiceImplementation(self, file):
8355 """Overridden from Function"""
8356 self.type_handler.WriteImmediateServiceImplementation(self, file)
8358 def WriteHandlerImplementation(self, file):
8359 """Overridden from Function"""
8360 self.type_handler.WriteImmediateHandlerImplementation(self, file)
8362 def WriteServiceUnitTest(self, file, *extras):
8363 """Writes the service implementation for a command."""
8364 self.type_handler.WriteImmediateServiceUnitTest(self, file, *extras)
8366 def WriteValidationCode(self, file):
8367 """Overridden from Function"""
8368 self.type_handler.WriteImmediateValidationCode(self, file)
8370 def WriteCmdArgFlag(self, file):
8371 """Overridden from Function"""
8372 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
8374 def WriteCmdComputeSize(self, file):
8375 """Overridden from Function"""
8376 self.type_handler.WriteImmediateCmdComputeSize(self, file)
8378 def WriteCmdSetHeader(self, file):
8379 """Overridden from Function"""
8380 self.type_handler.WriteImmediateCmdSetHeader(self, file)
8382 def WriteCmdInit(self, file):
8383 """Overridden from Function"""
8384 self.type_handler.WriteImmediateCmdInit(self, file)
8386 def WriteCmdSet(self, file):
8387 """Overridden from Function"""
8388 self.type_handler.WriteImmediateCmdSet(self, file)
8390 def WriteCmdHelper(self, file):
8391 """Overridden from Function"""
8392 self.type_handler.WriteImmediateCmdHelper(self, file)
8394 def WriteFormatTest(self, file):
8395 """Overridden from Function"""
8396 self.type_handler.WriteImmediateFormatTest(self, file)
8399 class BucketFunction(Function):
8400 """A class that represnets a bucket version of a function command."""
8402 def __init__(self, func):
8403 Function.__init__(
8404 self,
8405 "%sBucket" % func.name,
8406 func.info)
8408 def InitFunction(self):
8409 # Override args in original_args and args_for_cmds with bucket versions
8410 # of the args.
8412 new_original_args = []
8413 for arg in self.original_args:
8414 new_arg = arg.GetBucketVersion()
8415 if new_arg:
8416 new_original_args.append(new_arg)
8417 self.original_args = new_original_args
8419 new_args_for_cmds = []
8420 for arg in self.args_for_cmds:
8421 new_arg = arg.GetBucketVersion()
8422 if new_arg:
8423 new_args_for_cmds.append(new_arg)
8425 self.args_for_cmds = new_args_for_cmds
8427 Function.InitFunction(self)
8429 def WriteCommandDescription(self, file):
8430 """Overridden from Function"""
8431 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
8432 self.original_name)
8434 def WriteServiceImplementation(self, file):
8435 """Overridden from Function"""
8436 self.type_handler.WriteBucketServiceImplementation(self, file)
8438 def WriteHandlerImplementation(self, file):
8439 """Overridden from Function"""
8440 self.type_handler.WriteBucketHandlerImplementation(self, file)
8442 def WriteServiceUnitTest(self, file, *extras):
8443 """Overridden from Function"""
8444 self.type_handler.WriteBucketServiceUnitTest(self, file, *extras)
8446 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
8447 """Overridden from Function"""
8448 args = self.GetOriginalArgs()
8449 arg_string = separator.join(
8450 ["%s%s" % (prefix, arg.name[0:-10] if arg.name.endswith("_bucket_id")
8451 else arg.name) for arg in args])
8452 return super(BucketFunction, self)._MaybePrependComma(arg_string, add_comma)
8455 def CreateArg(arg_string):
8456 """Creates an Argument."""
8457 arg_parts = arg_string.split()
8458 if len(arg_parts) == 1 and arg_parts[0] == 'void':
8459 return None
8460 # Is this a pointer argument?
8461 elif arg_string.find('*') >= 0:
8462 return PointerArgument(
8463 arg_parts[-1],
8464 " ".join(arg_parts[0:-1]))
8465 # Is this a resource argument? Must come after pointer check.
8466 elif arg_parts[0].startswith('GLidBind'):
8467 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8468 elif arg_parts[0].startswith('GLidZero'):
8469 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8470 elif arg_parts[0].startswith('GLid'):
8471 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8472 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
8473 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8474 elif arg_parts[0].startswith('GLbitfield') and len(arg_parts[0]) > 10:
8475 return BitFieldArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8476 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
8477 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8478 elif arg_parts[0].startswith('GLboolean'):
8479 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8480 elif arg_parts[0].startswith('GLintUniformLocation'):
8481 return UniformLocationArgument(arg_parts[-1])
8482 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
8483 not arg_parts[0].startswith('GLintptr')):
8484 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8485 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
8486 arg_parts[0].startswith('GLintptrNotNegative')):
8487 return SizeNotNegativeArgument(arg_parts[-1],
8488 " ".join(arg_parts[0:-1]),
8489 arg_parts[0][0:-11])
8490 elif arg_parts[0].startswith('GLsize'):
8491 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8492 else:
8493 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
8496 class GLGenerator(object):
8497 """A class to generate GL command buffers."""
8499 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
8501 def __init__(self, verbose):
8502 self.original_functions = []
8503 self.functions = []
8504 self.verbose = verbose
8505 self.errors = 0
8506 self.pepper_interfaces = []
8507 self.interface_info = {}
8508 self.generated_cpp_filenames = []
8510 for interface in _PEPPER_INTERFACES:
8511 interface = PepperInterface(interface)
8512 self.pepper_interfaces.append(interface)
8513 self.interface_info[interface.GetName()] = interface
8515 def AddFunction(self, func):
8516 """Adds a function."""
8517 self.functions.append(func)
8519 def GetFunctionInfo(self, name):
8520 """Gets a type info for the given function name."""
8521 if name in _FUNCTION_INFO:
8522 func_info = _FUNCTION_INFO[name].copy()
8523 else:
8524 func_info = {}
8526 if not 'type' in func_info:
8527 func_info['type'] = ''
8529 return func_info
8531 def Log(self, msg):
8532 """Prints something if verbose is true."""
8533 if self.verbose:
8534 print msg
8536 def Error(self, msg):
8537 """Prints an error."""
8538 print "Error: %s" % msg
8539 self.errors += 1
8541 def WriteLicense(self, file):
8542 """Writes the license."""
8543 file.Write(_LICENSE)
8545 def WriteNamespaceOpen(self, file):
8546 """Writes the code for the namespace."""
8547 file.Write("namespace gpu {\n")
8548 file.Write("namespace gles2 {\n")
8549 file.Write("\n")
8551 def WriteNamespaceClose(self, file):
8552 """Writes the code to close the namespace."""
8553 file.Write("} // namespace gles2\n")
8554 file.Write("} // namespace gpu\n")
8555 file.Write("\n")
8557 def ParseGLH(self, filename):
8558 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
8559 f = open(filename, "r")
8560 functions = f.read()
8561 f.close()
8562 for line in functions.splitlines():
8563 match = self._function_re.match(line)
8564 if match:
8565 func_name = match.group(2)[2:]
8566 func_info = self.GetFunctionInfo(func_name)
8567 if func_info['type'] == 'Noop':
8568 continue
8570 parsed_func_info = {
8571 'original_name': func_name,
8572 'original_args': match.group(3),
8573 'return_type': match.group(1).strip(),
8576 for k in parsed_func_info.keys():
8577 if not k in func_info:
8578 func_info[k] = parsed_func_info[k]
8580 f = Function(func_name, func_info)
8581 self.original_functions.append(f)
8583 #for arg in f.GetOriginalArgs():
8584 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
8585 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
8587 gen_cmd = f.GetInfo('gen_cmd')
8588 if gen_cmd == True or gen_cmd == None:
8589 if f.type_handler.NeedsDataTransferFunction(f):
8590 methods = f.GetDataTransferMethods()
8591 if 'immediate' in methods:
8592 self.AddFunction(ImmediateFunction(f))
8593 if 'bucket' in methods:
8594 self.AddFunction(BucketFunction(f))
8595 if 'shm' in methods:
8596 self.AddFunction(f)
8597 else:
8598 self.AddFunction(f)
8600 self.Log("Auto Generated Functions : %d" %
8601 len([f for f in self.functions if f.can_auto_generate or
8602 (not f.IsType('') and not f.IsType('Custom') and
8603 not f.IsType('Todo'))]))
8605 funcs = [f for f in self.functions if not f.can_auto_generate and
8606 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
8607 self.Log("Non Auto Generated Functions: %d" % len(funcs))
8609 for f in funcs:
8610 self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
8612 def WriteCommandIds(self, filename):
8613 """Writes the command buffer format"""
8614 file = CHeaderWriter(filename)
8615 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
8616 id = 256
8617 for func in self.functions:
8618 file.Write(" %-60s /* %d */ \\\n" %
8619 ("OP(%s)" % func.name, id))
8620 id += 1
8621 file.Write("\n")
8623 file.Write("enum CommandId {\n")
8624 file.Write(" kStartPoint = cmd::kLastCommonId, "
8625 "// All GLES2 commands start after this.\n")
8626 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
8627 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
8628 file.Write("#undef GLES2_CMD_OP\n")
8629 file.Write(" kNumCommands\n")
8630 file.Write("};\n")
8631 file.Write("\n")
8632 file.Close()
8633 self.generated_cpp_filenames.append(file.filename)
8635 def WriteFormat(self, filename):
8636 """Writes the command buffer format"""
8637 file = CHeaderWriter(filename)
8638 for func in self.functions:
8639 if True:
8640 #gen_cmd = func.GetInfo('gen_cmd')
8641 #if gen_cmd == True or gen_cmd == None:
8642 func.WriteStruct(file)
8643 file.Write("\n")
8644 file.Close()
8645 self.generated_cpp_filenames.append(file.filename)
8647 def WriteDocs(self, filename):
8648 """Writes the command buffer doc version of the commands"""
8649 file = CWriter(filename)
8650 for func in self.functions:
8651 if True:
8652 #gen_cmd = func.GetInfo('gen_cmd')
8653 #if gen_cmd == True or gen_cmd == None:
8654 func.WriteDocs(file)
8655 file.Write("\n")
8656 file.Close()
8657 self.generated_cpp_filenames.append(file.filename)
8659 def WriteFormatTest(self, filename):
8660 """Writes the command buffer format test."""
8661 file = CHeaderWriter(
8662 filename,
8663 "// This file contains unit tests for gles2 commmands\n"
8664 "// It is included by gles2_cmd_format_test.cc\n"
8665 "\n")
8667 for func in self.functions:
8668 if True:
8669 #gen_cmd = func.GetInfo('gen_cmd')
8670 #if gen_cmd == True or gen_cmd == None:
8671 func.WriteFormatTest(file)
8673 file.Close()
8674 self.generated_cpp_filenames.append(file.filename)
8676 def WriteCmdHelperHeader(self, filename):
8677 """Writes the gles2 command helper."""
8678 file = CHeaderWriter(filename)
8680 for func in self.functions:
8681 if True:
8682 #gen_cmd = func.GetInfo('gen_cmd')
8683 #if gen_cmd == True or gen_cmd == None:
8684 func.WriteCmdHelper(file)
8686 file.Close()
8687 self.generated_cpp_filenames.append(file.filename)
8689 def WriteServiceContextStateHeader(self, filename):
8690 """Writes the service context state header."""
8691 file = CHeaderWriter(
8692 filename,
8693 "// It is included by context_state.h\n")
8694 file.Write("struct EnableFlags {\n")
8695 file.Write(" EnableFlags();\n")
8696 for capability in _CAPABILITY_FLAGS:
8697 file.Write(" bool %s;\n" % capability['name'])
8698 file.Write(" bool cached_%s;\n" % capability['name'])
8699 file.Write("};\n\n")
8701 for state_name in sorted(_STATES.keys()):
8702 state = _STATES[state_name]
8703 for item in state['states']:
8704 if isinstance(item['default'], list):
8705 file.Write("%s %s[%d];\n" % (item['type'], item['name'],
8706 len(item['default'])))
8707 else:
8708 file.Write("%s %s;\n" % (item['type'], item['name']))
8710 if item.get('cached', False):
8711 if isinstance(item['default'], list):
8712 file.Write("%s cached_%s[%d];\n" % (item['type'], item['name'],
8713 len(item['default'])))
8714 else:
8715 file.Write("%s cached_%s;\n" % (item['type'], item['name']))
8717 file.Write("\n")
8719 file.Write("""
8720 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
8721 switch (cap) {
8722 """)
8723 for capability in _CAPABILITY_FLAGS:
8724 file.Write("""\
8725 case GL_%s:
8726 """ % capability['name'].upper())
8727 file.Write("""\
8728 if (enable_flags.cached_%(name)s == enable &&
8729 !ignore_cached_state)
8730 return;
8731 enable_flags.cached_%(name)s = enable;
8732 break;
8733 """ % capability)
8735 file.Write("""\
8736 default:
8737 NOTREACHED();
8738 return;
8740 if (enable)
8741 glEnable(cap);
8742 else
8743 glDisable(cap);
8745 """)
8747 file.Close()
8748 self.generated_cpp_filenames.append(file.filename)
8750 def WriteClientContextStateHeader(self, filename):
8751 """Writes the client context state header."""
8752 file = CHeaderWriter(
8753 filename,
8754 "// It is included by client_context_state.h\n")
8755 file.Write("struct EnableFlags {\n")
8756 file.Write(" EnableFlags();\n")
8757 for capability in _CAPABILITY_FLAGS:
8758 file.Write(" bool %s;\n" % capability['name'])
8759 file.Write("};\n\n")
8761 file.Close()
8762 self.generated_cpp_filenames.append(file.filename)
8764 def WriteContextStateGetters(self, file, class_name):
8765 """Writes the state getters."""
8766 for gl_type in ["GLint", "GLfloat"]:
8767 file.Write("""
8768 bool %s::GetStateAs%s(
8769 GLenum pname, %s* params, GLsizei* num_written) const {
8770 switch (pname) {
8771 """ % (class_name, gl_type, gl_type))
8772 for state_name in sorted(_STATES.keys()):
8773 state = _STATES[state_name]
8774 if 'enum' in state:
8775 file.Write(" case %s:\n" % state['enum'])
8776 file.Write(" *num_written = %d;\n" % len(state['states']))
8777 file.Write(" if (params) {\n")
8778 for ndx,item in enumerate(state['states']):
8779 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
8780 (ndx, gl_type, item['name']))
8781 file.Write(" }\n")
8782 file.Write(" return true;\n")
8783 else:
8784 for item in state['states']:
8785 file.Write(" case %s:\n" % item['enum'])
8786 if isinstance(item['default'], list):
8787 item_len = len(item['default'])
8788 file.Write(" *num_written = %d;\n" % item_len)
8789 file.Write(" if (params) {\n")
8790 if item['type'] == gl_type:
8791 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
8792 (item['name'], item['type'], item_len))
8793 else:
8794 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
8795 item_len)
8796 file.Write(" params[i] = %s;\n" %
8797 (GetGLGetTypeConversion(gl_type, item['type'],
8798 "%s[i]" % item['name'])))
8799 file.Write(" }\n");
8800 else:
8801 file.Write(" *num_written = 1;\n")
8802 file.Write(" if (params) {\n")
8803 file.Write(" params[0] = %s;\n" %
8804 (GetGLGetTypeConversion(gl_type, item['type'],
8805 item['name'])))
8806 file.Write(" }\n")
8807 file.Write(" return true;\n")
8808 for capability in _CAPABILITY_FLAGS:
8809 file.Write(" case GL_%s:\n" % capability['name'].upper())
8810 file.Write(" *num_written = 1;\n")
8811 file.Write(" if (params) {\n")
8812 file.Write(
8813 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
8814 (gl_type, capability['name']))
8815 file.Write(" }\n")
8816 file.Write(" return true;\n")
8817 file.Write(""" default:
8818 return false;
8821 """)
8823 def WriteServiceContextStateImpl(self, filename):
8824 """Writes the context state service implementation."""
8825 file = CHeaderWriter(
8826 filename,
8827 "// It is included by context_state.cc\n")
8828 code = []
8829 for capability in _CAPABILITY_FLAGS:
8830 code.append("%s(%s)" %
8831 (capability['name'],
8832 ('false', 'true')['default' in capability]))
8833 code.append("cached_%s(%s)" %
8834 (capability['name'],
8835 ('false', 'true')['default' in capability]))
8836 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
8837 ",\n ".join(code))
8838 file.Write("\n")
8840 file.Write("void ContextState::Initialize() {\n")
8841 for state_name in sorted(_STATES.keys()):
8842 state = _STATES[state_name]
8843 for item in state['states']:
8844 if isinstance(item['default'], list):
8845 for ndx, value in enumerate(item['default']):
8846 file.Write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
8847 else:
8848 file.Write(" %s = %s;\n" % (item['name'], item['default']))
8849 if item.get('cached', False):
8850 if isinstance(item['default'], list):
8851 for ndx, value in enumerate(item['default']):
8852 file.Write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
8853 else:
8854 file.Write(" cached_%s = %s;\n" % (item['name'], item['default']))
8855 file.Write("}\n")
8857 file.Write("""
8858 void ContextState::InitCapabilities(const ContextState* prev_state) const {
8859 """)
8860 def WriteCapabilities(test_prev):
8861 for capability in _CAPABILITY_FLAGS:
8862 capability_name = capability['name']
8863 if test_prev:
8864 file.Write(""" if (prev_state->enable_flags.cached_%s !=
8865 enable_flags.cached_%s)\n""" %
8866 (capability_name, capability_name))
8867 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
8868 (capability_name.upper(), capability_name))
8870 file.Write(" if (prev_state) {")
8871 WriteCapabilities(True)
8872 file.Write(" } else {")
8873 WriteCapabilities(False)
8874 file.Write(" }")
8876 file.Write("""}
8878 void ContextState::InitState(const ContextState *prev_state) const {
8879 """)
8881 def WriteStates(test_prev):
8882 # We need to sort the keys so the expectations match
8883 for state_name in sorted(_STATES.keys()):
8884 state = _STATES[state_name]
8885 if state['type'] == 'FrontBack':
8886 num_states = len(state['states'])
8887 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
8888 if test_prev:
8889 file.Write(" if (")
8890 args = []
8891 for place, item in enumerate(group):
8892 item_name = CachedStateName(item)
8893 args.append('%s' % item_name)
8894 if test_prev:
8895 if place > 0:
8896 file.Write(' ||\n')
8897 file.Write("(%s != prev_state->%s)" % (item_name, item_name))
8898 if test_prev:
8899 file.Write(")\n")
8900 file.Write(
8901 " gl%s(%s, %s);\n" %
8902 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
8903 elif state['type'] == 'NamedParameter':
8904 for item in state['states']:
8905 item_name = CachedStateName(item)
8907 if 'extension_flag' in item:
8908 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
8909 item['extension_flag'])
8910 if test_prev:
8911 if isinstance(item['default'], list):
8912 file.Write(" if (memcmp(prev_state->%s, %s, "
8913 "sizeof(%s) * %d)) {\n" %
8914 (item_name, item_name, item['type'],
8915 len(item['default'])))
8916 else:
8917 file.Write(" if (prev_state->%s != %s) {\n " %
8918 (item_name, item_name))
8919 file.Write(" gl%s(%s, %s);\n" %
8920 (state['func'],
8921 (item['enum_set']
8922 if 'enum_set' in item else item['enum']),
8923 item['name']))
8924 if test_prev:
8925 if 'extension_flag' in item:
8926 file.Write(" ")
8927 file.Write(" }")
8928 if 'extension_flag' in item:
8929 file.Write(" }")
8930 else:
8931 if 'extension_flag' in state:
8932 file.Write(" if (feature_info_->feature_flags().%s)\n " %
8933 state['extension_flag'])
8934 if test_prev:
8935 file.Write(" if (")
8936 args = []
8937 for place, item in enumerate(state['states']):
8938 item_name = CachedStateName(item)
8939 args.append('%s' % item_name)
8940 if test_prev:
8941 if place > 0:
8942 file.Write(' ||\n')
8943 file.Write("(%s != prev_state->%s)" %
8944 (item_name, item_name))
8945 if test_prev:
8946 file.Write(" )\n")
8947 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
8949 file.Write(" if (prev_state) {")
8950 WriteStates(True)
8951 file.Write(" } else {")
8952 WriteStates(False)
8953 file.Write(" }")
8954 file.Write("}\n")
8956 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
8957 switch (cap) {
8958 """)
8959 for capability in _CAPABILITY_FLAGS:
8960 file.Write(" case GL_%s:\n" % capability['name'].upper())
8961 file.Write(" return enable_flags.%s;\n" % capability['name'])
8962 file.Write(""" default:
8963 NOTREACHED();
8964 return false;
8967 """)
8969 self.WriteContextStateGetters(file, "ContextState")
8970 file.Close()
8971 self.generated_cpp_filenames.append(file.filename)
8973 def WriteClientContextStateImpl(self, filename):
8974 """Writes the context state client side implementation."""
8975 file = CHeaderWriter(
8976 filename,
8977 "// It is included by client_context_state.cc\n")
8978 code = []
8979 for capability in _CAPABILITY_FLAGS:
8980 code.append("%s(%s)" %
8981 (capability['name'],
8982 ('false', 'true')['default' in capability]))
8983 file.Write(
8984 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
8985 ",\n ".join(code))
8986 file.Write("\n")
8988 file.Write("""
8989 bool ClientContextState::SetCapabilityState(
8990 GLenum cap, bool enabled, bool* changed) {
8991 *changed = false;
8992 switch (cap) {
8993 """)
8994 for capability in _CAPABILITY_FLAGS:
8995 file.Write(" case GL_%s:\n" % capability['name'].upper())
8996 file.Write(""" if (enable_flags.%(name)s != enabled) {
8997 *changed = true;
8998 enable_flags.%(name)s = enabled;
9000 return true;
9001 """ % capability)
9002 file.Write(""" default:
9003 return false;
9006 """)
9007 file.Write("""bool ClientContextState::GetEnabled(
9008 GLenum cap, bool* enabled) const {
9009 switch (cap) {
9010 """)
9011 for capability in _CAPABILITY_FLAGS:
9012 file.Write(" case GL_%s:\n" % capability['name'].upper())
9013 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
9014 file.Write(" return true;\n")
9015 file.Write(""" default:
9016 return false;
9019 """)
9020 file.Close()
9021 self.generated_cpp_filenames.append(file.filename)
9023 def WriteServiceImplementation(self, filename):
9024 """Writes the service decorder implementation."""
9025 file = CHeaderWriter(
9026 filename,
9027 "// It is included by gles2_cmd_decoder.cc\n")
9029 for func in self.functions:
9030 if True:
9031 #gen_cmd = func.GetInfo('gen_cmd')
9032 #if gen_cmd == True or gen_cmd == None:
9033 func.WriteServiceImplementation(file)
9035 file.Write("""
9036 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
9037 switch (cap) {
9038 """)
9039 for capability in _CAPABILITY_FLAGS:
9040 file.Write(" case GL_%s:\n" % capability['name'].upper())
9041 if 'state_flag' in capability:
9043 file.Write("""\
9044 state_.enable_flags.%(name)s = enabled;
9045 if (state_.enable_flags.cached_%(name)s != enabled
9046 || state_.ignore_cached_state) {
9047 %(state_flag)s = true;
9049 return false;
9050 """ % capability)
9051 else:
9052 file.Write("""\
9053 state_.enable_flags.%(name)s = enabled;
9054 if (state_.enable_flags.cached_%(name)s != enabled
9055 || state_.ignore_cached_state) {
9056 state_.enable_flags.cached_%(name)s = enabled;
9057 return true;
9059 return false;
9060 """ % capability)
9061 file.Write(""" default:
9062 NOTREACHED();
9063 return false;
9066 """)
9067 file.Close()
9068 self.generated_cpp_filenames.append(file.filename)
9070 def WriteServiceUnitTests(self, filename):
9071 """Writes the service decorder unit tests."""
9072 num_tests = len(self.functions)
9073 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
9074 count = 0
9075 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
9076 count += 1
9077 name = filename % count
9078 file = CHeaderWriter(
9079 name,
9080 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
9081 test_name = 'GLES2DecoderTest%d' % count
9082 end = test_num + FUNCTIONS_PER_FILE
9083 if end > num_tests:
9084 end = num_tests
9085 for idx in range(test_num, end):
9086 func = self.functions[idx]
9088 # Do any filtering of the functions here, so that the functions
9089 # will not move between the numbered files if filtering properties
9090 # are changed.
9091 if func.GetInfo('extension_flag'):
9092 continue
9094 if True:
9095 #gen_cmd = func.GetInfo('gen_cmd')
9096 #if gen_cmd == True or gen_cmd == None:
9097 if func.GetInfo('unit_test') == False:
9098 file.Write("// TODO(gman): %s\n" % func.name)
9099 else:
9100 func.WriteServiceUnitTest(file, {
9101 'test_name': test_name
9103 file.Close()
9104 self.generated_cpp_filenames.append(file.filename)
9105 file = CHeaderWriter(
9106 filename % 0,
9107 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
9108 file.Write(
9109 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
9110 """)
9111 for capability in _CAPABILITY_FLAGS:
9112 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
9113 (capability['name'].upper(),
9114 ('false', 'true')['default' in capability]))
9115 file.Write("""}
9117 void GLES2DecoderTestBase::SetupInitStateExpectations() {
9118 """)
9120 # We need to sort the keys so the expectations match
9121 for state_name in sorted(_STATES.keys()):
9122 state = _STATES[state_name]
9123 if state['type'] == 'FrontBack':
9124 num_states = len(state['states'])
9125 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
9126 args = []
9127 for item in group:
9128 if 'expected' in item:
9129 args.append(item['expected'])
9130 else:
9131 args.append(item['default'])
9132 file.Write(
9133 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
9134 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
9135 file.Write(" .Times(1)\n")
9136 file.Write(" .RetiresOnSaturation();\n")
9137 elif state['type'] == 'NamedParameter':
9138 for item in state['states']:
9139 if 'extension_flag' in item:
9140 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
9141 item['extension_flag'])
9142 file.Write(" ")
9143 expect_value = item['default']
9144 if isinstance(expect_value, list):
9145 # TODO: Currently we do not check array values.
9146 expect_value = "_"
9148 file.Write(
9149 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
9150 (state['func'],
9151 (item['enum_set']
9152 if 'enum_set' in item else item['enum']),
9153 expect_value))
9154 file.Write(" .Times(1)\n")
9155 file.Write(" .RetiresOnSaturation();\n")
9156 if 'extension_flag' in item:
9157 file.Write(" }\n")
9158 else:
9159 if 'extension_flag' in state:
9160 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
9161 state['extension_flag'])
9162 file.Write(" ")
9163 args = []
9164 for item in state['states']:
9165 if 'expected' in item:
9166 args.append(item['expected'])
9167 else:
9168 args.append(item['default'])
9169 # TODO: Currently we do not check array values.
9170 args = ["_" if isinstance(arg, list) else arg for arg in args]
9171 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
9172 (state['func'], ", ".join(args)))
9173 file.Write(" .Times(1)\n")
9174 file.Write(" .RetiresOnSaturation();\n")
9175 if 'extension_flag' in state:
9176 file.Write(" }\n")
9177 file.Write("""}
9178 """)
9179 file.Close()
9180 self.generated_cpp_filenames.append(file.filename)
9182 def WriteServiceUnitTestsForExtensions(self, filename):
9183 """Writes the service decorder unit tests for functions with extension_flag.
9185 The functions are special in that they need a specific unit test
9186 baseclass to turn on the extension.
9188 functions = [f for f in self.functions if f.GetInfo('extension_flag')]
9189 file = CHeaderWriter(
9190 filename,
9191 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
9192 for func in functions:
9193 if True:
9194 if func.GetInfo('unit_test') == False:
9195 file.Write("// TODO(gman): %s\n" % func.name)
9196 else:
9197 extension = ToCamelCase(
9198 ToGLExtensionString(func.GetInfo('extension_flag')))
9199 func.WriteServiceUnitTest(file, {
9200 'test_name': 'GLES2DecoderTestWith%s' % extension
9203 file.Close()
9204 self.generated_cpp_filenames.append(file.filename)
9206 def WriteGLES2Header(self, filename):
9207 """Writes the GLES2 header."""
9208 file = CHeaderWriter(
9209 filename,
9210 "// This file contains Chromium-specific GLES2 declarations.\n\n")
9212 for func in self.original_functions:
9213 func.WriteGLES2Header(file)
9215 file.Write("\n")
9216 file.Close()
9217 self.generated_cpp_filenames.append(file.filename)
9219 def WriteGLES2CLibImplementation(self, filename):
9220 """Writes the GLES2 c lib implementation."""
9221 file = CHeaderWriter(
9222 filename,
9223 "// These functions emulate GLES2 over command buffers.\n")
9225 for func in self.original_functions:
9226 func.WriteGLES2CLibImplementation(file)
9228 file.Write("""
9229 namespace gles2 {
9231 extern const NameToFunc g_gles2_function_table[] = {
9232 """)
9233 for func in self.original_functions:
9234 file.Write(
9235 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
9236 (func.name, func.name))
9237 file.Write(""" { NULL, NULL, },
9240 } // namespace gles2
9241 """)
9242 file.Close()
9243 self.generated_cpp_filenames.append(file.filename)
9245 def WriteGLES2InterfaceHeader(self, filename):
9246 """Writes the GLES2 interface header."""
9247 file = CHeaderWriter(
9248 filename,
9249 "// This file is included by gles2_interface.h to declare the\n"
9250 "// GL api functions.\n")
9251 for func in self.original_functions:
9252 func.WriteGLES2InterfaceHeader(file)
9253 file.Close()
9254 self.generated_cpp_filenames.append(file.filename)
9256 def WriteGLES2InterfaceStub(self, filename):
9257 """Writes the GLES2 interface stub header."""
9258 file = CHeaderWriter(
9259 filename,
9260 "// This file is included by gles2_interface_stub.h.\n")
9261 for func in self.original_functions:
9262 func.WriteGLES2InterfaceStub(file)
9263 file.Close()
9264 self.generated_cpp_filenames.append(file.filename)
9266 def WriteGLES2InterfaceStubImpl(self, filename):
9267 """Writes the GLES2 interface header."""
9268 file = CHeaderWriter(
9269 filename,
9270 "// This file is included by gles2_interface_stub.cc.\n")
9271 for func in self.original_functions:
9272 func.WriteGLES2InterfaceStubImpl(file)
9273 file.Close()
9274 self.generated_cpp_filenames.append(file.filename)
9276 def WriteGLES2ImplementationHeader(self, filename):
9277 """Writes the GLES2 Implementation header."""
9278 file = CHeaderWriter(
9279 filename,
9280 "// This file is included by gles2_implementation.h to declare the\n"
9281 "// GL api functions.\n")
9282 for func in self.original_functions:
9283 func.WriteGLES2ImplementationHeader(file)
9284 file.Close()
9285 self.generated_cpp_filenames.append(file.filename)
9287 def WriteGLES2Implementation(self, filename):
9288 """Writes the GLES2 Implementation."""
9289 file = CHeaderWriter(
9290 filename,
9291 "// This file is included by gles2_implementation.cc to define the\n"
9292 "// GL api functions.\n")
9293 for func in self.original_functions:
9294 func.WriteGLES2Implementation(file)
9295 file.Close()
9296 self.generated_cpp_filenames.append(file.filename)
9298 def WriteGLES2TraceImplementationHeader(self, filename):
9299 """Writes the GLES2 Trace Implementation header."""
9300 file = CHeaderWriter(
9301 filename,
9302 "// This file is included by gles2_trace_implementation.h\n")
9303 for func in self.original_functions:
9304 func.WriteGLES2TraceImplementationHeader(file)
9305 file.Close()
9306 self.generated_cpp_filenames.append(file.filename)
9308 def WriteGLES2TraceImplementation(self, filename):
9309 """Writes the GLES2 Trace Implementation."""
9310 file = CHeaderWriter(
9311 filename,
9312 "// This file is included by gles2_trace_implementation.cc\n")
9313 for func in self.original_functions:
9314 func.WriteGLES2TraceImplementation(file)
9315 file.Close()
9316 self.generated_cpp_filenames.append(file.filename)
9318 def WriteGLES2ImplementationUnitTests(self, filename):
9319 """Writes the GLES2 helper header."""
9320 file = CHeaderWriter(
9321 filename,
9322 "// This file is included by gles2_implementation.h to declare the\n"
9323 "// GL api functions.\n")
9324 for func in self.original_functions:
9325 func.WriteGLES2ImplementationUnitTest(file)
9326 file.Close()
9327 self.generated_cpp_filenames.append(file.filename)
9329 def WriteServiceUtilsHeader(self, filename):
9330 """Writes the gles2 auto generated utility header."""
9331 file = CHeaderWriter(filename)
9332 for name in sorted(_NAMED_TYPE_INFO.keys()):
9333 named_type = NamedType(_NAMED_TYPE_INFO[name])
9334 if named_type.IsConstant():
9335 continue
9336 file.Write("ValueValidator<%s> %s;\n" %
9337 (named_type.GetType(), ToUnderscore(name)))
9338 file.Write("\n")
9339 file.Close()
9340 self.generated_cpp_filenames.append(file.filename)
9342 def WriteServiceUtilsImplementation(self, filename):
9343 """Writes the gles2 auto generated utility implementation."""
9344 file = CHeaderWriter(filename)
9345 names = sorted(_NAMED_TYPE_INFO.keys())
9346 for name in names:
9347 named_type = NamedType(_NAMED_TYPE_INFO[name])
9348 if named_type.IsConstant():
9349 continue
9350 if named_type.GetValidValues():
9351 file.Write("static const %s valid_%s_table[] = {\n" %
9352 (named_type.GetType(), ToUnderscore(name)))
9353 for value in named_type.GetValidValues():
9354 file.Write(" %s,\n" % value)
9355 file.Write("};\n")
9356 file.Write("\n")
9357 file.Write("Validators::Validators()")
9358 pre = ' : '
9359 for count, name in enumerate(names):
9360 named_type = NamedType(_NAMED_TYPE_INFO[name])
9361 if named_type.IsConstant():
9362 continue
9363 if named_type.GetValidValues():
9364 code = """%(pre)s%(name)s(
9365 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
9366 else:
9367 code = "%(pre)s%(name)s()"
9368 file.Write(code % {
9369 'name': ToUnderscore(name),
9370 'pre': pre,
9372 pre = ',\n '
9373 file.Write(" {\n");
9374 file.Write("}\n\n");
9375 file.Close()
9376 self.generated_cpp_filenames.append(file.filename)
9378 def WriteCommonUtilsHeader(self, filename):
9379 """Writes the gles2 common utility header."""
9380 file = CHeaderWriter(filename)
9381 type_infos = sorted(_NAMED_TYPE_INFO.keys())
9382 for type_info in type_infos:
9383 if _NAMED_TYPE_INFO[type_info]['type'] == 'GLenum':
9384 file.Write("static std::string GetString%s(uint32_t value);\n" %
9385 type_info)
9386 file.Write("\n")
9387 file.Close()
9388 self.generated_cpp_filenames.append(file.filename)
9390 def WriteCommonUtilsImpl(self, filename):
9391 """Writes the gles2 common utility header."""
9392 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
9393 dict = {}
9394 for fname in ['third_party/khronos/GLES2/gl2.h',
9395 'third_party/khronos/GLES2/gl2ext.h',
9396 'third_party/khronos/GLES3/gl3.h',
9397 'gpu/GLES2/gl2chromium.h',
9398 'gpu/GLES2/gl2extchromium.h']:
9399 lines = open(fname).readlines()
9400 for line in lines:
9401 m = enum_re.match(line)
9402 if m:
9403 name = m.group(1)
9404 value = m.group(2)
9405 if len(value) <= 10:
9406 if not value in dict:
9407 dict[value] = name
9408 # check our own _CHROMIUM macro conflicts with khronos GL headers.
9409 elif dict[value] != name and (name.endswith('_CHROMIUM') or
9410 dict[value].endswith('_CHROMIUM')):
9411 self.Error("code collision: %s and %s have the same code %s" %
9412 (dict[value], name, value))
9414 file = CHeaderWriter(filename)
9415 file.Write("static const GLES2Util::EnumToString "
9416 "enum_to_string_table[] = {\n")
9417 for value in dict:
9418 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
9419 file.Write("""};
9421 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
9422 enum_to_string_table;
9423 const size_t GLES2Util::enum_to_string_table_len_ =
9424 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
9426 """)
9428 enums = sorted(_NAMED_TYPE_INFO.keys())
9429 for enum in enums:
9430 if _NAMED_TYPE_INFO[enum]['type'] == 'GLenum':
9431 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
9432 enum)
9433 if len(_NAMED_TYPE_INFO[enum]['valid']) > 0:
9434 file.Write(" static const EnumToString string_table[] = {\n")
9435 for value in _NAMED_TYPE_INFO[enum]['valid']:
9436 file.Write(' { %s, "%s" },\n' % (value, value))
9437 file.Write(""" };
9438 return GLES2Util::GetQualifiedEnumString(
9439 string_table, arraysize(string_table), value);
9442 """)
9443 else:
9444 file.Write(""" return GLES2Util::GetQualifiedEnumString(
9445 NULL, 0, value);
9448 """)
9449 file.Close()
9450 self.generated_cpp_filenames.append(file.filename)
9452 def WritePepperGLES2Interface(self, filename, dev):
9453 """Writes the Pepper OpenGLES interface definition."""
9454 file = CWriter(filename)
9455 file.Write(_LICENSE)
9456 file.Write(_DO_NOT_EDIT_WARNING)
9458 file.Write("label Chrome {\n")
9459 file.Write(" M39 = 1.0\n")
9460 file.Write("};\n\n")
9462 if not dev:
9463 # Declare GL types.
9464 file.Write("[version=1.0]\n")
9465 file.Write("describe {\n")
9466 for gltype in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
9467 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
9468 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
9469 'GLubyte', 'GLuint', 'GLushort']:
9470 file.Write(" %s;\n" % gltype)
9471 file.Write(" %s_ptr_t;\n" % gltype)
9472 file.Write("};\n\n")
9474 # C level typedefs.
9475 file.Write("#inline c\n")
9476 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
9477 if dev:
9478 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
9479 else:
9480 file.Write("\n#ifndef __gl2_h_\n")
9481 for (k, v) in _GL_TYPES.iteritems():
9482 file.Write("typedef %s %s;\n" % (v, k))
9483 file.Write("#ifdef _WIN64\n")
9484 for (k, v) in _GL_TYPES_64.iteritems():
9485 file.Write("typedef %s %s;\n" % (v, k))
9486 file.Write("#else\n")
9487 for (k, v) in _GL_TYPES_32.iteritems():
9488 file.Write("typedef %s %s;\n" % (v, k))
9489 file.Write("#endif // _WIN64\n")
9490 file.Write("#endif // __gl2_h_\n\n")
9491 file.Write("#endinl\n")
9493 for interface in self.pepper_interfaces:
9494 if interface.dev != dev:
9495 continue
9496 # Historically, we provide OpenGLES2 interfaces with struct
9497 # namespace. Not to break code which uses the interface as
9498 # "struct OpenGLES2", we put it in struct namespace.
9499 file.Write('\n[macro="%s", force_struct_namespace]\n' %
9500 interface.GetInterfaceName())
9501 file.Write("interface %s {\n" % interface.GetStructName())
9502 for func in self.original_functions:
9503 if not func.InPepperInterface(interface):
9504 continue
9506 ret_type = func.MapCTypeToPepperIdlType(func.return_type,
9507 is_for_return_type=True)
9508 func_prefix = " %s %s(" % (ret_type, func.GetPepperName())
9509 file.Write(func_prefix)
9510 file.Write("[in] PP_Resource context")
9511 for arg in func.MakeTypedPepperIdlArgStrings():
9512 file.Write(",\n" + " " * len(func_prefix) + arg)
9513 file.Write(");\n")
9514 file.Write("};\n\n")
9517 file.Close()
9519 def WritePepperGLES2Implementation(self, filename):
9520 """Writes the Pepper OpenGLES interface implementation."""
9522 file = CWriter(filename)
9523 file.Write(_LICENSE)
9524 file.Write(_DO_NOT_EDIT_WARNING)
9526 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
9527 file.Write("#include \"base/logging.h\"\n")
9528 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
9529 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
9530 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
9532 file.Write("namespace ppapi {\n\n")
9533 file.Write("namespace {\n\n")
9535 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
9536 " Enter3D;\n\n")
9538 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
9539 " enter) {\n")
9540 file.Write(" DCHECK(enter);\n")
9541 file.Write(" DCHECK(enter->succeeded());\n")
9542 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
9543 "gles2_impl();\n");
9544 file.Write("}\n\n");
9546 for func in self.original_functions:
9547 if not func.InAnyPepperExtension():
9548 continue
9550 original_arg = func.MakeTypedPepperArgString("")
9551 context_arg = "PP_Resource context_id"
9552 if len(original_arg):
9553 arg = context_arg + ", " + original_arg
9554 else:
9555 arg = context_arg
9556 file.Write("%s %s(%s) {\n" %
9557 (func.return_type, func.GetPepperName(), arg))
9558 file.Write(" Enter3D enter(context_id, true);\n")
9559 file.Write(" if (enter.succeeded()) {\n")
9561 return_str = "" if func.return_type == "void" else "return "
9562 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
9563 (return_str, func.original_name,
9564 func.MakeOriginalArgString("")))
9565 file.Write(" }")
9566 if func.return_type == "void":
9567 file.Write("\n")
9568 else:
9569 file.Write(" else {\n")
9570 file.Write(" return %s;\n" % func.GetErrorReturnString())
9571 file.Write(" }\n")
9572 file.Write("}\n\n")
9574 file.Write("} // namespace\n")
9576 for interface in self.pepper_interfaces:
9577 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
9578 (interface.GetStructName(), interface.GetName()))
9579 file.Write(" static const struct %s "
9580 "ppb_opengles2 = {\n" % interface.GetStructName())
9581 file.Write(" &")
9582 file.Write(",\n &".join(
9583 f.GetPepperName() for f in self.original_functions
9584 if f.InPepperInterface(interface)))
9585 file.Write("\n")
9587 file.Write(" };\n")
9588 file.Write(" return &ppb_opengles2;\n")
9589 file.Write("}\n")
9591 file.Write("} // namespace ppapi\n")
9592 file.Close()
9593 self.generated_cpp_filenames.append(file.filename)
9595 def WriteGLES2ToPPAPIBridge(self, filename):
9596 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
9598 file = CWriter(filename)
9599 file.Write(_LICENSE)
9600 file.Write(_DO_NOT_EDIT_WARNING)
9602 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
9603 file.Write("#define GL_GLEXT_PROTOTYPES\n")
9604 file.Write("#endif\n")
9605 file.Write("#include <GLES2/gl2.h>\n")
9606 file.Write("#include <GLES2/gl2ext.h>\n")
9607 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
9609 for func in self.original_functions:
9610 if not func.InAnyPepperExtension():
9611 continue
9613 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
9615 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
9616 (func.return_type, func.GetPepperName(),
9617 func.MakeTypedPepperArgString("")))
9618 return_str = "" if func.return_type == "void" else "return "
9619 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
9620 original_arg = func.MakeOriginalArgString("")
9621 context_arg = "glGetCurrentContextPPAPI()"
9622 if len(original_arg):
9623 arg = context_arg + ", " + original_arg
9624 else:
9625 arg = context_arg
9626 if interface.GetName():
9627 file.Write(" const struct %s* ext = %s;\n" %
9628 (interface.GetStructName(), interface_str))
9629 file.Write(" if (ext)\n")
9630 file.Write(" %sext->%s(%s);\n" %
9631 (return_str, func.GetPepperName(), arg))
9632 if return_str:
9633 file.Write(" %s0;\n" % return_str)
9634 else:
9635 file.Write(" %s%s->%s(%s);\n" %
9636 (return_str, interface_str, func.GetPepperName(), arg))
9637 file.Write("}\n\n")
9638 file.Close()
9639 self.generated_cpp_filenames.append(file.filename)
9641 def WriteMojoGLCallVisitor(self, filename):
9642 """Provides the GL implementation for mojo"""
9643 file = CWriter(filename)
9644 file.Write(_LICENSE)
9645 file.Write(_DO_NOT_EDIT_WARNING)
9647 for func in self.original_functions:
9648 if not func.IsCoreGLFunction():
9649 continue
9650 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
9651 (func.name, func.return_type,
9652 func.MakeTypedOriginalArgString(""),
9653 func.MakeOriginalArgString("")))
9655 file.Close()
9656 self.generated_cpp_filenames.append(file.filename)
9658 def WriteMojoGLCallVisitorForExtension(self, filename, extension):
9659 """Provides the GL implementation for mojo for a particular extension"""
9660 file = CWriter(filename)
9661 file.Write(_LICENSE)
9662 file.Write(_DO_NOT_EDIT_WARNING)
9664 for func in self.original_functions:
9665 if func.GetInfo("extension") != extension:
9666 continue
9667 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
9668 (func.name, func.return_type,
9669 func.MakeTypedOriginalArgString(""),
9670 func.MakeOriginalArgString("")))
9672 file.Close()
9673 self.generated_cpp_filenames.append(file.filename)
9675 def Format(generated_files):
9676 formatter = "clang-format"
9677 if platform.system() == "Windows":
9678 formatter += ".bat"
9679 for filename in generated_files:
9680 call([formatter, "-i", "-style=chromium", filename])
9682 def main(argv):
9683 """This is the main function."""
9684 parser = OptionParser()
9685 parser.add_option(
9686 "--output-dir",
9687 help="base directory for resulting files, under chrome/src. default is "
9688 "empty. Use this if you want the result stored under gen.")
9689 parser.add_option(
9690 "-v", "--verbose", action="store_true",
9691 help="prints more output.")
9693 (options, args) = parser.parse_args(args=argv)
9695 # Add in states and capabilites to GLState
9696 gl_state_valid = _NAMED_TYPE_INFO['GLState']['valid']
9697 for state_name in sorted(_STATES.keys()):
9698 state = _STATES[state_name]
9699 if 'extension_flag' in state:
9700 continue
9701 if 'enum' in state:
9702 if not state['enum'] in gl_state_valid:
9703 gl_state_valid.append(state['enum'])
9704 else:
9705 for item in state['states']:
9706 if 'extension_flag' in item:
9707 continue
9708 if not item['enum'] in gl_state_valid:
9709 gl_state_valid.append(item['enum'])
9710 for capability in _CAPABILITY_FLAGS:
9711 valid_value = "GL_%s" % capability['name'].upper()
9712 if not valid_value in gl_state_valid:
9713 gl_state_valid.append(valid_value)
9715 # This script lives under gpu/command_buffer, cd to base directory.
9716 os.chdir(os.path.dirname(__file__) + "/../..")
9717 base_dir = os.getcwd()
9718 gen = GLGenerator(options.verbose)
9719 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
9721 # Support generating files under gen/
9722 if options.output_dir != None:
9723 os.chdir(options.output_dir)
9725 gen.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
9726 gen.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
9727 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
9728 gen.WritePepperGLES2Implementation(
9729 "ppapi/shared_impl/ppb_opengles2_shared.cc")
9730 os.chdir(base_dir)
9731 gen.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
9732 gen.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
9733 gen.WriteFormatTest(
9734 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
9735 gen.WriteGLES2InterfaceHeader(
9736 "gpu/command_buffer/client/gles2_interface_autogen.h")
9737 gen.WriteGLES2InterfaceStub(
9738 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
9739 gen.WriteGLES2InterfaceStubImpl(
9740 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
9741 gen.WriteGLES2ImplementationHeader(
9742 "gpu/command_buffer/client/gles2_implementation_autogen.h")
9743 gen.WriteGLES2Implementation(
9744 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
9745 gen.WriteGLES2ImplementationUnitTests(
9746 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
9747 gen.WriteGLES2TraceImplementationHeader(
9748 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
9749 gen.WriteGLES2TraceImplementation(
9750 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
9751 gen.WriteGLES2CLibImplementation(
9752 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
9753 gen.WriteCmdHelperHeader(
9754 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
9755 gen.WriteServiceImplementation(
9756 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
9757 gen.WriteServiceContextStateHeader(
9758 "gpu/command_buffer/service/context_state_autogen.h")
9759 gen.WriteServiceContextStateImpl(
9760 "gpu/command_buffer/service/context_state_impl_autogen.h")
9761 gen.WriteClientContextStateHeader(
9762 "gpu/command_buffer/client/client_context_state_autogen.h")
9763 gen.WriteClientContextStateImpl(
9764 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
9765 gen.WriteServiceUnitTests(
9766 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
9767 gen.WriteServiceUnitTestsForExtensions(
9768 "gpu/command_buffer/service/"
9769 "gles2_cmd_decoder_unittest_extensions_autogen.h")
9770 gen.WriteServiceUtilsHeader(
9771 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
9772 gen.WriteServiceUtilsImplementation(
9773 "gpu/command_buffer/service/"
9774 "gles2_cmd_validation_implementation_autogen.h")
9775 gen.WriteCommonUtilsHeader(
9776 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
9777 gen.WriteCommonUtilsImpl(
9778 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
9779 gen.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
9780 mojo_gles2_prefix = ("third_party/mojo/src/mojo/public/c/gles2/"
9781 "gles2_call_visitor")
9782 gen.WriteMojoGLCallVisitor(mojo_gles2_prefix + "_autogen.h")
9783 gen.WriteMojoGLCallVisitorForExtension(
9784 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
9785 "CHROMIUM_texture_mailbox")
9786 gen.WriteMojoGLCallVisitorForExtension(
9787 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
9788 "CHROMIUM_sync_point")
9790 Format(gen.generated_cpp_filenames)
9792 if gen.errors > 0:
9793 print "%d errors" % gen.errors
9794 return 1
9795 return 0
9798 if __name__ == '__main__':
9799 sys.exit(main(sys.argv[1:]))