Android Chromoting: Remove exit-fullscreen button.
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blob040703352c1b382c0f0e3ec2fe58a064582b045b
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'},
85 {'name': 'rasterizer_discard', 'es3': True},
88 _STATES = {
89 'ClearColor': {
90 'type': 'Normal',
91 'func': 'ClearColor',
92 'enum': 'GL_COLOR_CLEAR_VALUE',
93 'states': [
94 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
95 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
97 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
100 'ClearDepthf': {
101 'type': 'Normal',
102 'func': 'ClearDepth',
103 'enum': 'GL_DEPTH_CLEAR_VALUE',
104 'states': [
105 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
108 'ColorMask': {
109 'type': 'Normal',
110 'func': 'ColorMask',
111 'enum': 'GL_COLOR_WRITEMASK',
112 'states': [
114 'name': 'color_mask_red',
115 'type': 'GLboolean',
116 'default': 'true',
117 'cached': True
120 'name': 'color_mask_green',
121 'type': 'GLboolean',
122 'default': 'true',
123 'cached': True
126 'name': 'color_mask_blue',
127 'type': 'GLboolean',
128 'default': 'true',
129 'cached': True
132 'name': 'color_mask_alpha',
133 'type': 'GLboolean',
134 'default': 'true',
135 'cached': True
138 'state_flag': 'framebuffer_state_.clear_state_dirty',
140 'ClearStencil': {
141 'type': 'Normal',
142 'func': 'ClearStencil',
143 'enum': 'GL_STENCIL_CLEAR_VALUE',
144 'states': [
145 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
148 'BlendColor': {
149 'type': 'Normal',
150 'func': 'BlendColor',
151 'enum': 'GL_BLEND_COLOR',
152 'states': [
153 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
154 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
155 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
156 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
159 'BlendEquation': {
160 'type': 'SrcDst',
161 'func': 'BlendEquationSeparate',
162 'states': [
164 'name': 'blend_equation_rgb',
165 'type': 'GLenum',
166 'enum': 'GL_BLEND_EQUATION_RGB',
167 'default': 'GL_FUNC_ADD',
170 'name': 'blend_equation_alpha',
171 'type': 'GLenum',
172 'enum': 'GL_BLEND_EQUATION_ALPHA',
173 'default': 'GL_FUNC_ADD',
177 'BlendFunc': {
178 'type': 'SrcDst',
179 'func': 'BlendFuncSeparate',
180 'states': [
182 'name': 'blend_source_rgb',
183 'type': 'GLenum',
184 'enum': 'GL_BLEND_SRC_RGB',
185 'default': 'GL_ONE',
188 'name': 'blend_dest_rgb',
189 'type': 'GLenum',
190 'enum': 'GL_BLEND_DST_RGB',
191 'default': 'GL_ZERO',
194 'name': 'blend_source_alpha',
195 'type': 'GLenum',
196 'enum': 'GL_BLEND_SRC_ALPHA',
197 'default': 'GL_ONE',
200 'name': 'blend_dest_alpha',
201 'type': 'GLenum',
202 'enum': 'GL_BLEND_DST_ALPHA',
203 'default': 'GL_ZERO',
207 'PolygonOffset': {
208 'type': 'Normal',
209 'func': 'PolygonOffset',
210 'states': [
212 'name': 'polygon_offset_factor',
213 'type': 'GLfloat',
214 'enum': 'GL_POLYGON_OFFSET_FACTOR',
215 'default': '0.0f',
218 'name': 'polygon_offset_units',
219 'type': 'GLfloat',
220 'enum': 'GL_POLYGON_OFFSET_UNITS',
221 'default': '0.0f',
225 'CullFace': {
226 'type': 'Normal',
227 'func': 'CullFace',
228 'enum': 'GL_CULL_FACE_MODE',
229 'states': [
231 'name': 'cull_mode',
232 'type': 'GLenum',
233 'default': 'GL_BACK',
237 'FrontFace': {
238 'type': 'Normal',
239 'func': 'FrontFace',
240 'enum': 'GL_FRONT_FACE',
241 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
243 'DepthFunc': {
244 'type': 'Normal',
245 'func': 'DepthFunc',
246 'enum': 'GL_DEPTH_FUNC',
247 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
249 'DepthRange': {
250 'type': 'Normal',
251 'func': 'DepthRange',
252 'enum': 'GL_DEPTH_RANGE',
253 'states': [
254 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
255 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
258 'SampleCoverage': {
259 'type': 'Normal',
260 'func': 'SampleCoverage',
261 'states': [
263 'name': 'sample_coverage_value',
264 'type': 'GLclampf',
265 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
266 'default': '1.0f',
269 'name': 'sample_coverage_invert',
270 'type': 'GLboolean',
271 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
272 'default': 'false',
276 'StencilMask': {
277 'type': 'FrontBack',
278 'func': 'StencilMaskSeparate',
279 'state_flag': 'framebuffer_state_.clear_state_dirty',
280 'states': [
282 'name': 'stencil_front_writemask',
283 'type': 'GLuint',
284 'enum': 'GL_STENCIL_WRITEMASK',
285 'default': '0xFFFFFFFFU',
286 'cached': True,
289 'name': 'stencil_back_writemask',
290 'type': 'GLuint',
291 'enum': 'GL_STENCIL_BACK_WRITEMASK',
292 'default': '0xFFFFFFFFU',
293 'cached': True,
297 'StencilOp': {
298 'type': 'FrontBack',
299 'func': 'StencilOpSeparate',
300 'states': [
302 'name': 'stencil_front_fail_op',
303 'type': 'GLenum',
304 'enum': 'GL_STENCIL_FAIL',
305 'default': 'GL_KEEP',
308 'name': 'stencil_front_z_fail_op',
309 'type': 'GLenum',
310 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
311 'default': 'GL_KEEP',
314 'name': 'stencil_front_z_pass_op',
315 'type': 'GLenum',
316 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
317 'default': 'GL_KEEP',
320 'name': 'stencil_back_fail_op',
321 'type': 'GLenum',
322 'enum': 'GL_STENCIL_BACK_FAIL',
323 'default': 'GL_KEEP',
326 'name': 'stencil_back_z_fail_op',
327 'type': 'GLenum',
328 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
329 'default': 'GL_KEEP',
332 'name': 'stencil_back_z_pass_op',
333 'type': 'GLenum',
334 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
335 'default': 'GL_KEEP',
339 'StencilFunc': {
340 'type': 'FrontBack',
341 'func': 'StencilFuncSeparate',
342 'states': [
344 'name': 'stencil_front_func',
345 'type': 'GLenum',
346 'enum': 'GL_STENCIL_FUNC',
347 'default': 'GL_ALWAYS',
350 'name': 'stencil_front_ref',
351 'type': 'GLint',
352 'enum': 'GL_STENCIL_REF',
353 'default': '0',
356 'name': 'stencil_front_mask',
357 'type': 'GLuint',
358 'enum': 'GL_STENCIL_VALUE_MASK',
359 'default': '0xFFFFFFFFU',
362 'name': 'stencil_back_func',
363 'type': 'GLenum',
364 'enum': 'GL_STENCIL_BACK_FUNC',
365 'default': 'GL_ALWAYS',
368 'name': 'stencil_back_ref',
369 'type': 'GLint',
370 'enum': 'GL_STENCIL_BACK_REF',
371 'default': '0',
374 'name': 'stencil_back_mask',
375 'type': 'GLuint',
376 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
377 'default': '0xFFFFFFFFU',
381 'Hint': {
382 'type': 'NamedParameter',
383 'func': 'Hint',
384 'states': [
386 'name': 'hint_generate_mipmap',
387 'type': 'GLenum',
388 'enum': 'GL_GENERATE_MIPMAP_HINT',
389 'default': 'GL_DONT_CARE',
390 'gl_version_flag': '!is_desktop_core_profile'
393 'name': 'hint_fragment_shader_derivative',
394 'type': 'GLenum',
395 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
396 'default': 'GL_DONT_CARE',
397 'extension_flag': 'oes_standard_derivatives'
401 'PixelStore': {
402 'type': 'NamedParameter',
403 'func': 'PixelStorei',
404 'states': [
406 'name': 'pack_alignment',
407 'type': 'GLint',
408 'enum': 'GL_PACK_ALIGNMENT',
409 'default': '4'
412 'name': 'unpack_alignment',
413 'type': 'GLint',
414 'enum': 'GL_UNPACK_ALIGNMENT',
415 'default': '4'
419 # TODO: Consider implemenenting these states
420 # GL_ACTIVE_TEXTURE
421 'LineWidth': {
422 'type': 'Normal',
423 'func': 'LineWidth',
424 'enum': 'GL_LINE_WIDTH',
425 'states': [
427 'name': 'line_width',
428 'type': 'GLfloat',
429 'default': '1.0f',
430 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
431 'nan_check': True,
434 'DepthMask': {
435 'type': 'Normal',
436 'func': 'DepthMask',
437 'enum': 'GL_DEPTH_WRITEMASK',
438 'states': [
440 'name': 'depth_mask',
441 'type': 'GLboolean',
442 'default': 'true',
443 'cached': True
446 'state_flag': 'framebuffer_state_.clear_state_dirty',
448 'Scissor': {
449 'type': 'Normal',
450 'func': 'Scissor',
451 'enum': 'GL_SCISSOR_BOX',
452 'states': [
453 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
455 'name': 'scissor_x',
456 'type': 'GLint',
457 'default': '0',
458 'expected': 'kViewportX',
461 'name': 'scissor_y',
462 'type': 'GLint',
463 'default': '0',
464 'expected': 'kViewportY',
467 'name': 'scissor_width',
468 'type': 'GLsizei',
469 'default': '1',
470 'expected': 'kViewportWidth',
473 'name': 'scissor_height',
474 'type': 'GLsizei',
475 'default': '1',
476 'expected': 'kViewportHeight',
480 'Viewport': {
481 'type': 'Normal',
482 'func': 'Viewport',
483 'enum': 'GL_VIEWPORT',
484 'states': [
485 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
487 'name': 'viewport_x',
488 'type': 'GLint',
489 'default': '0',
490 'expected': 'kViewportX',
493 'name': 'viewport_y',
494 'type': 'GLint',
495 'default': '0',
496 'expected': 'kViewportY',
499 'name': 'viewport_width',
500 'type': 'GLsizei',
501 'default': '1',
502 'expected': 'kViewportWidth',
505 'name': 'viewport_height',
506 'type': 'GLsizei',
507 'default': '1',
508 'expected': 'kViewportHeight',
512 'MatrixValuesCHROMIUM': {
513 'type': 'NamedParameter',
514 'func': 'MatrixLoadfEXT',
515 'states': [
516 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
517 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
518 'name': 'modelview_matrix',
519 'type': 'GLfloat',
520 'default': [
521 '1.0f', '0.0f','0.0f','0.0f',
522 '0.0f', '1.0f','0.0f','0.0f',
523 '0.0f', '0.0f','1.0f','0.0f',
524 '0.0f', '0.0f','0.0f','1.0f',
526 'extension_flag': 'chromium_path_rendering',
528 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
529 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
530 'name': 'projection_matrix',
531 'type': 'GLfloat',
532 'default': [
533 '1.0f', '0.0f','0.0f','0.0f',
534 '0.0f', '1.0f','0.0f','0.0f',
535 '0.0f', '0.0f','1.0f','0.0f',
536 '0.0f', '0.0f','0.0f','1.0f',
538 'extension_flag': 'chromium_path_rendering',
544 # Named type info object represents a named type that is used in OpenGL call
545 # arguments. Each named type defines a set of valid OpenGL call arguments. The
546 # named types are used in 'cmd_buffer_functions.txt'.
547 # type: The actual GL type of the named type.
548 # valid: The list of values that are valid for both the client and the service.
549 # valid_es3: The list of values that are valid in OpenGL ES 3, but not ES 2.
550 # invalid: Examples of invalid values for the type. At least these values
551 # should be tested to be invalid.
552 # deprecated_es3: The list of values that are valid in OpenGL ES 2, but
553 # deprecated in ES 3.
554 # is_complete: The list of valid values of type are final and will not be
555 # modified during runtime.
556 _NAMED_TYPE_INFO = {
557 'BlitFilter': {
558 'type': 'GLenum',
559 'valid': [
560 'GL_NEAREST',
561 'GL_LINEAR',
563 'invalid': [
564 'GL_LINEAR_MIPMAP_LINEAR',
567 'FrameBufferTarget': {
568 'type': 'GLenum',
569 'valid': [
570 'GL_FRAMEBUFFER',
572 'invalid': [
573 'GL_DRAW_FRAMEBUFFER' ,
574 'GL_READ_FRAMEBUFFER' ,
577 'RenderBufferTarget': {
578 'type': 'GLenum',
579 'valid': [
580 'GL_RENDERBUFFER',
582 'invalid': [
583 'GL_FRAMEBUFFER',
586 'BufferTarget': {
587 'type': 'GLenum',
588 'valid': [
589 'GL_ARRAY_BUFFER',
590 'GL_ELEMENT_ARRAY_BUFFER',
592 'valid_es3': [
593 'GL_COPY_READ_BUFFER',
594 'GL_COPY_WRITE_BUFFER',
595 'GL_PIXEL_PACK_BUFFER',
596 'GL_PIXEL_UNPACK_BUFFER',
597 'GL_TRANSFORM_FEEDBACK_BUFFER',
598 'GL_UNIFORM_BUFFER',
600 'invalid': [
601 'GL_RENDERBUFFER',
604 'IndexedBufferTarget': {
605 'type': 'GLenum',
606 'valid': [
607 'GL_TRANSFORM_FEEDBACK_BUFFER',
608 'GL_UNIFORM_BUFFER',
610 'invalid': [
611 'GL_RENDERBUFFER',
614 'MapBufferAccess': {
615 'type': 'GLenum',
616 'valid': [
617 'GL_MAP_READ_BIT',
618 'GL_MAP_WRITE_BIT',
619 'GL_MAP_INVALIDATE_RANGE_BIT',
620 'GL_MAP_INVALIDATE_BUFFER_BIT',
621 'GL_MAP_FLUSH_EXPLICIT_BIT',
622 'GL_MAP_UNSYNCHRONIZED_BIT',
624 'invalid': [
625 'GL_SYNC_FLUSH_COMMANDS_BIT',
628 'Bufferiv': {
629 'type': 'GLenum',
630 'valid': [
631 'GL_COLOR',
632 'GL_STENCIL',
634 'invalid': [
635 'GL_RENDERBUFFER',
638 'Bufferuiv': {
639 'type': 'GLenum',
640 'valid': [
641 'GL_COLOR',
643 'invalid': [
644 'GL_RENDERBUFFER',
647 'Bufferfv': {
648 'type': 'GLenum',
649 'valid': [
650 'GL_COLOR',
651 'GL_DEPTH',
653 'invalid': [
654 'GL_RENDERBUFFER',
657 'Bufferfi': {
658 'type': 'GLenum',
659 'valid': [
660 'GL_DEPTH_STENCIL',
662 'invalid': [
663 'GL_RENDERBUFFER',
666 'BufferUsage': {
667 'type': 'GLenum',
668 'valid': [
669 'GL_STREAM_DRAW',
670 'GL_STATIC_DRAW',
671 'GL_DYNAMIC_DRAW',
673 'invalid': [
674 'GL_STATIC_READ',
677 'CompressedTextureFormat': {
678 'type': 'GLenum',
679 'valid': [
682 'GLState': {
683 'type': 'GLenum',
684 'valid': [
685 # NOTE: State an Capability entries added later.
686 'GL_ACTIVE_TEXTURE',
687 'GL_ALIASED_LINE_WIDTH_RANGE',
688 'GL_ALIASED_POINT_SIZE_RANGE',
689 'GL_ALPHA_BITS',
690 'GL_ARRAY_BUFFER_BINDING',
691 'GL_BLUE_BITS',
692 'GL_COMPRESSED_TEXTURE_FORMATS',
693 'GL_CURRENT_PROGRAM',
694 'GL_DEPTH_BITS',
695 'GL_DEPTH_RANGE',
696 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
697 'GL_FRAMEBUFFER_BINDING',
698 'GL_GENERATE_MIPMAP_HINT',
699 'GL_GREEN_BITS',
700 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
701 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
702 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
703 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
704 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
705 'GL_MAX_RENDERBUFFER_SIZE',
706 'GL_MAX_TEXTURE_IMAGE_UNITS',
707 'GL_MAX_TEXTURE_SIZE',
708 'GL_MAX_VARYING_VECTORS',
709 'GL_MAX_VERTEX_ATTRIBS',
710 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
711 'GL_MAX_VERTEX_UNIFORM_VECTORS',
712 'GL_MAX_VIEWPORT_DIMS',
713 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
714 'GL_NUM_SHADER_BINARY_FORMATS',
715 'GL_PACK_ALIGNMENT',
716 'GL_RED_BITS',
717 'GL_RENDERBUFFER_BINDING',
718 'GL_SAMPLE_BUFFERS',
719 'GL_SAMPLE_COVERAGE_INVERT',
720 'GL_SAMPLE_COVERAGE_VALUE',
721 'GL_SAMPLES',
722 'GL_SCISSOR_BOX',
723 'GL_SHADER_BINARY_FORMATS',
724 'GL_SHADER_COMPILER',
725 'GL_SUBPIXEL_BITS',
726 'GL_STENCIL_BITS',
727 'GL_TEXTURE_BINDING_2D',
728 'GL_TEXTURE_BINDING_CUBE_MAP',
729 'GL_UNPACK_ALIGNMENT',
730 'GL_UNPACK_FLIP_Y_CHROMIUM',
731 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
732 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
733 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
734 # we can add this because we emulate it if the driver does not support it.
735 'GL_VERTEX_ARRAY_BINDING_OES',
736 'GL_VIEWPORT',
738 'invalid': [
739 'GL_FOG_HINT',
742 'GetTexParamTarget': {
743 'type': 'GLenum',
744 'valid': [
745 'GL_TEXTURE_2D',
746 'GL_TEXTURE_CUBE_MAP',
748 'invalid': [
749 'GL_PROXY_TEXTURE_CUBE_MAP',
752 'TextureTarget': {
753 'type': 'GLenum',
754 'valid': [
755 'GL_TEXTURE_2D',
756 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
757 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
758 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
759 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
760 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
761 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
763 'invalid': [
764 'GL_PROXY_TEXTURE_CUBE_MAP',
767 'Texture3DTarget': {
768 'type': 'GLenum',
769 'valid': [
770 'GL_TEXTURE_3D',
771 'GL_TEXTURE_2D_ARRAY',
773 'invalid': [
774 'GL_TEXTURE_2D',
777 'TextureBindTarget': {
778 'type': 'GLenum',
779 'valid': [
780 'GL_TEXTURE_2D',
781 'GL_TEXTURE_CUBE_MAP',
783 'valid_es3': [
784 'GL_TEXTURE_3D',
785 'GL_TEXTURE_2D_ARRAY',
787 'invalid': [
788 'GL_TEXTURE_1D',
789 'GL_TEXTURE_3D',
792 'TransformFeedbackBindTarget': {
793 'type': 'GLenum',
794 'valid': [
795 'GL_TRANSFORM_FEEDBACK',
797 'invalid': [
798 'GL_TEXTURE_2D',
801 'TransformFeedbackPrimitiveMode': {
802 'type': 'GLenum',
803 'valid': [
804 'GL_POINTS',
805 'GL_LINES',
806 'GL_TRIANGLES',
808 'invalid': [
809 'GL_LINE_LOOP',
812 'ShaderType': {
813 'type': 'GLenum',
814 'valid': [
815 'GL_VERTEX_SHADER',
816 'GL_FRAGMENT_SHADER',
818 'invalid': [
819 'GL_GEOMETRY_SHADER',
822 'FaceType': {
823 'type': 'GLenum',
824 'valid': [
825 'GL_FRONT',
826 'GL_BACK',
827 'GL_FRONT_AND_BACK',
830 'FaceMode': {
831 'type': 'GLenum',
832 'valid': [
833 'GL_CW',
834 'GL_CCW',
837 'CmpFunction': {
838 'type': 'GLenum',
839 'valid': [
840 'GL_NEVER',
841 'GL_LESS',
842 'GL_EQUAL',
843 'GL_LEQUAL',
844 'GL_GREATER',
845 'GL_NOTEQUAL',
846 'GL_GEQUAL',
847 'GL_ALWAYS',
850 'Equation': {
851 'type': 'GLenum',
852 'valid': [
853 'GL_FUNC_ADD',
854 'GL_FUNC_SUBTRACT',
855 'GL_FUNC_REVERSE_SUBTRACT',
857 'invalid': [
858 'GL_MIN',
859 'GL_MAX',
862 'SrcBlendFactor': {
863 'type': 'GLenum',
864 'valid': [
865 'GL_ZERO',
866 'GL_ONE',
867 'GL_SRC_COLOR',
868 'GL_ONE_MINUS_SRC_COLOR',
869 'GL_DST_COLOR',
870 'GL_ONE_MINUS_DST_COLOR',
871 'GL_SRC_ALPHA',
872 'GL_ONE_MINUS_SRC_ALPHA',
873 'GL_DST_ALPHA',
874 'GL_ONE_MINUS_DST_ALPHA',
875 'GL_CONSTANT_COLOR',
876 'GL_ONE_MINUS_CONSTANT_COLOR',
877 'GL_CONSTANT_ALPHA',
878 'GL_ONE_MINUS_CONSTANT_ALPHA',
879 'GL_SRC_ALPHA_SATURATE',
882 'DstBlendFactor': {
883 'type': 'GLenum',
884 'valid': [
885 'GL_ZERO',
886 'GL_ONE',
887 'GL_SRC_COLOR',
888 'GL_ONE_MINUS_SRC_COLOR',
889 'GL_DST_COLOR',
890 'GL_ONE_MINUS_DST_COLOR',
891 'GL_SRC_ALPHA',
892 'GL_ONE_MINUS_SRC_ALPHA',
893 'GL_DST_ALPHA',
894 'GL_ONE_MINUS_DST_ALPHA',
895 'GL_CONSTANT_COLOR',
896 'GL_ONE_MINUS_CONSTANT_COLOR',
897 'GL_CONSTANT_ALPHA',
898 'GL_ONE_MINUS_CONSTANT_ALPHA',
901 'Capability': {
902 'type': 'GLenum',
903 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
904 if 'es3' not in cap or cap['es3'] != True],
905 'valid_es3': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
906 if 'es3' in cap and cap['es3'] == True],
907 'invalid': [
908 'GL_CLIP_PLANE0',
909 'GL_POINT_SPRITE',
912 'DrawMode': {
913 'type': 'GLenum',
914 'valid': [
915 'GL_POINTS',
916 'GL_LINE_STRIP',
917 'GL_LINE_LOOP',
918 'GL_LINES',
919 'GL_TRIANGLE_STRIP',
920 'GL_TRIANGLE_FAN',
921 'GL_TRIANGLES',
923 'invalid': [
924 'GL_QUADS',
925 'GL_POLYGON',
928 'IndexType': {
929 'type': 'GLenum',
930 'valid': [
931 'GL_UNSIGNED_BYTE',
932 'GL_UNSIGNED_SHORT',
934 'invalid': [
935 'GL_UNSIGNED_INT',
936 'GL_INT',
939 'GetMaxIndexType': {
940 'type': 'GLenum',
941 'valid': [
942 'GL_UNSIGNED_BYTE',
943 'GL_UNSIGNED_SHORT',
944 'GL_UNSIGNED_INT',
946 'invalid': [
947 'GL_INT',
950 'Attachment': {
951 'type': 'GLenum',
952 'valid': [
953 'GL_COLOR_ATTACHMENT0',
954 'GL_DEPTH_ATTACHMENT',
955 'GL_STENCIL_ATTACHMENT',
958 'BackbufferAttachment': {
959 'type': 'GLenum',
960 'valid': [
961 'GL_COLOR_EXT',
962 'GL_DEPTH_EXT',
963 'GL_STENCIL_EXT',
966 'BufferParameter': {
967 'type': 'GLenum',
968 'valid': [
969 'GL_BUFFER_SIZE',
970 'GL_BUFFER_USAGE',
972 'invalid': [
973 'GL_PIXEL_PACK_BUFFER',
976 'BufferMode': {
977 'type': 'GLenum',
978 'valid': [
979 'GL_INTERLEAVED_ATTRIBS',
980 'GL_SEPARATE_ATTRIBS',
982 'invalid': [
983 'GL_PIXEL_PACK_BUFFER',
986 'FrameBufferParameter': {
987 'type': 'GLenum',
988 'valid': [
989 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
990 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
991 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
992 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
995 'MatrixMode': {
996 'type': 'GLenum',
997 'valid': [
998 'GL_PATH_PROJECTION_CHROMIUM',
999 'GL_PATH_MODELVIEW_CHROMIUM',
1002 'ProgramParameter': {
1003 'type': 'GLenum',
1004 'valid': [
1005 'GL_DELETE_STATUS',
1006 'GL_LINK_STATUS',
1007 'GL_VALIDATE_STATUS',
1008 'GL_INFO_LOG_LENGTH',
1009 'GL_ATTACHED_SHADERS',
1010 'GL_ACTIVE_ATTRIBUTES',
1011 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1012 'GL_ACTIVE_UNIFORMS',
1013 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1016 'QueryObjectParameter': {
1017 'type': 'GLenum',
1018 'valid': [
1019 'GL_QUERY_RESULT_EXT',
1020 'GL_QUERY_RESULT_AVAILABLE_EXT',
1023 'QueryParameter': {
1024 'type': 'GLenum',
1025 'valid': [
1026 'GL_CURRENT_QUERY_EXT',
1029 'QueryTarget': {
1030 'type': 'GLenum',
1031 'valid': [
1032 'GL_ANY_SAMPLES_PASSED_EXT',
1033 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1034 'GL_COMMANDS_ISSUED_CHROMIUM',
1035 'GL_LATENCY_QUERY_CHROMIUM',
1036 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1037 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1038 'GL_COMMANDS_COMPLETED_CHROMIUM',
1041 'RenderBufferParameter': {
1042 'type': 'GLenum',
1043 'valid': [
1044 'GL_RENDERBUFFER_RED_SIZE',
1045 'GL_RENDERBUFFER_GREEN_SIZE',
1046 'GL_RENDERBUFFER_BLUE_SIZE',
1047 'GL_RENDERBUFFER_ALPHA_SIZE',
1048 'GL_RENDERBUFFER_DEPTH_SIZE',
1049 'GL_RENDERBUFFER_STENCIL_SIZE',
1050 'GL_RENDERBUFFER_WIDTH',
1051 'GL_RENDERBUFFER_HEIGHT',
1052 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1055 'SamplerParameter': {
1056 'type': 'GLenum',
1057 'valid': [
1058 'GL_TEXTURE_MAG_FILTER',
1059 'GL_TEXTURE_MIN_FILTER',
1060 'GL_TEXTURE_MIN_LOD',
1061 'GL_TEXTURE_MAX_LOD',
1062 'GL_TEXTURE_WRAP_S',
1063 'GL_TEXTURE_WRAP_T',
1064 'GL_TEXTURE_WRAP_R',
1065 'GL_TEXTURE_COMPARE_MODE',
1066 'GL_TEXTURE_COMPARE_FUNC',
1068 'invalid': [
1069 'GL_GENERATE_MIPMAP',
1072 'ShaderParameter': {
1073 'type': 'GLenum',
1074 'valid': [
1075 'GL_SHADER_TYPE',
1076 'GL_DELETE_STATUS',
1077 'GL_COMPILE_STATUS',
1078 'GL_INFO_LOG_LENGTH',
1079 'GL_SHADER_SOURCE_LENGTH',
1080 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1083 'ShaderPrecision': {
1084 'type': 'GLenum',
1085 'valid': [
1086 'GL_LOW_FLOAT',
1087 'GL_MEDIUM_FLOAT',
1088 'GL_HIGH_FLOAT',
1089 'GL_LOW_INT',
1090 'GL_MEDIUM_INT',
1091 'GL_HIGH_INT',
1094 'StringType': {
1095 'type': 'GLenum',
1096 'valid': [
1097 'GL_VENDOR',
1098 'GL_RENDERER',
1099 'GL_VERSION',
1100 'GL_SHADING_LANGUAGE_VERSION',
1101 'GL_EXTENSIONS',
1104 'TextureParameter': {
1105 'type': 'GLenum',
1106 'valid': [
1107 'GL_TEXTURE_MAG_FILTER',
1108 'GL_TEXTURE_MIN_FILTER',
1109 'GL_TEXTURE_POOL_CHROMIUM',
1110 'GL_TEXTURE_WRAP_S',
1111 'GL_TEXTURE_WRAP_T',
1113 'invalid': [
1114 'GL_GENERATE_MIPMAP',
1117 'TexturePool': {
1118 'type': 'GLenum',
1119 'valid': [
1120 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1121 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1124 'TextureWrapMode': {
1125 'type': 'GLenum',
1126 'valid': [
1127 'GL_CLAMP_TO_EDGE',
1128 'GL_MIRRORED_REPEAT',
1129 'GL_REPEAT',
1132 'TextureMinFilterMode': {
1133 'type': 'GLenum',
1134 'valid': [
1135 'GL_NEAREST',
1136 'GL_LINEAR',
1137 'GL_NEAREST_MIPMAP_NEAREST',
1138 'GL_LINEAR_MIPMAP_NEAREST',
1139 'GL_NEAREST_MIPMAP_LINEAR',
1140 'GL_LINEAR_MIPMAP_LINEAR',
1143 'TextureMagFilterMode': {
1144 'type': 'GLenum',
1145 'valid': [
1146 'GL_NEAREST',
1147 'GL_LINEAR',
1150 'TextureUsage': {
1151 'type': 'GLenum',
1152 'valid': [
1153 'GL_NONE',
1154 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1157 'VertexAttribute': {
1158 'type': 'GLenum',
1159 'valid': [
1160 # some enum that the decoder actually passes through to GL needs
1161 # to be the first listed here since it's used in unit tests.
1162 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1163 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1164 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1165 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1166 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1167 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1168 'GL_CURRENT_VERTEX_ATTRIB',
1171 'VertexPointer': {
1172 'type': 'GLenum',
1173 'valid': [
1174 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1177 'HintTarget': {
1178 'type': 'GLenum',
1179 'valid': [
1180 'GL_GENERATE_MIPMAP_HINT',
1182 'invalid': [
1183 'GL_PERSPECTIVE_CORRECTION_HINT',
1186 'HintMode': {
1187 'type': 'GLenum',
1188 'valid': [
1189 'GL_FASTEST',
1190 'GL_NICEST',
1191 'GL_DONT_CARE',
1194 'PixelStore': {
1195 'type': 'GLenum',
1196 'valid': [
1197 'GL_PACK_ALIGNMENT',
1198 'GL_UNPACK_ALIGNMENT',
1199 'GL_UNPACK_FLIP_Y_CHROMIUM',
1200 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
1201 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
1203 'invalid': [
1204 'GL_PACK_SWAP_BYTES',
1205 'GL_UNPACK_SWAP_BYTES',
1208 'PixelStoreAlignment': {
1209 'type': 'GLint',
1210 'valid': [
1211 '1',
1212 '2',
1213 '4',
1214 '8',
1216 'invalid': [
1217 '3',
1218 '9',
1221 'ReadPixelFormat': {
1222 'type': 'GLenum',
1223 'valid': [
1224 'GL_ALPHA',
1225 'GL_RGB',
1226 'GL_RGBA',
1229 'PixelType': {
1230 'type': 'GLenum',
1231 'valid': [
1232 'GL_UNSIGNED_BYTE',
1233 'GL_UNSIGNED_SHORT_5_6_5',
1234 'GL_UNSIGNED_SHORT_4_4_4_4',
1235 'GL_UNSIGNED_SHORT_5_5_5_1',
1237 'valid_es3': [
1238 'GL_BYTE',
1239 'GL_UNSIGNED_SHORT',
1240 'GL_SHORT',
1241 'GL_UNSIGNED_INT',
1242 'GL_INT',
1243 'GL_HALF_FLOAT',
1244 'GL_FLOAT',
1245 'GL_UNSIGNED_INT_2_10_10_10_REV',
1246 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1247 'GL_UNSIGNED_INT_5_9_9_9_REV',
1248 'GL_UNSIGNED_INT_24_8',
1249 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1251 'invalid': [
1252 'GL_UNSIGNED_BYTE_3_3_2',
1255 'ReadPixelType': {
1256 'type': 'GLenum',
1257 'valid': [
1258 'GL_UNSIGNED_BYTE',
1259 'GL_UNSIGNED_SHORT_5_6_5',
1260 'GL_UNSIGNED_SHORT_4_4_4_4',
1261 'GL_UNSIGNED_SHORT_5_5_5_1',
1263 'invalid': [
1264 'GL_SHORT',
1265 'GL_INT',
1268 'RenderBufferFormat': {
1269 'type': 'GLenum',
1270 'valid': [
1271 'GL_RGBA4',
1272 'GL_RGB565',
1273 'GL_RGB5_A1',
1274 'GL_DEPTH_COMPONENT16',
1275 'GL_STENCIL_INDEX8',
1278 'ShaderBinaryFormat': {
1279 'type': 'GLenum',
1280 'valid': [
1283 'StencilOp': {
1284 'type': 'GLenum',
1285 'valid': [
1286 'GL_KEEP',
1287 'GL_ZERO',
1288 'GL_REPLACE',
1289 'GL_INCR',
1290 'GL_INCR_WRAP',
1291 'GL_DECR',
1292 'GL_DECR_WRAP',
1293 'GL_INVERT',
1296 'TextureFormat': {
1297 'type': 'GLenum',
1298 'valid': [
1299 'GL_ALPHA',
1300 'GL_LUMINANCE',
1301 'GL_LUMINANCE_ALPHA',
1302 'GL_RGB',
1303 'GL_RGBA',
1305 'valid_es3': [
1306 'GL_RED',
1307 'GL_RED_INTEGER',
1308 'GL_RG',
1309 'GL_RG_INTEGER',
1310 'GL_RGB_INTEGER',
1311 'GL_RGBA_INTEGER',
1312 'GL_DEPTH_COMPONENT',
1313 'GL_DEPTH_STENCIL',
1315 'invalid': [
1316 'GL_BGRA',
1317 'GL_BGR',
1320 'TextureInternalFormat': {
1321 'type': 'GLenum',
1322 'valid': [
1323 'GL_ALPHA',
1324 'GL_LUMINANCE',
1325 'GL_LUMINANCE_ALPHA',
1326 'GL_RGB',
1327 'GL_RGBA',
1329 'valid_es3': [
1330 'GL_R8',
1331 'GL_R8_SNORM',
1332 'GL_R16F',
1333 'GL_R32F',
1334 'GL_R8UI',
1335 'GL_R8I',
1336 'GL_R16UI',
1337 'GL_R16I',
1338 'GL_R32UI',
1339 'GL_R32I',
1340 'GL_RG8',
1341 'GL_RG8_SNORM',
1342 'GL_RG16F',
1343 'GL_RG32F',
1344 'GL_RG8UI',
1345 'GL_RG8I',
1346 'GL_RG16UI',
1347 'GL_RG16I',
1348 'GL_RG32UI',
1349 'GL_RG32I',
1350 'GL_RGB8',
1351 'GL_SRGB8',
1352 'GL_RGB565',
1353 'GL_RGB8_SNORM',
1354 'GL_R11F_G11F_B10F',
1355 'GL_RGB9_E5',
1356 'GL_RGB16F',
1357 'GL_RGB32F',
1358 'GL_RGB8UI',
1359 'GL_RGB8I',
1360 'GL_RGB16UI',
1361 'GL_RGB16I',
1362 'GL_RGB32UI',
1363 'GL_RGB32I',
1364 'GL_RGBA8',
1365 'GL_SRGB8_ALPHA8',
1366 'GL_RGBA8_SNORM',
1367 'GL_RGB5_A1',
1368 'GL_RGBA4',
1369 'GL_RGB10_A2',
1370 'GL_RGBA16F',
1371 'GL_RGBA32F',
1372 'GL_RGBA8UI',
1373 'GL_RGBA8I',
1374 'GL_RGB10_A2UI',
1375 'GL_RGBA16UI',
1376 'GL_RGBA16I',
1377 'GL_RGBA32UI',
1378 'GL_RGBA32I',
1379 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1380 # We will reject them dynamically in GPU command buffer.
1381 'GL_DEPTH_COMPONENT16',
1382 'GL_DEPTH_COMPONENT24',
1383 'GL_DEPTH_COMPONENT32F',
1384 'GL_DEPTH24_STENCIL8',
1385 'GL_DEPTH32F_STENCIL8',
1387 'invalid': [
1388 'GL_BGRA',
1389 'GL_BGR',
1392 'TextureInternalFormatStorage': {
1393 'type': 'GLenum',
1394 'valid': [
1395 'GL_RGB565',
1396 'GL_RGBA4',
1397 'GL_RGB5_A1',
1398 'GL_ALPHA8_EXT',
1399 'GL_LUMINANCE8_EXT',
1400 'GL_LUMINANCE8_ALPHA8_EXT',
1401 'GL_RGB8_OES',
1402 'GL_RGBA8_OES',
1404 'valid_es3': [
1405 'GL_R8',
1406 'GL_R8_SNORM',
1407 'GL_R16F',
1408 'GL_R32F',
1409 'GL_R8UI',
1410 'GL_R8I',
1411 'GL_R16UI',
1412 'GL_R16I',
1413 'GL_R32UI',
1414 'GL_R32I',
1415 'GL_RG8',
1416 'GL_RG8_SNORM',
1417 'GL_RG16F',
1418 'GL_RG32F',
1419 'GL_RG8UI',
1420 'GL_RG8I',
1421 'GL_RG16UI',
1422 'GL_RG16I',
1423 'GL_RG32UI',
1424 'GL_RG32I',
1425 'GL_SRGB8',
1426 'GL_RGB8_SNORM',
1427 'GL_R11F_G11F_B10F',
1428 'GL_RGB9_E5',
1429 'GL_RGB16F',
1430 'GL_RGB32F',
1431 'GL_RGB8UI',
1432 'GL_RGB8I',
1433 'GL_RGB16UI',
1434 'GL_RGB16I',
1435 'GL_RGB32UI',
1436 'GL_RGB32I',
1437 'GL_SRGB8_ALPHA8',
1438 'GL_RGBA8_SNORM',
1439 'GL_RGB10_A2',
1440 'GL_RGBA16F',
1441 'GL_RGBA32F',
1442 'GL_RGBA8UI',
1443 'GL_RGBA8I',
1444 'GL_RGB10_A2UI',
1445 'GL_RGBA16UI',
1446 'GL_RGBA16I',
1447 'GL_RGBA32UI',
1448 'GL_RGBA32I',
1449 'GL_DEPTH_COMPONENT16',
1450 'GL_DEPTH_COMPONENT24',
1451 'GL_DEPTH_COMPONENT32F',
1452 'GL_DEPTH24_STENCIL8',
1453 'GL_DEPTH32F_STENCIL8',
1454 'GL_COMPRESSED_R11_EAC',
1455 'GL_COMPRESSED_SIGNED_R11_EAC',
1456 'GL_COMPRESSED_RG11_EAC',
1457 'GL_COMPRESSED_SIGNED_RG11_EAC',
1458 'GL_COMPRESSED_RGB8_ETC2',
1459 'GL_COMPRESSED_SRGB8_ETC2',
1460 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1461 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1462 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1463 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1465 'deprecated_es3': [
1466 'GL_ALPHA8_EXT',
1467 'GL_LUMINANCE8_EXT',
1468 'GL_LUMINANCE8_ALPHA8_EXT',
1469 'GL_ALPHA16F_EXT',
1470 'GL_LUMINANCE16F_EXT',
1471 'GL_LUMINANCE_ALPHA16F_EXT',
1472 'GL_ALPHA32F_EXT',
1473 'GL_LUMINANCE32F_EXT',
1474 'GL_LUMINANCE_ALPHA32F_EXT',
1477 'ImageInternalFormat': {
1478 'type': 'GLenum',
1479 'valid': [
1480 'GL_RGB',
1481 'GL_RGBA',
1484 'ImageUsage': {
1485 'type': 'GLenum',
1486 'valid': [
1487 'GL_MAP_CHROMIUM',
1488 'GL_SCANOUT_CHROMIUM'
1491 'ValueBufferTarget': {
1492 'type': 'GLenum',
1493 'valid': [
1494 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1497 'SubscriptionTarget': {
1498 'type': 'GLenum',
1499 'valid': [
1500 'GL_MOUSE_POSITION_CHROMIUM',
1503 'UniformParameter': {
1504 'type': 'GLenum',
1505 'valid': [
1506 'GL_UNIFORM_SIZE',
1507 'GL_UNIFORM_TYPE',
1508 'GL_UNIFORM_NAME_LENGTH',
1509 'GL_UNIFORM_BLOCK_INDEX',
1510 'GL_UNIFORM_OFFSET',
1511 'GL_UNIFORM_ARRAY_STRIDE',
1512 'GL_UNIFORM_MATRIX_STRIDE',
1513 'GL_UNIFORM_IS_ROW_MAJOR',
1515 'invalid': [
1516 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1519 'UniformBlockParameter': {
1520 'type': 'GLenum',
1521 'valid': [
1522 'GL_UNIFORM_BLOCK_BINDING',
1523 'GL_UNIFORM_BLOCK_DATA_SIZE',
1524 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1525 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1526 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1527 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1528 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1530 'invalid': [
1531 'GL_NEAREST',
1534 'VertexAttribType': {
1535 'type': 'GLenum',
1536 'valid': [
1537 'GL_BYTE',
1538 'GL_UNSIGNED_BYTE',
1539 'GL_SHORT',
1540 'GL_UNSIGNED_SHORT',
1541 # 'GL_FIXED', // This is not available on Desktop GL.
1542 'GL_FLOAT',
1544 'invalid': [
1545 'GL_DOUBLE',
1548 'TextureBorder': {
1549 'type': 'GLint',
1550 'is_complete': True,
1551 'valid': [
1552 '0',
1554 'invalid': [
1555 '1',
1558 'VertexAttribSize': {
1559 'type': 'GLint',
1560 'valid': [
1561 '1',
1562 '2',
1563 '3',
1564 '4',
1566 'invalid': [
1567 '0',
1568 '5',
1571 'ZeroOnly': {
1572 'type': 'GLint',
1573 'is_complete': True,
1574 'valid': [
1575 '0',
1577 'invalid': [
1578 '1',
1581 'FalseOnly': {
1582 'type': 'GLboolean',
1583 'is_complete': True,
1584 'valid': [
1585 'false',
1587 'invalid': [
1588 'true',
1591 'ResetStatus': {
1592 'type': 'GLenum',
1593 'valid': [
1594 'GL_GUILTY_CONTEXT_RESET_ARB',
1595 'GL_INNOCENT_CONTEXT_RESET_ARB',
1596 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1599 'SyncCondition': {
1600 'type': 'GLenum',
1601 'is_complete': True,
1602 'valid': [
1603 'GL_SYNC_GPU_COMMANDS_COMPLETE',
1605 'invalid': [
1606 '0',
1609 'SyncFlags': {
1610 'type': 'GLbitfield',
1611 'is_complete': True,
1612 'valid': [
1613 '0',
1615 'invalid': [
1616 '1',
1619 'SyncFlushFlags': {
1620 'type': 'GLbitfield',
1621 'valid': [
1622 'GL_SYNC_FLUSH_COMMANDS_BIT',
1623 '0',
1625 'invalid': [
1626 '0xFFFFFFFF',
1629 'SyncParameter': {
1630 'type': 'GLenum',
1631 'valid': [
1632 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
1633 'GL_OBJECT_TYPE',
1634 'GL_SYNC_CONDITION',
1635 'GL_SYNC_FLAGS',
1637 'invalid': [
1638 'GL_SYNC_FENCE',
1643 # This table specifies the different pepper interfaces that are supported for
1644 # GL commands. 'dev' is true if it's a dev interface.
1645 _PEPPER_INTERFACES = [
1646 {'name': '', 'dev': False},
1647 {'name': 'InstancedArrays', 'dev': False},
1648 {'name': 'FramebufferBlit', 'dev': False},
1649 {'name': 'FramebufferMultisample', 'dev': False},
1650 {'name': 'ChromiumEnableFeature', 'dev': False},
1651 {'name': 'ChromiumMapSub', 'dev': False},
1652 {'name': 'Query', 'dev': False},
1653 {'name': 'VertexArrayObject', 'dev': False},
1654 {'name': 'DrawBuffers', 'dev': True},
1657 # A function info object specifies the type and other special data for the
1658 # command that will be generated. A base function info object is generated by
1659 # parsing the "cmd_buffer_functions.txt", one for each function in the
1660 # file. These function info objects can be augmented and their values can be
1661 # overridden by adding an object to the table below.
1663 # Must match function names specified in "cmd_buffer_functions.txt".
1665 # cmd_comment: A comment added to the cmd format.
1666 # type: defines which handler will be used to generate code.
1667 # decoder_func: defines which function to call in the decoder to execute the
1668 # corresponding GL command. If not specified the GL command will
1669 # be called directly.
1670 # gl_test_func: GL function that is expected to be called when testing.
1671 # cmd_args: The arguments to use for the command. This overrides generating
1672 # them based on the GL function arguments.
1673 # gen_cmd: Whether or not this function geneates a command. Default = True.
1674 # data_transfer_methods: Array of methods that are used for transfering the
1675 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1676 # The default is 'immediate' if the command has one pointer
1677 # argument, otherwise 'shm'. One command is generated for each
1678 # transfer method. Affects only commands which are not of type
1679 # 'HandWritten', 'GETn' or 'GLcharN'.
1680 # Note: the command arguments that affect this are the final args,
1681 # taking cmd_args override into consideration.
1682 # impl_func: Whether or not to generate the GLES2Implementation part of this
1683 # command.
1684 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1685 # for this command.
1686 # needs_size: If True a data_size field is added to the command.
1687 # count: The number of units per element. For PUTn or PUT types.
1688 # use_count_func: If True the actual data count needs to be computed; the count
1689 # argument specifies the maximum count.
1690 # unit_test: If False no service side unit test will be generated.
1691 # client_test: If False no client side unit test will be generated.
1692 # expectation: If False the unit test will have no expected calls.
1693 # gen_func: Name of function that generates GL resource for corresponding
1694 # bind function.
1695 # states: array of states that get set by this function corresponding to
1696 # the given arguments
1697 # state_flag: name of flag that is set to true when function is called.
1698 # no_gl: no GL function is called.
1699 # valid_args: A dictionary of argument indices to args to use in unit tests
1700 # when they can not be automatically determined.
1701 # pepper_interface: The pepper interface that is used for this extension
1702 # pepper_name: The name of the function as exposed to pepper.
1703 # pepper_args: A string representing the argument list (what would appear in
1704 # C/C++ between the parentheses for the function declaration)
1705 # that the Pepper API expects for this function. Use this only if
1706 # the stable Pepper API differs from the GLES2 argument list.
1707 # invalid_test: False if no invalid test needed.
1708 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1709 # first_element_only: For PUT types, True if only the first element of an
1710 # array is used and we end up calling the single value
1711 # corresponding function. eg. TexParameteriv -> TexParameteri
1712 # extension: Function is an extension to GL and should not be exposed to
1713 # pepper unless pepper_interface is defined.
1714 # extension_flag: Function is an extension and should be enabled only when
1715 # the corresponding feature info flag is enabled. Implies
1716 # 'extension': True.
1717 # not_shared: For GENn types, True if objects can't be shared between contexts
1718 # unsafe: True = no validation is implemented on the service side and the
1719 # command is only available with --enable-unsafe-es3-apis.
1720 # id_mapping: A list of resource type names whose client side IDs need to be
1721 # mapped to service side IDs. This is only used for unsafe APIs.
1723 _FUNCTION_INFO = {
1724 'ActiveTexture': {
1725 'decoder_func': 'DoActiveTexture',
1726 'unit_test': False,
1727 'impl_func': False,
1728 'client_test': False,
1730 'AttachShader': {'decoder_func': 'DoAttachShader'},
1731 'BindAttribLocation': {
1732 'type': 'GLchar',
1733 'data_transfer_methods': ['bucket'],
1734 'needs_size': True,
1736 'BindBuffer': {
1737 'type': 'Bind',
1738 'decoder_func': 'DoBindBuffer',
1739 'gen_func': 'GenBuffersARB',
1741 'BindBufferBase': {
1742 'type': 'Bind',
1743 'id_mapping': [ 'Buffer' ],
1744 'gen_func': 'GenBuffersARB',
1745 'unsafe': True,
1747 'BindBufferRange': {
1748 'type': 'Bind',
1749 'id_mapping': [ 'Buffer' ],
1750 'gen_func': 'GenBuffersARB',
1751 'valid_args': {
1752 '3': '4',
1753 '4': '4'
1755 'unsafe': True,
1757 'BindFramebuffer': {
1758 'type': 'Bind',
1759 'decoder_func': 'DoBindFramebuffer',
1760 'gl_test_func': 'glBindFramebufferEXT',
1761 'gen_func': 'GenFramebuffersEXT',
1762 'trace_level': 1,
1764 'BindRenderbuffer': {
1765 'type': 'Bind',
1766 'decoder_func': 'DoBindRenderbuffer',
1767 'gl_test_func': 'glBindRenderbufferEXT',
1768 'gen_func': 'GenRenderbuffersEXT',
1770 'BindSampler': {
1771 'type': 'Bind',
1772 'id_mapping': [ 'Sampler' ],
1773 'unsafe': True,
1775 'BindTexture': {
1776 'type': 'Bind',
1777 'decoder_func': 'DoBindTexture',
1778 'gen_func': 'GenTextures',
1779 # TODO(gman): remove this once client side caching works.
1780 'client_test': False,
1781 'trace_level': 1,
1783 'BindTransformFeedback': {
1784 'type': 'Bind',
1785 'id_mapping': [ 'TransformFeedback' ],
1786 'unsafe': True,
1788 'BlitFramebufferCHROMIUM': {
1789 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1790 'unit_test': False,
1791 'extension_flag': 'chromium_framebuffer_multisample',
1792 'pepper_interface': 'FramebufferBlit',
1793 'pepper_name': 'BlitFramebufferEXT',
1794 'defer_reads': True,
1795 'defer_draws': True,
1796 'trace_level': 1,
1798 'BufferData': {
1799 'type': 'Manual',
1800 'data_transfer_methods': ['shm'],
1801 'client_test': False,
1803 'BufferSubData': {
1804 'type': 'Data',
1805 'client_test': False,
1806 'decoder_func': 'DoBufferSubData',
1807 'data_transfer_methods': ['shm'],
1809 'CheckFramebufferStatus': {
1810 'type': 'Is',
1811 'decoder_func': 'DoCheckFramebufferStatus',
1812 'gl_test_func': 'glCheckFramebufferStatusEXT',
1813 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1814 'result': ['GLenum'],
1816 'Clear': {
1817 'decoder_func': 'DoClear',
1818 'defer_draws': True,
1819 'trace_level': 1,
1821 'ClearBufferiv': {
1822 'type': 'PUT',
1823 'use_count_func': True,
1824 'count': 4,
1825 'unsafe': True,
1827 'ClearBufferuiv': {
1828 'type': 'PUT',
1829 'count': 4,
1830 'unsafe': True,
1832 'ClearBufferfv': {
1833 'type': 'PUT',
1834 'use_count_func': True,
1835 'count': 4,
1836 'unsafe': True,
1838 'ClearBufferfi': {
1839 'unsafe': True,
1841 'ClearColor': {
1842 'type': 'StateSet',
1843 'state': 'ClearColor',
1845 'ClearDepthf': {
1846 'type': 'StateSet',
1847 'state': 'ClearDepthf',
1848 'decoder_func': 'glClearDepth',
1849 'gl_test_func': 'glClearDepth',
1850 'valid_args': {
1851 '0': '0.5f'
1854 'ClientWaitSync': {
1855 'type': 'Custom',
1856 'data_transfer_methods': ['shm'],
1857 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
1858 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
1859 'unsafe': True,
1860 'result': ['GLenum'],
1862 'ColorMask': {
1863 'type': 'StateSet',
1864 'state': 'ColorMask',
1865 'no_gl': True,
1866 'expectation': False,
1868 'ConsumeTextureCHROMIUM': {
1869 'decoder_func': 'DoConsumeTextureCHROMIUM',
1870 'impl_func': False,
1871 'type': 'PUT',
1872 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1873 'unit_test': False,
1874 'client_test': False,
1875 'extension': "CHROMIUM_texture_mailbox",
1876 'chromium': True,
1877 'trace_level': 1,
1879 'CopyBufferSubData': {
1880 'unsafe': True,
1882 'CreateAndConsumeTextureCHROMIUM': {
1883 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
1884 'impl_func': False,
1885 'type': 'HandWritten',
1886 'data_transfer_methods': ['immediate'],
1887 'unit_test': False,
1888 'client_test': False,
1889 'extension': "CHROMIUM_texture_mailbox",
1890 'chromium': True,
1892 'GenValuebuffersCHROMIUM': {
1893 'type': 'GENn',
1894 'gl_test_func': 'glGenValuebuffersCHROMIUM',
1895 'resource_type': 'Valuebuffer',
1896 'resource_types': 'Valuebuffers',
1897 'unit_test': False,
1898 'extension': True,
1899 'chromium': True,
1901 'DeleteValuebuffersCHROMIUM': {
1902 'type': 'DELn',
1903 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
1904 'resource_type': 'Valuebuffer',
1905 'resource_types': 'Valuebuffers',
1906 'unit_test': False,
1907 'extension': True,
1908 'chromium': True,
1910 'IsValuebufferCHROMIUM': {
1911 'type': 'Is',
1912 'decoder_func': 'DoIsValuebufferCHROMIUM',
1913 'expectation': False,
1914 'extension': True,
1915 'chromium': True,
1917 'BindValuebufferCHROMIUM': {
1918 'type': 'Bind',
1919 'decoder_func': 'DoBindValueBufferCHROMIUM',
1920 'gen_func': 'GenValueBuffersCHROMIUM',
1921 'unit_test': False,
1922 'extension': True,
1923 'chromium': True,
1925 'SubscribeValueCHROMIUM': {
1926 'decoder_func': 'DoSubscribeValueCHROMIUM',
1927 'unit_test': False,
1928 'extension': True,
1929 'chromium': True,
1931 'PopulateSubscribedValuesCHROMIUM': {
1932 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
1933 'unit_test': False,
1934 'extension': True,
1935 'chromium': True,
1937 'UniformValuebufferCHROMIUM': {
1938 'decoder_func': 'DoUniformValueBufferCHROMIUM',
1939 'unit_test': False,
1940 'extension': True,
1941 'chromium': True,
1943 'ClearStencil': {
1944 'type': 'StateSet',
1945 'state': 'ClearStencil',
1947 'EnableFeatureCHROMIUM': {
1948 'type': 'Custom',
1949 'data_transfer_methods': ['shm'],
1950 'decoder_func': 'DoEnableFeatureCHROMIUM',
1951 'expectation': False,
1952 'cmd_args': 'GLuint bucket_id, GLint* result',
1953 'result': ['GLint'],
1954 'extension': True,
1955 'chromium': True,
1956 'pepper_interface': 'ChromiumEnableFeature',
1958 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1959 'CompressedTexImage2D': {
1960 'type': 'Manual',
1961 'data_transfer_methods': ['bucket', 'shm'],
1963 'CompressedTexSubImage2D': {
1964 'type': 'Data',
1965 'data_transfer_methods': ['bucket', 'shm'],
1966 'decoder_func': 'DoCompressedTexSubImage2D',
1968 'CopyTexImage2D': {
1969 'decoder_func': 'DoCopyTexImage2D',
1970 'unit_test': False,
1971 'defer_reads': True,
1973 'CopyTexSubImage2D': {
1974 'decoder_func': 'DoCopyTexSubImage2D',
1975 'defer_reads': True,
1977 'CopyTexSubImage3D': {
1978 'defer_reads': True,
1979 'unsafe': True,
1981 'CreateImageCHROMIUM': {
1982 'type': 'Manual',
1983 'cmd_args':
1984 'ClientBuffer buffer, GLsizei width, GLsizei height, '
1985 'GLenum internalformat',
1986 'result': ['GLuint'],
1987 'client_test': False,
1988 'gen_cmd': False,
1989 'expectation': False,
1990 'extension': True,
1991 'chromium': True,
1993 'DestroyImageCHROMIUM': {
1994 'type': 'Manual',
1995 'client_test': False,
1996 'gen_cmd': False,
1997 'extension': True,
1998 'chromium': True,
2000 'CreateGpuMemoryBufferImageCHROMIUM': {
2001 'type': 'Manual',
2002 'cmd_args':
2003 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2004 'result': ['GLuint'],
2005 'client_test': False,
2006 'gen_cmd': False,
2007 'expectation': False,
2008 'extension': True,
2009 'chromium': True,
2011 'CreateProgram': {
2012 'type': 'Create',
2013 'client_test': False,
2015 'CreateShader': {
2016 'type': 'Create',
2017 'client_test': False,
2019 'BlendColor': {
2020 'type': 'StateSet',
2021 'state': 'BlendColor',
2023 'BlendEquation': {
2024 'type': 'StateSetRGBAlpha',
2025 'state': 'BlendEquation',
2026 'valid_args': {
2027 '0': 'GL_FUNC_SUBTRACT'
2030 'BlendEquationSeparate': {
2031 'type': 'StateSet',
2032 'state': 'BlendEquation',
2033 'valid_args': {
2034 '0': 'GL_FUNC_SUBTRACT'
2037 'BlendFunc': {
2038 'type': 'StateSetRGBAlpha',
2039 'state': 'BlendFunc',
2041 'BlendFuncSeparate': {
2042 'type': 'StateSet',
2043 'state': 'BlendFunc',
2045 'BlendBarrierKHR': {
2046 'gl_test_func': 'glBlendBarrierKHR',
2047 'extension': True,
2048 'extension_flag': 'blend_equation_advanced',
2049 'client_test': False,
2051 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2052 'StencilFunc': {
2053 'type': 'StateSetFrontBack',
2054 'state': 'StencilFunc',
2056 'StencilFuncSeparate': {
2057 'type': 'StateSetFrontBackSeparate',
2058 'state': 'StencilFunc',
2060 'StencilOp': {
2061 'type': 'StateSetFrontBack',
2062 'state': 'StencilOp',
2063 'valid_args': {
2064 '1': 'GL_INCR'
2067 'StencilOpSeparate': {
2068 'type': 'StateSetFrontBackSeparate',
2069 'state': 'StencilOp',
2070 'valid_args': {
2071 '1': 'GL_INCR'
2074 'Hint': {
2075 'type': 'StateSetNamedParameter',
2076 'state': 'Hint',
2078 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2079 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2080 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2081 'LineWidth': {
2082 'type': 'StateSet',
2083 'state': 'LineWidth',
2084 'valid_args': {
2085 '0': '0.5f'
2088 'PolygonOffset': {
2089 'type': 'StateSet',
2090 'state': 'PolygonOffset',
2092 'DeleteBuffers': {
2093 'type': 'DELn',
2094 'gl_test_func': 'glDeleteBuffersARB',
2095 'resource_type': 'Buffer',
2096 'resource_types': 'Buffers',
2098 'DeleteFramebuffers': {
2099 'type': 'DELn',
2100 'gl_test_func': 'glDeleteFramebuffersEXT',
2101 'resource_type': 'Framebuffer',
2102 'resource_types': 'Framebuffers',
2104 'DeleteProgram': { 'type': 'Delete' },
2105 'DeleteRenderbuffers': {
2106 'type': 'DELn',
2107 'gl_test_func': 'glDeleteRenderbuffersEXT',
2108 'resource_type': 'Renderbuffer',
2109 'resource_types': 'Renderbuffers',
2111 'DeleteSamplers': {
2112 'type': 'DELn',
2113 'resource_type': 'Sampler',
2114 'resource_types': 'Samplers',
2115 'unsafe': True,
2117 'DeleteShader': { 'type': 'Delete' },
2118 'DeleteSync': {
2119 'type': 'Delete',
2120 'cmd_args': 'GLuint sync',
2121 'resource_type': 'Sync',
2122 'unsafe': True,
2124 'DeleteTextures': {
2125 'type': 'DELn',
2126 'resource_type': 'Texture',
2127 'resource_types': 'Textures',
2129 'DeleteTransformFeedbacks': {
2130 'type': 'DELn',
2131 'resource_type': 'TransformFeedback',
2132 'resource_types': 'TransformFeedbacks',
2133 'unsafe': True,
2135 'DepthRangef': {
2136 'decoder_func': 'DoDepthRangef',
2137 'gl_test_func': 'glDepthRange',
2139 'DepthMask': {
2140 'type': 'StateSet',
2141 'state': 'DepthMask',
2142 'no_gl': True,
2143 'expectation': False,
2145 'DetachShader': {'decoder_func': 'DoDetachShader'},
2146 'Disable': {
2147 'decoder_func': 'DoDisable',
2148 'impl_func': False,
2149 'client_test': False,
2151 'DisableVertexAttribArray': {
2152 'decoder_func': 'DoDisableVertexAttribArray',
2153 'impl_decl': False,
2155 'DrawArrays': {
2156 'type': 'Manual',
2157 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2158 'defer_draws': True,
2159 'trace_level': 2,
2161 'DrawElements': {
2162 'type': 'Manual',
2163 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2164 'GLenumIndexType type, GLuint index_offset',
2165 'client_test': False,
2166 'defer_draws': True,
2167 'trace_level': 2,
2169 'DrawRangeElements': {
2170 'type': 'Manual',
2171 'gen_cmd': 'False',
2172 'unsafe': True,
2174 'Enable': {
2175 'decoder_func': 'DoEnable',
2176 'impl_func': False,
2177 'client_test': False,
2179 'EnableVertexAttribArray': {
2180 'decoder_func': 'DoEnableVertexAttribArray',
2181 'impl_decl': False,
2183 'FenceSync': {
2184 'type': 'Create',
2185 'client_test': False,
2186 'unsafe': True,
2188 'Finish': {
2189 'impl_func': False,
2190 'client_test': False,
2191 'decoder_func': 'DoFinish',
2192 'defer_reads': True,
2194 'Flush': {
2195 'impl_func': False,
2196 'decoder_func': 'DoFlush',
2198 'FramebufferRenderbuffer': {
2199 'decoder_func': 'DoFramebufferRenderbuffer',
2200 'gl_test_func': 'glFramebufferRenderbufferEXT',
2202 'FramebufferTexture2D': {
2203 'decoder_func': 'DoFramebufferTexture2D',
2204 'gl_test_func': 'glFramebufferTexture2DEXT',
2205 'trace_level': 1,
2207 'FramebufferTexture2DMultisampleEXT': {
2208 'decoder_func': 'DoFramebufferTexture2DMultisample',
2209 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2210 'expectation': False,
2211 'unit_test': False,
2212 'extension_flag': 'multisampled_render_to_texture',
2213 'trace_level': 1,
2215 'FramebufferTextureLayer': {
2216 'decoder_func': 'DoFramebufferTextureLayer',
2217 'unsafe': True,
2219 'GenerateMipmap': {
2220 'decoder_func': 'DoGenerateMipmap',
2221 'gl_test_func': 'glGenerateMipmapEXT',
2223 'GenBuffers': {
2224 'type': 'GENn',
2225 'gl_test_func': 'glGenBuffersARB',
2226 'resource_type': 'Buffer',
2227 'resource_types': 'Buffers',
2229 'GenMailboxCHROMIUM': {
2230 'type': 'HandWritten',
2231 'impl_func': False,
2232 'extension': "CHROMIUM_texture_mailbox",
2233 'chromium': True,
2235 'GenFramebuffers': {
2236 'type': 'GENn',
2237 'gl_test_func': 'glGenFramebuffersEXT',
2238 'resource_type': 'Framebuffer',
2239 'resource_types': 'Framebuffers',
2241 'GenRenderbuffers': {
2242 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2243 'resource_type': 'Renderbuffer',
2244 'resource_types': 'Renderbuffers',
2246 'GenSamplers': {
2247 'type': 'GENn',
2248 'gl_test_func': 'glGenSamplers',
2249 'resource_type': 'Sampler',
2250 'resource_types': 'Samplers',
2251 'unsafe': True,
2253 'GenTextures': {
2254 'type': 'GENn',
2255 'gl_test_func': 'glGenTextures',
2256 'resource_type': 'Texture',
2257 'resource_types': 'Textures',
2259 'GenTransformFeedbacks': {
2260 'type': 'GENn',
2261 'gl_test_func': 'glGenTransformFeedbacks',
2262 'resource_type': 'TransformFeedback',
2263 'resource_types': 'TransformFeedbacks',
2264 'unsafe': True,
2266 'GetActiveAttrib': {
2267 'type': 'Custom',
2268 'data_transfer_methods': ['shm'],
2269 'cmd_args':
2270 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2271 'void* result',
2272 'result': [
2273 'int32_t success',
2274 'int32_t size',
2275 'uint32_t type',
2278 'GetActiveUniform': {
2279 'type': 'Custom',
2280 'data_transfer_methods': ['shm'],
2281 'cmd_args':
2282 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2283 'void* result',
2284 'result': [
2285 'int32_t success',
2286 'int32_t size',
2287 'uint32_t type',
2290 'GetActiveUniformBlockiv': {
2291 'type': 'Custom',
2292 'data_transfer_methods': ['shm'],
2293 'result': ['SizedResult<GLint>'],
2294 'unsafe': True,
2296 'GetActiveUniformBlockName': {
2297 'type': 'Custom',
2298 'data_transfer_methods': ['shm'],
2299 'cmd_args':
2300 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2301 'void* result',
2302 'result': ['int32_t'],
2303 'unsafe': True,
2305 'GetActiveUniformsiv': {
2306 'type': 'Custom',
2307 'data_transfer_methods': ['shm'],
2308 'cmd_args':
2309 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2310 'GLint* params',
2311 'result': ['SizedResult<GLint>'],
2312 'unsafe': True,
2314 'GetAttachedShaders': {
2315 'type': 'Custom',
2316 'data_transfer_methods': ['shm'],
2317 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2318 'result': ['SizedResult<GLuint>'],
2320 'GetAttribLocation': {
2321 'type': 'Custom',
2322 'data_transfer_methods': ['shm'],
2323 'cmd_args':
2324 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2325 'result': ['GLint'],
2326 'error_return': -1,
2328 'GetFragDataLocation': {
2329 'type': 'Custom',
2330 'data_transfer_methods': ['shm'],
2331 'cmd_args':
2332 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2333 'result': ['GLint'],
2334 'error_return': -1,
2335 'unsafe': True,
2337 'GetBooleanv': {
2338 'type': 'GETn',
2339 'result': ['SizedResult<GLboolean>'],
2340 'decoder_func': 'DoGetBooleanv',
2341 'gl_test_func': 'glGetBooleanv',
2343 'GetBufferParameteriv': {
2344 'type': 'GETn',
2345 'result': ['SizedResult<GLint>'],
2346 'decoder_func': 'DoGetBufferParameteriv',
2347 'expectation': False,
2348 'shadowed': True,
2350 'GetError': {
2351 'type': 'Is',
2352 'decoder_func': 'GetErrorState()->GetGLError',
2353 'impl_func': False,
2354 'result': ['GLenum'],
2355 'client_test': False,
2357 'GetFloatv': {
2358 'type': 'GETn',
2359 'result': ['SizedResult<GLfloat>'],
2360 'decoder_func': 'DoGetFloatv',
2361 'gl_test_func': 'glGetFloatv',
2363 'GetFramebufferAttachmentParameteriv': {
2364 'type': 'GETn',
2365 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2366 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2367 'result': ['SizedResult<GLint>'],
2369 'GetIntegerv': {
2370 'type': 'GETn',
2371 'result': ['SizedResult<GLint>'],
2372 'decoder_func': 'DoGetIntegerv',
2373 'client_test': False,
2375 'GetInternalformativ': {
2376 'type': 'GETn',
2377 'result': ['SizedResult<GLint>'],
2378 'unsafe': True,
2380 'GetMaxValueInBufferCHROMIUM': {
2381 'type': 'Is',
2382 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2383 'result': ['GLuint'],
2384 'unit_test': False,
2385 'client_test': False,
2386 'extension': True,
2387 'chromium': True,
2388 'impl_func': False,
2390 'GetProgramiv': {
2391 'type': 'GETn',
2392 'decoder_func': 'DoGetProgramiv',
2393 'result': ['SizedResult<GLint>'],
2394 'expectation': False,
2396 'GetProgramInfoCHROMIUM': {
2397 'type': 'Custom',
2398 'expectation': False,
2399 'impl_func': False,
2400 'extension': True,
2401 'chromium': True,
2402 'client_test': False,
2403 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2404 'result': [
2405 'uint32_t link_status',
2406 'uint32_t num_attribs',
2407 'uint32_t num_uniforms',
2410 'GetProgramInfoLog': {
2411 'type': 'STRn',
2412 'expectation': False,
2414 'GetRenderbufferParameteriv': {
2415 'type': 'GETn',
2416 'decoder_func': 'DoGetRenderbufferParameteriv',
2417 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2418 'result': ['SizedResult<GLint>'],
2420 'GetSamplerParameterfv': {
2421 'type': 'GETn',
2422 'result': ['SizedResult<GLfloat>'],
2423 'id_mapping': [ 'Sampler' ],
2424 'unsafe': True,
2426 'GetSamplerParameteriv': {
2427 'type': 'GETn',
2428 'result': ['SizedResult<GLint>'],
2429 'id_mapping': [ 'Sampler' ],
2430 'unsafe': True,
2432 'GetShaderiv': {
2433 'type': 'GETn',
2434 'decoder_func': 'DoGetShaderiv',
2435 'result': ['SizedResult<GLint>'],
2437 'GetShaderInfoLog': {
2438 'type': 'STRn',
2439 'get_len_func': 'glGetShaderiv',
2440 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2441 'unit_test': False,
2443 'GetShaderPrecisionFormat': {
2444 'type': 'Custom',
2445 'data_transfer_methods': ['shm'],
2446 'cmd_args':
2447 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2448 'void* result',
2449 'result': [
2450 'int32_t success',
2451 'int32_t min_range',
2452 'int32_t max_range',
2453 'int32_t precision',
2456 'GetShaderSource': {
2457 'type': 'STRn',
2458 'get_len_func': 'DoGetShaderiv',
2459 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2460 'unit_test': False,
2461 'client_test': False,
2463 'GetString': {
2464 'type': 'Custom',
2465 'client_test': False,
2466 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2468 'GetSynciv': {
2469 'type': 'GETn',
2470 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2471 'result': ['SizedResult<GLint>'],
2472 'id_mapping': ['Sync'],
2473 'unsafe': True,
2475 'GetTexParameterfv': {
2476 'type': 'GETn',
2477 'decoder_func': 'DoGetTexParameterfv',
2478 'result': ['SizedResult<GLfloat>']
2480 'GetTexParameteriv': {
2481 'type': 'GETn',
2482 'decoder_func': 'DoGetTexParameteriv',
2483 'result': ['SizedResult<GLint>']
2485 'GetTranslatedShaderSourceANGLE': {
2486 'type': 'STRn',
2487 'get_len_func': 'DoGetShaderiv',
2488 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2489 'unit_test': False,
2490 'extension': True,
2492 'GetUniformBlockIndex': {
2493 'type': 'Custom',
2494 'data_transfer_methods': ['shm'],
2495 'cmd_args':
2496 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2497 'result': ['GLuint'],
2498 'error_return': 'GL_INVALID_INDEX',
2499 'unsafe': True,
2501 'GetUniformBlocksCHROMIUM': {
2502 'type': 'Custom',
2503 'expectation': False,
2504 'impl_func': False,
2505 'extension': True,
2506 'chromium': True,
2507 'client_test': False,
2508 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2509 'result': ['uint32_t'],
2510 'unsafe': True,
2512 'GetUniformsES3CHROMIUM': {
2513 'type': 'Custom',
2514 'expectation': False,
2515 'impl_func': False,
2516 'extension': True,
2517 'chromium': True,
2518 'client_test': False,
2519 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2520 'result': ['uint32_t'],
2521 'unsafe': True,
2523 'GetTransformFeedbackVarying': {
2524 'type': 'Custom',
2525 'data_transfer_methods': ['shm'],
2526 'cmd_args':
2527 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2528 'void* result',
2529 'result': [
2530 'int32_t success',
2531 'int32_t size',
2532 'uint32_t type',
2534 'unsafe': True,
2536 'GetTransformFeedbackVaryingsCHROMIUM': {
2537 'type': 'Custom',
2538 'expectation': False,
2539 'impl_func': False,
2540 'extension': True,
2541 'chromium': True,
2542 'client_test': False,
2543 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2544 'result': ['uint32_t'],
2545 'unsafe': True,
2547 'GetUniformfv': {
2548 'type': 'Custom',
2549 'data_transfer_methods': ['shm'],
2550 'result': ['SizedResult<GLfloat>'],
2552 'GetUniformiv': {
2553 'type': 'Custom',
2554 'data_transfer_methods': ['shm'],
2555 'result': ['SizedResult<GLint>'],
2557 'GetUniformIndices': {
2558 'type': 'Custom',
2559 'data_transfer_methods': ['shm'],
2560 'result': ['SizedResult<GLuint>'],
2561 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
2562 'GLuint* indices',
2563 'unsafe': True,
2565 'GetUniformLocation': {
2566 'type': 'Custom',
2567 'data_transfer_methods': ['shm'],
2568 'cmd_args':
2569 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2570 'result': ['GLint'],
2571 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
2573 'GetVertexAttribfv': {
2574 'type': 'GETn',
2575 'result': ['SizedResult<GLfloat>'],
2576 'impl_decl': False,
2577 'decoder_func': 'DoGetVertexAttribfv',
2578 'expectation': False,
2579 'client_test': False,
2581 'GetVertexAttribiv': {
2582 'type': 'GETn',
2583 'result': ['SizedResult<GLint>'],
2584 'impl_decl': False,
2585 'decoder_func': 'DoGetVertexAttribiv',
2586 'expectation': False,
2587 'client_test': False,
2589 'GetVertexAttribPointerv': {
2590 'type': 'Custom',
2591 'data_transfer_methods': ['shm'],
2592 'result': ['SizedResult<GLuint>'],
2593 'client_test': False,
2595 'InvalidateFramebuffer': {
2596 'type': 'PUTn',
2597 'count': 1,
2598 'client_test': False,
2599 'unit_test': False,
2600 'unsafe': True,
2602 'InvalidateSubFramebuffer': {
2603 'type': 'PUTn',
2604 'count': 1,
2605 'client_test': False,
2606 'unit_test': False,
2607 'unsafe': True,
2609 'IsBuffer': {
2610 'type': 'Is',
2611 'decoder_func': 'DoIsBuffer',
2612 'expectation': False,
2614 'IsEnabled': {
2615 'type': 'Is',
2616 'decoder_func': 'DoIsEnabled',
2617 'client_test': False,
2618 'impl_func': False,
2619 'expectation': False,
2621 'IsFramebuffer': {
2622 'type': 'Is',
2623 'decoder_func': 'DoIsFramebuffer',
2624 'expectation': False,
2626 'IsProgram': {
2627 'type': 'Is',
2628 'decoder_func': 'DoIsProgram',
2629 'expectation': False,
2631 'IsRenderbuffer': {
2632 'type': 'Is',
2633 'decoder_func': 'DoIsRenderbuffer',
2634 'expectation': False,
2636 'IsShader': {
2637 'type': 'Is',
2638 'decoder_func': 'DoIsShader',
2639 'expectation': False,
2641 'IsSampler': {
2642 'type': 'Is',
2643 'id_mapping': [ 'Sampler' ],
2644 'expectation': False,
2645 'unsafe': True,
2647 'IsSync': {
2648 'type': 'Is',
2649 'id_mapping': [ 'Sync' ],
2650 'cmd_args': 'GLuint sync',
2651 'expectation': False,
2652 'unsafe': True,
2654 'IsTexture': {
2655 'type': 'Is',
2656 'decoder_func': 'DoIsTexture',
2657 'expectation': False,
2659 'IsTransformFeedback': {
2660 'type': 'Is',
2661 'id_mapping': [ 'TransformFeedback' ],
2662 'expectation': False,
2663 'unsafe': True,
2665 'LinkProgram': {
2666 'decoder_func': 'DoLinkProgram',
2667 'impl_func': False,
2669 'MapBufferCHROMIUM': {
2670 'gen_cmd': False,
2671 'extension': True,
2672 'chromium': True,
2673 'client_test': False,
2675 'MapBufferSubDataCHROMIUM': {
2676 'gen_cmd': False,
2677 'extension': True,
2678 'chromium': True,
2679 'client_test': False,
2680 'pepper_interface': 'ChromiumMapSub',
2682 'MapTexSubImage2DCHROMIUM': {
2683 'gen_cmd': False,
2684 'extension': "CHROMIUM_sub_image",
2685 'chromium': True,
2686 'client_test': False,
2687 'pepper_interface': 'ChromiumMapSub',
2689 'MapBufferRange': {
2690 'type': 'Custom',
2691 'data_transfer_methods': ['shm'],
2692 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
2693 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
2694 'uint32_t data_shm_id, uint32_t data_shm_offset, '
2695 'uint32_t result_shm_id, uint32_t result_shm_offset',
2696 'unsafe': True,
2697 'result': ['uint32_t'],
2699 'PauseTransformFeedback': {
2700 'unsafe': True,
2702 'PixelStorei': {'type': 'Manual'},
2703 'PostSubBufferCHROMIUM': {
2704 'type': 'Custom',
2705 'impl_func': False,
2706 'unit_test': False,
2707 'client_test': False,
2708 'extension': True,
2709 'chromium': True,
2711 'ProduceTextureCHROMIUM': {
2712 'decoder_func': 'DoProduceTextureCHROMIUM',
2713 'impl_func': False,
2714 'type': 'PUT',
2715 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2716 'unit_test': False,
2717 'client_test': False,
2718 'extension': "CHROMIUM_texture_mailbox",
2719 'chromium': True,
2720 'trace_level': 1,
2722 'ProduceTextureDirectCHROMIUM': {
2723 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
2724 'impl_func': False,
2725 'type': 'PUT',
2726 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2727 'unit_test': False,
2728 'client_test': False,
2729 'extension': "CHROMIUM_texture_mailbox",
2730 'chromium': True,
2731 'trace_level': 1,
2733 'RenderbufferStorage': {
2734 'decoder_func': 'DoRenderbufferStorage',
2735 'gl_test_func': 'glRenderbufferStorageEXT',
2736 'expectation': False,
2738 'RenderbufferStorageMultisampleCHROMIUM': {
2739 'cmd_comment':
2740 '// GL_CHROMIUM_framebuffer_multisample\n',
2741 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
2742 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
2743 'expectation': False,
2744 'unit_test': False,
2745 'extension_flag': 'chromium_framebuffer_multisample',
2746 'pepper_interface': 'FramebufferMultisample',
2747 'pepper_name': 'RenderbufferStorageMultisampleEXT',
2749 'RenderbufferStorageMultisampleEXT': {
2750 'cmd_comment':
2751 '// GL_EXT_multisampled_render_to_texture\n',
2752 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
2753 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
2754 'expectation': False,
2755 'unit_test': False,
2756 'extension_flag': 'multisampled_render_to_texture',
2758 'ReadBuffer': {
2759 'unsafe': True,
2761 'ReadPixels': {
2762 'cmd_comment':
2763 '// ReadPixels has the result separated from the pixel buffer so that\n'
2764 '// it is easier to specify the result going to some specific place\n'
2765 '// that exactly fits the rectangle of pixels.\n',
2766 'type': 'Custom',
2767 'data_transfer_methods': ['shm'],
2768 'impl_func': False,
2769 'client_test': False,
2770 'cmd_args':
2771 'GLint x, GLint y, GLsizei width, GLsizei height, '
2772 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
2773 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
2774 'uint32_t result_shm_id, uint32_t result_shm_offset, '
2775 'GLboolean async',
2776 'result': ['uint32_t'],
2777 'defer_reads': True,
2779 'ReleaseShaderCompiler': {
2780 'decoder_func': 'DoReleaseShaderCompiler',
2781 'unit_test': False,
2783 'ResumeTransformFeedback': {
2784 'unsafe': True,
2786 'SamplerParameterf': {
2787 'valid_args': {
2788 '2': 'GL_NEAREST'
2790 'id_mapping': [ 'Sampler' ],
2791 'unsafe': True,
2793 'SamplerParameterfv': {
2794 'type': 'PUT',
2795 'data_value': 'GL_NEAREST',
2796 'count': 1,
2797 'gl_test_func': 'glSamplerParameterf',
2798 'decoder_func': 'DoSamplerParameterfv',
2799 'first_element_only': True,
2800 'id_mapping': [ 'Sampler' ],
2801 'unsafe': True,
2803 'SamplerParameteri': {
2804 'valid_args': {
2805 '2': 'GL_NEAREST'
2807 'id_mapping': [ 'Sampler' ],
2808 'unsafe': True,
2810 'SamplerParameteriv': {
2811 'type': 'PUT',
2812 'data_value': 'GL_NEAREST',
2813 'count': 1,
2814 'gl_test_func': 'glSamplerParameteri',
2815 'decoder_func': 'DoSamplerParameteriv',
2816 'first_element_only': True,
2817 'unsafe': True,
2819 'ShaderBinary': {
2820 'type': 'Custom',
2821 'client_test': False,
2823 'ShaderSource': {
2824 'type': 'PUTSTR',
2825 'decoder_func': 'DoShaderSource',
2826 'expectation': False,
2827 'data_transfer_methods': ['bucket'],
2828 'cmd_args':
2829 'GLuint shader, const char** str',
2830 'pepper_args':
2831 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2833 'StencilMask': {
2834 'type': 'StateSetFrontBack',
2835 'state': 'StencilMask',
2836 'no_gl': True,
2837 'expectation': False,
2839 'StencilMaskSeparate': {
2840 'type': 'StateSetFrontBackSeparate',
2841 'state': 'StencilMask',
2842 'no_gl': True,
2843 'expectation': False,
2845 'SwapBuffers': {
2846 'impl_func': False,
2847 'decoder_func': 'DoSwapBuffers',
2848 'unit_test': False,
2849 'client_test': False,
2850 'extension': True,
2851 'trace_level': 1,
2853 'SwapInterval': {
2854 'impl_func': False,
2855 'decoder_func': 'DoSwapInterval',
2856 'unit_test': False,
2857 'client_test': False,
2858 'extension': True,
2859 'trace_level': 1,
2861 'TexImage2D': {
2862 'type': 'Manual',
2863 'data_transfer_methods': ['shm'],
2864 'client_test': False,
2866 'TexImage3D': {
2867 'type': 'Manual',
2868 'data_transfer_methods': ['shm'],
2869 'client_test': False,
2870 'unsafe': True,
2872 'TexParameterf': {
2873 'decoder_func': 'DoTexParameterf',
2874 'valid_args': {
2875 '2': 'GL_NEAREST'
2878 'TexParameteri': {
2879 'decoder_func': 'DoTexParameteri',
2880 'valid_args': {
2881 '2': 'GL_NEAREST'
2884 'TexParameterfv': {
2885 'type': 'PUT',
2886 'data_value': 'GL_NEAREST',
2887 'count': 1,
2888 'decoder_func': 'DoTexParameterfv',
2889 'gl_test_func': 'glTexParameterf',
2890 'first_element_only': True,
2892 'TexParameteriv': {
2893 'type': 'PUT',
2894 'data_value': 'GL_NEAREST',
2895 'count': 1,
2896 'decoder_func': 'DoTexParameteriv',
2897 'gl_test_func': 'glTexParameteri',
2898 'first_element_only': True,
2900 'TexStorage3D': {
2901 'unsafe': True,
2903 'TexSubImage2D': {
2904 'type': 'Manual',
2905 'data_transfer_methods': ['shm'],
2906 'client_test': False,
2907 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2908 'GLint xoffset, GLint yoffset, '
2909 'GLsizei width, GLsizei height, '
2910 'GLenumTextureFormat format, GLenumPixelType type, '
2911 'const void* pixels, GLboolean internal'
2913 'TexSubImage3D': {
2914 'type': 'Manual',
2915 'data_transfer_methods': ['shm'],
2916 'client_test': False,
2917 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2918 'GLint xoffset, GLint yoffset, GLint zoffset, '
2919 'GLsizei width, GLsizei height, GLsizei depth, '
2920 'GLenumTextureFormat format, GLenumPixelType type, '
2921 'const void* pixels, GLboolean internal',
2922 'unsafe': True,
2924 'TransformFeedbackVaryings': {
2925 'type': 'PUTSTR',
2926 'data_transfer_methods': ['bucket'],
2927 'decoder_func': 'DoTransformFeedbackVaryings',
2928 'cmd_args':
2929 'GLuint program, const char** varyings, GLenum buffermode',
2930 'unsafe': True,
2932 'Uniform1f': {'type': 'PUTXn', 'count': 1},
2933 'Uniform1fv': {
2934 'type': 'PUTn',
2935 'count': 1,
2936 'decoder_func': 'DoUniform1fv',
2938 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2939 'Uniform1iv': {
2940 'type': 'PUTn',
2941 'count': 1,
2942 'decoder_func': 'DoUniform1iv',
2943 'unit_test': False,
2945 'Uniform1ui': {
2946 'type': 'PUTXn',
2947 'count': 1,
2948 'unsafe': True,
2950 'Uniform1uiv': {
2951 'type': 'PUTn',
2952 'count': 1,
2953 'unsafe': True,
2955 'Uniform2i': {'type': 'PUTXn', 'count': 2},
2956 'Uniform2f': {'type': 'PUTXn', 'count': 2},
2957 'Uniform2fv': {
2958 'type': 'PUTn',
2959 'count': 2,
2960 'decoder_func': 'DoUniform2fv',
2962 'Uniform2iv': {
2963 'type': 'PUTn',
2964 'count': 2,
2965 'decoder_func': 'DoUniform2iv',
2967 'Uniform2ui': {
2968 'type': 'PUTXn',
2969 'count': 2,
2970 'unsafe': True,
2972 'Uniform2uiv': {
2973 'type': 'PUTn',
2974 'count': 2,
2975 'unsafe': True,
2977 'Uniform3i': {'type': 'PUTXn', 'count': 3},
2978 'Uniform3f': {'type': 'PUTXn', 'count': 3},
2979 'Uniform3fv': {
2980 'type': 'PUTn',
2981 'count': 3,
2982 'decoder_func': 'DoUniform3fv',
2984 'Uniform3iv': {
2985 'type': 'PUTn',
2986 'count': 3,
2987 'decoder_func': 'DoUniform3iv',
2989 'Uniform3ui': {
2990 'type': 'PUTXn',
2991 'count': 3,
2992 'unsafe': True,
2994 'Uniform3uiv': {
2995 'type': 'PUTn',
2996 'count': 3,
2997 'unsafe': True,
2999 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3000 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3001 'Uniform4fv': {
3002 'type': 'PUTn',
3003 'count': 4,
3004 'decoder_func': 'DoUniform4fv',
3006 'Uniform4iv': {
3007 'type': 'PUTn',
3008 'count': 4,
3009 'decoder_func': 'DoUniform4iv',
3011 'Uniform4ui': {
3012 'type': 'PUTXn',
3013 'count': 4,
3014 'unsafe': True,
3016 'Uniform4uiv': {
3017 'type': 'PUTn',
3018 'count': 4,
3019 'unsafe': True,
3021 'UniformMatrix2fv': {
3022 'type': 'PUTn',
3023 'count': 4,
3024 'decoder_func': 'DoUniformMatrix2fv',
3026 'UniformMatrix2x3fv': {
3027 'type': 'PUTn',
3028 'count': 6,
3029 'unsafe': True,
3031 'UniformMatrix2x4fv': {
3032 'type': 'PUTn',
3033 'count': 8,
3034 'unsafe': True,
3036 'UniformMatrix3fv': {
3037 'type': 'PUTn',
3038 'count': 9,
3039 'decoder_func': 'DoUniformMatrix3fv',
3041 'UniformMatrix3x2fv': {
3042 'type': 'PUTn',
3043 'count': 6,
3044 'unsafe': True,
3046 'UniformMatrix3x4fv': {
3047 'type': 'PUTn',
3048 'count': 12,
3049 'unsafe': True,
3051 'UniformMatrix4fv': {
3052 'type': 'PUTn',
3053 'count': 16,
3054 'decoder_func': 'DoUniformMatrix4fv',
3056 'UniformMatrix4x2fv': {
3057 'type': 'PUTn',
3058 'count': 8,
3059 'unsafe': True,
3061 'UniformMatrix4x3fv': {
3062 'type': 'PUTn',
3063 'count': 12,
3064 'unsafe': True,
3066 'UniformBlockBinding': {
3067 'type': 'Custom',
3068 'impl_func': False,
3069 'unsafe': True,
3071 'UnmapBufferCHROMIUM': {
3072 'gen_cmd': False,
3073 'extension': True,
3074 'chromium': True,
3075 'client_test': False,
3077 'UnmapBufferSubDataCHROMIUM': {
3078 'gen_cmd': False,
3079 'extension': True,
3080 'chromium': True,
3081 'client_test': False,
3082 'pepper_interface': 'ChromiumMapSub',
3084 'UnmapBuffer': {
3085 'type': 'Custom',
3086 'unsafe': True,
3088 'UnmapTexSubImage2DCHROMIUM': {
3089 'gen_cmd': False,
3090 'extension': "CHROMIUM_sub_image",
3091 'chromium': True,
3092 'client_test': False,
3093 'pepper_interface': 'ChromiumMapSub',
3095 'UseProgram': {
3096 'type': 'Bind',
3097 'decoder_func': 'DoUseProgram',
3099 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3100 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3101 'VertexAttrib1fv': {
3102 'type': 'PUT',
3103 'count': 1,
3104 'decoder_func': 'DoVertexAttrib1fv',
3106 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3107 'VertexAttrib2fv': {
3108 'type': 'PUT',
3109 'count': 2,
3110 'decoder_func': 'DoVertexAttrib2fv',
3112 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3113 'VertexAttrib3fv': {
3114 'type': 'PUT',
3115 'count': 3,
3116 'decoder_func': 'DoVertexAttrib3fv',
3118 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3119 'VertexAttrib4fv': {
3120 'type': 'PUT',
3121 'count': 4,
3122 'decoder_func': 'DoVertexAttrib4fv',
3124 'VertexAttribI4i': {
3125 'unsafe': True,
3127 'VertexAttribI4iv': {
3128 'type': 'PUT',
3129 'count': 4,
3130 'unsafe': True,
3132 'VertexAttribI4ui': {
3133 'unsafe': True,
3135 'VertexAttribI4uiv': {
3136 'type': 'PUT',
3137 'count': 4,
3138 'unsafe': True,
3140 'VertexAttribIPointer': {
3141 'type': 'Manual',
3142 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3143 'GLenumVertexAttribType type, GLsizei stride, '
3144 'GLuint offset',
3145 'client_test': False,
3146 'unsafe': True,
3148 'VertexAttribPointer': {
3149 'type': 'Manual',
3150 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3151 'GLenumVertexAttribType type, GLboolean normalized, '
3152 'GLsizei stride, GLuint offset',
3153 'client_test': False,
3155 'WaitSync': {
3156 'type': 'Custom',
3157 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3158 'GLuint timeout_0, GLuint timeout_1',
3159 'impl_func': False,
3160 'client_test': False,
3161 'unsafe': True,
3163 'Scissor': {
3164 'type': 'StateSet',
3165 'state': 'Scissor',
3167 'Viewport': {
3168 'decoder_func': 'DoViewport',
3170 'ResizeCHROMIUM': {
3171 'type': 'Custom',
3172 'impl_func': False,
3173 'unit_test': False,
3174 'extension': True,
3175 'chromium': True,
3177 'GetRequestableExtensionsCHROMIUM': {
3178 'type': 'Custom',
3179 'impl_func': False,
3180 'cmd_args': 'uint32_t bucket_id',
3181 'extension': True,
3182 'chromium': True,
3184 'RequestExtensionCHROMIUM': {
3185 'type': 'Custom',
3186 'impl_func': False,
3187 'client_test': False,
3188 'cmd_args': 'uint32_t bucket_id',
3189 'extension': True,
3190 'chromium': True,
3192 'RateLimitOffscreenContextCHROMIUM': {
3193 'gen_cmd': False,
3194 'extension': True,
3195 'chromium': True,
3196 'client_test': False,
3198 'CreateStreamTextureCHROMIUM': {
3199 'type': 'HandWritten',
3200 'impl_func': False,
3201 'gen_cmd': False,
3202 'extension': True,
3203 'chromium': True,
3205 'TexImageIOSurface2DCHROMIUM': {
3206 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3207 'unit_test': False,
3208 'extension': True,
3209 'chromium': True,
3211 'CopyTextureCHROMIUM': {
3212 'decoder_func': 'DoCopyTextureCHROMIUM',
3213 'unit_test': False,
3214 'extension': True,
3215 'chromium': True,
3217 'CopySubTextureCHROMIUM': {
3218 'decoder_func': 'DoCopySubTextureCHROMIUM',
3219 'unit_test': False,
3220 'extension': True,
3221 'chromium': True,
3223 'TexStorage2DEXT': {
3224 'unit_test': False,
3225 'extension': True,
3226 'decoder_func': 'DoTexStorage2DEXT',
3228 'DrawArraysInstancedANGLE': {
3229 'type': 'Manual',
3230 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3231 'GLsizei primcount',
3232 'extension': True,
3233 'unit_test': False,
3234 'pepper_interface': 'InstancedArrays',
3235 'defer_draws': True,
3237 'DrawBuffersEXT': {
3238 'type': 'PUTn',
3239 'decoder_func': 'DoDrawBuffersEXT',
3240 'count': 1,
3241 'client_test': False,
3242 'unit_test': False,
3243 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3244 # work without.
3245 'extension': True,
3246 'pepper_interface': 'DrawBuffers',
3248 'DrawElementsInstancedANGLE': {
3249 'type': 'Manual',
3250 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3251 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3252 'extension': True,
3253 'unit_test': False,
3254 'client_test': False,
3255 'pepper_interface': 'InstancedArrays',
3256 'defer_draws': True,
3258 'VertexAttribDivisorANGLE': {
3259 'type': 'Manual',
3260 'cmd_args': 'GLuint index, GLuint divisor',
3261 'extension': True,
3262 'unit_test': False,
3263 'pepper_interface': 'InstancedArrays',
3265 'GenQueriesEXT': {
3266 'type': 'GENn',
3267 'gl_test_func': 'glGenQueriesARB',
3268 'resource_type': 'Query',
3269 'resource_types': 'Queries',
3270 'unit_test': False,
3271 'pepper_interface': 'Query',
3272 'not_shared': 'True',
3273 'extension': "occlusion_query_EXT",
3275 'DeleteQueriesEXT': {
3276 'type': 'DELn',
3277 'gl_test_func': 'glDeleteQueriesARB',
3278 'resource_type': 'Query',
3279 'resource_types': 'Queries',
3280 'unit_test': False,
3281 'pepper_interface': 'Query',
3282 'extension': "occlusion_query_EXT",
3284 'IsQueryEXT': {
3285 'gen_cmd': False,
3286 'client_test': False,
3287 'pepper_interface': 'Query',
3288 'extension': "occlusion_query_EXT",
3290 'BeginQueryEXT': {
3291 'type': 'Manual',
3292 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3293 'data_transfer_methods': ['shm'],
3294 'gl_test_func': 'glBeginQuery',
3295 'pepper_interface': 'Query',
3296 'extension': "occlusion_query_EXT",
3298 'BeginTransformFeedback': {
3299 'unsafe': True,
3301 'EndQueryEXT': {
3302 'type': 'Manual',
3303 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3304 'gl_test_func': 'glEndnQuery',
3305 'client_test': False,
3306 'pepper_interface': 'Query',
3307 'extension': "occlusion_query_EXT",
3309 'EndTransformFeedback': {
3310 'unsafe': True,
3312 'GetQueryivEXT': {
3313 'gen_cmd': False,
3314 'client_test': False,
3315 'gl_test_func': 'glGetQueryiv',
3316 'pepper_interface': 'Query',
3317 'extension': "occlusion_query_EXT",
3319 'GetQueryObjectuivEXT': {
3320 'gen_cmd': False,
3321 'client_test': False,
3322 'gl_test_func': 'glGetQueryObjectuiv',
3323 'pepper_interface': 'Query',
3324 'extension': "occlusion_query_EXT",
3326 'BindUniformLocationCHROMIUM': {
3327 'type': 'GLchar',
3328 'extension': True,
3329 'data_transfer_methods': ['bucket'],
3330 'needs_size': True,
3331 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3333 'InsertEventMarkerEXT': {
3334 'type': 'GLcharN',
3335 'decoder_func': 'DoInsertEventMarkerEXT',
3336 'expectation': False,
3337 'extension': True,
3339 'PushGroupMarkerEXT': {
3340 'type': 'GLcharN',
3341 'decoder_func': 'DoPushGroupMarkerEXT',
3342 'expectation': False,
3343 'extension': True,
3345 'PopGroupMarkerEXT': {
3346 'decoder_func': 'DoPopGroupMarkerEXT',
3347 'expectation': False,
3348 'extension': True,
3349 'impl_func': False,
3352 'GenVertexArraysOES': {
3353 'type': 'GENn',
3354 'extension': True,
3355 'gl_test_func': 'glGenVertexArraysOES',
3356 'resource_type': 'VertexArray',
3357 'resource_types': 'VertexArrays',
3358 'unit_test': False,
3359 'pepper_interface': 'VertexArrayObject',
3361 'BindVertexArrayOES': {
3362 'type': 'Bind',
3363 'extension': True,
3364 'gl_test_func': 'glBindVertexArrayOES',
3365 'decoder_func': 'DoBindVertexArrayOES',
3366 'gen_func': 'GenVertexArraysOES',
3367 'unit_test': False,
3368 'client_test': False,
3369 'pepper_interface': 'VertexArrayObject',
3371 'DeleteVertexArraysOES': {
3372 'type': 'DELn',
3373 'extension': True,
3374 'gl_test_func': 'glDeleteVertexArraysOES',
3375 'resource_type': 'VertexArray',
3376 'resource_types': 'VertexArrays',
3377 'unit_test': False,
3378 'pepper_interface': 'VertexArrayObject',
3380 'IsVertexArrayOES': {
3381 'type': 'Is',
3382 'extension': True,
3383 'gl_test_func': 'glIsVertexArrayOES',
3384 'decoder_func': 'DoIsVertexArrayOES',
3385 'expectation': False,
3386 'unit_test': False,
3387 'pepper_interface': 'VertexArrayObject',
3389 'BindTexImage2DCHROMIUM': {
3390 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3391 'unit_test': False,
3392 'extension': True,
3393 'chromium': True,
3395 'ReleaseTexImage2DCHROMIUM': {
3396 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3397 'unit_test': False,
3398 'extension': True,
3399 'chromium': True,
3401 'ShallowFinishCHROMIUM': {
3402 'impl_func': False,
3403 'gen_cmd': False,
3404 'extension': True,
3405 'chromium': True,
3406 'client_test': False,
3408 'ShallowFlushCHROMIUM': {
3409 'impl_func': False,
3410 'gen_cmd': False,
3411 'extension': "CHROMIUM_miscellaneous",
3412 'chromium': True,
3413 'client_test': False,
3415 'OrderingBarrierCHROMIUM': {
3416 'impl_func': False,
3417 'gen_cmd': False,
3418 'extension': True,
3419 'chromium': True,
3420 'client_test': False,
3422 'TraceBeginCHROMIUM': {
3423 'type': 'Custom',
3424 'impl_func': False,
3425 'client_test': False,
3426 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3427 'extension': True,
3428 'chromium': True,
3430 'TraceEndCHROMIUM': {
3431 'impl_func': False,
3432 'client_test': False,
3433 'decoder_func': 'DoTraceEndCHROMIUM',
3434 'unit_test': False,
3435 'extension': True,
3436 'chromium': True,
3438 'AsyncTexImage2DCHROMIUM': {
3439 'type': 'Manual',
3440 'data_transfer_methods': ['shm'],
3441 'client_test': False,
3442 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3443 'GLintTextureInternalFormat internalformat, '
3444 'GLsizei width, GLsizei height, '
3445 'GLintTextureBorder border, '
3446 'GLenumTextureFormat format, GLenumPixelType type, '
3447 'const void* pixels, '
3448 'uint32_t async_upload_token, '
3449 'void* sync_data',
3450 'extension': True,
3451 'chromium': True,
3453 'AsyncTexSubImage2DCHROMIUM': {
3454 'type': 'Manual',
3455 'data_transfer_methods': ['shm'],
3456 'client_test': False,
3457 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3458 'GLint xoffset, GLint yoffset, '
3459 'GLsizei width, GLsizei height, '
3460 'GLenumTextureFormat format, GLenumPixelType type, '
3461 'const void* data, '
3462 'uint32_t async_upload_token, '
3463 'void* sync_data',
3464 'extension': True,
3465 'chromium': True,
3467 'WaitAsyncTexImage2DCHROMIUM': {
3468 'type': 'Manual',
3469 'client_test': False,
3470 'extension': True,
3471 'chromium': True,
3473 'WaitAllAsyncTexImage2DCHROMIUM': {
3474 'type': 'Manual',
3475 'client_test': False,
3476 'extension': True,
3477 'chromium': True,
3479 'DiscardFramebufferEXT': {
3480 'type': 'PUTn',
3481 'count': 1,
3482 'decoder_func': 'DoDiscardFramebufferEXT',
3483 'unit_test': False,
3484 'client_test': False,
3485 'extension_flag': 'ext_discard_framebuffer',
3487 'LoseContextCHROMIUM': {
3488 'decoder_func': 'DoLoseContextCHROMIUM',
3489 'unit_test': False,
3490 'extension': True,
3491 'chromium': True,
3493 'InsertSyncPointCHROMIUM': {
3494 'type': 'HandWritten',
3495 'impl_func': False,
3496 'extension': "CHROMIUM_sync_point",
3497 'chromium': True,
3499 'WaitSyncPointCHROMIUM': {
3500 'type': 'Custom',
3501 'impl_func': True,
3502 'extension': "CHROMIUM_sync_point",
3503 'chromium': True,
3504 'trace_level': 1,
3506 'DiscardBackbufferCHROMIUM': {
3507 'type': 'Custom',
3508 'impl_func': True,
3509 'extension': True,
3510 'chromium': True,
3512 'ScheduleOverlayPlaneCHROMIUM': {
3513 'type': 'Custom',
3514 'impl_func': True,
3515 'unit_test': False,
3516 'client_test': False,
3517 'extension': True,
3518 'chromium': True,
3520 'MatrixLoadfCHROMIUM': {
3521 'type': 'PUT',
3522 'count': 16,
3523 'data_type': 'GLfloat',
3524 'decoder_func': 'DoMatrixLoadfCHROMIUM',
3525 'gl_test_func': 'glMatrixLoadfEXT',
3526 'chromium': True,
3527 'extension': True,
3528 'extension_flag': 'chromium_path_rendering',
3530 'MatrixLoadIdentityCHROMIUM': {
3531 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
3532 'gl_test_func': 'glMatrixLoadIdentityEXT',
3533 'chromium': True,
3534 'extension': True,
3535 'extension_flag': 'chromium_path_rendering',
3540 def Grouper(n, iterable, fillvalue=None):
3541 """Collect data into fixed-length chunks or blocks"""
3542 args = [iter(iterable)] * n
3543 return itertools.izip_longest(fillvalue=fillvalue, *args)
3546 def SplitWords(input_string):
3547 """Transforms a input_string into a list of lower-case components.
3549 Args:
3550 input_string: the input string.
3552 Returns:
3553 a list of lower-case words.
3555 if input_string.find('_') > -1:
3556 # 'some_TEXT_' -> 'some text'
3557 return input_string.replace('_', ' ').strip().lower().split()
3558 else:
3559 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
3560 # mixed case.
3561 # look for capitalization to cut input_strings
3562 # 'SomeText' -> 'Some Text'
3563 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
3564 # 'Vector3' -> 'Vector 3'
3565 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
3566 return input_string.lower().split()
3569 def Lower(words):
3570 """Makes a lower-case identifier from words.
3572 Args:
3573 words: a list of lower-case words.
3575 Returns:
3576 the lower-case identifier.
3578 return '_'.join(words)
3581 def ToUnderscore(input_string):
3582 """converts CamelCase to camel_case."""
3583 words = SplitWords(input_string)
3584 return Lower(words)
3586 def CachedStateName(item):
3587 if item.get('cached', False):
3588 return 'cached_' + item['name']
3589 return item['name']
3591 def ToGLExtensionString(extension_flag):
3592 """Returns GL-type extension string of a extension flag."""
3593 if extension_flag == "oes_compressed_etc1_rgb8_texture":
3594 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
3595 # unfortunate.
3596 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
3597 'egl', 'atc', 'etc1', 'angle']
3598 parts = extension_flag.split('_')
3599 return "_".join(
3600 [part.upper() if part in uppercase_words else part for part in parts])
3602 def ToCamelCase(input_string):
3603 """converts ABC_underscore_case to ABCUnderscoreCase."""
3604 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
3606 def GetGLGetTypeConversion(result_type, value_type, value):
3607 """Makes a gl compatible type conversion string for accessing state variables.
3609 Useful when accessing state variables through glGetXXX calls.
3610 glGet documetation (for example, the manual pages):
3611 [...] If glGetIntegerv is called, [...] most floating-point values are
3612 rounded to the nearest integer value. [...]
3614 Args:
3615 result_type: the gl type to be obtained
3616 value_type: the GL type of the state variable
3617 value: the name of the state variable
3619 Returns:
3620 String that converts the state variable to desired GL type according to GL
3621 rules.
3624 if result_type == 'GLint':
3625 if value_type == 'GLfloat':
3626 return 'static_cast<GLint>(round(%s))' % value
3627 return 'static_cast<%s>(%s)' % (result_type, value)
3629 class CWriter(object):
3630 """Writes to a file formatting it for Google's style guidelines."""
3632 def __init__(self, filename):
3633 self.filename = filename
3634 self.content = []
3636 def Write(self, string):
3637 """Writes a string to a file spliting if it's > 80 characters."""
3638 lines = string.splitlines()
3639 num_lines = len(lines)
3640 for ii in range(0, num_lines):
3641 self.content.append(lines[ii])
3642 if ii < (num_lines - 1) or string[-1] == '\n':
3643 self.content.append('\n')
3645 def Close(self):
3646 """Close the file."""
3647 content = "".join(self.content)
3648 write_file = True
3649 if os.path.exists(self.filename):
3650 old_file = open(self.filename, "rb");
3651 old_content = old_file.read()
3652 old_file.close();
3653 if content == old_content:
3654 write_file = False
3655 if write_file:
3656 file = open(self.filename, "wb")
3657 file.write(content)
3658 file.close()
3661 class CHeaderWriter(CWriter):
3662 """Writes a C Header file."""
3664 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
3666 def __init__(self, filename, file_comment = None):
3667 CWriter.__init__(self, filename)
3669 base = os.path.abspath(filename)
3670 while os.path.basename(base) != 'src':
3671 new_base = os.path.dirname(base)
3672 assert new_base != base # Prevent infinite loop.
3673 base = new_base
3675 hpath = os.path.relpath(filename, base)
3676 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
3678 self.Write(_LICENSE)
3679 self.Write(_DO_NOT_EDIT_WARNING)
3680 if not file_comment == None:
3681 self.Write(file_comment)
3682 self.Write("#ifndef %s\n" % self.guard)
3683 self.Write("#define %s\n\n" % self.guard)
3685 def Close(self):
3686 self.Write("#endif // %s\n\n" % self.guard)
3687 CWriter.Close(self)
3689 class TypeHandler(object):
3690 """This class emits code for a particular type of function."""
3692 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
3694 def __init__(self):
3695 pass
3697 def InitFunction(self, func):
3698 """Add or adjust anything type specific for this function."""
3699 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
3700 func.AddCmdArg(DataSizeArgument('data_size'))
3702 def NeedsDataTransferFunction(self, func):
3703 """Overriden from TypeHandler."""
3704 return func.num_pointer_args >= 1
3706 def WriteStruct(self, func, file):
3707 """Writes a structure that matches the arguments to a function."""
3708 comment = func.GetInfo('cmd_comment')
3709 if not comment == None:
3710 file.Write(comment)
3711 file.Write("struct %s {\n" % func.name)
3712 file.Write(" typedef %s ValueType;\n" % func.name)
3713 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
3714 func.WriteCmdArgFlag(file)
3715 func.WriteCmdFlag(file)
3716 file.Write("\n")
3717 result = func.GetInfo('result')
3718 if not result == None:
3719 if len(result) == 1:
3720 file.Write(" typedef %s Result;\n\n" % result[0])
3721 else:
3722 file.Write(" struct Result {\n")
3723 for line in result:
3724 file.Write(" %s;\n" % line)
3725 file.Write(" };\n\n")
3727 func.WriteCmdComputeSize(file)
3728 func.WriteCmdSetHeader(file)
3729 func.WriteCmdInit(file)
3730 func.WriteCmdSet(file)
3732 file.Write(" gpu::CommandHeader header;\n")
3733 args = func.GetCmdArgs()
3734 for arg in args:
3735 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
3737 consts = func.GetCmdConstants()
3738 for const in consts:
3739 file.Write(" static const %s %s = %s;\n" %
3740 (const.cmd_type, const.name, const.GetConstantValue()))
3742 file.Write("};\n")
3743 file.Write("\n")
3745 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
3746 file.Write("static_assert(sizeof(%s) == %d,\n" % (func.name, size))
3747 file.Write(" \"size of %s should be %d\");\n" %
3748 (func.name, size))
3749 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func.name)
3750 file.Write(" \"offset of %s header should be 0\");\n" %
3751 func.name)
3752 offset = _SIZE_OF_COMMAND_HEADER
3753 for arg in args:
3754 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
3755 (func.name, arg.name, offset))
3756 file.Write(" \"offset of %s %s should be %d\");\n" %
3757 (func.name, arg.name, offset))
3758 offset += _SIZE_OF_UINT32
3759 if not result == None and len(result) > 1:
3760 offset = 0;
3761 for line in result:
3762 parts = line.split()
3763 name = parts[-1]
3764 check = """
3765 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
3766 "offset of %(cmd_name)s Result %(field_name)s should be "
3767 "%(offset)d");
3769 file.Write((check.strip() + "\n") % {
3770 'cmd_name': func.name,
3771 'field_name': name,
3772 'offset': offset,
3774 offset += _SIZE_OF_UINT32
3775 file.Write("\n")
3777 def WriteHandlerImplementation(self, func, file):
3778 """Writes the handler implementation for this command."""
3779 if func.IsUnsafe() and func.GetInfo('id_mapping'):
3780 code_no_gen = """ if (!group_->Get%(type)sServiceId(
3781 %(var)s, &%(service_var)s)) {
3782 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3783 return error::kNoError;
3786 code_gen = """ if (!group_->Get%(type)sServiceId(
3787 %(var)s, &%(service_var)s)) {
3788 if (!group_->bind_generates_resource()) {
3789 LOCAL_SET_GL_ERROR(
3790 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3791 return error::kNoError;
3793 GLuint client_id = %(var)s;
3794 gl%(gen_func)s(1, &%(service_var)s);
3795 Create%(type)s(client_id, %(service_var)s);
3798 gen_func = func.GetInfo('gen_func')
3799 for id_type in func.GetInfo('id_mapping'):
3800 service_var = id_type.lower()
3801 if id_type == 'Sync':
3802 service_var = "service_%s" % service_var
3803 file.Write(" GLsync %s = 0;\n" % service_var)
3804 if gen_func and id_type in gen_func:
3805 file.Write(code_gen % { 'type': id_type,
3806 'var': id_type.lower(),
3807 'service_var': service_var,
3808 'func': func.GetGLFunctionName(),
3809 'gen_func': gen_func })
3810 else:
3811 file.Write(code_no_gen % { 'type': id_type,
3812 'var': id_type.lower(),
3813 'service_var': service_var,
3814 'func': func.GetGLFunctionName() })
3815 args = []
3816 for arg in func.GetOriginalArgs():
3817 if arg.type == "GLsync":
3818 args.append("service_%s" % arg.name)
3819 elif arg.name.endswith("size") and arg.type == "GLsizei":
3820 args.append("num_%s" % func.GetLastOriginalArg().name)
3821 elif arg.name == "length":
3822 args.append("nullptr")
3823 else:
3824 args.append(arg.name)
3825 file.Write(" %s(%s);\n" %
3826 (func.GetGLFunctionName(), ", ".join(args)))
3828 def WriteCmdSizeTest(self, func, file):
3829 """Writes the size test for a command."""
3830 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3832 def WriteFormatTest(self, func, file):
3833 """Writes a format test for a command."""
3834 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
3835 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
3836 (func.name, func.name))
3837 file.Write(" void* next_cmd = cmd.Set(\n")
3838 file.Write(" &cmd")
3839 args = func.GetCmdArgs()
3840 for value, arg in enumerate(args):
3841 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
3842 file.Write(");\n")
3843 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
3844 func.name)
3845 file.Write(" cmd.header.command);\n")
3846 func.type_handler.WriteCmdSizeTest(func, file)
3847 for value, arg in enumerate(args):
3848 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
3849 (arg.type, value + 11, arg.name))
3850 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
3851 file.Write(" next_cmd, sizeof(cmd));\n")
3852 file.Write("}\n")
3853 file.Write("\n")
3855 def WriteImmediateFormatTest(self, func, file):
3856 """Writes a format test for an immediate version of a command."""
3857 pass
3859 def WriteBucketFormatTest(self, func, file):
3860 """Writes a format test for a bucket version of a command."""
3861 pass
3863 def WriteGetDataSizeCode(self, func, file):
3864 """Writes the code to set data_size used in validation"""
3865 pass
3867 def WriteImmediateCmdSizeTest(self, func, file):
3868 """Writes a size test for an immediate version of a command."""
3869 file.Write(" // TODO(gman): Compute correct size.\n")
3870 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3872 def __WriteIdMapping(self, func, file):
3873 """Writes client side / service side ID mapping."""
3874 if not func.IsUnsafe() or not func.GetInfo('id_mapping'):
3875 return
3876 for id_type in func.GetInfo('id_mapping'):
3877 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
3878 (id_type, id_type.lower(), id_type.lower()))
3880 def WriteImmediateHandlerImplementation (self, func, file):
3881 """Writes the handler impl for the immediate version of a command."""
3882 self.__WriteIdMapping(func, file)
3883 file.Write(" %s(%s);\n" %
3884 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3886 def WriteBucketHandlerImplementation (self, func, file):
3887 """Writes the handler impl for the bucket version of a command."""
3888 self.__WriteIdMapping(func, file)
3889 file.Write(" %s(%s);\n" %
3890 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3892 def WriteServiceHandlerFunctionHeader(self, func, file):
3893 """Writes function header for service implementation handlers."""
3894 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
3895 uint32_t immediate_data_size, const void* cmd_data) {
3896 """ % {'name': func.name})
3897 if func.IsUnsafe():
3898 file.Write("""if (!unsafe_es3_apis_enabled())
3899 return error::kUnknownCommand;
3900 """)
3901 file.Write("""const gles2::cmds::%(name)s& c =
3902 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
3903 (void)c;
3904 """ % {'name': func.name})
3906 def WriteServiceImplementation(self, func, file):
3907 """Writes the service implementation for a command."""
3908 self.WriteServiceHandlerFunctionHeader(func, file)
3909 self.WriteHandlerExtensionCheck(func, file)
3910 self.WriteHandlerDeferReadWrite(func, file);
3911 if len(func.GetOriginalArgs()) > 0:
3912 last_arg = func.GetLastOriginalArg()
3913 all_but_last_arg = func.GetOriginalArgs()[:-1]
3914 for arg in all_but_last_arg:
3915 arg.WriteGetCode(file)
3916 self.WriteGetDataSizeCode(func, file)
3917 last_arg.WriteGetCode(file)
3918 func.WriteHandlerValidation(file)
3919 func.WriteHandlerImplementation(file)
3920 file.Write(" return error::kNoError;\n")
3921 file.Write("}\n")
3922 file.Write("\n")
3924 def WriteImmediateServiceImplementation(self, func, file):
3925 """Writes the service implementation for an immediate version of command."""
3926 self.WriteServiceHandlerFunctionHeader(func, file)
3927 self.WriteHandlerExtensionCheck(func, file)
3928 self.WriteHandlerDeferReadWrite(func, file);
3929 for arg in func.GetOriginalArgs():
3930 if arg.IsPointer():
3931 self.WriteGetDataSizeCode(func, file)
3932 arg.WriteGetCode(file)
3933 func.WriteHandlerValidation(file)
3934 func.WriteHandlerImplementation(file)
3935 file.Write(" return error::kNoError;\n")
3936 file.Write("}\n")
3937 file.Write("\n")
3939 def WriteBucketServiceImplementation(self, func, file):
3940 """Writes the service implementation for a bucket version of command."""
3941 self.WriteServiceHandlerFunctionHeader(func, file)
3942 self.WriteHandlerExtensionCheck(func, file)
3943 self.WriteHandlerDeferReadWrite(func, file);
3944 for arg in func.GetCmdArgs():
3945 arg.WriteGetCode(file)
3946 func.WriteHandlerValidation(file)
3947 func.WriteHandlerImplementation(file)
3948 file.Write(" return error::kNoError;\n")
3949 file.Write("}\n")
3950 file.Write("\n")
3952 def WriteHandlerExtensionCheck(self, func, file):
3953 if func.GetInfo('extension_flag'):
3954 file.Write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
3955 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
3956 " \"function not available\");\n" % func.original_name)
3957 file.Write(" return error::kNoError;")
3958 file.Write(" }\n\n")
3960 def WriteHandlerDeferReadWrite(self, func, file):
3961 """Writes the code to handle deferring reads or writes."""
3962 defer_draws = func.GetInfo('defer_draws')
3963 defer_reads = func.GetInfo('defer_reads')
3964 if defer_draws or defer_reads:
3965 file.Write(" error::Error error;\n")
3966 if defer_draws:
3967 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
3968 file.Write(" if (error != error::kNoError)\n")
3969 file.Write(" return error;\n")
3970 if defer_reads:
3971 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
3972 file.Write(" if (error != error::kNoError)\n")
3973 file.Write(" return error;\n")
3975 def WriteValidUnitTest(self, func, file, test, *extras):
3976 """Writes a valid unit test for the service implementation."""
3977 if func.GetInfo('expectation') == False:
3978 test = self._remove_expected_call_re.sub('', test)
3979 name = func.name
3980 arg_strings = [
3981 arg.GetValidArg(func) \
3982 for arg in func.GetOriginalArgs() if not arg.IsConstant()
3984 gl_arg_strings = [
3985 arg.GetValidGLArg(func) \
3986 for arg in func.GetOriginalArgs()
3988 gl_func_name = func.GetGLTestFunctionName()
3989 vars = {
3990 'name':name,
3991 'gl_func_name': gl_func_name,
3992 'args': ", ".join(arg_strings),
3993 'gl_args': ", ".join(gl_arg_strings),
3995 for extra in extras:
3996 vars.update(extra)
3997 old_test = ""
3998 while (old_test != test):
3999 old_test = test
4000 test = test % vars
4001 file.Write(test % vars)
4003 def WriteInvalidUnitTest(self, func, file, test, *extras):
4004 """Writes an invalid unit test for the service implementation."""
4005 if func.IsUnsafe():
4006 return
4007 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
4008 # Service implementation does not test constants, as they are not part of
4009 # the call in the service side.
4010 if invalid_arg.IsConstant():
4011 continue
4013 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
4014 for value_index in range(0, num_invalid_values):
4015 arg_strings = []
4016 parse_result = "kNoError"
4017 gl_error = None
4018 for arg in func.GetOriginalArgs():
4019 if arg.IsConstant():
4020 continue
4021 if invalid_arg is arg:
4022 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
4023 value_index)
4024 else:
4025 arg_string = arg.GetValidArg(func)
4026 arg_strings.append(arg_string)
4027 gl_arg_strings = []
4028 for arg in func.GetOriginalArgs():
4029 gl_arg_strings.append("_")
4030 gl_func_name = func.GetGLTestFunctionName()
4031 gl_error_test = ''
4032 if not gl_error == None:
4033 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4035 vars = {
4036 'name': func.name,
4037 'arg_index': invalid_arg_index,
4038 'value_index': value_index,
4039 'gl_func_name': gl_func_name,
4040 'args': ", ".join(arg_strings),
4041 'all_but_last_args': ", ".join(arg_strings[:-1]),
4042 'gl_args': ", ".join(gl_arg_strings),
4043 'parse_result': parse_result,
4044 'gl_error_test': gl_error_test,
4046 for extra in extras:
4047 vars.update(extra)
4048 file.Write(test % vars)
4050 def WriteServiceUnitTest(self, func, file, *extras):
4051 """Writes the service unit test for a command."""
4053 if func.name == 'Enable':
4054 valid_test = """
4055 TEST_P(%(test_name)s, %(name)sValidArgs) {
4056 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4057 SpecializedSetup<cmds::%(name)s, 0>(true);
4058 cmds::%(name)s cmd;
4059 cmd.Init(%(args)s);"""
4060 elif func.name == 'Disable':
4061 valid_test = """
4062 TEST_P(%(test_name)s, %(name)sValidArgs) {
4063 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4064 SpecializedSetup<cmds::%(name)s, 0>(true);
4065 cmds::%(name)s cmd;
4066 cmd.Init(%(args)s);"""
4067 else:
4068 valid_test = """
4069 TEST_P(%(test_name)s, %(name)sValidArgs) {
4070 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4071 SpecializedSetup<cmds::%(name)s, 0>(true);
4072 cmds::%(name)s cmd;
4073 cmd.Init(%(args)s);"""
4074 if func.IsUnsafe():
4075 valid_test += """
4076 decoder_->set_unsafe_es3_apis_enabled(true);
4077 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4078 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4079 decoder_->set_unsafe_es3_apis_enabled(false);
4080 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4083 else:
4084 valid_test += """
4085 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4086 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4089 self.WriteValidUnitTest(func, file, valid_test, *extras)
4091 if not func.IsUnsafe():
4092 invalid_test = """
4093 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4094 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4095 SpecializedSetup<cmds::%(name)s, 0>(false);
4096 cmds::%(name)s cmd;
4097 cmd.Init(%(args)s);
4098 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4101 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
4103 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4104 """Writes the service unit test for an immediate command."""
4105 file.Write("// TODO(gman): %s\n" % func.name)
4107 def WriteImmediateValidationCode(self, func, file):
4108 """Writes the validation code for an immediate version of a command."""
4109 pass
4111 def WriteBucketServiceUnitTest(self, func, file, *extras):
4112 """Writes the service unit test for a bucket command."""
4113 file.Write("// TODO(gman): %s\n" % func.name)
4115 def WriteBucketValidationCode(self, func, file):
4116 """Writes the validation code for a bucket version of a command."""
4117 file.Write("// TODO(gman): %s\n" % func.name)
4119 def WriteGLES2ImplementationDeclaration(self, func, file):
4120 """Writes the GLES2 Implemention declaration."""
4121 impl_decl = func.GetInfo('impl_decl')
4122 if impl_decl == None or impl_decl == True:
4123 file.Write("%s %s(%s) override;\n" %
4124 (func.return_type, func.original_name,
4125 func.MakeTypedOriginalArgString("")))
4126 file.Write("\n")
4128 def WriteGLES2CLibImplementation(self, func, file):
4129 file.Write("%s GLES2%s(%s) {\n" %
4130 (func.return_type, func.name,
4131 func.MakeTypedOriginalArgString("")))
4132 result_string = "return "
4133 if func.return_type == "void":
4134 result_string = ""
4135 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
4136 (result_string, func.original_name,
4137 func.MakeOriginalArgString("")))
4138 file.Write("}\n")
4140 def WriteGLES2Header(self, func, file):
4141 """Writes a re-write macro for GLES"""
4142 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
4144 def WriteClientGLCallLog(self, func, file):
4145 """Writes a logging macro for the client side code."""
4146 comma = ""
4147 if len(func.GetOriginalArgs()):
4148 comma = " << "
4149 file.Write(
4150 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4151 (func.original_name, comma, func.MakeLogArgString()))
4153 def WriteClientGLReturnLog(self, func, file):
4154 """Writes the return value logging code."""
4155 if func.return_type != "void":
4156 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
4158 def WriteGLES2ImplementationHeader(self, func, file):
4159 """Writes the GLES2 Implemention."""
4160 self.WriteGLES2ImplementationDeclaration(func, file)
4162 def WriteGLES2TraceImplementationHeader(self, func, file):
4163 """Writes the GLES2 Trace Implemention header."""
4164 file.Write("%s %s(%s) override;\n" %
4165 (func.return_type, func.original_name,
4166 func.MakeTypedOriginalArgString("")))
4168 def WriteGLES2TraceImplementation(self, func, file):
4169 """Writes the GLES2 Trace Implemention."""
4170 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
4171 (func.return_type, func.original_name,
4172 func.MakeTypedOriginalArgString("")))
4173 result_string = "return "
4174 if func.return_type == "void":
4175 result_string = ""
4176 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4177 func.name)
4178 file.Write(" %sgl_->%s(%s);\n" %
4179 (result_string, func.name, func.MakeOriginalArgString("")))
4180 file.Write("}\n")
4181 file.Write("\n")
4183 def WriteGLES2Implementation(self, func, file):
4184 """Writes the GLES2 Implemention."""
4185 impl_func = func.GetInfo('impl_func')
4186 impl_decl = func.GetInfo('impl_decl')
4187 gen_cmd = func.GetInfo('gen_cmd')
4188 if (func.can_auto_generate and
4189 (impl_func == None or impl_func == True) and
4190 (impl_decl == None or impl_decl == True) and
4191 (gen_cmd == None or gen_cmd == True)):
4192 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4193 (func.return_type, func.original_name,
4194 func.MakeTypedOriginalArgString("")))
4195 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4196 self.WriteClientGLCallLog(func, file)
4197 func.WriteDestinationInitalizationValidation(file)
4198 for arg in func.GetOriginalArgs():
4199 arg.WriteClientSideValidationCode(file, func)
4200 file.Write(" helper_->%s(%s);\n" %
4201 (func.name, func.MakeHelperArgString("")))
4202 file.Write(" CheckGLError();\n")
4203 self.WriteClientGLReturnLog(func, file)
4204 file.Write("}\n")
4205 file.Write("\n")
4207 def WriteGLES2InterfaceHeader(self, func, file):
4208 """Writes the GLES2 Interface."""
4209 file.Write("virtual %s %s(%s) = 0;\n" %
4210 (func.return_type, func.original_name,
4211 func.MakeTypedOriginalArgString("")))
4213 def WriteMojoGLES2ImplHeader(self, func, file):
4214 """Writes the Mojo GLES2 implementation header."""
4215 file.Write("%s %s(%s) override;\n" %
4216 (func.return_type, func.original_name,
4217 func.MakeTypedOriginalArgString("")))
4219 def WriteMojoGLES2Impl(self, func, file):
4220 """Writes the Mojo GLES2 implementation."""
4221 file.Write("%s MojoGLES2Impl::%s(%s) {\n" %
4222 (func.return_type, func.original_name,
4223 func.MakeTypedOriginalArgString("")))
4224 extensions = ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4225 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4226 "occlusion_query_EXT"]
4227 if func.IsCoreGLFunction() or func.GetInfo("extension") in extensions:
4228 file.Write("MojoGLES2MakeCurrent(context_);");
4229 func_return = "gl" + func.original_name + "(" + \
4230 func.MakeOriginalArgString("") + ");"
4231 if func.return_type == "void":
4232 file.Write(func_return);
4233 else:
4234 file.Write("return " + func_return);
4235 else:
4236 file.Write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4237 func.original_name);
4238 if func.return_type != "void":
4239 file.Write("return 0;")
4240 file.Write("}")
4242 def WriteGLES2InterfaceStub(self, func, file):
4243 """Writes the GLES2 Interface stub declaration."""
4244 file.Write("%s %s(%s) override;\n" %
4245 (func.return_type, func.original_name,
4246 func.MakeTypedOriginalArgString("")))
4248 def WriteGLES2InterfaceStubImpl(self, func, file):
4249 """Writes the GLES2 Interface stub declaration."""
4250 args = func.GetOriginalArgs()
4251 arg_string = ", ".join(
4252 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
4253 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
4254 (func.return_type, func.original_name, arg_string))
4255 if func.return_type != "void":
4256 file.Write(" return 0;\n")
4257 file.Write("}\n")
4259 def WriteGLES2ImplementationUnitTest(self, func, file):
4260 """Writes the GLES2 Implemention unit test."""
4261 client_test = func.GetInfo('client_test')
4262 if (func.can_auto_generate and
4263 (client_test == None or client_test == True)):
4264 code = """
4265 TEST_F(GLES2ImplementationTest, %(name)s) {
4266 struct Cmds {
4267 cmds::%(name)s cmd;
4269 Cmds expected;
4270 expected.cmd.Init(%(cmd_args)s);
4272 gl_->%(name)s(%(args)s);
4273 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4276 cmd_arg_strings = [
4277 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4280 gl_arg_strings = [
4281 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4284 file.Write(code % {
4285 'name': func.name,
4286 'args': ", ".join(gl_arg_strings),
4287 'cmd_args': ", ".join(cmd_arg_strings),
4290 # Test constants for invalid values, as they are not tested by the
4291 # service.
4292 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
4293 if constants:
4294 code = """
4295 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4296 gl_->%(name)s(%(args)s);
4297 EXPECT_TRUE(NoCommandsWritten());
4298 EXPECT_EQ(%(gl_error)s, CheckError());
4301 for invalid_arg in constants:
4302 gl_arg_strings = []
4303 invalid = invalid_arg.GetInvalidArg(func)
4304 for arg in func.GetOriginalArgs():
4305 if arg is invalid_arg:
4306 gl_arg_strings.append(invalid[0])
4307 else:
4308 gl_arg_strings.append(arg.GetValidClientSideArg(func))
4310 file.Write(code % {
4311 'name': func.name,
4312 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
4313 'args': ", ".join(gl_arg_strings),
4314 'gl_error': invalid[2],
4316 else:
4317 if client_test != False:
4318 file.Write("// TODO(zmo): Implement unit test for %s\n" % func.name)
4320 def WriteDestinationInitalizationValidation(self, func, file):
4321 """Writes the client side destintion initialization validation."""
4322 for arg in func.GetOriginalArgs():
4323 arg.WriteDestinationInitalizationValidation(file, func)
4325 def WriteTraceEvent(self, func, file):
4326 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4327 func.original_name)
4329 def WriteImmediateCmdComputeSize(self, func, file):
4330 """Writes the size computation code for the immediate version of a cmd."""
4331 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4332 file.Write(" return static_cast<uint32_t>(\n")
4333 file.Write(" sizeof(ValueType) + // NOLINT\n")
4334 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4335 file.Write(" }\n")
4336 file.Write("\n")
4338 def WriteImmediateCmdSetHeader(self, func, file):
4339 """Writes the SetHeader function for the immediate version of a cmd."""
4340 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
4341 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4342 file.Write(" }\n")
4343 file.Write("\n")
4345 def WriteImmediateCmdInit(self, func, file):
4346 """Writes the Init function for the immediate version of a command."""
4347 raise NotImplementedError(func.name)
4349 def WriteImmediateCmdSet(self, func, file):
4350 """Writes the Set function for the immediate version of a command."""
4351 raise NotImplementedError(func.name)
4353 def WriteCmdHelper(self, func, file):
4354 """Writes the cmd helper definition for a cmd."""
4355 code = """ void %(name)s(%(typed_args)s) {
4356 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4357 if (c) {
4358 c->Init(%(args)s);
4363 file.Write(code % {
4364 "name": func.name,
4365 "typed_args": func.MakeTypedCmdArgString(""),
4366 "args": func.MakeCmdArgString(""),
4369 def WriteImmediateCmdHelper(self, func, file):
4370 """Writes the cmd helper definition for the immediate version of a cmd."""
4371 code = """ void %(name)s(%(typed_args)s) {
4372 const uint32_t s = 0; // TODO(gman): compute correct size
4373 gles2::cmds::%(name)s* c =
4374 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4375 if (c) {
4376 c->Init(%(args)s);
4381 file.Write(code % {
4382 "name": func.name,
4383 "typed_args": func.MakeTypedCmdArgString(""),
4384 "args": func.MakeCmdArgString(""),
4388 class StateSetHandler(TypeHandler):
4389 """Handler for commands that simply set state."""
4391 def __init__(self):
4392 TypeHandler.__init__(self)
4394 def WriteHandlerImplementation(self, func, file):
4395 """Overrriden from TypeHandler."""
4396 state_name = func.GetInfo('state')
4397 state = _STATES[state_name]
4398 states = state['states']
4399 args = func.GetOriginalArgs()
4400 for ndx,item in enumerate(states):
4401 code = []
4402 if 'range_checks' in item:
4403 for range_check in item['range_checks']:
4404 code.append("%s %s" % (args[ndx].name, range_check['check']))
4405 if 'nan_check' in item:
4406 # Drivers might generate an INVALID_VALUE error when a value is set
4407 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
4408 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
4409 # Make this behavior consistent within Chromium, and avoid leaking GL
4410 # errors by generating the error in the command buffer instead of
4411 # letting the GL driver generate it.
4412 code.append("base::IsNaN(%s)" % args[ndx].name)
4413 if len(code):
4414 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4415 file.Write(
4416 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
4417 ' "%s", "%s out of range");\n' %
4418 (func.name, args[ndx].name))
4419 file.Write(" return error::kNoError;\n")
4420 file.Write(" }\n")
4421 code = []
4422 for ndx,item in enumerate(states):
4423 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
4424 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4425 for ndx,item in enumerate(states):
4426 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
4427 if 'state_flag' in state:
4428 file.Write(" %s = true;\n" % state['state_flag'])
4429 if not func.GetInfo("no_gl"):
4430 for ndx,item in enumerate(states):
4431 if item.get('cached', False):
4432 file.Write(" state_.%s = %s;\n" %
4433 (CachedStateName(item), args[ndx].name))
4434 file.Write(" %s(%s);\n" %
4435 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4436 file.Write(" }\n")
4438 def WriteServiceUnitTest(self, func, file, *extras):
4439 """Overrriden from TypeHandler."""
4440 TypeHandler.WriteServiceUnitTest(self, func, file, *extras)
4441 state_name = func.GetInfo('state')
4442 state = _STATES[state_name]
4443 states = state['states']
4444 for ndx,item in enumerate(states):
4445 if 'range_checks' in item:
4446 for check_ndx, range_check in enumerate(item['range_checks']):
4447 valid_test = """
4448 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
4449 SpecializedSetup<cmds::%(name)s, 0>(false);
4450 cmds::%(name)s cmd;
4451 cmd.Init(%(args)s);
4452 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4453 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4456 name = func.name
4457 arg_strings = [
4458 arg.GetValidArg(func) \
4459 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4462 arg_strings[ndx] = range_check['test_value']
4463 vars = {
4464 'name': name,
4465 'ndx': ndx,
4466 'check_ndx': check_ndx,
4467 'args': ", ".join(arg_strings),
4469 for extra in extras:
4470 vars.update(extra)
4471 file.Write(valid_test % vars)
4472 if 'nan_check' in item:
4473 valid_test = """
4474 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
4475 SpecializedSetup<cmds::%(name)s, 0>(false);
4476 cmds::%(name)s cmd;
4477 cmd.Init(%(args)s);
4478 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4479 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4482 name = func.name
4483 arg_strings = [
4484 arg.GetValidArg(func) \
4485 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4488 arg_strings[ndx] = 'nanf("")'
4489 vars = {
4490 'name': name,
4491 'ndx': ndx,
4492 'args': ", ".join(arg_strings),
4494 for extra in extras:
4495 vars.update(extra)
4496 file.Write(valid_test % vars)
4499 class StateSetRGBAlphaHandler(TypeHandler):
4500 """Handler for commands that simply set state that have rgb/alpha."""
4502 def __init__(self):
4503 TypeHandler.__init__(self)
4505 def WriteHandlerImplementation(self, func, file):
4506 """Overrriden from TypeHandler."""
4507 state_name = func.GetInfo('state')
4508 state = _STATES[state_name]
4509 states = state['states']
4510 args = func.GetOriginalArgs()
4511 num_args = len(args)
4512 code = []
4513 for ndx,item in enumerate(states):
4514 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
4515 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4516 for ndx, item in enumerate(states):
4517 file.Write(" state_.%s = %s;\n" %
4518 (item['name'], args[ndx % num_args].name))
4519 if 'state_flag' in state:
4520 file.Write(" %s = true;\n" % state['state_flag'])
4521 if not func.GetInfo("no_gl"):
4522 file.Write(" %s(%s);\n" %
4523 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4524 file.Write(" }\n")
4527 class StateSetFrontBackSeparateHandler(TypeHandler):
4528 """Handler for commands that simply set state that have front/back."""
4530 def __init__(self):
4531 TypeHandler.__init__(self)
4533 def WriteHandlerImplementation(self, func, file):
4534 """Overrriden from TypeHandler."""
4535 state_name = func.GetInfo('state')
4536 state = _STATES[state_name]
4537 states = state['states']
4538 args = func.GetOriginalArgs()
4539 face = args[0].name
4540 num_args = len(args)
4541 file.Write(" bool changed = false;\n")
4542 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4543 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4544 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4545 code = []
4546 for ndx, item in enumerate(group):
4547 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
4548 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
4549 file.Write(" }\n")
4550 file.Write(" if (changed) {\n")
4551 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4552 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4553 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4554 for ndx, item in enumerate(group):
4555 file.Write(" state_.%s = %s;\n" %
4556 (item['name'], args[ndx + 1].name))
4557 file.Write(" }\n")
4558 if 'state_flag' in state:
4559 file.Write(" %s = true;\n" % state['state_flag'])
4560 if not func.GetInfo("no_gl"):
4561 file.Write(" %s(%s);\n" %
4562 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4563 file.Write(" }\n")
4566 class StateSetFrontBackHandler(TypeHandler):
4567 """Handler for commands that simply set state that set both front/back."""
4569 def __init__(self):
4570 TypeHandler.__init__(self)
4572 def WriteHandlerImplementation(self, func, file):
4573 """Overrriden from TypeHandler."""
4574 state_name = func.GetInfo('state')
4575 state = _STATES[state_name]
4576 states = state['states']
4577 args = func.GetOriginalArgs()
4578 num_args = len(args)
4579 code = []
4580 for group_ndx, group in enumerate(Grouper(num_args, states)):
4581 for ndx, item in enumerate(group):
4582 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
4583 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4584 for group_ndx, group in enumerate(Grouper(num_args, states)):
4585 for ndx, item in enumerate(group):
4586 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
4587 if 'state_flag' in state:
4588 file.Write(" %s = true;\n" % state['state_flag'])
4589 if not func.GetInfo("no_gl"):
4590 file.Write(" %s(%s);\n" %
4591 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4592 file.Write(" }\n")
4595 class StateSetNamedParameter(TypeHandler):
4596 """Handler for commands that set a state chosen with an enum parameter."""
4598 def __init__(self):
4599 TypeHandler.__init__(self)
4601 def WriteHandlerImplementation(self, func, file):
4602 """Overridden from TypeHandler."""
4603 state_name = func.GetInfo('state')
4604 state = _STATES[state_name]
4605 states = state['states']
4606 args = func.GetOriginalArgs()
4607 num_args = len(args)
4608 assert num_args == 2
4609 file.Write(" switch (%s) {\n" % args[0].name)
4610 for state in states:
4611 file.Write(" case %s:\n" % state['enum'])
4612 file.Write(" if (state_.%s != %s) {\n" %
4613 (state['name'], args[1].name))
4614 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
4615 if not func.GetInfo("no_gl"):
4616 file.Write(" %s(%s);\n" %
4617 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4618 file.Write(" }\n")
4619 file.Write(" break;\n")
4620 file.Write(" default:\n")
4621 file.Write(" NOTREACHED();\n")
4622 file.Write(" }\n")
4625 class CustomHandler(TypeHandler):
4626 """Handler for commands that are auto-generated but require minor tweaks."""
4628 def __init__(self):
4629 TypeHandler.__init__(self)
4631 def WriteServiceImplementation(self, func, file):
4632 """Overrriden from TypeHandler."""
4633 pass
4635 def WriteImmediateServiceImplementation(self, func, file):
4636 """Overrriden from TypeHandler."""
4637 pass
4639 def WriteBucketServiceImplementation(self, func, file):
4640 """Overrriden from TypeHandler."""
4641 pass
4643 def WriteServiceUnitTest(self, func, file, *extras):
4644 """Overrriden from TypeHandler."""
4645 file.Write("// TODO(gman): %s\n\n" % func.name)
4647 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4648 """Overrriden from TypeHandler."""
4649 file.Write("// TODO(gman): %s\n\n" % func.name)
4651 def WriteImmediateCmdGetTotalSize(self, func, file):
4652 """Overrriden from TypeHandler."""
4653 file.Write(
4654 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
4656 def WriteImmediateCmdInit(self, func, file):
4657 """Overrriden from TypeHandler."""
4658 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
4659 self.WriteImmediateCmdGetTotalSize(func, file)
4660 file.Write(" SetHeader(total_size);\n")
4661 args = func.GetCmdArgs()
4662 for arg in args:
4663 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4664 file.Write(" }\n")
4665 file.Write("\n")
4667 def WriteImmediateCmdSet(self, func, file):
4668 """Overrriden from TypeHandler."""
4669 copy_args = func.MakeCmdArgString("_", False)
4670 file.Write(" void* Set(void* cmd%s) {\n" %
4671 func.MakeTypedCmdArgString("_", True))
4672 self.WriteImmediateCmdGetTotalSize(func, file)
4673 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
4674 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4675 "cmd, total_size);\n")
4676 file.Write(" }\n")
4677 file.Write("\n")
4680 class TodoHandler(CustomHandler):
4681 """Handle for commands that are not yet implemented."""
4683 def NeedsDataTransferFunction(self, func):
4684 """Overriden from TypeHandler."""
4685 return False
4687 def WriteImmediateFormatTest(self, func, file):
4688 """Overrriden from TypeHandler."""
4689 pass
4691 def WriteGLES2ImplementationUnitTest(self, func, file):
4692 """Overrriden from TypeHandler."""
4693 pass
4695 def WriteGLES2Implementation(self, func, file):
4696 """Overrriden from TypeHandler."""
4697 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4698 (func.return_type, func.original_name,
4699 func.MakeTypedOriginalArgString("")))
4700 file.Write(" // TODO: for now this is a no-op\n")
4701 file.Write(
4702 " SetGLError("
4703 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4704 func.name)
4705 if func.return_type != "void":
4706 file.Write(" return 0;\n")
4707 file.Write("}\n")
4708 file.Write("\n")
4710 def WriteServiceImplementation(self, func, file):
4711 """Overrriden from TypeHandler."""
4712 self.WriteServiceHandlerFunctionHeader(func, file)
4713 file.Write(" // TODO: for now this is a no-op\n")
4714 file.Write(
4715 " LOCAL_SET_GL_ERROR("
4716 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4717 func.name)
4718 file.Write(" return error::kNoError;\n")
4719 file.Write("}\n")
4720 file.Write("\n")
4723 class HandWrittenHandler(CustomHandler):
4724 """Handler for comands where everything must be written by hand."""
4726 def InitFunction(self, func):
4727 """Add or adjust anything type specific for this function."""
4728 CustomHandler.InitFunction(self, func)
4729 func.can_auto_generate = False
4731 def NeedsDataTransferFunction(self, func):
4732 """Overriden from TypeHandler."""
4733 # If specified explicitly, force the data transfer method.
4734 if func.GetInfo('data_transfer_methods'):
4735 return True
4736 return False
4738 def WriteStruct(self, func, file):
4739 """Overrriden from TypeHandler."""
4740 pass
4742 def WriteDocs(self, func, file):
4743 """Overrriden from TypeHandler."""
4744 pass
4746 def WriteServiceUnitTest(self, func, file, *extras):
4747 """Overrriden from TypeHandler."""
4748 file.Write("// TODO(gman): %s\n\n" % func.name)
4750 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4751 """Overrriden from TypeHandler."""
4752 file.Write("// TODO(gman): %s\n\n" % func.name)
4754 def WriteBucketServiceUnitTest(self, func, file, *extras):
4755 """Overrriden from TypeHandler."""
4756 file.Write("// TODO(gman): %s\n\n" % func.name)
4758 def WriteServiceImplementation(self, func, file):
4759 """Overrriden from TypeHandler."""
4760 pass
4762 def WriteImmediateServiceImplementation(self, func, file):
4763 """Overrriden from TypeHandler."""
4764 pass
4766 def WriteBucketServiceImplementation(self, func, file):
4767 """Overrriden from TypeHandler."""
4768 pass
4770 def WriteImmediateCmdHelper(self, func, file):
4771 """Overrriden from TypeHandler."""
4772 pass
4774 def WriteCmdHelper(self, func, file):
4775 """Overrriden from TypeHandler."""
4776 pass
4778 def WriteFormatTest(self, func, file):
4779 """Overrriden from TypeHandler."""
4780 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4782 def WriteImmediateFormatTest(self, func, file):
4783 """Overrriden from TypeHandler."""
4784 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4786 def WriteBucketFormatTest(self, func, file):
4787 """Overrriden from TypeHandler."""
4788 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4792 class ManualHandler(CustomHandler):
4793 """Handler for commands who's handlers must be written by hand."""
4795 def __init__(self):
4796 CustomHandler.__init__(self)
4798 def InitFunction(self, func):
4799 """Overrriden from TypeHandler."""
4800 if (func.name == 'CompressedTexImage2DBucket'):
4801 func.cmd_args = func.cmd_args[:-1]
4802 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
4803 else:
4804 CustomHandler.InitFunction(self, func)
4806 def WriteServiceImplementation(self, func, file):
4807 """Overrriden from TypeHandler."""
4808 pass
4810 def WriteBucketServiceImplementation(self, func, file):
4811 """Overrriden from TypeHandler."""
4812 pass
4814 def WriteServiceUnitTest(self, func, file, *extras):
4815 """Overrriden from TypeHandler."""
4816 file.Write("// TODO(gman): %s\n\n" % func.name)
4818 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4819 """Overrriden from TypeHandler."""
4820 file.Write("// TODO(gman): %s\n\n" % func.name)
4822 def WriteImmediateServiceImplementation(self, func, file):
4823 """Overrriden from TypeHandler."""
4824 pass
4826 def WriteImmediateFormatTest(self, func, file):
4827 """Overrriden from TypeHandler."""
4828 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
4830 def WriteGLES2Implementation(self, func, file):
4831 """Overrriden from TypeHandler."""
4832 if func.GetInfo('impl_func'):
4833 super(ManualHandler, self).WriteGLES2Implementation(func, file)
4835 def WriteGLES2ImplementationHeader(self, func, file):
4836 """Overrriden from TypeHandler."""
4837 file.Write("%s %s(%s) override;\n" %
4838 (func.return_type, func.original_name,
4839 func.MakeTypedOriginalArgString("")))
4840 file.Write("\n")
4842 def WriteImmediateCmdGetTotalSize(self, func, file):
4843 """Overrriden from TypeHandler."""
4844 # TODO(gman): Move this data to _FUNCTION_INFO?
4845 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
4848 class DataHandler(TypeHandler):
4849 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
4850 glCompressedTexImage2D, glCompressedTexImageSub2D."""
4851 def __init__(self):
4852 TypeHandler.__init__(self)
4854 def InitFunction(self, func):
4855 """Overrriden from TypeHandler."""
4856 if func.name == 'CompressedTexSubImage2DBucket':
4857 func.cmd_args = func.cmd_args[:-1]
4858 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
4860 def WriteGetDataSizeCode(self, func, file):
4861 """Overrriden from TypeHandler."""
4862 # TODO(gman): Move this data to _FUNCTION_INFO?
4863 name = func.name
4864 if name.endswith("Immediate"):
4865 name = name[0:-9]
4866 if name == 'BufferData' or name == 'BufferSubData':
4867 file.Write(" uint32_t data_size = size;\n")
4868 elif (name == 'CompressedTexImage2D' or
4869 name == 'CompressedTexSubImage2D'):
4870 file.Write(" uint32_t data_size = imageSize;\n")
4871 elif (name == 'CompressedTexSubImage2DBucket'):
4872 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
4873 file.Write(" uint32_t data_size = bucket->size();\n")
4874 file.Write(" GLsizei imageSize = data_size;\n")
4875 elif name == 'TexImage2D' or name == 'TexSubImage2D':
4876 code = """ uint32_t data_size;
4877 if (!GLES2Util::ComputeImageDataSize(
4878 width, height, format, type, unpack_alignment_, &data_size)) {
4879 return error::kOutOfBounds;
4882 file.Write(code)
4883 else:
4884 file.Write(
4885 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
4887 def WriteImmediateCmdGetTotalSize(self, func, file):
4888 """Overrriden from TypeHandler."""
4889 pass
4891 def WriteImmediateCmdSizeTest(self, func, file):
4892 """Overrriden from TypeHandler."""
4893 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
4895 def WriteImmediateCmdInit(self, func, file):
4896 """Overrriden from TypeHandler."""
4897 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
4898 self.WriteImmediateCmdGetTotalSize(func, file)
4899 file.Write(" SetHeader(total_size);\n")
4900 args = func.GetCmdArgs()
4901 for arg in args:
4902 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4903 file.Write(" }\n")
4904 file.Write("\n")
4906 def WriteImmediateCmdSet(self, func, file):
4907 """Overrriden from TypeHandler."""
4908 copy_args = func.MakeCmdArgString("_", False)
4909 file.Write(" void* Set(void* cmd%s) {\n" %
4910 func.MakeTypedCmdArgString("_", True))
4911 self.WriteImmediateCmdGetTotalSize(func, file)
4912 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
4913 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4914 "cmd, total_size);\n")
4915 file.Write(" }\n")
4916 file.Write("\n")
4918 def WriteImmediateFormatTest(self, func, file):
4919 """Overrriden from TypeHandler."""
4920 # TODO(gman): Remove this exception.
4921 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
4922 return
4924 def WriteServiceUnitTest(self, func, file, *extras):
4925 """Overrriden from TypeHandler."""
4926 file.Write("// TODO(gman): %s\n\n" % func.name)
4928 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4929 """Overrriden from TypeHandler."""
4930 file.Write("// TODO(gman): %s\n\n" % func.name)
4932 def WriteBucketServiceImplementation(self, func, file):
4933 """Overrriden from TypeHandler."""
4934 if not func.name == 'CompressedTexSubImage2DBucket':
4935 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
4938 class BindHandler(TypeHandler):
4939 """Handler for glBind___ type functions."""
4941 def __init__(self):
4942 TypeHandler.__init__(self)
4944 def WriteServiceUnitTest(self, func, file, *extras):
4945 """Overrriden from TypeHandler."""
4947 if len(func.GetOriginalArgs()) == 1:
4948 valid_test = """
4949 TEST_P(%(test_name)s, %(name)sValidArgs) {
4950 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4951 SpecializedSetup<cmds::%(name)s, 0>(true);
4952 cmds::%(name)s cmd;
4953 cmd.Init(%(args)s);"""
4954 if func.IsUnsafe():
4955 valid_test += """
4956 decoder_->set_unsafe_es3_apis_enabled(true);
4957 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4958 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4959 decoder_->set_unsafe_es3_apis_enabled(false);
4960 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4963 else:
4964 valid_test += """
4965 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4966 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4969 if func.GetInfo("gen_func"):
4970 valid_test += """
4971 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
4972 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
4973 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
4974 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4975 SpecializedSetup<cmds::%(name)s, 0>(true);
4976 cmds::%(name)s cmd;
4977 cmd.Init(kNewClientId);
4978 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4979 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4980 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4983 self.WriteValidUnitTest(func, file, valid_test, {
4984 'resource_type': func.GetOriginalArgs()[0].resource_type,
4985 'gl_gen_func_name': func.GetInfo("gen_func"),
4986 }, *extras)
4987 else:
4988 valid_test = """
4989 TEST_P(%(test_name)s, %(name)sValidArgs) {
4990 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4991 SpecializedSetup<cmds::%(name)s, 0>(true);
4992 cmds::%(name)s cmd;
4993 cmd.Init(%(args)s);"""
4994 if func.IsUnsafe():
4995 valid_test += """
4996 decoder_->set_unsafe_es3_apis_enabled(true);
4997 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4998 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4999 decoder_->set_unsafe_es3_apis_enabled(false);
5000 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5003 else:
5004 valid_test += """
5005 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5006 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5009 if func.GetInfo("gen_func"):
5010 valid_test += """
5011 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5012 EXPECT_CALL(*gl_,
5013 %(gl_func_name)s(%(gl_args_with_new_id)s));
5014 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5015 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5016 SpecializedSetup<cmds::%(name)s, 0>(true);
5017 cmds::%(name)s cmd;
5018 cmd.Init(%(args_with_new_id)s);"""
5019 if func.IsUnsafe():
5020 valid_test += """
5021 decoder_->set_unsafe_es3_apis_enabled(true);
5022 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5023 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5024 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5025 decoder_->set_unsafe_es3_apis_enabled(false);
5026 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5029 else:
5030 valid_test += """
5031 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5032 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5033 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5037 gl_args_with_new_id = []
5038 args_with_new_id = []
5039 for arg in func.GetOriginalArgs():
5040 if hasattr(arg, 'resource_type'):
5041 gl_args_with_new_id.append('kNewServiceId')
5042 args_with_new_id.append('kNewClientId')
5043 else:
5044 gl_args_with_new_id.append(arg.GetValidGLArg(func))
5045 args_with_new_id.append(arg.GetValidArg(func))
5046 self.WriteValidUnitTest(func, file, valid_test, {
5047 'args_with_new_id': ", ".join(args_with_new_id),
5048 'gl_args_with_new_id': ", ".join(gl_args_with_new_id),
5049 'resource_type': func.GetResourceIdArg().resource_type,
5050 'gl_gen_func_name': func.GetInfo("gen_func"),
5051 }, *extras)
5053 invalid_test = """
5054 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5055 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5056 SpecializedSetup<cmds::%(name)s, 0>(false);
5057 cmds::%(name)s cmd;
5058 cmd.Init(%(args)s);
5059 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5062 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
5064 def WriteGLES2Implementation(self, func, file):
5065 """Writes the GLES2 Implemention."""
5067 impl_func = func.GetInfo('impl_func')
5068 impl_decl = func.GetInfo('impl_decl')
5070 if (func.can_auto_generate and
5071 (impl_func == None or impl_func == True) and
5072 (impl_decl == None or impl_decl == True)):
5074 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5075 (func.return_type, func.original_name,
5076 func.MakeTypedOriginalArgString("")))
5077 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5078 func.WriteDestinationInitalizationValidation(file)
5079 self.WriteClientGLCallLog(func, file)
5080 for arg in func.GetOriginalArgs():
5081 arg.WriteClientSideValidationCode(file, func)
5083 code = """ if (Is%(type)sReservedId(%(id)s)) {
5084 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5085 return;
5087 %(name)sHelper(%(arg_string)s);
5088 CheckGLError();
5092 name_arg = func.GetResourceIdArg()
5093 file.Write(code % {
5094 'name': func.name,
5095 'arg_string': func.MakeOriginalArgString(""),
5096 'id': name_arg.name,
5097 'type': name_arg.resource_type,
5098 'lc_type': name_arg.resource_type.lower(),
5101 def WriteGLES2ImplementationUnitTest(self, func, file):
5102 """Overrriden from TypeHandler."""
5103 client_test = func.GetInfo('client_test')
5104 if client_test == False:
5105 return
5106 code = """
5107 TEST_F(GLES2ImplementationTest, %(name)s) {
5108 struct Cmds {
5109 cmds::%(name)s cmd;
5111 Cmds expected;
5112 expected.cmd.Init(%(cmd_args)s);
5114 gl_->%(name)s(%(args)s);
5115 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5116 if not func.IsUnsafe():
5117 code += """
5118 ClearCommands();
5119 gl_->%(name)s(%(args)s);
5120 EXPECT_TRUE(NoCommandsWritten());"""
5121 code += """
5124 cmd_arg_strings = [
5125 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
5127 gl_arg_strings = [
5128 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
5131 file.Write(code % {
5132 'name': func.name,
5133 'args': ", ".join(gl_arg_strings),
5134 'cmd_args': ", ".join(cmd_arg_strings),
5138 class GENnHandler(TypeHandler):
5139 """Handler for glGen___ type functions."""
5141 def __init__(self):
5142 TypeHandler.__init__(self)
5144 def InitFunction(self, func):
5145 """Overrriden from TypeHandler."""
5146 pass
5148 def WriteGetDataSizeCode(self, func, file):
5149 """Overrriden from TypeHandler."""
5150 code = """ uint32_t data_size;
5151 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5152 return error::kOutOfBounds;
5155 file.Write(code)
5157 def WriteHandlerImplementation (self, func, file):
5158 """Overrriden from TypeHandler."""
5159 file.Write(" if (!%sHelper(n, %s)) {\n"
5160 " return error::kInvalidArguments;\n"
5161 " }\n" %
5162 (func.name, func.GetLastOriginalArg().name))
5164 def WriteImmediateHandlerImplementation(self, func, file):
5165 """Overrriden from TypeHandler."""
5166 if func.IsUnsafe():
5167 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5168 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5169 return error::kInvalidArguments;
5172 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5173 gl%(func_name)s(n, service_ids.get());
5174 for (GLsizei ii = 0; ii < n; ++ii) {
5175 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5177 """ % { 'func_name': func.original_name,
5178 'last_arg_name': func.GetLastOriginalArg().name,
5179 'resource_name': func.GetInfo('resource_type') })
5180 else:
5181 file.Write(" if (!%sHelper(n, %s)) {\n"
5182 " return error::kInvalidArguments;\n"
5183 " }\n" %
5184 (func.original_name, func.GetLastOriginalArg().name))
5186 def WriteGLES2Implementation(self, func, file):
5187 """Overrriden from TypeHandler."""
5188 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
5189 for (GLsizei i = 0; i < n; ++i) {
5190 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5192 });""" % func.GetOriginalArgs()[1].name)
5193 args = {
5194 'log_code': log_code,
5195 'return_type': func.return_type,
5196 'name': func.original_name,
5197 'typed_args': func.MakeTypedOriginalArgString(""),
5198 'args': func.MakeOriginalArgString(""),
5199 'resource_types': func.GetInfo('resource_types'),
5200 'count_name': func.GetOriginalArgs()[0].name,
5202 file.Write(
5203 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5204 args)
5205 func.WriteDestinationInitalizationValidation(file)
5206 self.WriteClientGLCallLog(func, file)
5207 for arg in func.GetOriginalArgs():
5208 arg.WriteClientSideValidationCode(file, func)
5209 not_shared = func.GetInfo('not_shared')
5210 if not_shared:
5211 alloc_code = (
5213 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5214 for (GLsizei ii = 0; ii < n; ++ii)
5215 %s[ii] = id_allocator->AllocateID();""" %
5216 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
5217 else:
5218 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5219 MakeIds(this, 0, %(args)s);""" % args)
5220 args['alloc_code'] = alloc_code
5222 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5223 %(alloc_code)s
5224 %(name)sHelper(%(args)s);
5225 helper_->%(name)sImmediate(%(args)s);
5226 if (share_group_->bind_generates_resource())
5227 helper_->CommandBufferHelper::Flush();
5228 %(log_code)s
5229 CheckGLError();
5233 file.Write(code % args)
5235 def WriteGLES2ImplementationUnitTest(self, func, file):
5236 """Overrriden from TypeHandler."""
5237 code = """
5238 TEST_F(GLES2ImplementationTest, %(name)s) {
5239 GLuint ids[2] = { 0, };
5240 struct Cmds {
5241 cmds::%(name)sImmediate gen;
5242 GLuint data[2];
5244 Cmds expected;
5245 expected.gen.Init(arraysize(ids), &ids[0]);
5246 expected.data[0] = k%(types)sStartId;
5247 expected.data[1] = k%(types)sStartId + 1;
5248 gl_->%(name)s(arraysize(ids), &ids[0]);
5249 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5250 EXPECT_EQ(k%(types)sStartId, ids[0]);
5251 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5254 file.Write(code % {
5255 'name': func.name,
5256 'types': func.GetInfo('resource_types'),
5259 def WriteServiceUnitTest(self, func, file, *extras):
5260 """Overrriden from TypeHandler."""
5261 valid_test = """
5262 TEST_P(%(test_name)s, %(name)sValidArgs) {
5263 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5264 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5265 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5266 SpecializedSetup<cmds::%(name)s, 0>(true);
5267 cmds::%(name)s cmd;
5268 cmd.Init(%(args)s);
5269 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5270 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5271 if func.IsUnsafe():
5272 valid_test += """
5273 GLuint service_id;
5274 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5275 EXPECT_EQ(kNewServiceId, service_id)
5278 else:
5279 valid_test += """
5280 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5283 self.WriteValidUnitTest(func, file, valid_test, {
5284 'resource_name': func.GetInfo('resource_type'),
5285 }, *extras)
5286 invalid_test = """
5287 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5288 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5289 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5290 SpecializedSetup<cmds::%(name)s, 0>(false);
5291 cmds::%(name)s cmd;
5292 cmd.Init(%(args)s);
5293 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5296 self.WriteValidUnitTest(func, file, invalid_test, {
5297 'resource_name': func.GetInfo('resource_type').lower(),
5298 }, *extras)
5300 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5301 """Overrriden from TypeHandler."""
5302 valid_test = """
5303 TEST_P(%(test_name)s, %(name)sValidArgs) {
5304 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5305 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5306 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5307 GLuint temp = kNewClientId;
5308 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5309 if func.IsUnsafe():
5310 valid_test += """
5311 decoder_->set_unsafe_es3_apis_enabled(true);"""
5312 valid_test += """
5313 cmd->Init(1, &temp);
5314 EXPECT_EQ(error::kNoError,
5315 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5316 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5317 if func.IsUnsafe():
5318 valid_test += """
5319 GLuint service_id;
5320 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5321 EXPECT_EQ(kNewServiceId, service_id);
5322 decoder_->set_unsafe_es3_apis_enabled(false);
5323 EXPECT_EQ(error::kUnknownCommand,
5324 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5327 else:
5328 valid_test += """
5329 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5332 self.WriteValidUnitTest(func, file, valid_test, {
5333 'resource_name': func.GetInfo('resource_type'),
5334 }, *extras)
5335 invalid_test = """
5336 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5337 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5338 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5339 SpecializedSetup<cmds::%(name)s, 0>(false);
5340 cmd->Init(1, &client_%(resource_name)s_id_);"""
5341 if func.IsUnsafe():
5342 invalid_test += """
5343 decoder_->set_unsafe_es3_apis_enabled(true);
5344 EXPECT_EQ(error::kInvalidArguments,
5345 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5346 decoder_->set_unsafe_es3_apis_enabled(false);
5349 else:
5350 invalid_test += """
5351 EXPECT_EQ(error::kInvalidArguments,
5352 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5355 self.WriteValidUnitTest(func, file, invalid_test, {
5356 'resource_name': func.GetInfo('resource_type').lower(),
5357 }, *extras)
5359 def WriteImmediateCmdComputeSize(self, func, file):
5360 """Overrriden from TypeHandler."""
5361 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5362 file.Write(
5363 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5364 file.Write(" }\n")
5365 file.Write("\n")
5366 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5367 file.Write(" return static_cast<uint32_t>(\n")
5368 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5369 file.Write(" }\n")
5370 file.Write("\n")
5372 def WriteImmediateCmdSetHeader(self, func, file):
5373 """Overrriden from TypeHandler."""
5374 file.Write(" void SetHeader(GLsizei n) {\n")
5375 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5376 file.Write(" }\n")
5377 file.Write("\n")
5379 def WriteImmediateCmdInit(self, func, file):
5380 """Overrriden from TypeHandler."""
5381 last_arg = func.GetLastOriginalArg()
5382 file.Write(" void Init(%s, %s _%s) {\n" %
5383 (func.MakeTypedCmdArgString("_"),
5384 last_arg.type, last_arg.name))
5385 file.Write(" SetHeader(_n);\n")
5386 args = func.GetCmdArgs()
5387 for arg in args:
5388 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5389 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5390 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5391 file.Write(" }\n")
5392 file.Write("\n")
5394 def WriteImmediateCmdSet(self, func, file):
5395 """Overrriden from TypeHandler."""
5396 last_arg = func.GetLastOriginalArg()
5397 copy_args = func.MakeCmdArgString("_", False)
5398 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5399 (func.MakeTypedCmdArgString("_", True),
5400 last_arg.type, last_arg.name))
5401 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5402 (copy_args, last_arg.name))
5403 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5404 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5405 "cmd, size);\n")
5406 file.Write(" }\n")
5407 file.Write("\n")
5409 def WriteImmediateCmdHelper(self, func, file):
5410 """Overrriden from TypeHandler."""
5411 code = """ void %(name)s(%(typed_args)s) {
5412 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5413 gles2::cmds::%(name)s* c =
5414 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5415 if (c) {
5416 c->Init(%(args)s);
5421 file.Write(code % {
5422 "name": func.name,
5423 "typed_args": func.MakeTypedOriginalArgString(""),
5424 "args": func.MakeOriginalArgString(""),
5427 def WriteImmediateFormatTest(self, func, file):
5428 """Overrriden from TypeHandler."""
5429 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5430 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5431 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5432 (func.name, func.name))
5433 file.Write(" void* next_cmd = cmd.Set(\n")
5434 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5435 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5436 func.name)
5437 file.Write(" cmd.header.command);\n")
5438 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5439 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5440 file.Write(" cmd.header.size * 4u);\n")
5441 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5442 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5443 file.Write(" next_cmd, sizeof(cmd) +\n")
5444 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5445 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5446 file.Write("}\n")
5447 file.Write("\n")
5450 class CreateHandler(TypeHandler):
5451 """Handler for glCreate___ type functions."""
5453 def __init__(self):
5454 TypeHandler.__init__(self)
5456 def InitFunction(self, func):
5457 """Overrriden from TypeHandler."""
5458 func.AddCmdArg(Argument("client_id", 'uint32_t'))
5460 def __GetResourceType(self, func):
5461 if func.return_type == "GLsync":
5462 return "Sync"
5463 else:
5464 return func.name[6:] # Create*
5466 def WriteServiceUnitTest(self, func, file, *extras):
5467 """Overrriden from TypeHandler."""
5468 valid_test = """
5469 TEST_P(%(test_name)s, %(name)sValidArgs) {
5470 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5471 .WillOnce(Return(%(const_service_id)s));
5472 SpecializedSetup<cmds::%(name)s, 0>(true);
5473 cmds::%(name)s cmd;
5474 cmd.Init(%(args)s%(comma)skNewClientId);"""
5475 if func.IsUnsafe():
5476 valid_test += """
5477 decoder_->set_unsafe_es3_apis_enabled(true);"""
5478 valid_test += """
5479 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5480 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5481 if func.IsUnsafe():
5482 valid_test += """
5483 %(return_type)s service_id = 0;
5484 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
5485 EXPECT_EQ(%(const_service_id)s, service_id);
5486 decoder_->set_unsafe_es3_apis_enabled(false);
5487 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5490 else:
5491 valid_test += """
5492 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
5495 comma = ""
5496 cmd_arg_count = 0
5497 for arg in func.GetOriginalArgs():
5498 if not arg.IsConstant():
5499 cmd_arg_count += 1
5500 if cmd_arg_count:
5501 comma = ", "
5502 if func.return_type == 'GLsync':
5503 id_type_cast = ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
5504 "<GLsync>(kNewServiceId);\n ")
5505 const_service_id = "kNewServiceIdGLuint"
5506 else:
5507 id_type_cast = ""
5508 const_service_id = "kNewServiceId"
5509 self.WriteValidUnitTest(func, file, valid_test, {
5510 'comma': comma,
5511 'resource_type': self.__GetResourceType(func),
5512 'return_type': func.return_type,
5513 'id_type_cast': id_type_cast,
5514 'const_service_id': const_service_id,
5515 }, *extras)
5516 invalid_test = """
5517 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5518 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5519 SpecializedSetup<cmds::%(name)s, 0>(false);
5520 cmds::%(name)s cmd;
5521 cmd.Init(%(args)s%(comma)skNewClientId);
5522 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
5525 self.WriteInvalidUnitTest(func, file, invalid_test, {
5526 'comma': comma,
5527 }, *extras)
5529 def WriteHandlerImplementation (self, func, file):
5530 """Overrriden from TypeHandler."""
5531 if func.IsUnsafe():
5532 code = """ uint32_t client_id = c.client_id;
5533 %(return_type)s service_id = 0;
5534 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
5535 return error::kInvalidArguments;
5537 service_id = %(gl_func_name)s(%(gl_args)s);
5538 if (service_id) {
5539 group_->Add%(resource_name)sId(client_id, service_id);
5542 else:
5543 code = """ uint32_t client_id = c.client_id;
5544 if (Get%(resource_name)s(client_id)) {
5545 return error::kInvalidArguments;
5547 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
5548 if (service_id) {
5549 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
5552 file.Write(code % {
5553 'resource_name': self.__GetResourceType(func),
5554 'return_type': func.return_type,
5555 'gl_func_name': func.GetGLFunctionName(),
5556 'gl_args': func.MakeOriginalArgString(""),
5557 'gl_args_with_comma': func.MakeOriginalArgString("", True) })
5559 def WriteGLES2Implementation(self, func, file):
5560 """Overrriden from TypeHandler."""
5561 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5562 (func.return_type, func.original_name,
5563 func.MakeTypedOriginalArgString("")))
5564 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5565 func.WriteDestinationInitalizationValidation(file)
5566 self.WriteClientGLCallLog(func, file)
5567 for arg in func.GetOriginalArgs():
5568 arg.WriteClientSideValidationCode(file, func)
5569 file.Write(" GLuint client_id;\n")
5570 if func.return_type == "GLsync":
5571 file.Write(
5572 " GetIdHandler(id_namespaces::kSyncs)->\n")
5573 else:
5574 file.Write(
5575 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
5576 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
5577 file.Write(" helper_->%s(%s);\n" %
5578 (func.name, func.MakeCmdArgString("")))
5579 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
5580 file.Write(" CheckGLError();\n")
5581 if func.return_type == "GLsync":
5582 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
5583 else:
5584 file.Write(" return client_id;\n")
5585 file.Write("}\n")
5586 file.Write("\n")
5589 class DeleteHandler(TypeHandler):
5590 """Handler for glDelete___ single resource type functions."""
5592 def __init__(self):
5593 TypeHandler.__init__(self)
5595 def WriteServiceImplementation(self, func, file):
5596 """Overrriden from TypeHandler."""
5597 if func.IsUnsafe():
5598 TypeHandler.WriteServiceImplementation(self, func, file)
5599 # HandleDeleteShader and HandleDeleteProgram are manually written.
5600 pass
5602 def WriteGLES2Implementation(self, func, file):
5603 """Overrriden from TypeHandler."""
5604 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5605 (func.return_type, func.original_name,
5606 func.MakeTypedOriginalArgString("")))
5607 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5608 func.WriteDestinationInitalizationValidation(file)
5609 self.WriteClientGLCallLog(func, file)
5610 for arg in func.GetOriginalArgs():
5611 arg.WriteClientSideValidationCode(file, func)
5612 file.Write(
5613 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
5614 file.Write(" %sHelper(%s);\n" %
5615 (func.original_name, func.GetOriginalArgs()[-1].name))
5616 file.Write(" CheckGLError();\n")
5617 file.Write("}\n")
5618 file.Write("\n")
5620 def WriteHandlerImplementation (self, func, file):
5621 """Overrriden from TypeHandler."""
5622 assert len(func.GetOriginalArgs()) == 1
5623 arg = func.GetOriginalArgs()[0]
5624 if func.IsUnsafe():
5625 file.Write(""" %(arg_type)s service_id = 0;
5626 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
5627 glDelete%(resource_type)s(service_id);
5628 group_->Remove%(resource_type)sId(%(arg_name)s);
5629 } else {
5630 LOCAL_SET_GL_ERROR(
5631 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
5633 """ % { 'resource_type': func.GetInfo('resource_type'),
5634 'arg_name': arg.name,
5635 'arg_type': arg.type,
5636 'func_name': func.original_name })
5637 else:
5638 file.Write(" %sHelper(%s);\n" % (func.original_name, arg.name))
5640 class DELnHandler(TypeHandler):
5641 """Handler for glDelete___ type functions."""
5643 def __init__(self):
5644 TypeHandler.__init__(self)
5646 def WriteGetDataSizeCode(self, func, file):
5647 """Overrriden from TypeHandler."""
5648 code = """ uint32_t data_size;
5649 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5650 return error::kOutOfBounds;
5653 file.Write(code)
5655 def WriteGLES2ImplementationUnitTest(self, func, file):
5656 """Overrriden from TypeHandler."""
5657 code = """
5658 TEST_F(GLES2ImplementationTest, %(name)s) {
5659 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
5660 struct Cmds {
5661 cmds::%(name)sImmediate del;
5662 GLuint data[2];
5664 Cmds expected;
5665 expected.del.Init(arraysize(ids), &ids[0]);
5666 expected.data[0] = k%(types)sStartId;
5667 expected.data[1] = k%(types)sStartId + 1;
5668 gl_->%(name)s(arraysize(ids), &ids[0]);
5669 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5672 file.Write(code % {
5673 'name': func.name,
5674 'types': func.GetInfo('resource_types'),
5677 def WriteServiceUnitTest(self, func, file, *extras):
5678 """Overrriden from TypeHandler."""
5679 valid_test = """
5680 TEST_P(%(test_name)s, %(name)sValidArgs) {
5681 EXPECT_CALL(
5682 *gl_,
5683 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5684 .Times(1);
5685 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5686 SpecializedSetup<cmds::%(name)s, 0>(true);
5687 cmds::%(name)s cmd;
5688 cmd.Init(%(args)s);
5689 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5690 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5691 EXPECT_TRUE(
5692 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5695 self.WriteValidUnitTest(func, file, valid_test, {
5696 'resource_name': func.GetInfo('resource_type').lower(),
5697 'upper_resource_name': func.GetInfo('resource_type'),
5698 }, *extras)
5699 invalid_test = """
5700 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5701 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
5702 SpecializedSetup<cmds::%(name)s, 0>(false);
5703 cmds::%(name)s cmd;
5704 cmd.Init(%(args)s);
5705 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5708 self.WriteValidUnitTest(func, file, invalid_test, *extras)
5710 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5711 """Overrriden from TypeHandler."""
5712 valid_test = """
5713 TEST_P(%(test_name)s, %(name)sValidArgs) {
5714 EXPECT_CALL(
5715 *gl_,
5716 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5717 .Times(1);
5718 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5719 SpecializedSetup<cmds::%(name)s, 0>(true);
5720 cmd.Init(1, &client_%(resource_name)s_id_);"""
5721 if func.IsUnsafe():
5722 valid_test += """
5723 decoder_->set_unsafe_es3_apis_enabled(true);"""
5724 valid_test += """
5725 EXPECT_EQ(error::kNoError,
5726 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5727 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5728 if func.IsUnsafe():
5729 valid_test += """
5730 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
5731 client_%(resource_name)s_id_, NULL));
5732 decoder_->set_unsafe_es3_apis_enabled(false);
5733 EXPECT_EQ(error::kUnknownCommand,
5734 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5737 else:
5738 valid_test += """
5739 EXPECT_TRUE(
5740 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5743 self.WriteValidUnitTest(func, file, valid_test, {
5744 'resource_name': func.GetInfo('resource_type').lower(),
5745 'upper_resource_name': func.GetInfo('resource_type'),
5746 }, *extras)
5747 invalid_test = """
5748 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5749 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5750 SpecializedSetup<cmds::%(name)s, 0>(false);
5751 GLuint temp = kInvalidClientId;
5752 cmd.Init(1, &temp);"""
5753 if func.IsUnsafe():
5754 invalid_test += """
5755 decoder_->set_unsafe_es3_apis_enabled(true);
5756 EXPECT_EQ(error::kNoError,
5757 ExecuteImmediateCmd(cmd, sizeof(temp)));
5758 decoder_->set_unsafe_es3_apis_enabled(false);
5759 EXPECT_EQ(error::kUnknownCommand,
5760 ExecuteImmediateCmd(cmd, sizeof(temp)));
5763 else:
5764 invalid_test += """
5765 EXPECT_EQ(error::kNoError,
5766 ExecuteImmediateCmd(cmd, sizeof(temp)));
5769 self.WriteValidUnitTest(func, file, invalid_test, *extras)
5771 def WriteHandlerImplementation (self, func, file):
5772 """Overrriden from TypeHandler."""
5773 file.Write(" %sHelper(n, %s);\n" %
5774 (func.name, func.GetLastOriginalArg().name))
5776 def WriteImmediateHandlerImplementation (self, func, file):
5777 """Overrriden from TypeHandler."""
5778 if func.IsUnsafe():
5779 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5780 GLuint service_id = 0;
5781 if (group_->Get%(resource_type)sServiceId(
5782 %(last_arg_name)s[ii], &service_id)) {
5783 glDelete%(resource_type)ss(1, &service_id);
5784 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
5787 """ % { 'resource_type': func.GetInfo('resource_type'),
5788 'last_arg_name': func.GetLastOriginalArg().name })
5789 else:
5790 file.Write(" %sHelper(n, %s);\n" %
5791 (func.original_name, func.GetLastOriginalArg().name))
5793 def WriteGLES2Implementation(self, func, file):
5794 """Overrriden from TypeHandler."""
5795 impl_decl = func.GetInfo('impl_decl')
5796 if impl_decl == None or impl_decl == True:
5797 args = {
5798 'return_type': func.return_type,
5799 'name': func.original_name,
5800 'typed_args': func.MakeTypedOriginalArgString(""),
5801 'args': func.MakeOriginalArgString(""),
5802 'resource_type': func.GetInfo('resource_type').lower(),
5803 'count_name': func.GetOriginalArgs()[0].name,
5805 file.Write(
5806 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5807 args)
5808 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5809 func.WriteDestinationInitalizationValidation(file)
5810 self.WriteClientGLCallLog(func, file)
5811 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5812 for (GLsizei i = 0; i < n; ++i) {
5813 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5816 """ % func.GetOriginalArgs()[1].name)
5817 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
5818 for (GLsizei i = 0; i < n; ++i) {
5819 DCHECK(%s[i] != 0);
5822 """ % func.GetOriginalArgs()[1].name)
5823 for arg in func.GetOriginalArgs():
5824 arg.WriteClientSideValidationCode(file, func)
5825 code = """ %(name)sHelper(%(args)s);
5826 CheckGLError();
5830 file.Write(code % args)
5832 def WriteImmediateCmdComputeSize(self, func, file):
5833 """Overrriden from TypeHandler."""
5834 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5835 file.Write(
5836 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5837 file.Write(" }\n")
5838 file.Write("\n")
5839 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5840 file.Write(" return static_cast<uint32_t>(\n")
5841 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5842 file.Write(" }\n")
5843 file.Write("\n")
5845 def WriteImmediateCmdSetHeader(self, func, file):
5846 """Overrriden from TypeHandler."""
5847 file.Write(" void SetHeader(GLsizei n) {\n")
5848 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5849 file.Write(" }\n")
5850 file.Write("\n")
5852 def WriteImmediateCmdInit(self, func, file):
5853 """Overrriden from TypeHandler."""
5854 last_arg = func.GetLastOriginalArg()
5855 file.Write(" void Init(%s, %s _%s) {\n" %
5856 (func.MakeTypedCmdArgString("_"),
5857 last_arg.type, last_arg.name))
5858 file.Write(" SetHeader(_n);\n")
5859 args = func.GetCmdArgs()
5860 for arg in args:
5861 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5862 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5863 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5864 file.Write(" }\n")
5865 file.Write("\n")
5867 def WriteImmediateCmdSet(self, func, file):
5868 """Overrriden from TypeHandler."""
5869 last_arg = func.GetLastOriginalArg()
5870 copy_args = func.MakeCmdArgString("_", False)
5871 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5872 (func.MakeTypedCmdArgString("_", True),
5873 last_arg.type, last_arg.name))
5874 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5875 (copy_args, last_arg.name))
5876 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5877 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5878 "cmd, size);\n")
5879 file.Write(" }\n")
5880 file.Write("\n")
5882 def WriteImmediateCmdHelper(self, func, file):
5883 """Overrriden from TypeHandler."""
5884 code = """ void %(name)s(%(typed_args)s) {
5885 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5886 gles2::cmds::%(name)s* c =
5887 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5888 if (c) {
5889 c->Init(%(args)s);
5894 file.Write(code % {
5895 "name": func.name,
5896 "typed_args": func.MakeTypedOriginalArgString(""),
5897 "args": func.MakeOriginalArgString(""),
5900 def WriteImmediateFormatTest(self, func, file):
5901 """Overrriden from TypeHandler."""
5902 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5903 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5904 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5905 (func.name, func.name))
5906 file.Write(" void* next_cmd = cmd.Set(\n")
5907 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5908 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5909 func.name)
5910 file.Write(" cmd.header.command);\n")
5911 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5912 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5913 file.Write(" cmd.header.size * 4u);\n")
5914 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5915 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5916 file.Write(" next_cmd, sizeof(cmd) +\n")
5917 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5918 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5919 file.Write("}\n")
5920 file.Write("\n")
5923 class GETnHandler(TypeHandler):
5924 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
5926 def __init__(self):
5927 TypeHandler.__init__(self)
5929 def NeedsDataTransferFunction(self, func):
5930 """Overriden from TypeHandler."""
5931 return False
5933 def WriteServiceImplementation(self, func, file):
5934 """Overrriden from TypeHandler."""
5935 self.WriteServiceHandlerFunctionHeader(func, file)
5936 last_arg = func.GetLastOriginalArg()
5937 # All except shm_id and shm_offset.
5938 all_but_last_args = func.GetCmdArgs()[:-2]
5939 for arg in all_but_last_args:
5940 arg.WriteGetCode(file)
5942 code = """ typedef cmds::%(func_name)s::Result Result;
5943 GLsizei num_values = 0;
5944 GetNumValuesReturnedForGLGet(pname, &num_values);
5945 Result* result = GetSharedMemoryAs<Result*>(
5946 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
5947 Result::ComputeSize(num_values));
5948 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
5950 file.Write(code % {
5951 'last_arg_type': last_arg.type,
5952 'last_arg_name': last_arg.name,
5953 'func_name': func.name,
5955 func.WriteHandlerValidation(file)
5956 code = """ // Check that the client initialized the result.
5957 if (result->size != 0) {
5958 return error::kInvalidArguments;
5961 shadowed = func.GetInfo('shadowed')
5962 if not shadowed:
5963 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
5964 file.Write(code)
5965 func.WriteHandlerImplementation(file)
5966 if shadowed:
5967 code = """ result->SetNumResults(num_values);
5968 return error::kNoError;
5971 else:
5972 code = """ GLenum error = glGetError();
5973 if (error == GL_NO_ERROR) {
5974 result->SetNumResults(num_values);
5975 } else {
5976 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
5978 return error::kNoError;
5982 file.Write(code % {'func_name': func.name})
5984 def WriteGLES2Implementation(self, func, file):
5985 """Overrriden from TypeHandler."""
5986 impl_decl = func.GetInfo('impl_decl')
5987 if impl_decl == None or impl_decl == True:
5988 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5989 (func.return_type, func.original_name,
5990 func.MakeTypedOriginalArgString("")))
5991 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5992 func.WriteDestinationInitalizationValidation(file)
5993 self.WriteClientGLCallLog(func, file)
5994 for arg in func.GetOriginalArgs():
5995 arg.WriteClientSideValidationCode(file, func)
5996 all_but_last_args = func.GetOriginalArgs()[:-1]
5997 args = []
5998 has_length_arg = False
5999 for arg in all_but_last_args:
6000 if arg.type == 'GLsync':
6001 args.append('ToGLuint(%s)' % arg.name)
6002 elif arg.name.endswith('size') and arg.type == 'GLsizei':
6003 continue
6004 elif arg.name == 'length':
6005 has_length_arg = True
6006 continue
6007 else:
6008 args.append(arg.name)
6009 arg_string = ", ".join(args)
6010 all_arg_string = (
6011 ", ".join([
6012 "%s" % arg.name
6013 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
6014 self.WriteTraceEvent(func, file)
6015 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6016 return;
6018 typedef cmds::%(func_name)s::Result Result;
6019 Result* result = GetResultAs<Result*>();
6020 if (!result) {
6021 return;
6023 result->SetNumResults(0);
6024 helper_->%(func_name)s(%(arg_string)s,
6025 GetResultShmId(), GetResultShmOffset());
6026 WaitForCmd();
6027 result->CopyResult(%(last_arg_name)s);
6028 GPU_CLIENT_LOG_CODE_BLOCK({
6029 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6030 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6032 });"""
6033 if has_length_arg:
6034 code += """
6035 if (length) {
6036 *length = result->GetNumResults();
6037 }"""
6038 code += """
6039 CheckGLError();
6042 file.Write(code % {
6043 'func_name': func.name,
6044 'arg_string': arg_string,
6045 'all_arg_string': all_arg_string,
6046 'last_arg_name': func.GetLastOriginalArg().name,
6049 def WriteGLES2ImplementationUnitTest(self, func, file):
6050 """Writes the GLES2 Implemention unit test."""
6051 code = """
6052 TEST_F(GLES2ImplementationTest, %(name)s) {
6053 struct Cmds {
6054 cmds::%(name)s cmd;
6056 typedef cmds::%(name)s::Result Result;
6057 Result::Type result = 0;
6058 Cmds expected;
6059 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
6060 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6061 EXPECT_CALL(*command_buffer(), OnFlush())
6062 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
6063 .RetiresOnSaturation();
6064 gl_->%(name)s(%(args)s, &result);
6065 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6066 EXPECT_EQ(static_cast<Result::Type>(1), result);
6069 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
6070 if not first_cmd_arg:
6071 return
6073 first_gl_arg = func.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6074 func)
6076 cmd_arg_strings = [first_cmd_arg]
6077 for arg in func.GetCmdArgs()[1:-2]:
6078 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6079 gl_arg_strings = [first_gl_arg]
6080 for arg in func.GetOriginalArgs()[1:-1]:
6081 gl_arg_strings.append(arg.GetValidClientSideArg(func))
6083 file.Write(code % {
6084 'name': func.name,
6085 'args': ", ".join(gl_arg_strings),
6086 'cmd_args': ", ".join(cmd_arg_strings),
6089 def WriteServiceUnitTest(self, func, file, *extras):
6090 """Overrriden from TypeHandler."""
6091 valid_test = """
6092 TEST_P(%(test_name)s, %(name)sValidArgs) {
6093 EXPECT_CALL(*gl_, GetError())
6094 .WillOnce(Return(GL_NO_ERROR))
6095 .WillOnce(Return(GL_NO_ERROR))
6096 .RetiresOnSaturation();
6097 SpecializedSetup<cmds::%(name)s, 0>(true);
6098 typedef cmds::%(name)s::Result Result;
6099 Result* result = static_cast<Result*>(shared_memory_address_);
6100 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6101 result->size = 0;
6102 cmds::%(name)s cmd;
6103 cmd.Init(%(cmd_args)s);"""
6104 if func.IsUnsafe():
6105 valid_test += """
6106 decoder_->set_unsafe_es3_apis_enabled(true);"""
6107 valid_test += """
6108 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6109 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6110 %(valid_pname)s),
6111 result->GetNumResults());
6112 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6113 if func.IsUnsafe():
6114 valid_test += """
6115 decoder_->set_unsafe_es3_apis_enabled(false);
6116 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6117 valid_test += """
6120 gl_arg_strings = []
6121 cmd_arg_strings = []
6122 valid_pname = ''
6123 for arg in func.GetOriginalArgs()[:-1]:
6124 if arg.name == 'length':
6125 gl_arg_value = 'nullptr'
6126 elif arg.name.endswith('size'):
6127 gl_arg_value = ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6128 valid_pname)
6129 elif arg.type == 'GLsync':
6130 gl_arg_value = 'reinterpret_cast<GLsync>(kServiceSyncId)'
6131 else:
6132 gl_arg_value = arg.GetValidGLArg(func)
6133 gl_arg_strings.append(gl_arg_value)
6134 if arg.name == 'pname':
6135 valid_pname = gl_arg_value
6136 if arg.name.endswith('size') or arg.name == 'length':
6137 continue
6138 if arg.type == 'GLsync':
6139 arg_value = 'client_sync_id_'
6140 else:
6141 arg_value = arg.GetValidArg(func)
6142 cmd_arg_strings.append(arg_value)
6143 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
6144 gl_arg_strings.append("_")
6145 else:
6146 gl_arg_strings.append("result->GetData()")
6147 cmd_arg_strings.append("shared_memory_id_")
6148 cmd_arg_strings.append("shared_memory_offset_")
6150 self.WriteValidUnitTest(func, file, valid_test, {
6151 'local_gl_args': ", ".join(gl_arg_strings),
6152 'cmd_args': ", ".join(cmd_arg_strings),
6153 'valid_pname': valid_pname,
6154 }, *extras)
6156 if not func.IsUnsafe():
6157 invalid_test = """
6158 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6159 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6160 SpecializedSetup<cmds::%(name)s, 0>(false);
6161 cmds::%(name)s::Result* result =
6162 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6163 result->size = 0;
6164 cmds::%(name)s cmd;
6165 cmd.Init(%(args)s);
6166 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6167 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6170 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
6172 class ArrayArgTypeHandler(TypeHandler):
6173 """Base class for type handlers that handle args that are arrays"""
6175 def __init__(self):
6176 TypeHandler.__init__(self)
6178 def GetArrayType(self, func):
6179 """Returns the type of the element in the element array being PUT to."""
6180 for arg in func.GetOriginalArgs():
6181 if arg.IsPointer():
6182 element_type = arg.GetPointedType()
6183 return element_type
6185 # Special case: array type handler is used for a function that is forwarded
6186 # to the actual array type implementation
6187 element_type = func.GetOriginalArgs()[-1].type
6188 assert all(arg.type == element_type \
6189 for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
6190 return element_type
6192 def GetArrayCount(self, func):
6193 """Returns the count of the elements in the array being PUT to."""
6194 return func.GetInfo('count')
6196 class PUTHandler(ArrayArgTypeHandler):
6197 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6199 def __init__(self):
6200 ArrayArgTypeHandler.__init__(self)
6202 def WriteServiceUnitTest(self, func, file, *extras):
6203 """Writes the service unit test for a command."""
6204 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6205 if func.GetInfo("first_element_only"):
6206 gl_arg_strings = [
6207 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
6209 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
6210 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6211 ", ".join(gl_arg_strings))
6212 valid_test = """
6213 TEST_P(%(test_name)s, %(name)sValidArgs) {
6214 SpecializedSetup<cmds::%(name)s, 0>(true);
6215 cmds::%(name)s cmd;
6216 cmd.Init(%(args)s);
6217 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6218 %(expected_call)s
6219 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6220 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6223 extra = {
6224 'data_type': self.GetArrayType(func),
6225 'data_value': func.GetInfo('data_value') or '0',
6226 'expected_call': expected_call,
6228 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6230 invalid_test = """
6231 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6232 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6233 SpecializedSetup<cmds::%(name)s, 0>(false);
6234 cmds::%(name)s cmd;
6235 cmd.Init(%(args)s);
6236 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6237 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6240 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6242 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6243 """Writes the service unit test for a command."""
6244 valid_test = """
6245 TEST_P(%(test_name)s, %(name)sValidArgs) {
6246 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6247 SpecializedSetup<cmds::%(name)s, 0>(true);
6248 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6249 cmd.Init(%(gl_args)s, &temp[0]);
6250 EXPECT_CALL(
6251 *gl_,
6252 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6253 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6254 if func.IsUnsafe():
6255 valid_test += """
6256 decoder_->set_unsafe_es3_apis_enabled(true);"""
6257 valid_test += """
6258 EXPECT_EQ(error::kNoError,
6259 ExecuteImmediateCmd(cmd, sizeof(temp)));
6260 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6261 if func.IsUnsafe():
6262 valid_test += """
6263 decoder_->set_unsafe_es3_apis_enabled(false);
6264 EXPECT_EQ(error::kUnknownCommand,
6265 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6266 valid_test += """
6269 gl_arg_strings = [
6270 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
6272 gl_any_strings = ["_"] * len(gl_arg_strings)
6274 extra = {
6275 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
6276 'data_type': self.GetArrayType(func),
6277 'data_count': self.GetArrayCount(func),
6278 'data_value': func.GetInfo('data_value') or '0',
6279 'gl_args': ", ".join(gl_arg_strings),
6280 'gl_any_args': ", ".join(gl_any_strings),
6282 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6284 invalid_test = """
6285 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6286 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6287 if func.IsUnsafe():
6288 invalid_test += """
6289 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6291 else:
6292 invalid_test += """
6293 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6295 invalid_test += """
6296 SpecializedSetup<cmds::%(name)s, 0>(false);
6297 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6298 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6299 if func.IsUnsafe():
6300 invalid_test += """
6301 decoder_->set_unsafe_es3_apis_enabled(true);
6302 EXPECT_EQ(error::%(parse_result)s,
6303 ExecuteImmediateCmd(cmd, sizeof(temp)));
6304 decoder_->set_unsafe_es3_apis_enabled(false);
6307 else:
6308 invalid_test += """
6309 EXPECT_EQ(error::%(parse_result)s,
6310 ExecuteImmediateCmd(cmd, sizeof(temp)));
6311 %(gl_error_test)s
6314 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6316 def WriteGetDataSizeCode(self, func, file):
6317 """Overrriden from TypeHandler."""
6318 code = """ uint32_t data_size;
6319 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6320 return error::kOutOfBounds;
6323 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6324 if func.IsImmediate():
6325 file.Write(" if (data_size > immediate_data_size) {\n")
6326 file.Write(" return error::kOutOfBounds;\n")
6327 file.Write(" }\n")
6329 def __NeedsToCalcDataCount(self, func):
6330 use_count_func = func.GetInfo('use_count_func')
6331 return use_count_func != None and use_count_func != False
6333 def WriteGLES2Implementation(self, func, file):
6334 """Overrriden from TypeHandler."""
6335 impl_func = func.GetInfo('impl_func')
6336 if (impl_func != None and impl_func != True):
6337 return;
6338 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6339 (func.return_type, func.original_name,
6340 func.MakeTypedOriginalArgString("")))
6341 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6342 func.WriteDestinationInitalizationValidation(file)
6343 self.WriteClientGLCallLog(func, file)
6345 if self.__NeedsToCalcDataCount(func):
6346 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6347 (func.name, func.GetOriginalArgs()[0].name))
6348 file.Write(" DCHECK_LE(count, %du);\n" % self.GetArrayCount(func))
6349 else:
6350 file.Write(" size_t count = %d;" % self.GetArrayCount(func))
6351 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
6352 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6353 func.GetLastOriginalArg().name)
6354 for arg in func.GetOriginalArgs():
6355 arg.WriteClientSideValidationCode(file, func)
6356 file.Write(" helper_->%sImmediate(%s);\n" %
6357 (func.name, func.MakeOriginalArgString("")))
6358 file.Write(" CheckGLError();\n")
6359 file.Write("}\n")
6360 file.Write("\n")
6362 def WriteGLES2ImplementationUnitTest(self, func, file):
6363 """Writes the GLES2 Implemention unit test."""
6364 client_test = func.GetInfo('client_test')
6365 if (client_test != None and client_test != True):
6366 return;
6367 code = """
6368 TEST_F(GLES2ImplementationTest, %(name)s) {
6369 %(type)s data[%(count)d] = {0};
6370 struct Cmds {
6371 cmds::%(name)sImmediate cmd;
6372 %(type)s data[%(count)d];
6375 for (int jj = 0; jj < %(count)d; ++jj) {
6376 data[jj] = static_cast<%(type)s>(jj);
6378 Cmds expected;
6379 expected.cmd.Init(%(cmd_args)s, &data[0]);
6380 gl_->%(name)s(%(args)s, &data[0]);
6381 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6384 cmd_arg_strings = [
6385 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
6387 gl_arg_strings = [
6388 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
6391 file.Write(code % {
6392 'name': func.name,
6393 'type': self.GetArrayType(func),
6394 'count': self.GetArrayCount(func),
6395 'args': ", ".join(gl_arg_strings),
6396 'cmd_args': ", ".join(cmd_arg_strings),
6399 def WriteImmediateCmdComputeSize(self, func, file):
6400 """Overrriden from TypeHandler."""
6401 file.Write(" static uint32_t ComputeDataSize() {\n")
6402 file.Write(" return static_cast<uint32_t>(\n")
6403 file.Write(" sizeof(%s) * %d);\n" %
6404 (self.GetArrayType(func), self.GetArrayCount(func)))
6405 file.Write(" }\n")
6406 file.Write("\n")
6407 if self.__NeedsToCalcDataCount(func):
6408 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6409 (func.GetOriginalArgs()[0].type,
6410 func.GetOriginalArgs()[0].name))
6411 file.Write(" return static_cast<uint32_t>(\n")
6412 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6413 (self.GetArrayType(func), func.original_name,
6414 func.GetOriginalArgs()[0].name))
6415 file.Write(" }\n")
6416 file.Write("\n")
6417 file.Write(" static uint32_t ComputeSize() {\n")
6418 file.Write(" return static_cast<uint32_t>(\n")
6419 file.Write(
6420 " sizeof(ValueType) + ComputeDataSize());\n")
6421 file.Write(" }\n")
6422 file.Write("\n")
6424 def WriteImmediateCmdSetHeader(self, func, file):
6425 """Overrriden from TypeHandler."""
6426 file.Write(" void SetHeader() {\n")
6427 file.Write(
6428 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6429 file.Write(" }\n")
6430 file.Write("\n")
6432 def WriteImmediateCmdInit(self, func, file):
6433 """Overrriden from TypeHandler."""
6434 last_arg = func.GetLastOriginalArg()
6435 file.Write(" void Init(%s, %s _%s) {\n" %
6436 (func.MakeTypedCmdArgString("_"),
6437 last_arg.type, last_arg.name))
6438 file.Write(" SetHeader();\n")
6439 args = func.GetCmdArgs()
6440 for arg in args:
6441 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6442 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6443 if self.__NeedsToCalcDataCount(func):
6444 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
6445 (last_arg.name, func.GetOriginalArgs()[0].name))
6446 file.Write("""
6447 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6448 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6449 ComputeEffectiveDataSize(%(arg)s);
6450 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6451 """ % { 'arg': func.GetOriginalArgs()[0].name, })
6452 else:
6453 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
6454 file.Write(" }\n")
6455 file.Write("\n")
6457 def WriteImmediateCmdSet(self, func, file):
6458 """Overrriden from TypeHandler."""
6459 last_arg = func.GetLastOriginalArg()
6460 copy_args = func.MakeCmdArgString("_", False)
6461 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6462 (func.MakeTypedCmdArgString("_", True),
6463 last_arg.type, last_arg.name))
6464 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6465 (copy_args, last_arg.name))
6466 file.Write(" const uint32_t size = ComputeSize();\n")
6467 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6468 "cmd, size);\n")
6469 file.Write(" }\n")
6470 file.Write("\n")
6472 def WriteImmediateCmdHelper(self, func, file):
6473 """Overrriden from TypeHandler."""
6474 code = """ void %(name)s(%(typed_args)s) {
6475 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
6476 gles2::cmds::%(name)s* c =
6477 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6478 if (c) {
6479 c->Init(%(args)s);
6484 file.Write(code % {
6485 "name": func.name,
6486 "typed_args": func.MakeTypedOriginalArgString(""),
6487 "args": func.MakeOriginalArgString(""),
6490 def WriteImmediateFormatTest(self, func, file):
6491 """Overrriden from TypeHandler."""
6492 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6493 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6494 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
6495 for v in range(0, self.GetArrayCount(func)):
6496 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6497 (self.GetArrayType(func), v))
6498 file.Write(" };\n")
6499 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6500 (func.name, func.name))
6501 file.Write(" void* next_cmd = cmd.Set(\n")
6502 file.Write(" &cmd")
6503 args = func.GetCmdArgs()
6504 for value, arg in enumerate(args):
6505 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
6506 file.Write(",\n data);\n")
6507 args = func.GetCmdArgs()
6508 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
6509 % func.name)
6510 file.Write(" cmd.header.command);\n")
6511 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6512 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
6513 file.Write(" cmd.header.size * 4u);\n")
6514 for value, arg in enumerate(args):
6515 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6516 (arg.type, value + 11, arg.name))
6517 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6518 file.Write(" next_cmd, sizeof(cmd) +\n")
6519 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6520 file.Write(" // TODO(gman): Check that data was inserted;\n")
6521 file.Write("}\n")
6522 file.Write("\n")
6525 class PUTnHandler(ArrayArgTypeHandler):
6526 """Handler for PUTn 'glUniform__v' type functions."""
6528 def __init__(self):
6529 ArrayArgTypeHandler.__init__(self)
6531 def WriteServiceUnitTest(self, func, file, *extras):
6532 """Overridden from TypeHandler."""
6533 ArrayArgTypeHandler.WriteServiceUnitTest(self, func, file, *extras)
6535 valid_test = """
6536 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
6537 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6538 SpecializedSetup<cmds::%(name)s, 0>(true);
6539 cmds::%(name)s cmd;
6540 cmd.Init(%(args)s);
6541 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6542 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6545 gl_arg_strings = []
6546 arg_strings = []
6547 for count, arg in enumerate(func.GetOriginalArgs()):
6548 # hardcoded to match unit tests.
6549 if count == 0:
6550 # the location of the second element of the 2nd uniform.
6551 # defined in GLES2DecoderBase::SetupShaderForUniform
6552 gl_arg_strings.append("3")
6553 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
6554 elif count == 1:
6555 # the number of elements that gl will be called with.
6556 gl_arg_strings.append("3")
6557 # the number of elements requested in the command.
6558 arg_strings.append("5")
6559 else:
6560 gl_arg_strings.append(arg.GetValidGLArg(func))
6561 if not arg.IsConstant():
6562 arg_strings.append(arg.GetValidArg(func))
6563 extra = {
6564 'gl_args': ", ".join(gl_arg_strings),
6565 'args': ", ".join(arg_strings),
6567 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6569 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6570 """Overridden from TypeHandler."""
6571 valid_test = """
6572 TEST_P(%(test_name)s, %(name)sValidArgs) {
6573 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6574 EXPECT_CALL(
6575 *gl_,
6576 %(gl_func_name)s(%(gl_args)s,
6577 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
6578 SpecializedSetup<cmds::%(name)s, 0>(true);
6579 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6580 cmd.Init(%(args)s, &temp[0]);"""
6581 if func.IsUnsafe():
6582 valid_test += """
6583 decoder_->set_unsafe_es3_apis_enabled(true);"""
6584 valid_test += """
6585 EXPECT_EQ(error::kNoError,
6586 ExecuteImmediateCmd(cmd, sizeof(temp)));
6587 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6588 if func.IsUnsafe():
6589 valid_test += """
6590 decoder_->set_unsafe_es3_apis_enabled(false);
6591 EXPECT_EQ(error::kUnknownCommand,
6592 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6593 valid_test += """
6596 gl_arg_strings = []
6597 gl_any_strings = []
6598 arg_strings = []
6599 for arg in func.GetOriginalArgs()[0:-1]:
6600 gl_arg_strings.append(arg.GetValidGLArg(func))
6601 gl_any_strings.append("_")
6602 if not arg.IsConstant():
6603 arg_strings.append(arg.GetValidArg(func))
6604 extra = {
6605 'data_type': self.GetArrayType(func),
6606 'data_count': self.GetArrayCount(func),
6607 'args': ", ".join(arg_strings),
6608 'gl_args': ", ".join(gl_arg_strings),
6609 'gl_any_args': ", ".join(gl_any_strings),
6611 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6613 invalid_test = """
6614 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6615 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6616 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6617 SpecializedSetup<cmds::%(name)s, 0>(false);
6618 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6619 cmd.Init(%(all_but_last_args)s, &temp[0]);
6620 EXPECT_EQ(error::%(parse_result)s,
6621 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
6624 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6626 def WriteGetDataSizeCode(self, func, file):
6627 """Overrriden from TypeHandler."""
6628 code = """ uint32_t data_size;
6629 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
6630 return error::kOutOfBounds;
6633 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6634 if func.IsImmediate():
6635 file.Write(" if (data_size > immediate_data_size) {\n")
6636 file.Write(" return error::kOutOfBounds;\n")
6637 file.Write(" }\n")
6639 def WriteGLES2Implementation(self, func, file):
6640 """Overrriden from TypeHandler."""
6641 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6642 (func.return_type, func.original_name,
6643 func.MakeTypedOriginalArgString("")))
6644 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6645 func.WriteDestinationInitalizationValidation(file)
6646 self.WriteClientGLCallLog(func, file)
6647 last_pointer_name = func.GetLastOriginalPointerArg().name
6648 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6649 for (GLsizei i = 0; i < count; ++i) {
6650 """)
6651 values_str = ' << ", " << '.join(
6652 ["%s[%d + i * %d]" % (
6653 last_pointer_name, ndx, self.GetArrayCount(func)) for ndx in range(
6654 0, self.GetArrayCount(func))])
6655 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
6656 file.Write(" }\n });\n")
6657 for arg in func.GetOriginalArgs():
6658 arg.WriteClientSideValidationCode(file, func)
6659 file.Write(" helper_->%sImmediate(%s);\n" %
6660 (func.name, func.MakeInitString("")))
6661 file.Write(" CheckGLError();\n")
6662 file.Write("}\n")
6663 file.Write("\n")
6665 def WriteGLES2ImplementationUnitTest(self, func, file):
6666 """Writes the GLES2 Implemention unit test."""
6667 code = """
6668 TEST_F(GLES2ImplementationTest, %(name)s) {
6669 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6670 struct Cmds {
6671 cmds::%(name)sImmediate cmd;
6672 %(type)s data[%(count_param)d][%(count)d];
6675 Cmds expected;
6676 for (int ii = 0; ii < %(count_param)d; ++ii) {
6677 for (int jj = 0; jj < %(count)d; ++jj) {
6678 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6681 expected.cmd.Init(%(cmd_args)s);
6682 gl_->%(name)s(%(args)s);
6683 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6686 cmd_arg_strings = []
6687 for arg in func.GetCmdArgs():
6688 if arg.name.endswith("_shm_id"):
6689 cmd_arg_strings.append("&data[0][0]")
6690 elif arg.name.endswith("_shm_offset"):
6691 continue
6692 else:
6693 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6694 gl_arg_strings = []
6695 count_param = 0
6696 for arg in func.GetOriginalArgs():
6697 if arg.IsPointer():
6698 valid_value = "&data[0][0]"
6699 else:
6700 valid_value = arg.GetValidClientSideArg(func)
6701 gl_arg_strings.append(valid_value)
6702 if arg.name == "count":
6703 count_param = int(valid_value)
6704 file.Write(code % {
6705 'name': func.name,
6706 'type': self.GetArrayType(func),
6707 'count': self.GetArrayCount(func),
6708 'args': ", ".join(gl_arg_strings),
6709 'cmd_args': ", ".join(cmd_arg_strings),
6710 'count_param': count_param,
6713 # Test constants for invalid values, as they are not tested by the
6714 # service.
6715 constants = [
6716 arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
6718 if not constants:
6719 return
6721 code = """
6722 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
6723 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6724 for (int ii = 0; ii < %(count_param)d; ++ii) {
6725 for (int jj = 0; jj < %(count)d; ++jj) {
6726 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6729 gl_->%(name)s(%(args)s);
6730 EXPECT_TRUE(NoCommandsWritten());
6731 EXPECT_EQ(%(gl_error)s, CheckError());
6734 for invalid_arg in constants:
6735 gl_arg_strings = []
6736 invalid = invalid_arg.GetInvalidArg(func)
6737 for arg in func.GetOriginalArgs():
6738 if arg is invalid_arg:
6739 gl_arg_strings.append(invalid[0])
6740 elif arg.IsPointer():
6741 gl_arg_strings.append("&data[0][0]")
6742 else:
6743 valid_value = arg.GetValidClientSideArg(func)
6744 gl_arg_strings.append(valid_value)
6745 if arg.name == "count":
6746 count_param = int(valid_value)
6748 file.Write(code % {
6749 'name': func.name,
6750 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
6751 'type': self.GetArrayType(func),
6752 'count': self.GetArrayCount(func),
6753 'args': ", ".join(gl_arg_strings),
6754 'gl_error': invalid[2],
6755 'count_param': count_param,
6759 def WriteImmediateCmdComputeSize(self, func, file):
6760 """Overrriden from TypeHandler."""
6761 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
6762 file.Write(" return static_cast<uint32_t>(\n")
6763 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
6764 (self.GetArrayType(func), self.GetArrayCount(func)))
6765 file.Write(" }\n")
6766 file.Write("\n")
6767 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
6768 file.Write(" return static_cast<uint32_t>(\n")
6769 file.Write(
6770 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
6771 file.Write(" }\n")
6772 file.Write("\n")
6774 def WriteImmediateCmdSetHeader(self, func, file):
6775 """Overrriden from TypeHandler."""
6776 file.Write(" void SetHeader(GLsizei count) {\n")
6777 file.Write(
6778 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
6779 file.Write(" }\n")
6780 file.Write("\n")
6782 def WriteImmediateCmdInit(self, func, file):
6783 """Overrriden from TypeHandler."""
6784 file.Write(" void Init(%s) {\n" %
6785 func.MakeTypedInitString("_"))
6786 file.Write(" SetHeader(_count);\n")
6787 args = func.GetCmdArgs()
6788 for arg in args:
6789 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6790 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6791 pointer_arg = func.GetLastOriginalPointerArg()
6792 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg.name)
6793 file.Write(" }\n")
6794 file.Write("\n")
6796 def WriteImmediateCmdSet(self, func, file):
6797 """Overrriden from TypeHandler."""
6798 file.Write(" void* Set(void* cmd%s) {\n" %
6799 func.MakeTypedInitString("_", True))
6800 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
6801 func.MakeInitString("_"))
6802 file.Write(" const uint32_t size = ComputeSize(_count);\n")
6803 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6804 "cmd, size);\n")
6805 file.Write(" }\n")
6806 file.Write("\n")
6808 def WriteImmediateCmdHelper(self, func, file):
6809 """Overrriden from TypeHandler."""
6810 code = """ void %(name)s(%(typed_args)s) {
6811 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
6812 gles2::cmds::%(name)s* c =
6813 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6814 if (c) {
6815 c->Init(%(args)s);
6820 file.Write(code % {
6821 "name": func.name,
6822 "typed_args": func.MakeTypedInitString(""),
6823 "args": func.MakeInitString("")
6826 def WriteImmediateFormatTest(self, func, file):
6827 """Overrriden from TypeHandler."""
6828 args = func.GetOriginalArgs()
6829 count_param = 0
6830 for arg in args:
6831 if arg.name == "count":
6832 count_param = int(arg.GetValidClientSideCmdArg(func))
6833 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6834 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6835 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
6836 for v in range(0, self.GetArrayCount(func) * count_param):
6837 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6838 (self.GetArrayType(func), v))
6839 file.Write(" };\n")
6840 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6841 (func.name, func.name))
6842 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
6843 file.Write(" const size_t kExpectedCmdSize =\n")
6844 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
6845 (self.GetArrayType(func), self.GetArrayCount(func)))
6846 file.Write(" void* next_cmd = cmd.Set(\n")
6847 file.Write(" &cmd")
6848 for value, arg in enumerate(args):
6849 if arg.IsPointer():
6850 file.Write(",\n data")
6851 elif arg.IsConstant():
6852 continue
6853 else:
6854 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
6855 file.Write(");\n")
6856 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6857 func.name)
6858 file.Write(" cmd.header.command);\n")
6859 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
6860 for value, arg in enumerate(args):
6861 if arg.IsPointer() or arg.IsConstant():
6862 continue
6863 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6864 (arg.type, value + 1, arg.name))
6865 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6866 file.Write(" next_cmd, sizeof(cmd) +\n")
6867 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6868 file.Write(" // TODO(gman): Check that data was inserted;\n")
6869 file.Write("}\n")
6870 file.Write("\n")
6872 class PUTSTRHandler(ArrayArgTypeHandler):
6873 """Handler for functions that pass a string array."""
6875 def __init__(self):
6876 ArrayArgTypeHandler.__init__(self)
6878 def __GetDataArg(self, func):
6879 """Return the argument that points to the 2D char arrays"""
6880 for arg in func.GetOriginalArgs():
6881 if arg.IsPointer2D():
6882 return arg
6883 return None
6885 def __GetLengthArg(self, func):
6886 """Return the argument that holds length for each char array"""
6887 for arg in func.GetOriginalArgs():
6888 if arg.IsPointer() and not arg.IsPointer2D():
6889 return arg
6890 return None
6892 def WriteGLES2Implementation(self, func, file):
6893 """Overrriden from TypeHandler."""
6894 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6895 (func.return_type, func.original_name,
6896 func.MakeTypedOriginalArgString("")))
6897 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6898 func.WriteDestinationInitalizationValidation(file)
6899 self.WriteClientGLCallLog(func, file)
6900 data_arg = self.__GetDataArg(func)
6901 length_arg = self.__GetLengthArg(func)
6902 log_code_block = """ GPU_CLIENT_LOG_CODE_BLOCK({
6903 for (GLsizei ii = 0; ii < count; ++ii) {
6904 if (%(data)s[ii]) {"""
6905 if length_arg == None:
6906 log_code_block += """
6907 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
6908 else:
6909 log_code_block += """
6910 if (%(length)s && %(length)s[ii] >= 0) {
6911 const std::string my_str(%(data)s[ii], %(length)s[ii]);
6912 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
6913 } else {
6914 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
6915 }"""
6916 log_code_block += """
6917 } else {
6918 GPU_CLIENT_LOG(" " << ii << ": NULL");
6923 file.Write(log_code_block % {
6924 'data': data_arg.name,
6925 'length': length_arg.name if not length_arg == None else ''
6927 for arg in func.GetOriginalArgs():
6928 arg.WriteClientSideValidationCode(file, func)
6930 bucket_args = []
6931 for arg in func.GetOriginalArgs():
6932 if arg.name == 'count' or arg == self.__GetLengthArg(func):
6933 continue
6934 if arg == self.__GetDataArg(func):
6935 bucket_args.append('kResultBucketId')
6936 else:
6937 bucket_args.append(arg.name)
6938 code_block = """
6939 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
6940 return;
6942 helper_->%(func_name)sBucket(%(bucket_args)s);
6943 helper_->SetBucketSize(kResultBucketId, 0);
6944 CheckGLError();
6948 file.Write(code_block % {
6949 'data': data_arg.name,
6950 'length': length_arg.name if not length_arg == None else 'NULL',
6951 'func_name': func.name,
6952 'bucket_args': ', '.join(bucket_args),
6955 def WriteGLES2ImplementationUnitTest(self, func, file):
6956 """Overrriden from TypeHandler."""
6957 code = """
6958 TEST_F(GLES2ImplementationTest, %(name)s) {
6959 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
6960 const char* kString1 = "happy";
6961 const char* kString2 = "ending";
6962 const size_t kString1Size = ::strlen(kString1) + 1;
6963 const size_t kString2Size = ::strlen(kString2) + 1;
6964 const size_t kHeaderSize = sizeof(GLint) * 3;
6965 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
6966 const size_t kPaddedHeaderSize =
6967 transfer_buffer_->RoundToAlignment(kHeaderSize);
6968 const size_t kPaddedString1Size =
6969 transfer_buffer_->RoundToAlignment(kString1Size);
6970 const size_t kPaddedString2Size =
6971 transfer_buffer_->RoundToAlignment(kString2Size);
6972 struct Cmds {
6973 cmd::SetBucketSize set_bucket_size;
6974 cmd::SetBucketData set_bucket_header;
6975 cmd::SetToken set_token1;
6976 cmd::SetBucketData set_bucket_data1;
6977 cmd::SetToken set_token2;
6978 cmd::SetBucketData set_bucket_data2;
6979 cmd::SetToken set_token3;
6980 cmds::%(name)sBucket cmd_bucket;
6981 cmd::SetBucketSize clear_bucket_size;
6984 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
6985 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
6986 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
6988 Cmds expected;
6989 expected.set_bucket_size.Init(kBucketId, kSourceSize);
6990 expected.set_bucket_header.Init(
6991 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
6992 expected.set_token1.Init(GetNextToken());
6993 expected.set_bucket_data1.Init(
6994 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
6995 expected.set_token2.Init(GetNextToken());
6996 expected.set_bucket_data2.Init(
6997 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
6998 mem2.offset);
6999 expected.set_token3.Init(GetNextToken());
7000 expected.cmd_bucket.Init(%(bucket_args)s);
7001 expected.clear_bucket_size.Init(kBucketId, 0);
7002 const char* kStrings[] = { kString1, kString2 };
7003 gl_->%(name)s(%(gl_args)s);
7004 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7007 gl_args = []
7008 bucket_args = []
7009 for arg in func.GetOriginalArgs():
7010 if arg == self.__GetDataArg(func):
7011 gl_args.append('kStrings')
7012 bucket_args.append('kBucketId')
7013 elif arg == self.__GetLengthArg(func):
7014 gl_args.append('NULL')
7015 elif arg.name == 'count':
7016 gl_args.append('2')
7017 else:
7018 gl_args.append(arg.GetValidClientSideArg(func))
7019 bucket_args.append(arg.GetValidClientSideArg(func))
7020 file.Write(code % {
7021 'name': func.name,
7022 'gl_args': ", ".join(gl_args),
7023 'bucket_args': ", ".join(bucket_args),
7026 if self.__GetLengthArg(func) == None:
7027 return
7028 code = """
7029 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7030 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7031 const char* kString = "foobar******";
7032 const size_t kStringSize = 6; // We only need "foobar".
7033 const size_t kHeaderSize = sizeof(GLint) * 2;
7034 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7035 const size_t kPaddedHeaderSize =
7036 transfer_buffer_->RoundToAlignment(kHeaderSize);
7037 const size_t kPaddedStringSize =
7038 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7039 struct Cmds {
7040 cmd::SetBucketSize set_bucket_size;
7041 cmd::SetBucketData set_bucket_header;
7042 cmd::SetToken set_token1;
7043 cmd::SetBucketData set_bucket_data;
7044 cmd::SetToken set_token2;
7045 cmds::ShaderSourceBucket shader_source_bucket;
7046 cmd::SetBucketSize clear_bucket_size;
7049 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7050 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7052 Cmds expected;
7053 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7054 expected.set_bucket_header.Init(
7055 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7056 expected.set_token1.Init(GetNextToken());
7057 expected.set_bucket_data.Init(
7058 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7059 expected.set_token2.Init(GetNextToken());
7060 expected.shader_source_bucket.Init(%(bucket_args)s);
7061 expected.clear_bucket_size.Init(kBucketId, 0);
7062 const char* kStrings[] = { kString };
7063 const GLint kLength[] = { kStringSize };
7064 gl_->%(name)s(%(gl_args)s);
7065 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7068 gl_args = []
7069 for arg in func.GetOriginalArgs():
7070 if arg == self.__GetDataArg(func):
7071 gl_args.append('kStrings')
7072 elif arg == self.__GetLengthArg(func):
7073 gl_args.append('kLength')
7074 elif arg.name == 'count':
7075 gl_args.append('1')
7076 else:
7077 gl_args.append(arg.GetValidClientSideArg(func))
7078 file.Write(code % {
7079 'name': func.name,
7080 'gl_args': ", ".join(gl_args),
7081 'bucket_args': ", ".join(bucket_args),
7084 def WriteBucketServiceUnitTest(self, func, file, *extras):
7085 """Overrriden from TypeHandler."""
7086 cmd_args = []
7087 cmd_args_with_invalid_id = []
7088 gl_args = []
7089 for index, arg in enumerate(func.GetOriginalArgs()):
7090 if arg == self.__GetLengthArg(func):
7091 gl_args.append('_')
7092 elif arg.name == 'count':
7093 gl_args.append('1')
7094 elif arg == self.__GetDataArg(func):
7095 cmd_args.append('kBucketId')
7096 cmd_args_with_invalid_id.append('kBucketId')
7097 gl_args.append('_')
7098 elif index == 0: # Resource ID arg
7099 cmd_args.append(arg.GetValidArg(func))
7100 cmd_args_with_invalid_id.append('kInvalidClientId')
7101 gl_args.append(arg.GetValidGLArg(func))
7102 else:
7103 cmd_args.append(arg.GetValidArg(func))
7104 cmd_args_with_invalid_id.append(arg.GetValidArg(func))
7105 gl_args.append(arg.GetValidGLArg(func))
7107 test = """
7108 TEST_P(%(test_name)s, %(name)sValidArgs) {
7109 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7110 const uint32 kBucketId = 123;
7111 const char kSource0[] = "hello";
7112 const char* kSource[] = { kSource0 };
7113 const char kValidStrEnd = 0;
7114 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7115 cmds::%(name)s cmd;
7116 cmd.Init(%(cmd_args)s);
7117 decoder_->set_unsafe_es3_apis_enabled(true);
7118 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7119 if func.IsUnsafe():
7120 test += """
7121 decoder_->set_unsafe_es3_apis_enabled(false);
7122 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7124 test += """
7127 self.WriteValidUnitTest(func, file, test, {
7128 'cmd_args': ", ".join(cmd_args),
7129 'gl_args': ", ".join(gl_args),
7130 }, *extras)
7132 test = """
7133 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7134 const uint32 kBucketId = 123;
7135 const char kSource0[] = "hello";
7136 const char* kSource[] = { kSource0 };
7137 const char kValidStrEnd = 0;
7138 decoder_->set_unsafe_es3_apis_enabled(true);
7139 cmds::%(name)s cmd;
7140 // Test no bucket.
7141 cmd.Init(%(cmd_args)s);
7142 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7143 // Test invalid client.
7144 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7145 cmd.Init(%(cmd_args_with_invalid_id)s);
7146 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7147 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7150 self.WriteValidUnitTest(func, file, test, {
7151 'cmd_args': ", ".join(cmd_args),
7152 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id),
7153 }, *extras)
7155 test = """
7156 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7157 const uint32 kBucketId = 123;
7158 const char kSource0[] = "hello";
7159 const char* kSource[] = { kSource0 };
7160 const char kValidStrEnd = 0;
7161 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7162 const GLsizei kTests[] = {
7163 kCount + 1,
7165 std::numeric_limits<GLsizei>::max(),
7168 decoder_->set_unsafe_es3_apis_enabled(true);
7169 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7170 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7171 cmds::%(name)s cmd;
7172 cmd.Init(%(cmd_args)s);
7173 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7177 self.WriteValidUnitTest(func, file, test, {
7178 'cmd_args': ", ".join(cmd_args),
7179 }, *extras)
7181 test = """
7182 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7183 const uint32 kBucketId = 123;
7184 const char kSource0[] = "hello";
7185 const char* kSource[] = { kSource0 };
7186 const char kInvalidStrEnd = '*';
7187 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7188 cmds::%(name)s cmd;
7189 cmd.Init(%(cmd_args)s);
7190 decoder_->set_unsafe_es3_apis_enabled(true);
7191 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7194 self.WriteValidUnitTest(func, file, test, {
7195 'cmd_args': ", ".join(cmd_args),
7196 }, *extras)
7199 class PUTXnHandler(ArrayArgTypeHandler):
7200 """Handler for glUniform?f functions."""
7201 def __init__(self):
7202 ArrayArgTypeHandler.__init__(self)
7204 def WriteHandlerImplementation(self, func, file):
7205 """Overrriden from TypeHandler."""
7206 code = """ %(type)s temp[%(count)s] = { %(values)s};"""
7207 if func.IsUnsafe():
7208 code += """
7209 gl%(name)sv(%(location)s, 1, &temp[0]);
7211 else:
7212 code += """
7213 Do%(name)sv(%(location)s, 1, &temp[0]);
7215 values = ""
7216 args = func.GetOriginalArgs()
7217 count = int(self.GetArrayCount(func))
7218 num_args = len(args)
7219 for ii in range(count):
7220 values += "%s, " % args[len(args) - count + ii].name
7222 file.Write(code % {
7223 'name': func.name,
7224 'count': self.GetArrayCount(func),
7225 'type': self.GetArrayType(func),
7226 'location': args[0].name,
7227 'args': func.MakeOriginalArgString(""),
7228 'values': values,
7231 def WriteServiceUnitTest(self, func, file, *extras):
7232 """Overrriden from TypeHandler."""
7233 valid_test = """
7234 TEST_P(%(test_name)s, %(name)sValidArgs) {
7235 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7236 SpecializedSetup<cmds::%(name)s, 0>(true);
7237 cmds::%(name)s cmd;
7238 cmd.Init(%(args)s);"""
7239 if func.IsUnsafe():
7240 valid_test += """
7241 decoder_->set_unsafe_es3_apis_enabled(true);"""
7242 valid_test += """
7243 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7244 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7245 if func.IsUnsafe():
7246 valid_test += """
7247 decoder_->set_unsafe_es3_apis_enabled(false);
7248 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7249 valid_test += """
7252 args = func.GetOriginalArgs()
7253 local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
7254 self.WriteValidUnitTest(func, file, valid_test, {
7255 'name': func.name,
7256 'count': self.GetArrayCount(func),
7257 'local_args': local_args,
7258 }, *extras)
7260 invalid_test = """
7261 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7262 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7263 SpecializedSetup<cmds::%(name)s, 0>(false);
7264 cmds::%(name)s cmd;
7265 cmd.Init(%(args)s);
7266 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7269 self.WriteInvalidUnitTest(func, file, invalid_test, {
7270 'name': func.GetInfo('name'),
7271 'count': self.GetArrayCount(func),
7275 class GLcharHandler(CustomHandler):
7276 """Handler for functions that pass a single string ."""
7278 def __init__(self):
7279 CustomHandler.__init__(self)
7281 def WriteImmediateCmdComputeSize(self, func, file):
7282 """Overrriden from TypeHandler."""
7283 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7284 file.Write(" return static_cast<uint32_t>(\n")
7285 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
7286 file.Write(" }\n")
7288 def WriteImmediateCmdSetHeader(self, func, file):
7289 """Overrriden from TypeHandler."""
7290 code = """
7291 void SetHeader(uint32_t data_size) {
7292 header.SetCmdBySize<ValueType>(data_size);
7295 file.Write(code)
7297 def WriteImmediateCmdInit(self, func, file):
7298 """Overrriden from TypeHandler."""
7299 last_arg = func.GetLastOriginalArg()
7300 args = func.GetCmdArgs()
7301 set_code = []
7302 for arg in args:
7303 set_code.append(" %s = _%s;" % (arg.name, arg.name))
7304 code = """
7305 void Init(%(typed_args)s, uint32_t _data_size) {
7306 SetHeader(_data_size);
7307 %(set_code)s
7308 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7312 file.Write(code % {
7313 "typed_args": func.MakeTypedArgString("_"),
7314 "set_code": "\n".join(set_code),
7315 "last_arg": last_arg.name
7318 def WriteImmediateCmdSet(self, func, file):
7319 """Overrriden from TypeHandler."""
7320 last_arg = func.GetLastOriginalArg()
7321 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7322 func.MakeTypedCmdArgString("_", True))
7323 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7324 func.MakeCmdArgString("_"))
7325 file.Write(" return NextImmediateCmdAddress<ValueType>("
7326 "cmd, _data_size);\n")
7327 file.Write(" }\n")
7328 file.Write("\n")
7330 def WriteImmediateCmdHelper(self, func, file):
7331 """Overrriden from TypeHandler."""
7332 code = """ void %(name)s(%(typed_args)s) {
7333 const uint32_t data_size = strlen(name);
7334 gles2::cmds::%(name)s* c =
7335 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7336 if (c) {
7337 c->Init(%(args)s, data_size);
7342 file.Write(code % {
7343 "name": func.name,
7344 "typed_args": func.MakeTypedOriginalArgString(""),
7345 "args": func.MakeOriginalArgString(""),
7349 def WriteImmediateFormatTest(self, func, file):
7350 """Overrriden from TypeHandler."""
7351 init_code = []
7352 check_code = []
7353 all_but_last_arg = func.GetCmdArgs()[:-1]
7354 for value, arg in enumerate(all_but_last_arg):
7355 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
7356 for value, arg in enumerate(all_but_last_arg):
7357 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7358 (arg.type, value + 11, arg.name))
7359 code = """
7360 TEST_F(GLES2FormatTest, %(func_name)s) {
7361 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7362 static const char* const test_str = \"test string\";
7363 void* next_cmd = cmd.Set(
7364 &cmd,
7365 %(init_code)s
7366 test_str,
7367 strlen(test_str));
7368 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7369 cmd.header.command);
7370 EXPECT_EQ(sizeof(cmd) +
7371 RoundSizeToMultipleOfEntries(strlen(test_str)),
7372 cmd.header.size * 4u);
7373 EXPECT_EQ(static_cast<char*>(next_cmd),
7374 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7375 RoundSizeToMultipleOfEntries(strlen(test_str)));
7376 %(check_code)s
7377 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7378 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7379 CheckBytesWritten(
7380 next_cmd,
7381 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7382 sizeof(cmd) + strlen(test_str));
7386 file.Write(code % {
7387 'func_name': func.name,
7388 'init_code': "\n".join(init_code),
7389 'check_code': "\n".join(check_code),
7393 class GLcharNHandler(CustomHandler):
7394 """Handler for functions that pass a single string with an optional len."""
7396 def __init__(self):
7397 CustomHandler.__init__(self)
7399 def InitFunction(self, func):
7400 """Overrriden from TypeHandler."""
7401 func.cmd_args = []
7402 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
7404 def NeedsDataTransferFunction(self, func):
7405 """Overriden from TypeHandler."""
7406 return False
7408 def AddBucketFunction(self, generator, func):
7409 """Overrriden from TypeHandler."""
7410 pass
7412 def WriteServiceImplementation(self, func, file):
7413 """Overrriden from TypeHandler."""
7414 self.WriteServiceHandlerFunctionHeader(func, file)
7415 file.Write("""
7416 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7417 Bucket* bucket = GetBucket(bucket_id);
7418 if (!bucket || bucket->size() == 0) {
7419 return error::kInvalidArguments;
7421 std::string str;
7422 if (!bucket->GetAsString(&str)) {
7423 return error::kInvalidArguments;
7425 %(gl_func_name)s(0, str.c_str());
7426 return error::kNoError;
7429 """ % {
7430 'name': func.name,
7431 'gl_func_name': func.GetGLFunctionName(),
7432 'bucket_id': func.cmd_args[0].name,
7436 class IsHandler(TypeHandler):
7437 """Handler for glIs____ type and glGetError functions."""
7439 def __init__(self):
7440 TypeHandler.__init__(self)
7442 def InitFunction(self, func):
7443 """Overrriden from TypeHandler."""
7444 func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7445 func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7446 if func.GetInfo('result') == None:
7447 func.AddInfo('result', ['uint32_t'])
7449 def WriteServiceUnitTest(self, func, file, *extras):
7450 """Overrriden from TypeHandler."""
7451 valid_test = """
7452 TEST_P(%(test_name)s, %(name)sValidArgs) {
7453 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7454 SpecializedSetup<cmds::%(name)s, 0>(true);
7455 cmds::%(name)s cmd;
7456 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7457 if func.IsUnsafe():
7458 valid_test += """
7459 decoder_->set_unsafe_es3_apis_enabled(true);"""
7460 valid_test += """
7461 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7462 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7463 if func.IsUnsafe():
7464 valid_test += """
7465 decoder_->set_unsafe_es3_apis_enabled(false);
7466 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7467 valid_test += """
7470 comma = ""
7471 if len(func.GetOriginalArgs()):
7472 comma =", "
7473 self.WriteValidUnitTest(func, file, valid_test, {
7474 'comma': comma,
7475 }, *extras)
7477 invalid_test = """
7478 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7479 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7480 SpecializedSetup<cmds::%(name)s, 0>(false);
7481 cmds::%(name)s cmd;
7482 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7483 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7486 self.WriteInvalidUnitTest(func, file, invalid_test, {
7487 'comma': comma,
7488 }, *extras)
7490 invalid_test = """
7491 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
7492 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7493 SpecializedSetup<cmds::%(name)s, 0>(false);"""
7494 if func.IsUnsafe():
7495 invalid_test += """
7496 decoder_->set_unsafe_es3_apis_enabled(true);"""
7497 invalid_test += """
7498 cmds::%(name)s cmd;
7499 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
7500 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
7501 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
7502 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
7503 if func.IsUnsafe():
7504 invalid_test += """
7505 decoder_->set_unsafe_es3_apis_enabled(true);"""
7506 invalid_test += """
7509 self.WriteValidUnitTest(func, file, invalid_test, {
7510 'comma': comma,
7511 }, *extras)
7513 def WriteServiceImplementation(self, func, file):
7514 """Overrriden from TypeHandler."""
7515 self.WriteServiceHandlerFunctionHeader(func, file)
7516 args = func.GetOriginalArgs()
7517 for arg in args:
7518 arg.WriteGetCode(file)
7520 code = """ typedef cmds::%(func_name)s::Result Result;
7521 Result* result_dst = GetSharedMemoryAs<Result*>(
7522 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
7523 if (!result_dst) {
7524 return error::kOutOfBounds;
7527 file.Write(code % {'func_name': func.name})
7528 func.WriteHandlerValidation(file)
7529 if func.IsUnsafe():
7530 assert func.GetInfo('id_mapping')
7531 assert len(func.GetInfo('id_mapping')) == 1
7532 assert len(args) == 1
7533 id_type = func.GetInfo('id_mapping')[0]
7534 file.Write(" %s service_%s = 0;\n" % (args[0].type, id_type.lower()))
7535 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
7536 (id_type, id_type.lower(), id_type.lower()))
7537 else:
7538 file.Write(" *result_dst = %s(%s);\n" %
7539 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
7540 file.Write(" return error::kNoError;\n")
7541 file.Write("}\n")
7542 file.Write("\n")
7544 def WriteGLES2Implementation(self, func, file):
7545 """Overrriden from TypeHandler."""
7546 impl_func = func.GetInfo('impl_func')
7547 if impl_func == None or impl_func == True:
7548 error_value = func.GetInfo("error_value") or "GL_FALSE"
7549 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7550 (func.return_type, func.original_name,
7551 func.MakeTypedOriginalArgString("")))
7552 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7553 self.WriteTraceEvent(func, file)
7554 func.WriteDestinationInitalizationValidation(file)
7555 self.WriteClientGLCallLog(func, file)
7556 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
7557 file.Write(" Result* result = GetResultAs<Result*>();\n")
7558 file.Write(" if (!result) {\n")
7559 file.Write(" return %s;\n" % error_value)
7560 file.Write(" }\n")
7561 file.Write(" *result = 0;\n")
7562 assert len(func.GetOriginalArgs()) == 1
7563 id_arg = func.GetOriginalArgs()[0]
7564 if id_arg.type == 'GLsync':
7565 arg_string = "ToGLuint(%s)" % func.MakeOriginalArgString("")
7566 else:
7567 arg_string = func.MakeOriginalArgString("")
7568 file.Write(
7569 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
7570 (func.name, arg_string))
7571 file.Write(" WaitForCmd();\n")
7572 file.Write(" %s result_value = *result" % func.return_type)
7573 if func.return_type == "GLboolean":
7574 file.Write(" != 0")
7575 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
7576 file.Write(" CheckGLError();\n")
7577 file.Write(" return result_value;\n")
7578 file.Write("}\n")
7579 file.Write("\n")
7581 def WriteGLES2ImplementationUnitTest(self, func, file):
7582 """Overrriden from TypeHandler."""
7583 client_test = func.GetInfo('client_test')
7584 if client_test == None or client_test == True:
7585 code = """
7586 TEST_F(GLES2ImplementationTest, %(name)s) {
7587 struct Cmds {
7588 cmds::%(name)s cmd;
7591 Cmds expected;
7592 ExpectedMemoryInfo result1 =
7593 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
7594 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
7596 EXPECT_CALL(*command_buffer(), OnFlush())
7597 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
7598 .RetiresOnSaturation();
7600 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
7601 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7602 EXPECT_TRUE(result);
7605 args = func.GetOriginalArgs()
7606 assert len(args) == 1
7607 file.Write(code % {
7608 'name': func.name,
7609 'cmd_id_value': args[0].GetValidClientSideCmdArg(func),
7610 'gl_id_value': args[0].GetValidClientSideArg(func) })
7613 class STRnHandler(TypeHandler):
7614 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
7615 GetTranslatedShaderSourceANGLE."""
7617 def __init__(self):
7618 TypeHandler.__init__(self)
7620 def InitFunction(self, func):
7621 """Overrriden from TypeHandler."""
7622 # remove all but the first cmd args.
7623 cmd_args = func.GetCmdArgs()
7624 func.ClearCmdArgs()
7625 func.AddCmdArg(cmd_args[0])
7626 # add on a bucket id.
7627 func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
7629 def WriteGLES2Implementation(self, func, file):
7630 """Overrriden from TypeHandler."""
7631 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
7632 GPU_CLIENT_SINGLE_THREAD_CHECK();
7634 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
7635 << "] gl%(func_name)s" << "("
7636 << %(arg0)s << ", "
7637 << %(arg1)s << ", "
7638 << static_cast<void*>(%(arg2)s) << ", "
7639 << static_cast<void*>(%(arg3)s) << ")");
7640 helper_->SetBucketSize(kResultBucketId, 0);
7641 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
7642 std::string str;
7643 GLsizei max_size = 0;
7644 if (GetBucketAsString(kResultBucketId, &str)) {
7645 if (bufsize > 0) {
7646 max_size =
7647 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
7648 memcpy(%(dest_name)s, str.c_str(), max_size);
7649 %(dest_name)s[max_size] = '\\0';
7650 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
7653 if (%(length_name)s != NULL) {
7654 *%(length_name)s = max_size;
7656 CheckGLError();
7659 args = func.GetOriginalArgs()
7660 str_args = {
7661 'return_type': func.return_type,
7662 'func_name': func.original_name,
7663 'args': func.MakeTypedOriginalArgString(""),
7664 'id_name': args[0].name,
7665 'bufsize_name': args[1].name,
7666 'length_name': args[2].name,
7667 'dest_name': args[3].name,
7668 'arg0': args[0].name,
7669 'arg1': args[1].name,
7670 'arg2': args[2].name,
7671 'arg3': args[3].name,
7673 file.Write(code_1 % str_args)
7674 func.WriteDestinationInitalizationValidation(file)
7675 file.Write(code_2 % str_args)
7677 def WriteServiceUnitTest(self, func, file, *extras):
7678 """Overrriden from TypeHandler."""
7679 valid_test = """
7680 TEST_P(%(test_name)s, %(name)sValidArgs) {
7681 const char* kInfo = "hello";
7682 const uint32_t kBucketId = 123;
7683 SpecializedSetup<cmds::%(name)s, 0>(true);
7684 %(expect_len_code)s
7685 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
7686 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
7687 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
7688 cmds::%(name)s cmd;
7689 cmd.Init(%(args)s);
7690 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7691 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
7692 ASSERT_TRUE(bucket != NULL);
7693 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
7694 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
7695 bucket->size()));
7696 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7699 args = func.GetOriginalArgs()
7700 id_name = args[0].GetValidGLArg(func)
7701 get_len_func = func.GetInfo('get_len_func')
7702 get_len_enum = func.GetInfo('get_len_enum')
7703 sub = {
7704 'id_name': id_name,
7705 'get_len_func': get_len_func,
7706 'get_len_enum': get_len_enum,
7707 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
7708 args[0].GetValidGLArg(func),
7709 'args': '%s, kBucketId' % args[0].GetValidArg(func),
7710 'expect_len_code': '',
7712 if get_len_func and get_len_func[0:2] == 'gl':
7713 sub['expect_len_code'] = (
7714 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
7715 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
7716 get_len_func[2:], id_name, get_len_enum)
7717 self.WriteValidUnitTest(func, file, valid_test, sub, *extras)
7719 invalid_test = """
7720 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7721 const uint32_t kBucketId = 123;
7722 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
7723 .Times(0);
7724 cmds::%(name)s cmd;
7725 cmd.Init(kInvalidClientId, kBucketId);
7726 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7727 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7730 self.WriteValidUnitTest(func, file, invalid_test, *extras)
7732 def WriteServiceImplementation(self, func, file):
7733 """Overrriden from TypeHandler."""
7734 pass
7736 class NamedType(object):
7737 """A class that represents a type of an argument in a client function.
7739 A type of an argument that is to be passed through in the command buffer
7740 command. Currently used only for the arguments that are specificly named in
7741 the 'cmd_buffer_functions.txt' file, mostly enums.
7744 def __init__(self, info):
7745 assert not 'is_complete' in info or info['is_complete'] == True
7746 self.info = info
7747 self.valid = info['valid']
7748 if 'invalid' in info:
7749 self.invalid = info['invalid']
7750 else:
7751 self.invalid = []
7752 if 'valid_es3' in info:
7753 self.valid_es3 = info['valid_es3']
7754 else:
7755 self.valid_es3 = []
7756 if 'deprecated_es3' in info:
7757 self.deprecated_es3 = info['deprecated_es3']
7758 else:
7759 self.deprecated_es3 = []
7761 def GetType(self):
7762 return self.info['type']
7764 def GetInvalidValues(self):
7765 return self.invalid
7767 def GetValidValues(self):
7768 return self.valid
7770 def GetValidValuesES3(self):
7771 return self.valid_es3
7773 def GetDeprecatedValuesES3(self):
7774 return self.deprecated_es3
7776 def IsConstant(self):
7777 if not 'is_complete' in self.info:
7778 return False
7780 return len(self.GetValidValues()) == 1
7782 def GetConstantValue(self):
7783 return self.GetValidValues()[0]
7785 class Argument(object):
7786 """A class that represents a function argument."""
7788 cmd_type_map_ = {
7789 'GLenum': 'uint32_t',
7790 'GLint': 'int32_t',
7791 'GLintptr': 'int32_t',
7792 'GLsizei': 'int32_t',
7793 'GLsizeiptr': 'int32_t',
7794 'GLfloat': 'float',
7795 'GLclampf': 'float',
7797 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
7799 def __init__(self, name, type):
7800 self.name = name
7801 self.optional = type.endswith("Optional*")
7802 if self.optional:
7803 type = type[:-9] + "*"
7804 self.type = type
7806 if type in self.cmd_type_map_:
7807 self.cmd_type = self.cmd_type_map_[type]
7808 else:
7809 self.cmd_type = 'uint32_t'
7811 def IsPointer(self):
7812 """Returns true if argument is a pointer."""
7813 return False
7815 def IsPointer2D(self):
7816 """Returns true if argument is a 2D pointer."""
7817 return False
7819 def IsConstant(self):
7820 """Returns true if the argument has only one valid value."""
7821 return False
7823 def AddCmdArgs(self, args):
7824 """Adds command arguments for this argument to the given list."""
7825 if not self.IsConstant():
7826 return args.append(self)
7828 def AddInitArgs(self, args):
7829 """Adds init arguments for this argument to the given list."""
7830 if not self.IsConstant():
7831 return args.append(self)
7833 def GetValidArg(self, func):
7834 """Gets a valid value for this argument."""
7835 valid_arg = func.GetValidArg(self)
7836 if valid_arg != None:
7837 return valid_arg
7839 index = func.GetOriginalArgs().index(self)
7840 return str(index + 1)
7842 def GetValidClientSideArg(self, func):
7843 """Gets a valid value for this argument."""
7844 valid_arg = func.GetValidArg(self)
7845 if valid_arg != None:
7846 return valid_arg
7848 if self.IsPointer():
7849 return 'nullptr'
7850 index = func.GetOriginalArgs().index(self)
7851 if self.type == 'GLsync':
7852 return ("reinterpret_cast<GLsync>(%d)" % (index + 1))
7853 return str(index + 1)
7855 def GetValidClientSideCmdArg(self, func):
7856 """Gets a valid value for this argument."""
7857 valid_arg = func.GetValidArg(self)
7858 if valid_arg != None:
7859 return valid_arg
7860 try:
7861 index = func.GetOriginalArgs().index(self)
7862 return str(index + 1)
7863 except ValueError:
7864 pass
7865 index = func.GetCmdArgs().index(self)
7866 return str(index + 1)
7868 def GetValidGLArg(self, func):
7869 """Gets a valid GL value for this argument."""
7870 value = self.GetValidArg(func)
7871 if self.type == 'GLsync':
7872 return ("reinterpret_cast<GLsync>(%s)" % value)
7873 return value
7875 def GetValidNonCachedClientSideArg(self, func):
7876 """Returns a valid value for this argument in a GL call.
7877 Using the value will produce a command buffer service invocation.
7878 Returns None if there is no such value."""
7879 value = '123'
7880 if self.type == 'GLsync':
7881 return ("reinterpret_cast<GLsync>(%s)" % value)
7882 return value
7884 def GetValidNonCachedClientSideCmdArg(self, func):
7885 """Returns a valid value for this argument in a command buffer command.
7886 Calling the GL function with the value returned by
7887 GetValidNonCachedClientSideArg will result in a command buffer command
7888 that contains the value returned by this function. """
7889 return '123'
7891 def GetNumInvalidValues(self, func):
7892 """returns the number of invalid values to be tested."""
7893 return 0
7895 def GetInvalidArg(self, index):
7896 """returns an invalid value and expected parse result by index."""
7897 return ("---ERROR0---", "---ERROR2---", None)
7899 def GetLogArg(self):
7900 """Get argument appropriate for LOG macro."""
7901 if self.type == 'GLboolean':
7902 return 'GLES2Util::GetStringBool(%s)' % self.name
7903 if self.type == 'GLenum':
7904 return 'GLES2Util::GetStringEnum(%s)' % self.name
7905 return self.name
7907 def WriteGetCode(self, file):
7908 """Writes the code to get an argument from a command structure."""
7909 if self.type == 'GLsync':
7910 my_type = 'GLuint'
7911 else:
7912 my_type = self.type
7913 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
7914 (my_type, self.name, my_type, self.name))
7916 def WriteValidationCode(self, file, func):
7917 """Writes the validation code for an argument."""
7918 pass
7920 def WriteClientSideValidationCode(self, file, func):
7921 """Writes the validation code for an argument."""
7922 pass
7924 def WriteDestinationInitalizationValidation(self, file, func):
7925 """Writes the client side destintion initialization validation."""
7926 pass
7928 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
7929 """Writes the client side destintion initialization validation if needed."""
7930 parts = self.type.split(" ")
7931 if len(parts) > 1:
7932 return
7933 if parts[0] in self.need_validation_:
7934 file.Write(
7935 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
7936 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
7939 def WriteGetAddress(self, file):
7940 """Writes the code to get the address this argument refers to."""
7941 pass
7943 def GetImmediateVersion(self):
7944 """Gets the immediate version of this argument."""
7945 return self
7947 def GetBucketVersion(self):
7948 """Gets the bucket version of this argument."""
7949 return self
7952 class BoolArgument(Argument):
7953 """class for GLboolean"""
7955 def __init__(self, name, type):
7956 Argument.__init__(self, name, 'GLboolean')
7958 def GetValidArg(self, func):
7959 """Gets a valid value for this argument."""
7960 return 'true'
7962 def GetValidClientSideArg(self, func):
7963 """Gets a valid value for this argument."""
7964 return 'true'
7966 def GetValidClientSideCmdArg(self, func):
7967 """Gets a valid value for this argument."""
7968 return 'true'
7970 def GetValidGLArg(self, func):
7971 """Gets a valid GL value for this argument."""
7972 return 'true'
7975 class UniformLocationArgument(Argument):
7976 """class for uniform locations."""
7978 def __init__(self, name):
7979 Argument.__init__(self, name, "GLint")
7981 def WriteGetCode(self, file):
7982 """Writes the code to get an argument from a command structure."""
7983 code = """ %s %s = static_cast<%s>(c.%s);
7985 file.Write(code % (self.type, self.name, self.type, self.name))
7987 class DataSizeArgument(Argument):
7988 """class for data_size which Bucket commands do not need."""
7990 def __init__(self, name):
7991 Argument.__init__(self, name, "uint32_t")
7993 def GetBucketVersion(self):
7994 return None
7997 class SizeArgument(Argument):
7998 """class for GLsizei and GLsizeiptr."""
8000 def __init__(self, name, type):
8001 Argument.__init__(self, name, type)
8003 def GetNumInvalidValues(self, func):
8004 """overridden from Argument."""
8005 if func.IsImmediate():
8006 return 0
8007 return 1
8009 def GetInvalidArg(self, index):
8010 """overridden from Argument."""
8011 return ("-1", "kNoError", "GL_INVALID_VALUE")
8013 def WriteValidationCode(self, file, func):
8014 """overridden from Argument."""
8015 if func.IsUnsafe():
8016 return
8017 code = """ if (%(var_name)s < 0) {
8018 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8019 return error::kNoError;
8022 file.Write(code % {
8023 "var_name": self.name,
8024 "func_name": func.original_name,
8027 def WriteClientSideValidationCode(self, file, func):
8028 """overridden from Argument."""
8029 code = """ if (%(var_name)s < 0) {
8030 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8031 return;
8034 file.Write(code % {
8035 "var_name": self.name,
8036 "func_name": func.original_name,
8040 class SizeNotNegativeArgument(SizeArgument):
8041 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8043 def __init__(self, name, type, gl_type):
8044 SizeArgument.__init__(self, name, gl_type)
8046 def GetInvalidArg(self, index):
8047 """overridden from SizeArgument."""
8048 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8050 def WriteValidationCode(self, file, func):
8051 """overridden from SizeArgument."""
8052 pass
8055 class EnumBaseArgument(Argument):
8056 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8057 ValidatedBoolArgument."""
8059 def __init__(self, name, gl_type, type, gl_error):
8060 Argument.__init__(self, name, gl_type)
8062 self.local_type = type
8063 self.gl_error = gl_error
8064 name = type[len(gl_type):]
8065 self.type_name = name
8066 self.named_type = NamedType(_NAMED_TYPE_INFO[name])
8068 def IsConstant(self):
8069 return self.named_type.IsConstant()
8071 def GetConstantValue(self):
8072 return self.named_type.GetConstantValue()
8074 def WriteValidationCode(self, file, func):
8075 if func.IsUnsafe():
8076 return
8077 if self.named_type.IsConstant():
8078 return
8079 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
8080 (ToUnderscore(self.type_name), self.name))
8081 if self.gl_error == "GL_INVALID_ENUM":
8082 file.Write(
8083 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8084 (func.original_name, self.name, self.name))
8085 else:
8086 file.Write(
8087 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8088 (self.gl_error, func.original_name, self.name, self.gl_error))
8089 file.Write(" return error::kNoError;\n")
8090 file.Write(" }\n")
8092 def WriteClientSideValidationCode(self, file, func):
8093 if not self.named_type.IsConstant():
8094 return
8095 file.Write(" if (%s != %s) {" % (self.name,
8096 self.GetConstantValue()))
8097 file.Write(
8098 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8099 (self.gl_error, func.original_name, self.name, self.gl_error))
8100 if func.return_type == "void":
8101 file.Write(" return;\n")
8102 else:
8103 file.Write(" return %s;\n" % func.GetErrorReturnString())
8104 file.Write(" }\n")
8106 def GetValidArg(self, func):
8107 valid_arg = func.GetValidArg(self)
8108 if valid_arg != None:
8109 return valid_arg
8110 valid = self.named_type.GetValidValues()
8111 if valid:
8112 num_valid = len(valid)
8113 return valid[0]
8115 index = func.GetOriginalArgs().index(self)
8116 return str(index + 1)
8118 def GetValidClientSideArg(self, func):
8119 """Gets a valid value for this argument."""
8120 return self.GetValidArg(func)
8122 def GetValidClientSideCmdArg(self, func):
8123 """Gets a valid value for this argument."""
8124 valid_arg = func.GetValidArg(self)
8125 if valid_arg != None:
8126 return valid_arg
8128 valid = self.named_type.GetValidValues()
8129 if valid:
8130 num_valid = len(valid)
8131 return valid[0]
8133 try:
8134 index = func.GetOriginalArgs().index(self)
8135 return str(index + 1)
8136 except ValueError:
8137 pass
8138 index = func.GetCmdArgs().index(self)
8139 return str(index + 1)
8141 def GetValidGLArg(self, func):
8142 """Gets a valid value for this argument."""
8143 return self.GetValidArg(func)
8145 def GetNumInvalidValues(self, func):
8146 """returns the number of invalid values to be tested."""
8147 return len(self.named_type.GetInvalidValues())
8149 def GetInvalidArg(self, index):
8150 """returns an invalid value by index."""
8151 invalid = self.named_type.GetInvalidValues()
8152 if invalid:
8153 num_invalid = len(invalid)
8154 if index >= num_invalid:
8155 index = num_invalid - 1
8156 return (invalid[index], "kNoError", self.gl_error)
8157 return ("---ERROR1---", "kNoError", self.gl_error)
8160 class EnumArgument(EnumBaseArgument):
8161 """A class that represents a GLenum argument"""
8163 def __init__(self, name, type):
8164 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
8166 def GetLogArg(self):
8167 """Overridden from Argument."""
8168 return ("GLES2Util::GetString%s(%s)" %
8169 (self.type_name, self.name))
8172 class IntArgument(EnumBaseArgument):
8173 """A class for a GLint argument that can only accept specific values.
8175 For example glTexImage2D takes a GLint for its internalformat
8176 argument instead of a GLenum.
8179 def __init__(self, name, type):
8180 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
8183 class ValidatedBoolArgument(EnumBaseArgument):
8184 """A class for a GLboolean argument that can only accept specific values.
8186 For example glUniformMatrix takes a GLboolean for it's transpose but it
8187 must be false.
8190 def __init__(self, name, type):
8191 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
8193 def GetLogArg(self):
8194 """Overridden from Argument."""
8195 return 'GLES2Util::GetStringBool(%s)' % self.name
8198 class BitFieldArgument(EnumBaseArgument):
8199 """A class for a GLbitfield argument that can only accept specific values.
8201 For example glFenceSync takes a GLbitfield for its flags argument bit it
8202 must be 0.
8205 def __init__(self, name, type):
8206 EnumBaseArgument.__init__(self, name, "GLbitfield", type,
8207 "GL_INVALID_VALUE")
8210 class ImmediatePointerArgument(Argument):
8211 """A class that represents an immediate argument to a function.
8213 An immediate argument is one where the data follows the command.
8216 def __init__(self, name, type):
8217 Argument.__init__(self, name, type)
8219 def IsPointer(self):
8220 return True
8222 def GetPointedType(self):
8223 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8224 assert match
8225 return match.groupdict()['element_type']
8227 def AddCmdArgs(self, args):
8228 """Overridden from Argument."""
8229 pass
8231 def WriteGetCode(self, file):
8232 """Overridden from Argument."""
8233 file.Write(
8234 " %s %s = GetImmediateDataAs<%s>(\n" %
8235 (self.type, self.name, self.type))
8236 file.Write(" c, data_size, immediate_data_size);\n")
8238 def WriteValidationCode(self, file, func):
8239 """Overridden from Argument."""
8240 if self.optional:
8241 return
8242 file.Write(" if (%s == NULL) {\n" % self.name)
8243 file.Write(" return error::kOutOfBounds;\n")
8244 file.Write(" }\n")
8246 def GetImmediateVersion(self):
8247 """Overridden from Argument."""
8248 return None
8250 def WriteDestinationInitalizationValidation(self, file, func):
8251 """Overridden from Argument."""
8252 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8254 def GetLogArg(self):
8255 """Overridden from Argument."""
8256 return "static_cast<const void*>(%s)" % self.name
8259 class PointerArgument(Argument):
8260 """A class that represents a pointer argument to a function."""
8262 def __init__(self, name, type):
8263 Argument.__init__(self, name, type)
8265 def IsPointer(self):
8266 """Overridden from Argument."""
8267 return True
8269 def IsPointer2D(self):
8270 """Overridden from Argument."""
8271 return self.type.count('*') == 2
8273 def GetPointedType(self):
8274 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8275 assert match
8276 return match.groupdict()['element_type']
8278 def GetValidArg(self, func):
8279 """Overridden from Argument."""
8280 return "shared_memory_id_, shared_memory_offset_"
8282 def GetValidGLArg(self, func):
8283 """Overridden from Argument."""
8284 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
8286 def GetNumInvalidValues(self, func):
8287 """Overridden from Argument."""
8288 return 2
8290 def GetInvalidArg(self, index):
8291 """Overridden from Argument."""
8292 if index == 0:
8293 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8294 else:
8295 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8296 "kOutOfBounds", None)
8298 def GetLogArg(self):
8299 """Overridden from Argument."""
8300 return "static_cast<const void*>(%s)" % self.name
8302 def AddCmdArgs(self, args):
8303 """Overridden from Argument."""
8304 args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
8305 args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
8307 def WriteGetCode(self, file):
8308 """Overridden from Argument."""
8309 file.Write(
8310 " %s %s = GetSharedMemoryAs<%s>(\n" %
8311 (self.type, self.name, self.type))
8312 file.Write(
8313 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8314 (self.name, self.name))
8316 def WriteGetAddress(self, file):
8317 """Overridden from Argument."""
8318 file.Write(
8319 " %s %s = GetSharedMemoryAs<%s>(\n" %
8320 (self.type, self.name, self.type))
8321 file.Write(
8322 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8323 (self.name, self.name, self.name))
8325 def WriteValidationCode(self, file, func):
8326 """Overridden from Argument."""
8327 if self.optional:
8328 return
8329 file.Write(" if (%s == NULL) {\n" % self.name)
8330 file.Write(" return error::kOutOfBounds;\n")
8331 file.Write(" }\n")
8333 def GetImmediateVersion(self):
8334 """Overridden from Argument."""
8335 return ImmediatePointerArgument(self.name, self.type)
8337 def GetBucketVersion(self):
8338 """Overridden from Argument."""
8339 if self.type.find('char') >= 0:
8340 if self.IsPointer2D():
8341 return InputStringArrayBucketArgument(self.name, self.type)
8342 return InputStringBucketArgument(self.name, self.type)
8343 return BucketPointerArgument(self.name, self.type)
8345 def WriteDestinationInitalizationValidation(self, file, func):
8346 """Overridden from Argument."""
8347 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8350 class BucketPointerArgument(PointerArgument):
8351 """A class that represents an bucket argument to a function."""
8353 def __init__(self, name, type):
8354 Argument.__init__(self, name, type)
8356 def AddCmdArgs(self, args):
8357 """Overridden from Argument."""
8358 pass
8360 def WriteGetCode(self, file):
8361 """Overridden from Argument."""
8362 file.Write(
8363 " %s %s = bucket->GetData(0, data_size);\n" %
8364 (self.type, self.name))
8366 def WriteValidationCode(self, file, func):
8367 """Overridden from Argument."""
8368 pass
8370 def GetImmediateVersion(self):
8371 """Overridden from Argument."""
8372 return None
8374 def WriteDestinationInitalizationValidation(self, file, func):
8375 """Overridden from Argument."""
8376 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8378 def GetLogArg(self):
8379 """Overridden from Argument."""
8380 return "static_cast<const void*>(%s)" % self.name
8383 class InputStringBucketArgument(Argument):
8384 """A string input argument where the string is passed in a bucket."""
8386 def __init__(self, name, type):
8387 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8389 def IsPointer(self):
8390 """Overridden from Argument."""
8391 return True
8393 def IsPointer2D(self):
8394 """Overridden from Argument."""
8395 return False
8398 class InputStringArrayBucketArgument(Argument):
8399 """A string array input argument where the strings are passed in a bucket."""
8401 def __init__(self, name, type):
8402 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8403 self._original_name = name
8405 def WriteGetCode(self, file):
8406 """Overridden from Argument."""
8407 code = """
8408 Bucket* bucket = GetBucket(c.%(name)s);
8409 if (!bucket) {
8410 return error::kInvalidArguments;
8412 GLsizei count = 0;
8413 std::vector<char*> strs;
8414 std::vector<GLint> len;
8415 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8416 return error::kInvalidArguments;
8418 const char** %(original_name)s =
8419 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8420 const GLint* length =
8421 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8422 (void)length;
8424 file.Write(code % {
8425 'name': self.name,
8426 'original_name': self._original_name,
8429 def GetValidArg(self, func):
8430 return "kNameBucketId"
8432 def GetValidGLArg(self, func):
8433 return "_"
8435 def IsPointer(self):
8436 """Overridden from Argument."""
8437 return True
8439 def IsPointer2D(self):
8440 """Overridden from Argument."""
8441 return True
8444 class ResourceIdArgument(Argument):
8445 """A class that represents a resource id argument to a function."""
8447 def __init__(self, name, type):
8448 match = re.match("(GLid\w+)", type)
8449 self.resource_type = match.group(1)[4:]
8450 if self.resource_type == "Sync":
8451 type = type.replace(match.group(1), "GLsync")
8452 else:
8453 type = type.replace(match.group(1), "GLuint")
8454 Argument.__init__(self, name, type)
8456 def WriteGetCode(self, file):
8457 """Overridden from Argument."""
8458 if self.type == "GLsync":
8459 my_type = "GLuint"
8460 else:
8461 my_type = self.type
8462 file.Write(" %s %s = c.%s;\n" % (my_type, self.name, self.name))
8464 def GetValidArg(self, func):
8465 return "client_%s_id_" % self.resource_type.lower()
8467 def GetValidGLArg(self, func):
8468 if self.resource_type == "Sync":
8469 return "reinterpret_cast<GLsync>(kService%sId)" % self.resource_type
8470 return "kService%sId" % self.resource_type
8473 class ResourceIdBindArgument(Argument):
8474 """Represents a resource id argument to a bind function."""
8476 def __init__(self, name, type):
8477 match = re.match("(GLidBind\w+)", type)
8478 self.resource_type = match.group(1)[8:]
8479 type = type.replace(match.group(1), "GLuint")
8480 Argument.__init__(self, name, type)
8482 def WriteGetCode(self, file):
8483 """Overridden from Argument."""
8484 code = """ %(type)s %(name)s = c.%(name)s;
8486 file.Write(code % {'type': self.type, 'name': self.name})
8488 def GetValidArg(self, func):
8489 return "client_%s_id_" % self.resource_type.lower()
8491 def GetValidGLArg(self, func):
8492 return "kService%sId" % self.resource_type
8495 class ResourceIdZeroArgument(Argument):
8496 """Represents a resource id argument to a function that can be zero."""
8498 def __init__(self, name, type):
8499 match = re.match("(GLidZero\w+)", type)
8500 self.resource_type = match.group(1)[8:]
8501 type = type.replace(match.group(1), "GLuint")
8502 Argument.__init__(self, name, type)
8504 def WriteGetCode(self, file):
8505 """Overridden from Argument."""
8506 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
8508 def GetValidArg(self, func):
8509 return "client_%s_id_" % self.resource_type.lower()
8511 def GetValidGLArg(self, func):
8512 return "kService%sId" % self.resource_type
8514 def GetNumInvalidValues(self, func):
8515 """returns the number of invalid values to be tested."""
8516 return 1
8518 def GetInvalidArg(self, index):
8519 """returns an invalid value by index."""
8520 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
8523 class Function(object):
8524 """A class that represents a function."""
8526 type_handlers = {
8527 '': TypeHandler(),
8528 'Bind': BindHandler(),
8529 'Create': CreateHandler(),
8530 'Custom': CustomHandler(),
8531 'Data': DataHandler(),
8532 'Delete': DeleteHandler(),
8533 'DELn': DELnHandler(),
8534 'GENn': GENnHandler(),
8535 'GETn': GETnHandler(),
8536 'GLchar': GLcharHandler(),
8537 'GLcharN': GLcharNHandler(),
8538 'HandWritten': HandWrittenHandler(),
8539 'Is': IsHandler(),
8540 'Manual': ManualHandler(),
8541 'PUT': PUTHandler(),
8542 'PUTn': PUTnHandler(),
8543 'PUTSTR': PUTSTRHandler(),
8544 'PUTXn': PUTXnHandler(),
8545 'StateSet': StateSetHandler(),
8546 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
8547 'StateSetFrontBack': StateSetFrontBackHandler(),
8548 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
8549 'StateSetNamedParameter': StateSetNamedParameter(),
8550 'STRn': STRnHandler(),
8551 'Todo': TodoHandler(),
8554 def __init__(self, name, info):
8555 self.name = name
8556 self.original_name = info['original_name']
8558 self.original_args = self.ParseArgs(info['original_args'])
8560 if 'cmd_args' in info:
8561 self.args_for_cmds = self.ParseArgs(info['cmd_args'])
8562 else:
8563 self.args_for_cmds = self.original_args[:]
8565 self.return_type = info['return_type']
8566 if self.return_type != 'void':
8567 self.return_arg = CreateArg(info['return_type'] + " result")
8568 else:
8569 self.return_arg = None
8571 self.num_pointer_args = sum(
8572 [1 for arg in self.args_for_cmds if arg.IsPointer()])
8573 if self.num_pointer_args > 0:
8574 for arg in reversed(self.original_args):
8575 if arg.IsPointer():
8576 self.last_original_pointer_arg = arg
8577 break
8578 else:
8579 self.last_original_pointer_arg = None
8580 self.info = info
8581 self.type_handler = self.type_handlers[info['type']]
8582 self.can_auto_generate = (self.num_pointer_args == 0 and
8583 info['return_type'] == "void")
8584 self.InitFunction()
8586 def ParseArgs(self, arg_string):
8587 """Parses a function arg string."""
8588 args = []
8589 parts = arg_string.split(',')
8590 for arg_string in parts:
8591 arg = CreateArg(arg_string)
8592 if arg:
8593 args.append(arg)
8594 return args
8596 def IsType(self, type_name):
8597 """Returns true if function is a certain type."""
8598 return self.info['type'] == type_name
8600 def InitFunction(self):
8601 """Creates command args and calls the init function for the type handler.
8603 Creates argument lists for command buffer commands, eg. self.cmd_args and
8604 self.init_args.
8605 Calls the type function initialization.
8606 Override to create different kind of command buffer command argument lists.
8608 self.cmd_args = []
8609 for arg in self.args_for_cmds:
8610 arg.AddCmdArgs(self.cmd_args)
8612 self.init_args = []
8613 for arg in self.args_for_cmds:
8614 arg.AddInitArgs(self.init_args)
8616 if self.return_arg:
8617 self.init_args.append(self.return_arg)
8619 self.type_handler.InitFunction(self)
8621 def IsImmediate(self):
8622 """Returns whether the function is immediate data function or not."""
8623 return False
8625 def IsUnsafe(self):
8626 """Returns whether the function has service side validation or not."""
8627 return self.GetInfo('unsafe', False)
8629 def GetInfo(self, name, default = None):
8630 """Returns a value from the function info for this function."""
8631 if name in self.info:
8632 return self.info[name]
8633 return default
8635 def GetValidArg(self, arg):
8636 """Gets a valid argument value for the parameter arg from the function info
8637 if one exists."""
8638 try:
8639 index = self.GetOriginalArgs().index(arg)
8640 except ValueError:
8641 return None
8643 valid_args = self.GetInfo('valid_args')
8644 if valid_args and str(index) in valid_args:
8645 return valid_args[str(index)]
8646 return None
8648 def AddInfo(self, name, value):
8649 """Adds an info."""
8650 self.info[name] = value
8652 def IsExtension(self):
8653 return self.GetInfo('extension') or self.GetInfo('extension_flag')
8655 def IsCoreGLFunction(self):
8656 return (not self.IsExtension() and
8657 not self.GetInfo('pepper_interface') and
8658 not self.IsUnsafe())
8660 def InPepperInterface(self, interface):
8661 ext = self.GetInfo('pepper_interface')
8662 if not interface.GetName():
8663 return self.IsCoreGLFunction()
8664 return ext == interface.GetName()
8666 def InAnyPepperExtension(self):
8667 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
8669 def GetErrorReturnString(self):
8670 if self.GetInfo("error_return"):
8671 return self.GetInfo("error_return")
8672 elif self.return_type == "GLboolean":
8673 return "GL_FALSE"
8674 elif "*" in self.return_type:
8675 return "NULL"
8676 return "0"
8678 def GetGLFunctionName(self):
8679 """Gets the function to call to execute GL for this command."""
8680 if self.GetInfo('decoder_func'):
8681 return self.GetInfo('decoder_func')
8682 return "gl%s" % self.original_name
8684 def GetGLTestFunctionName(self):
8685 gl_func_name = self.GetInfo('gl_test_func')
8686 if gl_func_name == None:
8687 gl_func_name = self.GetGLFunctionName()
8688 if gl_func_name.startswith("gl"):
8689 gl_func_name = gl_func_name[2:]
8690 else:
8691 gl_func_name = self.original_name
8692 return gl_func_name
8694 def GetDataTransferMethods(self):
8695 return self.GetInfo('data_transfer_methods',
8696 ['immediate' if self.num_pointer_args == 1 else 'shm'])
8698 def AddCmdArg(self, arg):
8699 """Adds a cmd argument to this function."""
8700 self.cmd_args.append(arg)
8702 def GetCmdArgs(self):
8703 """Gets the command args for this function."""
8704 return self.cmd_args
8706 def ClearCmdArgs(self):
8707 """Clears the command args for this function."""
8708 self.cmd_args = []
8710 def GetCmdConstants(self):
8711 """Gets the constants for this function."""
8712 return [arg for arg in self.args_for_cmds if arg.IsConstant()]
8714 def GetInitArgs(self):
8715 """Gets the init args for this function."""
8716 return self.init_args
8718 def GetOriginalArgs(self):
8719 """Gets the original arguments to this function."""
8720 return self.original_args
8722 def GetLastOriginalArg(self):
8723 """Gets the last original argument to this function."""
8724 return self.original_args[len(self.original_args) - 1]
8726 def GetLastOriginalPointerArg(self):
8727 return self.last_original_pointer_arg
8729 def GetResourceIdArg(self):
8730 for arg in self.original_args:
8731 if hasattr(arg, 'resource_type'):
8732 return arg
8733 return None
8735 def _MaybePrependComma(self, arg_string, add_comma):
8736 """Adds a comma if arg_string is not empty and add_comma is true."""
8737 comma = ""
8738 if add_comma and len(arg_string):
8739 comma = ", "
8740 return "%s%s" % (comma, arg_string)
8742 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
8743 """Gets a list of arguments as they are in GL."""
8744 args = self.GetOriginalArgs()
8745 arg_string = ", ".join(
8746 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8747 return self._MaybePrependComma(arg_string, add_comma)
8749 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
8750 """Gets the list of arguments as they are in GL."""
8751 args = self.GetOriginalArgs()
8752 arg_string = separator.join(
8753 ["%s%s" % (prefix, arg.name) for arg in args])
8754 return self._MaybePrependComma(arg_string, add_comma)
8756 def MakeTypedHelperArgString(self, prefix, add_comma = False):
8757 """Gets a list of typed GL arguments after removing unneeded arguments."""
8758 args = self.GetOriginalArgs()
8759 arg_string = ", ".join(
8760 ["%s %s%s" % (
8761 arg.type,
8762 prefix,
8763 arg.name,
8764 ) for arg in args if not arg.IsConstant()])
8765 return self._MaybePrependComma(arg_string, add_comma)
8767 def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
8768 """Gets a list of GL arguments after removing unneeded arguments."""
8769 args = self.GetOriginalArgs()
8770 arg_string = separator.join(
8771 ["%s%s" % (prefix, arg.name)
8772 for arg in args if not arg.IsConstant()])
8773 return self._MaybePrependComma(arg_string, add_comma)
8775 def MakeTypedPepperArgString(self, prefix):
8776 """Gets a list of arguments as they need to be for Pepper."""
8777 if self.GetInfo("pepper_args"):
8778 return self.GetInfo("pepper_args")
8779 else:
8780 return self.MakeTypedOriginalArgString(prefix, False)
8782 def MapCTypeToPepperIdlType(self, ctype, is_for_return_type=False):
8783 """Converts a C type name to the corresponding Pepper IDL type."""
8784 idltype = {
8785 'char*': '[out] str_t',
8786 'const GLchar* const*': '[out] cstr_t',
8787 'const char*': 'cstr_t',
8788 'const void*': 'mem_t',
8789 'void*': '[out] mem_t',
8790 'void**': '[out] mem_ptr_t',
8791 }.get(ctype, ctype)
8792 # We use "GLxxx_ptr_t" for "GLxxx*".
8793 matched = re.match(r'(const )?(GL\w+)\*$', ctype)
8794 if matched:
8795 idltype = matched.group(2) + '_ptr_t'
8796 if not matched.group(1):
8797 idltype = '[out] ' + idltype
8798 # If an in/out specifier is not specified yet, prepend [in].
8799 if idltype[0] != '[':
8800 idltype = '[in] ' + idltype
8801 # Strip the in/out specifier for a return type.
8802 if is_for_return_type:
8803 idltype = re.sub(r'\[\w+\] ', '', idltype)
8804 return idltype
8806 def MakeTypedPepperIdlArgStrings(self):
8807 """Gets a list of arguments as they need to be for Pepper IDL."""
8808 args = self.GetOriginalArgs()
8809 return ["%s %s" % (self.MapCTypeToPepperIdlType(arg.type), arg.name)
8810 for arg in args]
8812 def GetPepperName(self):
8813 if self.GetInfo("pepper_name"):
8814 return self.GetInfo("pepper_name")
8815 return self.name
8817 def MakeTypedCmdArgString(self, prefix, add_comma = False):
8818 """Gets a typed list of arguments as they need to be for command buffers."""
8819 args = self.GetCmdArgs()
8820 arg_string = ", ".join(
8821 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8822 return self._MaybePrependComma(arg_string, add_comma)
8824 def MakeCmdArgString(self, prefix, add_comma = False):
8825 """Gets the list of arguments as they need to be for command buffers."""
8826 args = self.GetCmdArgs()
8827 arg_string = ", ".join(
8828 ["%s%s" % (prefix, arg.name) for arg in args])
8829 return self._MaybePrependComma(arg_string, add_comma)
8831 def MakeTypedInitString(self, prefix, add_comma = False):
8832 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
8833 args = self.GetInitArgs()
8834 arg_string = ", ".join(
8835 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8836 return self._MaybePrependComma(arg_string, add_comma)
8838 def MakeInitString(self, prefix, add_comma = False):
8839 """Gets the list of arguments as they need to be for cmd Init/Set."""
8840 args = self.GetInitArgs()
8841 arg_string = ", ".join(
8842 ["%s%s" % (prefix, arg.name) for arg in args])
8843 return self._MaybePrependComma(arg_string, add_comma)
8845 def MakeLogArgString(self):
8846 """Makes a string of the arguments for the LOG macros"""
8847 args = self.GetOriginalArgs()
8848 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
8850 def WriteCommandDescription(self, file):
8851 """Writes a description of the command."""
8852 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
8854 def WriteHandlerValidation(self, file):
8855 """Writes validation code for the function."""
8856 for arg in self.GetOriginalArgs():
8857 arg.WriteValidationCode(file, self)
8858 self.WriteValidationCode(file)
8860 def WriteHandlerImplementation(self, file):
8861 """Writes the handler implementation for this command."""
8862 self.type_handler.WriteHandlerImplementation(self, file)
8864 def WriteValidationCode(self, file):
8865 """Writes the validation code for a command."""
8866 pass
8868 def WriteCmdFlag(self, file):
8869 """Writes the cmd cmd_flags constant."""
8870 flags = []
8871 # By default trace only at the highest level 3.
8872 trace_level = int(self.GetInfo('trace_level', default = 3))
8873 if trace_level not in xrange(0, 4):
8874 raise KeyError("Unhandled trace_level: %d" % trace_level)
8876 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
8878 if len(flags) > 0:
8879 cmd_flags = ' | '.join(flags)
8880 else:
8881 cmd_flags = 0
8883 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
8886 def WriteCmdArgFlag(self, file):
8887 """Writes the cmd kArgFlags constant."""
8888 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
8890 def WriteCmdComputeSize(self, file):
8891 """Writes the ComputeSize function for the command."""
8892 file.Write(" static uint32_t ComputeSize() {\n")
8893 file.Write(
8894 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
8895 file.Write(" }\n")
8896 file.Write("\n")
8898 def WriteCmdSetHeader(self, file):
8899 """Writes the cmd's SetHeader function."""
8900 file.Write(" void SetHeader() {\n")
8901 file.Write(" header.SetCmd<ValueType>();\n")
8902 file.Write(" }\n")
8903 file.Write("\n")
8905 def WriteCmdInit(self, file):
8906 """Writes the cmd's Init function."""
8907 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
8908 file.Write(" SetHeader();\n")
8909 args = self.GetCmdArgs()
8910 for arg in args:
8911 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
8912 file.Write(" }\n")
8913 file.Write("\n")
8915 def WriteCmdSet(self, file):
8916 """Writes the cmd's Set function."""
8917 copy_args = self.MakeCmdArgString("_", False)
8918 file.Write(" void* Set(void* cmd%s) {\n" %
8919 self.MakeTypedCmdArgString("_", True))
8920 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
8921 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
8922 file.Write(" }\n")
8923 file.Write("\n")
8925 def WriteStruct(self, file):
8926 self.type_handler.WriteStruct(self, file)
8928 def WriteDocs(self, file):
8929 self.type_handler.WriteDocs(self, file)
8931 def WriteCmdHelper(self, file):
8932 """Writes the cmd's helper."""
8933 self.type_handler.WriteCmdHelper(self, file)
8935 def WriteServiceImplementation(self, file):
8936 """Writes the service implementation for a command."""
8937 self.type_handler.WriteServiceImplementation(self, file)
8939 def WriteServiceUnitTest(self, file, *extras):
8940 """Writes the service implementation for a command."""
8941 self.type_handler.WriteServiceUnitTest(self, file, *extras)
8943 def WriteGLES2CLibImplementation(self, file):
8944 """Writes the GLES2 C Lib Implemention."""
8945 self.type_handler.WriteGLES2CLibImplementation(self, file)
8947 def WriteGLES2InterfaceHeader(self, file):
8948 """Writes the GLES2 Interface declaration."""
8949 self.type_handler.WriteGLES2InterfaceHeader(self, file)
8951 def WriteMojoGLES2ImplHeader(self, file):
8952 """Writes the Mojo GLES2 implementation header declaration."""
8953 self.type_handler.WriteMojoGLES2ImplHeader(self, file)
8955 def WriteMojoGLES2Impl(self, file):
8956 """Writes the Mojo GLES2 implementation declaration."""
8957 self.type_handler.WriteMojoGLES2Impl(self, file)
8959 def WriteGLES2InterfaceStub(self, file):
8960 """Writes the GLES2 Interface Stub declaration."""
8961 self.type_handler.WriteGLES2InterfaceStub(self, file)
8963 def WriteGLES2InterfaceStubImpl(self, file):
8964 """Writes the GLES2 Interface Stub declaration."""
8965 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
8967 def WriteGLES2ImplementationHeader(self, file):
8968 """Writes the GLES2 Implemention declaration."""
8969 self.type_handler.WriteGLES2ImplementationHeader(self, file)
8971 def WriteGLES2Implementation(self, file):
8972 """Writes the GLES2 Implemention definition."""
8973 self.type_handler.WriteGLES2Implementation(self, file)
8975 def WriteGLES2TraceImplementationHeader(self, file):
8976 """Writes the GLES2 Trace Implemention declaration."""
8977 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
8979 def WriteGLES2TraceImplementation(self, file):
8980 """Writes the GLES2 Trace Implemention definition."""
8981 self.type_handler.WriteGLES2TraceImplementation(self, file)
8983 def WriteGLES2Header(self, file):
8984 """Writes the GLES2 Implemention unit test."""
8985 self.type_handler.WriteGLES2Header(self, file)
8987 def WriteGLES2ImplementationUnitTest(self, file):
8988 """Writes the GLES2 Implemention unit test."""
8989 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
8991 def WriteDestinationInitalizationValidation(self, file):
8992 """Writes the client side destintion initialization validation."""
8993 self.type_handler.WriteDestinationInitalizationValidation(self, file)
8995 def WriteFormatTest(self, file):
8996 """Writes the cmd's format test."""
8997 self.type_handler.WriteFormatTest(self, file)
9000 class PepperInterface(object):
9001 """A class that represents a function."""
9003 def __init__(self, info):
9004 self.name = info["name"]
9005 self.dev = info["dev"]
9007 def GetName(self):
9008 return self.name
9010 def GetInterfaceName(self):
9011 upperint = ""
9012 dev = ""
9013 if self.name:
9014 upperint = "_" + self.name.upper()
9015 if self.dev:
9016 dev = "_DEV"
9017 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
9019 def GetInterfaceString(self):
9020 dev = ""
9021 if self.dev:
9022 dev = "(Dev)"
9023 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9025 def GetStructName(self):
9026 dev = ""
9027 if self.dev:
9028 dev = "_Dev"
9029 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9032 class ImmediateFunction(Function):
9033 """A class that represnets an immediate function command."""
9035 def __init__(self, func):
9036 Function.__init__(
9037 self,
9038 "%sImmediate" % func.name,
9039 func.info)
9041 def InitFunction(self):
9042 # Override args in original_args and args_for_cmds with immediate versions
9043 # of the args.
9045 new_original_args = []
9046 for arg in self.original_args:
9047 new_arg = arg.GetImmediateVersion()
9048 if new_arg:
9049 new_original_args.append(new_arg)
9050 self.original_args = new_original_args
9052 new_args_for_cmds = []
9053 for arg in self.args_for_cmds:
9054 new_arg = arg.GetImmediateVersion()
9055 if new_arg:
9056 new_args_for_cmds.append(new_arg)
9058 self.args_for_cmds = new_args_for_cmds
9060 Function.InitFunction(self)
9062 def IsImmediate(self):
9063 return True
9065 def WriteCommandDescription(self, file):
9066 """Overridden from Function"""
9067 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
9068 self.original_name)
9070 def WriteServiceImplementation(self, file):
9071 """Overridden from Function"""
9072 self.type_handler.WriteImmediateServiceImplementation(self, file)
9074 def WriteHandlerImplementation(self, file):
9075 """Overridden from Function"""
9076 self.type_handler.WriteImmediateHandlerImplementation(self, file)
9078 def WriteServiceUnitTest(self, file, *extras):
9079 """Writes the service implementation for a command."""
9080 self.type_handler.WriteImmediateServiceUnitTest(self, file, *extras)
9082 def WriteValidationCode(self, file):
9083 """Overridden from Function"""
9084 self.type_handler.WriteImmediateValidationCode(self, file)
9086 def WriteCmdArgFlag(self, file):
9087 """Overridden from Function"""
9088 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9090 def WriteCmdComputeSize(self, file):
9091 """Overridden from Function"""
9092 self.type_handler.WriteImmediateCmdComputeSize(self, file)
9094 def WriteCmdSetHeader(self, file):
9095 """Overridden from Function"""
9096 self.type_handler.WriteImmediateCmdSetHeader(self, file)
9098 def WriteCmdInit(self, file):
9099 """Overridden from Function"""
9100 self.type_handler.WriteImmediateCmdInit(self, file)
9102 def WriteCmdSet(self, file):
9103 """Overridden from Function"""
9104 self.type_handler.WriteImmediateCmdSet(self, file)
9106 def WriteCmdHelper(self, file):
9107 """Overridden from Function"""
9108 self.type_handler.WriteImmediateCmdHelper(self, file)
9110 def WriteFormatTest(self, file):
9111 """Overridden from Function"""
9112 self.type_handler.WriteImmediateFormatTest(self, file)
9115 class BucketFunction(Function):
9116 """A class that represnets a bucket version of a function command."""
9118 def __init__(self, func):
9119 Function.__init__(
9120 self,
9121 "%sBucket" % func.name,
9122 func.info)
9124 def InitFunction(self):
9125 # Override args in original_args and args_for_cmds with bucket versions
9126 # of the args.
9128 new_original_args = []
9129 for arg in self.original_args:
9130 new_arg = arg.GetBucketVersion()
9131 if new_arg:
9132 new_original_args.append(new_arg)
9133 self.original_args = new_original_args
9135 new_args_for_cmds = []
9136 for arg in self.args_for_cmds:
9137 new_arg = arg.GetBucketVersion()
9138 if new_arg:
9139 new_args_for_cmds.append(new_arg)
9141 self.args_for_cmds = new_args_for_cmds
9143 Function.InitFunction(self)
9145 def WriteCommandDescription(self, file):
9146 """Overridden from Function"""
9147 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
9148 self.original_name)
9150 def WriteServiceImplementation(self, file):
9151 """Overridden from Function"""
9152 self.type_handler.WriteBucketServiceImplementation(self, file)
9154 def WriteHandlerImplementation(self, file):
9155 """Overridden from Function"""
9156 self.type_handler.WriteBucketHandlerImplementation(self, file)
9158 def WriteServiceUnitTest(self, file, *extras):
9159 """Overridden from Function"""
9160 self.type_handler.WriteBucketServiceUnitTest(self, file, *extras)
9162 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9163 """Overridden from Function"""
9164 args = self.GetOriginalArgs()
9165 arg_string = separator.join(
9166 ["%s%s" % (prefix, arg.name[0:-10] if arg.name.endswith("_bucket_id")
9167 else arg.name) for arg in args])
9168 return super(BucketFunction, self)._MaybePrependComma(arg_string, add_comma)
9171 def CreateArg(arg_string):
9172 """Creates an Argument."""
9173 arg_parts = arg_string.split()
9174 if len(arg_parts) == 1 and arg_parts[0] == 'void':
9175 return None
9176 # Is this a pointer argument?
9177 elif arg_string.find('*') >= 0:
9178 return PointerArgument(
9179 arg_parts[-1],
9180 " ".join(arg_parts[0:-1]))
9181 # Is this a resource argument? Must come after pointer check.
9182 elif arg_parts[0].startswith('GLidBind'):
9183 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9184 elif arg_parts[0].startswith('GLidZero'):
9185 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9186 elif arg_parts[0].startswith('GLid'):
9187 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9188 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
9189 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9190 elif arg_parts[0].startswith('GLbitfield') and len(arg_parts[0]) > 10:
9191 return BitFieldArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9192 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
9193 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9194 elif arg_parts[0].startswith('GLboolean'):
9195 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9196 elif arg_parts[0].startswith('GLintUniformLocation'):
9197 return UniformLocationArgument(arg_parts[-1])
9198 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
9199 not arg_parts[0].startswith('GLintptr')):
9200 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9201 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
9202 arg_parts[0].startswith('GLintptrNotNegative')):
9203 return SizeNotNegativeArgument(arg_parts[-1],
9204 " ".join(arg_parts[0:-1]),
9205 arg_parts[0][0:-11])
9206 elif arg_parts[0].startswith('GLsize'):
9207 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9208 else:
9209 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9212 class GLGenerator(object):
9213 """A class to generate GL command buffers."""
9215 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9217 def __init__(self, verbose):
9218 self.original_functions = []
9219 self.functions = []
9220 self.verbose = verbose
9221 self.errors = 0
9222 self.pepper_interfaces = []
9223 self.interface_info = {}
9224 self.generated_cpp_filenames = []
9226 for interface in _PEPPER_INTERFACES:
9227 interface = PepperInterface(interface)
9228 self.pepper_interfaces.append(interface)
9229 self.interface_info[interface.GetName()] = interface
9231 def AddFunction(self, func):
9232 """Adds a function."""
9233 self.functions.append(func)
9235 def GetFunctionInfo(self, name):
9236 """Gets a type info for the given function name."""
9237 if name in _FUNCTION_INFO:
9238 func_info = _FUNCTION_INFO[name].copy()
9239 else:
9240 func_info = {}
9242 if not 'type' in func_info:
9243 func_info['type'] = ''
9245 return func_info
9247 def Log(self, msg):
9248 """Prints something if verbose is true."""
9249 if self.verbose:
9250 print msg
9252 def Error(self, msg):
9253 """Prints an error."""
9254 print "Error: %s" % msg
9255 self.errors += 1
9257 def WriteLicense(self, file):
9258 """Writes the license."""
9259 file.Write(_LICENSE)
9261 def WriteNamespaceOpen(self, file):
9262 """Writes the code for the namespace."""
9263 file.Write("namespace gpu {\n")
9264 file.Write("namespace gles2 {\n")
9265 file.Write("\n")
9267 def WriteNamespaceClose(self, file):
9268 """Writes the code to close the namespace."""
9269 file.Write("} // namespace gles2\n")
9270 file.Write("} // namespace gpu\n")
9271 file.Write("\n")
9273 def ParseGLH(self, filename):
9274 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9275 f = open(filename, "r")
9276 functions = f.read()
9277 f.close()
9278 for line in functions.splitlines():
9279 match = self._function_re.match(line)
9280 if match:
9281 func_name = match.group(2)[2:]
9282 func_info = self.GetFunctionInfo(func_name)
9283 if func_info['type'] == 'Noop':
9284 continue
9286 parsed_func_info = {
9287 'original_name': func_name,
9288 'original_args': match.group(3),
9289 'return_type': match.group(1).strip(),
9292 for k in parsed_func_info.keys():
9293 if not k in func_info:
9294 func_info[k] = parsed_func_info[k]
9296 f = Function(func_name, func_info)
9297 self.original_functions.append(f)
9299 #for arg in f.GetOriginalArgs():
9300 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9301 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9303 gen_cmd = f.GetInfo('gen_cmd')
9304 if gen_cmd == True or gen_cmd == None:
9305 if f.type_handler.NeedsDataTransferFunction(f):
9306 methods = f.GetDataTransferMethods()
9307 if 'immediate' in methods:
9308 self.AddFunction(ImmediateFunction(f))
9309 if 'bucket' in methods:
9310 self.AddFunction(BucketFunction(f))
9311 if 'shm' in methods:
9312 self.AddFunction(f)
9313 else:
9314 self.AddFunction(f)
9316 self.Log("Auto Generated Functions : %d" %
9317 len([f for f in self.functions if f.can_auto_generate or
9318 (not f.IsType('') and not f.IsType('Custom') and
9319 not f.IsType('Todo'))]))
9321 funcs = [f for f in self.functions if not f.can_auto_generate and
9322 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
9323 self.Log("Non Auto Generated Functions: %d" % len(funcs))
9325 for f in funcs:
9326 self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
9328 def WriteCommandIds(self, filename):
9329 """Writes the command buffer format"""
9330 file = CHeaderWriter(filename)
9331 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
9332 id = 256
9333 for func in self.functions:
9334 file.Write(" %-60s /* %d */ \\\n" %
9335 ("OP(%s)" % func.name, id))
9336 id += 1
9337 file.Write("\n")
9339 file.Write("enum CommandId {\n")
9340 file.Write(" kStartPoint = cmd::kLastCommonId, "
9341 "// All GLES2 commands start after this.\n")
9342 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
9343 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9344 file.Write("#undef GLES2_CMD_OP\n")
9345 file.Write(" kNumCommands\n")
9346 file.Write("};\n")
9347 file.Write("\n")
9348 file.Close()
9349 self.generated_cpp_filenames.append(file.filename)
9351 def WriteFormat(self, filename):
9352 """Writes the command buffer format"""
9353 file = CHeaderWriter(filename)
9354 # Forward declaration of a few enums used in constant argument
9355 # to avoid including GL header files.
9356 enum_defines = {
9357 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9358 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9360 file.Write('\n')
9361 for enum in enum_defines:
9362 file.Write("#define %s %s\n" % (enum, enum_defines[enum]))
9363 file.Write('\n')
9364 for func in self.functions:
9365 if True:
9366 #gen_cmd = func.GetInfo('gen_cmd')
9367 #if gen_cmd == True or gen_cmd == None:
9368 func.WriteStruct(file)
9369 file.Write("\n")
9370 file.Close()
9371 self.generated_cpp_filenames.append(file.filename)
9373 def WriteDocs(self, filename):
9374 """Writes the command buffer doc version of the commands"""
9375 file = CWriter(filename)
9376 for func in self.functions:
9377 if True:
9378 #gen_cmd = func.GetInfo('gen_cmd')
9379 #if gen_cmd == True or gen_cmd == None:
9380 func.WriteDocs(file)
9381 file.Write("\n")
9382 file.Close()
9383 self.generated_cpp_filenames.append(file.filename)
9385 def WriteFormatTest(self, filename):
9386 """Writes the command buffer format test."""
9387 file = CHeaderWriter(
9388 filename,
9389 "// This file contains unit tests for gles2 commmands\n"
9390 "// It is included by gles2_cmd_format_test.cc\n"
9391 "\n")
9393 for func in self.functions:
9394 if True:
9395 #gen_cmd = func.GetInfo('gen_cmd')
9396 #if gen_cmd == True or gen_cmd == None:
9397 func.WriteFormatTest(file)
9399 file.Close()
9400 self.generated_cpp_filenames.append(file.filename)
9402 def WriteCmdHelperHeader(self, filename):
9403 """Writes the gles2 command helper."""
9404 file = CHeaderWriter(filename)
9406 for func in self.functions:
9407 if True:
9408 #gen_cmd = func.GetInfo('gen_cmd')
9409 #if gen_cmd == True or gen_cmd == None:
9410 func.WriteCmdHelper(file)
9412 file.Close()
9413 self.generated_cpp_filenames.append(file.filename)
9415 def WriteServiceContextStateHeader(self, filename):
9416 """Writes the service context state header."""
9417 file = CHeaderWriter(
9418 filename,
9419 "// It is included by context_state.h\n")
9420 file.Write("struct EnableFlags {\n")
9421 file.Write(" EnableFlags();\n")
9422 for capability in _CAPABILITY_FLAGS:
9423 file.Write(" bool %s;\n" % capability['name'])
9424 file.Write(" bool cached_%s;\n" % capability['name'])
9425 file.Write("};\n\n")
9427 for state_name in sorted(_STATES.keys()):
9428 state = _STATES[state_name]
9429 for item in state['states']:
9430 if isinstance(item['default'], list):
9431 file.Write("%s %s[%d];\n" % (item['type'], item['name'],
9432 len(item['default'])))
9433 else:
9434 file.Write("%s %s;\n" % (item['type'], item['name']))
9436 if item.get('cached', False):
9437 if isinstance(item['default'], list):
9438 file.Write("%s cached_%s[%d];\n" % (item['type'], item['name'],
9439 len(item['default'])))
9440 else:
9441 file.Write("%s cached_%s;\n" % (item['type'], item['name']))
9443 file.Write("\n")
9445 file.Write("""
9446 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9447 switch (cap) {
9448 """)
9449 for capability in _CAPABILITY_FLAGS:
9450 file.Write("""\
9451 case GL_%s:
9452 """ % capability['name'].upper())
9453 file.Write("""\
9454 if (enable_flags.cached_%(name)s == enable &&
9455 !ignore_cached_state)
9456 return;
9457 enable_flags.cached_%(name)s = enable;
9458 break;
9459 """ % capability)
9461 file.Write("""\
9462 default:
9463 NOTREACHED();
9464 return;
9466 if (enable)
9467 glEnable(cap);
9468 else
9469 glDisable(cap);
9471 """)
9473 file.Close()
9474 self.generated_cpp_filenames.append(file.filename)
9476 def WriteClientContextStateHeader(self, filename):
9477 """Writes the client context state header."""
9478 file = CHeaderWriter(
9479 filename,
9480 "// It is included by client_context_state.h\n")
9481 file.Write("struct EnableFlags {\n")
9482 file.Write(" EnableFlags();\n")
9483 for capability in _CAPABILITY_FLAGS:
9484 file.Write(" bool %s;\n" % capability['name'])
9485 file.Write("};\n\n")
9487 file.Close()
9488 self.generated_cpp_filenames.append(file.filename)
9490 def WriteContextStateGetters(self, file, class_name):
9491 """Writes the state getters."""
9492 for gl_type in ["GLint", "GLfloat"]:
9493 file.Write("""
9494 bool %s::GetStateAs%s(
9495 GLenum pname, %s* params, GLsizei* num_written) const {
9496 switch (pname) {
9497 """ % (class_name, gl_type, gl_type))
9498 for state_name in sorted(_STATES.keys()):
9499 state = _STATES[state_name]
9500 if 'enum' in state:
9501 file.Write(" case %s:\n" % state['enum'])
9502 file.Write(" *num_written = %d;\n" % len(state['states']))
9503 file.Write(" if (params) {\n")
9504 for ndx,item in enumerate(state['states']):
9505 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
9506 (ndx, gl_type, item['name']))
9507 file.Write(" }\n")
9508 file.Write(" return true;\n")
9509 else:
9510 for item in state['states']:
9511 file.Write(" case %s:\n" % item['enum'])
9512 if isinstance(item['default'], list):
9513 item_len = len(item['default'])
9514 file.Write(" *num_written = %d;\n" % item_len)
9515 file.Write(" if (params) {\n")
9516 if item['type'] == gl_type:
9517 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9518 (item['name'], item['type'], item_len))
9519 else:
9520 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
9521 item_len)
9522 file.Write(" params[i] = %s;\n" %
9523 (GetGLGetTypeConversion(gl_type, item['type'],
9524 "%s[i]" % item['name'])))
9525 file.Write(" }\n");
9526 else:
9527 file.Write(" *num_written = 1;\n")
9528 file.Write(" if (params) {\n")
9529 file.Write(" params[0] = %s;\n" %
9530 (GetGLGetTypeConversion(gl_type, item['type'],
9531 item['name'])))
9532 file.Write(" }\n")
9533 file.Write(" return true;\n")
9534 for capability in _CAPABILITY_FLAGS:
9535 file.Write(" case GL_%s:\n" % capability['name'].upper())
9536 file.Write(" *num_written = 1;\n")
9537 file.Write(" if (params) {\n")
9538 file.Write(
9539 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9540 (gl_type, capability['name']))
9541 file.Write(" }\n")
9542 file.Write(" return true;\n")
9543 file.Write(""" default:
9544 return false;
9547 """)
9549 def WriteServiceContextStateImpl(self, filename):
9550 """Writes the context state service implementation."""
9551 file = CHeaderWriter(
9552 filename,
9553 "// It is included by context_state.cc\n")
9554 code = []
9555 for capability in _CAPABILITY_FLAGS:
9556 code.append("%s(%s)" %
9557 (capability['name'],
9558 ('false', 'true')['default' in capability]))
9559 code.append("cached_%s(%s)" %
9560 (capability['name'],
9561 ('false', 'true')['default' in capability]))
9562 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9563 ",\n ".join(code))
9564 file.Write("\n")
9566 file.Write("void ContextState::Initialize() {\n")
9567 for state_name in sorted(_STATES.keys()):
9568 state = _STATES[state_name]
9569 for item in state['states']:
9570 if isinstance(item['default'], list):
9571 for ndx, value in enumerate(item['default']):
9572 file.Write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
9573 else:
9574 file.Write(" %s = %s;\n" % (item['name'], item['default']))
9575 if item.get('cached', False):
9576 if isinstance(item['default'], list):
9577 for ndx, value in enumerate(item['default']):
9578 file.Write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
9579 else:
9580 file.Write(" cached_%s = %s;\n" % (item['name'], item['default']))
9581 file.Write("}\n")
9583 file.Write("""
9584 void ContextState::InitCapabilities(const ContextState* prev_state) const {
9585 """)
9586 def WriteCapabilities(test_prev, es3_caps):
9587 for capability in _CAPABILITY_FLAGS:
9588 capability_name = capability['name']
9589 capability_es3 = 'es3' in capability and capability['es3'] == True
9590 if capability_es3 and not es3_caps or not capability_es3 and es3_caps:
9591 continue
9592 if test_prev:
9593 file.Write(""" if (prev_state->enable_flags.cached_%s !=
9594 enable_flags.cached_%s) {\n""" %
9595 (capability_name, capability_name))
9596 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
9597 (capability_name.upper(), capability_name))
9598 if test_prev:
9599 file.Write(" }")
9601 file.Write(" if (prev_state) {")
9602 WriteCapabilities(True, False)
9603 file.Write(" if (feature_info_->IsES3Capable()) {\n")
9604 WriteCapabilities(True, True)
9605 file.Write(" }\n")
9606 file.Write(" } else {")
9607 WriteCapabilities(False, False)
9608 file.Write(" if (feature_info_->IsES3Capable()) {\n")
9609 WriteCapabilities(False, True)
9610 file.Write(" }\n")
9611 file.Write(" }")
9613 file.Write("""}
9615 void ContextState::InitState(const ContextState *prev_state) const {
9616 """)
9618 def WriteStates(test_prev):
9619 # We need to sort the keys so the expectations match
9620 for state_name in sorted(_STATES.keys()):
9621 state = _STATES[state_name]
9622 if state['type'] == 'FrontBack':
9623 num_states = len(state['states'])
9624 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
9625 if test_prev:
9626 file.Write(" if (")
9627 args = []
9628 for place, item in enumerate(group):
9629 item_name = CachedStateName(item)
9630 args.append('%s' % item_name)
9631 if test_prev:
9632 if place > 0:
9633 file.Write(' ||\n')
9634 file.Write("(%s != prev_state->%s)" % (item_name, item_name))
9635 if test_prev:
9636 file.Write(")\n")
9637 file.Write(
9638 " gl%s(%s, %s);\n" %
9639 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
9640 elif state['type'] == 'NamedParameter':
9641 for item in state['states']:
9642 item_name = CachedStateName(item)
9644 if 'extension_flag' in item:
9645 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
9646 item['extension_flag'])
9647 if test_prev:
9648 if isinstance(item['default'], list):
9649 file.Write(" if (memcmp(prev_state->%s, %s, "
9650 "sizeof(%s) * %d)) {\n" %
9651 (item_name, item_name, item['type'],
9652 len(item['default'])))
9653 else:
9654 file.Write(" if (prev_state->%s != %s) {\n " %
9655 (item_name, item_name))
9656 if 'gl_version_flag' in item:
9657 item_name = item['gl_version_flag']
9658 inverted = ''
9659 if item_name[0] == '!':
9660 inverted = '!'
9661 item_name = item_name[1:]
9662 file.Write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
9663 (inverted, item_name))
9664 file.Write(" gl%s(%s, %s);\n" %
9665 (state['func'],
9666 (item['enum_set']
9667 if 'enum_set' in item else item['enum']),
9668 item['name']))
9669 if 'gl_version_flag' in item:
9670 file.Write(" }\n")
9671 if test_prev:
9672 if 'extension_flag' in item:
9673 file.Write(" ")
9674 file.Write(" }")
9675 if 'extension_flag' in item:
9676 file.Write(" }")
9677 else:
9678 if 'extension_flag' in state:
9679 file.Write(" if (feature_info_->feature_flags().%s)\n " %
9680 state['extension_flag'])
9681 if test_prev:
9682 file.Write(" if (")
9683 args = []
9684 for place, item in enumerate(state['states']):
9685 item_name = CachedStateName(item)
9686 args.append('%s' % item_name)
9687 if test_prev:
9688 if place > 0:
9689 file.Write(' ||\n')
9690 file.Write("(%s != prev_state->%s)" %
9691 (item_name, item_name))
9692 if test_prev:
9693 file.Write(" )\n")
9694 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
9696 file.Write(" if (prev_state) {")
9697 WriteStates(True)
9698 file.Write(" } else {")
9699 WriteStates(False)
9700 file.Write(" }")
9701 file.Write("}\n")
9703 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
9704 switch (cap) {
9705 """)
9706 for capability in _CAPABILITY_FLAGS:
9707 file.Write(" case GL_%s:\n" % capability['name'].upper())
9708 file.Write(" return enable_flags.%s;\n" % capability['name'])
9709 file.Write(""" default:
9710 NOTREACHED();
9711 return false;
9714 """)
9716 self.WriteContextStateGetters(file, "ContextState")
9717 file.Close()
9718 self.generated_cpp_filenames.append(file.filename)
9720 def WriteClientContextStateImpl(self, filename):
9721 """Writes the context state client side implementation."""
9722 file = CHeaderWriter(
9723 filename,
9724 "// It is included by client_context_state.cc\n")
9725 code = []
9726 for capability in _CAPABILITY_FLAGS:
9727 code.append("%s(%s)" %
9728 (capability['name'],
9729 ('false', 'true')['default' in capability]))
9730 file.Write(
9731 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9732 ",\n ".join(code))
9733 file.Write("\n")
9735 file.Write("""
9736 bool ClientContextState::SetCapabilityState(
9737 GLenum cap, bool enabled, bool* changed) {
9738 *changed = false;
9739 switch (cap) {
9740 """)
9741 for capability in _CAPABILITY_FLAGS:
9742 file.Write(" case GL_%s:\n" % capability['name'].upper())
9743 file.Write(""" if (enable_flags.%(name)s != enabled) {
9744 *changed = true;
9745 enable_flags.%(name)s = enabled;
9747 return true;
9748 """ % capability)
9749 file.Write(""" default:
9750 return false;
9753 """)
9754 file.Write("""bool ClientContextState::GetEnabled(
9755 GLenum cap, bool* enabled) const {
9756 switch (cap) {
9757 """)
9758 for capability in _CAPABILITY_FLAGS:
9759 file.Write(" case GL_%s:\n" % capability['name'].upper())
9760 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
9761 file.Write(" return true;\n")
9762 file.Write(""" default:
9763 return false;
9766 """)
9767 file.Close()
9768 self.generated_cpp_filenames.append(file.filename)
9770 def WriteServiceImplementation(self, filename):
9771 """Writes the service decorder implementation."""
9772 file = CHeaderWriter(
9773 filename,
9774 "// It is included by gles2_cmd_decoder.cc\n")
9776 for func in self.functions:
9777 if True:
9778 #gen_cmd = func.GetInfo('gen_cmd')
9779 #if gen_cmd == True or gen_cmd == None:
9780 func.WriteServiceImplementation(file)
9782 file.Write("""
9783 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
9784 switch (cap) {
9785 """)
9786 for capability in _CAPABILITY_FLAGS:
9787 file.Write(" case GL_%s:\n" % capability['name'].upper())
9788 if 'state_flag' in capability:
9790 file.Write("""\
9791 state_.enable_flags.%(name)s = enabled;
9792 if (state_.enable_flags.cached_%(name)s != enabled
9793 || state_.ignore_cached_state) {
9794 %(state_flag)s = true;
9796 return false;
9797 """ % capability)
9798 else:
9799 file.Write("""\
9800 state_.enable_flags.%(name)s = enabled;
9801 if (state_.enable_flags.cached_%(name)s != enabled
9802 || state_.ignore_cached_state) {
9803 state_.enable_flags.cached_%(name)s = enabled;
9804 return true;
9806 return false;
9807 """ % capability)
9808 file.Write(""" default:
9809 NOTREACHED();
9810 return false;
9813 """)
9814 file.Close()
9815 self.generated_cpp_filenames.append(file.filename)
9817 def WriteServiceUnitTests(self, filename):
9818 """Writes the service decorder unit tests."""
9819 num_tests = len(self.functions)
9820 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
9821 count = 0
9822 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
9823 count += 1
9824 name = filename % count
9825 file = CHeaderWriter(
9826 name,
9827 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
9828 test_name = 'GLES2DecoderTest%d' % count
9829 end = test_num + FUNCTIONS_PER_FILE
9830 if end > num_tests:
9831 end = num_tests
9832 for idx in range(test_num, end):
9833 func = self.functions[idx]
9835 # Do any filtering of the functions here, so that the functions
9836 # will not move between the numbered files if filtering properties
9837 # are changed.
9838 if func.GetInfo('extension_flag'):
9839 continue
9841 if True:
9842 #gen_cmd = func.GetInfo('gen_cmd')
9843 #if gen_cmd == True or gen_cmd == None:
9844 if func.GetInfo('unit_test') == False:
9845 file.Write("// TODO(gman): %s\n" % func.name)
9846 else:
9847 func.WriteServiceUnitTest(file, {
9848 'test_name': test_name
9850 file.Close()
9851 self.generated_cpp_filenames.append(file.filename)
9852 file = CHeaderWriter(
9853 filename % 0,
9854 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
9855 file.Write(
9856 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
9857 bool es3_capable) {""")
9858 for capability in _CAPABILITY_FLAGS:
9859 capability_es3 = 'es3' in capability and capability['es3'] == True
9860 if not capability_es3:
9861 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
9862 (capability['name'].upper(),
9863 ('false', 'true')['default' in capability]))
9865 file.Write(" if (es3_capable) {")
9866 for capability in _CAPABILITY_FLAGS:
9867 capability_es3 = 'es3' in capability and capability['es3'] == True
9868 if capability_es3:
9869 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
9870 (capability['name'].upper(),
9871 ('false', 'true')['default' in capability]))
9872 file.Write(""" }
9875 void GLES2DecoderTestBase::SetupInitStateExpectations() {
9876 """)
9878 # We need to sort the keys so the expectations match
9879 for state_name in sorted(_STATES.keys()):
9880 state = _STATES[state_name]
9881 if state['type'] == 'FrontBack':
9882 num_states = len(state['states'])
9883 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
9884 args = []
9885 for item in group:
9886 if 'expected' in item:
9887 args.append(item['expected'])
9888 else:
9889 args.append(item['default'])
9890 file.Write(
9891 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
9892 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
9893 file.Write(" .Times(1)\n")
9894 file.Write(" .RetiresOnSaturation();\n")
9895 elif state['type'] == 'NamedParameter':
9896 for item in state['states']:
9897 if 'extension_flag' in item:
9898 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
9899 item['extension_flag'])
9900 file.Write(" ")
9901 expect_value = item['default']
9902 if isinstance(expect_value, list):
9903 # TODO: Currently we do not check array values.
9904 expect_value = "_"
9906 file.Write(
9907 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
9908 (state['func'],
9909 (item['enum_set']
9910 if 'enum_set' in item else item['enum']),
9911 expect_value))
9912 file.Write(" .Times(1)\n")
9913 file.Write(" .RetiresOnSaturation();\n")
9914 if 'extension_flag' in item:
9915 file.Write(" }\n")
9916 else:
9917 if 'extension_flag' in state:
9918 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
9919 state['extension_flag'])
9920 file.Write(" ")
9921 args = []
9922 for item in state['states']:
9923 if 'expected' in item:
9924 args.append(item['expected'])
9925 else:
9926 args.append(item['default'])
9927 # TODO: Currently we do not check array values.
9928 args = ["_" if isinstance(arg, list) else arg for arg in args]
9929 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
9930 (state['func'], ", ".join(args)))
9931 file.Write(" .Times(1)\n")
9932 file.Write(" .RetiresOnSaturation();\n")
9933 if 'extension_flag' in state:
9934 file.Write(" }\n")
9935 file.Write("""}
9936 """)
9937 file.Close()
9938 self.generated_cpp_filenames.append(file.filename)
9940 def WriteServiceUnitTestsForExtensions(self, filename):
9941 """Writes the service decorder unit tests for functions with extension_flag.
9943 The functions are special in that they need a specific unit test
9944 baseclass to turn on the extension.
9946 functions = [f for f in self.functions if f.GetInfo('extension_flag')]
9947 file = CHeaderWriter(
9948 filename,
9949 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
9950 for func in functions:
9951 if True:
9952 if func.GetInfo('unit_test') == False:
9953 file.Write("// TODO(gman): %s\n" % func.name)
9954 else:
9955 extension = ToCamelCase(
9956 ToGLExtensionString(func.GetInfo('extension_flag')))
9957 func.WriteServiceUnitTest(file, {
9958 'test_name': 'GLES2DecoderTestWith%s' % extension
9961 file.Close()
9962 self.generated_cpp_filenames.append(file.filename)
9964 def WriteGLES2Header(self, filename):
9965 """Writes the GLES2 header."""
9966 file = CHeaderWriter(
9967 filename,
9968 "// This file contains Chromium-specific GLES2 declarations.\n\n")
9970 for func in self.original_functions:
9971 func.WriteGLES2Header(file)
9973 file.Write("\n")
9974 file.Close()
9975 self.generated_cpp_filenames.append(file.filename)
9977 def WriteGLES2CLibImplementation(self, filename):
9978 """Writes the GLES2 c lib implementation."""
9979 file = CHeaderWriter(
9980 filename,
9981 "// These functions emulate GLES2 over command buffers.\n")
9983 for func in self.original_functions:
9984 func.WriteGLES2CLibImplementation(file)
9986 file.Write("""
9987 namespace gles2 {
9989 extern const NameToFunc g_gles2_function_table[] = {
9990 """)
9991 for func in self.original_functions:
9992 file.Write(
9993 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
9994 (func.name, func.name))
9995 file.Write(""" { NULL, NULL, },
9998 } // namespace gles2
9999 """)
10000 file.Close()
10001 self.generated_cpp_filenames.append(file.filename)
10003 def WriteGLES2InterfaceHeader(self, filename):
10004 """Writes the GLES2 interface header."""
10005 file = CHeaderWriter(
10006 filename,
10007 "// This file is included by gles2_interface.h to declare the\n"
10008 "// GL api functions.\n")
10009 for func in self.original_functions:
10010 func.WriteGLES2InterfaceHeader(file)
10011 file.Close()
10012 self.generated_cpp_filenames.append(file.filename)
10014 def WriteMojoGLES2ImplHeader(self, filename):
10015 """Writes the Mojo GLES2 implementation header."""
10016 file = CHeaderWriter(
10017 filename,
10018 "// This file is included by gles2_interface.h to declare the\n"
10019 "// GL api functions.\n")
10021 code = """
10022 #include "gpu/command_buffer/client/gles2_interface.h"
10023 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10025 namespace mojo {
10027 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10028 public:
10029 explicit MojoGLES2Impl(MojoGLES2Context context) {
10030 context_ = context;
10032 ~MojoGLES2Impl() override {}
10034 file.Write(code);
10035 for func in self.original_functions:
10036 func.WriteMojoGLES2ImplHeader(file)
10037 code = """
10038 private:
10039 MojoGLES2Context context_;
10042 } // namespace mojo
10044 file.Write(code);
10045 file.Close()
10046 self.generated_cpp_filenames.append(file.filename)
10048 def WriteMojoGLES2Impl(self, filename):
10049 """Writes the Mojo GLES2 implementation."""
10050 file = CWriter(filename)
10051 file.Write(_LICENSE)
10052 file.Write(_DO_NOT_EDIT_WARNING)
10054 code = """
10055 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10057 #include "base/logging.h"
10058 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10059 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10060 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10061 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10062 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10063 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10065 namespace mojo {
10068 file.Write(code);
10069 for func in self.original_functions:
10070 func.WriteMojoGLES2Impl(file)
10071 code = """
10073 } // namespace mojo
10075 file.Write(code);
10076 file.Close()
10077 self.generated_cpp_filenames.append(file.filename)
10079 def WriteGLES2InterfaceStub(self, filename):
10080 """Writes the GLES2 interface stub header."""
10081 file = CHeaderWriter(
10082 filename,
10083 "// This file is included by gles2_interface_stub.h.\n")
10084 for func in self.original_functions:
10085 func.WriteGLES2InterfaceStub(file)
10086 file.Close()
10087 self.generated_cpp_filenames.append(file.filename)
10089 def WriteGLES2InterfaceStubImpl(self, filename):
10090 """Writes the GLES2 interface header."""
10091 file = CHeaderWriter(
10092 filename,
10093 "// This file is included by gles2_interface_stub.cc.\n")
10094 for func in self.original_functions:
10095 func.WriteGLES2InterfaceStubImpl(file)
10096 file.Close()
10097 self.generated_cpp_filenames.append(file.filename)
10099 def WriteGLES2ImplementationHeader(self, filename):
10100 """Writes the GLES2 Implementation header."""
10101 file = CHeaderWriter(
10102 filename,
10103 "// This file is included by gles2_implementation.h to declare the\n"
10104 "// GL api functions.\n")
10105 for func in self.original_functions:
10106 func.WriteGLES2ImplementationHeader(file)
10107 file.Close()
10108 self.generated_cpp_filenames.append(file.filename)
10110 def WriteGLES2Implementation(self, filename):
10111 """Writes the GLES2 Implementation."""
10112 file = CHeaderWriter(
10113 filename,
10114 "// This file is included by gles2_implementation.cc to define the\n"
10115 "// GL api functions.\n")
10116 for func in self.original_functions:
10117 func.WriteGLES2Implementation(file)
10118 file.Close()
10119 self.generated_cpp_filenames.append(file.filename)
10121 def WriteGLES2TraceImplementationHeader(self, filename):
10122 """Writes the GLES2 Trace Implementation header."""
10123 file = CHeaderWriter(
10124 filename,
10125 "// This file is included by gles2_trace_implementation.h\n")
10126 for func in self.original_functions:
10127 func.WriteGLES2TraceImplementationHeader(file)
10128 file.Close()
10129 self.generated_cpp_filenames.append(file.filename)
10131 def WriteGLES2TraceImplementation(self, filename):
10132 """Writes the GLES2 Trace Implementation."""
10133 file = CHeaderWriter(
10134 filename,
10135 "// This file is included by gles2_trace_implementation.cc\n")
10136 for func in self.original_functions:
10137 func.WriteGLES2TraceImplementation(file)
10138 file.Close()
10139 self.generated_cpp_filenames.append(file.filename)
10141 def WriteGLES2ImplementationUnitTests(self, filename):
10142 """Writes the GLES2 helper header."""
10143 file = CHeaderWriter(
10144 filename,
10145 "// This file is included by gles2_implementation.h to declare the\n"
10146 "// GL api functions.\n")
10147 for func in self.original_functions:
10148 func.WriteGLES2ImplementationUnitTest(file)
10149 file.Close()
10150 self.generated_cpp_filenames.append(file.filename)
10152 def WriteServiceUtilsHeader(self, filename):
10153 """Writes the gles2 auto generated utility header."""
10154 file = CHeaderWriter(filename)
10155 for name in sorted(_NAMED_TYPE_INFO.keys()):
10156 named_type = NamedType(_NAMED_TYPE_INFO[name])
10157 if named_type.IsConstant():
10158 continue
10159 file.Write("ValueValidator<%s> %s;\n" %
10160 (named_type.GetType(), ToUnderscore(name)))
10161 file.Write("\n")
10162 file.Close()
10163 self.generated_cpp_filenames.append(file.filename)
10165 def WriteServiceUtilsImplementation(self, filename):
10166 """Writes the gles2 auto generated utility implementation."""
10167 file = CHeaderWriter(filename)
10168 names = sorted(_NAMED_TYPE_INFO.keys())
10169 for name in names:
10170 named_type = NamedType(_NAMED_TYPE_INFO[name])
10171 if named_type.IsConstant():
10172 continue
10173 if named_type.GetValidValues():
10174 file.Write("static const %s valid_%s_table[] = {\n" %
10175 (named_type.GetType(), ToUnderscore(name)))
10176 for value in named_type.GetValidValues():
10177 file.Write(" %s,\n" % value)
10178 file.Write("};\n")
10179 file.Write("\n")
10180 if named_type.GetValidValuesES3():
10181 file.Write("static const %s valid_%s_table_es3[] = {\n" %
10182 (named_type.GetType(), ToUnderscore(name)))
10183 for value in named_type.GetValidValuesES3():
10184 file.Write(" %s,\n" % value)
10185 file.Write("};\n")
10186 file.Write("\n")
10187 if named_type.GetDeprecatedValuesES3():
10188 file.Write("static const %s deprecated_%s_table_es3[] = {\n" %
10189 (named_type.GetType(), ToUnderscore(name)))
10190 for value in named_type.GetDeprecatedValuesES3():
10191 file.Write(" %s,\n" % value)
10192 file.Write("};\n")
10193 file.Write("\n")
10194 file.Write("Validators::Validators()")
10195 pre = ' : '
10196 for count, name in enumerate(names):
10197 named_type = NamedType(_NAMED_TYPE_INFO[name])
10198 if named_type.IsConstant():
10199 continue
10200 if named_type.GetValidValues():
10201 code = """%(pre)s%(name)s(
10202 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10203 else:
10204 code = "%(pre)s%(name)s()"
10205 file.Write(code % {
10206 'name': ToUnderscore(name),
10207 'pre': pre,
10209 pre = ',\n '
10210 file.Write(" {\n");
10211 file.Write("}\n\n");
10213 file.Write("void Validators::UpdateValuesES3() {\n")
10214 for name in names:
10215 named_type = NamedType(_NAMED_TYPE_INFO[name])
10216 if named_type.GetDeprecatedValuesES3():
10217 code = """ %(name)s.RemoveValues(
10218 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10220 file.Write(code % {
10221 'name': ToUnderscore(name),
10223 if named_type.GetValidValuesES3():
10224 code = """ %(name)s.AddValues(
10225 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10227 file.Write(code % {
10228 'name': ToUnderscore(name),
10230 file.Write("}\n\n");
10231 file.Close()
10232 self.generated_cpp_filenames.append(file.filename)
10234 def WriteCommonUtilsHeader(self, filename):
10235 """Writes the gles2 common utility header."""
10236 file = CHeaderWriter(filename)
10237 type_infos = sorted(_NAMED_TYPE_INFO.keys())
10238 for type_info in type_infos:
10239 if _NAMED_TYPE_INFO[type_info]['type'] == 'GLenum':
10240 file.Write("static std::string GetString%s(uint32_t value);\n" %
10241 type_info)
10242 file.Write("\n")
10243 file.Close()
10244 self.generated_cpp_filenames.append(file.filename)
10246 def WriteCommonUtilsImpl(self, filename):
10247 """Writes the gles2 common utility header."""
10248 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10249 dict = {}
10250 for fname in ['third_party/khronos/GLES2/gl2.h',
10251 'third_party/khronos/GLES2/gl2ext.h',
10252 'third_party/khronos/GLES3/gl3.h',
10253 'gpu/GLES2/gl2chromium.h',
10254 'gpu/GLES2/gl2extchromium.h']:
10255 lines = open(fname).readlines()
10256 for line in lines:
10257 m = enum_re.match(line)
10258 if m:
10259 name = m.group(1)
10260 value = m.group(2)
10261 if len(value) <= 10:
10262 if not value in dict:
10263 dict[value] = name
10264 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10265 elif dict[value] != name and (name.endswith('_CHROMIUM') or
10266 dict[value].endswith('_CHROMIUM')):
10267 self.Error("code collision: %s and %s have the same code %s" %
10268 (dict[value], name, value))
10270 file = CHeaderWriter(filename)
10271 file.Write("static const GLES2Util::EnumToString "
10272 "enum_to_string_table[] = {\n")
10273 for value in dict:
10274 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
10275 file.Write("""};
10277 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10278 enum_to_string_table;
10279 const size_t GLES2Util::enum_to_string_table_len_ =
10280 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10282 """)
10284 enums = sorted(_NAMED_TYPE_INFO.keys())
10285 for enum in enums:
10286 if _NAMED_TYPE_INFO[enum]['type'] == 'GLenum':
10287 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10288 enum)
10289 valid_list = _NAMED_TYPE_INFO[enum]['valid']
10290 if 'valid_es3' in _NAMED_TYPE_INFO[enum]:
10291 valid_list = valid_list + _NAMED_TYPE_INFO[enum]['valid_es3']
10292 assert len(valid_list) == len(set(valid_list))
10293 if len(valid_list) > 0:
10294 file.Write(" static const EnumToString string_table[] = {\n")
10295 for value in valid_list:
10296 file.Write(' { %s, "%s" },\n' % (value, value))
10297 file.Write(""" };
10298 return GLES2Util::GetQualifiedEnumString(
10299 string_table, arraysize(string_table), value);
10302 """)
10303 else:
10304 file.Write(""" return GLES2Util::GetQualifiedEnumString(
10305 NULL, 0, value);
10308 """)
10309 file.Close()
10310 self.generated_cpp_filenames.append(file.filename)
10312 def WritePepperGLES2Interface(self, filename, dev):
10313 """Writes the Pepper OpenGLES interface definition."""
10314 file = CWriter(filename)
10315 file.Write(_LICENSE)
10316 file.Write(_DO_NOT_EDIT_WARNING)
10318 file.Write("label Chrome {\n")
10319 file.Write(" M39 = 1.0\n")
10320 file.Write("};\n\n")
10322 if not dev:
10323 # Declare GL types.
10324 file.Write("[version=1.0]\n")
10325 file.Write("describe {\n")
10326 for gltype in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10327 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10328 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10329 'GLubyte', 'GLuint', 'GLushort']:
10330 file.Write(" %s;\n" % gltype)
10331 file.Write(" %s_ptr_t;\n" % gltype)
10332 file.Write("};\n\n")
10334 # C level typedefs.
10335 file.Write("#inline c\n")
10336 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
10337 if dev:
10338 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10339 else:
10340 file.Write("\n#ifndef __gl2_h_\n")
10341 for (k, v) in _GL_TYPES.iteritems():
10342 file.Write("typedef %s %s;\n" % (v, k))
10343 file.Write("#ifdef _WIN64\n")
10344 for (k, v) in _GL_TYPES_64.iteritems():
10345 file.Write("typedef %s %s;\n" % (v, k))
10346 file.Write("#else\n")
10347 for (k, v) in _GL_TYPES_32.iteritems():
10348 file.Write("typedef %s %s;\n" % (v, k))
10349 file.Write("#endif // _WIN64\n")
10350 file.Write("#endif // __gl2_h_\n\n")
10351 file.Write("#endinl\n")
10353 for interface in self.pepper_interfaces:
10354 if interface.dev != dev:
10355 continue
10356 # Historically, we provide OpenGLES2 interfaces with struct
10357 # namespace. Not to break code which uses the interface as
10358 # "struct OpenGLES2", we put it in struct namespace.
10359 file.Write('\n[macro="%s", force_struct_namespace]\n' %
10360 interface.GetInterfaceName())
10361 file.Write("interface %s {\n" % interface.GetStructName())
10362 for func in self.original_functions:
10363 if not func.InPepperInterface(interface):
10364 continue
10366 ret_type = func.MapCTypeToPepperIdlType(func.return_type,
10367 is_for_return_type=True)
10368 func_prefix = " %s %s(" % (ret_type, func.GetPepperName())
10369 file.Write(func_prefix)
10370 file.Write("[in] PP_Resource context")
10371 for arg in func.MakeTypedPepperIdlArgStrings():
10372 file.Write(",\n" + " " * len(func_prefix) + arg)
10373 file.Write(");\n")
10374 file.Write("};\n\n")
10377 file.Close()
10379 def WritePepperGLES2Implementation(self, filename):
10380 """Writes the Pepper OpenGLES interface implementation."""
10382 file = CWriter(filename)
10383 file.Write(_LICENSE)
10384 file.Write(_DO_NOT_EDIT_WARNING)
10386 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10387 file.Write("#include \"base/logging.h\"\n")
10388 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10389 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10390 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
10392 file.Write("namespace ppapi {\n\n")
10393 file.Write("namespace {\n\n")
10395 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10396 " Enter3D;\n\n")
10398 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10399 " enter) {\n")
10400 file.Write(" DCHECK(enter);\n")
10401 file.Write(" DCHECK(enter->succeeded());\n")
10402 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10403 "gles2_impl();\n");
10404 file.Write("}\n\n");
10406 for func in self.original_functions:
10407 if not func.InAnyPepperExtension():
10408 continue
10410 original_arg = func.MakeTypedPepperArgString("")
10411 context_arg = "PP_Resource context_id"
10412 if len(original_arg):
10413 arg = context_arg + ", " + original_arg
10414 else:
10415 arg = context_arg
10416 file.Write("%s %s(%s) {\n" %
10417 (func.return_type, func.GetPepperName(), arg))
10418 file.Write(" Enter3D enter(context_id, true);\n")
10419 file.Write(" if (enter.succeeded()) {\n")
10421 return_str = "" if func.return_type == "void" else "return "
10422 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10423 (return_str, func.original_name,
10424 func.MakeOriginalArgString("")))
10425 file.Write(" }")
10426 if func.return_type == "void":
10427 file.Write("\n")
10428 else:
10429 file.Write(" else {\n")
10430 file.Write(" return %s;\n" % func.GetErrorReturnString())
10431 file.Write(" }\n")
10432 file.Write("}\n\n")
10434 file.Write("} // namespace\n")
10436 for interface in self.pepper_interfaces:
10437 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10438 (interface.GetStructName(), interface.GetName()))
10439 file.Write(" static const struct %s "
10440 "ppb_opengles2 = {\n" % interface.GetStructName())
10441 file.Write(" &")
10442 file.Write(",\n &".join(
10443 f.GetPepperName() for f in self.original_functions
10444 if f.InPepperInterface(interface)))
10445 file.Write("\n")
10447 file.Write(" };\n")
10448 file.Write(" return &ppb_opengles2;\n")
10449 file.Write("}\n")
10451 file.Write("} // namespace ppapi\n")
10452 file.Close()
10453 self.generated_cpp_filenames.append(file.filename)
10455 def WriteGLES2ToPPAPIBridge(self, filename):
10456 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10458 file = CWriter(filename)
10459 file.Write(_LICENSE)
10460 file.Write(_DO_NOT_EDIT_WARNING)
10462 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
10463 file.Write("#define GL_GLEXT_PROTOTYPES\n")
10464 file.Write("#endif\n")
10465 file.Write("#include <GLES2/gl2.h>\n")
10466 file.Write("#include <GLES2/gl2ext.h>\n")
10467 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10469 for func in self.original_functions:
10470 if not func.InAnyPepperExtension():
10471 continue
10473 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
10475 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
10476 (func.return_type, func.GetPepperName(),
10477 func.MakeTypedPepperArgString("")))
10478 return_str = "" if func.return_type == "void" else "return "
10479 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
10480 original_arg = func.MakeOriginalArgString("")
10481 context_arg = "glGetCurrentContextPPAPI()"
10482 if len(original_arg):
10483 arg = context_arg + ", " + original_arg
10484 else:
10485 arg = context_arg
10486 if interface.GetName():
10487 file.Write(" const struct %s* ext = %s;\n" %
10488 (interface.GetStructName(), interface_str))
10489 file.Write(" if (ext)\n")
10490 file.Write(" %sext->%s(%s);\n" %
10491 (return_str, func.GetPepperName(), arg))
10492 if return_str:
10493 file.Write(" %s0;\n" % return_str)
10494 else:
10495 file.Write(" %s%s->%s(%s);\n" %
10496 (return_str, interface_str, func.GetPepperName(), arg))
10497 file.Write("}\n\n")
10498 file.Close()
10499 self.generated_cpp_filenames.append(file.filename)
10501 def WriteMojoGLCallVisitor(self, filename):
10502 """Provides the GL implementation for mojo"""
10503 file = CWriter(filename)
10504 file.Write(_LICENSE)
10505 file.Write(_DO_NOT_EDIT_WARNING)
10507 for func in self.original_functions:
10508 if not func.IsCoreGLFunction():
10509 continue
10510 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10511 (func.name, func.return_type,
10512 func.MakeTypedOriginalArgString(""),
10513 func.MakeOriginalArgString("")))
10515 file.Close()
10516 self.generated_cpp_filenames.append(file.filename)
10518 def WriteMojoGLCallVisitorForExtension(self, filename, extension):
10519 """Provides the GL implementation for mojo for a particular extension"""
10520 file = CWriter(filename)
10521 file.Write(_LICENSE)
10522 file.Write(_DO_NOT_EDIT_WARNING)
10524 for func in self.original_functions:
10525 if func.GetInfo("extension") != extension:
10526 continue
10527 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10528 (func.name, func.return_type,
10529 func.MakeTypedOriginalArgString(""),
10530 func.MakeOriginalArgString("")))
10532 file.Close()
10533 self.generated_cpp_filenames.append(file.filename)
10535 def Format(generated_files):
10536 formatter = "clang-format"
10537 if platform.system() == "Windows":
10538 formatter += ".bat"
10539 for filename in generated_files:
10540 call([formatter, "-i", "-style=chromium", filename])
10542 def main(argv):
10543 """This is the main function."""
10544 parser = OptionParser()
10545 parser.add_option(
10546 "--output-dir",
10547 help="base directory for resulting files, under chrome/src. default is "
10548 "empty. Use this if you want the result stored under gen.")
10549 parser.add_option(
10550 "-v", "--verbose", action="store_true",
10551 help="prints more output.")
10553 (options, args) = parser.parse_args(args=argv)
10555 # Add in states and capabilites to GLState
10556 gl_state_valid = _NAMED_TYPE_INFO['GLState']['valid']
10557 for state_name in sorted(_STATES.keys()):
10558 state = _STATES[state_name]
10559 if 'extension_flag' in state:
10560 continue
10561 if 'enum' in state:
10562 if not state['enum'] in gl_state_valid:
10563 gl_state_valid.append(state['enum'])
10564 else:
10565 for item in state['states']:
10566 if 'extension_flag' in item:
10567 continue
10568 if not item['enum'] in gl_state_valid:
10569 gl_state_valid.append(item['enum'])
10570 for capability in _CAPABILITY_FLAGS:
10571 valid_value = "GL_%s" % capability['name'].upper()
10572 if not valid_value in gl_state_valid:
10573 gl_state_valid.append(valid_value)
10575 # This script lives under gpu/command_buffer, cd to base directory.
10576 os.chdir(os.path.dirname(__file__) + "/../..")
10577 base_dir = os.getcwd()
10578 gen = GLGenerator(options.verbose)
10579 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10581 # Support generating files under gen/
10582 if options.output_dir != None:
10583 os.chdir(options.output_dir)
10585 gen.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10586 gen.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10587 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10588 gen.WritePepperGLES2Implementation(
10589 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10590 os.chdir(base_dir)
10591 gen.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10592 gen.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10593 gen.WriteFormatTest(
10594 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10595 gen.WriteGLES2InterfaceHeader(
10596 "gpu/command_buffer/client/gles2_interface_autogen.h")
10597 gen.WriteMojoGLES2ImplHeader(
10598 "mojo/gpu/mojo_gles2_impl_autogen.h")
10599 gen.WriteMojoGLES2Impl(
10600 "mojo/gpu/mojo_gles2_impl_autogen.cc")
10601 gen.WriteGLES2InterfaceStub(
10602 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10603 gen.WriteGLES2InterfaceStubImpl(
10604 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10605 gen.WriteGLES2ImplementationHeader(
10606 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10607 gen.WriteGLES2Implementation(
10608 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10609 gen.WriteGLES2ImplementationUnitTests(
10610 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10611 gen.WriteGLES2TraceImplementationHeader(
10612 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10613 gen.WriteGLES2TraceImplementation(
10614 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10615 gen.WriteGLES2CLibImplementation(
10616 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10617 gen.WriteCmdHelperHeader(
10618 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
10619 gen.WriteServiceImplementation(
10620 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
10621 gen.WriteServiceContextStateHeader(
10622 "gpu/command_buffer/service/context_state_autogen.h")
10623 gen.WriteServiceContextStateImpl(
10624 "gpu/command_buffer/service/context_state_impl_autogen.h")
10625 gen.WriteClientContextStateHeader(
10626 "gpu/command_buffer/client/client_context_state_autogen.h")
10627 gen.WriteClientContextStateImpl(
10628 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
10629 gen.WriteServiceUnitTests(
10630 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
10631 gen.WriteServiceUnitTestsForExtensions(
10632 "gpu/command_buffer/service/"
10633 "gles2_cmd_decoder_unittest_extensions_autogen.h")
10634 gen.WriteServiceUtilsHeader(
10635 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
10636 gen.WriteServiceUtilsImplementation(
10637 "gpu/command_buffer/service/"
10638 "gles2_cmd_validation_implementation_autogen.h")
10639 gen.WriteCommonUtilsHeader(
10640 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
10641 gen.WriteCommonUtilsImpl(
10642 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
10643 gen.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
10644 mojo_gles2_prefix = ("third_party/mojo/src/mojo/public/c/gles2/"
10645 "gles2_call_visitor")
10646 gen.WriteMojoGLCallVisitor(mojo_gles2_prefix + "_autogen.h")
10647 gen.WriteMojoGLCallVisitorForExtension(
10648 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
10649 "CHROMIUM_texture_mailbox")
10650 gen.WriteMojoGLCallVisitorForExtension(
10651 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
10652 "CHROMIUM_sync_point")
10653 gen.WriteMojoGLCallVisitorForExtension(
10654 mojo_gles2_prefix + "_chromium_sub_image_autogen.h",
10655 "CHROMIUM_sub_image")
10656 gen.WriteMojoGLCallVisitorForExtension(
10657 mojo_gles2_prefix + "_chromium_miscellaneous_autogen.h",
10658 "CHROMIUM_miscellaneous")
10659 gen.WriteMojoGLCallVisitorForExtension(
10660 mojo_gles2_prefix + "_occlusion_query_ext_autogen.h",
10661 "occlusion_query_EXT")
10663 Format(gen.generated_cpp_filenames)
10665 if gen.errors > 0:
10666 print "%d errors" % gen.errors
10667 return 1
10668 return 0
10671 if __name__ == '__main__':
10672 sys.exit(main(sys.argv[1:]))