Upstreaming browser/ui/uikit_ui_util from iOS.
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blobe48d38b0569cf11bca4026c52ef4510708f3af79
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},
86 {'name': 'primitive_restart_fixed_index', 'es3': True},
89 _STATES = {
90 'ClearColor': {
91 'type': 'Normal',
92 'func': 'ClearColor',
93 'enum': 'GL_COLOR_CLEAR_VALUE',
94 'states': [
95 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
97 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
98 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
101 'ClearDepthf': {
102 'type': 'Normal',
103 'func': 'ClearDepth',
104 'enum': 'GL_DEPTH_CLEAR_VALUE',
105 'states': [
106 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
109 'ColorMask': {
110 'type': 'Normal',
111 'func': 'ColorMask',
112 'enum': 'GL_COLOR_WRITEMASK',
113 'states': [
115 'name': 'color_mask_red',
116 'type': 'GLboolean',
117 'default': 'true',
118 'cached': True
121 'name': 'color_mask_green',
122 'type': 'GLboolean',
123 'default': 'true',
124 'cached': True
127 'name': 'color_mask_blue',
128 'type': 'GLboolean',
129 'default': 'true',
130 'cached': True
133 'name': 'color_mask_alpha',
134 'type': 'GLboolean',
135 'default': 'true',
136 'cached': True
139 'state_flag': 'framebuffer_state_.clear_state_dirty',
141 'ClearStencil': {
142 'type': 'Normal',
143 'func': 'ClearStencil',
144 'enum': 'GL_STENCIL_CLEAR_VALUE',
145 'states': [
146 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
149 'BlendColor': {
150 'type': 'Normal',
151 'func': 'BlendColor',
152 'enum': 'GL_BLEND_COLOR',
153 'states': [
154 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
155 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
156 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
157 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
160 'BlendEquation': {
161 'type': 'SrcDst',
162 'func': 'BlendEquationSeparate',
163 'states': [
165 'name': 'blend_equation_rgb',
166 'type': 'GLenum',
167 'enum': 'GL_BLEND_EQUATION_RGB',
168 'default': 'GL_FUNC_ADD',
171 'name': 'blend_equation_alpha',
172 'type': 'GLenum',
173 'enum': 'GL_BLEND_EQUATION_ALPHA',
174 'default': 'GL_FUNC_ADD',
178 'BlendFunc': {
179 'type': 'SrcDst',
180 'func': 'BlendFuncSeparate',
181 'states': [
183 'name': 'blend_source_rgb',
184 'type': 'GLenum',
185 'enum': 'GL_BLEND_SRC_RGB',
186 'default': 'GL_ONE',
189 'name': 'blend_dest_rgb',
190 'type': 'GLenum',
191 'enum': 'GL_BLEND_DST_RGB',
192 'default': 'GL_ZERO',
195 'name': 'blend_source_alpha',
196 'type': 'GLenum',
197 'enum': 'GL_BLEND_SRC_ALPHA',
198 'default': 'GL_ONE',
201 'name': 'blend_dest_alpha',
202 'type': 'GLenum',
203 'enum': 'GL_BLEND_DST_ALPHA',
204 'default': 'GL_ZERO',
208 'PolygonOffset': {
209 'type': 'Normal',
210 'func': 'PolygonOffset',
211 'states': [
213 'name': 'polygon_offset_factor',
214 'type': 'GLfloat',
215 'enum': 'GL_POLYGON_OFFSET_FACTOR',
216 'default': '0.0f',
219 'name': 'polygon_offset_units',
220 'type': 'GLfloat',
221 'enum': 'GL_POLYGON_OFFSET_UNITS',
222 'default': '0.0f',
226 'CullFace': {
227 'type': 'Normal',
228 'func': 'CullFace',
229 'enum': 'GL_CULL_FACE_MODE',
230 'states': [
232 'name': 'cull_mode',
233 'type': 'GLenum',
234 'default': 'GL_BACK',
238 'FrontFace': {
239 'type': 'Normal',
240 'func': 'FrontFace',
241 'enum': 'GL_FRONT_FACE',
242 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
244 'DepthFunc': {
245 'type': 'Normal',
246 'func': 'DepthFunc',
247 'enum': 'GL_DEPTH_FUNC',
248 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
250 'DepthRange': {
251 'type': 'Normal',
252 'func': 'DepthRange',
253 'enum': 'GL_DEPTH_RANGE',
254 'states': [
255 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
256 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
259 'SampleCoverage': {
260 'type': 'Normal',
261 'func': 'SampleCoverage',
262 'states': [
264 'name': 'sample_coverage_value',
265 'type': 'GLclampf',
266 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
267 'default': '1.0f',
270 'name': 'sample_coverage_invert',
271 'type': 'GLboolean',
272 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
273 'default': 'false',
277 'StencilMask': {
278 'type': 'FrontBack',
279 'func': 'StencilMaskSeparate',
280 'state_flag': 'framebuffer_state_.clear_state_dirty',
281 'states': [
283 'name': 'stencil_front_writemask',
284 'type': 'GLuint',
285 'enum': 'GL_STENCIL_WRITEMASK',
286 'default': '0xFFFFFFFFU',
287 'cached': True,
290 'name': 'stencil_back_writemask',
291 'type': 'GLuint',
292 'enum': 'GL_STENCIL_BACK_WRITEMASK',
293 'default': '0xFFFFFFFFU',
294 'cached': True,
298 'StencilOp': {
299 'type': 'FrontBack',
300 'func': 'StencilOpSeparate',
301 'states': [
303 'name': 'stencil_front_fail_op',
304 'type': 'GLenum',
305 'enum': 'GL_STENCIL_FAIL',
306 'default': 'GL_KEEP',
309 'name': 'stencil_front_z_fail_op',
310 'type': 'GLenum',
311 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
312 'default': 'GL_KEEP',
315 'name': 'stencil_front_z_pass_op',
316 'type': 'GLenum',
317 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
318 'default': 'GL_KEEP',
321 'name': 'stencil_back_fail_op',
322 'type': 'GLenum',
323 'enum': 'GL_STENCIL_BACK_FAIL',
324 'default': 'GL_KEEP',
327 'name': 'stencil_back_z_fail_op',
328 'type': 'GLenum',
329 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
330 'default': 'GL_KEEP',
333 'name': 'stencil_back_z_pass_op',
334 'type': 'GLenum',
335 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
336 'default': 'GL_KEEP',
340 'StencilFunc': {
341 'type': 'FrontBack',
342 'func': 'StencilFuncSeparate',
343 'states': [
345 'name': 'stencil_front_func',
346 'type': 'GLenum',
347 'enum': 'GL_STENCIL_FUNC',
348 'default': 'GL_ALWAYS',
351 'name': 'stencil_front_ref',
352 'type': 'GLint',
353 'enum': 'GL_STENCIL_REF',
354 'default': '0',
357 'name': 'stencil_front_mask',
358 'type': 'GLuint',
359 'enum': 'GL_STENCIL_VALUE_MASK',
360 'default': '0xFFFFFFFFU',
363 'name': 'stencil_back_func',
364 'type': 'GLenum',
365 'enum': 'GL_STENCIL_BACK_FUNC',
366 'default': 'GL_ALWAYS',
369 'name': 'stencil_back_ref',
370 'type': 'GLint',
371 'enum': 'GL_STENCIL_BACK_REF',
372 'default': '0',
375 'name': 'stencil_back_mask',
376 'type': 'GLuint',
377 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
378 'default': '0xFFFFFFFFU',
382 'Hint': {
383 'type': 'NamedParameter',
384 'func': 'Hint',
385 'states': [
387 'name': 'hint_generate_mipmap',
388 'type': 'GLenum',
389 'enum': 'GL_GENERATE_MIPMAP_HINT',
390 'default': 'GL_DONT_CARE',
391 'gl_version_flag': '!is_desktop_core_profile'
394 'name': 'hint_fragment_shader_derivative',
395 'type': 'GLenum',
396 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
397 'default': 'GL_DONT_CARE',
398 'extension_flag': 'oes_standard_derivatives'
402 'PixelStore': {
403 'type': 'NamedParameter',
404 'func': 'PixelStorei',
405 'states': [
407 'name': 'pack_alignment',
408 'type': 'GLint',
409 'enum': 'GL_PACK_ALIGNMENT',
410 'default': '4'
413 'name': 'unpack_alignment',
414 'type': 'GLint',
415 'enum': 'GL_UNPACK_ALIGNMENT',
416 'default': '4'
420 # TODO: Consider implemenenting these states
421 # GL_ACTIVE_TEXTURE
422 'LineWidth': {
423 'type': 'Normal',
424 'func': 'LineWidth',
425 'enum': 'GL_LINE_WIDTH',
426 'states': [
428 'name': 'line_width',
429 'type': 'GLfloat',
430 'default': '1.0f',
431 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
432 'nan_check': True,
435 'DepthMask': {
436 'type': 'Normal',
437 'func': 'DepthMask',
438 'enum': 'GL_DEPTH_WRITEMASK',
439 'states': [
441 'name': 'depth_mask',
442 'type': 'GLboolean',
443 'default': 'true',
444 'cached': True
447 'state_flag': 'framebuffer_state_.clear_state_dirty',
449 'Scissor': {
450 'type': 'Normal',
451 'func': 'Scissor',
452 'enum': 'GL_SCISSOR_BOX',
453 'states': [
454 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
456 'name': 'scissor_x',
457 'type': 'GLint',
458 'default': '0',
459 'expected': 'kViewportX',
462 'name': 'scissor_y',
463 'type': 'GLint',
464 'default': '0',
465 'expected': 'kViewportY',
468 'name': 'scissor_width',
469 'type': 'GLsizei',
470 'default': '1',
471 'expected': 'kViewportWidth',
474 'name': 'scissor_height',
475 'type': 'GLsizei',
476 'default': '1',
477 'expected': 'kViewportHeight',
481 'Viewport': {
482 'type': 'Normal',
483 'func': 'Viewport',
484 'enum': 'GL_VIEWPORT',
485 'states': [
486 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
488 'name': 'viewport_x',
489 'type': 'GLint',
490 'default': '0',
491 'expected': 'kViewportX',
494 'name': 'viewport_y',
495 'type': 'GLint',
496 'default': '0',
497 'expected': 'kViewportY',
500 'name': 'viewport_width',
501 'type': 'GLsizei',
502 'default': '1',
503 'expected': 'kViewportWidth',
506 'name': 'viewport_height',
507 'type': 'GLsizei',
508 'default': '1',
509 'expected': 'kViewportHeight',
513 'MatrixValuesCHROMIUM': {
514 'type': 'NamedParameter',
515 'func': 'MatrixLoadfEXT',
516 'states': [
517 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
518 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
519 'name': 'modelview_matrix',
520 'type': 'GLfloat',
521 'default': [
522 '1.0f', '0.0f','0.0f','0.0f',
523 '0.0f', '1.0f','0.0f','0.0f',
524 '0.0f', '0.0f','1.0f','0.0f',
525 '0.0f', '0.0f','0.0f','1.0f',
527 'extension_flag': 'chromium_path_rendering',
529 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
530 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
531 'name': 'projection_matrix',
532 'type': 'GLfloat',
533 'default': [
534 '1.0f', '0.0f','0.0f','0.0f',
535 '0.0f', '1.0f','0.0f','0.0f',
536 '0.0f', '0.0f','1.0f','0.0f',
537 '0.0f', '0.0f','0.0f','1.0f',
539 'extension_flag': 'chromium_path_rendering',
543 'PathStencilFuncCHROMIUM': {
544 'type': 'Normal',
545 'func': 'PathStencilFuncNV',
546 'extension_flag': 'chromium_path_rendering',
547 'states': [
549 'name': 'stencil_path_func',
550 'type': 'GLenum',
551 'enum': 'GL_PATH_STENCIL_FUNC_CHROMIUM',
552 'default': 'GL_ALWAYS',
555 'name': 'stencil_path_ref',
556 'type': 'GLint',
557 'enum': 'GL_PATH_STENCIL_REF_CHROMIUM',
558 'default': '0',
561 'name': 'stencil_path_mask',
562 'type': 'GLuint',
563 'enum': 'GL_PATH_STENCIL_VALUE_MASK_CHROMIUM',
564 'default': '0xFFFFFFFFU',
570 # Named type info object represents a named type that is used in OpenGL call
571 # arguments. Each named type defines a set of valid OpenGL call arguments. The
572 # named types are used in 'cmd_buffer_functions.txt'.
573 # type: The actual GL type of the named type.
574 # valid: The list of values that are valid for both the client and the service.
575 # valid_es3: The list of values that are valid in OpenGL ES 3, but not ES 2.
576 # invalid: Examples of invalid values for the type. At least these values
577 # should be tested to be invalid.
578 # deprecated_es3: The list of values that are valid in OpenGL ES 2, but
579 # deprecated in ES 3.
580 # is_complete: The list of valid values of type are final and will not be
581 # modified during runtime.
582 _NAMED_TYPE_INFO = {
583 'BlitFilter': {
584 'type': 'GLenum',
585 'valid': [
586 'GL_NEAREST',
587 'GL_LINEAR',
589 'invalid': [
590 'GL_LINEAR_MIPMAP_LINEAR',
593 'FrameBufferTarget': {
594 'type': 'GLenum',
595 'valid': [
596 'GL_FRAMEBUFFER',
598 'valid_es3': [
599 'GL_DRAW_FRAMEBUFFER' ,
600 'GL_READ_FRAMEBUFFER' ,
602 'invalid': [
603 'GL_RENDERBUFFER',
606 'InvalidateFrameBufferTarget': {
607 'type': 'GLenum',
608 'valid': [
609 'GL_FRAMEBUFFER',
611 'invalid': [
612 'GL_DRAW_FRAMEBUFFER' ,
613 'GL_READ_FRAMEBUFFER' ,
616 'RenderBufferTarget': {
617 'type': 'GLenum',
618 'valid': [
619 'GL_RENDERBUFFER',
621 'invalid': [
622 'GL_FRAMEBUFFER',
625 'BufferTarget': {
626 'type': 'GLenum',
627 'valid': [
628 'GL_ARRAY_BUFFER',
629 'GL_ELEMENT_ARRAY_BUFFER',
631 'valid_es3': [
632 'GL_COPY_READ_BUFFER',
633 'GL_COPY_WRITE_BUFFER',
634 'GL_PIXEL_PACK_BUFFER',
635 'GL_PIXEL_UNPACK_BUFFER',
636 'GL_TRANSFORM_FEEDBACK_BUFFER',
637 'GL_UNIFORM_BUFFER',
639 'invalid': [
640 'GL_RENDERBUFFER',
643 'IndexedBufferTarget': {
644 'type': 'GLenum',
645 'valid': [
646 'GL_TRANSFORM_FEEDBACK_BUFFER',
647 'GL_UNIFORM_BUFFER',
649 'invalid': [
650 'GL_RENDERBUFFER',
653 'MapBufferAccess': {
654 'type': 'GLenum',
655 'valid': [
656 'GL_MAP_READ_BIT',
657 'GL_MAP_WRITE_BIT',
658 'GL_MAP_INVALIDATE_RANGE_BIT',
659 'GL_MAP_INVALIDATE_BUFFER_BIT',
660 'GL_MAP_FLUSH_EXPLICIT_BIT',
661 'GL_MAP_UNSYNCHRONIZED_BIT',
663 'invalid': [
664 'GL_SYNC_FLUSH_COMMANDS_BIT',
667 'Bufferiv': {
668 'type': 'GLenum',
669 'valid': [
670 'GL_COLOR',
671 'GL_STENCIL',
673 'invalid': [
674 'GL_RENDERBUFFER',
677 'Bufferuiv': {
678 'type': 'GLenum',
679 'valid': [
680 'GL_COLOR',
682 'invalid': [
683 'GL_RENDERBUFFER',
686 'Bufferfv': {
687 'type': 'GLenum',
688 'valid': [
689 'GL_COLOR',
690 'GL_DEPTH',
692 'invalid': [
693 'GL_RENDERBUFFER',
696 'Bufferfi': {
697 'type': 'GLenum',
698 'valid': [
699 'GL_DEPTH_STENCIL',
701 'invalid': [
702 'GL_RENDERBUFFER',
705 'BufferUsage': {
706 'type': 'GLenum',
707 'valid': [
708 'GL_STREAM_DRAW',
709 'GL_STATIC_DRAW',
710 'GL_DYNAMIC_DRAW',
712 'valid_es3': [
713 'GL_STREAM_READ',
714 'GL_STREAM_COPY',
715 'GL_STATIC_READ',
716 'GL_STATIC_COPY',
717 'GL_DYNAMIC_READ',
718 'GL_DYNAMIC_COPY',
720 'invalid': [
721 'GL_NONE',
724 'CompressedTextureFormat': {
725 'type': 'GLenum',
726 'valid': [
728 'valid_es3': [
729 'GL_COMPRESSED_R11_EAC',
730 'GL_COMPRESSED_SIGNED_R11_EAC',
731 'GL_COMPRESSED_RG11_EAC',
732 'GL_COMPRESSED_SIGNED_RG11_EAC',
733 'GL_COMPRESSED_RGB8_ETC2',
734 'GL_COMPRESSED_SRGB8_ETC2',
735 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
736 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
737 'GL_COMPRESSED_RGBA8_ETC2_EAC',
738 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
741 'GLState': {
742 'type': 'GLenum',
743 'valid': [
744 # NOTE: State an Capability entries added later.
745 'GL_ACTIVE_TEXTURE',
746 'GL_ALIASED_LINE_WIDTH_RANGE',
747 'GL_ALIASED_POINT_SIZE_RANGE',
748 'GL_ALPHA_BITS',
749 'GL_ARRAY_BUFFER_BINDING',
750 'GL_BLUE_BITS',
751 'GL_COMPRESSED_TEXTURE_FORMATS',
752 'GL_CURRENT_PROGRAM',
753 'GL_DEPTH_BITS',
754 'GL_DEPTH_RANGE',
755 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
756 'GL_FRAMEBUFFER_BINDING',
757 'GL_GENERATE_MIPMAP_HINT',
758 'GL_GREEN_BITS',
759 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
760 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
761 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
762 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
763 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
764 'GL_MAX_RENDERBUFFER_SIZE',
765 'GL_MAX_TEXTURE_IMAGE_UNITS',
766 'GL_MAX_TEXTURE_SIZE',
767 'GL_MAX_VARYING_VECTORS',
768 'GL_MAX_VERTEX_ATTRIBS',
769 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
770 'GL_MAX_VERTEX_UNIFORM_VECTORS',
771 'GL_MAX_VIEWPORT_DIMS',
772 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
773 'GL_NUM_SHADER_BINARY_FORMATS',
774 'GL_PACK_ALIGNMENT',
775 'GL_RED_BITS',
776 'GL_RENDERBUFFER_BINDING',
777 'GL_SAMPLE_BUFFERS',
778 'GL_SAMPLE_COVERAGE_INVERT',
779 'GL_SAMPLE_COVERAGE_VALUE',
780 'GL_SAMPLES',
781 'GL_SCISSOR_BOX',
782 'GL_SHADER_BINARY_FORMATS',
783 'GL_SHADER_COMPILER',
784 'GL_SUBPIXEL_BITS',
785 'GL_STENCIL_BITS',
786 'GL_TEXTURE_BINDING_2D',
787 'GL_TEXTURE_BINDING_CUBE_MAP',
788 'GL_UNPACK_ALIGNMENT',
789 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
790 # we can add this because we emulate it if the driver does not support it.
791 'GL_VERTEX_ARRAY_BINDING_OES',
792 'GL_VIEWPORT',
794 'valid_es3': [
795 'GL_COPY_READ_BUFFER_BINDING',
796 'GL_COPY_WRITE_BUFFER_BINDING',
797 'GL_DRAW_BUFFER0',
798 'GL_DRAW_BUFFER1',
799 'GL_DRAW_BUFFER2',
800 'GL_DRAW_BUFFER3',
801 'GL_DRAW_BUFFER4',
802 'GL_DRAW_BUFFER5',
803 'GL_DRAW_BUFFER6',
804 'GL_DRAW_BUFFER7',
805 'GL_DRAW_BUFFER8',
806 'GL_DRAW_BUFFER9',
807 'GL_DRAW_BUFFER10',
808 'GL_DRAW_BUFFER11',
809 'GL_DRAW_BUFFER12',
810 'GL_DRAW_BUFFER13',
811 'GL_DRAW_BUFFER14',
812 'GL_DRAW_BUFFER15',
813 'GL_DRAW_FRAMEBUFFER_BINDING',
814 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
815 'GL_MAJOR_VERSION',
816 'GL_MAX_3D_TEXTURE_SIZE',
817 'GL_MAX_ARRAY_TEXTURE_LAYERS',
818 'GL_MAX_COLOR_ATTACHMENTS',
819 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
820 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
821 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
822 'GL_MAX_DRAW_BUFFERS',
823 'GL_MAX_ELEMENT_INDEX',
824 'GL_MAX_ELEMENTS_INDICES',
825 'GL_MAX_ELEMENTS_VERTICES',
826 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
827 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
828 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
829 'GL_MAX_PROGRAM_TEXEL_OFFSET',
830 'GL_MAX_SAMPLES',
831 'GL_MAX_SERVER_WAIT_TIMEOUT',
832 'GL_MAX_TEXTURE_LOD_BIAS',
833 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
834 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
835 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
836 'GL_MAX_UNIFORM_BLOCK_SIZE',
837 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
838 'GL_MAX_VARYING_COMPONENTS',
839 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
840 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
841 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
842 'GL_MIN_PROGRAM_TEXEL_OFFSET',
843 'GL_MINOR_VERSION',
844 'GL_NUM_EXTENSIONS',
845 'GL_NUM_PROGRAM_BINARY_FORMATS',
846 'GL_PACK_ROW_LENGTH',
847 'GL_PACK_SKIP_PIXELS',
848 'GL_PACK_SKIP_ROWS',
849 'GL_PIXEL_PACK_BUFFER_BINDING',
850 'GL_PIXEL_UNPACK_BUFFER_BINDING',
851 'GL_PROGRAM_BINARY_FORMATS',
852 'GL_READ_BUFFER',
853 'GL_READ_FRAMEBUFFER_BINDING',
854 'GL_SAMPLER_BINDING',
855 'GL_TEXTURE_BINDING_2D_ARRAY',
856 'GL_TEXTURE_BINDING_3D',
857 'GL_TRANSFORM_FEEDBACK_BINDING',
858 'GL_TRANSFORM_FEEDBACK_ACTIVE',
859 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
860 'GL_TRANSFORM_FEEDBACK_PAUSED',
861 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
862 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
863 'GL_UNIFORM_BUFFER_BINDING',
864 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
865 'GL_UNIFORM_BUFFER_SIZE',
866 'GL_UNIFORM_BUFFER_START',
867 'GL_UNPACK_IMAGE_HEIGHT',
868 'GL_UNPACK_ROW_LENGTH',
869 'GL_UNPACK_SKIP_IMAGES',
870 'GL_UNPACK_SKIP_PIXELS',
871 'GL_UNPACK_SKIP_ROWS',
872 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
873 # 'GL_VERTEX_ARRAY_BINDING',
875 'invalid': [
876 'GL_FOG_HINT',
879 'IndexedGLState': {
880 'type': 'GLenum',
881 'valid': [
882 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
883 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
884 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
885 'GL_UNIFORM_BUFFER_BINDING',
886 'GL_UNIFORM_BUFFER_SIZE',
887 'GL_UNIFORM_BUFFER_START',
889 'invalid': [
890 'GL_FOG_HINT',
893 'GetTexParamTarget': {
894 'type': 'GLenum',
895 'valid': [
896 'GL_TEXTURE_2D',
897 'GL_TEXTURE_CUBE_MAP',
899 'valid_es3': [
900 'GL_TEXTURE_2D_ARRAY',
901 'GL_TEXTURE_3D',
903 'invalid': [
904 'GL_PROXY_TEXTURE_CUBE_MAP',
907 'ReadBuffer': {
908 'type': 'GLenum',
909 'valid': [
910 'GL_NONE',
911 'GL_BACK',
912 'GL_COLOR_ATTACHMENT0',
913 'GL_COLOR_ATTACHMENT1',
914 'GL_COLOR_ATTACHMENT2',
915 'GL_COLOR_ATTACHMENT3',
916 'GL_COLOR_ATTACHMENT4',
917 'GL_COLOR_ATTACHMENT5',
918 'GL_COLOR_ATTACHMENT6',
919 'GL_COLOR_ATTACHMENT7',
920 'GL_COLOR_ATTACHMENT8',
921 'GL_COLOR_ATTACHMENT9',
922 'GL_COLOR_ATTACHMENT10',
923 'GL_COLOR_ATTACHMENT11',
924 'GL_COLOR_ATTACHMENT12',
925 'GL_COLOR_ATTACHMENT13',
926 'GL_COLOR_ATTACHMENT14',
927 'GL_COLOR_ATTACHMENT15',
929 'invalid': [
930 'GL_RENDERBUFFER',
933 'TextureTarget': {
934 'type': 'GLenum',
935 'valid': [
936 'GL_TEXTURE_2D',
937 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
938 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
939 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
940 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
941 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
942 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
944 'invalid': [
945 'GL_PROXY_TEXTURE_CUBE_MAP',
948 'Texture3DTarget': {
949 'type': 'GLenum',
950 'valid': [
951 'GL_TEXTURE_3D',
952 'GL_TEXTURE_2D_ARRAY',
954 'invalid': [
955 'GL_TEXTURE_2D',
958 'TextureBindTarget': {
959 'type': 'GLenum',
960 'valid': [
961 'GL_TEXTURE_2D',
962 'GL_TEXTURE_CUBE_MAP',
964 'valid_es3': [
965 'GL_TEXTURE_3D',
966 'GL_TEXTURE_2D_ARRAY',
968 'invalid': [
969 'GL_TEXTURE_1D',
970 'GL_TEXTURE_3D',
973 'TransformFeedbackBindTarget': {
974 'type': 'GLenum',
975 'valid': [
976 'GL_TRANSFORM_FEEDBACK',
978 'invalid': [
979 'GL_TEXTURE_2D',
982 'TransformFeedbackPrimitiveMode': {
983 'type': 'GLenum',
984 'valid': [
985 'GL_POINTS',
986 'GL_LINES',
987 'GL_TRIANGLES',
989 'invalid': [
990 'GL_LINE_LOOP',
993 'ShaderType': {
994 'type': 'GLenum',
995 'valid': [
996 'GL_VERTEX_SHADER',
997 'GL_FRAGMENT_SHADER',
999 'invalid': [
1000 'GL_GEOMETRY_SHADER',
1003 'FaceType': {
1004 'type': 'GLenum',
1005 'valid': [
1006 'GL_FRONT',
1007 'GL_BACK',
1008 'GL_FRONT_AND_BACK',
1011 'FaceMode': {
1012 'type': 'GLenum',
1013 'valid': [
1014 'GL_CW',
1015 'GL_CCW',
1018 'CmpFunction': {
1019 'type': 'GLenum',
1020 'valid': [
1021 'GL_NEVER',
1022 'GL_LESS',
1023 'GL_EQUAL',
1024 'GL_LEQUAL',
1025 'GL_GREATER',
1026 'GL_NOTEQUAL',
1027 'GL_GEQUAL',
1028 'GL_ALWAYS',
1031 'Equation': {
1032 'type': 'GLenum',
1033 'valid': [
1034 'GL_FUNC_ADD',
1035 'GL_FUNC_SUBTRACT',
1036 'GL_FUNC_REVERSE_SUBTRACT',
1038 'valid_es3': [
1039 'GL_MIN',
1040 'GL_MAX',
1042 'invalid': [
1043 'GL_NONE',
1046 'SrcBlendFactor': {
1047 'type': 'GLenum',
1048 'valid': [
1049 'GL_ZERO',
1050 'GL_ONE',
1051 'GL_SRC_COLOR',
1052 'GL_ONE_MINUS_SRC_COLOR',
1053 'GL_DST_COLOR',
1054 'GL_ONE_MINUS_DST_COLOR',
1055 'GL_SRC_ALPHA',
1056 'GL_ONE_MINUS_SRC_ALPHA',
1057 'GL_DST_ALPHA',
1058 'GL_ONE_MINUS_DST_ALPHA',
1059 'GL_CONSTANT_COLOR',
1060 'GL_ONE_MINUS_CONSTANT_COLOR',
1061 'GL_CONSTANT_ALPHA',
1062 'GL_ONE_MINUS_CONSTANT_ALPHA',
1063 'GL_SRC_ALPHA_SATURATE',
1066 'DstBlendFactor': {
1067 'type': 'GLenum',
1068 'valid': [
1069 'GL_ZERO',
1070 'GL_ONE',
1071 'GL_SRC_COLOR',
1072 'GL_ONE_MINUS_SRC_COLOR',
1073 'GL_DST_COLOR',
1074 'GL_ONE_MINUS_DST_COLOR',
1075 'GL_SRC_ALPHA',
1076 'GL_ONE_MINUS_SRC_ALPHA',
1077 'GL_DST_ALPHA',
1078 'GL_ONE_MINUS_DST_ALPHA',
1079 'GL_CONSTANT_COLOR',
1080 'GL_ONE_MINUS_CONSTANT_COLOR',
1081 'GL_CONSTANT_ALPHA',
1082 'GL_ONE_MINUS_CONSTANT_ALPHA',
1085 'Capability': {
1086 'type': 'GLenum',
1087 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
1088 if 'es3' not in cap or cap['es3'] != True],
1089 'valid_es3': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
1090 if 'es3' in cap and cap['es3'] == True],
1091 'invalid': [
1092 'GL_CLIP_PLANE0',
1093 'GL_POINT_SPRITE',
1096 'DrawMode': {
1097 'type': 'GLenum',
1098 'valid': [
1099 'GL_POINTS',
1100 'GL_LINE_STRIP',
1101 'GL_LINE_LOOP',
1102 'GL_LINES',
1103 'GL_TRIANGLE_STRIP',
1104 'GL_TRIANGLE_FAN',
1105 'GL_TRIANGLES',
1107 'invalid': [
1108 'GL_QUADS',
1109 'GL_POLYGON',
1112 'IndexType': {
1113 'type': 'GLenum',
1114 'valid': [
1115 'GL_UNSIGNED_BYTE',
1116 'GL_UNSIGNED_SHORT',
1118 'valid_es3': [
1119 'GL_UNSIGNED_INT',
1121 'invalid': [
1122 'GL_INT',
1125 'GetMaxIndexType': {
1126 'type': 'GLenum',
1127 'valid': [
1128 'GL_UNSIGNED_BYTE',
1129 'GL_UNSIGNED_SHORT',
1130 'GL_UNSIGNED_INT',
1132 'invalid': [
1133 'GL_INT',
1136 'Attachment': {
1137 'type': 'GLenum',
1138 'valid': [
1139 'GL_COLOR_ATTACHMENT0',
1140 'GL_DEPTH_ATTACHMENT',
1141 'GL_STENCIL_ATTACHMENT',
1143 'valid_es3': [
1144 'GL_DEPTH_STENCIL_ATTACHMENT',
1147 'BackbufferAttachment': {
1148 'type': 'GLenum',
1149 'valid': [
1150 'GL_COLOR_EXT',
1151 'GL_DEPTH_EXT',
1152 'GL_STENCIL_EXT',
1155 'BufferParameter': {
1156 'type': 'GLenum',
1157 'valid': [
1158 'GL_BUFFER_SIZE',
1159 'GL_BUFFER_USAGE',
1161 'valid_es3': [
1162 'GL_BUFFER_ACCESS_FLAGS',
1163 'GL_BUFFER_MAPPED',
1165 'invalid': [
1166 'GL_PIXEL_PACK_BUFFER',
1169 'BufferParameter64': {
1170 'type': 'GLenum',
1171 'valid': [
1172 'GL_BUFFER_SIZE',
1173 'GL_BUFFER_MAP_LENGTH',
1174 'GL_BUFFER_MAP_OFFSET',
1176 'invalid': [
1177 'GL_PIXEL_PACK_BUFFER',
1180 'BufferMode': {
1181 'type': 'GLenum',
1182 'valid': [
1183 'GL_INTERLEAVED_ATTRIBS',
1184 'GL_SEPARATE_ATTRIBS',
1186 'invalid': [
1187 'GL_PIXEL_PACK_BUFFER',
1190 'FrameBufferParameter': {
1191 'type': 'GLenum',
1192 'valid': [
1193 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1194 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1195 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1196 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1198 'valid_es3': [
1199 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1200 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1201 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1202 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1203 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1204 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1205 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1206 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1207 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1210 'MatrixMode': {
1211 'type': 'GLenum',
1212 'valid': [
1213 'GL_PATH_PROJECTION_CHROMIUM',
1214 'GL_PATH_MODELVIEW_CHROMIUM',
1217 'ProgramParameter': {
1218 'type': 'GLenum',
1219 'valid': [
1220 'GL_DELETE_STATUS',
1221 'GL_LINK_STATUS',
1222 'GL_VALIDATE_STATUS',
1223 'GL_INFO_LOG_LENGTH',
1224 'GL_ATTACHED_SHADERS',
1225 'GL_ACTIVE_ATTRIBUTES',
1226 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1227 'GL_ACTIVE_UNIFORMS',
1228 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1230 'valid_es3': [
1231 'GL_ACTIVE_UNIFORM_BLOCKS',
1232 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1233 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1234 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1235 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1237 'invalid': [
1238 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1241 'QueryObjectParameter': {
1242 'type': 'GLenum',
1243 'valid': [
1244 'GL_QUERY_RESULT_EXT',
1245 'GL_QUERY_RESULT_AVAILABLE_EXT',
1248 'QueryParameter': {
1249 'type': 'GLenum',
1250 'valid': [
1251 'GL_CURRENT_QUERY_EXT',
1254 'QueryTarget': {
1255 'type': 'GLenum',
1256 'valid': [
1257 'GL_ANY_SAMPLES_PASSED_EXT',
1258 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1259 'GL_COMMANDS_ISSUED_CHROMIUM',
1260 'GL_LATENCY_QUERY_CHROMIUM',
1261 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1262 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1263 'GL_COMMANDS_COMPLETED_CHROMIUM',
1266 'RenderBufferParameter': {
1267 'type': 'GLenum',
1268 'valid': [
1269 'GL_RENDERBUFFER_RED_SIZE',
1270 'GL_RENDERBUFFER_GREEN_SIZE',
1271 'GL_RENDERBUFFER_BLUE_SIZE',
1272 'GL_RENDERBUFFER_ALPHA_SIZE',
1273 'GL_RENDERBUFFER_DEPTH_SIZE',
1274 'GL_RENDERBUFFER_STENCIL_SIZE',
1275 'GL_RENDERBUFFER_WIDTH',
1276 'GL_RENDERBUFFER_HEIGHT',
1277 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1279 'valid_es3': [
1280 'GL_RENDERBUFFER_SAMPLES',
1283 'InternalFormatParameter': {
1284 'type': 'GLenum',
1285 'valid': [
1286 'GL_NUM_SAMPLE_COUNTS',
1287 'GL_SAMPLES',
1290 'SamplerParameter': {
1291 'type': 'GLenum',
1292 'valid': [
1293 'GL_TEXTURE_MAG_FILTER',
1294 'GL_TEXTURE_MIN_FILTER',
1295 'GL_TEXTURE_MIN_LOD',
1296 'GL_TEXTURE_MAX_LOD',
1297 'GL_TEXTURE_WRAP_S',
1298 'GL_TEXTURE_WRAP_T',
1299 'GL_TEXTURE_WRAP_R',
1300 'GL_TEXTURE_COMPARE_MODE',
1301 'GL_TEXTURE_COMPARE_FUNC',
1303 'invalid': [
1304 'GL_GENERATE_MIPMAP',
1307 'ShaderParameter': {
1308 'type': 'GLenum',
1309 'valid': [
1310 'GL_SHADER_TYPE',
1311 'GL_DELETE_STATUS',
1312 'GL_COMPILE_STATUS',
1313 'GL_INFO_LOG_LENGTH',
1314 'GL_SHADER_SOURCE_LENGTH',
1315 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1318 'ShaderPrecision': {
1319 'type': 'GLenum',
1320 'valid': [
1321 'GL_LOW_FLOAT',
1322 'GL_MEDIUM_FLOAT',
1323 'GL_HIGH_FLOAT',
1324 'GL_LOW_INT',
1325 'GL_MEDIUM_INT',
1326 'GL_HIGH_INT',
1329 'StringType': {
1330 'type': 'GLenum',
1331 'valid': [
1332 'GL_VENDOR',
1333 'GL_RENDERER',
1334 'GL_VERSION',
1335 'GL_SHADING_LANGUAGE_VERSION',
1336 'GL_EXTENSIONS',
1339 'TextureParameter': {
1340 'type': 'GLenum',
1341 'valid': [
1342 'GL_TEXTURE_MAG_FILTER',
1343 'GL_TEXTURE_MIN_FILTER',
1344 'GL_TEXTURE_POOL_CHROMIUM',
1345 'GL_TEXTURE_WRAP_S',
1346 'GL_TEXTURE_WRAP_T',
1348 'valid_es3': [
1349 'GL_TEXTURE_BASE_LEVEL',
1350 'GL_TEXTURE_COMPARE_FUNC',
1351 'GL_TEXTURE_COMPARE_MODE',
1352 'GL_TEXTURE_IMMUTABLE_FORMAT',
1353 'GL_TEXTURE_IMMUTABLE_LEVELS',
1354 'GL_TEXTURE_MAX_LEVEL',
1355 'GL_TEXTURE_MAX_LOD',
1356 'GL_TEXTURE_MIN_LOD',
1357 'GL_TEXTURE_WRAP_R',
1359 'invalid': [
1360 'GL_GENERATE_MIPMAP',
1363 'TexturePool': {
1364 'type': 'GLenum',
1365 'valid': [
1366 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1367 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1370 'TextureWrapMode': {
1371 'type': 'GLenum',
1372 'valid': [
1373 'GL_CLAMP_TO_EDGE',
1374 'GL_MIRRORED_REPEAT',
1375 'GL_REPEAT',
1378 'TextureMinFilterMode': {
1379 'type': 'GLenum',
1380 'valid': [
1381 'GL_NEAREST',
1382 'GL_LINEAR',
1383 'GL_NEAREST_MIPMAP_NEAREST',
1384 'GL_LINEAR_MIPMAP_NEAREST',
1385 'GL_NEAREST_MIPMAP_LINEAR',
1386 'GL_LINEAR_MIPMAP_LINEAR',
1389 'TextureMagFilterMode': {
1390 'type': 'GLenum',
1391 'valid': [
1392 'GL_NEAREST',
1393 'GL_LINEAR',
1396 'TextureCompareFunc': {
1397 'type': 'GLenum',
1398 'valid': [
1399 'GL_LEQUAL',
1400 'GL_GEQUAL',
1401 'GL_LESS',
1402 'GL_GREATER',
1403 'GL_EQUAL',
1404 'GL_NOTEQUAL',
1405 'GL_ALWAYS',
1406 'GL_NEVER',
1409 'TextureCompareMode': {
1410 'type': 'GLenum',
1411 'valid': [
1412 'GL_NONE',
1413 'GL_COMPARE_REF_TO_TEXTURE',
1416 'TextureUsage': {
1417 'type': 'GLenum',
1418 'valid': [
1419 'GL_NONE',
1420 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1423 'VertexAttribute': {
1424 'type': 'GLenum',
1425 'valid': [
1426 # some enum that the decoder actually passes through to GL needs
1427 # to be the first listed here since it's used in unit tests.
1428 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1429 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1430 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1431 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1432 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1433 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1434 'GL_CURRENT_VERTEX_ATTRIB',
1436 'valid_es3': [
1437 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1438 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1441 'VertexPointer': {
1442 'type': 'GLenum',
1443 'valid': [
1444 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1447 'HintTarget': {
1448 'type': 'GLenum',
1449 'valid': [
1450 'GL_GENERATE_MIPMAP_HINT',
1452 'valid_es3': [
1453 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1455 'invalid': [
1456 'GL_PERSPECTIVE_CORRECTION_HINT',
1459 'HintMode': {
1460 'type': 'GLenum',
1461 'valid': [
1462 'GL_FASTEST',
1463 'GL_NICEST',
1464 'GL_DONT_CARE',
1467 'PixelStore': {
1468 'type': 'GLenum',
1469 'valid': [
1470 'GL_PACK_ALIGNMENT',
1471 'GL_UNPACK_ALIGNMENT',
1473 'valid_es3': [
1474 'GL_PACK_ROW_LENGTH',
1475 'GL_PACK_SKIP_PIXELS',
1476 'GL_PACK_SKIP_ROWS',
1477 'GL_UNPACK_ROW_LENGTH',
1478 'GL_UNPACK_IMAGE_HEIGHT',
1479 'GL_UNPACK_SKIP_PIXELS',
1480 'GL_UNPACK_SKIP_ROWS',
1481 'GL_UNPACK_SKIP_IMAGES',
1483 'invalid': [
1484 'GL_PACK_SWAP_BYTES',
1485 'GL_UNPACK_SWAP_BYTES',
1488 'PixelStoreAlignment': {
1489 'type': 'GLint',
1490 'valid': [
1491 '1',
1492 '2',
1493 '4',
1494 '8',
1496 'invalid': [
1497 '3',
1498 '9',
1501 'ReadPixelFormat': {
1502 'type': 'GLenum',
1503 'valid': [
1504 'GL_ALPHA',
1505 'GL_RGB',
1506 'GL_RGBA',
1508 'valid_es3': [
1509 'GL_RGBA_INTEGER',
1511 'deprecated_es3': [
1512 'GL_ALPHA',
1513 'GL_RGB',
1516 'PixelType': {
1517 'type': 'GLenum',
1518 'valid': [
1519 'GL_UNSIGNED_BYTE',
1520 'GL_UNSIGNED_SHORT_5_6_5',
1521 'GL_UNSIGNED_SHORT_4_4_4_4',
1522 'GL_UNSIGNED_SHORT_5_5_5_1',
1524 'valid_es3': [
1525 'GL_BYTE',
1526 'GL_UNSIGNED_SHORT',
1527 'GL_SHORT',
1528 'GL_UNSIGNED_INT',
1529 'GL_INT',
1530 'GL_HALF_FLOAT',
1531 'GL_FLOAT',
1532 'GL_UNSIGNED_INT_2_10_10_10_REV',
1533 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1534 'GL_UNSIGNED_INT_5_9_9_9_REV',
1535 'GL_UNSIGNED_INT_24_8',
1536 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1538 'invalid': [
1539 'GL_UNSIGNED_BYTE_3_3_2',
1542 'PathCoordType': {
1543 'type': 'GLenum',
1544 'valid': [
1545 'GL_BYTE',
1546 'GL_UNSIGNED_BYTE',
1547 'GL_SHORT',
1548 'GL_UNSIGNED_SHORT',
1549 'GL_FLOAT',
1552 'PathCoverMode': {
1553 'type': 'GLenum',
1554 'valid': [
1555 'GL_CONVEX_HULL_CHROMIUM',
1556 'GL_BOUNDING_BOX_CHROMIUM',
1559 'PathFillMode': {
1560 'type': 'GLenum',
1561 'valid': [
1562 'GL_INVERT',
1563 'GL_COUNT_UP_CHROMIUM',
1564 'GL_COUNT_DOWN_CHROMIUM',
1567 'PathParameter': {
1568 'type': 'GLenum',
1569 'valid': [
1570 'GL_PATH_STROKE_WIDTH_CHROMIUM',
1571 'GL_PATH_END_CAPS_CHROMIUM',
1572 'GL_PATH_JOIN_STYLE_CHROMIUM',
1573 'GL_PATH_MITER_LIMIT_CHROMIUM',
1574 'GL_PATH_STROKE_BOUND_CHROMIUM',
1577 'PathParameterCapValues': {
1578 'type': 'GLint',
1579 'valid': [
1580 'GL_FLAT',
1581 'GL_SQUARE_CHROMIUM',
1582 'GL_ROUND_CHROMIUM',
1585 'PathParameterJoinValues': {
1586 'type': 'GLint',
1587 'valid': [
1588 'GL_MITER_REVERT_CHROMIUM',
1589 'GL_BEVEL_CHROMIUM',
1590 'GL_ROUND_CHROMIUM',
1593 'ReadPixelType': {
1594 'type': 'GLenum',
1595 'valid': [
1596 'GL_UNSIGNED_BYTE',
1597 'GL_UNSIGNED_SHORT_5_6_5',
1598 'GL_UNSIGNED_SHORT_4_4_4_4',
1599 'GL_UNSIGNED_SHORT_5_5_5_1',
1601 'invalid': [
1602 'GL_SHORT',
1604 'valid_es3': [
1605 'GL_UNSIGNED_INT',
1606 'GL_INT',
1607 'GL_FLOAT',
1609 'deprecated_es3': [
1610 'GL_UNSIGNED_SHORT_5_6_5',
1611 'GL_UNSIGNED_SHORT_4_4_4_4',
1612 'GL_UNSIGNED_SHORT_5_5_5_1',
1615 'RenderBufferFormat': {
1616 'type': 'GLenum',
1617 'valid': [
1618 'GL_RGBA4',
1619 'GL_RGB565',
1620 'GL_RGB5_A1',
1621 'GL_DEPTH_COMPONENT16',
1622 'GL_STENCIL_INDEX8',
1624 'valid_es3': [
1625 'GL_R8',
1626 'GL_R8UI',
1627 'GL_R8I',
1628 'GL_R16UI',
1629 'GL_R16I',
1630 'GL_R32UI',
1631 'GL_R32I',
1632 'GL_RG8',
1633 'GL_RG8UI',
1634 'GL_RG8I',
1635 'GL_RG16UI',
1636 'GL_RG16I',
1637 'GL_RG32UI',
1638 'GL_RG32I',
1639 'GL_RGB8',
1640 'GL_RGBA8',
1641 'GL_SRGB8_ALPHA8',
1642 'GL_RGB10_A2',
1643 'GL_RGBA8UI',
1644 'GL_RGBA8I',
1645 'GL_RGB10_A2UI',
1646 'GL_RGBA16UI',
1647 'GL_RGBA16I',
1648 'GL_RGBA32UI',
1649 'GL_RGBA32I',
1650 'GL_DEPTH_COMPONENT24',
1651 'GL_DEPTH_COMPONENT32F',
1652 'GL_DEPTH24_STENCIL8',
1653 'GL_DEPTH32F_STENCIL8',
1656 'ShaderBinaryFormat': {
1657 'type': 'GLenum',
1658 'valid': [
1661 'StencilOp': {
1662 'type': 'GLenum',
1663 'valid': [
1664 'GL_KEEP',
1665 'GL_ZERO',
1666 'GL_REPLACE',
1667 'GL_INCR',
1668 'GL_INCR_WRAP',
1669 'GL_DECR',
1670 'GL_DECR_WRAP',
1671 'GL_INVERT',
1674 'TextureFormat': {
1675 'type': 'GLenum',
1676 'valid': [
1677 'GL_ALPHA',
1678 'GL_LUMINANCE',
1679 'GL_LUMINANCE_ALPHA',
1680 'GL_RGB',
1681 'GL_RGBA',
1683 'valid_es3': [
1684 'GL_RED',
1685 'GL_RED_INTEGER',
1686 'GL_RG',
1687 'GL_RG_INTEGER',
1688 'GL_RGB_INTEGER',
1689 'GL_RGBA_INTEGER',
1690 'GL_DEPTH_COMPONENT',
1691 'GL_DEPTH_STENCIL',
1693 'invalid': [
1694 'GL_BGRA',
1695 'GL_BGR',
1698 'TextureInternalFormat': {
1699 'type': 'GLenum',
1700 'valid': [
1701 'GL_ALPHA',
1702 'GL_LUMINANCE',
1703 'GL_LUMINANCE_ALPHA',
1704 'GL_RGB',
1705 'GL_RGBA',
1707 'valid_es3': [
1708 'GL_R8',
1709 'GL_R8_SNORM',
1710 'GL_R16F',
1711 'GL_R32F',
1712 'GL_R8UI',
1713 'GL_R8I',
1714 'GL_R16UI',
1715 'GL_R16I',
1716 'GL_R32UI',
1717 'GL_R32I',
1718 'GL_RG8',
1719 'GL_RG8_SNORM',
1720 'GL_RG16F',
1721 'GL_RG32F',
1722 'GL_RG8UI',
1723 'GL_RG8I',
1724 'GL_RG16UI',
1725 'GL_RG16I',
1726 'GL_RG32UI',
1727 'GL_RG32I',
1728 'GL_RGB8',
1729 'GL_SRGB8',
1730 'GL_RGB565',
1731 'GL_RGB8_SNORM',
1732 'GL_R11F_G11F_B10F',
1733 'GL_RGB9_E5',
1734 'GL_RGB16F',
1735 'GL_RGB32F',
1736 'GL_RGB8UI',
1737 'GL_RGB8I',
1738 'GL_RGB16UI',
1739 'GL_RGB16I',
1740 'GL_RGB32UI',
1741 'GL_RGB32I',
1742 'GL_RGBA8',
1743 'GL_SRGB8_ALPHA8',
1744 'GL_RGBA8_SNORM',
1745 'GL_RGB5_A1',
1746 'GL_RGBA4',
1747 'GL_RGB10_A2',
1748 'GL_RGBA16F',
1749 'GL_RGBA32F',
1750 'GL_RGBA8UI',
1751 'GL_RGBA8I',
1752 'GL_RGB10_A2UI',
1753 'GL_RGBA16UI',
1754 'GL_RGBA16I',
1755 'GL_RGBA32UI',
1756 'GL_RGBA32I',
1757 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1758 # We will reject them dynamically in GPU command buffer.
1759 'GL_DEPTH_COMPONENT16',
1760 'GL_DEPTH_COMPONENT24',
1761 'GL_DEPTH_COMPONENT32F',
1762 'GL_DEPTH24_STENCIL8',
1763 'GL_DEPTH32F_STENCIL8',
1765 'invalid': [
1766 'GL_BGRA',
1767 'GL_BGR',
1770 'TextureInternalFormatStorage': {
1771 'type': 'GLenum',
1772 'valid': [
1773 'GL_RGB565',
1774 'GL_RGBA4',
1775 'GL_RGB5_A1',
1776 'GL_ALPHA8_EXT',
1777 'GL_LUMINANCE8_EXT',
1778 'GL_LUMINANCE8_ALPHA8_EXT',
1779 'GL_RGB8_OES',
1780 'GL_RGBA8_OES',
1782 'valid_es3': [
1783 'GL_R8',
1784 'GL_R8_SNORM',
1785 'GL_R16F',
1786 'GL_R32F',
1787 'GL_R8UI',
1788 'GL_R8I',
1789 'GL_R16UI',
1790 'GL_R16I',
1791 'GL_R32UI',
1792 'GL_R32I',
1793 'GL_RG8',
1794 'GL_RG8_SNORM',
1795 'GL_RG16F',
1796 'GL_RG32F',
1797 'GL_RG8UI',
1798 'GL_RG8I',
1799 'GL_RG16UI',
1800 'GL_RG16I',
1801 'GL_RG32UI',
1802 'GL_RG32I',
1803 'GL_RGB8',
1804 'GL_SRGB8',
1805 'GL_RGB8_SNORM',
1806 'GL_R11F_G11F_B10F',
1807 'GL_RGB9_E5',
1808 'GL_RGB16F',
1809 'GL_RGB32F',
1810 'GL_RGB8UI',
1811 'GL_RGB8I',
1812 'GL_RGB16UI',
1813 'GL_RGB16I',
1814 'GL_RGB32UI',
1815 'GL_RGB32I',
1816 'GL_RGBA8',
1817 'GL_SRGB8_ALPHA8',
1818 'GL_RGBA8_SNORM',
1819 'GL_RGB10_A2',
1820 'GL_RGBA16F',
1821 'GL_RGBA32F',
1822 'GL_RGBA8UI',
1823 'GL_RGBA8I',
1824 'GL_RGB10_A2UI',
1825 'GL_RGBA16UI',
1826 'GL_RGBA16I',
1827 'GL_RGBA32UI',
1828 'GL_RGBA32I',
1829 'GL_DEPTH_COMPONENT16',
1830 'GL_DEPTH_COMPONENT24',
1831 'GL_DEPTH_COMPONENT32F',
1832 'GL_DEPTH24_STENCIL8',
1833 'GL_DEPTH32F_STENCIL8',
1834 'GL_COMPRESSED_R11_EAC',
1835 'GL_COMPRESSED_SIGNED_R11_EAC',
1836 'GL_COMPRESSED_RG11_EAC',
1837 'GL_COMPRESSED_SIGNED_RG11_EAC',
1838 'GL_COMPRESSED_RGB8_ETC2',
1839 'GL_COMPRESSED_SRGB8_ETC2',
1840 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1841 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1842 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1843 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1845 'deprecated_es3': [
1846 'GL_ALPHA8_EXT',
1847 'GL_LUMINANCE8_EXT',
1848 'GL_LUMINANCE8_ALPHA8_EXT',
1849 'GL_ALPHA16F_EXT',
1850 'GL_LUMINANCE16F_EXT',
1851 'GL_LUMINANCE_ALPHA16F_EXT',
1852 'GL_ALPHA32F_EXT',
1853 'GL_LUMINANCE32F_EXT',
1854 'GL_LUMINANCE_ALPHA32F_EXT',
1857 'ImageInternalFormat': {
1858 'type': 'GLenum',
1859 'valid': [
1860 'GL_RGB',
1861 'GL_RGB_YUV_420_CHROMIUM',
1862 'GL_RGBA',
1865 'ImageUsage': {
1866 'type': 'GLenum',
1867 'valid': [
1868 'GL_MAP_CHROMIUM',
1869 'GL_SCANOUT_CHROMIUM'
1872 'ValueBufferTarget': {
1873 'type': 'GLenum',
1874 'valid': [
1875 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1878 'SubscriptionTarget': {
1879 'type': 'GLenum',
1880 'valid': [
1881 'GL_MOUSE_POSITION_CHROMIUM',
1884 'UniformParameter': {
1885 'type': 'GLenum',
1886 'valid': [
1887 'GL_UNIFORM_SIZE',
1888 'GL_UNIFORM_TYPE',
1889 'GL_UNIFORM_NAME_LENGTH',
1890 'GL_UNIFORM_BLOCK_INDEX',
1891 'GL_UNIFORM_OFFSET',
1892 'GL_UNIFORM_ARRAY_STRIDE',
1893 'GL_UNIFORM_MATRIX_STRIDE',
1894 'GL_UNIFORM_IS_ROW_MAJOR',
1896 'invalid': [
1897 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1900 'UniformBlockParameter': {
1901 'type': 'GLenum',
1902 'valid': [
1903 'GL_UNIFORM_BLOCK_BINDING',
1904 'GL_UNIFORM_BLOCK_DATA_SIZE',
1905 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1906 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1907 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1908 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1909 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1911 'invalid': [
1912 'GL_NEAREST',
1915 'VertexAttribType': {
1916 'type': 'GLenum',
1917 'valid': [
1918 'GL_BYTE',
1919 'GL_UNSIGNED_BYTE',
1920 'GL_SHORT',
1921 'GL_UNSIGNED_SHORT',
1922 # 'GL_FIXED', // This is not available on Desktop GL.
1923 'GL_FLOAT',
1925 'valid_es3': [
1926 'GL_INT',
1927 'GL_UNSIGNED_INT',
1928 'GL_HALF_FLOAT',
1929 'GL_INT_2_10_10_10_REV',
1930 'GL_UNSIGNED_INT_2_10_10_10_REV',
1932 'invalid': [
1933 'GL_DOUBLE',
1936 'VertexAttribIType': {
1937 'type': 'GLenum',
1938 'valid': [
1939 'GL_BYTE',
1940 'GL_UNSIGNED_BYTE',
1941 'GL_SHORT',
1942 'GL_UNSIGNED_SHORT',
1943 'GL_INT',
1944 'GL_UNSIGNED_INT',
1946 'invalid': [
1947 'GL_FLOAT',
1948 'GL_DOUBLE',
1951 'TextureBorder': {
1952 'type': 'GLint',
1953 'is_complete': True,
1954 'valid': [
1955 '0',
1957 'invalid': [
1958 '1',
1961 'VertexAttribSize': {
1962 'type': 'GLint',
1963 'valid': [
1964 '1',
1965 '2',
1966 '3',
1967 '4',
1969 'invalid': [
1970 '0',
1971 '5',
1974 'ZeroOnly': {
1975 'type': 'GLint',
1976 'is_complete': True,
1977 'valid': [
1978 '0',
1980 'invalid': [
1981 '1',
1984 'FalseOnly': {
1985 'type': 'GLboolean',
1986 'is_complete': True,
1987 'valid': [
1988 'false',
1990 'invalid': [
1991 'true',
1994 'ResetStatus': {
1995 'type': 'GLenum',
1996 'valid': [
1997 'GL_GUILTY_CONTEXT_RESET_ARB',
1998 'GL_INNOCENT_CONTEXT_RESET_ARB',
1999 'GL_UNKNOWN_CONTEXT_RESET_ARB',
2002 'SyncCondition': {
2003 'type': 'GLenum',
2004 'is_complete': True,
2005 'valid': [
2006 'GL_SYNC_GPU_COMMANDS_COMPLETE',
2008 'invalid': [
2009 '0',
2012 'SyncFlags': {
2013 'type': 'GLbitfield',
2014 'is_complete': True,
2015 'valid': [
2016 '0',
2018 'invalid': [
2019 '1',
2022 'SyncFlushFlags': {
2023 'type': 'GLbitfield',
2024 'valid': [
2025 'GL_SYNC_FLUSH_COMMANDS_BIT',
2026 '0',
2028 'invalid': [
2029 '0xFFFFFFFF',
2032 'SyncParameter': {
2033 'type': 'GLenum',
2034 'valid': [
2035 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
2036 'GL_OBJECT_TYPE',
2037 'GL_SYNC_CONDITION',
2038 'GL_SYNC_FLAGS',
2040 'invalid': [
2041 'GL_SYNC_FENCE',
2046 # This table specifies the different pepper interfaces that are supported for
2047 # GL commands. 'dev' is true if it's a dev interface.
2048 _PEPPER_INTERFACES = [
2049 {'name': '', 'dev': False},
2050 {'name': 'InstancedArrays', 'dev': False},
2051 {'name': 'FramebufferBlit', 'dev': False},
2052 {'name': 'FramebufferMultisample', 'dev': False},
2053 {'name': 'ChromiumEnableFeature', 'dev': False},
2054 {'name': 'ChromiumMapSub', 'dev': False},
2055 {'name': 'Query', 'dev': False},
2056 {'name': 'VertexArrayObject', 'dev': False},
2057 {'name': 'DrawBuffers', 'dev': True},
2060 # A function info object specifies the type and other special data for the
2061 # command that will be generated. A base function info object is generated by
2062 # parsing the "cmd_buffer_functions.txt", one for each function in the
2063 # file. These function info objects can be augmented and their values can be
2064 # overridden by adding an object to the table below.
2066 # Must match function names specified in "cmd_buffer_functions.txt".
2068 # cmd_comment: A comment added to the cmd format.
2069 # type: defines which handler will be used to generate code.
2070 # decoder_func: defines which function to call in the decoder to execute the
2071 # corresponding GL command. If not specified the GL command will
2072 # be called directly.
2073 # gl_test_func: GL function that is expected to be called when testing.
2074 # cmd_args: The arguments to use for the command. This overrides generating
2075 # them based on the GL function arguments.
2076 # gen_cmd: Whether or not this function geneates a command. Default = True.
2077 # data_transfer_methods: Array of methods that are used for transfering the
2078 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
2079 # The default is 'immediate' if the command has one pointer
2080 # argument, otherwise 'shm'. One command is generated for each
2081 # transfer method. Affects only commands which are not of type
2082 # 'HandWritten', 'GETn' or 'GLcharN'.
2083 # Note: the command arguments that affect this are the final args,
2084 # taking cmd_args override into consideration.
2085 # impl_func: Whether or not to generate the GLES2Implementation part of this
2086 # command.
2087 # impl_decl: Whether or not to generate the GLES2Implementation declaration
2088 # for this command.
2089 # needs_size: If True a data_size field is added to the command.
2090 # count: The number of units per element. For PUTn or PUT types.
2091 # use_count_func: If True the actual data count needs to be computed; the count
2092 # argument specifies the maximum count.
2093 # unit_test: If False no service side unit test will be generated.
2094 # client_test: If False no client side unit test will be generated.
2095 # expectation: If False the unit test will have no expected calls.
2096 # gen_func: Name of function that generates GL resource for corresponding
2097 # bind function.
2098 # states: array of states that get set by this function corresponding to
2099 # the given arguments
2100 # state_flag: name of flag that is set to true when function is called.
2101 # no_gl: no GL function is called.
2102 # valid_args: A dictionary of argument indices to args to use in unit tests
2103 # when they can not be automatically determined.
2104 # pepper_interface: The pepper interface that is used for this extension
2105 # pepper_name: The name of the function as exposed to pepper.
2106 # pepper_args: A string representing the argument list (what would appear in
2107 # C/C++ between the parentheses for the function declaration)
2108 # that the Pepper API expects for this function. Use this only if
2109 # the stable Pepper API differs from the GLES2 argument list.
2110 # invalid_test: False if no invalid test needed.
2111 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2112 # first_element_only: For PUT types, True if only the first element of an
2113 # array is used and we end up calling the single value
2114 # corresponding function. eg. TexParameteriv -> TexParameteri
2115 # extension: Function is an extension to GL and should not be exposed to
2116 # pepper unless pepper_interface is defined.
2117 # extension_flag: Function is an extension and should be enabled only when
2118 # the corresponding feature info flag is enabled. Implies
2119 # 'extension': True.
2120 # not_shared: For GENn types, True if objects can't be shared between contexts
2121 # unsafe: True = no validation is implemented on the service side and the
2122 # command is only available with --enable-unsafe-es3-apis.
2123 # id_mapping: A list of resource type names whose client side IDs need to be
2124 # mapped to service side IDs. This is only used for unsafe APIs.
2126 _FUNCTION_INFO = {
2127 'ActiveTexture': {
2128 'decoder_func': 'DoActiveTexture',
2129 'unit_test': False,
2130 'impl_func': False,
2131 'client_test': False,
2133 'AttachShader': {'decoder_func': 'DoAttachShader'},
2134 'BindAttribLocation': {
2135 'type': 'GLchar',
2136 'data_transfer_methods': ['bucket'],
2137 'needs_size': True,
2139 'BindBuffer': {
2140 'type': 'Bind',
2141 'decoder_func': 'DoBindBuffer',
2142 'gen_func': 'GenBuffersARB',
2144 'BindBufferBase': {
2145 'type': 'Bind',
2146 'id_mapping': [ 'Buffer' ],
2147 'gen_func': 'GenBuffersARB',
2148 'unsafe': True,
2150 'BindBufferRange': {
2151 'type': 'Bind',
2152 'id_mapping': [ 'Buffer' ],
2153 'gen_func': 'GenBuffersARB',
2154 'valid_args': {
2155 '3': '4',
2156 '4': '4'
2158 'unsafe': True,
2160 'BindFramebuffer': {
2161 'type': 'Bind',
2162 'decoder_func': 'DoBindFramebuffer',
2163 'gl_test_func': 'glBindFramebufferEXT',
2164 'gen_func': 'GenFramebuffersEXT',
2165 'trace_level': 1,
2167 'BindRenderbuffer': {
2168 'type': 'Bind',
2169 'decoder_func': 'DoBindRenderbuffer',
2170 'gl_test_func': 'glBindRenderbufferEXT',
2171 'gen_func': 'GenRenderbuffersEXT',
2173 'BindSampler': {
2174 'type': 'Bind',
2175 'id_mapping': [ 'Sampler' ],
2176 'unsafe': True,
2178 'BindTexture': {
2179 'type': 'Bind',
2180 'decoder_func': 'DoBindTexture',
2181 'gen_func': 'GenTextures',
2182 # TODO(gman): remove this once client side caching works.
2183 'client_test': False,
2184 'trace_level': 2,
2186 'BindTransformFeedback': {
2187 'type': 'Bind',
2188 'id_mapping': [ 'TransformFeedback' ],
2189 'unsafe': True,
2191 'BlitFramebufferCHROMIUM': {
2192 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2193 'unit_test': False,
2194 'extension_flag': 'chromium_framebuffer_multisample',
2195 'pepper_interface': 'FramebufferBlit',
2196 'pepper_name': 'BlitFramebufferEXT',
2197 'defer_reads': True,
2198 'defer_draws': True,
2199 'trace_level': 1,
2201 'BufferData': {
2202 'type': 'Manual',
2203 'data_transfer_methods': ['shm'],
2204 'client_test': False,
2205 'trace_level': 2,
2207 'BufferSubData': {
2208 'type': 'Data',
2209 'client_test': False,
2210 'decoder_func': 'DoBufferSubData',
2211 'data_transfer_methods': ['shm'],
2212 'trace_level': 2,
2214 'CheckFramebufferStatus': {
2215 'type': 'Is',
2216 'decoder_func': 'DoCheckFramebufferStatus',
2217 'gl_test_func': 'glCheckFramebufferStatusEXT',
2218 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2219 'result': ['GLenum'],
2221 'Clear': {
2222 'decoder_func': 'DoClear',
2223 'defer_draws': True,
2224 'trace_level': 2,
2226 'ClearBufferiv': {
2227 'type': 'PUT',
2228 'use_count_func': True,
2229 'count': 4,
2230 'unsafe': True,
2231 'trace_level': 2,
2233 'ClearBufferuiv': {
2234 'type': 'PUT',
2235 'count': 4,
2236 'unsafe': True,
2237 'trace_level': 2,
2239 'ClearBufferfv': {
2240 'type': 'PUT',
2241 'use_count_func': True,
2242 'count': 4,
2243 'unsafe': True,
2244 'trace_level': 2,
2246 'ClearBufferfi': {
2247 'unsafe': True,
2248 'trace_level': 2,
2250 'ClearColor': {
2251 'type': 'StateSet',
2252 'state': 'ClearColor',
2254 'ClearDepthf': {
2255 'type': 'StateSet',
2256 'state': 'ClearDepthf',
2257 'decoder_func': 'glClearDepth',
2258 'gl_test_func': 'glClearDepth',
2259 'valid_args': {
2260 '0': '0.5f'
2263 'ClientWaitSync': {
2264 'type': 'Custom',
2265 'data_transfer_methods': ['shm'],
2266 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2267 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2268 'unsafe': True,
2269 'result': ['GLenum'],
2270 'trace_level': 2,
2272 'ColorMask': {
2273 'type': 'StateSet',
2274 'state': 'ColorMask',
2275 'no_gl': True,
2276 'expectation': False,
2278 'ConsumeTextureCHROMIUM': {
2279 'decoder_func': 'DoConsumeTextureCHROMIUM',
2280 'impl_func': False,
2281 'type': 'PUT',
2282 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2283 'unit_test': False,
2284 'client_test': False,
2285 'extension': "CHROMIUM_texture_mailbox",
2286 'chromium': True,
2287 'trace_level': 2,
2289 'CopyBufferSubData': {
2290 'unsafe': True,
2292 'CreateAndConsumeTextureCHROMIUM': {
2293 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2294 'impl_func': False,
2295 'type': 'HandWritten',
2296 'data_transfer_methods': ['immediate'],
2297 'unit_test': False,
2298 'client_test': False,
2299 'extension': "CHROMIUM_texture_mailbox",
2300 'chromium': True,
2301 'trace_level': 2,
2303 'GenValuebuffersCHROMIUM': {
2304 'type': 'GENn',
2305 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2306 'resource_type': 'Valuebuffer',
2307 'resource_types': 'Valuebuffers',
2308 'unit_test': False,
2309 'extension': True,
2310 'chromium': True,
2312 'DeleteValuebuffersCHROMIUM': {
2313 'type': 'DELn',
2314 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2315 'resource_type': 'Valuebuffer',
2316 'resource_types': 'Valuebuffers',
2317 'unit_test': False,
2318 'extension': True,
2319 'chromium': True,
2321 'IsValuebufferCHROMIUM': {
2322 'type': 'Is',
2323 'decoder_func': 'DoIsValuebufferCHROMIUM',
2324 'expectation': False,
2325 'extension': True,
2326 'chromium': True,
2328 'BindValuebufferCHROMIUM': {
2329 'type': 'Bind',
2330 'decoder_func': 'DoBindValueBufferCHROMIUM',
2331 'gen_func': 'GenValueBuffersCHROMIUM',
2332 'unit_test': False,
2333 'extension': True,
2334 'chromium': True,
2336 'SubscribeValueCHROMIUM': {
2337 'decoder_func': 'DoSubscribeValueCHROMIUM',
2338 'unit_test': False,
2339 'extension': True,
2340 'chromium': True,
2342 'PopulateSubscribedValuesCHROMIUM': {
2343 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2344 'unit_test': False,
2345 'extension': True,
2346 'chromium': True,
2348 'UniformValuebufferCHROMIUM': {
2349 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2350 'unit_test': False,
2351 'extension': True,
2352 'chromium': True,
2354 'ClearStencil': {
2355 'type': 'StateSet',
2356 'state': 'ClearStencil',
2358 'EnableFeatureCHROMIUM': {
2359 'type': 'Custom',
2360 'data_transfer_methods': ['shm'],
2361 'decoder_func': 'DoEnableFeatureCHROMIUM',
2362 'expectation': False,
2363 'cmd_args': 'GLuint bucket_id, GLint* result',
2364 'result': ['GLint'],
2365 'extension': True,
2366 'chromium': True,
2367 'pepper_interface': 'ChromiumEnableFeature',
2369 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2370 'CompressedTexImage2D': {
2371 'type': 'Manual',
2372 'data_transfer_methods': ['bucket', 'shm'],
2373 'trace_level': 1,
2375 'CompressedTexSubImage2D': {
2376 'type': 'Data',
2377 'data_transfer_methods': ['bucket', 'shm'],
2378 'decoder_func': 'DoCompressedTexSubImage2D',
2379 'trace_level': 1,
2381 'CopyTexImage2D': {
2382 'decoder_func': 'DoCopyTexImage2D',
2383 'unit_test': False,
2384 'defer_reads': True,
2385 'trace_level': 1,
2387 'CopyTexSubImage2D': {
2388 'decoder_func': 'DoCopyTexSubImage2D',
2389 'defer_reads': True,
2390 'trace_level': 1,
2392 'CompressedTexImage3D': {
2393 'type': 'Manual',
2394 'data_transfer_methods': ['bucket', 'shm'],
2395 'unsafe': True,
2396 'trace_level': 1,
2398 'CompressedTexSubImage3D': {
2399 'type': 'Data',
2400 'data_transfer_methods': ['bucket', 'shm'],
2401 'decoder_func': 'DoCompressedTexSubImage3D',
2402 'unsafe': True,
2403 'trace_level': 1,
2405 'CopyTexSubImage3D': {
2406 'defer_reads': True,
2407 'unsafe': True,
2408 'trace_level': 1,
2410 'CreateImageCHROMIUM': {
2411 'type': 'Manual',
2412 'cmd_args':
2413 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2414 'GLenum internalformat',
2415 'result': ['GLuint'],
2416 'client_test': False,
2417 'gen_cmd': False,
2418 'expectation': False,
2419 'extension': "CHROMIUM_image",
2420 'chromium': True,
2421 'trace_level': 1,
2423 'DestroyImageCHROMIUM': {
2424 'type': 'Manual',
2425 'client_test': False,
2426 'gen_cmd': False,
2427 'extension': "CHROMIUM_image",
2428 'chromium': True,
2429 'trace_level': 1,
2431 'CreateGpuMemoryBufferImageCHROMIUM': {
2432 'type': 'Manual',
2433 'cmd_args':
2434 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2435 'result': ['GLuint'],
2436 'client_test': False,
2437 'gen_cmd': False,
2438 'expectation': False,
2439 'extension': "CHROMIUM_image",
2440 'chromium': True,
2441 'trace_level': 1,
2443 'CreateProgram': {
2444 'type': 'Create',
2445 'client_test': False,
2447 'CreateShader': {
2448 'type': 'Create',
2449 'client_test': False,
2451 'BlendColor': {
2452 'type': 'StateSet',
2453 'state': 'BlendColor',
2455 'BlendEquation': {
2456 'type': 'StateSetRGBAlpha',
2457 'state': 'BlendEquation',
2458 'valid_args': {
2459 '0': 'GL_FUNC_SUBTRACT'
2462 'BlendEquationSeparate': {
2463 'type': 'StateSet',
2464 'state': 'BlendEquation',
2465 'valid_args': {
2466 '0': 'GL_FUNC_SUBTRACT'
2469 'BlendFunc': {
2470 'type': 'StateSetRGBAlpha',
2471 'state': 'BlendFunc',
2473 'BlendFuncSeparate': {
2474 'type': 'StateSet',
2475 'state': 'BlendFunc',
2477 'BlendBarrierKHR': {
2478 'gl_test_func': 'glBlendBarrierKHR',
2479 'extension': True,
2480 'extension_flag': 'blend_equation_advanced',
2481 'client_test': False,
2483 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2484 'StencilFunc': {
2485 'type': 'StateSetFrontBack',
2486 'state': 'StencilFunc',
2488 'StencilFuncSeparate': {
2489 'type': 'StateSetFrontBackSeparate',
2490 'state': 'StencilFunc',
2492 'StencilOp': {
2493 'type': 'StateSetFrontBack',
2494 'state': 'StencilOp',
2495 'valid_args': {
2496 '1': 'GL_INCR'
2499 'StencilOpSeparate': {
2500 'type': 'StateSetFrontBackSeparate',
2501 'state': 'StencilOp',
2502 'valid_args': {
2503 '1': 'GL_INCR'
2506 'Hint': {
2507 'type': 'StateSetNamedParameter',
2508 'state': 'Hint',
2510 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2511 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2512 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2513 'LineWidth': {
2514 'type': 'StateSet',
2515 'state': 'LineWidth',
2516 'valid_args': {
2517 '0': '0.5f'
2520 'PolygonOffset': {
2521 'type': 'StateSet',
2522 'state': 'PolygonOffset',
2524 'DeleteBuffers': {
2525 'type': 'DELn',
2526 'gl_test_func': 'glDeleteBuffersARB',
2527 'resource_type': 'Buffer',
2528 'resource_types': 'Buffers',
2530 'DeleteFramebuffers': {
2531 'type': 'DELn',
2532 'gl_test_func': 'glDeleteFramebuffersEXT',
2533 'resource_type': 'Framebuffer',
2534 'resource_types': 'Framebuffers',
2535 'trace_level': 2,
2537 'DeleteProgram': { 'type': 'Delete' },
2538 'DeleteRenderbuffers': {
2539 'type': 'DELn',
2540 'gl_test_func': 'glDeleteRenderbuffersEXT',
2541 'resource_type': 'Renderbuffer',
2542 'resource_types': 'Renderbuffers',
2543 'trace_level': 2,
2545 'DeleteSamplers': {
2546 'type': 'DELn',
2547 'resource_type': 'Sampler',
2548 'resource_types': 'Samplers',
2549 'unsafe': True,
2551 'DeleteShader': { 'type': 'Delete' },
2552 'DeleteSync': {
2553 'type': 'Delete',
2554 'cmd_args': 'GLuint sync',
2555 'resource_type': 'Sync',
2556 'unsafe': True,
2558 'DeleteTextures': {
2559 'type': 'DELn',
2560 'resource_type': 'Texture',
2561 'resource_types': 'Textures',
2563 'DeleteTransformFeedbacks': {
2564 'type': 'DELn',
2565 'resource_type': 'TransformFeedback',
2566 'resource_types': 'TransformFeedbacks',
2567 'unsafe': True,
2569 'DepthRangef': {
2570 'decoder_func': 'DoDepthRangef',
2571 'gl_test_func': 'glDepthRange',
2573 'DepthMask': {
2574 'type': 'StateSet',
2575 'state': 'DepthMask',
2576 'no_gl': True,
2577 'expectation': False,
2579 'DetachShader': {'decoder_func': 'DoDetachShader'},
2580 'Disable': {
2581 'decoder_func': 'DoDisable',
2582 'impl_func': False,
2583 'client_test': False,
2585 'DisableVertexAttribArray': {
2586 'decoder_func': 'DoDisableVertexAttribArray',
2587 'impl_decl': False,
2589 'DrawArrays': {
2590 'type': 'Manual',
2591 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2592 'defer_draws': True,
2593 'trace_level': 2,
2595 'DrawElements': {
2596 'type': 'Manual',
2597 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2598 'GLenumIndexType type, GLuint index_offset',
2599 'client_test': False,
2600 'defer_draws': True,
2601 'trace_level': 2,
2603 'DrawRangeElements': {
2604 'type': 'Manual',
2605 'gen_cmd': 'False',
2606 'unsafe': True,
2608 'Enable': {
2609 'decoder_func': 'DoEnable',
2610 'impl_func': False,
2611 'client_test': False,
2613 'EnableVertexAttribArray': {
2614 'decoder_func': 'DoEnableVertexAttribArray',
2615 'impl_decl': False,
2617 'FenceSync': {
2618 'type': 'Create',
2619 'client_test': False,
2620 'unsafe': True,
2621 'trace_level': 1,
2623 'Finish': {
2624 'impl_func': False,
2625 'client_test': False,
2626 'decoder_func': 'DoFinish',
2627 'defer_reads': True,
2628 'trace_level': 1,
2630 'Flush': {
2631 'impl_func': False,
2632 'decoder_func': 'DoFlush',
2633 'trace_level': 1,
2635 'FramebufferRenderbuffer': {
2636 'decoder_func': 'DoFramebufferRenderbuffer',
2637 'gl_test_func': 'glFramebufferRenderbufferEXT',
2638 'trace_level': 1,
2640 'FramebufferTexture2D': {
2641 'decoder_func': 'DoFramebufferTexture2D',
2642 'gl_test_func': 'glFramebufferTexture2DEXT',
2643 'trace_level': 1,
2645 'FramebufferTexture2DMultisampleEXT': {
2646 'decoder_func': 'DoFramebufferTexture2DMultisample',
2647 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2648 'expectation': False,
2649 'unit_test': False,
2650 'extension_flag': 'multisampled_render_to_texture',
2651 'trace_level': 1,
2653 'FramebufferTextureLayer': {
2654 'decoder_func': 'DoFramebufferTextureLayer',
2655 'unsafe': True,
2656 'trace_level': 1,
2658 'GenerateMipmap': {
2659 'decoder_func': 'DoGenerateMipmap',
2660 'gl_test_func': 'glGenerateMipmapEXT',
2661 'trace_level': 1,
2663 'GenBuffers': {
2664 'type': 'GENn',
2665 'gl_test_func': 'glGenBuffersARB',
2666 'resource_type': 'Buffer',
2667 'resource_types': 'Buffers',
2669 'GenMailboxCHROMIUM': {
2670 'type': 'HandWritten',
2671 'impl_func': False,
2672 'extension': "CHROMIUM_texture_mailbox",
2673 'chromium': True,
2675 'GenFramebuffers': {
2676 'type': 'GENn',
2677 'gl_test_func': 'glGenFramebuffersEXT',
2678 'resource_type': 'Framebuffer',
2679 'resource_types': 'Framebuffers',
2681 'GenRenderbuffers': {
2682 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2683 'resource_type': 'Renderbuffer',
2684 'resource_types': 'Renderbuffers',
2686 'GenSamplers': {
2687 'type': 'GENn',
2688 'gl_test_func': 'glGenSamplers',
2689 'resource_type': 'Sampler',
2690 'resource_types': 'Samplers',
2691 'unsafe': True,
2693 'GenTextures': {
2694 'type': 'GENn',
2695 'gl_test_func': 'glGenTextures',
2696 'resource_type': 'Texture',
2697 'resource_types': 'Textures',
2699 'GenTransformFeedbacks': {
2700 'type': 'GENn',
2701 'gl_test_func': 'glGenTransformFeedbacks',
2702 'resource_type': 'TransformFeedback',
2703 'resource_types': 'TransformFeedbacks',
2704 'unsafe': True,
2706 'GetActiveAttrib': {
2707 'type': 'Custom',
2708 'data_transfer_methods': ['shm'],
2709 'cmd_args':
2710 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2711 'void* result',
2712 'result': [
2713 'int32_t success',
2714 'int32_t size',
2715 'uint32_t type',
2718 'GetActiveUniform': {
2719 'type': 'Custom',
2720 'data_transfer_methods': ['shm'],
2721 'cmd_args':
2722 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2723 'void* result',
2724 'result': [
2725 'int32_t success',
2726 'int32_t size',
2727 'uint32_t type',
2730 'GetActiveUniformBlockiv': {
2731 'type': 'Custom',
2732 'data_transfer_methods': ['shm'],
2733 'result': ['SizedResult<GLint>'],
2734 'unsafe': True,
2736 'GetActiveUniformBlockName': {
2737 'type': 'Custom',
2738 'data_transfer_methods': ['shm'],
2739 'cmd_args':
2740 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2741 'void* result',
2742 'result': ['int32_t'],
2743 'unsafe': True,
2745 'GetActiveUniformsiv': {
2746 'type': 'Custom',
2747 'data_transfer_methods': ['shm'],
2748 'cmd_args':
2749 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2750 'GLint* params',
2751 'result': ['SizedResult<GLint>'],
2752 'unsafe': True,
2754 'GetAttachedShaders': {
2755 'type': 'Custom',
2756 'data_transfer_methods': ['shm'],
2757 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2758 'result': ['SizedResult<GLuint>'],
2760 'GetAttribLocation': {
2761 'type': 'Custom',
2762 'data_transfer_methods': ['shm'],
2763 'cmd_args':
2764 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2765 'result': ['GLint'],
2766 'error_return': -1,
2768 'GetFragDataLocation': {
2769 'type': 'Custom',
2770 'data_transfer_methods': ['shm'],
2771 'cmd_args':
2772 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2773 'result': ['GLint'],
2774 'error_return': -1,
2775 'unsafe': True,
2777 'GetBooleanv': {
2778 'type': 'GETn',
2779 'result': ['SizedResult<GLboolean>'],
2780 'decoder_func': 'DoGetBooleanv',
2781 'gl_test_func': 'glGetBooleanv',
2783 'GetBufferParameteri64v': {
2784 'type': 'GETn',
2785 'result': ['SizedResult<GLint64>'],
2786 'decoder_func': 'DoGetBufferParameteri64v',
2787 'expectation': False,
2788 'shadowed': True,
2789 'unsafe': True,
2791 'GetBufferParameteriv': {
2792 'type': 'GETn',
2793 'result': ['SizedResult<GLint>'],
2794 'decoder_func': 'DoGetBufferParameteriv',
2795 'expectation': False,
2796 'shadowed': True,
2798 'GetError': {
2799 'type': 'Is',
2800 'decoder_func': 'GetErrorState()->GetGLError',
2801 'impl_func': False,
2802 'result': ['GLenum'],
2803 'client_test': False,
2805 'GetFloatv': {
2806 'type': 'GETn',
2807 'result': ['SizedResult<GLfloat>'],
2808 'decoder_func': 'DoGetFloatv',
2809 'gl_test_func': 'glGetFloatv',
2811 'GetFramebufferAttachmentParameteriv': {
2812 'type': 'GETn',
2813 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2814 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2815 'result': ['SizedResult<GLint>'],
2817 'GetGraphicsResetStatusKHR': {
2818 'extension': True,
2819 'client_test': False,
2820 'gen_cmd': False,
2821 'trace_level': 1,
2823 'GetInteger64v': {
2824 'type': 'GETn',
2825 'result': ['SizedResult<GLint64>'],
2826 'client_test': False,
2827 'decoder_func': 'DoGetInteger64v',
2828 'unsafe': True
2830 'GetIntegerv': {
2831 'type': 'GETn',
2832 'result': ['SizedResult<GLint>'],
2833 'decoder_func': 'DoGetIntegerv',
2834 'client_test': False,
2836 'GetInteger64i_v': {
2837 'type': 'GETn',
2838 'result': ['SizedResult<GLint64>'],
2839 'client_test': False,
2840 'unsafe': True
2842 'GetIntegeri_v': {
2843 'type': 'GETn',
2844 'result': ['SizedResult<GLint>'],
2845 'client_test': False,
2846 'unsafe': True
2848 'GetInternalformativ': {
2849 'type': 'Custom',
2850 'data_transfer_methods': ['shm'],
2851 'result': ['SizedResult<GLint>'],
2852 'cmd_args':
2853 'GLenumRenderBufferTarget target, GLenumRenderBufferFormat format, '
2854 'GLenumInternalFormatParameter pname, GLint* params',
2855 'unsafe': True,
2857 'GetMaxValueInBufferCHROMIUM': {
2858 'type': 'Is',
2859 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2860 'result': ['GLuint'],
2861 'unit_test': False,
2862 'client_test': False,
2863 'extension': True,
2864 'chromium': True,
2865 'impl_func': False,
2867 'GetProgramiv': {
2868 'type': 'GETn',
2869 'decoder_func': 'DoGetProgramiv',
2870 'result': ['SizedResult<GLint>'],
2871 'expectation': False,
2873 'GetProgramInfoCHROMIUM': {
2874 'type': 'Custom',
2875 'expectation': False,
2876 'impl_func': False,
2877 'extension': True,
2878 'chromium': True,
2879 'client_test': False,
2880 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2881 'result': [
2882 'uint32_t link_status',
2883 'uint32_t num_attribs',
2884 'uint32_t num_uniforms',
2887 'GetProgramInfoLog': {
2888 'type': 'STRn',
2889 'expectation': False,
2891 'GetRenderbufferParameteriv': {
2892 'type': 'GETn',
2893 'decoder_func': 'DoGetRenderbufferParameteriv',
2894 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2895 'result': ['SizedResult<GLint>'],
2897 'GetSamplerParameterfv': {
2898 'type': 'GETn',
2899 'result': ['SizedResult<GLfloat>'],
2900 'id_mapping': [ 'Sampler' ],
2901 'unsafe': True,
2903 'GetSamplerParameteriv': {
2904 'type': 'GETn',
2905 'result': ['SizedResult<GLint>'],
2906 'id_mapping': [ 'Sampler' ],
2907 'unsafe': True,
2909 'GetShaderiv': {
2910 'type': 'GETn',
2911 'decoder_func': 'DoGetShaderiv',
2912 'result': ['SizedResult<GLint>'],
2914 'GetShaderInfoLog': {
2915 'type': 'STRn',
2916 'get_len_func': 'glGetShaderiv',
2917 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2918 'unit_test': False,
2920 'GetShaderPrecisionFormat': {
2921 'type': 'Custom',
2922 'data_transfer_methods': ['shm'],
2923 'cmd_args':
2924 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2925 'void* result',
2926 'result': [
2927 'int32_t success',
2928 'int32_t min_range',
2929 'int32_t max_range',
2930 'int32_t precision',
2933 'GetShaderSource': {
2934 'type': 'STRn',
2935 'get_len_func': 'DoGetShaderiv',
2936 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2937 'unit_test': False,
2938 'client_test': False,
2940 'GetString': {
2941 'type': 'Custom',
2942 'client_test': False,
2943 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2945 'GetSynciv': {
2946 'type': 'GETn',
2947 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2948 'result': ['SizedResult<GLint>'],
2949 'id_mapping': ['Sync'],
2950 'unsafe': True,
2952 'GetTexParameterfv': {
2953 'type': 'GETn',
2954 'decoder_func': 'DoGetTexParameterfv',
2955 'result': ['SizedResult<GLfloat>']
2957 'GetTexParameteriv': {
2958 'type': 'GETn',
2959 'decoder_func': 'DoGetTexParameteriv',
2960 'result': ['SizedResult<GLint>']
2962 'GetTranslatedShaderSourceANGLE': {
2963 'type': 'STRn',
2964 'get_len_func': 'DoGetShaderiv',
2965 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2966 'unit_test': False,
2967 'extension': True,
2969 'GetUniformBlockIndex': {
2970 'type': 'Custom',
2971 'data_transfer_methods': ['shm'],
2972 'cmd_args':
2973 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2974 'result': ['GLuint'],
2975 'error_return': 'GL_INVALID_INDEX',
2976 'unsafe': True,
2978 'GetUniformBlocksCHROMIUM': {
2979 'type': 'Custom',
2980 'expectation': False,
2981 'impl_func': False,
2982 'extension': True,
2983 'chromium': True,
2984 'client_test': False,
2985 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2986 'result': ['uint32_t'],
2987 'unsafe': True,
2989 'GetUniformsES3CHROMIUM': {
2990 'type': 'Custom',
2991 'expectation': False,
2992 'impl_func': False,
2993 'extension': True,
2994 'chromium': True,
2995 'client_test': False,
2996 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2997 'result': ['uint32_t'],
2998 'unsafe': True,
3000 'GetTransformFeedbackVarying': {
3001 'type': 'Custom',
3002 'data_transfer_methods': ['shm'],
3003 'cmd_args':
3004 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
3005 'void* result',
3006 'result': [
3007 'int32_t success',
3008 'int32_t size',
3009 'uint32_t type',
3011 'unsafe': True,
3013 'GetTransformFeedbackVaryingsCHROMIUM': {
3014 'type': 'Custom',
3015 'expectation': False,
3016 'impl_func': False,
3017 'extension': True,
3018 'chromium': True,
3019 'client_test': False,
3020 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3021 'result': ['uint32_t'],
3022 'unsafe': True,
3024 'GetUniformfv': {
3025 'type': 'Custom',
3026 'data_transfer_methods': ['shm'],
3027 'result': ['SizedResult<GLfloat>'],
3029 'GetUniformiv': {
3030 'type': 'Custom',
3031 'data_transfer_methods': ['shm'],
3032 'result': ['SizedResult<GLint>'],
3034 'GetUniformuiv': {
3035 'type': 'Custom',
3036 'data_transfer_methods': ['shm'],
3037 'result': ['SizedResult<GLuint>'],
3038 'unsafe': True,
3040 'GetUniformIndices': {
3041 'type': 'Custom',
3042 'data_transfer_methods': ['shm'],
3043 'result': ['SizedResult<GLuint>'],
3044 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
3045 'GLuint* indices',
3046 'unsafe': True,
3048 'GetUniformLocation': {
3049 'type': 'Custom',
3050 'data_transfer_methods': ['shm'],
3051 'cmd_args':
3052 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
3053 'result': ['GLint'],
3054 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
3056 'GetVertexAttribfv': {
3057 'type': 'GETn',
3058 'result': ['SizedResult<GLfloat>'],
3059 'impl_decl': False,
3060 'decoder_func': 'DoGetVertexAttribfv',
3061 'expectation': False,
3062 'client_test': False,
3064 'GetVertexAttribiv': {
3065 'type': 'GETn',
3066 'result': ['SizedResult<GLint>'],
3067 'impl_decl': False,
3068 'decoder_func': 'DoGetVertexAttribiv',
3069 'expectation': False,
3070 'client_test': False,
3072 'GetVertexAttribIiv': {
3073 'type': 'GETn',
3074 'result': ['SizedResult<GLint>'],
3075 'impl_decl': False,
3076 'decoder_func': 'DoGetVertexAttribIiv',
3077 'expectation': False,
3078 'client_test': False,
3079 'unsafe': True,
3081 'GetVertexAttribIuiv': {
3082 'type': 'GETn',
3083 'result': ['SizedResult<GLuint>'],
3084 'impl_decl': False,
3085 'decoder_func': 'DoGetVertexAttribIuiv',
3086 'expectation': False,
3087 'client_test': False,
3088 'unsafe': True,
3090 'GetVertexAttribPointerv': {
3091 'type': 'Custom',
3092 'data_transfer_methods': ['shm'],
3093 'result': ['SizedResult<GLuint>'],
3094 'client_test': False,
3096 'InvalidateFramebuffer': {
3097 'type': 'PUTn',
3098 'count': 1,
3099 'client_test': False,
3100 'unit_test': False,
3101 'unsafe': True,
3103 'InvalidateSubFramebuffer': {
3104 'type': 'PUTn',
3105 'count': 1,
3106 'client_test': False,
3107 'unit_test': False,
3108 'unsafe': True,
3110 'IsBuffer': {
3111 'type': 'Is',
3112 'decoder_func': 'DoIsBuffer',
3113 'expectation': False,
3115 'IsEnabled': {
3116 'type': 'Is',
3117 'decoder_func': 'DoIsEnabled',
3118 'client_test': False,
3119 'impl_func': False,
3120 'expectation': False,
3122 'IsFramebuffer': {
3123 'type': 'Is',
3124 'decoder_func': 'DoIsFramebuffer',
3125 'expectation': False,
3127 'IsProgram': {
3128 'type': 'Is',
3129 'decoder_func': 'DoIsProgram',
3130 'expectation': False,
3132 'IsRenderbuffer': {
3133 'type': 'Is',
3134 'decoder_func': 'DoIsRenderbuffer',
3135 'expectation': False,
3137 'IsShader': {
3138 'type': 'Is',
3139 'decoder_func': 'DoIsShader',
3140 'expectation': False,
3142 'IsSampler': {
3143 'type': 'Is',
3144 'id_mapping': [ 'Sampler' ],
3145 'expectation': False,
3146 'unsafe': True,
3148 'IsSync': {
3149 'type': 'Is',
3150 'id_mapping': [ 'Sync' ],
3151 'cmd_args': 'GLuint sync',
3152 'expectation': False,
3153 'unsafe': True,
3155 'IsTexture': {
3156 'type': 'Is',
3157 'decoder_func': 'DoIsTexture',
3158 'expectation': False,
3160 'IsTransformFeedback': {
3161 'type': 'Is',
3162 'id_mapping': [ 'TransformFeedback' ],
3163 'expectation': False,
3164 'unsafe': True,
3166 'LinkProgram': {
3167 'decoder_func': 'DoLinkProgram',
3168 'impl_func': False,
3169 'trace_level': 1,
3171 'MapBufferCHROMIUM': {
3172 'gen_cmd': False,
3173 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3174 'chromium': True,
3175 'client_test': False,
3176 'trace_level': 1,
3178 'MapBufferSubDataCHROMIUM': {
3179 'gen_cmd': False,
3180 'extension': True,
3181 'chromium': True,
3182 'client_test': False,
3183 'pepper_interface': 'ChromiumMapSub',
3184 'trace_level': 1,
3186 'MapTexSubImage2DCHROMIUM': {
3187 'gen_cmd': False,
3188 'extension': "CHROMIUM_sub_image",
3189 'chromium': True,
3190 'client_test': False,
3191 'pepper_interface': 'ChromiumMapSub',
3192 'trace_level': 1,
3194 'MapBufferRange': {
3195 'type': 'Custom',
3196 'data_transfer_methods': ['shm'],
3197 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3198 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3199 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3200 'uint32_t result_shm_id, uint32_t result_shm_offset',
3201 'unsafe': True,
3202 'result': ['uint32_t'],
3203 'trace_level': 1,
3205 'PauseTransformFeedback': {
3206 'unsafe': True,
3208 'PixelStorei': {'type': 'Manual'},
3209 'PostSubBufferCHROMIUM': {
3210 'type': 'Custom',
3211 'impl_func': False,
3212 'unit_test': False,
3213 'client_test': False,
3214 'extension': True,
3215 'chromium': True,
3217 'ProduceTextureCHROMIUM': {
3218 'decoder_func': 'DoProduceTextureCHROMIUM',
3219 'impl_func': False,
3220 'type': 'PUT',
3221 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3222 'unit_test': False,
3223 'client_test': False,
3224 'extension': "CHROMIUM_texture_mailbox",
3225 'chromium': True,
3226 'trace_level': 1,
3228 'ProduceTextureDirectCHROMIUM': {
3229 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3230 'impl_func': False,
3231 'type': 'PUT',
3232 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3233 'unit_test': False,
3234 'client_test': False,
3235 'extension': "CHROMIUM_texture_mailbox",
3236 'chromium': True,
3237 'trace_level': 1,
3239 'RenderbufferStorage': {
3240 'decoder_func': 'DoRenderbufferStorage',
3241 'gl_test_func': 'glRenderbufferStorageEXT',
3242 'expectation': False,
3243 'trace_level': 1,
3245 'RenderbufferStorageMultisampleCHROMIUM': {
3246 'cmd_comment':
3247 '// GL_CHROMIUM_framebuffer_multisample\n',
3248 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3249 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3250 'expectation': False,
3251 'unit_test': False,
3252 'extension_flag': 'chromium_framebuffer_multisample',
3253 'pepper_interface': 'FramebufferMultisample',
3254 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3255 'trace_level': 1,
3257 'RenderbufferStorageMultisampleEXT': {
3258 'cmd_comment':
3259 '// GL_EXT_multisampled_render_to_texture\n',
3260 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3261 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3262 'expectation': False,
3263 'unit_test': False,
3264 'extension_flag': 'multisampled_render_to_texture',
3265 'trace_level': 1,
3267 'ReadBuffer': {
3268 'unsafe': True,
3269 'decoder_func': 'DoReadBuffer',
3270 'trace_level': 1,
3272 'ReadPixels': {
3273 'cmd_comment':
3274 '// ReadPixels has the result separated from the pixel buffer so that\n'
3275 '// it is easier to specify the result going to some specific place\n'
3276 '// that exactly fits the rectangle of pixels.\n',
3277 'type': 'Custom',
3278 'data_transfer_methods': ['shm'],
3279 'impl_func': False,
3280 'client_test': False,
3281 'cmd_args':
3282 'GLint x, GLint y, GLsizei width, GLsizei height, '
3283 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3284 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3285 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3286 'GLboolean async',
3287 'result': ['uint32_t'],
3288 'defer_reads': True,
3289 'trace_level': 1,
3291 'ReleaseShaderCompiler': {
3292 'decoder_func': 'DoReleaseShaderCompiler',
3293 'unit_test': False,
3295 'ResumeTransformFeedback': {
3296 'unsafe': True,
3298 'SamplerParameterf': {
3299 'valid_args': {
3300 '2': 'GL_NEAREST'
3302 'id_mapping': [ 'Sampler' ],
3303 'unsafe': True,
3305 'SamplerParameterfv': {
3306 'type': 'PUT',
3307 'data_value': 'GL_NEAREST',
3308 'count': 1,
3309 'gl_test_func': 'glSamplerParameterf',
3310 'decoder_func': 'DoSamplerParameterfv',
3311 'first_element_only': True,
3312 'id_mapping': [ 'Sampler' ],
3313 'unsafe': True,
3315 'SamplerParameteri': {
3316 'valid_args': {
3317 '2': 'GL_NEAREST'
3319 'id_mapping': [ 'Sampler' ],
3320 'unsafe': True,
3322 'SamplerParameteriv': {
3323 'type': 'PUT',
3324 'data_value': 'GL_NEAREST',
3325 'count': 1,
3326 'gl_test_func': 'glSamplerParameteri',
3327 'decoder_func': 'DoSamplerParameteriv',
3328 'first_element_only': True,
3329 'unsafe': True,
3331 'ShaderBinary': {
3332 'type': 'Custom',
3333 'client_test': False,
3335 'ShaderSource': {
3336 'type': 'PUTSTR',
3337 'decoder_func': 'DoShaderSource',
3338 'expectation': False,
3339 'data_transfer_methods': ['bucket'],
3340 'cmd_args':
3341 'GLuint shader, const char** str',
3342 'pepper_args':
3343 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3345 'StencilMask': {
3346 'type': 'StateSetFrontBack',
3347 'state': 'StencilMask',
3348 'no_gl': True,
3349 'expectation': False,
3351 'StencilMaskSeparate': {
3352 'type': 'StateSetFrontBackSeparate',
3353 'state': 'StencilMask',
3354 'no_gl': True,
3355 'expectation': False,
3357 'SwapBuffers': {
3358 'impl_func': False,
3359 'decoder_func': 'DoSwapBuffers',
3360 'unit_test': False,
3361 'client_test': False,
3362 'extension': True,
3363 'trace_level': 1,
3365 'SwapInterval': {
3366 'impl_func': False,
3367 'decoder_func': 'DoSwapInterval',
3368 'unit_test': False,
3369 'client_test': False,
3370 'extension': True,
3371 'trace_level': 1,
3373 'TexImage2D': {
3374 'type': 'Manual',
3375 'data_transfer_methods': ['shm'],
3376 'client_test': False,
3377 'trace_level': 2,
3379 'TexImage3D': {
3380 'type': 'Manual',
3381 'data_transfer_methods': ['shm'],
3382 'client_test': False,
3383 'unsafe': True,
3384 'trace_level': 2,
3386 'TexParameterf': {
3387 'decoder_func': 'DoTexParameterf',
3388 'valid_args': {
3389 '2': 'GL_NEAREST'
3392 'TexParameteri': {
3393 'decoder_func': 'DoTexParameteri',
3394 'valid_args': {
3395 '2': 'GL_NEAREST'
3398 'TexParameterfv': {
3399 'type': 'PUT',
3400 'data_value': 'GL_NEAREST',
3401 'count': 1,
3402 'decoder_func': 'DoTexParameterfv',
3403 'gl_test_func': 'glTexParameterf',
3404 'first_element_only': True,
3406 'TexParameteriv': {
3407 'type': 'PUT',
3408 'data_value': 'GL_NEAREST',
3409 'count': 1,
3410 'decoder_func': 'DoTexParameteriv',
3411 'gl_test_func': 'glTexParameteri',
3412 'first_element_only': True,
3414 'TexStorage3D': {
3415 'unsafe': True,
3416 'trace_level': 2,
3418 'TexSubImage2D': {
3419 'type': 'Manual',
3420 'data_transfer_methods': ['shm'],
3421 'client_test': False,
3422 'trace_level': 2,
3423 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3424 'GLint xoffset, GLint yoffset, '
3425 'GLsizei width, GLsizei height, '
3426 'GLenumTextureFormat format, GLenumPixelType type, '
3427 'const void* pixels, GLboolean internal'
3429 'TexSubImage3D': {
3430 'type': 'Manual',
3431 'data_transfer_methods': ['shm'],
3432 'client_test': False,
3433 'trace_level': 2,
3434 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3435 'GLint xoffset, GLint yoffset, GLint zoffset, '
3436 'GLsizei width, GLsizei height, GLsizei depth, '
3437 'GLenumTextureFormat format, GLenumPixelType type, '
3438 'const void* pixels, GLboolean internal',
3439 'unsafe': True,
3441 'TransformFeedbackVaryings': {
3442 'type': 'PUTSTR',
3443 'data_transfer_methods': ['bucket'],
3444 'decoder_func': 'DoTransformFeedbackVaryings',
3445 'cmd_args':
3446 'GLuint program, const char** varyings, GLenum buffermode',
3447 'unsafe': True,
3449 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3450 'Uniform1fv': {
3451 'type': 'PUTn',
3452 'count': 1,
3453 'decoder_func': 'DoUniform1fv',
3455 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3456 'Uniform1iv': {
3457 'type': 'PUTn',
3458 'count': 1,
3459 'decoder_func': 'DoUniform1iv',
3460 'unit_test': False,
3462 'Uniform1ui': {
3463 'type': 'PUTXn',
3464 'count': 1,
3465 'unsafe': True,
3467 'Uniform1uiv': {
3468 'type': 'PUTn',
3469 'count': 1,
3470 'unsafe': True,
3472 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3473 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3474 'Uniform2fv': {
3475 'type': 'PUTn',
3476 'count': 2,
3477 'decoder_func': 'DoUniform2fv',
3479 'Uniform2iv': {
3480 'type': 'PUTn',
3481 'count': 2,
3482 'decoder_func': 'DoUniform2iv',
3484 'Uniform2ui': {
3485 'type': 'PUTXn',
3486 'count': 2,
3487 'unsafe': True,
3489 'Uniform2uiv': {
3490 'type': 'PUTn',
3491 'count': 2,
3492 'unsafe': True,
3494 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3495 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3496 'Uniform3fv': {
3497 'type': 'PUTn',
3498 'count': 3,
3499 'decoder_func': 'DoUniform3fv',
3501 'Uniform3iv': {
3502 'type': 'PUTn',
3503 'count': 3,
3504 'decoder_func': 'DoUniform3iv',
3506 'Uniform3ui': {
3507 'type': 'PUTXn',
3508 'count': 3,
3509 'unsafe': True,
3511 'Uniform3uiv': {
3512 'type': 'PUTn',
3513 'count': 3,
3514 'unsafe': True,
3516 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3517 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3518 'Uniform4fv': {
3519 'type': 'PUTn',
3520 'count': 4,
3521 'decoder_func': 'DoUniform4fv',
3523 'Uniform4iv': {
3524 'type': 'PUTn',
3525 'count': 4,
3526 'decoder_func': 'DoUniform4iv',
3528 'Uniform4ui': {
3529 'type': 'PUTXn',
3530 'count': 4,
3531 'unsafe': True,
3533 'Uniform4uiv': {
3534 'type': 'PUTn',
3535 'count': 4,
3536 'unsafe': True,
3538 'UniformMatrix2fv': {
3539 'type': 'PUTn',
3540 'count': 4,
3541 'decoder_func': 'DoUniformMatrix2fv',
3543 'UniformMatrix2x3fv': {
3544 'type': 'PUTn',
3545 'count': 6,
3546 'unsafe': True,
3548 'UniformMatrix2x4fv': {
3549 'type': 'PUTn',
3550 'count': 8,
3551 'unsafe': True,
3553 'UniformMatrix3fv': {
3554 'type': 'PUTn',
3555 'count': 9,
3556 'decoder_func': 'DoUniformMatrix3fv',
3558 'UniformMatrix3x2fv': {
3559 'type': 'PUTn',
3560 'count': 6,
3561 'unsafe': True,
3563 'UniformMatrix3x4fv': {
3564 'type': 'PUTn',
3565 'count': 12,
3566 'unsafe': True,
3568 'UniformMatrix4fv': {
3569 'type': 'PUTn',
3570 'count': 16,
3571 'decoder_func': 'DoUniformMatrix4fv',
3573 'UniformMatrix4x2fv': {
3574 'type': 'PUTn',
3575 'count': 8,
3576 'unsafe': True,
3578 'UniformMatrix4x3fv': {
3579 'type': 'PUTn',
3580 'count': 12,
3581 'unsafe': True,
3583 'UniformBlockBinding': {
3584 'type': 'Custom',
3585 'impl_func': False,
3586 'unsafe': True,
3588 'UnmapBufferCHROMIUM': {
3589 'gen_cmd': False,
3590 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3591 'chromium': True,
3592 'client_test': False,
3593 'trace_level': 1,
3595 'UnmapBufferSubDataCHROMIUM': {
3596 'gen_cmd': False,
3597 'extension': True,
3598 'chromium': True,
3599 'client_test': False,
3600 'pepper_interface': 'ChromiumMapSub',
3601 'trace_level': 1,
3603 'UnmapBuffer': {
3604 'type': 'Custom',
3605 'unsafe': True,
3606 'trace_level': 1,
3608 'UnmapTexSubImage2DCHROMIUM': {
3609 'gen_cmd': False,
3610 'extension': "CHROMIUM_sub_image",
3611 'chromium': True,
3612 'client_test': False,
3613 'pepper_interface': 'ChromiumMapSub',
3614 'trace_level': 1,
3616 'UseProgram': {
3617 'type': 'Bind',
3618 'decoder_func': 'DoUseProgram',
3620 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3621 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3622 'VertexAttrib1fv': {
3623 'type': 'PUT',
3624 'count': 1,
3625 'decoder_func': 'DoVertexAttrib1fv',
3627 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3628 'VertexAttrib2fv': {
3629 'type': 'PUT',
3630 'count': 2,
3631 'decoder_func': 'DoVertexAttrib2fv',
3633 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3634 'VertexAttrib3fv': {
3635 'type': 'PUT',
3636 'count': 3,
3637 'decoder_func': 'DoVertexAttrib3fv',
3639 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3640 'VertexAttrib4fv': {
3641 'type': 'PUT',
3642 'count': 4,
3643 'decoder_func': 'DoVertexAttrib4fv',
3645 'VertexAttribI4i': {
3646 'unsafe': True,
3647 'decoder_func': 'DoVertexAttribI4i',
3649 'VertexAttribI4iv': {
3650 'type': 'PUT',
3651 'count': 4,
3652 'unsafe': True,
3653 'decoder_func': 'DoVertexAttribI4iv',
3655 'VertexAttribI4ui': {
3656 'unsafe': True,
3657 'decoder_func': 'DoVertexAttribI4ui',
3659 'VertexAttribI4uiv': {
3660 'type': 'PUT',
3661 'count': 4,
3662 'unsafe': True,
3663 'decoder_func': 'DoVertexAttribI4uiv',
3665 'VertexAttribIPointer': {
3666 'type': 'Manual',
3667 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3668 'GLenumVertexAttribIType type, GLsizei stride, '
3669 'GLuint offset',
3670 'client_test': False,
3671 'unsafe': True,
3673 'VertexAttribPointer': {
3674 'type': 'Manual',
3675 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3676 'GLenumVertexAttribType type, GLboolean normalized, '
3677 'GLsizei stride, GLuint offset',
3678 'client_test': False,
3680 'WaitSync': {
3681 'type': 'Custom',
3682 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3683 'GLuint timeout_0, GLuint timeout_1',
3684 'impl_func': False,
3685 'client_test': False,
3686 'unsafe': True,
3687 'trace_level': 1,
3689 'Scissor': {
3690 'type': 'StateSet',
3691 'state': 'Scissor',
3693 'Viewport': {
3694 'decoder_func': 'DoViewport',
3696 'ResizeCHROMIUM': {
3697 'type': 'Custom',
3698 'impl_func': False,
3699 'unit_test': False,
3700 'extension': True,
3701 'chromium': True,
3702 'trace_level': 1,
3704 'GetRequestableExtensionsCHROMIUM': {
3705 'type': 'Custom',
3706 'impl_func': False,
3707 'cmd_args': 'uint32_t bucket_id',
3708 'extension': True,
3709 'chromium': True,
3711 'RequestExtensionCHROMIUM': {
3712 'type': 'Custom',
3713 'impl_func': False,
3714 'client_test': False,
3715 'cmd_args': 'uint32_t bucket_id',
3716 'extension': True,
3717 'chromium': True,
3719 'RateLimitOffscreenContextCHROMIUM': {
3720 'gen_cmd': False,
3721 'extension': True,
3722 'chromium': True,
3723 'client_test': False,
3725 'CreateStreamTextureCHROMIUM': {
3726 'type': 'HandWritten',
3727 'impl_func': False,
3728 'gen_cmd': False,
3729 'extension': True,
3730 'chromium': True,
3731 'trace_level': 1,
3733 'TexImageIOSurface2DCHROMIUM': {
3734 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3735 'unit_test': False,
3736 'extension': True,
3737 'chromium': True,
3738 'trace_level': 1,
3740 'CopyTextureCHROMIUM': {
3741 'decoder_func': 'DoCopyTextureCHROMIUM',
3742 'unit_test': False,
3743 'extension': "CHROMIUM_copy_texture",
3744 'chromium': True,
3745 'trace_level': 2,
3747 'CopySubTextureCHROMIUM': {
3748 'decoder_func': 'DoCopySubTextureCHROMIUM',
3749 'unit_test': False,
3750 'extension': "CHROMIUM_copy_texture",
3751 'chromium': True,
3752 'trace_level': 2,
3754 'CompressedCopyTextureCHROMIUM': {
3755 'decoder_func': 'DoCompressedCopyTextureCHROMIUM',
3756 'unit_test': False,
3757 'extension': True,
3758 'chromium': True,
3760 'TexStorage2DEXT': {
3761 'unit_test': False,
3762 'extension': True,
3763 'decoder_func': 'DoTexStorage2DEXT',
3764 'trace_level': 2,
3766 'DrawArraysInstancedANGLE': {
3767 'type': 'Manual',
3768 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3769 'GLsizei primcount',
3770 'extension': True,
3771 'unit_test': False,
3772 'pepper_interface': 'InstancedArrays',
3773 'defer_draws': True,
3774 'trace_level': 2,
3776 'DrawBuffersEXT': {
3777 'type': 'PUTn',
3778 'decoder_func': 'DoDrawBuffersEXT',
3779 'count': 1,
3780 'client_test': False,
3781 'unit_test': False,
3782 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3783 # work without.
3784 'extension': True,
3785 'pepper_interface': 'DrawBuffers',
3786 'trace_level': 2,
3788 'DrawElementsInstancedANGLE': {
3789 'type': 'Manual',
3790 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3791 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3792 'extension': True,
3793 'unit_test': False,
3794 'client_test': False,
3795 'pepper_interface': 'InstancedArrays',
3796 'defer_draws': True,
3797 'trace_level': 2,
3799 'VertexAttribDivisorANGLE': {
3800 'type': 'Manual',
3801 'cmd_args': 'GLuint index, GLuint divisor',
3802 'extension': True,
3803 'unit_test': False,
3804 'pepper_interface': 'InstancedArrays',
3806 'GenQueriesEXT': {
3807 'type': 'GENn',
3808 'gl_test_func': 'glGenQueriesARB',
3809 'resource_type': 'Query',
3810 'resource_types': 'Queries',
3811 'unit_test': False,
3812 'pepper_interface': 'Query',
3813 'not_shared': 'True',
3814 'extension': "occlusion_query_EXT",
3816 'DeleteQueriesEXT': {
3817 'type': 'DELn',
3818 'gl_test_func': 'glDeleteQueriesARB',
3819 'resource_type': 'Query',
3820 'resource_types': 'Queries',
3821 'unit_test': False,
3822 'pepper_interface': 'Query',
3823 'extension': "occlusion_query_EXT",
3825 'IsQueryEXT': {
3826 'gen_cmd': False,
3827 'client_test': False,
3828 'pepper_interface': 'Query',
3829 'extension': "occlusion_query_EXT",
3831 'BeginQueryEXT': {
3832 'type': 'Manual',
3833 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3834 'data_transfer_methods': ['shm'],
3835 'gl_test_func': 'glBeginQuery',
3836 'pepper_interface': 'Query',
3837 'extension': "occlusion_query_EXT",
3839 'BeginTransformFeedback': {
3840 'unsafe': True,
3842 'EndQueryEXT': {
3843 'type': 'Manual',
3844 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3845 'gl_test_func': 'glEndnQuery',
3846 'client_test': False,
3847 'pepper_interface': 'Query',
3848 'extension': "occlusion_query_EXT",
3850 'EndTransformFeedback': {
3851 'unsafe': True,
3853 'FlushDriverCachesCHROMIUM': {
3854 'decoder_func': 'DoFlushDriverCachesCHROMIUM',
3855 'unit_test': False,
3856 'extension': True,
3857 'chromium': True,
3858 'trace_level': 1,
3860 'GetQueryivEXT': {
3861 'gen_cmd': False,
3862 'client_test': False,
3863 'gl_test_func': 'glGetQueryiv',
3864 'pepper_interface': 'Query',
3865 'extension': "occlusion_query_EXT",
3867 'QueryCounterEXT' : {
3868 'type': 'Manual',
3869 'cmd_args': 'GLidQuery id, GLenumQueryTarget target, '
3870 'void* sync_data, GLuint submit_count',
3871 'data_transfer_methods': ['shm'],
3872 'gl_test_func': 'glQueryCounter',
3873 'extension': "disjoint_timer_query_EXT",
3875 'GetQueryObjectuivEXT': {
3876 'gen_cmd': False,
3877 'client_test': False,
3878 'gl_test_func': 'glGetQueryObjectuiv',
3879 'pepper_interface': 'Query',
3880 'extension': "occlusion_query_EXT",
3882 'GetQueryObjectui64vEXT': {
3883 'gen_cmd': False,
3884 'client_test': False,
3885 'gl_test_func': 'glGetQueryObjectui64v',
3886 'extension': "disjoint_timer_query_EXT",
3888 'BindUniformLocationCHROMIUM': {
3889 'type': 'GLchar',
3890 'extension': True,
3891 'data_transfer_methods': ['bucket'],
3892 'needs_size': True,
3893 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3895 'InsertEventMarkerEXT': {
3896 'type': 'GLcharN',
3897 'decoder_func': 'DoInsertEventMarkerEXT',
3898 'expectation': False,
3899 'extension': True,
3901 'PushGroupMarkerEXT': {
3902 'type': 'GLcharN',
3903 'decoder_func': 'DoPushGroupMarkerEXT',
3904 'expectation': False,
3905 'extension': True,
3907 'PopGroupMarkerEXT': {
3908 'decoder_func': 'DoPopGroupMarkerEXT',
3909 'expectation': False,
3910 'extension': True,
3911 'impl_func': False,
3914 'GenVertexArraysOES': {
3915 'type': 'GENn',
3916 'extension': True,
3917 'gl_test_func': 'glGenVertexArraysOES',
3918 'resource_type': 'VertexArray',
3919 'resource_types': 'VertexArrays',
3920 'unit_test': False,
3921 'pepper_interface': 'VertexArrayObject',
3923 'BindVertexArrayOES': {
3924 'type': 'Bind',
3925 'extension': True,
3926 'gl_test_func': 'glBindVertexArrayOES',
3927 'decoder_func': 'DoBindVertexArrayOES',
3928 'gen_func': 'GenVertexArraysOES',
3929 'unit_test': False,
3930 'client_test': False,
3931 'pepper_interface': 'VertexArrayObject',
3933 'DeleteVertexArraysOES': {
3934 'type': 'DELn',
3935 'extension': True,
3936 'gl_test_func': 'glDeleteVertexArraysOES',
3937 'resource_type': 'VertexArray',
3938 'resource_types': 'VertexArrays',
3939 'unit_test': False,
3940 'pepper_interface': 'VertexArrayObject',
3942 'IsVertexArrayOES': {
3943 'type': 'Is',
3944 'extension': True,
3945 'gl_test_func': 'glIsVertexArrayOES',
3946 'decoder_func': 'DoIsVertexArrayOES',
3947 'expectation': False,
3948 'unit_test': False,
3949 'pepper_interface': 'VertexArrayObject',
3951 'BindTexImage2DCHROMIUM': {
3952 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3953 'unit_test': False,
3954 'extension': "CHROMIUM_image",
3955 'chromium': True,
3957 'ReleaseTexImage2DCHROMIUM': {
3958 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3959 'unit_test': False,
3960 'extension': "CHROMIUM_image",
3961 'chromium': True,
3963 'ShallowFinishCHROMIUM': {
3964 'impl_func': False,
3965 'gen_cmd': False,
3966 'extension': True,
3967 'chromium': True,
3968 'client_test': False,
3970 'ShallowFlushCHROMIUM': {
3971 'impl_func': False,
3972 'gen_cmd': False,
3973 'extension': "CHROMIUM_miscellaneous",
3974 'chromium': True,
3975 'client_test': False,
3977 'OrderingBarrierCHROMIUM': {
3978 'impl_func': False,
3979 'gen_cmd': False,
3980 'extension': True,
3981 'chromium': True,
3982 'client_test': False,
3984 'TraceBeginCHROMIUM': {
3985 'type': 'Custom',
3986 'impl_func': False,
3987 'client_test': False,
3988 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3989 'extension': True,
3990 'chromium': True,
3992 'TraceEndCHROMIUM': {
3993 'impl_func': False,
3994 'client_test': False,
3995 'decoder_func': 'DoTraceEndCHROMIUM',
3996 'unit_test': False,
3997 'extension': True,
3998 'chromium': True,
4000 'AsyncTexImage2DCHROMIUM': {
4001 'type': 'Manual',
4002 'data_transfer_methods': ['shm'],
4003 'client_test': False,
4004 'cmd_args': 'GLenumTextureTarget target, GLint level, '
4005 'GLintTextureInternalFormat internalformat, '
4006 'GLsizei width, GLsizei height, '
4007 'GLintTextureBorder border, '
4008 'GLenumTextureFormat format, GLenumPixelType type, '
4009 'const void* pixels, '
4010 'uint32_t async_upload_token, '
4011 'void* sync_data',
4012 'extension': True,
4013 'chromium': True,
4014 'trace_level': 2,
4016 'AsyncTexSubImage2DCHROMIUM': {
4017 'type': 'Manual',
4018 'data_transfer_methods': ['shm'],
4019 'client_test': False,
4020 'cmd_args': 'GLenumTextureTarget target, GLint level, '
4021 'GLint xoffset, GLint yoffset, '
4022 'GLsizei width, GLsizei height, '
4023 'GLenumTextureFormat format, GLenumPixelType type, '
4024 'const void* data, '
4025 'uint32_t async_upload_token, '
4026 'void* sync_data',
4027 'extension': True,
4028 'chromium': True,
4029 'trace_level': 2,
4031 'WaitAsyncTexImage2DCHROMIUM': {
4032 'type': 'Manual',
4033 'client_test': False,
4034 'extension': True,
4035 'chromium': True,
4036 'trace_level': 1,
4038 'WaitAllAsyncTexImage2DCHROMIUM': {
4039 'type': 'Manual',
4040 'client_test': False,
4041 'extension': True,
4042 'chromium': True,
4043 'trace_level': 1,
4045 'DiscardFramebufferEXT': {
4046 'type': 'PUTn',
4047 'count': 1,
4048 'decoder_func': 'DoDiscardFramebufferEXT',
4049 'unit_test': False,
4050 'client_test': False,
4051 'extension_flag': 'ext_discard_framebuffer',
4052 'trace_level': 2,
4054 'LoseContextCHROMIUM': {
4055 'decoder_func': 'DoLoseContextCHROMIUM',
4056 'unit_test': False,
4057 'extension': True,
4058 'chromium': True,
4059 'trace_level': 1,
4061 'InsertSyncPointCHROMIUM': {
4062 'type': 'HandWritten',
4063 'impl_func': False,
4064 'extension': "CHROMIUM_sync_point",
4065 'chromium': True,
4066 'trace_level': 1,
4068 'WaitSyncPointCHROMIUM': {
4069 'type': 'Custom',
4070 'impl_func': True,
4071 'extension': "CHROMIUM_sync_point",
4072 'chromium': True,
4073 'trace_level': 1,
4075 'DiscardBackbufferCHROMIUM': {
4076 'type': 'Custom',
4077 'impl_func': True,
4078 'extension': True,
4079 'chromium': True,
4080 'trace_level': 2,
4082 'ScheduleOverlayPlaneCHROMIUM': {
4083 'type': 'Custom',
4084 'impl_func': True,
4085 'unit_test': False,
4086 'client_test': False,
4087 'extension': True,
4088 'chromium': True,
4090 'MatrixLoadfCHROMIUM': {
4091 'type': 'PUT',
4092 'count': 16,
4093 'data_type': 'GLfloat',
4094 'decoder_func': 'DoMatrixLoadfCHROMIUM',
4095 'gl_test_func': 'glMatrixLoadfEXT',
4096 'chromium': True,
4097 'extension': True,
4098 'extension_flag': 'chromium_path_rendering',
4100 'MatrixLoadIdentityCHROMIUM': {
4101 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
4102 'gl_test_func': 'glMatrixLoadIdentityEXT',
4103 'chromium': True,
4104 'extension': True,
4105 'extension_flag': 'chromium_path_rendering',
4107 'GenPathsCHROMIUM': {
4108 'type': 'Custom',
4109 'cmd_args': 'GLuint first_client_id, GLsizei range',
4110 'chromium': True,
4111 'extension': True,
4112 'extension_flag': 'chromium_path_rendering',
4114 'DeletePathsCHROMIUM': {
4115 'type': 'Custom',
4116 'cmd_args': 'GLuint first_client_id, GLsizei range',
4117 'impl_func': False,
4118 'unit_test': False,
4119 'chromium': True,
4120 'extension': True,
4121 'extension_flag': 'chromium_path_rendering',
4123 'IsPathCHROMIUM': {
4124 'type': 'Is',
4125 'decoder_func': 'DoIsPathCHROMIUM',
4126 'gl_test_func': 'glIsPathNV',
4127 'chromium': True,
4128 'extension': True,
4129 'extension_flag': 'chromium_path_rendering',
4131 'PathCommandsCHROMIUM': {
4132 'type': 'Manual',
4133 'immediate': False,
4134 'chromium': True,
4135 'extension': True,
4136 'extension_flag': 'chromium_path_rendering',
4138 'PathParameterfCHROMIUM': {
4139 'type': 'Custom',
4140 'chromium': True,
4141 'extension': True,
4142 'extension_flag': 'chromium_path_rendering',
4144 'PathParameteriCHROMIUM': {
4145 'type': 'Custom',
4146 'chromium': True,
4147 'extension': True,
4148 'extension_flag': 'chromium_path_rendering',
4150 'PathStencilFuncCHROMIUM': {
4151 'type': 'StateSet',
4152 'state': 'PathStencilFuncCHROMIUM',
4153 'decoder_func': 'glPathStencilFuncNV',
4154 'chromium': True,
4155 'extension': True,
4156 'extension_flag': 'chromium_path_rendering',
4158 'StencilFillPathCHROMIUM': {
4159 'type': 'Custom',
4160 'chromium': True,
4161 'extension': True,
4162 'extension_flag': 'chromium_path_rendering',
4164 'StencilStrokePathCHROMIUM': {
4165 'type': 'Custom',
4166 'chromium': True,
4167 'extension': True,
4168 'extension_flag': 'chromium_path_rendering',
4170 'CoverFillPathCHROMIUM': {
4171 'type': 'Custom',
4172 'chromium': True,
4173 'extension': True,
4174 'extension_flag': 'chromium_path_rendering',
4176 'CoverStrokePathCHROMIUM': {
4177 'type': 'Custom',
4178 'chromium': True,
4179 'extension': True,
4180 'extension_flag': 'chromium_path_rendering',
4182 'StencilThenCoverFillPathCHROMIUM': {
4183 'type': 'Custom',
4184 'chromium': True,
4185 'extension': True,
4186 'extension_flag': 'chromium_path_rendering',
4188 'StencilThenCoverStrokePathCHROMIUM': {
4189 'type': 'Custom',
4190 'chromium': True,
4191 'extension': True,
4192 'extension_flag': 'chromium_path_rendering',
4198 def Grouper(n, iterable, fillvalue=None):
4199 """Collect data into fixed-length chunks or blocks"""
4200 args = [iter(iterable)] * n
4201 return itertools.izip_longest(fillvalue=fillvalue, *args)
4204 def SplitWords(input_string):
4205 """Split by '_' if found, otherwise split at uppercase/numeric chars.
4207 Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
4208 "Case"], and "Vector3" into ["Vector", "3"].
4210 if input_string.find('_') > -1:
4211 # 'some_TEXT_' -> 'some TEXT'
4212 return input_string.replace('_', ' ').strip().split()
4213 else:
4214 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
4215 # mixed case.
4216 # look for capitalization to cut input_strings
4217 # 'SomeText' -> 'Some Text'
4218 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
4219 # 'Vector3' -> 'Vector 3'
4220 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
4221 return input_string.split()
4223 def ToUnderscore(input_string):
4224 """converts CamelCase to camel_case."""
4225 words = SplitWords(input_string)
4226 return '_'.join([word.lower() for word in words])
4228 def CachedStateName(item):
4229 if item.get('cached', False):
4230 return 'cached_' + item['name']
4231 return item['name']
4233 def ToGLExtensionString(extension_flag):
4234 """Returns GL-type extension string of a extension flag."""
4235 if extension_flag == "oes_compressed_etc1_rgb8_texture":
4236 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
4237 # unfortunate.
4238 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
4239 'egl', 'atc', 'etc1', 'angle']
4240 parts = extension_flag.split('_')
4241 return "_".join(
4242 [part.upper() if part in uppercase_words else part for part in parts])
4244 def ToCamelCase(input_string):
4245 """converts ABC_underscore_case to ABCUnderscoreCase."""
4246 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
4248 def GetGLGetTypeConversion(result_type, value_type, value):
4249 """Makes a gl compatible type conversion string for accessing state variables.
4251 Useful when accessing state variables through glGetXXX calls.
4252 glGet documetation (for example, the manual pages):
4253 [...] If glGetIntegerv is called, [...] most floating-point values are
4254 rounded to the nearest integer value. [...]
4256 Args:
4257 result_type: the gl type to be obtained
4258 value_type: the GL type of the state variable
4259 value: the name of the state variable
4261 Returns:
4262 String that converts the state variable to desired GL type according to GL
4263 rules.
4266 if result_type == 'GLint':
4267 if value_type == 'GLfloat':
4268 return 'static_cast<GLint>(round(%s))' % value
4269 return 'static_cast<%s>(%s)' % (result_type, value)
4272 class CWriter(object):
4273 """Context manager that creates a C source file.
4275 To be used with the `with` statement. Returns a normal `file` type, open only
4276 for writing - any existing files with that name will be overwritten. It will
4277 automatically write the contents of `_LICENSE` and `_DO_NOT_EDIT_WARNING`
4278 at the beginning.
4280 Example:
4281 with CWriter("file.cpp") as myfile:
4282 myfile.write("hello")
4283 # type(myfile) == file
4285 def __init__(self, filename):
4286 self.filename = filename
4287 self._file = open(filename, 'w')
4288 self._ENTER_MSG = _LICENSE + _DO_NOT_EDIT_WARNING
4289 self._EXIT_MSG = ""
4291 def __enter__(self):
4292 self._file.write(self._ENTER_MSG)
4293 return self._file
4295 def __exit__(self, exc_type, exc_value, traceback):
4296 self._file.write(self._EXIT_MSG)
4297 self._file.close()
4300 class CHeaderWriter(CWriter):
4301 """Context manager that creates a C header file.
4303 Works the same way as CWriter, except it will also add the #ifdef guard
4304 around it. If `file_comment` is set, it will write that before the #ifdef
4305 guard.
4307 def __init__(self, filename, file_comment=None):
4308 super(CHeaderWriter, self).__init__(filename)
4309 guard = self._get_guard()
4310 if file_comment is None:
4311 file_comment = ""
4312 self._ENTER_MSG = self._ENTER_MSG + file_comment \
4313 + "#ifndef %s\n#define %s\n\n" % (guard, guard)
4314 self._EXIT_MSG = self._EXIT_MSG + "#endif // %s\n" % guard
4316 def _get_guard(self):
4317 non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
4318 base = os.path.abspath(self.filename)
4319 while os.path.basename(base) != 'src':
4320 new_base = os.path.dirname(base)
4321 assert new_base != base # Prevent infinite loop.
4322 base = new_base
4323 hpath = os.path.relpath(self.filename, base)
4324 return non_alnum_re.sub('_', hpath).upper() + '_'
4327 class TypeHandler(object):
4328 """This class emits code for a particular type of function."""
4330 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
4332 def InitFunction(self, func):
4333 """Add or adjust anything type specific for this function."""
4334 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
4335 func.AddCmdArg(DataSizeArgument('data_size'))
4337 def NeedsDataTransferFunction(self, func):
4338 """Overriden from TypeHandler."""
4339 return func.num_pointer_args >= 1
4341 def WriteStruct(self, func, f):
4342 """Writes a structure that matches the arguments to a function."""
4343 comment = func.GetInfo('cmd_comment')
4344 if not comment == None:
4345 f.write(comment)
4346 f.write("struct %s {\n" % func.name)
4347 f.write(" typedef %s ValueType;\n" % func.name)
4348 f.write(" static const CommandId kCmdId = k%s;\n" % func.name)
4349 func.WriteCmdArgFlag(f)
4350 func.WriteCmdFlag(f)
4351 f.write("\n")
4352 result = func.GetInfo('result')
4353 if not result == None:
4354 if len(result) == 1:
4355 f.write(" typedef %s Result;\n\n" % result[0])
4356 else:
4357 f.write(" struct Result {\n")
4358 for line in result:
4359 f.write(" %s;\n" % line)
4360 f.write(" };\n\n")
4362 func.WriteCmdComputeSize(f)
4363 func.WriteCmdSetHeader(f)
4364 func.WriteCmdInit(f)
4365 func.WriteCmdSet(f)
4367 f.write(" gpu::CommandHeader header;\n")
4368 args = func.GetCmdArgs()
4369 for arg in args:
4370 f.write(" %s %s;\n" % (arg.cmd_type, arg.name))
4372 consts = func.GetCmdConstants()
4373 for const in consts:
4374 f.write(" static const %s %s = %s;\n" %
4375 (const.cmd_type, const.name, const.GetConstantValue()))
4377 f.write("};\n")
4378 f.write("\n")
4380 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
4381 f.write("static_assert(sizeof(%s) == %d,\n" % (func.name, size))
4382 f.write(" \"size of %s should be %d\");\n" %
4383 (func.name, size))
4384 f.write("static_assert(offsetof(%s, header) == 0,\n" % func.name)
4385 f.write(" \"offset of %s header should be 0\");\n" %
4386 func.name)
4387 offset = _SIZE_OF_COMMAND_HEADER
4388 for arg in args:
4389 f.write("static_assert(offsetof(%s, %s) == %d,\n" %
4390 (func.name, arg.name, offset))
4391 f.write(" \"offset of %s %s should be %d\");\n" %
4392 (func.name, arg.name, offset))
4393 offset += _SIZE_OF_UINT32
4394 if not result == None and len(result) > 1:
4395 offset = 0;
4396 for line in result:
4397 parts = line.split()
4398 name = parts[-1]
4399 check = """
4400 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4401 "offset of %(cmd_name)s Result %(field_name)s should be "
4402 "%(offset)d");
4404 f.write((check.strip() + "\n") % {
4405 'cmd_name': func.name,
4406 'field_name': name,
4407 'offset': offset,
4409 offset += _SIZE_OF_UINT32
4410 f.write("\n")
4412 def WriteHandlerImplementation(self, func, f):
4413 """Writes the handler implementation for this command."""
4414 if func.IsUnsafe() and func.GetInfo('id_mapping'):
4415 code_no_gen = """ if (!group_->Get%(type)sServiceId(
4416 %(var)s, &%(service_var)s)) {
4417 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4418 return error::kNoError;
4421 code_gen = """ if (!group_->Get%(type)sServiceId(
4422 %(var)s, &%(service_var)s)) {
4423 if (!group_->bind_generates_resource()) {
4424 LOCAL_SET_GL_ERROR(
4425 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4426 return error::kNoError;
4428 GLuint client_id = %(var)s;
4429 gl%(gen_func)s(1, &%(service_var)s);
4430 Create%(type)s(client_id, %(service_var)s);
4433 gen_func = func.GetInfo('gen_func')
4434 for id_type in func.GetInfo('id_mapping'):
4435 service_var = id_type.lower()
4436 if id_type == 'Sync':
4437 service_var = "service_%s" % service_var
4438 f.write(" GLsync %s = 0;\n" % service_var)
4439 if gen_func and id_type in gen_func:
4440 f.write(code_gen % { 'type': id_type,
4441 'var': id_type.lower(),
4442 'service_var': service_var,
4443 'func': func.GetGLFunctionName(),
4444 'gen_func': gen_func })
4445 else:
4446 f.write(code_no_gen % { 'type': id_type,
4447 'var': id_type.lower(),
4448 'service_var': service_var,
4449 'func': func.GetGLFunctionName() })
4450 args = []
4451 for arg in func.GetOriginalArgs():
4452 if arg.type == "GLsync":
4453 args.append("service_%s" % arg.name)
4454 elif arg.name.endswith("size") and arg.type == "GLsizei":
4455 args.append("num_%s" % func.GetLastOriginalArg().name)
4456 elif arg.name == "length":
4457 args.append("nullptr")
4458 else:
4459 args.append(arg.name)
4460 f.write(" %s(%s);\n" %
4461 (func.GetGLFunctionName(), ", ".join(args)))
4463 def WriteCmdSizeTest(self, func, f):
4464 """Writes the size test for a command."""
4465 f.write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4467 def WriteFormatTest(self, func, f):
4468 """Writes a format test for a command."""
4469 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4470 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4471 (func.name, func.name))
4472 f.write(" void* next_cmd = cmd.Set(\n")
4473 f.write(" &cmd")
4474 args = func.GetCmdArgs()
4475 for value, arg in enumerate(args):
4476 f.write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
4477 f.write(");\n")
4478 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4479 func.name)
4480 f.write(" cmd.header.command);\n")
4481 func.type_handler.WriteCmdSizeTest(func, f)
4482 for value, arg in enumerate(args):
4483 f.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4484 (arg.type, value + 11, arg.name))
4485 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
4486 f.write(" next_cmd, sizeof(cmd));\n")
4487 f.write("}\n")
4488 f.write("\n")
4490 def WriteImmediateFormatTest(self, func, f):
4491 """Writes a format test for an immediate version of a command."""
4492 pass
4494 def WriteGetDataSizeCode(self, func, f):
4495 """Writes the code to set data_size used in validation"""
4496 pass
4498 def __WriteIdMapping(self, func, f):
4499 """Writes client side / service side ID mapping."""
4500 if not func.IsUnsafe() or not func.GetInfo('id_mapping'):
4501 return
4502 for id_type in func.GetInfo('id_mapping'):
4503 f.write(" group_->Get%sServiceId(%s, &%s);\n" %
4504 (id_type, id_type.lower(), id_type.lower()))
4506 def WriteImmediateHandlerImplementation (self, func, f):
4507 """Writes the handler impl for the immediate version of a command."""
4508 self.__WriteIdMapping(func, f)
4509 f.write(" %s(%s);\n" %
4510 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4512 def WriteBucketHandlerImplementation (self, func, f):
4513 """Writes the handler impl for the bucket version of a command."""
4514 self.__WriteIdMapping(func, f)
4515 f.write(" %s(%s);\n" %
4516 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4518 def WriteServiceHandlerFunctionHeader(self, func, f):
4519 """Writes function header for service implementation handlers."""
4520 f.write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4521 uint32_t immediate_data_size, const void* cmd_data) {
4522 """ % {'name': func.name})
4523 if func.IsUnsafe():
4524 f.write("""if (!unsafe_es3_apis_enabled())
4525 return error::kUnknownCommand;
4526 """)
4527 f.write("""const gles2::cmds::%(name)s& c =
4528 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4529 (void)c;
4530 """ % {'name': func.name})
4532 def WriteServiceImplementation(self, func, f):
4533 """Writes the service implementation for a command."""
4534 self.WriteServiceHandlerFunctionHeader(func, f)
4535 self.WriteHandlerExtensionCheck(func, f)
4536 self.WriteHandlerDeferReadWrite(func, f);
4537 if len(func.GetOriginalArgs()) > 0:
4538 last_arg = func.GetLastOriginalArg()
4539 all_but_last_arg = func.GetOriginalArgs()[:-1]
4540 for arg in all_but_last_arg:
4541 arg.WriteGetCode(f)
4542 self.WriteGetDataSizeCode(func, f)
4543 last_arg.WriteGetCode(f)
4544 func.WriteHandlerValidation(f)
4545 func.WriteHandlerImplementation(f)
4546 f.write(" return error::kNoError;\n")
4547 f.write("}\n")
4548 f.write("\n")
4550 def WriteImmediateServiceImplementation(self, func, f):
4551 """Writes the service implementation for an immediate version of command."""
4552 self.WriteServiceHandlerFunctionHeader(func, f)
4553 self.WriteHandlerExtensionCheck(func, f)
4554 self.WriteHandlerDeferReadWrite(func, f);
4555 for arg in func.GetOriginalArgs():
4556 if arg.IsPointer():
4557 self.WriteGetDataSizeCode(func, f)
4558 arg.WriteGetCode(f)
4559 func.WriteHandlerValidation(f)
4560 func.WriteHandlerImplementation(f)
4561 f.write(" return error::kNoError;\n")
4562 f.write("}\n")
4563 f.write("\n")
4565 def WriteBucketServiceImplementation(self, func, f):
4566 """Writes the service implementation for a bucket version of command."""
4567 self.WriteServiceHandlerFunctionHeader(func, f)
4568 self.WriteHandlerExtensionCheck(func, f)
4569 self.WriteHandlerDeferReadWrite(func, f);
4570 for arg in func.GetCmdArgs():
4571 arg.WriteGetCode(f)
4572 func.WriteHandlerValidation(f)
4573 func.WriteHandlerImplementation(f)
4574 f.write(" return error::kNoError;\n")
4575 f.write("}\n")
4576 f.write("\n")
4578 def WriteHandlerExtensionCheck(self, func, f):
4579 if func.GetInfo('extension_flag'):
4580 f.write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
4581 f.write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4582 " \"function not available\");\n" % func.original_name)
4583 f.write(" return error::kNoError;")
4584 f.write(" }\n\n")
4586 def WriteHandlerDeferReadWrite(self, func, f):
4587 """Writes the code to handle deferring reads or writes."""
4588 defer_draws = func.GetInfo('defer_draws')
4589 defer_reads = func.GetInfo('defer_reads')
4590 if defer_draws or defer_reads:
4591 f.write(" error::Error error;\n")
4592 if defer_draws:
4593 f.write(" error = WillAccessBoundFramebufferForDraw();\n")
4594 f.write(" if (error != error::kNoError)\n")
4595 f.write(" return error;\n")
4596 if defer_reads:
4597 f.write(" error = WillAccessBoundFramebufferForRead();\n")
4598 f.write(" if (error != error::kNoError)\n")
4599 f.write(" return error;\n")
4601 def WriteValidUnitTest(self, func, f, test, *extras):
4602 """Writes a valid unit test for the service implementation."""
4603 if func.GetInfo('expectation') == False:
4604 test = self._remove_expected_call_re.sub('', test)
4605 name = func.name
4606 arg_strings = [
4607 arg.GetValidArg(func) \
4608 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4610 gl_arg_strings = [
4611 arg.GetValidGLArg(func) \
4612 for arg in func.GetOriginalArgs()
4614 gl_func_name = func.GetGLTestFunctionName()
4615 vars = {
4616 'name':name,
4617 'gl_func_name': gl_func_name,
4618 'args': ", ".join(arg_strings),
4619 'gl_args': ", ".join(gl_arg_strings),
4621 for extra in extras:
4622 vars.update(extra)
4623 old_test = ""
4624 while (old_test != test):
4625 old_test = test
4626 test = test % vars
4627 f.write(test % vars)
4629 def WriteInvalidUnitTest(self, func, f, test, *extras):
4630 """Writes an invalid unit test for the service implementation."""
4631 if func.IsUnsafe():
4632 return
4633 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
4634 # Service implementation does not test constants, as they are not part of
4635 # the call in the service side.
4636 if invalid_arg.IsConstant():
4637 continue
4639 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
4640 for value_index in range(0, num_invalid_values):
4641 arg_strings = []
4642 parse_result = "kNoError"
4643 gl_error = None
4644 for arg in func.GetOriginalArgs():
4645 if arg.IsConstant():
4646 continue
4647 if invalid_arg is arg:
4648 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
4649 value_index)
4650 else:
4651 arg_string = arg.GetValidArg(func)
4652 arg_strings.append(arg_string)
4653 gl_arg_strings = []
4654 for arg in func.GetOriginalArgs():
4655 gl_arg_strings.append("_")
4656 gl_func_name = func.GetGLTestFunctionName()
4657 gl_error_test = ''
4658 if not gl_error == None:
4659 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4661 vars = {
4662 'name': func.name,
4663 'arg_index': invalid_arg_index,
4664 'value_index': value_index,
4665 'gl_func_name': gl_func_name,
4666 'args': ", ".join(arg_strings),
4667 'all_but_last_args': ", ".join(arg_strings[:-1]),
4668 'gl_args': ", ".join(gl_arg_strings),
4669 'parse_result': parse_result,
4670 'gl_error_test': gl_error_test,
4672 for extra in extras:
4673 vars.update(extra)
4674 f.write(test % vars)
4676 def WriteServiceUnitTest(self, func, f, *extras):
4677 """Writes the service unit test for a command."""
4679 if func.name == 'Enable':
4680 valid_test = """
4681 TEST_P(%(test_name)s, %(name)sValidArgs) {
4682 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4683 SpecializedSetup<cmds::%(name)s, 0>(true);
4684 cmds::%(name)s cmd;
4685 cmd.Init(%(args)s);"""
4686 elif func.name == 'Disable':
4687 valid_test = """
4688 TEST_P(%(test_name)s, %(name)sValidArgs) {
4689 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4690 SpecializedSetup<cmds::%(name)s, 0>(true);
4691 cmds::%(name)s cmd;
4692 cmd.Init(%(args)s);"""
4693 else:
4694 valid_test = """
4695 TEST_P(%(test_name)s, %(name)sValidArgs) {
4696 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4697 SpecializedSetup<cmds::%(name)s, 0>(true);
4698 cmds::%(name)s cmd;
4699 cmd.Init(%(args)s);"""
4700 if func.IsUnsafe():
4701 valid_test += """
4702 decoder_->set_unsafe_es3_apis_enabled(true);
4703 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4704 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4705 decoder_->set_unsafe_es3_apis_enabled(false);
4706 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4709 else:
4710 valid_test += """
4711 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4712 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4715 self.WriteValidUnitTest(func, f, valid_test, *extras)
4717 if not func.IsUnsafe():
4718 invalid_test = """
4719 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4720 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4721 SpecializedSetup<cmds::%(name)s, 0>(false);
4722 cmds::%(name)s cmd;
4723 cmd.Init(%(args)s);
4724 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4727 self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
4729 def WriteImmediateServiceUnitTest(self, func, f, *extras):
4730 """Writes the service unit test for an immediate command."""
4731 f.write("// TODO(gman): %s\n" % func.name)
4733 def WriteImmediateValidationCode(self, func, f):
4734 """Writes the validation code for an immediate version of a command."""
4735 pass
4737 def WriteBucketServiceUnitTest(self, func, f, *extras):
4738 """Writes the service unit test for a bucket command."""
4739 f.write("// TODO(gman): %s\n" % func.name)
4741 def WriteGLES2ImplementationDeclaration(self, func, f):
4742 """Writes the GLES2 Implemention declaration."""
4743 impl_decl = func.GetInfo('impl_decl')
4744 if impl_decl == None or impl_decl == True:
4745 f.write("%s %s(%s) override;\n" %
4746 (func.return_type, func.original_name,
4747 func.MakeTypedOriginalArgString("")))
4748 f.write("\n")
4750 def WriteGLES2CLibImplementation(self, func, f):
4751 f.write("%s GL_APIENTRY GLES2%s(%s) {\n" %
4752 (func.return_type, func.name,
4753 func.MakeTypedOriginalArgString("")))
4754 result_string = "return "
4755 if func.return_type == "void":
4756 result_string = ""
4757 f.write(" %sgles2::GetGLContext()->%s(%s);\n" %
4758 (result_string, func.original_name,
4759 func.MakeOriginalArgString("")))
4760 f.write("}\n")
4762 def WriteGLES2Header(self, func, f):
4763 """Writes a re-write macro for GLES"""
4764 f.write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
4766 def WriteClientGLCallLog(self, func, f):
4767 """Writes a logging macro for the client side code."""
4768 comma = ""
4769 if len(func.GetOriginalArgs()):
4770 comma = " << "
4771 f.write(
4772 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4773 (func.original_name, comma, func.MakeLogArgString()))
4775 def WriteClientGLReturnLog(self, func, f):
4776 """Writes the return value logging code."""
4777 if func.return_type != "void":
4778 f.write(' GPU_CLIENT_LOG("return:" << result)\n')
4780 def WriteGLES2ImplementationHeader(self, func, f):
4781 """Writes the GLES2 Implemention."""
4782 self.WriteGLES2ImplementationDeclaration(func, f)
4784 def WriteGLES2TraceImplementationHeader(self, func, f):
4785 """Writes the GLES2 Trace Implemention header."""
4786 f.write("%s %s(%s) override;\n" %
4787 (func.return_type, func.original_name,
4788 func.MakeTypedOriginalArgString("")))
4790 def WriteGLES2TraceImplementation(self, func, f):
4791 """Writes the GLES2 Trace Implemention."""
4792 f.write("%s GLES2TraceImplementation::%s(%s) {\n" %
4793 (func.return_type, func.original_name,
4794 func.MakeTypedOriginalArgString("")))
4795 result_string = "return "
4796 if func.return_type == "void":
4797 result_string = ""
4798 f.write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4799 func.name)
4800 f.write(" %sgl_->%s(%s);\n" %
4801 (result_string, func.name, func.MakeOriginalArgString("")))
4802 f.write("}\n")
4803 f.write("\n")
4805 def WriteGLES2Implementation(self, func, f):
4806 """Writes the GLES2 Implemention."""
4807 impl_func = func.GetInfo('impl_func')
4808 impl_decl = func.GetInfo('impl_decl')
4809 gen_cmd = func.GetInfo('gen_cmd')
4810 if (func.can_auto_generate and
4811 (impl_func == None or impl_func == True) and
4812 (impl_decl == None or impl_decl == True) and
4813 (gen_cmd == None or gen_cmd == True)):
4814 f.write("%s GLES2Implementation::%s(%s) {\n" %
4815 (func.return_type, func.original_name,
4816 func.MakeTypedOriginalArgString("")))
4817 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4818 self.WriteClientGLCallLog(func, f)
4819 func.WriteDestinationInitalizationValidation(f)
4820 for arg in func.GetOriginalArgs():
4821 arg.WriteClientSideValidationCode(f, func)
4822 f.write(" helper_->%s(%s);\n" %
4823 (func.name, func.MakeHelperArgString("")))
4824 f.write(" CheckGLError();\n")
4825 self.WriteClientGLReturnLog(func, f)
4826 f.write("}\n")
4827 f.write("\n")
4829 def WriteGLES2InterfaceHeader(self, func, f):
4830 """Writes the GLES2 Interface."""
4831 f.write("virtual %s %s(%s) = 0;\n" %
4832 (func.return_type, func.original_name,
4833 func.MakeTypedOriginalArgString("")))
4835 def WriteMojoGLES2ImplHeader(self, func, f):
4836 """Writes the Mojo GLES2 implementation header."""
4837 f.write("%s %s(%s) override;\n" %
4838 (func.return_type, func.original_name,
4839 func.MakeTypedOriginalArgString("")))
4841 def WriteMojoGLES2Impl(self, func, f):
4842 """Writes the Mojo GLES2 implementation."""
4843 f.write("%s MojoGLES2Impl::%s(%s) {\n" %
4844 (func.return_type, func.original_name,
4845 func.MakeTypedOriginalArgString("")))
4846 extensions = ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4847 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4848 "occlusion_query_EXT", "CHROMIUM_image",
4849 "CHROMIUM_copy_texture",
4850 "CHROMIUM_pixel_transfer_buffer_object"]
4851 if func.IsCoreGLFunction() or func.GetInfo("extension") in extensions:
4852 f.write("MojoGLES2MakeCurrent(context_);");
4853 func_return = "gl" + func.original_name + "(" + \
4854 func.MakeOriginalArgString("") + ");"
4855 if func.return_type == "void":
4856 f.write(func_return);
4857 else:
4858 f.write("return " + func_return);
4859 else:
4860 f.write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4861 func.original_name);
4862 if func.return_type != "void":
4863 f.write("return 0;")
4864 f.write("}")
4866 def WriteGLES2InterfaceStub(self, func, f):
4867 """Writes the GLES2 Interface stub declaration."""
4868 f.write("%s %s(%s) override;\n" %
4869 (func.return_type, func.original_name,
4870 func.MakeTypedOriginalArgString("")))
4872 def WriteGLES2InterfaceStubImpl(self, func, f):
4873 """Writes the GLES2 Interface stub declaration."""
4874 args = func.GetOriginalArgs()
4875 arg_string = ", ".join(
4876 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
4877 f.write("%s GLES2InterfaceStub::%s(%s) {\n" %
4878 (func.return_type, func.original_name, arg_string))
4879 if func.return_type != "void":
4880 f.write(" return 0;\n")
4881 f.write("}\n")
4883 def WriteGLES2ImplementationUnitTest(self, func, f):
4884 """Writes the GLES2 Implemention unit test."""
4885 client_test = func.GetInfo('client_test')
4886 if (func.can_auto_generate and
4887 (client_test == None or client_test == True)):
4888 code = """
4889 TEST_F(GLES2ImplementationTest, %(name)s) {
4890 struct Cmds {
4891 cmds::%(name)s cmd;
4893 Cmds expected;
4894 expected.cmd.Init(%(cmd_args)s);
4896 gl_->%(name)s(%(args)s);
4897 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4900 cmd_arg_strings = [
4901 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4904 gl_arg_strings = [
4905 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4908 f.write(code % {
4909 'name': func.name,
4910 'args': ", ".join(gl_arg_strings),
4911 'cmd_args': ", ".join(cmd_arg_strings),
4914 # Test constants for invalid values, as they are not tested by the
4915 # service.
4916 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
4917 if constants:
4918 code = """
4919 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4920 gl_->%(name)s(%(args)s);
4921 EXPECT_TRUE(NoCommandsWritten());
4922 EXPECT_EQ(%(gl_error)s, CheckError());
4925 for invalid_arg in constants:
4926 gl_arg_strings = []
4927 invalid = invalid_arg.GetInvalidArg(func)
4928 for arg in func.GetOriginalArgs():
4929 if arg is invalid_arg:
4930 gl_arg_strings.append(invalid[0])
4931 else:
4932 gl_arg_strings.append(arg.GetValidClientSideArg(func))
4934 f.write(code % {
4935 'name': func.name,
4936 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
4937 'args': ", ".join(gl_arg_strings),
4938 'gl_error': invalid[2],
4940 else:
4941 if client_test != False:
4942 f.write("// TODO(zmo): Implement unit test for %s\n" % func.name)
4944 def WriteDestinationInitalizationValidation(self, func, f):
4945 """Writes the client side destintion initialization validation."""
4946 for arg in func.GetOriginalArgs():
4947 arg.WriteDestinationInitalizationValidation(f, func)
4949 def WriteTraceEvent(self, func, f):
4950 f.write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4951 func.original_name)
4953 def WriteImmediateCmdComputeSize(self, func, f):
4954 """Writes the size computation code for the immediate version of a cmd."""
4955 f.write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4956 f.write(" return static_cast<uint32_t>(\n")
4957 f.write(" sizeof(ValueType) + // NOLINT\n")
4958 f.write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4959 f.write(" }\n")
4960 f.write("\n")
4962 def WriteImmediateCmdSetHeader(self, func, f):
4963 """Writes the SetHeader function for the immediate version of a cmd."""
4964 f.write(" void SetHeader(uint32_t size_in_bytes) {\n")
4965 f.write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4966 f.write(" }\n")
4967 f.write("\n")
4969 def WriteImmediateCmdInit(self, func, f):
4970 """Writes the Init function for the immediate version of a command."""
4971 raise NotImplementedError(func.name)
4973 def WriteImmediateCmdSet(self, func, f):
4974 """Writes the Set function for the immediate version of a command."""
4975 raise NotImplementedError(func.name)
4977 def WriteCmdHelper(self, func, f):
4978 """Writes the cmd helper definition for a cmd."""
4979 code = """ void %(name)s(%(typed_args)s) {
4980 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4981 if (c) {
4982 c->Init(%(args)s);
4987 f.write(code % {
4988 "name": func.name,
4989 "typed_args": func.MakeTypedCmdArgString(""),
4990 "args": func.MakeCmdArgString(""),
4993 def WriteImmediateCmdHelper(self, func, f):
4994 """Writes the cmd helper definition for the immediate version of a cmd."""
4995 code = """ void %(name)s(%(typed_args)s) {
4996 const uint32_t s = 0; // TODO(gman): compute correct size
4997 gles2::cmds::%(name)s* c =
4998 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4999 if (c) {
5000 c->Init(%(args)s);
5005 f.write(code % {
5006 "name": func.name,
5007 "typed_args": func.MakeTypedCmdArgString(""),
5008 "args": func.MakeCmdArgString(""),
5012 class StateSetHandler(TypeHandler):
5013 """Handler for commands that simply set state."""
5015 def WriteHandlerImplementation(self, func, f):
5016 """Overrriden from TypeHandler."""
5017 state_name = func.GetInfo('state')
5018 state = _STATES[state_name]
5019 states = state['states']
5020 args = func.GetOriginalArgs()
5021 for ndx,item in enumerate(states):
5022 code = []
5023 if 'range_checks' in item:
5024 for range_check in item['range_checks']:
5025 code.append("%s %s" % (args[ndx].name, range_check['check']))
5026 if 'nan_check' in item:
5027 # Drivers might generate an INVALID_VALUE error when a value is set
5028 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
5029 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
5030 # Make this behavior consistent within Chromium, and avoid leaking GL
5031 # errors by generating the error in the command buffer instead of
5032 # letting the GL driver generate it.
5033 code.append("std::isnan(%s)" % args[ndx].name)
5034 if len(code):
5035 f.write(" if (%s) {\n" % " ||\n ".join(code))
5036 f.write(
5037 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
5038 ' "%s", "%s out of range");\n' %
5039 (func.name, args[ndx].name))
5040 f.write(" return error::kNoError;\n")
5041 f.write(" }\n")
5042 code = []
5043 for ndx,item in enumerate(states):
5044 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
5045 f.write(" if (%s) {\n" % " ||\n ".join(code))
5046 for ndx,item in enumerate(states):
5047 f.write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
5048 if 'state_flag' in state:
5049 f.write(" %s = true;\n" % state['state_flag'])
5050 if not func.GetInfo("no_gl"):
5051 for ndx,item in enumerate(states):
5052 if item.get('cached', False):
5053 f.write(" state_.%s = %s;\n" %
5054 (CachedStateName(item), args[ndx].name))
5055 f.write(" %s(%s);\n" %
5056 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5057 f.write(" }\n")
5059 def WriteServiceUnitTest(self, func, f, *extras):
5060 """Overrriden from TypeHandler."""
5061 TypeHandler.WriteServiceUnitTest(self, func, f, *extras)
5062 state_name = func.GetInfo('state')
5063 state = _STATES[state_name]
5064 states = state['states']
5065 for ndx,item in enumerate(states):
5066 if 'range_checks' in item:
5067 for check_ndx, range_check in enumerate(item['range_checks']):
5068 valid_test = """
5069 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
5070 SpecializedSetup<cmds::%(name)s, 0>(false);
5071 cmds::%(name)s cmd;
5072 cmd.Init(%(args)s);
5073 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5074 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5077 name = func.name
5078 arg_strings = [
5079 arg.GetValidArg(func) \
5080 for arg in func.GetOriginalArgs() if not arg.IsConstant()
5083 arg_strings[ndx] = range_check['test_value']
5084 vars = {
5085 'name': name,
5086 'ndx': ndx,
5087 'check_ndx': check_ndx,
5088 'args': ", ".join(arg_strings),
5090 for extra in extras:
5091 vars.update(extra)
5092 f.write(valid_test % vars)
5093 if 'nan_check' in item:
5094 valid_test = """
5095 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
5096 SpecializedSetup<cmds::%(name)s, 0>(false);
5097 cmds::%(name)s cmd;
5098 cmd.Init(%(args)s);
5099 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5100 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5103 name = func.name
5104 arg_strings = [
5105 arg.GetValidArg(func) \
5106 for arg in func.GetOriginalArgs() if not arg.IsConstant()
5109 arg_strings[ndx] = 'nanf("")'
5110 vars = {
5111 'name': name,
5112 'ndx': ndx,
5113 'args': ", ".join(arg_strings),
5115 for extra in extras:
5116 vars.update(extra)
5117 f.write(valid_test % vars)
5120 class StateSetRGBAlphaHandler(TypeHandler):
5121 """Handler for commands that simply set state that have rgb/alpha."""
5123 def WriteHandlerImplementation(self, func, f):
5124 """Overrriden from TypeHandler."""
5125 state_name = func.GetInfo('state')
5126 state = _STATES[state_name]
5127 states = state['states']
5128 args = func.GetOriginalArgs()
5129 num_args = len(args)
5130 code = []
5131 for ndx,item in enumerate(states):
5132 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
5133 f.write(" if (%s) {\n" % " ||\n ".join(code))
5134 for ndx, item in enumerate(states):
5135 f.write(" state_.%s = %s;\n" %
5136 (item['name'], args[ndx % num_args].name))
5137 if 'state_flag' in state:
5138 f.write(" %s = true;\n" % state['state_flag'])
5139 if not func.GetInfo("no_gl"):
5140 f.write(" %s(%s);\n" %
5141 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5142 f.write(" }\n")
5145 class StateSetFrontBackSeparateHandler(TypeHandler):
5146 """Handler for commands that simply set state that have front/back."""
5148 def WriteHandlerImplementation(self, func, f):
5149 """Overrriden from TypeHandler."""
5150 state_name = func.GetInfo('state')
5151 state = _STATES[state_name]
5152 states = state['states']
5153 args = func.GetOriginalArgs()
5154 face = args[0].name
5155 num_args = len(args)
5156 f.write(" bool changed = false;\n")
5157 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
5158 f.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5159 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
5160 code = []
5161 for ndx, item in enumerate(group):
5162 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
5163 f.write(" changed |= %s;\n" % " ||\n ".join(code))
5164 f.write(" }\n")
5165 f.write(" if (changed) {\n")
5166 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
5167 f.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5168 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
5169 for ndx, item in enumerate(group):
5170 f.write(" state_.%s = %s;\n" %
5171 (item['name'], args[ndx + 1].name))
5172 f.write(" }\n")
5173 if 'state_flag' in state:
5174 f.write(" %s = true;\n" % state['state_flag'])
5175 if not func.GetInfo("no_gl"):
5176 f.write(" %s(%s);\n" %
5177 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5178 f.write(" }\n")
5181 class StateSetFrontBackHandler(TypeHandler):
5182 """Handler for commands that simply set state that set both front/back."""
5184 def WriteHandlerImplementation(self, func, f):
5185 """Overrriden from TypeHandler."""
5186 state_name = func.GetInfo('state')
5187 state = _STATES[state_name]
5188 states = state['states']
5189 args = func.GetOriginalArgs()
5190 num_args = len(args)
5191 code = []
5192 for group_ndx, group in enumerate(Grouper(num_args, states)):
5193 for ndx, item in enumerate(group):
5194 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
5195 f.write(" if (%s) {\n" % " ||\n ".join(code))
5196 for group_ndx, group in enumerate(Grouper(num_args, states)):
5197 for ndx, item in enumerate(group):
5198 f.write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
5199 if 'state_flag' in state:
5200 f.write(" %s = true;\n" % state['state_flag'])
5201 if not func.GetInfo("no_gl"):
5202 f.write(" %s(%s);\n" %
5203 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5204 f.write(" }\n")
5207 class StateSetNamedParameter(TypeHandler):
5208 """Handler for commands that set a state chosen with an enum parameter."""
5210 def WriteHandlerImplementation(self, func, f):
5211 """Overridden from TypeHandler."""
5212 state_name = func.GetInfo('state')
5213 state = _STATES[state_name]
5214 states = state['states']
5215 args = func.GetOriginalArgs()
5216 num_args = len(args)
5217 assert num_args == 2
5218 f.write(" switch (%s) {\n" % args[0].name)
5219 for state in states:
5220 f.write(" case %s:\n" % state['enum'])
5221 f.write(" if (state_.%s != %s) {\n" %
5222 (state['name'], args[1].name))
5223 f.write(" state_.%s = %s;\n" % (state['name'], args[1].name))
5224 if not func.GetInfo("no_gl"):
5225 f.write(" %s(%s);\n" %
5226 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5227 f.write(" }\n")
5228 f.write(" break;\n")
5229 f.write(" default:\n")
5230 f.write(" NOTREACHED();\n")
5231 f.write(" }\n")
5234 class CustomHandler(TypeHandler):
5235 """Handler for commands that are auto-generated but require minor tweaks."""
5237 def WriteServiceImplementation(self, func, f):
5238 """Overrriden from TypeHandler."""
5239 pass
5241 def WriteImmediateServiceImplementation(self, func, f):
5242 """Overrriden from TypeHandler."""
5243 pass
5245 def WriteBucketServiceImplementation(self, func, f):
5246 """Overrriden from TypeHandler."""
5247 pass
5249 def WriteServiceUnitTest(self, func, f, *extras):
5250 """Overrriden from TypeHandler."""
5251 f.write("// TODO(gman): %s\n\n" % func.name)
5253 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5254 """Overrriden from TypeHandler."""
5255 f.write("// TODO(gman): %s\n\n" % func.name)
5257 def WriteImmediateCmdGetTotalSize(self, func, f):
5258 """Overrriden from TypeHandler."""
5259 f.write(
5260 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5262 def WriteImmediateCmdInit(self, func, f):
5263 """Overrriden from TypeHandler."""
5264 f.write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5265 self.WriteImmediateCmdGetTotalSize(func, f)
5266 f.write(" SetHeader(total_size);\n")
5267 args = func.GetCmdArgs()
5268 for arg in args:
5269 f.write(" %s = _%s;\n" % (arg.name, arg.name))
5270 f.write(" }\n")
5271 f.write("\n")
5273 def WriteImmediateCmdSet(self, func, f):
5274 """Overrriden from TypeHandler."""
5275 copy_args = func.MakeCmdArgString("_", False)
5276 f.write(" void* Set(void* cmd%s) {\n" %
5277 func.MakeTypedCmdArgString("_", True))
5278 self.WriteImmediateCmdGetTotalSize(func, f)
5279 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5280 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5281 "cmd, total_size);\n")
5282 f.write(" }\n")
5283 f.write("\n")
5286 class HandWrittenHandler(CustomHandler):
5287 """Handler for comands where everything must be written by hand."""
5289 def InitFunction(self, func):
5290 """Add or adjust anything type specific for this function."""
5291 CustomHandler.InitFunction(self, func)
5292 func.can_auto_generate = False
5294 def NeedsDataTransferFunction(self, func):
5295 """Overriden from TypeHandler."""
5296 # If specified explicitly, force the data transfer method.
5297 if func.GetInfo('data_transfer_methods'):
5298 return True
5299 return False
5301 def WriteStruct(self, func, f):
5302 """Overrriden from TypeHandler."""
5303 pass
5305 def WriteDocs(self, func, f):
5306 """Overrriden from TypeHandler."""
5307 pass
5309 def WriteServiceUnitTest(self, func, f, *extras):
5310 """Overrriden from TypeHandler."""
5311 f.write("// TODO(gman): %s\n\n" % func.name)
5313 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5314 """Overrriden from TypeHandler."""
5315 f.write("// TODO(gman): %s\n\n" % func.name)
5317 def WriteBucketServiceUnitTest(self, func, f, *extras):
5318 """Overrriden from TypeHandler."""
5319 f.write("// TODO(gman): %s\n\n" % func.name)
5321 def WriteServiceImplementation(self, func, f):
5322 """Overrriden from TypeHandler."""
5323 pass
5325 def WriteImmediateServiceImplementation(self, func, f):
5326 """Overrriden from TypeHandler."""
5327 pass
5329 def WriteBucketServiceImplementation(self, func, f):
5330 """Overrriden from TypeHandler."""
5331 pass
5333 def WriteImmediateCmdHelper(self, func, f):
5334 """Overrriden from TypeHandler."""
5335 pass
5337 def WriteCmdHelper(self, func, f):
5338 """Overrriden from TypeHandler."""
5339 pass
5341 def WriteFormatTest(self, func, f):
5342 """Overrriden from TypeHandler."""
5343 f.write("// TODO(gman): Write test for %s\n" % func.name)
5345 def WriteImmediateFormatTest(self, func, f):
5346 """Overrriden from TypeHandler."""
5347 f.write("// TODO(gman): Write test for %s\n" % func.name)
5350 class ManualHandler(CustomHandler):
5351 """Handler for commands who's handlers must be written by hand."""
5353 def InitFunction(self, func):
5354 """Overrriden from TypeHandler."""
5355 if (func.name == 'CompressedTexImage2DBucket' or
5356 func.name == 'CompressedTexImage3DBucket'):
5357 func.cmd_args = func.cmd_args[:-1]
5358 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5359 else:
5360 CustomHandler.InitFunction(self, func)
5362 def WriteServiceImplementation(self, func, f):
5363 """Overrriden from TypeHandler."""
5364 pass
5366 def WriteBucketServiceImplementation(self, func, f):
5367 """Overrriden from TypeHandler."""
5368 pass
5370 def WriteServiceUnitTest(self, func, f, *extras):
5371 """Overrriden from TypeHandler."""
5372 f.write("// TODO(gman): %s\n\n" % func.name)
5374 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5375 """Overrriden from TypeHandler."""
5376 f.write("// TODO(gman): %s\n\n" % func.name)
5378 def WriteImmediateServiceImplementation(self, func, f):
5379 """Overrriden from TypeHandler."""
5380 pass
5382 def WriteImmediateFormatTest(self, func, f):
5383 """Overrriden from TypeHandler."""
5384 f.write("// TODO(gman): Implement test for %s\n" % func.name)
5386 def WriteGLES2Implementation(self, func, f):
5387 """Overrriden from TypeHandler."""
5388 if func.GetInfo('impl_func'):
5389 super(ManualHandler, self).WriteGLES2Implementation(func, f)
5391 def WriteGLES2ImplementationHeader(self, func, f):
5392 """Overrriden from TypeHandler."""
5393 f.write("%s %s(%s) override;\n" %
5394 (func.return_type, func.original_name,
5395 func.MakeTypedOriginalArgString("")))
5396 f.write("\n")
5398 def WriteImmediateCmdGetTotalSize(self, func, f):
5399 """Overrriden from TypeHandler."""
5400 # TODO(gman): Move this data to _FUNCTION_INFO?
5401 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, f)
5404 class DataHandler(TypeHandler):
5405 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5406 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5408 def InitFunction(self, func):
5409 """Overrriden from TypeHandler."""
5410 if (func.name == 'CompressedTexSubImage2DBucket' or
5411 func.name == 'CompressedTexSubImage3DBucket'):
5412 func.cmd_args = func.cmd_args[:-1]
5413 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5415 def WriteGetDataSizeCode(self, func, f):
5416 """Overrriden from TypeHandler."""
5417 # TODO(gman): Move this data to _FUNCTION_INFO?
5418 name = func.name
5419 if name.endswith("Immediate"):
5420 name = name[0:-9]
5421 if name == 'BufferData' or name == 'BufferSubData':
5422 f.write(" uint32_t data_size = size;\n")
5423 elif (name == 'CompressedTexImage2D' or
5424 name == 'CompressedTexSubImage2D' or
5425 name == 'CompressedTexImage3D' or
5426 name == 'CompressedTexSubImage3D'):
5427 f.write(" uint32_t data_size = imageSize;\n")
5428 elif (name == 'CompressedTexSubImage2DBucket' or
5429 name == 'CompressedTexSubImage3DBucket'):
5430 f.write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5431 f.write(" uint32_t data_size = bucket->size();\n")
5432 f.write(" GLsizei imageSize = data_size;\n")
5433 elif name == 'TexImage2D' or name == 'TexSubImage2D':
5434 code = """ uint32_t data_size;
5435 if (!GLES2Util::ComputeImageDataSize(
5436 width, height, format, type, unpack_alignment_, &data_size)) {
5437 return error::kOutOfBounds;
5440 f.write(code)
5441 else:
5442 f.write(
5443 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5445 def WriteImmediateCmdGetTotalSize(self, func, f):
5446 """Overrriden from TypeHandler."""
5447 pass
5449 def WriteImmediateCmdInit(self, func, f):
5450 """Overrriden from TypeHandler."""
5451 f.write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5452 self.WriteImmediateCmdGetTotalSize(func, f)
5453 f.write(" SetHeader(total_size);\n")
5454 args = func.GetCmdArgs()
5455 for arg in args:
5456 f.write(" %s = _%s;\n" % (arg.name, arg.name))
5457 f.write(" }\n")
5458 f.write("\n")
5460 def WriteImmediateCmdSet(self, func, f):
5461 """Overrriden from TypeHandler."""
5462 copy_args = func.MakeCmdArgString("_", False)
5463 f.write(" void* Set(void* cmd%s) {\n" %
5464 func.MakeTypedCmdArgString("_", True))
5465 self.WriteImmediateCmdGetTotalSize(func, f)
5466 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5467 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5468 "cmd, total_size);\n")
5469 f.write(" }\n")
5470 f.write("\n")
5472 def WriteImmediateFormatTest(self, func, f):
5473 """Overrriden from TypeHandler."""
5474 # TODO(gman): Remove this exception.
5475 f.write("// TODO(gman): Implement test for %s\n" % func.name)
5476 return
5478 def WriteServiceUnitTest(self, func, f, *extras):
5479 """Overrriden from TypeHandler."""
5480 f.write("// TODO(gman): %s\n\n" % func.name)
5482 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5483 """Overrriden from TypeHandler."""
5484 f.write("// TODO(gman): %s\n\n" % func.name)
5486 def WriteBucketServiceImplementation(self, func, f):
5487 """Overrriden from TypeHandler."""
5488 if ((not func.name == 'CompressedTexSubImage2DBucket') and
5489 (not func.name == 'CompressedTexSubImage3DBucket')):
5490 TypeHandler.WriteBucketServiceImplemenation(self, func, f)
5493 class BindHandler(TypeHandler):
5494 """Handler for glBind___ type functions."""
5496 def WriteServiceUnitTest(self, func, f, *extras):
5497 """Overrriden from TypeHandler."""
5499 if len(func.GetOriginalArgs()) == 1:
5500 valid_test = """
5501 TEST_P(%(test_name)s, %(name)sValidArgs) {
5502 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5503 SpecializedSetup<cmds::%(name)s, 0>(true);
5504 cmds::%(name)s cmd;
5505 cmd.Init(%(args)s);"""
5506 if func.IsUnsafe():
5507 valid_test += """
5508 decoder_->set_unsafe_es3_apis_enabled(true);
5509 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5510 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5511 decoder_->set_unsafe_es3_apis_enabled(false);
5512 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5515 else:
5516 valid_test += """
5517 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5518 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5521 if func.GetInfo("gen_func"):
5522 valid_test += """
5523 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5524 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5525 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5526 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5527 SpecializedSetup<cmds::%(name)s, 0>(true);
5528 cmds::%(name)s cmd;
5529 cmd.Init(kNewClientId);
5530 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5531 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5532 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5535 self.WriteValidUnitTest(func, f, valid_test, {
5536 'resource_type': func.GetOriginalArgs()[0].resource_type,
5537 'gl_gen_func_name': func.GetInfo("gen_func"),
5538 }, *extras)
5539 else:
5540 valid_test = """
5541 TEST_P(%(test_name)s, %(name)sValidArgs) {
5542 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5543 SpecializedSetup<cmds::%(name)s, 0>(true);
5544 cmds::%(name)s cmd;
5545 cmd.Init(%(args)s);"""
5546 if func.IsUnsafe():
5547 valid_test += """
5548 decoder_->set_unsafe_es3_apis_enabled(true);
5549 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5550 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5551 decoder_->set_unsafe_es3_apis_enabled(false);
5552 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5555 else:
5556 valid_test += """
5557 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5558 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5561 if func.GetInfo("gen_func"):
5562 valid_test += """
5563 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5564 EXPECT_CALL(*gl_,
5565 %(gl_func_name)s(%(gl_args_with_new_id)s));
5566 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5567 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5568 SpecializedSetup<cmds::%(name)s, 0>(true);
5569 cmds::%(name)s cmd;
5570 cmd.Init(%(args_with_new_id)s);"""
5571 if func.IsUnsafe():
5572 valid_test += """
5573 decoder_->set_unsafe_es3_apis_enabled(true);
5574 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5575 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5576 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5577 decoder_->set_unsafe_es3_apis_enabled(false);
5578 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5581 else:
5582 valid_test += """
5583 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5584 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5585 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5589 gl_args_with_new_id = []
5590 args_with_new_id = []
5591 for arg in func.GetOriginalArgs():
5592 if hasattr(arg, 'resource_type'):
5593 gl_args_with_new_id.append('kNewServiceId')
5594 args_with_new_id.append('kNewClientId')
5595 else:
5596 gl_args_with_new_id.append(arg.GetValidGLArg(func))
5597 args_with_new_id.append(arg.GetValidArg(func))
5598 self.WriteValidUnitTest(func, f, valid_test, {
5599 'args_with_new_id': ", ".join(args_with_new_id),
5600 'gl_args_with_new_id': ", ".join(gl_args_with_new_id),
5601 'resource_type': func.GetResourceIdArg().resource_type,
5602 'gl_gen_func_name': func.GetInfo("gen_func"),
5603 }, *extras)
5605 invalid_test = """
5606 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5607 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5608 SpecializedSetup<cmds::%(name)s, 0>(false);
5609 cmds::%(name)s cmd;
5610 cmd.Init(%(args)s);
5611 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5614 self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
5616 def WriteGLES2Implementation(self, func, f):
5617 """Writes the GLES2 Implemention."""
5619 impl_func = func.GetInfo('impl_func')
5620 impl_decl = func.GetInfo('impl_decl')
5622 if (func.can_auto_generate and
5623 (impl_func == None or impl_func == True) and
5624 (impl_decl == None or impl_decl == True)):
5626 f.write("%s GLES2Implementation::%s(%s) {\n" %
5627 (func.return_type, func.original_name,
5628 func.MakeTypedOriginalArgString("")))
5629 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5630 func.WriteDestinationInitalizationValidation(f)
5631 self.WriteClientGLCallLog(func, f)
5632 for arg in func.GetOriginalArgs():
5633 arg.WriteClientSideValidationCode(f, func)
5635 code = """ if (Is%(type)sReservedId(%(id)s)) {
5636 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5637 return;
5639 %(name)sHelper(%(arg_string)s);
5640 CheckGLError();
5644 name_arg = func.GetResourceIdArg()
5645 f.write(code % {
5646 'name': func.name,
5647 'arg_string': func.MakeOriginalArgString(""),
5648 'id': name_arg.name,
5649 'type': name_arg.resource_type,
5650 'lc_type': name_arg.resource_type.lower(),
5653 def WriteGLES2ImplementationUnitTest(self, func, f):
5654 """Overrriden from TypeHandler."""
5655 client_test = func.GetInfo('client_test')
5656 if client_test == False:
5657 return
5658 code = """
5659 TEST_F(GLES2ImplementationTest, %(name)s) {
5660 struct Cmds {
5661 cmds::%(name)s cmd;
5663 Cmds expected;
5664 expected.cmd.Init(%(cmd_args)s);
5666 gl_->%(name)s(%(args)s);
5667 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5668 if not func.IsUnsafe():
5669 code += """
5670 ClearCommands();
5671 gl_->%(name)s(%(args)s);
5672 EXPECT_TRUE(NoCommandsWritten());"""
5673 code += """
5676 cmd_arg_strings = [
5677 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
5679 gl_arg_strings = [
5680 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
5683 f.write(code % {
5684 'name': func.name,
5685 'args': ", ".join(gl_arg_strings),
5686 'cmd_args': ", ".join(cmd_arg_strings),
5690 class GENnHandler(TypeHandler):
5691 """Handler for glGen___ type functions."""
5693 def InitFunction(self, func):
5694 """Overrriden from TypeHandler."""
5695 pass
5697 def WriteGetDataSizeCode(self, func, f):
5698 """Overrriden from TypeHandler."""
5699 code = """ uint32_t data_size;
5700 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5701 return error::kOutOfBounds;
5704 f.write(code)
5706 def WriteHandlerImplementation (self, func, f):
5707 """Overrriden from TypeHandler."""
5708 f.write(" if (!%sHelper(n, %s)) {\n"
5709 " return error::kInvalidArguments;\n"
5710 " }\n" %
5711 (func.name, func.GetLastOriginalArg().name))
5713 def WriteImmediateHandlerImplementation(self, func, f):
5714 """Overrriden from TypeHandler."""
5715 if func.IsUnsafe():
5716 f.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5717 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5718 return error::kInvalidArguments;
5721 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5722 gl%(func_name)s(n, service_ids.get());
5723 for (GLsizei ii = 0; ii < n; ++ii) {
5724 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5726 """ % { 'func_name': func.original_name,
5727 'last_arg_name': func.GetLastOriginalArg().name,
5728 'resource_name': func.GetInfo('resource_type') })
5729 else:
5730 f.write(" if (!%sHelper(n, %s)) {\n"
5731 " return error::kInvalidArguments;\n"
5732 " }\n" %
5733 (func.original_name, func.GetLastOriginalArg().name))
5735 def WriteGLES2Implementation(self, func, f):
5736 """Overrriden from TypeHandler."""
5737 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
5738 for (GLsizei i = 0; i < n; ++i) {
5739 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5741 });""" % func.GetOriginalArgs()[1].name)
5742 args = {
5743 'log_code': log_code,
5744 'return_type': func.return_type,
5745 'name': func.original_name,
5746 'typed_args': func.MakeTypedOriginalArgString(""),
5747 'args': func.MakeOriginalArgString(""),
5748 'resource_types': func.GetInfo('resource_types'),
5749 'count_name': func.GetOriginalArgs()[0].name,
5751 f.write(
5752 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5753 args)
5754 func.WriteDestinationInitalizationValidation(f)
5755 self.WriteClientGLCallLog(func, f)
5756 for arg in func.GetOriginalArgs():
5757 arg.WriteClientSideValidationCode(f, func)
5758 not_shared = func.GetInfo('not_shared')
5759 if not_shared:
5760 alloc_code = (
5762 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5763 for (GLsizei ii = 0; ii < n; ++ii)
5764 %s[ii] = id_allocator->AllocateID();""" %
5765 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
5766 else:
5767 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5768 MakeIds(this, 0, %(args)s);""" % args)
5769 args['alloc_code'] = alloc_code
5771 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5772 %(alloc_code)s
5773 %(name)sHelper(%(args)s);
5774 helper_->%(name)sImmediate(%(args)s);
5775 if (share_group_->bind_generates_resource())
5776 helper_->CommandBufferHelper::Flush();
5777 %(log_code)s
5778 CheckGLError();
5782 f.write(code % args)
5784 def WriteGLES2ImplementationUnitTest(self, func, f):
5785 """Overrriden from TypeHandler."""
5786 code = """
5787 TEST_F(GLES2ImplementationTest, %(name)s) {
5788 GLuint ids[2] = { 0, };
5789 struct Cmds {
5790 cmds::%(name)sImmediate gen;
5791 GLuint data[2];
5793 Cmds expected;
5794 expected.gen.Init(arraysize(ids), &ids[0]);
5795 expected.data[0] = k%(types)sStartId;
5796 expected.data[1] = k%(types)sStartId + 1;
5797 gl_->%(name)s(arraysize(ids), &ids[0]);
5798 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5799 EXPECT_EQ(k%(types)sStartId, ids[0]);
5800 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5803 f.write(code % {
5804 'name': func.name,
5805 'types': func.GetInfo('resource_types'),
5808 def WriteServiceUnitTest(self, func, f, *extras):
5809 """Overrriden from TypeHandler."""
5810 valid_test = """
5811 TEST_P(%(test_name)s, %(name)sValidArgs) {
5812 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5813 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5814 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5815 SpecializedSetup<cmds::%(name)s, 0>(true);
5816 cmds::%(name)s cmd;
5817 cmd.Init(%(args)s);
5818 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5819 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5820 if func.IsUnsafe():
5821 valid_test += """
5822 GLuint service_id;
5823 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5824 EXPECT_EQ(kNewServiceId, service_id)
5827 else:
5828 valid_test += """
5829 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5832 self.WriteValidUnitTest(func, f, valid_test, {
5833 'resource_name': func.GetInfo('resource_type'),
5834 }, *extras)
5835 invalid_test = """
5836 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5837 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5838 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5839 SpecializedSetup<cmds::%(name)s, 0>(false);
5840 cmds::%(name)s cmd;
5841 cmd.Init(%(args)s);
5842 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5845 self.WriteValidUnitTest(func, f, invalid_test, {
5846 'resource_name': func.GetInfo('resource_type').lower(),
5847 }, *extras)
5849 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5850 """Overrriden from TypeHandler."""
5851 valid_test = """
5852 TEST_P(%(test_name)s, %(name)sValidArgs) {
5853 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5854 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5855 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5856 GLuint temp = kNewClientId;
5857 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5858 if func.IsUnsafe():
5859 valid_test += """
5860 decoder_->set_unsafe_es3_apis_enabled(true);"""
5861 valid_test += """
5862 cmd->Init(1, &temp);
5863 EXPECT_EQ(error::kNoError,
5864 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5865 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5866 if func.IsUnsafe():
5867 valid_test += """
5868 GLuint service_id;
5869 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5870 EXPECT_EQ(kNewServiceId, service_id);
5871 decoder_->set_unsafe_es3_apis_enabled(false);
5872 EXPECT_EQ(error::kUnknownCommand,
5873 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5876 else:
5877 valid_test += """
5878 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5881 self.WriteValidUnitTest(func, f, valid_test, {
5882 'resource_name': func.GetInfo('resource_type'),
5883 }, *extras)
5884 invalid_test = """
5885 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5886 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5887 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5888 SpecializedSetup<cmds::%(name)s, 0>(false);
5889 cmd->Init(1, &client_%(resource_name)s_id_);"""
5890 if func.IsUnsafe():
5891 invalid_test += """
5892 decoder_->set_unsafe_es3_apis_enabled(true);
5893 EXPECT_EQ(error::kInvalidArguments,
5894 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5895 decoder_->set_unsafe_es3_apis_enabled(false);
5898 else:
5899 invalid_test += """
5900 EXPECT_EQ(error::kInvalidArguments,
5901 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5904 self.WriteValidUnitTest(func, f, invalid_test, {
5905 'resource_name': func.GetInfo('resource_type').lower(),
5906 }, *extras)
5908 def WriteImmediateCmdComputeSize(self, func, f):
5909 """Overrriden from TypeHandler."""
5910 f.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5911 f.write(
5912 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5913 f.write(" }\n")
5914 f.write("\n")
5915 f.write(" static uint32_t ComputeSize(GLsizei n) {\n")
5916 f.write(" return static_cast<uint32_t>(\n")
5917 f.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5918 f.write(" }\n")
5919 f.write("\n")
5921 def WriteImmediateCmdSetHeader(self, func, f):
5922 """Overrriden from TypeHandler."""
5923 f.write(" void SetHeader(GLsizei n) {\n")
5924 f.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5925 f.write(" }\n")
5926 f.write("\n")
5928 def WriteImmediateCmdInit(self, func, f):
5929 """Overrriden from TypeHandler."""
5930 last_arg = func.GetLastOriginalArg()
5931 f.write(" void Init(%s, %s _%s) {\n" %
5932 (func.MakeTypedCmdArgString("_"),
5933 last_arg.type, last_arg.name))
5934 f.write(" SetHeader(_n);\n")
5935 args = func.GetCmdArgs()
5936 for arg in args:
5937 f.write(" %s = _%s;\n" % (arg.name, arg.name))
5938 f.write(" memcpy(ImmediateDataAddress(this),\n")
5939 f.write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5940 f.write(" }\n")
5941 f.write("\n")
5943 def WriteImmediateCmdSet(self, func, f):
5944 """Overrriden from TypeHandler."""
5945 last_arg = func.GetLastOriginalArg()
5946 copy_args = func.MakeCmdArgString("_", False)
5947 f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
5948 (func.MakeTypedCmdArgString("_", True),
5949 last_arg.type, last_arg.name))
5950 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5951 (copy_args, last_arg.name))
5952 f.write(" const uint32_t size = ComputeSize(_n);\n")
5953 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5954 "cmd, size);\n")
5955 f.write(" }\n")
5956 f.write("\n")
5958 def WriteImmediateCmdHelper(self, func, f):
5959 """Overrriden from TypeHandler."""
5960 code = """ void %(name)s(%(typed_args)s) {
5961 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5962 gles2::cmds::%(name)s* c =
5963 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5964 if (c) {
5965 c->Init(%(args)s);
5970 f.write(code % {
5971 "name": func.name,
5972 "typed_args": func.MakeTypedOriginalArgString(""),
5973 "args": func.MakeOriginalArgString(""),
5976 def WriteImmediateFormatTest(self, func, f):
5977 """Overrriden from TypeHandler."""
5978 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5979 f.write(" static GLuint ids[] = { 12, 23, 34, };\n")
5980 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5981 (func.name, func.name))
5982 f.write(" void* next_cmd = cmd.Set(\n")
5983 f.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5984 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5985 func.name)
5986 f.write(" cmd.header.command);\n")
5987 f.write(" EXPECT_EQ(sizeof(cmd) +\n")
5988 f.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5989 f.write(" cmd.header.size * 4u);\n")
5990 f.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5991 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
5992 f.write(" next_cmd, sizeof(cmd) +\n")
5993 f.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5994 f.write(" // TODO(gman): Check that ids were inserted;\n")
5995 f.write("}\n")
5996 f.write("\n")
5999 class CreateHandler(TypeHandler):
6000 """Handler for glCreate___ type functions."""
6002 def InitFunction(self, func):
6003 """Overrriden from TypeHandler."""
6004 func.AddCmdArg(Argument("client_id", 'uint32_t'))
6006 def __GetResourceType(self, func):
6007 if func.return_type == "GLsync":
6008 return "Sync"
6009 else:
6010 return func.name[6:] # Create*
6012 def WriteServiceUnitTest(self, func, f, *extras):
6013 """Overrriden from TypeHandler."""
6014 valid_test = """
6015 TEST_P(%(test_name)s, %(name)sValidArgs) {
6016 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
6017 .WillOnce(Return(%(const_service_id)s));
6018 SpecializedSetup<cmds::%(name)s, 0>(true);
6019 cmds::%(name)s cmd;
6020 cmd.Init(%(args)s%(comma)skNewClientId);"""
6021 if func.IsUnsafe():
6022 valid_test += """
6023 decoder_->set_unsafe_es3_apis_enabled(true);"""
6024 valid_test += """
6025 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6026 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6027 if func.IsUnsafe():
6028 valid_test += """
6029 %(return_type)s service_id = 0;
6030 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
6031 EXPECT_EQ(%(const_service_id)s, service_id);
6032 decoder_->set_unsafe_es3_apis_enabled(false);
6033 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
6036 else:
6037 valid_test += """
6038 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
6041 comma = ""
6042 cmd_arg_count = 0
6043 for arg in func.GetOriginalArgs():
6044 if not arg.IsConstant():
6045 cmd_arg_count += 1
6046 if cmd_arg_count:
6047 comma = ", "
6048 if func.return_type == 'GLsync':
6049 id_type_cast = ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
6050 "<GLsync>(kNewServiceId);\n ")
6051 const_service_id = "kNewServiceIdGLuint"
6052 else:
6053 id_type_cast = ""
6054 const_service_id = "kNewServiceId"
6055 self.WriteValidUnitTest(func, f, valid_test, {
6056 'comma': comma,
6057 'resource_type': self.__GetResourceType(func),
6058 'return_type': func.return_type,
6059 'id_type_cast': id_type_cast,
6060 'const_service_id': const_service_id,
6061 }, *extras)
6062 invalid_test = """
6063 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6064 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6065 SpecializedSetup<cmds::%(name)s, 0>(false);
6066 cmds::%(name)s cmd;
6067 cmd.Init(%(args)s%(comma)skNewClientId);
6068 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
6071 self.WriteInvalidUnitTest(func, f, invalid_test, {
6072 'comma': comma,
6073 }, *extras)
6075 def WriteHandlerImplementation (self, func, f):
6076 """Overrriden from TypeHandler."""
6077 if func.IsUnsafe():
6078 code = """ uint32_t client_id = c.client_id;
6079 %(return_type)s service_id = 0;
6080 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
6081 return error::kInvalidArguments;
6083 service_id = %(gl_func_name)s(%(gl_args)s);
6084 if (service_id) {
6085 group_->Add%(resource_name)sId(client_id, service_id);
6088 else:
6089 code = """ uint32_t client_id = c.client_id;
6090 if (Get%(resource_name)s(client_id)) {
6091 return error::kInvalidArguments;
6093 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
6094 if (service_id) {
6095 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
6098 f.write(code % {
6099 'resource_name': self.__GetResourceType(func),
6100 'return_type': func.return_type,
6101 'gl_func_name': func.GetGLFunctionName(),
6102 'gl_args': func.MakeOriginalArgString(""),
6103 'gl_args_with_comma': func.MakeOriginalArgString("", True) })
6105 def WriteGLES2Implementation(self, func, f):
6106 """Overrriden from TypeHandler."""
6107 f.write("%s GLES2Implementation::%s(%s) {\n" %
6108 (func.return_type, func.original_name,
6109 func.MakeTypedOriginalArgString("")))
6110 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6111 func.WriteDestinationInitalizationValidation(f)
6112 self.WriteClientGLCallLog(func, f)
6113 for arg in func.GetOriginalArgs():
6114 arg.WriteClientSideValidationCode(f, func)
6115 f.write(" GLuint client_id;\n")
6116 if func.return_type == "GLsync":
6117 f.write(
6118 " GetIdHandler(id_namespaces::kSyncs)->\n")
6119 else:
6120 f.write(
6121 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
6122 f.write(" MakeIds(this, 0, 1, &client_id);\n")
6123 f.write(" helper_->%s(%s);\n" %
6124 (func.name, func.MakeCmdArgString("")))
6125 f.write(' GPU_CLIENT_LOG("returned " << client_id);\n')
6126 f.write(" CheckGLError();\n")
6127 if func.return_type == "GLsync":
6128 f.write(" return reinterpret_cast<GLsync>(client_id);\n")
6129 else:
6130 f.write(" return client_id;\n")
6131 f.write("}\n")
6132 f.write("\n")
6135 class DeleteHandler(TypeHandler):
6136 """Handler for glDelete___ single resource type functions."""
6138 def WriteServiceImplementation(self, func, f):
6139 """Overrriden from TypeHandler."""
6140 if func.IsUnsafe():
6141 TypeHandler.WriteServiceImplementation(self, func, f)
6142 # HandleDeleteShader and HandleDeleteProgram are manually written.
6143 pass
6145 def WriteGLES2Implementation(self, func, f):
6146 """Overrriden from TypeHandler."""
6147 f.write("%s GLES2Implementation::%s(%s) {\n" %
6148 (func.return_type, func.original_name,
6149 func.MakeTypedOriginalArgString("")))
6150 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6151 func.WriteDestinationInitalizationValidation(f)
6152 self.WriteClientGLCallLog(func, f)
6153 for arg in func.GetOriginalArgs():
6154 arg.WriteClientSideValidationCode(f, func)
6155 f.write(
6156 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
6157 f.write(" %sHelper(%s);\n" %
6158 (func.original_name, func.GetOriginalArgs()[-1].name))
6159 f.write(" CheckGLError();\n")
6160 f.write("}\n")
6161 f.write("\n")
6163 def WriteHandlerImplementation (self, func, f):
6164 """Overrriden from TypeHandler."""
6165 assert len(func.GetOriginalArgs()) == 1
6166 arg = func.GetOriginalArgs()[0]
6167 if func.IsUnsafe():
6168 f.write(""" %(arg_type)s service_id = 0;
6169 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
6170 glDelete%(resource_type)s(service_id);
6171 group_->Remove%(resource_type)sId(%(arg_name)s);
6172 } else {
6173 LOCAL_SET_GL_ERROR(
6174 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
6176 """ % { 'resource_type': func.GetInfo('resource_type'),
6177 'arg_name': arg.name,
6178 'arg_type': arg.type,
6179 'func_name': func.original_name })
6180 else:
6181 f.write(" %sHelper(%s);\n" % (func.original_name, arg.name))
6183 class DELnHandler(TypeHandler):
6184 """Handler for glDelete___ type functions."""
6186 def WriteGetDataSizeCode(self, func, f):
6187 """Overrriden from TypeHandler."""
6188 code = """ uint32_t data_size;
6189 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6190 return error::kOutOfBounds;
6193 f.write(code)
6195 def WriteGLES2ImplementationUnitTest(self, func, f):
6196 """Overrriden from TypeHandler."""
6197 code = """
6198 TEST_F(GLES2ImplementationTest, %(name)s) {
6199 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6200 struct Cmds {
6201 cmds::%(name)sImmediate del;
6202 GLuint data[2];
6204 Cmds expected;
6205 expected.del.Init(arraysize(ids), &ids[0]);
6206 expected.data[0] = k%(types)sStartId;
6207 expected.data[1] = k%(types)sStartId + 1;
6208 gl_->%(name)s(arraysize(ids), &ids[0]);
6209 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6212 f.write(code % {
6213 'name': func.name,
6214 'types': func.GetInfo('resource_types'),
6217 def WriteServiceUnitTest(self, func, f, *extras):
6218 """Overrriden from TypeHandler."""
6219 valid_test = """
6220 TEST_P(%(test_name)s, %(name)sValidArgs) {
6221 EXPECT_CALL(
6222 *gl_,
6223 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6224 .Times(1);
6225 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6226 SpecializedSetup<cmds::%(name)s, 0>(true);
6227 cmds::%(name)s cmd;
6228 cmd.Init(%(args)s);
6229 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6230 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6231 EXPECT_TRUE(
6232 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6235 self.WriteValidUnitTest(func, f, valid_test, {
6236 'resource_name': func.GetInfo('resource_type').lower(),
6237 'upper_resource_name': func.GetInfo('resource_type'),
6238 }, *extras)
6239 invalid_test = """
6240 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6241 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6242 SpecializedSetup<cmds::%(name)s, 0>(false);
6243 cmds::%(name)s cmd;
6244 cmd.Init(%(args)s);
6245 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6248 self.WriteValidUnitTest(func, f, invalid_test, *extras)
6250 def WriteImmediateServiceUnitTest(self, func, f, *extras):
6251 """Overrriden from TypeHandler."""
6252 valid_test = """
6253 TEST_P(%(test_name)s, %(name)sValidArgs) {
6254 EXPECT_CALL(
6255 *gl_,
6256 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6257 .Times(1);
6258 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6259 SpecializedSetup<cmds::%(name)s, 0>(true);
6260 cmd.Init(1, &client_%(resource_name)s_id_);"""
6261 if func.IsUnsafe():
6262 valid_test += """
6263 decoder_->set_unsafe_es3_apis_enabled(true);"""
6264 valid_test += """
6265 EXPECT_EQ(error::kNoError,
6266 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6267 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6268 if func.IsUnsafe():
6269 valid_test += """
6270 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6271 client_%(resource_name)s_id_, NULL));
6272 decoder_->set_unsafe_es3_apis_enabled(false);
6273 EXPECT_EQ(error::kUnknownCommand,
6274 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6277 else:
6278 valid_test += """
6279 EXPECT_TRUE(
6280 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6283 self.WriteValidUnitTest(func, f, valid_test, {
6284 'resource_name': func.GetInfo('resource_type').lower(),
6285 'upper_resource_name': func.GetInfo('resource_type'),
6286 }, *extras)
6287 invalid_test = """
6288 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6289 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6290 SpecializedSetup<cmds::%(name)s, 0>(false);
6291 GLuint temp = kInvalidClientId;
6292 cmd.Init(1, &temp);"""
6293 if func.IsUnsafe():
6294 invalid_test += """
6295 decoder_->set_unsafe_es3_apis_enabled(true);
6296 EXPECT_EQ(error::kNoError,
6297 ExecuteImmediateCmd(cmd, sizeof(temp)));
6298 decoder_->set_unsafe_es3_apis_enabled(false);
6299 EXPECT_EQ(error::kUnknownCommand,
6300 ExecuteImmediateCmd(cmd, sizeof(temp)));
6303 else:
6304 invalid_test += """
6305 EXPECT_EQ(error::kNoError,
6306 ExecuteImmediateCmd(cmd, sizeof(temp)));
6309 self.WriteValidUnitTest(func, f, invalid_test, *extras)
6311 def WriteHandlerImplementation (self, func, f):
6312 """Overrriden from TypeHandler."""
6313 f.write(" %sHelper(n, %s);\n" %
6314 (func.name, func.GetLastOriginalArg().name))
6316 def WriteImmediateHandlerImplementation (self, func, f):
6317 """Overrriden from TypeHandler."""
6318 if func.IsUnsafe():
6319 f.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6320 GLuint service_id = 0;
6321 if (group_->Get%(resource_type)sServiceId(
6322 %(last_arg_name)s[ii], &service_id)) {
6323 glDelete%(resource_type)ss(1, &service_id);
6324 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6327 """ % { 'resource_type': func.GetInfo('resource_type'),
6328 'last_arg_name': func.GetLastOriginalArg().name })
6329 else:
6330 f.write(" %sHelper(n, %s);\n" %
6331 (func.original_name, func.GetLastOriginalArg().name))
6333 def WriteGLES2Implementation(self, func, f):
6334 """Overrriden from TypeHandler."""
6335 impl_decl = func.GetInfo('impl_decl')
6336 if impl_decl == None or impl_decl == True:
6337 args = {
6338 'return_type': func.return_type,
6339 'name': func.original_name,
6340 'typed_args': func.MakeTypedOriginalArgString(""),
6341 'args': func.MakeOriginalArgString(""),
6342 'resource_type': func.GetInfo('resource_type').lower(),
6343 'count_name': func.GetOriginalArgs()[0].name,
6345 f.write(
6346 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6347 args)
6348 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6349 func.WriteDestinationInitalizationValidation(f)
6350 self.WriteClientGLCallLog(func, f)
6351 f.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6352 for (GLsizei i = 0; i < n; ++i) {
6353 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6356 """ % func.GetOriginalArgs()[1].name)
6357 f.write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6358 for (GLsizei i = 0; i < n; ++i) {
6359 DCHECK(%s[i] != 0);
6362 """ % func.GetOriginalArgs()[1].name)
6363 for arg in func.GetOriginalArgs():
6364 arg.WriteClientSideValidationCode(f, func)
6365 code = """ %(name)sHelper(%(args)s);
6366 CheckGLError();
6370 f.write(code % args)
6372 def WriteImmediateCmdComputeSize(self, func, f):
6373 """Overrriden from TypeHandler."""
6374 f.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6375 f.write(
6376 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6377 f.write(" }\n")
6378 f.write("\n")
6379 f.write(" static uint32_t ComputeSize(GLsizei n) {\n")
6380 f.write(" return static_cast<uint32_t>(\n")
6381 f.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6382 f.write(" }\n")
6383 f.write("\n")
6385 def WriteImmediateCmdSetHeader(self, func, f):
6386 """Overrriden from TypeHandler."""
6387 f.write(" void SetHeader(GLsizei n) {\n")
6388 f.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6389 f.write(" }\n")
6390 f.write("\n")
6392 def WriteImmediateCmdInit(self, func, f):
6393 """Overrriden from TypeHandler."""
6394 last_arg = func.GetLastOriginalArg()
6395 f.write(" void Init(%s, %s _%s) {\n" %
6396 (func.MakeTypedCmdArgString("_"),
6397 last_arg.type, last_arg.name))
6398 f.write(" SetHeader(_n);\n")
6399 args = func.GetCmdArgs()
6400 for arg in args:
6401 f.write(" %s = _%s;\n" % (arg.name, arg.name))
6402 f.write(" memcpy(ImmediateDataAddress(this),\n")
6403 f.write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
6404 f.write(" }\n")
6405 f.write("\n")
6407 def WriteImmediateCmdSet(self, func, f):
6408 """Overrriden from TypeHandler."""
6409 last_arg = func.GetLastOriginalArg()
6410 copy_args = func.MakeCmdArgString("_", False)
6411 f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
6412 (func.MakeTypedCmdArgString("_", True),
6413 last_arg.type, last_arg.name))
6414 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6415 (copy_args, last_arg.name))
6416 f.write(" const uint32_t size = ComputeSize(_n);\n")
6417 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6418 "cmd, size);\n")
6419 f.write(" }\n")
6420 f.write("\n")
6422 def WriteImmediateCmdHelper(self, func, f):
6423 """Overrriden from TypeHandler."""
6424 code = """ void %(name)s(%(typed_args)s) {
6425 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6426 gles2::cmds::%(name)s* c =
6427 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6428 if (c) {
6429 c->Init(%(args)s);
6434 f.write(code % {
6435 "name": func.name,
6436 "typed_args": func.MakeTypedOriginalArgString(""),
6437 "args": func.MakeOriginalArgString(""),
6440 def WriteImmediateFormatTest(self, func, f):
6441 """Overrriden from TypeHandler."""
6442 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6443 f.write(" static GLuint ids[] = { 12, 23, 34, };\n")
6444 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6445 (func.name, func.name))
6446 f.write(" void* next_cmd = cmd.Set(\n")
6447 f.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6448 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6449 func.name)
6450 f.write(" cmd.header.command);\n")
6451 f.write(" EXPECT_EQ(sizeof(cmd) +\n")
6452 f.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6453 f.write(" cmd.header.size * 4u);\n")
6454 f.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6455 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
6456 f.write(" next_cmd, sizeof(cmd) +\n")
6457 f.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6458 f.write(" // TODO(gman): Check that ids were inserted;\n")
6459 f.write("}\n")
6460 f.write("\n")
6463 class GETnHandler(TypeHandler):
6464 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6466 def NeedsDataTransferFunction(self, func):
6467 """Overriden from TypeHandler."""
6468 return False
6470 def WriteServiceImplementation(self, func, f):
6471 """Overrriden from TypeHandler."""
6472 self.WriteServiceHandlerFunctionHeader(func, f)
6473 last_arg = func.GetLastOriginalArg()
6474 # All except shm_id and shm_offset.
6475 all_but_last_args = func.GetCmdArgs()[:-2]
6476 for arg in all_but_last_args:
6477 arg.WriteGetCode(f)
6479 code = """ typedef cmds::%(func_name)s::Result Result;
6480 GLsizei num_values = 0;
6481 GetNumValuesReturnedForGLGet(pname, &num_values);
6482 Result* result = GetSharedMemoryAs<Result*>(
6483 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6484 Result::ComputeSize(num_values));
6485 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6487 f.write(code % {
6488 'last_arg_type': last_arg.type,
6489 'last_arg_name': last_arg.name,
6490 'func_name': func.name,
6492 func.WriteHandlerValidation(f)
6493 code = """ // Check that the client initialized the result.
6494 if (result->size != 0) {
6495 return error::kInvalidArguments;
6498 shadowed = func.GetInfo('shadowed')
6499 if not shadowed:
6500 f.write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
6501 f.write(code)
6502 func.WriteHandlerImplementation(f)
6503 if shadowed:
6504 code = """ result->SetNumResults(num_values);
6505 return error::kNoError;
6508 else:
6509 code = """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
6510 if (error == GL_NO_ERROR) {
6511 result->SetNumResults(num_values);
6513 return error::kNoError;
6517 f.write(code % {'func_name': func.name})
6519 def WriteGLES2Implementation(self, func, f):
6520 """Overrriden from TypeHandler."""
6521 impl_decl = func.GetInfo('impl_decl')
6522 if impl_decl == None or impl_decl == True:
6523 f.write("%s GLES2Implementation::%s(%s) {\n" %
6524 (func.return_type, func.original_name,
6525 func.MakeTypedOriginalArgString("")))
6526 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6527 func.WriteDestinationInitalizationValidation(f)
6528 self.WriteClientGLCallLog(func, f)
6529 for arg in func.GetOriginalArgs():
6530 arg.WriteClientSideValidationCode(f, func)
6531 all_but_last_args = func.GetOriginalArgs()[:-1]
6532 args = []
6533 has_length_arg = False
6534 for arg in all_but_last_args:
6535 if arg.type == 'GLsync':
6536 args.append('ToGLuint(%s)' % arg.name)
6537 elif arg.name.endswith('size') and arg.type == 'GLsizei':
6538 continue
6539 elif arg.name == 'length':
6540 has_length_arg = True
6541 continue
6542 else:
6543 args.append(arg.name)
6544 arg_string = ", ".join(args)
6545 all_arg_string = (
6546 ", ".join([
6547 "%s" % arg.name
6548 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
6549 self.WriteTraceEvent(func, f)
6550 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6551 return;
6553 typedef cmds::%(func_name)s::Result Result;
6554 Result* result = GetResultAs<Result*>();
6555 if (!result) {
6556 return;
6558 result->SetNumResults(0);
6559 helper_->%(func_name)s(%(arg_string)s,
6560 GetResultShmId(), GetResultShmOffset());
6561 WaitForCmd();
6562 result->CopyResult(%(last_arg_name)s);
6563 GPU_CLIENT_LOG_CODE_BLOCK({
6564 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6565 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6567 });"""
6568 if has_length_arg:
6569 code += """
6570 if (length) {
6571 *length = result->GetNumResults();
6572 }"""
6573 code += """
6574 CheckGLError();
6577 f.write(code % {
6578 'func_name': func.name,
6579 'arg_string': arg_string,
6580 'all_arg_string': all_arg_string,
6581 'last_arg_name': func.GetLastOriginalArg().name,
6584 def WriteGLES2ImplementationUnitTest(self, func, f):
6585 """Writes the GLES2 Implemention unit test."""
6586 code = """
6587 TEST_F(GLES2ImplementationTest, %(name)s) {
6588 struct Cmds {
6589 cmds::%(name)s cmd;
6591 typedef cmds::%(name)s::Result::Type ResultType;
6592 ResultType result = 0;
6593 Cmds expected;
6594 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6595 sizeof(uint32_t) + sizeof(ResultType));
6596 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6597 EXPECT_CALL(*command_buffer(), OnFlush())
6598 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6599 .RetiresOnSaturation();
6600 gl_->%(name)s(%(args)s, &result);
6601 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6602 EXPECT_EQ(static_cast<ResultType>(1), result);
6605 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
6606 if not first_cmd_arg:
6607 return
6609 first_gl_arg = func.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6610 func)
6612 cmd_arg_strings = [first_cmd_arg]
6613 for arg in func.GetCmdArgs()[1:-2]:
6614 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6615 gl_arg_strings = [first_gl_arg]
6616 for arg in func.GetOriginalArgs()[1:-1]:
6617 gl_arg_strings.append(arg.GetValidClientSideArg(func))
6619 f.write(code % {
6620 'name': func.name,
6621 'args': ", ".join(gl_arg_strings),
6622 'cmd_args': ", ".join(cmd_arg_strings),
6625 def WriteServiceUnitTest(self, func, f, *extras):
6626 """Overrriden from TypeHandler."""
6627 valid_test = """
6628 TEST_P(%(test_name)s, %(name)sValidArgs) {
6629 EXPECT_CALL(*gl_, GetError())
6630 .WillOnce(Return(GL_NO_ERROR))
6631 .WillOnce(Return(GL_NO_ERROR))
6632 .RetiresOnSaturation();
6633 SpecializedSetup<cmds::%(name)s, 0>(true);
6634 typedef cmds::%(name)s::Result Result;
6635 Result* result = static_cast<Result*>(shared_memory_address_);
6636 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6637 result->size = 0;
6638 cmds::%(name)s cmd;
6639 cmd.Init(%(cmd_args)s);"""
6640 if func.IsUnsafe():
6641 valid_test += """
6642 decoder_->set_unsafe_es3_apis_enabled(true);"""
6643 valid_test += """
6644 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6645 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6646 %(valid_pname)s),
6647 result->GetNumResults());
6648 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6649 if func.IsUnsafe():
6650 valid_test += """
6651 decoder_->set_unsafe_es3_apis_enabled(false);
6652 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6653 valid_test += """
6656 gl_arg_strings = []
6657 cmd_arg_strings = []
6658 valid_pname = ''
6659 for arg in func.GetOriginalArgs()[:-1]:
6660 if arg.name == 'length':
6661 gl_arg_value = 'nullptr'
6662 elif arg.name.endswith('size'):
6663 gl_arg_value = ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6664 valid_pname)
6665 elif arg.type == 'GLsync':
6666 gl_arg_value = 'reinterpret_cast<GLsync>(kServiceSyncId)'
6667 else:
6668 gl_arg_value = arg.GetValidGLArg(func)
6669 gl_arg_strings.append(gl_arg_value)
6670 if arg.name == 'pname':
6671 valid_pname = gl_arg_value
6672 if arg.name.endswith('size') or arg.name == 'length':
6673 continue
6674 if arg.type == 'GLsync':
6675 arg_value = 'client_sync_id_'
6676 else:
6677 arg_value = arg.GetValidArg(func)
6678 cmd_arg_strings.append(arg_value)
6679 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
6680 gl_arg_strings.append("_")
6681 else:
6682 gl_arg_strings.append("result->GetData()")
6683 cmd_arg_strings.append("shared_memory_id_")
6684 cmd_arg_strings.append("shared_memory_offset_")
6686 self.WriteValidUnitTest(func, f, valid_test, {
6687 'local_gl_args': ", ".join(gl_arg_strings),
6688 'cmd_args': ", ".join(cmd_arg_strings),
6689 'valid_pname': valid_pname,
6690 }, *extras)
6692 if not func.IsUnsafe():
6693 invalid_test = """
6694 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6695 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6696 SpecializedSetup<cmds::%(name)s, 0>(false);
6697 cmds::%(name)s::Result* result =
6698 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6699 result->size = 0;
6700 cmds::%(name)s cmd;
6701 cmd.Init(%(args)s);
6702 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6703 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6706 self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
6708 class ArrayArgTypeHandler(TypeHandler):
6709 """Base class for type handlers that handle args that are arrays"""
6711 def GetArrayType(self, func):
6712 """Returns the type of the element in the element array being PUT to."""
6713 for arg in func.GetOriginalArgs():
6714 if arg.IsPointer():
6715 element_type = arg.GetPointedType()
6716 return element_type
6718 # Special case: array type handler is used for a function that is forwarded
6719 # to the actual array type implementation
6720 element_type = func.GetOriginalArgs()[-1].type
6721 assert all(arg.type == element_type \
6722 for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
6723 return element_type
6725 def GetArrayCount(self, func):
6726 """Returns the count of the elements in the array being PUT to."""
6727 return func.GetInfo('count')
6729 class PUTHandler(ArrayArgTypeHandler):
6730 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6732 def WriteServiceUnitTest(self, func, f, *extras):
6733 """Writes the service unit test for a command."""
6734 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6735 if func.GetInfo("first_element_only"):
6736 gl_arg_strings = [
6737 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
6739 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
6740 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6741 ", ".join(gl_arg_strings))
6742 valid_test = """
6743 TEST_P(%(test_name)s, %(name)sValidArgs) {
6744 SpecializedSetup<cmds::%(name)s, 0>(true);
6745 cmds::%(name)s cmd;
6746 cmd.Init(%(args)s);
6747 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6748 %(expected_call)s
6749 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6750 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6753 extra = {
6754 'data_type': self.GetArrayType(func),
6755 'data_value': func.GetInfo('data_value') or '0',
6756 'expected_call': expected_call,
6758 self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
6760 invalid_test = """
6761 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6762 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6763 SpecializedSetup<cmds::%(name)s, 0>(false);
6764 cmds::%(name)s cmd;
6765 cmd.Init(%(args)s);
6766 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6767 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6770 self.WriteInvalidUnitTest(func, f, invalid_test, extra, *extras)
6772 def WriteImmediateServiceUnitTest(self, func, f, *extras):
6773 """Writes the service unit test for a command."""
6774 valid_test = """
6775 TEST_P(%(test_name)s, %(name)sValidArgs) {
6776 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6777 SpecializedSetup<cmds::%(name)s, 0>(true);
6778 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6779 cmd.Init(%(gl_args)s, &temp[0]);
6780 EXPECT_CALL(
6781 *gl_,
6782 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6783 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6784 if func.IsUnsafe():
6785 valid_test += """
6786 decoder_->set_unsafe_es3_apis_enabled(true);"""
6787 valid_test += """
6788 EXPECT_EQ(error::kNoError,
6789 ExecuteImmediateCmd(cmd, sizeof(temp)));
6790 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6791 if func.IsUnsafe():
6792 valid_test += """
6793 decoder_->set_unsafe_es3_apis_enabled(false);
6794 EXPECT_EQ(error::kUnknownCommand,
6795 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6796 valid_test += """
6799 gl_arg_strings = [
6800 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
6802 gl_any_strings = ["_"] * len(gl_arg_strings)
6804 extra = {
6805 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
6806 'data_type': self.GetArrayType(func),
6807 'data_count': self.GetArrayCount(func),
6808 'data_value': func.GetInfo('data_value') or '0',
6809 'gl_args': ", ".join(gl_arg_strings),
6810 'gl_any_args': ", ".join(gl_any_strings),
6812 self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
6814 invalid_test = """
6815 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6816 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6817 if func.IsUnsafe():
6818 invalid_test += """
6819 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6821 else:
6822 invalid_test += """
6823 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6825 invalid_test += """
6826 SpecializedSetup<cmds::%(name)s, 0>(false);
6827 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6828 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6829 if func.IsUnsafe():
6830 invalid_test += """
6831 decoder_->set_unsafe_es3_apis_enabled(true);
6832 EXPECT_EQ(error::%(parse_result)s,
6833 ExecuteImmediateCmd(cmd, sizeof(temp)));
6834 decoder_->set_unsafe_es3_apis_enabled(false);
6837 else:
6838 invalid_test += """
6839 EXPECT_EQ(error::%(parse_result)s,
6840 ExecuteImmediateCmd(cmd, sizeof(temp)));
6841 %(gl_error_test)s
6844 self.WriteInvalidUnitTest(func, f, invalid_test, extra, *extras)
6846 def WriteGetDataSizeCode(self, func, f):
6847 """Overrriden from TypeHandler."""
6848 code = """ uint32_t data_size;
6849 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6850 return error::kOutOfBounds;
6853 f.write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6854 if func.IsImmediate():
6855 f.write(" if (data_size > immediate_data_size) {\n")
6856 f.write(" return error::kOutOfBounds;\n")
6857 f.write(" }\n")
6859 def __NeedsToCalcDataCount(self, func):
6860 use_count_func = func.GetInfo('use_count_func')
6861 return use_count_func != None and use_count_func != False
6863 def WriteGLES2Implementation(self, func, f):
6864 """Overrriden from TypeHandler."""
6865 impl_func = func.GetInfo('impl_func')
6866 if (impl_func != None and impl_func != True):
6867 return;
6868 f.write("%s GLES2Implementation::%s(%s) {\n" %
6869 (func.return_type, func.original_name,
6870 func.MakeTypedOriginalArgString("")))
6871 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6872 func.WriteDestinationInitalizationValidation(f)
6873 self.WriteClientGLCallLog(func, f)
6875 if self.__NeedsToCalcDataCount(func):
6876 f.write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6877 (func.name, func.GetOriginalArgs()[0].name))
6878 f.write(" DCHECK_LE(count, %du);\n" % self.GetArrayCount(func))
6879 else:
6880 f.write(" size_t count = %d;" % self.GetArrayCount(func))
6881 f.write(" for (size_t ii = 0; ii < count; ++ii)\n")
6882 f.write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6883 func.GetLastOriginalArg().name)
6884 for arg in func.GetOriginalArgs():
6885 arg.WriteClientSideValidationCode(f, func)
6886 f.write(" helper_->%sImmediate(%s);\n" %
6887 (func.name, func.MakeOriginalArgString("")))
6888 f.write(" CheckGLError();\n")
6889 f.write("}\n")
6890 f.write("\n")
6892 def WriteGLES2ImplementationUnitTest(self, func, f):
6893 """Writes the GLES2 Implemention unit test."""
6894 client_test = func.GetInfo('client_test')
6895 if (client_test != None and client_test != True):
6896 return;
6897 code = """
6898 TEST_F(GLES2ImplementationTest, %(name)s) {
6899 %(type)s data[%(count)d] = {0};
6900 struct Cmds {
6901 cmds::%(name)sImmediate cmd;
6902 %(type)s data[%(count)d];
6905 for (int jj = 0; jj < %(count)d; ++jj) {
6906 data[jj] = static_cast<%(type)s>(jj);
6908 Cmds expected;
6909 expected.cmd.Init(%(cmd_args)s, &data[0]);
6910 gl_->%(name)s(%(args)s, &data[0]);
6911 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6914 cmd_arg_strings = [
6915 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
6917 gl_arg_strings = [
6918 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
6921 f.write(code % {
6922 'name': func.name,
6923 'type': self.GetArrayType(func),
6924 'count': self.GetArrayCount(func),
6925 'args': ", ".join(gl_arg_strings),
6926 'cmd_args': ", ".join(cmd_arg_strings),
6929 def WriteImmediateCmdComputeSize(self, func, f):
6930 """Overrriden from TypeHandler."""
6931 f.write(" static uint32_t ComputeDataSize() {\n")
6932 f.write(" return static_cast<uint32_t>(\n")
6933 f.write(" sizeof(%s) * %d);\n" %
6934 (self.GetArrayType(func), self.GetArrayCount(func)))
6935 f.write(" }\n")
6936 f.write("\n")
6937 if self.__NeedsToCalcDataCount(func):
6938 f.write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6939 (func.GetOriginalArgs()[0].type,
6940 func.GetOriginalArgs()[0].name))
6941 f.write(" return static_cast<uint32_t>(\n")
6942 f.write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6943 (self.GetArrayType(func), func.original_name,
6944 func.GetOriginalArgs()[0].name))
6945 f.write(" }\n")
6946 f.write("\n")
6947 f.write(" static uint32_t ComputeSize() {\n")
6948 f.write(" return static_cast<uint32_t>(\n")
6949 f.write(
6950 " sizeof(ValueType) + ComputeDataSize());\n")
6951 f.write(" }\n")
6952 f.write("\n")
6954 def WriteImmediateCmdSetHeader(self, func, f):
6955 """Overrriden from TypeHandler."""
6956 f.write(" void SetHeader() {\n")
6957 f.write(
6958 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6959 f.write(" }\n")
6960 f.write("\n")
6962 def WriteImmediateCmdInit(self, func, f):
6963 """Overrriden from TypeHandler."""
6964 last_arg = func.GetLastOriginalArg()
6965 f.write(" void Init(%s, %s _%s) {\n" %
6966 (func.MakeTypedCmdArgString("_"),
6967 last_arg.type, last_arg.name))
6968 f.write(" SetHeader();\n")
6969 args = func.GetCmdArgs()
6970 for arg in args:
6971 f.write(" %s = _%s;\n" % (arg.name, arg.name))
6972 f.write(" memcpy(ImmediateDataAddress(this),\n")
6973 if self.__NeedsToCalcDataCount(func):
6974 f.write(" _%s, ComputeEffectiveDataSize(%s));" %
6975 (last_arg.name, func.GetOriginalArgs()[0].name))
6976 f.write("""
6977 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6978 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6979 ComputeEffectiveDataSize(%(arg)s);
6980 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6981 """ % { 'arg': func.GetOriginalArgs()[0].name, })
6982 else:
6983 f.write(" _%s, ComputeDataSize());\n" % last_arg.name)
6984 f.write(" }\n")
6985 f.write("\n")
6987 def WriteImmediateCmdSet(self, func, f):
6988 """Overrriden from TypeHandler."""
6989 last_arg = func.GetLastOriginalArg()
6990 copy_args = func.MakeCmdArgString("_", False)
6991 f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
6992 (func.MakeTypedCmdArgString("_", True),
6993 last_arg.type, last_arg.name))
6994 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6995 (copy_args, last_arg.name))
6996 f.write(" const uint32_t size = ComputeSize();\n")
6997 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6998 "cmd, size);\n")
6999 f.write(" }\n")
7000 f.write("\n")
7002 def WriteImmediateCmdHelper(self, func, f):
7003 """Overrriden from TypeHandler."""
7004 code = """ void %(name)s(%(typed_args)s) {
7005 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
7006 gles2::cmds::%(name)s* c =
7007 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7008 if (c) {
7009 c->Init(%(args)s);
7014 f.write(code % {
7015 "name": func.name,
7016 "typed_args": func.MakeTypedOriginalArgString(""),
7017 "args": func.MakeOriginalArgString(""),
7020 def WriteImmediateFormatTest(self, func, f):
7021 """Overrriden from TypeHandler."""
7022 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
7023 f.write(" const int kSomeBaseValueToTestWith = 51;\n")
7024 f.write(" static %s data[] = {\n" % self.GetArrayType(func))
7025 for v in range(0, self.GetArrayCount(func)):
7026 f.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7027 (self.GetArrayType(func), v))
7028 f.write(" };\n")
7029 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7030 (func.name, func.name))
7031 f.write(" void* next_cmd = cmd.Set(\n")
7032 f.write(" &cmd")
7033 args = func.GetCmdArgs()
7034 for value, arg in enumerate(args):
7035 f.write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
7036 f.write(",\n data);\n")
7037 args = func.GetCmdArgs()
7038 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
7039 % func.name)
7040 f.write(" cmd.header.command);\n")
7041 f.write(" EXPECT_EQ(sizeof(cmd) +\n")
7042 f.write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
7043 f.write(" cmd.header.size * 4u);\n")
7044 for value, arg in enumerate(args):
7045 f.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7046 (arg.type, value + 11, arg.name))
7047 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7048 f.write(" next_cmd, sizeof(cmd) +\n")
7049 f.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7050 f.write(" // TODO(gman): Check that data was inserted;\n")
7051 f.write("}\n")
7052 f.write("\n")
7055 class PUTnHandler(ArrayArgTypeHandler):
7056 """Handler for PUTn 'glUniform__v' type functions."""
7058 def WriteServiceUnitTest(self, func, f, *extras):
7059 """Overridden from TypeHandler."""
7060 ArrayArgTypeHandler.WriteServiceUnitTest(self, func, f, *extras)
7062 valid_test = """
7063 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
7064 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7065 SpecializedSetup<cmds::%(name)s, 0>(true);
7066 cmds::%(name)s cmd;
7067 cmd.Init(%(args)s);
7068 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7069 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7072 gl_arg_strings = []
7073 arg_strings = []
7074 for count, arg in enumerate(func.GetOriginalArgs()):
7075 # hardcoded to match unit tests.
7076 if count == 0:
7077 # the location of the second element of the 2nd uniform.
7078 # defined in GLES2DecoderBase::SetupShaderForUniform
7079 gl_arg_strings.append("3")
7080 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
7081 elif count == 1:
7082 # the number of elements that gl will be called with.
7083 gl_arg_strings.append("3")
7084 # the number of elements requested in the command.
7085 arg_strings.append("5")
7086 else:
7087 gl_arg_strings.append(arg.GetValidGLArg(func))
7088 if not arg.IsConstant():
7089 arg_strings.append(arg.GetValidArg(func))
7090 extra = {
7091 'gl_args': ", ".join(gl_arg_strings),
7092 'args': ", ".join(arg_strings),
7094 self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
7096 def WriteImmediateServiceUnitTest(self, func, f, *extras):
7097 """Overridden from TypeHandler."""
7098 valid_test = """
7099 TEST_P(%(test_name)s, %(name)sValidArgs) {
7100 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7101 EXPECT_CALL(
7102 *gl_,
7103 %(gl_func_name)s(%(gl_args)s,
7104 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
7105 SpecializedSetup<cmds::%(name)s, 0>(true);
7106 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7107 cmd.Init(%(args)s, &temp[0]);"""
7108 if func.IsUnsafe():
7109 valid_test += """
7110 decoder_->set_unsafe_es3_apis_enabled(true);"""
7111 valid_test += """
7112 EXPECT_EQ(error::kNoError,
7113 ExecuteImmediateCmd(cmd, sizeof(temp)));
7114 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7115 if func.IsUnsafe():
7116 valid_test += """
7117 decoder_->set_unsafe_es3_apis_enabled(false);
7118 EXPECT_EQ(error::kUnknownCommand,
7119 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
7120 valid_test += """
7123 gl_arg_strings = []
7124 gl_any_strings = []
7125 arg_strings = []
7126 for arg in func.GetOriginalArgs()[0:-1]:
7127 gl_arg_strings.append(arg.GetValidGLArg(func))
7128 gl_any_strings.append("_")
7129 if not arg.IsConstant():
7130 arg_strings.append(arg.GetValidArg(func))
7131 extra = {
7132 'data_type': self.GetArrayType(func),
7133 'data_count': self.GetArrayCount(func),
7134 'args': ", ".join(arg_strings),
7135 'gl_args': ", ".join(gl_arg_strings),
7136 'gl_any_args': ", ".join(gl_any_strings),
7138 self.WriteValidUnitTest(func, f, valid_test, extra, *extras)
7140 invalid_test = """
7141 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7142 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
7143 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
7144 SpecializedSetup<cmds::%(name)s, 0>(false);
7145 %(data_type)s temp[%(data_count)s * 2] = { 0, };
7146 cmd.Init(%(all_but_last_args)s, &temp[0]);
7147 EXPECT_EQ(error::%(parse_result)s,
7148 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
7151 self.WriteInvalidUnitTest(func, f, invalid_test, extra, *extras)
7153 def WriteGetDataSizeCode(self, func, f):
7154 """Overrriden from TypeHandler."""
7155 code = """ uint32_t data_size;
7156 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
7157 return error::kOutOfBounds;
7160 f.write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
7161 if func.IsImmediate():
7162 f.write(" if (data_size > immediate_data_size) {\n")
7163 f.write(" return error::kOutOfBounds;\n")
7164 f.write(" }\n")
7166 def WriteGLES2Implementation(self, func, f):
7167 """Overrriden from TypeHandler."""
7168 f.write("%s GLES2Implementation::%s(%s) {\n" %
7169 (func.return_type, func.original_name,
7170 func.MakeTypedOriginalArgString("")))
7171 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7172 func.WriteDestinationInitalizationValidation(f)
7173 self.WriteClientGLCallLog(func, f)
7174 last_pointer_name = func.GetLastOriginalPointerArg().name
7175 f.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
7176 for (GLsizei i = 0; i < count; ++i) {
7177 """)
7178 values_str = ' << ", " << '.join(
7179 ["%s[%d + i * %d]" % (
7180 last_pointer_name, ndx, self.GetArrayCount(func)) for ndx in range(
7181 0, self.GetArrayCount(func))])
7182 f.write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
7183 f.write(" }\n });\n")
7184 for arg in func.GetOriginalArgs():
7185 arg.WriteClientSideValidationCode(f, func)
7186 f.write(" helper_->%sImmediate(%s);\n" %
7187 (func.name, func.MakeInitString("")))
7188 f.write(" CheckGLError();\n")
7189 f.write("}\n")
7190 f.write("\n")
7192 def WriteGLES2ImplementationUnitTest(self, func, f):
7193 """Writes the GLES2 Implemention unit test."""
7194 code = """
7195 TEST_F(GLES2ImplementationTest, %(name)s) {
7196 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7197 struct Cmds {
7198 cmds::%(name)sImmediate cmd;
7199 %(type)s data[%(count_param)d][%(count)d];
7202 Cmds expected;
7203 for (int ii = 0; ii < %(count_param)d; ++ii) {
7204 for (int jj = 0; jj < %(count)d; ++jj) {
7205 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7208 expected.cmd.Init(%(cmd_args)s);
7209 gl_->%(name)s(%(args)s);
7210 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7213 cmd_arg_strings = []
7214 for arg in func.GetCmdArgs():
7215 if arg.name.endswith("_shm_id"):
7216 cmd_arg_strings.append("&data[0][0]")
7217 elif arg.name.endswith("_shm_offset"):
7218 continue
7219 else:
7220 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
7221 gl_arg_strings = []
7222 count_param = 0
7223 for arg in func.GetOriginalArgs():
7224 if arg.IsPointer():
7225 valid_value = "&data[0][0]"
7226 else:
7227 valid_value = arg.GetValidClientSideArg(func)
7228 gl_arg_strings.append(valid_value)
7229 if arg.name == "count":
7230 count_param = int(valid_value)
7231 f.write(code % {
7232 'name': func.name,
7233 'type': self.GetArrayType(func),
7234 'count': self.GetArrayCount(func),
7235 'args': ", ".join(gl_arg_strings),
7236 'cmd_args': ", ".join(cmd_arg_strings),
7237 'count_param': count_param,
7240 # Test constants for invalid values, as they are not tested by the
7241 # service.
7242 constants = [
7243 arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
7245 if not constants:
7246 return
7248 code = """
7249 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
7250 %(type)s data[%(count_param)d][%(count)d] = {{0}};
7251 for (int ii = 0; ii < %(count_param)d; ++ii) {
7252 for (int jj = 0; jj < %(count)d; ++jj) {
7253 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
7256 gl_->%(name)s(%(args)s);
7257 EXPECT_TRUE(NoCommandsWritten());
7258 EXPECT_EQ(%(gl_error)s, CheckError());
7261 for invalid_arg in constants:
7262 gl_arg_strings = []
7263 invalid = invalid_arg.GetInvalidArg(func)
7264 for arg in func.GetOriginalArgs():
7265 if arg is invalid_arg:
7266 gl_arg_strings.append(invalid[0])
7267 elif arg.IsPointer():
7268 gl_arg_strings.append("&data[0][0]")
7269 else:
7270 valid_value = arg.GetValidClientSideArg(func)
7271 gl_arg_strings.append(valid_value)
7272 if arg.name == "count":
7273 count_param = int(valid_value)
7275 f.write(code % {
7276 'name': func.name,
7277 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
7278 'type': self.GetArrayType(func),
7279 'count': self.GetArrayCount(func),
7280 'args': ", ".join(gl_arg_strings),
7281 'gl_error': invalid[2],
7282 'count_param': count_param,
7286 def WriteImmediateCmdComputeSize(self, func, f):
7287 """Overrriden from TypeHandler."""
7288 f.write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
7289 f.write(" return static_cast<uint32_t>(\n")
7290 f.write(" sizeof(%s) * %d * count); // NOLINT\n" %
7291 (self.GetArrayType(func), self.GetArrayCount(func)))
7292 f.write(" }\n")
7293 f.write("\n")
7294 f.write(" static uint32_t ComputeSize(GLsizei count) {\n")
7295 f.write(" return static_cast<uint32_t>(\n")
7296 f.write(
7297 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
7298 f.write(" }\n")
7299 f.write("\n")
7301 def WriteImmediateCmdSetHeader(self, func, f):
7302 """Overrriden from TypeHandler."""
7303 f.write(" void SetHeader(GLsizei count) {\n")
7304 f.write(
7305 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
7306 f.write(" }\n")
7307 f.write("\n")
7309 def WriteImmediateCmdInit(self, func, f):
7310 """Overrriden from TypeHandler."""
7311 f.write(" void Init(%s) {\n" %
7312 func.MakeTypedInitString("_"))
7313 f.write(" SetHeader(_count);\n")
7314 args = func.GetCmdArgs()
7315 for arg in args:
7316 f.write(" %s = _%s;\n" % (arg.name, arg.name))
7317 f.write(" memcpy(ImmediateDataAddress(this),\n")
7318 pointer_arg = func.GetLastOriginalPointerArg()
7319 f.write(" _%s, ComputeDataSize(_count));\n" % pointer_arg.name)
7320 f.write(" }\n")
7321 f.write("\n")
7323 def WriteImmediateCmdSet(self, func, f):
7324 """Overrriden from TypeHandler."""
7325 f.write(" void* Set(void* cmd%s) {\n" %
7326 func.MakeTypedInitString("_", True))
7327 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
7328 func.MakeInitString("_"))
7329 f.write(" const uint32_t size = ComputeSize(_count);\n")
7330 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
7331 "cmd, size);\n")
7332 f.write(" }\n")
7333 f.write("\n")
7335 def WriteImmediateCmdHelper(self, func, f):
7336 """Overrriden from TypeHandler."""
7337 code = """ void %(name)s(%(typed_args)s) {
7338 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
7339 gles2::cmds::%(name)s* c =
7340 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
7341 if (c) {
7342 c->Init(%(args)s);
7347 f.write(code % {
7348 "name": func.name,
7349 "typed_args": func.MakeTypedInitString(""),
7350 "args": func.MakeInitString("")
7353 def WriteImmediateFormatTest(self, func, f):
7354 """Overrriden from TypeHandler."""
7355 args = func.GetOriginalArgs()
7356 count_param = 0
7357 for arg in args:
7358 if arg.name == "count":
7359 count_param = int(arg.GetValidClientSideCmdArg(func))
7360 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
7361 f.write(" const int kSomeBaseValueToTestWith = 51;\n")
7362 f.write(" static %s data[] = {\n" % self.GetArrayType(func))
7363 for v in range(0, self.GetArrayCount(func) * count_param):
7364 f.write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
7365 (self.GetArrayType(func), v))
7366 f.write(" };\n")
7367 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
7368 (func.name, func.name))
7369 f.write(" const GLsizei kNumElements = %d;\n" % count_param)
7370 f.write(" const size_t kExpectedCmdSize =\n")
7371 f.write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
7372 (self.GetArrayType(func), self.GetArrayCount(func)))
7373 f.write(" void* next_cmd = cmd.Set(\n")
7374 f.write(" &cmd")
7375 for value, arg in enumerate(args):
7376 if arg.IsPointer():
7377 f.write(",\n data")
7378 elif arg.IsConstant():
7379 continue
7380 else:
7381 f.write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
7382 f.write(");\n")
7383 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
7384 func.name)
7385 f.write(" cmd.header.command);\n")
7386 f.write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
7387 for value, arg in enumerate(args):
7388 if arg.IsPointer() or arg.IsConstant():
7389 continue
7390 f.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
7391 (arg.type, value + 1, arg.name))
7392 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
7393 f.write(" next_cmd, sizeof(cmd) +\n")
7394 f.write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
7395 f.write(" // TODO(gman): Check that data was inserted;\n")
7396 f.write("}\n")
7397 f.write("\n")
7399 class PUTSTRHandler(ArrayArgTypeHandler):
7400 """Handler for functions that pass a string array."""
7402 def __GetDataArg(self, func):
7403 """Return the argument that points to the 2D char arrays"""
7404 for arg in func.GetOriginalArgs():
7405 if arg.IsPointer2D():
7406 return arg
7407 return None
7409 def __GetLengthArg(self, func):
7410 """Return the argument that holds length for each char array"""
7411 for arg in func.GetOriginalArgs():
7412 if arg.IsPointer() and not arg.IsPointer2D():
7413 return arg
7414 return None
7416 def WriteGLES2Implementation(self, func, f):
7417 """Overrriden from TypeHandler."""
7418 f.write("%s GLES2Implementation::%s(%s) {\n" %
7419 (func.return_type, func.original_name,
7420 func.MakeTypedOriginalArgString("")))
7421 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7422 func.WriteDestinationInitalizationValidation(f)
7423 self.WriteClientGLCallLog(func, f)
7424 data_arg = self.__GetDataArg(func)
7425 length_arg = self.__GetLengthArg(func)
7426 log_code_block = """ GPU_CLIENT_LOG_CODE_BLOCK({
7427 for (GLsizei ii = 0; ii < count; ++ii) {
7428 if (%(data)s[ii]) {"""
7429 if length_arg == None:
7430 log_code_block += """
7431 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
7432 else:
7433 log_code_block += """
7434 if (%(length)s && %(length)s[ii] >= 0) {
7435 const std::string my_str(%(data)s[ii], %(length)s[ii]);
7436 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
7437 } else {
7438 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
7439 }"""
7440 log_code_block += """
7441 } else {
7442 GPU_CLIENT_LOG(" " << ii << ": NULL");
7447 f.write(log_code_block % {
7448 'data': data_arg.name,
7449 'length': length_arg.name if not length_arg == None else ''
7451 for arg in func.GetOriginalArgs():
7452 arg.WriteClientSideValidationCode(f, func)
7454 bucket_args = []
7455 for arg in func.GetOriginalArgs():
7456 if arg.name == 'count' or arg == self.__GetLengthArg(func):
7457 continue
7458 if arg == self.__GetDataArg(func):
7459 bucket_args.append('kResultBucketId')
7460 else:
7461 bucket_args.append(arg.name)
7462 code_block = """
7463 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
7464 return;
7466 helper_->%(func_name)sBucket(%(bucket_args)s);
7467 helper_->SetBucketSize(kResultBucketId, 0);
7468 CheckGLError();
7472 f.write(code_block % {
7473 'data': data_arg.name,
7474 'length': length_arg.name if not length_arg == None else 'NULL',
7475 'func_name': func.name,
7476 'bucket_args': ', '.join(bucket_args),
7479 def WriteGLES2ImplementationUnitTest(self, func, f):
7480 """Overrriden from TypeHandler."""
7481 code = """
7482 TEST_F(GLES2ImplementationTest, %(name)s) {
7483 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7484 const char* kString1 = "happy";
7485 const char* kString2 = "ending";
7486 const size_t kString1Size = ::strlen(kString1) + 1;
7487 const size_t kString2Size = ::strlen(kString2) + 1;
7488 const size_t kHeaderSize = sizeof(GLint) * 3;
7489 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
7490 const size_t kPaddedHeaderSize =
7491 transfer_buffer_->RoundToAlignment(kHeaderSize);
7492 const size_t kPaddedString1Size =
7493 transfer_buffer_->RoundToAlignment(kString1Size);
7494 const size_t kPaddedString2Size =
7495 transfer_buffer_->RoundToAlignment(kString2Size);
7496 struct Cmds {
7497 cmd::SetBucketSize set_bucket_size;
7498 cmd::SetBucketData set_bucket_header;
7499 cmd::SetToken set_token1;
7500 cmd::SetBucketData set_bucket_data1;
7501 cmd::SetToken set_token2;
7502 cmd::SetBucketData set_bucket_data2;
7503 cmd::SetToken set_token3;
7504 cmds::%(name)sBucket cmd_bucket;
7505 cmd::SetBucketSize clear_bucket_size;
7508 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7509 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
7510 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
7512 Cmds expected;
7513 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7514 expected.set_bucket_header.Init(
7515 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7516 expected.set_token1.Init(GetNextToken());
7517 expected.set_bucket_data1.Init(
7518 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
7519 expected.set_token2.Init(GetNextToken());
7520 expected.set_bucket_data2.Init(
7521 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
7522 mem2.offset);
7523 expected.set_token3.Init(GetNextToken());
7524 expected.cmd_bucket.Init(%(bucket_args)s);
7525 expected.clear_bucket_size.Init(kBucketId, 0);
7526 const char* kStrings[] = { kString1, kString2 };
7527 gl_->%(name)s(%(gl_args)s);
7528 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7531 gl_args = []
7532 bucket_args = []
7533 for arg in func.GetOriginalArgs():
7534 if arg == self.__GetDataArg(func):
7535 gl_args.append('kStrings')
7536 bucket_args.append('kBucketId')
7537 elif arg == self.__GetLengthArg(func):
7538 gl_args.append('NULL')
7539 elif arg.name == 'count':
7540 gl_args.append('2')
7541 else:
7542 gl_args.append(arg.GetValidClientSideArg(func))
7543 bucket_args.append(arg.GetValidClientSideArg(func))
7544 f.write(code % {
7545 'name': func.name,
7546 'gl_args': ", ".join(gl_args),
7547 'bucket_args': ", ".join(bucket_args),
7550 if self.__GetLengthArg(func) == None:
7551 return
7552 code = """
7553 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7554 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7555 const char* kString = "foobar******";
7556 const size_t kStringSize = 6; // We only need "foobar".
7557 const size_t kHeaderSize = sizeof(GLint) * 2;
7558 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7559 const size_t kPaddedHeaderSize =
7560 transfer_buffer_->RoundToAlignment(kHeaderSize);
7561 const size_t kPaddedStringSize =
7562 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7563 struct Cmds {
7564 cmd::SetBucketSize set_bucket_size;
7565 cmd::SetBucketData set_bucket_header;
7566 cmd::SetToken set_token1;
7567 cmd::SetBucketData set_bucket_data;
7568 cmd::SetToken set_token2;
7569 cmds::ShaderSourceBucket shader_source_bucket;
7570 cmd::SetBucketSize clear_bucket_size;
7573 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7574 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7576 Cmds expected;
7577 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7578 expected.set_bucket_header.Init(
7579 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7580 expected.set_token1.Init(GetNextToken());
7581 expected.set_bucket_data.Init(
7582 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7583 expected.set_token2.Init(GetNextToken());
7584 expected.shader_source_bucket.Init(%(bucket_args)s);
7585 expected.clear_bucket_size.Init(kBucketId, 0);
7586 const char* kStrings[] = { kString };
7587 const GLint kLength[] = { kStringSize };
7588 gl_->%(name)s(%(gl_args)s);
7589 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7592 gl_args = []
7593 for arg in func.GetOriginalArgs():
7594 if arg == self.__GetDataArg(func):
7595 gl_args.append('kStrings')
7596 elif arg == self.__GetLengthArg(func):
7597 gl_args.append('kLength')
7598 elif arg.name == 'count':
7599 gl_args.append('1')
7600 else:
7601 gl_args.append(arg.GetValidClientSideArg(func))
7602 f.write(code % {
7603 'name': func.name,
7604 'gl_args': ", ".join(gl_args),
7605 'bucket_args': ", ".join(bucket_args),
7608 def WriteBucketServiceUnitTest(self, func, f, *extras):
7609 """Overrriden from TypeHandler."""
7610 cmd_args = []
7611 cmd_args_with_invalid_id = []
7612 gl_args = []
7613 for index, arg in enumerate(func.GetOriginalArgs()):
7614 if arg == self.__GetLengthArg(func):
7615 gl_args.append('_')
7616 elif arg.name == 'count':
7617 gl_args.append('1')
7618 elif arg == self.__GetDataArg(func):
7619 cmd_args.append('kBucketId')
7620 cmd_args_with_invalid_id.append('kBucketId')
7621 gl_args.append('_')
7622 elif index == 0: # Resource ID arg
7623 cmd_args.append(arg.GetValidArg(func))
7624 cmd_args_with_invalid_id.append('kInvalidClientId')
7625 gl_args.append(arg.GetValidGLArg(func))
7626 else:
7627 cmd_args.append(arg.GetValidArg(func))
7628 cmd_args_with_invalid_id.append(arg.GetValidArg(func))
7629 gl_args.append(arg.GetValidGLArg(func))
7631 test = """
7632 TEST_P(%(test_name)s, %(name)sValidArgs) {
7633 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7634 const uint32 kBucketId = 123;
7635 const char kSource0[] = "hello";
7636 const char* kSource[] = { kSource0 };
7637 const char kValidStrEnd = 0;
7638 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7639 cmds::%(name)s cmd;
7640 cmd.Init(%(cmd_args)s);
7641 decoder_->set_unsafe_es3_apis_enabled(true);
7642 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7643 if func.IsUnsafe():
7644 test += """
7645 decoder_->set_unsafe_es3_apis_enabled(false);
7646 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7648 test += """
7651 self.WriteValidUnitTest(func, f, test, {
7652 'cmd_args': ", ".join(cmd_args),
7653 'gl_args': ", ".join(gl_args),
7654 }, *extras)
7656 test = """
7657 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7658 const uint32 kBucketId = 123;
7659 const char kSource0[] = "hello";
7660 const char* kSource[] = { kSource0 };
7661 const char kValidStrEnd = 0;
7662 decoder_->set_unsafe_es3_apis_enabled(true);
7663 cmds::%(name)s cmd;
7664 // Test no bucket.
7665 cmd.Init(%(cmd_args)s);
7666 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7667 // Test invalid client.
7668 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7669 cmd.Init(%(cmd_args_with_invalid_id)s);
7670 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7671 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7674 self.WriteValidUnitTest(func, f, test, {
7675 'cmd_args': ", ".join(cmd_args),
7676 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id),
7677 }, *extras)
7679 test = """
7680 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7681 const uint32 kBucketId = 123;
7682 const char kSource0[] = "hello";
7683 const char* kSource[] = { kSource0 };
7684 const char kValidStrEnd = 0;
7685 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7686 const GLsizei kTests[] = {
7687 kCount + 1,
7689 std::numeric_limits<GLsizei>::max(),
7692 decoder_->set_unsafe_es3_apis_enabled(true);
7693 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7694 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7695 cmds::%(name)s cmd;
7696 cmd.Init(%(cmd_args)s);
7697 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7701 self.WriteValidUnitTest(func, f, test, {
7702 'cmd_args': ", ".join(cmd_args),
7703 }, *extras)
7705 test = """
7706 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7707 const uint32 kBucketId = 123;
7708 const char kSource0[] = "hello";
7709 const char* kSource[] = { kSource0 };
7710 const char kInvalidStrEnd = '*';
7711 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7712 cmds::%(name)s cmd;
7713 cmd.Init(%(cmd_args)s);
7714 decoder_->set_unsafe_es3_apis_enabled(true);
7715 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7718 self.WriteValidUnitTest(func, f, test, {
7719 'cmd_args': ", ".join(cmd_args),
7720 }, *extras)
7723 class PUTXnHandler(ArrayArgTypeHandler):
7724 """Handler for glUniform?f functions."""
7726 def WriteHandlerImplementation(self, func, f):
7727 """Overrriden from TypeHandler."""
7728 code = """ %(type)s temp[%(count)s] = { %(values)s};"""
7729 if func.IsUnsafe():
7730 code += """
7731 gl%(name)sv(%(location)s, 1, &temp[0]);
7733 else:
7734 code += """
7735 Do%(name)sv(%(location)s, 1, &temp[0]);
7737 values = ""
7738 args = func.GetOriginalArgs()
7739 count = int(self.GetArrayCount(func))
7740 num_args = len(args)
7741 for ii in range(count):
7742 values += "%s, " % args[len(args) - count + ii].name
7744 f.write(code % {
7745 'name': func.name,
7746 'count': self.GetArrayCount(func),
7747 'type': self.GetArrayType(func),
7748 'location': args[0].name,
7749 'args': func.MakeOriginalArgString(""),
7750 'values': values,
7753 def WriteServiceUnitTest(self, func, f, *extras):
7754 """Overrriden from TypeHandler."""
7755 valid_test = """
7756 TEST_P(%(test_name)s, %(name)sValidArgs) {
7757 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7758 SpecializedSetup<cmds::%(name)s, 0>(true);
7759 cmds::%(name)s cmd;
7760 cmd.Init(%(args)s);"""
7761 if func.IsUnsafe():
7762 valid_test += """
7763 decoder_->set_unsafe_es3_apis_enabled(true);"""
7764 valid_test += """
7765 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7766 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7767 if func.IsUnsafe():
7768 valid_test += """
7769 decoder_->set_unsafe_es3_apis_enabled(false);
7770 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7771 valid_test += """
7774 args = func.GetOriginalArgs()
7775 local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
7776 self.WriteValidUnitTest(func, f, valid_test, {
7777 'name': func.name,
7778 'count': self.GetArrayCount(func),
7779 'local_args': local_args,
7780 }, *extras)
7782 invalid_test = """
7783 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7784 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7785 SpecializedSetup<cmds::%(name)s, 0>(false);
7786 cmds::%(name)s cmd;
7787 cmd.Init(%(args)s);
7788 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7791 self.WriteInvalidUnitTest(func, f, invalid_test, {
7792 'name': func.GetInfo('name'),
7793 'count': self.GetArrayCount(func),
7797 class GLcharHandler(CustomHandler):
7798 """Handler for functions that pass a single string ."""
7800 def WriteImmediateCmdComputeSize(self, func, f):
7801 """Overrriden from TypeHandler."""
7802 f.write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7803 f.write(" return static_cast<uint32_t>(\n")
7804 f.write(" sizeof(ValueType) + data_size); // NOLINT\n")
7805 f.write(" }\n")
7807 def WriteImmediateCmdSetHeader(self, func, f):
7808 """Overrriden from TypeHandler."""
7809 code = """
7810 void SetHeader(uint32_t data_size) {
7811 header.SetCmdBySize<ValueType>(data_size);
7814 f.write(code)
7816 def WriteImmediateCmdInit(self, func, f):
7817 """Overrriden from TypeHandler."""
7818 last_arg = func.GetLastOriginalArg()
7819 args = func.GetCmdArgs()
7820 set_code = []
7821 for arg in args:
7822 set_code.append(" %s = _%s;" % (arg.name, arg.name))
7823 code = """
7824 void Init(%(typed_args)s, uint32_t _data_size) {
7825 SetHeader(_data_size);
7826 %(set_code)s
7827 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7831 f.write(code % {
7832 "typed_args": func.MakeTypedArgString("_"),
7833 "set_code": "\n".join(set_code),
7834 "last_arg": last_arg.name
7837 def WriteImmediateCmdSet(self, func, f):
7838 """Overrriden from TypeHandler."""
7839 last_arg = func.GetLastOriginalArg()
7840 f.write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7841 func.MakeTypedCmdArgString("_", True))
7842 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7843 func.MakeCmdArgString("_"))
7844 f.write(" return NextImmediateCmdAddress<ValueType>("
7845 "cmd, _data_size);\n")
7846 f.write(" }\n")
7847 f.write("\n")
7849 def WriteImmediateCmdHelper(self, func, f):
7850 """Overrriden from TypeHandler."""
7851 code = """ void %(name)s(%(typed_args)s) {
7852 const uint32_t data_size = strlen(name);
7853 gles2::cmds::%(name)s* c =
7854 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7855 if (c) {
7856 c->Init(%(args)s, data_size);
7861 f.write(code % {
7862 "name": func.name,
7863 "typed_args": func.MakeTypedOriginalArgString(""),
7864 "args": func.MakeOriginalArgString(""),
7868 def WriteImmediateFormatTest(self, func, f):
7869 """Overrriden from TypeHandler."""
7870 init_code = []
7871 check_code = []
7872 all_but_last_arg = func.GetCmdArgs()[:-1]
7873 for value, arg in enumerate(all_but_last_arg):
7874 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
7875 for value, arg in enumerate(all_but_last_arg):
7876 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7877 (arg.type, value + 11, arg.name))
7878 code = """
7879 TEST_F(GLES2FormatTest, %(func_name)s) {
7880 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7881 static const char* const test_str = \"test string\";
7882 void* next_cmd = cmd.Set(
7883 &cmd,
7884 %(init_code)s
7885 test_str,
7886 strlen(test_str));
7887 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7888 cmd.header.command);
7889 EXPECT_EQ(sizeof(cmd) +
7890 RoundSizeToMultipleOfEntries(strlen(test_str)),
7891 cmd.header.size * 4u);
7892 EXPECT_EQ(static_cast<char*>(next_cmd),
7893 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7894 RoundSizeToMultipleOfEntries(strlen(test_str)));
7895 %(check_code)s
7896 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7897 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7898 CheckBytesWritten(
7899 next_cmd,
7900 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7901 sizeof(cmd) + strlen(test_str));
7905 f.write(code % {
7906 'func_name': func.name,
7907 'init_code': "\n".join(init_code),
7908 'check_code': "\n".join(check_code),
7912 class GLcharNHandler(CustomHandler):
7913 """Handler for functions that pass a single string with an optional len."""
7915 def InitFunction(self, func):
7916 """Overrriden from TypeHandler."""
7917 func.cmd_args = []
7918 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
7920 def NeedsDataTransferFunction(self, func):
7921 """Overriden from TypeHandler."""
7922 return False
7924 def WriteServiceImplementation(self, func, f):
7925 """Overrriden from TypeHandler."""
7926 self.WriteServiceHandlerFunctionHeader(func, f)
7927 f.write("""
7928 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7929 Bucket* bucket = GetBucket(bucket_id);
7930 if (!bucket || bucket->size() == 0) {
7931 return error::kInvalidArguments;
7933 std::string str;
7934 if (!bucket->GetAsString(&str)) {
7935 return error::kInvalidArguments;
7937 %(gl_func_name)s(0, str.c_str());
7938 return error::kNoError;
7941 """ % {
7942 'name': func.name,
7943 'gl_func_name': func.GetGLFunctionName(),
7944 'bucket_id': func.cmd_args[0].name,
7948 class IsHandler(TypeHandler):
7949 """Handler for glIs____ type and glGetError functions."""
7951 def InitFunction(self, func):
7952 """Overrriden from TypeHandler."""
7953 func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7954 func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7955 if func.GetInfo('result') == None:
7956 func.AddInfo('result', ['uint32_t'])
7958 def WriteServiceUnitTest(self, func, f, *extras):
7959 """Overrriden from TypeHandler."""
7960 valid_test = """
7961 TEST_P(%(test_name)s, %(name)sValidArgs) {
7962 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7963 SpecializedSetup<cmds::%(name)s, 0>(true);
7964 cmds::%(name)s cmd;
7965 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7966 if func.IsUnsafe():
7967 valid_test += """
7968 decoder_->set_unsafe_es3_apis_enabled(true);"""
7969 valid_test += """
7970 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7971 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7972 if func.IsUnsafe():
7973 valid_test += """
7974 decoder_->set_unsafe_es3_apis_enabled(false);
7975 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7976 valid_test += """
7979 comma = ""
7980 if len(func.GetOriginalArgs()):
7981 comma =", "
7982 self.WriteValidUnitTest(func, f, valid_test, {
7983 'comma': comma,
7984 }, *extras)
7986 invalid_test = """
7987 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7988 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7989 SpecializedSetup<cmds::%(name)s, 0>(false);
7990 cmds::%(name)s cmd;
7991 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7992 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7995 self.WriteInvalidUnitTest(func, f, invalid_test, {
7996 'comma': comma,
7997 }, *extras)
7999 invalid_test = """
8000 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
8001 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
8002 SpecializedSetup<cmds::%(name)s, 0>(false);"""
8003 if func.IsUnsafe():
8004 invalid_test += """
8005 decoder_->set_unsafe_es3_apis_enabled(true);"""
8006 invalid_test += """
8007 cmds::%(name)s cmd;
8008 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
8009 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
8010 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
8011 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
8012 if func.IsUnsafe():
8013 invalid_test += """
8014 decoder_->set_unsafe_es3_apis_enabled(true);"""
8015 invalid_test += """
8018 self.WriteValidUnitTest(func, f, invalid_test, {
8019 'comma': comma,
8020 }, *extras)
8022 def WriteServiceImplementation(self, func, f):
8023 """Overrriden from TypeHandler."""
8024 self.WriteServiceHandlerFunctionHeader(func, f)
8025 self.WriteHandlerExtensionCheck(func, f)
8026 args = func.GetOriginalArgs()
8027 for arg in args:
8028 arg.WriteGetCode(f)
8030 code = """ typedef cmds::%(func_name)s::Result Result;
8031 Result* result_dst = GetSharedMemoryAs<Result*>(
8032 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
8033 if (!result_dst) {
8034 return error::kOutOfBounds;
8037 f.write(code % {'func_name': func.name})
8038 func.WriteHandlerValidation(f)
8039 if func.IsUnsafe():
8040 assert func.GetInfo('id_mapping')
8041 assert len(func.GetInfo('id_mapping')) == 1
8042 assert len(args) == 1
8043 id_type = func.GetInfo('id_mapping')[0]
8044 f.write(" %s service_%s = 0;\n" % (args[0].type, id_type.lower()))
8045 f.write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
8046 (id_type, id_type.lower(), id_type.lower()))
8047 else:
8048 f.write(" *result_dst = %s(%s);\n" %
8049 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
8050 f.write(" return error::kNoError;\n")
8051 f.write("}\n")
8052 f.write("\n")
8054 def WriteGLES2Implementation(self, func, f):
8055 """Overrriden from TypeHandler."""
8056 impl_func = func.GetInfo('impl_func')
8057 if impl_func == None or impl_func == True:
8058 error_value = func.GetInfo("error_value") or "GL_FALSE"
8059 f.write("%s GLES2Implementation::%s(%s) {\n" %
8060 (func.return_type, func.original_name,
8061 func.MakeTypedOriginalArgString("")))
8062 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
8063 self.WriteTraceEvent(func, f)
8064 func.WriteDestinationInitalizationValidation(f)
8065 self.WriteClientGLCallLog(func, f)
8066 f.write(" typedef cmds::%s::Result Result;\n" % func.name)
8067 f.write(" Result* result = GetResultAs<Result*>();\n")
8068 f.write(" if (!result) {\n")
8069 f.write(" return %s;\n" % error_value)
8070 f.write(" }\n")
8071 f.write(" *result = 0;\n")
8072 assert len(func.GetOriginalArgs()) == 1
8073 id_arg = func.GetOriginalArgs()[0]
8074 if id_arg.type == 'GLsync':
8075 arg_string = "ToGLuint(%s)" % func.MakeOriginalArgString("")
8076 else:
8077 arg_string = func.MakeOriginalArgString("")
8078 f.write(
8079 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
8080 (func.name, arg_string))
8081 f.write(" WaitForCmd();\n")
8082 f.write(" %s result_value = *result" % func.return_type)
8083 if func.return_type == "GLboolean":
8084 f.write(" != 0")
8085 f.write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
8086 f.write(" CheckGLError();\n")
8087 f.write(" return result_value;\n")
8088 f.write("}\n")
8089 f.write("\n")
8091 def WriteGLES2ImplementationUnitTest(self, func, f):
8092 """Overrriden from TypeHandler."""
8093 client_test = func.GetInfo('client_test')
8094 if client_test == None or client_test == True:
8095 code = """
8096 TEST_F(GLES2ImplementationTest, %(name)s) {
8097 struct Cmds {
8098 cmds::%(name)s cmd;
8101 Cmds expected;
8102 ExpectedMemoryInfo result1 =
8103 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
8104 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
8106 EXPECT_CALL(*command_buffer(), OnFlush())
8107 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
8108 .RetiresOnSaturation();
8110 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
8111 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
8112 EXPECT_TRUE(result);
8115 args = func.GetOriginalArgs()
8116 assert len(args) == 1
8117 f.write(code % {
8118 'name': func.name,
8119 'cmd_id_value': args[0].GetValidClientSideCmdArg(func),
8120 'gl_id_value': args[0].GetValidClientSideArg(func) })
8123 class STRnHandler(TypeHandler):
8124 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
8125 GetTranslatedShaderSourceANGLE."""
8127 def InitFunction(self, func):
8128 """Overrriden from TypeHandler."""
8129 # remove all but the first cmd args.
8130 cmd_args = func.GetCmdArgs()
8131 func.ClearCmdArgs()
8132 func.AddCmdArg(cmd_args[0])
8133 # add on a bucket id.
8134 func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
8136 def WriteGLES2Implementation(self, func, f):
8137 """Overrriden from TypeHandler."""
8138 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
8139 GPU_CLIENT_SINGLE_THREAD_CHECK();
8141 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
8142 << "] gl%(func_name)s" << "("
8143 << %(arg0)s << ", "
8144 << %(arg1)s << ", "
8145 << static_cast<void*>(%(arg2)s) << ", "
8146 << static_cast<void*>(%(arg3)s) << ")");
8147 helper_->SetBucketSize(kResultBucketId, 0);
8148 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
8149 std::string str;
8150 GLsizei max_size = 0;
8151 if (GetBucketAsString(kResultBucketId, &str)) {
8152 if (bufsize > 0) {
8153 max_size =
8154 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
8155 memcpy(%(dest_name)s, str.c_str(), max_size);
8156 %(dest_name)s[max_size] = '\\0';
8157 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
8160 if (%(length_name)s != NULL) {
8161 *%(length_name)s = max_size;
8163 CheckGLError();
8166 args = func.GetOriginalArgs()
8167 str_args = {
8168 'return_type': func.return_type,
8169 'func_name': func.original_name,
8170 'args': func.MakeTypedOriginalArgString(""),
8171 'id_name': args[0].name,
8172 'bufsize_name': args[1].name,
8173 'length_name': args[2].name,
8174 'dest_name': args[3].name,
8175 'arg0': args[0].name,
8176 'arg1': args[1].name,
8177 'arg2': args[2].name,
8178 'arg3': args[3].name,
8180 f.write(code_1 % str_args)
8181 func.WriteDestinationInitalizationValidation(f)
8182 f.write(code_2 % str_args)
8184 def WriteServiceUnitTest(self, func, f, *extras):
8185 """Overrriden from TypeHandler."""
8186 valid_test = """
8187 TEST_P(%(test_name)s, %(name)sValidArgs) {
8188 const char* kInfo = "hello";
8189 const uint32_t kBucketId = 123;
8190 SpecializedSetup<cmds::%(name)s, 0>(true);
8191 %(expect_len_code)s
8192 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
8193 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
8194 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
8195 cmds::%(name)s cmd;
8196 cmd.Init(%(args)s);
8197 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8198 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
8199 ASSERT_TRUE(bucket != NULL);
8200 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
8201 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
8202 bucket->size()));
8203 EXPECT_EQ(GL_NO_ERROR, GetGLError());
8206 args = func.GetOriginalArgs()
8207 id_name = args[0].GetValidGLArg(func)
8208 get_len_func = func.GetInfo('get_len_func')
8209 get_len_enum = func.GetInfo('get_len_enum')
8210 sub = {
8211 'id_name': id_name,
8212 'get_len_func': get_len_func,
8213 'get_len_enum': get_len_enum,
8214 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
8215 args[0].GetValidGLArg(func),
8216 'args': '%s, kBucketId' % args[0].GetValidArg(func),
8217 'expect_len_code': '',
8219 if get_len_func and get_len_func[0:2] == 'gl':
8220 sub['expect_len_code'] = (
8221 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
8222 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
8223 get_len_func[2:], id_name, get_len_enum)
8224 self.WriteValidUnitTest(func, f, valid_test, sub, *extras)
8226 invalid_test = """
8227 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
8228 const uint32_t kBucketId = 123;
8229 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
8230 .Times(0);
8231 cmds::%(name)s cmd;
8232 cmd.Init(kInvalidClientId, kBucketId);
8233 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
8234 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
8237 self.WriteValidUnitTest(func, f, invalid_test, *extras)
8239 def WriteServiceImplementation(self, func, f):
8240 """Overrriden from TypeHandler."""
8241 pass
8243 class NamedType(object):
8244 """A class that represents a type of an argument in a client function.
8246 A type of an argument that is to be passed through in the command buffer
8247 command. Currently used only for the arguments that are specificly named in
8248 the 'cmd_buffer_functions.txt' f, mostly enums.
8251 def __init__(self, info):
8252 assert not 'is_complete' in info or info['is_complete'] == True
8253 self.info = info
8254 self.valid = info['valid']
8255 if 'invalid' in info:
8256 self.invalid = info['invalid']
8257 else:
8258 self.invalid = []
8259 if 'valid_es3' in info:
8260 self.valid_es3 = info['valid_es3']
8261 else:
8262 self.valid_es3 = []
8263 if 'deprecated_es3' in info:
8264 self.deprecated_es3 = info['deprecated_es3']
8265 else:
8266 self.deprecated_es3 = []
8268 def GetType(self):
8269 return self.info['type']
8271 def GetInvalidValues(self):
8272 return self.invalid
8274 def GetValidValues(self):
8275 return self.valid
8277 def GetValidValuesES3(self):
8278 return self.valid_es3
8280 def GetDeprecatedValuesES3(self):
8281 return self.deprecated_es3
8283 def IsConstant(self):
8284 if not 'is_complete' in self.info:
8285 return False
8287 return len(self.GetValidValues()) == 1
8289 def GetConstantValue(self):
8290 return self.GetValidValues()[0]
8292 class Argument(object):
8293 """A class that represents a function argument."""
8295 cmd_type_map_ = {
8296 'GLenum': 'uint32_t',
8297 'GLint': 'int32_t',
8298 'GLintptr': 'int32_t',
8299 'GLsizei': 'int32_t',
8300 'GLsizeiptr': 'int32_t',
8301 'GLfloat': 'float',
8302 'GLclampf': 'float',
8304 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
8306 def __init__(self, name, type):
8307 self.name = name
8308 self.optional = type.endswith("Optional*")
8309 if self.optional:
8310 type = type[:-9] + "*"
8311 self.type = type
8313 if type in self.cmd_type_map_:
8314 self.cmd_type = self.cmd_type_map_[type]
8315 else:
8316 self.cmd_type = 'uint32_t'
8318 def IsPointer(self):
8319 """Returns true if argument is a pointer."""
8320 return False
8322 def IsPointer2D(self):
8323 """Returns true if argument is a 2D pointer."""
8324 return False
8326 def IsConstant(self):
8327 """Returns true if the argument has only one valid value."""
8328 return False
8330 def AddCmdArgs(self, args):
8331 """Adds command arguments for this argument to the given list."""
8332 if not self.IsConstant():
8333 return args.append(self)
8335 def AddInitArgs(self, args):
8336 """Adds init arguments for this argument to the given list."""
8337 if not self.IsConstant():
8338 return args.append(self)
8340 def GetValidArg(self, func):
8341 """Gets a valid value for this argument."""
8342 valid_arg = func.GetValidArg(self)
8343 if valid_arg != None:
8344 return valid_arg
8346 index = func.GetOriginalArgs().index(self)
8347 return str(index + 1)
8349 def GetValidClientSideArg(self, func):
8350 """Gets a valid value for this argument."""
8351 valid_arg = func.GetValidArg(self)
8352 if valid_arg != None:
8353 return valid_arg
8355 if self.IsPointer():
8356 return 'nullptr'
8357 index = func.GetOriginalArgs().index(self)
8358 if self.type == 'GLsync':
8359 return ("reinterpret_cast<GLsync>(%d)" % (index + 1))
8360 return str(index + 1)
8362 def GetValidClientSideCmdArg(self, func):
8363 """Gets a valid value for this argument."""
8364 valid_arg = func.GetValidArg(self)
8365 if valid_arg != None:
8366 return valid_arg
8367 try:
8368 index = func.GetOriginalArgs().index(self)
8369 return str(index + 1)
8370 except ValueError:
8371 pass
8372 index = func.GetCmdArgs().index(self)
8373 return str(index + 1)
8375 def GetValidGLArg(self, func):
8376 """Gets a valid GL value for this argument."""
8377 value = self.GetValidArg(func)
8378 if self.type == 'GLsync':
8379 return ("reinterpret_cast<GLsync>(%s)" % value)
8380 return value
8382 def GetValidNonCachedClientSideArg(self, func):
8383 """Returns a valid value for this argument in a GL call.
8384 Using the value will produce a command buffer service invocation.
8385 Returns None if there is no such value."""
8386 value = '123'
8387 if self.type == 'GLsync':
8388 return ("reinterpret_cast<GLsync>(%s)" % value)
8389 return value
8391 def GetValidNonCachedClientSideCmdArg(self, func):
8392 """Returns a valid value for this argument in a command buffer command.
8393 Calling the GL function with the value returned by
8394 GetValidNonCachedClientSideArg will result in a command buffer command
8395 that contains the value returned by this function. """
8396 return '123'
8398 def GetNumInvalidValues(self, func):
8399 """returns the number of invalid values to be tested."""
8400 return 0
8402 def GetInvalidArg(self, index):
8403 """returns an invalid value and expected parse result by index."""
8404 return ("---ERROR0---", "---ERROR2---", None)
8406 def GetLogArg(self):
8407 """Get argument appropriate for LOG macro."""
8408 if self.type == 'GLboolean':
8409 return 'GLES2Util::GetStringBool(%s)' % self.name
8410 if self.type == 'GLenum':
8411 return 'GLES2Util::GetStringEnum(%s)' % self.name
8412 return self.name
8414 def WriteGetCode(self, f):
8415 """Writes the code to get an argument from a command structure."""
8416 if self.type == 'GLsync':
8417 my_type = 'GLuint'
8418 else:
8419 my_type = self.type
8420 f.write(" %s %s = static_cast<%s>(c.%s);\n" %
8421 (my_type, self.name, my_type, self.name))
8423 def WriteValidationCode(self, f, func):
8424 """Writes the validation code for an argument."""
8425 pass
8427 def WriteClientSideValidationCode(self, f, func):
8428 """Writes the validation code for an argument."""
8429 pass
8431 def WriteDestinationInitalizationValidation(self, f, func):
8432 """Writes the client side destintion initialization validation."""
8433 pass
8435 def WriteDestinationInitalizationValidatationIfNeeded(self, f, func):
8436 """Writes the client side destintion initialization validation if needed."""
8437 parts = self.type.split(" ")
8438 if len(parts) > 1:
8439 return
8440 if parts[0] in self.need_validation_:
8441 f.write(
8442 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
8443 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
8445 def GetImmediateVersion(self):
8446 """Gets the immediate version of this argument."""
8447 return self
8449 def GetBucketVersion(self):
8450 """Gets the bucket version of this argument."""
8451 return self
8454 class BoolArgument(Argument):
8455 """class for GLboolean"""
8457 def __init__(self, name, type):
8458 Argument.__init__(self, name, 'GLboolean')
8460 def GetValidArg(self, func):
8461 """Gets a valid value for this argument."""
8462 return 'true'
8464 def GetValidClientSideArg(self, func):
8465 """Gets a valid value for this argument."""
8466 return 'true'
8468 def GetValidClientSideCmdArg(self, func):
8469 """Gets a valid value for this argument."""
8470 return 'true'
8472 def GetValidGLArg(self, func):
8473 """Gets a valid GL value for this argument."""
8474 return 'true'
8477 class UniformLocationArgument(Argument):
8478 """class for uniform locations."""
8480 def __init__(self, name):
8481 Argument.__init__(self, name, "GLint")
8483 def WriteGetCode(self, f):
8484 """Writes the code to get an argument from a command structure."""
8485 code = """ %s %s = static_cast<%s>(c.%s);
8487 f.write(code % (self.type, self.name, self.type, self.name))
8489 class DataSizeArgument(Argument):
8490 """class for data_size which Bucket commands do not need."""
8492 def __init__(self, name):
8493 Argument.__init__(self, name, "uint32_t")
8495 def GetBucketVersion(self):
8496 return None
8499 class SizeArgument(Argument):
8500 """class for GLsizei and GLsizeiptr."""
8502 def GetNumInvalidValues(self, func):
8503 """overridden from Argument."""
8504 if func.IsImmediate():
8505 return 0
8506 return 1
8508 def GetInvalidArg(self, index):
8509 """overridden from Argument."""
8510 return ("-1", "kNoError", "GL_INVALID_VALUE")
8512 def WriteValidationCode(self, f, func):
8513 """overridden from Argument."""
8514 if func.IsUnsafe():
8515 return
8516 code = """ if (%(var_name)s < 0) {
8517 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8518 return error::kNoError;
8521 f.write(code % {
8522 "var_name": self.name,
8523 "func_name": func.original_name,
8526 def WriteClientSideValidationCode(self, f, func):
8527 """overridden from Argument."""
8528 code = """ if (%(var_name)s < 0) {
8529 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8530 return;
8533 f.write(code % {
8534 "var_name": self.name,
8535 "func_name": func.original_name,
8539 class SizeNotNegativeArgument(SizeArgument):
8540 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8542 def __init__(self, name, type, gl_type):
8543 SizeArgument.__init__(self, name, gl_type)
8545 def GetInvalidArg(self, index):
8546 """overridden from SizeArgument."""
8547 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8549 def WriteValidationCode(self, f, func):
8550 """overridden from SizeArgument."""
8551 pass
8554 class EnumBaseArgument(Argument):
8555 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8556 ValidatedBoolArgument."""
8558 def __init__(self, name, gl_type, type, gl_error):
8559 Argument.__init__(self, name, gl_type)
8561 self.gl_error = gl_error
8562 name = type[len(gl_type):]
8563 self.type_name = name
8564 self.named_type = NamedType(_NAMED_TYPE_INFO[name])
8566 def IsConstant(self):
8567 return self.named_type.IsConstant()
8569 def GetConstantValue(self):
8570 return self.named_type.GetConstantValue()
8572 def WriteValidationCode(self, f, func):
8573 if func.IsUnsafe():
8574 return
8575 if self.named_type.IsConstant():
8576 return
8577 f.write(" if (!validators_->%s.IsValid(%s)) {\n" %
8578 (ToUnderscore(self.type_name), self.name))
8579 if self.gl_error == "GL_INVALID_ENUM":
8580 f.write(
8581 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8582 (func.original_name, self.name, self.name))
8583 else:
8584 f.write(
8585 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8586 (self.gl_error, func.original_name, self.name, self.gl_error))
8587 f.write(" return error::kNoError;\n")
8588 f.write(" }\n")
8590 def WriteClientSideValidationCode(self, f, func):
8591 if not self.named_type.IsConstant():
8592 return
8593 f.write(" if (%s != %s) {" % (self.name,
8594 self.GetConstantValue()))
8595 f.write(
8596 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8597 (self.gl_error, func.original_name, self.name, self.gl_error))
8598 if func.return_type == "void":
8599 f.write(" return;\n")
8600 else:
8601 f.write(" return %s;\n" % func.GetErrorReturnString())
8602 f.write(" }\n")
8604 def GetValidArg(self, func):
8605 valid_arg = func.GetValidArg(self)
8606 if valid_arg != None:
8607 return valid_arg
8608 valid = self.named_type.GetValidValues()
8609 if valid:
8610 return valid[0]
8612 index = func.GetOriginalArgs().index(self)
8613 return str(index + 1)
8615 def GetValidClientSideArg(self, func):
8616 """Gets a valid value for this argument."""
8617 return self.GetValidArg(func)
8619 def GetValidClientSideCmdArg(self, func):
8620 """Gets a valid value for this argument."""
8621 valid_arg = func.GetValidArg(self)
8622 if valid_arg != None:
8623 return valid_arg
8625 valid = self.named_type.GetValidValues()
8626 if valid:
8627 return valid[0]
8629 try:
8630 index = func.GetOriginalArgs().index(self)
8631 return str(index + 1)
8632 except ValueError:
8633 pass
8634 index = func.GetCmdArgs().index(self)
8635 return str(index + 1)
8637 def GetValidGLArg(self, func):
8638 """Gets a valid value for this argument."""
8639 return self.GetValidArg(func)
8641 def GetNumInvalidValues(self, func):
8642 """returns the number of invalid values to be tested."""
8643 return len(self.named_type.GetInvalidValues())
8645 def GetInvalidArg(self, index):
8646 """returns an invalid value by index."""
8647 invalid = self.named_type.GetInvalidValues()
8648 if invalid:
8649 num_invalid = len(invalid)
8650 if index >= num_invalid:
8651 index = num_invalid - 1
8652 return (invalid[index], "kNoError", self.gl_error)
8653 return ("---ERROR1---", "kNoError", self.gl_error)
8656 class EnumArgument(EnumBaseArgument):
8657 """A class that represents a GLenum argument"""
8659 def __init__(self, name, type):
8660 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
8662 def GetLogArg(self):
8663 """Overridden from Argument."""
8664 return ("GLES2Util::GetString%s(%s)" %
8665 (self.type_name, self.name))
8668 class IntArgument(EnumBaseArgument):
8669 """A class for a GLint argument that can only accept specific values.
8671 For example glTexImage2D takes a GLint for its internalformat
8672 argument instead of a GLenum.
8675 def __init__(self, name, type):
8676 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
8679 class ValidatedBoolArgument(EnumBaseArgument):
8680 """A class for a GLboolean argument that can only accept specific values.
8682 For example glUniformMatrix takes a GLboolean for it's transpose but it
8683 must be false.
8686 def __init__(self, name, type):
8687 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
8689 def GetLogArg(self):
8690 """Overridden from Argument."""
8691 return 'GLES2Util::GetStringBool(%s)' % self.name
8694 class BitFieldArgument(EnumBaseArgument):
8695 """A class for a GLbitfield argument that can only accept specific values.
8697 For example glFenceSync takes a GLbitfield for its flags argument bit it
8698 must be 0.
8701 def __init__(self, name, type):
8702 EnumBaseArgument.__init__(self, name, "GLbitfield", type,
8703 "GL_INVALID_VALUE")
8706 class ImmediatePointerArgument(Argument):
8707 """A class that represents an immediate argument to a function.
8709 An immediate argument is one where the data follows the command.
8712 def IsPointer(self):
8713 return True
8715 def GetPointedType(self):
8716 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8717 assert match
8718 return match.groupdict()['element_type']
8720 def AddCmdArgs(self, args):
8721 """Overridden from Argument."""
8722 pass
8724 def WriteGetCode(self, f):
8725 """Overridden from Argument."""
8726 f.write(
8727 " %s %s = GetImmediateDataAs<%s>(\n" %
8728 (self.type, self.name, self.type))
8729 f.write(" c, data_size, immediate_data_size);\n")
8731 def WriteValidationCode(self, f, func):
8732 """Overridden from Argument."""
8733 if self.optional:
8734 return
8735 f.write(" if (%s == NULL) {\n" % self.name)
8736 f.write(" return error::kOutOfBounds;\n")
8737 f.write(" }\n")
8739 def GetImmediateVersion(self):
8740 """Overridden from Argument."""
8741 return None
8743 def WriteDestinationInitalizationValidation(self, f, func):
8744 """Overridden from Argument."""
8745 self.WriteDestinationInitalizationValidatationIfNeeded(f, func)
8747 def GetLogArg(self):
8748 """Overridden from Argument."""
8749 return "static_cast<const void*>(%s)" % self.name
8752 class PointerArgument(Argument):
8753 """A class that represents a pointer argument to a function."""
8755 def IsPointer(self):
8756 """Overridden from Argument."""
8757 return True
8759 def IsPointer2D(self):
8760 """Overridden from Argument."""
8761 return self.type.count('*') == 2
8763 def GetPointedType(self):
8764 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8765 assert match
8766 return match.groupdict()['element_type']
8768 def GetValidArg(self, func):
8769 """Overridden from Argument."""
8770 return "shared_memory_id_, shared_memory_offset_"
8772 def GetValidGLArg(self, func):
8773 """Overridden from Argument."""
8774 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
8776 def GetNumInvalidValues(self, func):
8777 """Overridden from Argument."""
8778 return 2
8780 def GetInvalidArg(self, index):
8781 """Overridden from Argument."""
8782 if index == 0:
8783 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8784 else:
8785 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8786 "kOutOfBounds", None)
8788 def GetLogArg(self):
8789 """Overridden from Argument."""
8790 return "static_cast<const void*>(%s)" % self.name
8792 def AddCmdArgs(self, args):
8793 """Overridden from Argument."""
8794 args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
8795 args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
8797 def WriteGetCode(self, f):
8798 """Overridden from Argument."""
8799 f.write(
8800 " %s %s = GetSharedMemoryAs<%s>(\n" %
8801 (self.type, self.name, self.type))
8802 f.write(
8803 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8804 (self.name, self.name))
8806 def WriteValidationCode(self, f, func):
8807 """Overridden from Argument."""
8808 if self.optional:
8809 return
8810 f.write(" if (%s == NULL) {\n" % self.name)
8811 f.write(" return error::kOutOfBounds;\n")
8812 f.write(" }\n")
8814 def GetImmediateVersion(self):
8815 """Overridden from Argument."""
8816 return ImmediatePointerArgument(self.name, self.type)
8818 def GetBucketVersion(self):
8819 """Overridden from Argument."""
8820 if self.type.find('char') >= 0:
8821 if self.IsPointer2D():
8822 return InputStringArrayBucketArgument(self.name, self.type)
8823 return InputStringBucketArgument(self.name, self.type)
8824 return BucketPointerArgument(self.name, self.type)
8826 def WriteDestinationInitalizationValidation(self, f, func):
8827 """Overridden from Argument."""
8828 self.WriteDestinationInitalizationValidatationIfNeeded(f, func)
8831 class BucketPointerArgument(PointerArgument):
8832 """A class that represents an bucket argument to a function."""
8834 def AddCmdArgs(self, args):
8835 """Overridden from Argument."""
8836 pass
8838 def WriteGetCode(self, f):
8839 """Overridden from Argument."""
8840 f.write(
8841 " %s %s = bucket->GetData(0, data_size);\n" %
8842 (self.type, self.name))
8844 def WriteValidationCode(self, f, func):
8845 """Overridden from Argument."""
8846 pass
8848 def GetImmediateVersion(self):
8849 """Overridden from Argument."""
8850 return None
8852 def WriteDestinationInitalizationValidation(self, f, func):
8853 """Overridden from Argument."""
8854 self.WriteDestinationInitalizationValidatationIfNeeded(f, func)
8856 def GetLogArg(self):
8857 """Overridden from Argument."""
8858 return "static_cast<const void*>(%s)" % self.name
8861 class InputStringBucketArgument(Argument):
8862 """A string input argument where the string is passed in a bucket."""
8864 def __init__(self, name, type):
8865 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8867 def IsPointer(self):
8868 """Overridden from Argument."""
8869 return True
8871 def IsPointer2D(self):
8872 """Overridden from Argument."""
8873 return False
8876 class InputStringArrayBucketArgument(Argument):
8877 """A string array input argument where the strings are passed in a bucket."""
8879 def __init__(self, name, type):
8880 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8881 self._original_name = name
8883 def WriteGetCode(self, f):
8884 """Overridden from Argument."""
8885 code = """
8886 Bucket* bucket = GetBucket(c.%(name)s);
8887 if (!bucket) {
8888 return error::kInvalidArguments;
8890 GLsizei count = 0;
8891 std::vector<char*> strs;
8892 std::vector<GLint> len;
8893 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8894 return error::kInvalidArguments;
8896 const char** %(original_name)s =
8897 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8898 const GLint* length =
8899 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8900 (void)length;
8902 f.write(code % {
8903 'name': self.name,
8904 'original_name': self._original_name,
8907 def GetValidArg(self, func):
8908 return "kNameBucketId"
8910 def GetValidGLArg(self, func):
8911 return "_"
8913 def IsPointer(self):
8914 """Overridden from Argument."""
8915 return True
8917 def IsPointer2D(self):
8918 """Overridden from Argument."""
8919 return True
8922 class ResourceIdArgument(Argument):
8923 """A class that represents a resource id argument to a function."""
8925 def __init__(self, name, type):
8926 match = re.match("(GLid\w+)", type)
8927 self.resource_type = match.group(1)[4:]
8928 if self.resource_type == "Sync":
8929 type = type.replace(match.group(1), "GLsync")
8930 else:
8931 type = type.replace(match.group(1), "GLuint")
8932 Argument.__init__(self, name, type)
8934 def WriteGetCode(self, f):
8935 """Overridden from Argument."""
8936 if self.type == "GLsync":
8937 my_type = "GLuint"
8938 else:
8939 my_type = self.type
8940 f.write(" %s %s = c.%s;\n" % (my_type, self.name, self.name))
8942 def GetValidArg(self, func):
8943 return "client_%s_id_" % self.resource_type.lower()
8945 def GetValidGLArg(self, func):
8946 if self.resource_type == "Sync":
8947 return "reinterpret_cast<GLsync>(kService%sId)" % self.resource_type
8948 return "kService%sId" % self.resource_type
8951 class ResourceIdBindArgument(Argument):
8952 """Represents a resource id argument to a bind function."""
8954 def __init__(self, name, type):
8955 match = re.match("(GLidBind\w+)", type)
8956 self.resource_type = match.group(1)[8:]
8957 type = type.replace(match.group(1), "GLuint")
8958 Argument.__init__(self, name, type)
8960 def WriteGetCode(self, f):
8961 """Overridden from Argument."""
8962 code = """ %(type)s %(name)s = c.%(name)s;
8964 f.write(code % {'type': self.type, 'name': self.name})
8966 def GetValidArg(self, func):
8967 return "client_%s_id_" % self.resource_type.lower()
8969 def GetValidGLArg(self, func):
8970 return "kService%sId" % self.resource_type
8973 class ResourceIdZeroArgument(Argument):
8974 """Represents a resource id argument to a function that can be zero."""
8976 def __init__(self, name, type):
8977 match = re.match("(GLidZero\w+)", type)
8978 self.resource_type = match.group(1)[8:]
8979 type = type.replace(match.group(1), "GLuint")
8980 Argument.__init__(self, name, type)
8982 def WriteGetCode(self, f):
8983 """Overridden from Argument."""
8984 f.write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
8986 def GetValidArg(self, func):
8987 return "client_%s_id_" % self.resource_type.lower()
8989 def GetValidGLArg(self, func):
8990 return "kService%sId" % self.resource_type
8992 def GetNumInvalidValues(self, func):
8993 """returns the number of invalid values to be tested."""
8994 return 1
8996 def GetInvalidArg(self, index):
8997 """returns an invalid value by index."""
8998 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
9001 class Function(object):
9002 """A class that represents a function."""
9004 type_handlers = {
9005 '': TypeHandler(),
9006 'Bind': BindHandler(),
9007 'Create': CreateHandler(),
9008 'Custom': CustomHandler(),
9009 'Data': DataHandler(),
9010 'Delete': DeleteHandler(),
9011 'DELn': DELnHandler(),
9012 'GENn': GENnHandler(),
9013 'GETn': GETnHandler(),
9014 'GLchar': GLcharHandler(),
9015 'GLcharN': GLcharNHandler(),
9016 'HandWritten': HandWrittenHandler(),
9017 'Is': IsHandler(),
9018 'Manual': ManualHandler(),
9019 'PUT': PUTHandler(),
9020 'PUTn': PUTnHandler(),
9021 'PUTSTR': PUTSTRHandler(),
9022 'PUTXn': PUTXnHandler(),
9023 'StateSet': StateSetHandler(),
9024 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
9025 'StateSetFrontBack': StateSetFrontBackHandler(),
9026 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
9027 'StateSetNamedParameter': StateSetNamedParameter(),
9028 'STRn': STRnHandler(),
9031 def __init__(self, name, info):
9032 self.name = name
9033 self.original_name = info['original_name']
9035 self.original_args = self.ParseArgs(info['original_args'])
9037 if 'cmd_args' in info:
9038 self.args_for_cmds = self.ParseArgs(info['cmd_args'])
9039 else:
9040 self.args_for_cmds = self.original_args[:]
9042 self.return_type = info['return_type']
9043 if self.return_type != 'void':
9044 self.return_arg = CreateArg(info['return_type'] + " result")
9045 else:
9046 self.return_arg = None
9048 self.num_pointer_args = sum(
9049 [1 for arg in self.args_for_cmds if arg.IsPointer()])
9050 if self.num_pointer_args > 0:
9051 for arg in reversed(self.original_args):
9052 if arg.IsPointer():
9053 self.last_original_pointer_arg = arg
9054 break
9055 else:
9056 self.last_original_pointer_arg = None
9057 self.info = info
9058 self.type_handler = self.type_handlers[info['type']]
9059 self.can_auto_generate = (self.num_pointer_args == 0 and
9060 info['return_type'] == "void")
9061 self.InitFunction()
9063 def ParseArgs(self, arg_string):
9064 """Parses a function arg string."""
9065 args = []
9066 parts = arg_string.split(',')
9067 for arg_string in parts:
9068 arg = CreateArg(arg_string)
9069 if arg:
9070 args.append(arg)
9071 return args
9073 def IsType(self, type_name):
9074 """Returns true if function is a certain type."""
9075 return self.info['type'] == type_name
9077 def InitFunction(self):
9078 """Creates command args and calls the init function for the type handler.
9080 Creates argument lists for command buffer commands, eg. self.cmd_args and
9081 self.init_args.
9082 Calls the type function initialization.
9083 Override to create different kind of command buffer command argument lists.
9085 self.cmd_args = []
9086 for arg in self.args_for_cmds:
9087 arg.AddCmdArgs(self.cmd_args)
9089 self.init_args = []
9090 for arg in self.args_for_cmds:
9091 arg.AddInitArgs(self.init_args)
9093 if self.return_arg:
9094 self.init_args.append(self.return_arg)
9096 self.type_handler.InitFunction(self)
9098 def IsImmediate(self):
9099 """Returns whether the function is immediate data function or not."""
9100 return False
9102 def IsUnsafe(self):
9103 """Returns whether the function has service side validation or not."""
9104 return self.GetInfo('unsafe', False)
9106 def GetInfo(self, name, default = None):
9107 """Returns a value from the function info for this function."""
9108 if name in self.info:
9109 return self.info[name]
9110 return default
9112 def GetValidArg(self, arg):
9113 """Gets a valid argument value for the parameter arg from the function info
9114 if one exists."""
9115 try:
9116 index = self.GetOriginalArgs().index(arg)
9117 except ValueError:
9118 return None
9120 valid_args = self.GetInfo('valid_args')
9121 if valid_args and str(index) in valid_args:
9122 return valid_args[str(index)]
9123 return None
9125 def AddInfo(self, name, value):
9126 """Adds an info."""
9127 self.info[name] = value
9129 def IsExtension(self):
9130 return self.GetInfo('extension') or self.GetInfo('extension_flag')
9132 def IsCoreGLFunction(self):
9133 return (not self.IsExtension() and
9134 not self.GetInfo('pepper_interface') and
9135 not self.IsUnsafe())
9137 def InPepperInterface(self, interface):
9138 ext = self.GetInfo('pepper_interface')
9139 if not interface.GetName():
9140 return self.IsCoreGLFunction()
9141 return ext == interface.GetName()
9143 def InAnyPepperExtension(self):
9144 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
9146 def GetErrorReturnString(self):
9147 if self.GetInfo("error_return"):
9148 return self.GetInfo("error_return")
9149 elif self.return_type == "GLboolean":
9150 return "GL_FALSE"
9151 elif "*" in self.return_type:
9152 return "NULL"
9153 return "0"
9155 def GetGLFunctionName(self):
9156 """Gets the function to call to execute GL for this command."""
9157 if self.GetInfo('decoder_func'):
9158 return self.GetInfo('decoder_func')
9159 return "gl%s" % self.original_name
9161 def GetGLTestFunctionName(self):
9162 gl_func_name = self.GetInfo('gl_test_func')
9163 if gl_func_name == None:
9164 gl_func_name = self.GetGLFunctionName()
9165 if gl_func_name.startswith("gl"):
9166 gl_func_name = gl_func_name[2:]
9167 else:
9168 gl_func_name = self.original_name
9169 return gl_func_name
9171 def GetDataTransferMethods(self):
9172 return self.GetInfo('data_transfer_methods',
9173 ['immediate' if self.num_pointer_args == 1 else 'shm'])
9175 def AddCmdArg(self, arg):
9176 """Adds a cmd argument to this function."""
9177 self.cmd_args.append(arg)
9179 def GetCmdArgs(self):
9180 """Gets the command args for this function."""
9181 return self.cmd_args
9183 def ClearCmdArgs(self):
9184 """Clears the command args for this function."""
9185 self.cmd_args = []
9187 def GetCmdConstants(self):
9188 """Gets the constants for this function."""
9189 return [arg for arg in self.args_for_cmds if arg.IsConstant()]
9191 def GetInitArgs(self):
9192 """Gets the init args for this function."""
9193 return self.init_args
9195 def GetOriginalArgs(self):
9196 """Gets the original arguments to this function."""
9197 return self.original_args
9199 def GetLastOriginalArg(self):
9200 """Gets the last original argument to this function."""
9201 return self.original_args[len(self.original_args) - 1]
9203 def GetLastOriginalPointerArg(self):
9204 return self.last_original_pointer_arg
9206 def GetResourceIdArg(self):
9207 for arg in self.original_args:
9208 if hasattr(arg, 'resource_type'):
9209 return arg
9210 return None
9212 def _MaybePrependComma(self, arg_string, add_comma):
9213 """Adds a comma if arg_string is not empty and add_comma is true."""
9214 comma = ""
9215 if add_comma and len(arg_string):
9216 comma = ", "
9217 return "%s%s" % (comma, arg_string)
9219 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
9220 """Gets a list of arguments as they are in GL."""
9221 args = self.GetOriginalArgs()
9222 arg_string = ", ".join(
9223 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9224 return self._MaybePrependComma(arg_string, add_comma)
9226 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9227 """Gets the list of arguments as they are in GL."""
9228 args = self.GetOriginalArgs()
9229 arg_string = separator.join(
9230 ["%s%s" % (prefix, arg.name) for arg in args])
9231 return self._MaybePrependComma(arg_string, add_comma)
9233 def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
9234 """Gets a list of GL arguments after removing unneeded arguments."""
9235 args = self.GetOriginalArgs()
9236 arg_string = separator.join(
9237 ["%s%s" % (prefix, arg.name)
9238 for arg in args if not arg.IsConstant()])
9239 return self._MaybePrependComma(arg_string, add_comma)
9241 def MakeTypedPepperArgString(self, prefix):
9242 """Gets a list of arguments as they need to be for Pepper."""
9243 if self.GetInfo("pepper_args"):
9244 return self.GetInfo("pepper_args")
9245 else:
9246 return self.MakeTypedOriginalArgString(prefix, False)
9248 def MapCTypeToPepperIdlType(self, ctype, is_for_return_type=False):
9249 """Converts a C type name to the corresponding Pepper IDL type."""
9250 idltype = {
9251 'char*': '[out] str_t',
9252 'const GLchar* const*': '[out] cstr_t',
9253 'const char*': 'cstr_t',
9254 'const void*': 'mem_t',
9255 'void*': '[out] mem_t',
9256 'void**': '[out] mem_ptr_t',
9257 }.get(ctype, ctype)
9258 # We use "GLxxx_ptr_t" for "GLxxx*".
9259 matched = re.match(r'(const )?(GL\w+)\*$', ctype)
9260 if matched:
9261 idltype = matched.group(2) + '_ptr_t'
9262 if not matched.group(1):
9263 idltype = '[out] ' + idltype
9264 # If an in/out specifier is not specified yet, prepend [in].
9265 if idltype[0] != '[':
9266 idltype = '[in] ' + idltype
9267 # Strip the in/out specifier for a return type.
9268 if is_for_return_type:
9269 idltype = re.sub(r'\[\w+\] ', '', idltype)
9270 return idltype
9272 def MakeTypedPepperIdlArgStrings(self):
9273 """Gets a list of arguments as they need to be for Pepper IDL."""
9274 args = self.GetOriginalArgs()
9275 return ["%s %s" % (self.MapCTypeToPepperIdlType(arg.type), arg.name)
9276 for arg in args]
9278 def GetPepperName(self):
9279 if self.GetInfo("pepper_name"):
9280 return self.GetInfo("pepper_name")
9281 return self.name
9283 def MakeTypedCmdArgString(self, prefix, add_comma = False):
9284 """Gets a typed list of arguments as they need to be for command buffers."""
9285 args = self.GetCmdArgs()
9286 arg_string = ", ".join(
9287 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9288 return self._MaybePrependComma(arg_string, add_comma)
9290 def MakeCmdArgString(self, prefix, add_comma = False):
9291 """Gets the list of arguments as they need to be for command buffers."""
9292 args = self.GetCmdArgs()
9293 arg_string = ", ".join(
9294 ["%s%s" % (prefix, arg.name) for arg in args])
9295 return self._MaybePrependComma(arg_string, add_comma)
9297 def MakeTypedInitString(self, prefix, add_comma = False):
9298 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
9299 args = self.GetInitArgs()
9300 arg_string = ", ".join(
9301 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
9302 return self._MaybePrependComma(arg_string, add_comma)
9304 def MakeInitString(self, prefix, add_comma = False):
9305 """Gets the list of arguments as they need to be for cmd Init/Set."""
9306 args = self.GetInitArgs()
9307 arg_string = ", ".join(
9308 ["%s%s" % (prefix, arg.name) for arg in args])
9309 return self._MaybePrependComma(arg_string, add_comma)
9311 def MakeLogArgString(self):
9312 """Makes a string of the arguments for the LOG macros"""
9313 args = self.GetOriginalArgs()
9314 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
9316 def WriteHandlerValidation(self, f):
9317 """Writes validation code for the function."""
9318 for arg in self.GetOriginalArgs():
9319 arg.WriteValidationCode(f, self)
9320 self.WriteValidationCode(f)
9322 def WriteHandlerImplementation(self, f):
9323 """Writes the handler implementation for this command."""
9324 self.type_handler.WriteHandlerImplementation(self, f)
9326 def WriteValidationCode(self, f):
9327 """Writes the validation code for a command."""
9328 pass
9330 def WriteCmdFlag(self, f):
9331 """Writes the cmd cmd_flags constant."""
9332 flags = []
9333 # By default trace only at the highest level 3.
9334 trace_level = int(self.GetInfo('trace_level', default = 3))
9335 if trace_level not in xrange(0, 4):
9336 raise KeyError("Unhandled trace_level: %d" % trace_level)
9338 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
9340 if len(flags) > 0:
9341 cmd_flags = ' | '.join(flags)
9342 else:
9343 cmd_flags = 0
9345 f.write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
9348 def WriteCmdArgFlag(self, f):
9349 """Writes the cmd kArgFlags constant."""
9350 f.write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
9352 def WriteCmdComputeSize(self, f):
9353 """Writes the ComputeSize function for the command."""
9354 f.write(" static uint32_t ComputeSize() {\n")
9355 f.write(
9356 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
9357 f.write(" }\n")
9358 f.write("\n")
9360 def WriteCmdSetHeader(self, f):
9361 """Writes the cmd's SetHeader function."""
9362 f.write(" void SetHeader() {\n")
9363 f.write(" header.SetCmd<ValueType>();\n")
9364 f.write(" }\n")
9365 f.write("\n")
9367 def WriteCmdInit(self, f):
9368 """Writes the cmd's Init function."""
9369 f.write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
9370 f.write(" SetHeader();\n")
9371 args = self.GetCmdArgs()
9372 for arg in args:
9373 f.write(" %s = _%s;\n" % (arg.name, arg.name))
9374 f.write(" }\n")
9375 f.write("\n")
9377 def WriteCmdSet(self, f):
9378 """Writes the cmd's Set function."""
9379 copy_args = self.MakeCmdArgString("_", False)
9380 f.write(" void* Set(void* cmd%s) {\n" %
9381 self.MakeTypedCmdArgString("_", True))
9382 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
9383 f.write(" return NextCmdAddress<ValueType>(cmd);\n")
9384 f.write(" }\n")
9385 f.write("\n")
9387 def WriteStruct(self, f):
9388 self.type_handler.WriteStruct(self, f)
9390 def WriteDocs(self, f):
9391 self.type_handler.WriteDocs(self, f)
9393 def WriteCmdHelper(self, f):
9394 """Writes the cmd's helper."""
9395 self.type_handler.WriteCmdHelper(self, f)
9397 def WriteServiceImplementation(self, f):
9398 """Writes the service implementation for a command."""
9399 self.type_handler.WriteServiceImplementation(self, f)
9401 def WriteServiceUnitTest(self, f, *extras):
9402 """Writes the service implementation for a command."""
9403 self.type_handler.WriteServiceUnitTest(self, f, *extras)
9405 def WriteGLES2CLibImplementation(self, f):
9406 """Writes the GLES2 C Lib Implemention."""
9407 self.type_handler.WriteGLES2CLibImplementation(self, f)
9409 def WriteGLES2InterfaceHeader(self, f):
9410 """Writes the GLES2 Interface declaration."""
9411 self.type_handler.WriteGLES2InterfaceHeader(self, f)
9413 def WriteMojoGLES2ImplHeader(self, f):
9414 """Writes the Mojo GLES2 implementation header declaration."""
9415 self.type_handler.WriteMojoGLES2ImplHeader(self, f)
9417 def WriteMojoGLES2Impl(self, f):
9418 """Writes the Mojo GLES2 implementation declaration."""
9419 self.type_handler.WriteMojoGLES2Impl(self, f)
9421 def WriteGLES2InterfaceStub(self, f):
9422 """Writes the GLES2 Interface Stub declaration."""
9423 self.type_handler.WriteGLES2InterfaceStub(self, f)
9425 def WriteGLES2InterfaceStubImpl(self, f):
9426 """Writes the GLES2 Interface Stub declaration."""
9427 self.type_handler.WriteGLES2InterfaceStubImpl(self, f)
9429 def WriteGLES2ImplementationHeader(self, f):
9430 """Writes the GLES2 Implemention declaration."""
9431 self.type_handler.WriteGLES2ImplementationHeader(self, f)
9433 def WriteGLES2Implementation(self, f):
9434 """Writes the GLES2 Implemention definition."""
9435 self.type_handler.WriteGLES2Implementation(self, f)
9437 def WriteGLES2TraceImplementationHeader(self, f):
9438 """Writes the GLES2 Trace Implemention declaration."""
9439 self.type_handler.WriteGLES2TraceImplementationHeader(self, f)
9441 def WriteGLES2TraceImplementation(self, f):
9442 """Writes the GLES2 Trace Implemention definition."""
9443 self.type_handler.WriteGLES2TraceImplementation(self, f)
9445 def WriteGLES2Header(self, f):
9446 """Writes the GLES2 Implemention unit test."""
9447 self.type_handler.WriteGLES2Header(self, f)
9449 def WriteGLES2ImplementationUnitTest(self, f):
9450 """Writes the GLES2 Implemention unit test."""
9451 self.type_handler.WriteGLES2ImplementationUnitTest(self, f)
9453 def WriteDestinationInitalizationValidation(self, f):
9454 """Writes the client side destintion initialization validation."""
9455 self.type_handler.WriteDestinationInitalizationValidation(self, f)
9457 def WriteFormatTest(self, f):
9458 """Writes the cmd's format test."""
9459 self.type_handler.WriteFormatTest(self, f)
9462 class PepperInterface(object):
9463 """A class that represents a function."""
9465 def __init__(self, info):
9466 self.name = info["name"]
9467 self.dev = info["dev"]
9469 def GetName(self):
9470 return self.name
9472 def GetInterfaceName(self):
9473 upperint = ""
9474 dev = ""
9475 if self.name:
9476 upperint = "_" + self.name.upper()
9477 if self.dev:
9478 dev = "_DEV"
9479 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
9481 def GetStructName(self):
9482 dev = ""
9483 if self.dev:
9484 dev = "_Dev"
9485 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9488 class ImmediateFunction(Function):
9489 """A class that represnets an immediate function command."""
9491 def __init__(self, func):
9492 Function.__init__(
9493 self,
9494 "%sImmediate" % func.name,
9495 func.info)
9497 def InitFunction(self):
9498 # Override args in original_args and args_for_cmds with immediate versions
9499 # of the args.
9501 new_original_args = []
9502 for arg in self.original_args:
9503 new_arg = arg.GetImmediateVersion()
9504 if new_arg:
9505 new_original_args.append(new_arg)
9506 self.original_args = new_original_args
9508 new_args_for_cmds = []
9509 for arg in self.args_for_cmds:
9510 new_arg = arg.GetImmediateVersion()
9511 if new_arg:
9512 new_args_for_cmds.append(new_arg)
9514 self.args_for_cmds = new_args_for_cmds
9516 Function.InitFunction(self)
9518 def IsImmediate(self):
9519 return True
9521 def WriteServiceImplementation(self, f):
9522 """Overridden from Function"""
9523 self.type_handler.WriteImmediateServiceImplementation(self, f)
9525 def WriteHandlerImplementation(self, f):
9526 """Overridden from Function"""
9527 self.type_handler.WriteImmediateHandlerImplementation(self, f)
9529 def WriteServiceUnitTest(self, f, *extras):
9530 """Writes the service implementation for a command."""
9531 self.type_handler.WriteImmediateServiceUnitTest(self, f, *extras)
9533 def WriteValidationCode(self, f):
9534 """Overridden from Function"""
9535 self.type_handler.WriteImmediateValidationCode(self, f)
9537 def WriteCmdArgFlag(self, f):
9538 """Overridden from Function"""
9539 f.write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9541 def WriteCmdComputeSize(self, f):
9542 """Overridden from Function"""
9543 self.type_handler.WriteImmediateCmdComputeSize(self, f)
9545 def WriteCmdSetHeader(self, f):
9546 """Overridden from Function"""
9547 self.type_handler.WriteImmediateCmdSetHeader(self, f)
9549 def WriteCmdInit(self, f):
9550 """Overridden from Function"""
9551 self.type_handler.WriteImmediateCmdInit(self, f)
9553 def WriteCmdSet(self, f):
9554 """Overridden from Function"""
9555 self.type_handler.WriteImmediateCmdSet(self, f)
9557 def WriteCmdHelper(self, f):
9558 """Overridden from Function"""
9559 self.type_handler.WriteImmediateCmdHelper(self, f)
9561 def WriteFormatTest(self, f):
9562 """Overridden from Function"""
9563 self.type_handler.WriteImmediateFormatTest(self, f)
9566 class BucketFunction(Function):
9567 """A class that represnets a bucket version of a function command."""
9569 def __init__(self, func):
9570 Function.__init__(
9571 self,
9572 "%sBucket" % func.name,
9573 func.info)
9575 def InitFunction(self):
9576 # Override args in original_args and args_for_cmds with bucket versions
9577 # of the args.
9579 new_original_args = []
9580 for arg in self.original_args:
9581 new_arg = arg.GetBucketVersion()
9582 if new_arg:
9583 new_original_args.append(new_arg)
9584 self.original_args = new_original_args
9586 new_args_for_cmds = []
9587 for arg in self.args_for_cmds:
9588 new_arg = arg.GetBucketVersion()
9589 if new_arg:
9590 new_args_for_cmds.append(new_arg)
9592 self.args_for_cmds = new_args_for_cmds
9594 Function.InitFunction(self)
9596 def WriteServiceImplementation(self, f):
9597 """Overridden from Function"""
9598 self.type_handler.WriteBucketServiceImplementation(self, f)
9600 def WriteHandlerImplementation(self, f):
9601 """Overridden from Function"""
9602 self.type_handler.WriteBucketHandlerImplementation(self, f)
9604 def WriteServiceUnitTest(self, f, *extras):
9605 """Overridden from Function"""
9606 self.type_handler.WriteBucketServiceUnitTest(self, f, *extras)
9608 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9609 """Overridden from Function"""
9610 args = self.GetOriginalArgs()
9611 arg_string = separator.join(
9612 ["%s%s" % (prefix, arg.name[0:-10] if arg.name.endswith("_bucket_id")
9613 else arg.name) for arg in args])
9614 return super(BucketFunction, self)._MaybePrependComma(arg_string, add_comma)
9617 def CreateArg(arg_string):
9618 """Creates an Argument."""
9619 arg_parts = arg_string.split()
9620 if len(arg_parts) == 1 and arg_parts[0] == 'void':
9621 return None
9622 # Is this a pointer argument?
9623 elif arg_string.find('*') >= 0:
9624 return PointerArgument(
9625 arg_parts[-1],
9626 " ".join(arg_parts[0:-1]))
9627 # Is this a resource argument? Must come after pointer check.
9628 elif arg_parts[0].startswith('GLidBind'):
9629 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9630 elif arg_parts[0].startswith('GLidZero'):
9631 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9632 elif arg_parts[0].startswith('GLid'):
9633 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9634 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
9635 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9636 elif arg_parts[0].startswith('GLbitfield') and len(arg_parts[0]) > 10:
9637 return BitFieldArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9638 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
9639 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9640 elif arg_parts[0].startswith('GLboolean'):
9641 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9642 elif arg_parts[0].startswith('GLintUniformLocation'):
9643 return UniformLocationArgument(arg_parts[-1])
9644 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
9645 not arg_parts[0].startswith('GLintptr')):
9646 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9647 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
9648 arg_parts[0].startswith('GLintptrNotNegative')):
9649 return SizeNotNegativeArgument(arg_parts[-1],
9650 " ".join(arg_parts[0:-1]),
9651 arg_parts[0][0:-11])
9652 elif arg_parts[0].startswith('GLsize'):
9653 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9654 else:
9655 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9658 class GLGenerator(object):
9659 """A class to generate GL command buffers."""
9661 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9663 def __init__(self, verbose):
9664 self.original_functions = []
9665 self.functions = []
9666 self.verbose = verbose
9667 self.errors = 0
9668 self.pepper_interfaces = []
9669 self.interface_info = {}
9670 self.generated_cpp_filenames = []
9672 for interface in _PEPPER_INTERFACES:
9673 interface = PepperInterface(interface)
9674 self.pepper_interfaces.append(interface)
9675 self.interface_info[interface.GetName()] = interface
9677 def AddFunction(self, func):
9678 """Adds a function."""
9679 self.functions.append(func)
9681 def GetFunctionInfo(self, name):
9682 """Gets a type info for the given function name."""
9683 if name in _FUNCTION_INFO:
9684 func_info = _FUNCTION_INFO[name].copy()
9685 else:
9686 func_info = {}
9688 if not 'type' in func_info:
9689 func_info['type'] = ''
9691 return func_info
9693 def Log(self, msg):
9694 """Prints something if verbose is true."""
9695 if self.verbose:
9696 print msg
9698 def Error(self, msg):
9699 """Prints an error."""
9700 print "Error: %s" % msg
9701 self.errors += 1
9703 def ParseGLH(self, filename):
9704 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9705 with open(filename, "r") as f:
9706 functions = f.read()
9707 for line in functions.splitlines():
9708 match = self._function_re.match(line)
9709 if match:
9710 func_name = match.group(2)[2:]
9711 func_info = self.GetFunctionInfo(func_name)
9712 if func_info['type'] == 'Noop':
9713 continue
9715 parsed_func_info = {
9716 'original_name': func_name,
9717 'original_args': match.group(3),
9718 'return_type': match.group(1).strip(),
9721 for k in parsed_func_info.keys():
9722 if not k in func_info:
9723 func_info[k] = parsed_func_info[k]
9725 f = Function(func_name, func_info)
9726 self.original_functions.append(f)
9728 #for arg in f.GetOriginalArgs():
9729 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9730 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9732 gen_cmd = f.GetInfo('gen_cmd')
9733 if gen_cmd == True or gen_cmd == None:
9734 if f.type_handler.NeedsDataTransferFunction(f):
9735 methods = f.GetDataTransferMethods()
9736 if 'immediate' in methods:
9737 self.AddFunction(ImmediateFunction(f))
9738 if 'bucket' in methods:
9739 self.AddFunction(BucketFunction(f))
9740 if 'shm' in methods:
9741 self.AddFunction(f)
9742 else:
9743 self.AddFunction(f)
9745 self.Log("Auto Generated Functions : %d" %
9746 len([f for f in self.functions if f.can_auto_generate or
9747 (not f.IsType('') and not f.IsType('Custom') and
9748 not f.IsType('Todo'))]))
9750 funcs = [f for f in self.functions if not f.can_auto_generate and
9751 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
9752 self.Log("Non Auto Generated Functions: %d" % len(funcs))
9754 for f in funcs:
9755 self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
9757 def WriteCommandIds(self, filename):
9758 """Writes the command buffer format"""
9759 with CHeaderWriter(filename) as f:
9760 f.write("#define GLES2_COMMAND_LIST(OP) \\\n")
9761 id = 256
9762 for func in self.functions:
9763 f.write(" %-60s /* %d */ \\\n" %
9764 ("OP(%s)" % func.name, id))
9765 id += 1
9766 f.write("\n")
9768 f.write("enum CommandId {\n")
9769 f.write(" kStartPoint = cmd::kLastCommonId, "
9770 "// All GLES2 commands start after this.\n")
9771 f.write("#define GLES2_CMD_OP(name) k ## name,\n")
9772 f.write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9773 f.write("#undef GLES2_CMD_OP\n")
9774 f.write(" kNumCommands\n")
9775 f.write("};\n")
9776 f.write("\n")
9777 self.generated_cpp_filenames.append(filename)
9779 def WriteFormat(self, filename):
9780 """Writes the command buffer format"""
9781 with CHeaderWriter(filename) as f:
9782 # Forward declaration of a few enums used in constant argument
9783 # to avoid including GL header files.
9784 enum_defines = {
9785 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9786 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9788 f.write('\n')
9789 for enum in enum_defines:
9790 f.write("#define %s %s\n" % (enum, enum_defines[enum]))
9791 f.write('\n')
9792 for func in self.functions:
9793 if True:
9794 #gen_cmd = func.GetInfo('gen_cmd')
9795 #if gen_cmd == True or gen_cmd == None:
9796 func.WriteStruct(f)
9797 f.write("\n")
9798 self.generated_cpp_filenames.append(filename)
9800 def WriteDocs(self, filename):
9801 """Writes the command buffer doc version of the commands"""
9802 with CHeaderWriter(filename) as f:
9803 for func in self.functions:
9804 if True:
9805 #gen_cmd = func.GetInfo('gen_cmd')
9806 #if gen_cmd == True or gen_cmd == None:
9807 func.WriteDocs(f)
9808 f.write("\n")
9809 self.generated_cpp_filenames.append(filename)
9811 def WriteFormatTest(self, filename):
9812 """Writes the command buffer format test."""
9813 comment = ("// This file contains unit tests for gles2 commmands\n"
9814 "// It is included by gles2_cmd_format_test.cc\n\n")
9815 with CHeaderWriter(filename, comment) as f:
9816 for func in self.functions:
9817 if True:
9818 #gen_cmd = func.GetInfo('gen_cmd')
9819 #if gen_cmd == True or gen_cmd == None:
9820 func.WriteFormatTest(f)
9821 self.generated_cpp_filenames.append(filename)
9823 def WriteCmdHelperHeader(self, filename):
9824 """Writes the gles2 command helper."""
9825 with CHeaderWriter(filename) as f:
9826 for func in self.functions:
9827 if True:
9828 #gen_cmd = func.GetInfo('gen_cmd')
9829 #if gen_cmd == True or gen_cmd == None:
9830 func.WriteCmdHelper(f)
9831 self.generated_cpp_filenames.append(filename)
9833 def WriteServiceContextStateHeader(self, filename):
9834 """Writes the service context state header."""
9835 comment = "// It is included by context_state.h\n"
9836 with CHeaderWriter(filename, comment) as f:
9837 f.write("struct EnableFlags {\n")
9838 f.write(" EnableFlags();\n")
9839 for capability in _CAPABILITY_FLAGS:
9840 f.write(" bool %s;\n" % capability['name'])
9841 f.write(" bool cached_%s;\n" % capability['name'])
9842 f.write("};\n\n")
9844 for state_name in sorted(_STATES.keys()):
9845 state = _STATES[state_name]
9846 for item in state['states']:
9847 if isinstance(item['default'], list):
9848 f.write("%s %s[%d];\n" % (item['type'], item['name'],
9849 len(item['default'])))
9850 else:
9851 f.write("%s %s;\n" % (item['type'], item['name']))
9853 if item.get('cached', False):
9854 if isinstance(item['default'], list):
9855 f.write("%s cached_%s[%d];\n" % (item['type'], item['name'],
9856 len(item['default'])))
9857 else:
9858 f.write("%s cached_%s;\n" % (item['type'], item['name']))
9860 f.write("\n")
9861 f.write("""
9862 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9863 switch (cap) {
9864 """)
9865 for capability in _CAPABILITY_FLAGS:
9866 f.write("""\
9867 case GL_%s:
9868 """ % capability['name'].upper())
9869 f.write("""\
9870 if (enable_flags.cached_%(name)s == enable &&
9871 !ignore_cached_state)
9872 return;
9873 enable_flags.cached_%(name)s = enable;
9874 break;
9875 """ % capability)
9877 f.write("""\
9878 default:
9879 NOTREACHED();
9880 return;
9882 if (enable)
9883 glEnable(cap);
9884 else
9885 glDisable(cap);
9887 """)
9888 self.generated_cpp_filenames.append(filename)
9890 def WriteClientContextStateHeader(self, filename):
9891 """Writes the client context state header."""
9892 comment = "// It is included by client_context_state.h\n"
9893 with CHeaderWriter(filename, comment) as f:
9894 f.write("struct EnableFlags {\n")
9895 f.write(" EnableFlags();\n")
9896 for capability in _CAPABILITY_FLAGS:
9897 f.write(" bool %s;\n" % capability['name'])
9898 f.write("};\n\n")
9899 self.generated_cpp_filenames.append(filename)
9901 def WriteContextStateGetters(self, f, class_name):
9902 """Writes the state getters."""
9903 for gl_type in ["GLint", "GLfloat"]:
9904 f.write("""
9905 bool %s::GetStateAs%s(
9906 GLenum pname, %s* params, GLsizei* num_written) const {
9907 switch (pname) {
9908 """ % (class_name, gl_type, gl_type))
9909 for state_name in sorted(_STATES.keys()):
9910 state = _STATES[state_name]
9911 if 'enum' in state:
9912 f.write(" case %s:\n" % state['enum'])
9913 f.write(" *num_written = %d;\n" % len(state['states']))
9914 f.write(" if (params) {\n")
9915 for ndx,item in enumerate(state['states']):
9916 f.write(" params[%d] = static_cast<%s>(%s);\n" %
9917 (ndx, gl_type, item['name']))
9918 f.write(" }\n")
9919 f.write(" return true;\n")
9920 else:
9921 for item in state['states']:
9922 f.write(" case %s:\n" % item['enum'])
9923 if isinstance(item['default'], list):
9924 item_len = len(item['default'])
9925 f.write(" *num_written = %d;\n" % item_len)
9926 f.write(" if (params) {\n")
9927 if item['type'] == gl_type:
9928 f.write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9929 (item['name'], item['type'], item_len))
9930 else:
9931 f.write(" for (size_t i = 0; i < %s; ++i) {\n" %
9932 item_len)
9933 f.write(" params[i] = %s;\n" %
9934 (GetGLGetTypeConversion(gl_type, item['type'],
9935 "%s[i]" % item['name'])))
9936 f.write(" }\n");
9937 else:
9938 f.write(" *num_written = 1;\n")
9939 f.write(" if (params) {\n")
9940 f.write(" params[0] = %s;\n" %
9941 (GetGLGetTypeConversion(gl_type, item['type'],
9942 item['name'])))
9943 f.write(" }\n")
9944 f.write(" return true;\n")
9945 for capability in _CAPABILITY_FLAGS:
9946 f.write(" case GL_%s:\n" % capability['name'].upper())
9947 f.write(" *num_written = 1;\n")
9948 f.write(" if (params) {\n")
9949 f.write(
9950 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9951 (gl_type, capability['name']))
9952 f.write(" }\n")
9953 f.write(" return true;\n")
9954 f.write(""" default:
9955 return false;
9958 """)
9960 def WriteServiceContextStateImpl(self, filename):
9961 """Writes the context state service implementation."""
9962 comment = "// It is included by context_state.cc\n"
9963 with CHeaderWriter(filename, comment) as f:
9964 code = []
9965 for capability in _CAPABILITY_FLAGS:
9966 code.append("%s(%s)" %
9967 (capability['name'],
9968 ('false', 'true')['default' in capability]))
9969 code.append("cached_%s(%s)" %
9970 (capability['name'],
9971 ('false', 'true')['default' in capability]))
9972 f.write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9973 ",\n ".join(code))
9974 f.write("\n")
9976 f.write("void ContextState::Initialize() {\n")
9977 for state_name in sorted(_STATES.keys()):
9978 state = _STATES[state_name]
9979 for item in state['states']:
9980 if isinstance(item['default'], list):
9981 for ndx, value in enumerate(item['default']):
9982 f.write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
9983 else:
9984 f.write(" %s = %s;\n" % (item['name'], item['default']))
9985 if item.get('cached', False):
9986 if isinstance(item['default'], list):
9987 for ndx, value in enumerate(item['default']):
9988 f.write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
9989 else:
9990 f.write(" cached_%s = %s;\n" % (item['name'], item['default']))
9991 f.write("}\n")
9993 f.write("""
9994 void ContextState::InitCapabilities(const ContextState* prev_state) const {
9995 """)
9996 def WriteCapabilities(test_prev, es3_caps):
9997 for capability in _CAPABILITY_FLAGS:
9998 capability_name = capability['name']
9999 capability_es3 = 'es3' in capability and capability['es3'] == True
10000 if capability_es3 and not es3_caps or not capability_es3 and es3_caps:
10001 continue
10002 if test_prev:
10003 f.write(""" if (prev_state->enable_flags.cached_%s !=
10004 enable_flags.cached_%s) {\n""" %
10005 (capability_name, capability_name))
10006 f.write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
10007 (capability_name.upper(), capability_name))
10008 if test_prev:
10009 f.write(" }")
10011 f.write(" if (prev_state) {")
10012 WriteCapabilities(True, False)
10013 f.write(" if (feature_info_->IsES3Capable()) {\n")
10014 WriteCapabilities(True, True)
10015 f.write(" }\n")
10016 f.write(" } else {")
10017 WriteCapabilities(False, False)
10018 f.write(" if (feature_info_->IsES3Capable()) {\n")
10019 WriteCapabilities(False, True)
10020 f.write(" }\n")
10021 f.write(" }")
10022 f.write("""}
10024 void ContextState::InitState(const ContextState *prev_state) const {
10025 """)
10027 def WriteStates(test_prev):
10028 # We need to sort the keys so the expectations match
10029 for state_name in sorted(_STATES.keys()):
10030 state = _STATES[state_name]
10031 if state['type'] == 'FrontBack':
10032 num_states = len(state['states'])
10033 for ndx, group in enumerate(Grouper(num_states / 2,
10034 state['states'])):
10035 if test_prev:
10036 f.write(" if (")
10037 args = []
10038 for place, item in enumerate(group):
10039 item_name = CachedStateName(item)
10040 args.append('%s' % item_name)
10041 if test_prev:
10042 if place > 0:
10043 f.write(' ||\n')
10044 f.write("(%s != prev_state->%s)" % (item_name, item_name))
10045 if test_prev:
10046 f.write(")\n")
10047 f.write(
10048 " gl%s(%s, %s);\n" %
10049 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx],
10050 ", ".join(args)))
10051 elif state['type'] == 'NamedParameter':
10052 for item in state['states']:
10053 item_name = CachedStateName(item)
10055 if 'extension_flag' in item:
10056 f.write(" if (feature_info_->feature_flags().%s) {\n " %
10057 item['extension_flag'])
10058 if test_prev:
10059 if isinstance(item['default'], list):
10060 f.write(" if (memcmp(prev_state->%s, %s, "
10061 "sizeof(%s) * %d)) {\n" %
10062 (item_name, item_name, item['type'],
10063 len(item['default'])))
10064 else:
10065 f.write(" if (prev_state->%s != %s) {\n " %
10066 (item_name, item_name))
10067 if 'gl_version_flag' in item:
10068 item_name = item['gl_version_flag']
10069 inverted = ''
10070 if item_name[0] == '!':
10071 inverted = '!'
10072 item_name = item_name[1:]
10073 f.write(" if (%sfeature_info_->gl_version_info().%s) {\n" %
10074 (inverted, item_name))
10075 f.write(" gl%s(%s, %s);\n" %
10076 (state['func'],
10077 (item['enum_set']
10078 if 'enum_set' in item else item['enum']),
10079 item['name']))
10080 if 'gl_version_flag' in item:
10081 f.write(" }\n")
10082 if test_prev:
10083 if 'extension_flag' in item:
10084 f.write(" ")
10085 f.write(" }")
10086 if 'extension_flag' in item:
10087 f.write(" }")
10088 else:
10089 if 'extension_flag' in state:
10090 f.write(" if (feature_info_->feature_flags().%s)\n " %
10091 state['extension_flag'])
10092 if test_prev:
10093 f.write(" if (")
10094 args = []
10095 for place, item in enumerate(state['states']):
10096 item_name = CachedStateName(item)
10097 args.append('%s' % item_name)
10098 if test_prev:
10099 if place > 0:
10100 f.write(' ||\n')
10101 f.write("(%s != prev_state->%s)" %
10102 (item_name, item_name))
10103 if test_prev:
10104 f.write(" )\n")
10105 f.write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
10107 f.write(" if (prev_state) {")
10108 WriteStates(True)
10109 f.write(" } else {")
10110 WriteStates(False)
10111 f.write(" }")
10112 f.write("}\n")
10114 f.write("""bool ContextState::GetEnabled(GLenum cap) const {
10115 switch (cap) {
10116 """)
10117 for capability in _CAPABILITY_FLAGS:
10118 f.write(" case GL_%s:\n" % capability['name'].upper())
10119 f.write(" return enable_flags.%s;\n" % capability['name'])
10120 f.write(""" default:
10121 NOTREACHED();
10122 return false;
10125 """)
10126 self.WriteContextStateGetters(f, "ContextState")
10127 self.generated_cpp_filenames.append(filename)
10129 def WriteClientContextStateImpl(self, filename):
10130 """Writes the context state client side implementation."""
10131 comment = "// It is included by client_context_state.cc\n"
10132 with CHeaderWriter(filename, comment) as f:
10133 code = []
10134 for capability in _CAPABILITY_FLAGS:
10135 code.append("%s(%s)" %
10136 (capability['name'],
10137 ('false', 'true')['default' in capability]))
10138 f.write(
10139 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
10140 ",\n ".join(code))
10141 f.write("\n")
10143 f.write("""
10144 bool ClientContextState::SetCapabilityState(
10145 GLenum cap, bool enabled, bool* changed) {
10146 *changed = false;
10147 switch (cap) {
10148 """)
10149 for capability in _CAPABILITY_FLAGS:
10150 f.write(" case GL_%s:\n" % capability['name'].upper())
10151 f.write(""" if (enable_flags.%(name)s != enabled) {
10152 *changed = true;
10153 enable_flags.%(name)s = enabled;
10155 return true;
10156 """ % capability)
10157 f.write(""" default:
10158 return false;
10161 """)
10162 f.write("""bool ClientContextState::GetEnabled(
10163 GLenum cap, bool* enabled) const {
10164 switch (cap) {
10165 """)
10166 for capability in _CAPABILITY_FLAGS:
10167 f.write(" case GL_%s:\n" % capability['name'].upper())
10168 f.write(" *enabled = enable_flags.%s;\n" % capability['name'])
10169 f.write(" return true;\n")
10170 f.write(""" default:
10171 return false;
10174 """)
10175 self.generated_cpp_filenames.append(filename)
10177 def WriteServiceImplementation(self, filename):
10178 """Writes the service decorder implementation."""
10179 comment = "// It is included by gles2_cmd_decoder.cc\n"
10180 with CHeaderWriter(filename, comment) as f:
10181 for func in self.functions:
10182 if True:
10183 #gen_cmd = func.GetInfo('gen_cmd')
10184 #if gen_cmd == True or gen_cmd == None:
10185 func.WriteServiceImplementation(f)
10187 f.write("""
10188 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
10189 switch (cap) {
10190 """)
10191 for capability in _CAPABILITY_FLAGS:
10192 f.write(" case GL_%s:\n" % capability['name'].upper())
10193 if 'state_flag' in capability:
10195 f.write("""\
10196 state_.enable_flags.%(name)s = enabled;
10197 if (state_.enable_flags.cached_%(name)s != enabled
10198 || state_.ignore_cached_state) {
10199 %(state_flag)s = true;
10201 return false;
10202 """ % capability)
10203 else:
10204 f.write("""\
10205 state_.enable_flags.%(name)s = enabled;
10206 if (state_.enable_flags.cached_%(name)s != enabled
10207 || state_.ignore_cached_state) {
10208 state_.enable_flags.cached_%(name)s = enabled;
10209 return true;
10211 return false;
10212 """ % capability)
10213 f.write(""" default:
10214 NOTREACHED();
10215 return false;
10218 """)
10219 self.generated_cpp_filenames.append(filename)
10221 def WriteServiceUnitTests(self, filename_pattern):
10222 """Writes the service decorder unit tests."""
10223 num_tests = len(self.functions)
10224 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
10225 count = 0
10226 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
10227 count += 1
10228 filename = filename_pattern % count
10229 comment = "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" \
10230 % count
10231 with CHeaderWriter(filename, comment) as f:
10232 test_name = 'GLES2DecoderTest%d' % count
10233 end = test_num + FUNCTIONS_PER_FILE
10234 if end > num_tests:
10235 end = num_tests
10236 for idx in range(test_num, end):
10237 func = self.functions[idx]
10239 # Do any filtering of the functions here, so that the functions
10240 # will not move between the numbered files if filtering properties
10241 # are changed.
10242 if func.GetInfo('extension_flag'):
10243 continue
10245 if True:
10246 #gen_cmd = func.GetInfo('gen_cmd')
10247 #if gen_cmd == True or gen_cmd == None:
10248 if func.GetInfo('unit_test') == False:
10249 f.write("// TODO(gman): %s\n" % func.name)
10250 else:
10251 func.WriteServiceUnitTest(f, {
10252 'test_name': test_name
10254 self.generated_cpp_filenames.append(filename)
10256 comment = "// It is included by gles2_cmd_decoder_unittest_base.cc\n"
10257 filename = filename_pattern % 0
10258 with CHeaderWriter(filename, comment) as f:
10259 f.write(
10260 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
10261 bool es3_capable) {""")
10262 for capability in _CAPABILITY_FLAGS:
10263 capability_es3 = 'es3' in capability and capability['es3'] == True
10264 if not capability_es3:
10265 f.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10266 (capability['name'].upper(),
10267 ('false', 'true')['default' in capability]))
10269 f.write(" if (es3_capable) {")
10270 for capability in _CAPABILITY_FLAGS:
10271 capability_es3 = 'es3' in capability and capability['es3'] == True
10272 if capability_es3:
10273 f.write(" ExpectEnableDisable(GL_%s, %s);\n" %
10274 (capability['name'].upper(),
10275 ('false', 'true')['default' in capability]))
10276 f.write(""" }
10279 void GLES2DecoderTestBase::SetupInitStateExpectations() {
10280 """)
10281 # We need to sort the keys so the expectations match
10282 for state_name in sorted(_STATES.keys()):
10283 state = _STATES[state_name]
10284 if state['type'] == 'FrontBack':
10285 num_states = len(state['states'])
10286 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
10287 args = []
10288 for item in group:
10289 if 'expected' in item:
10290 args.append(item['expected'])
10291 else:
10292 args.append(item['default'])
10293 f.write(
10294 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10295 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
10296 f.write(" .Times(1)\n")
10297 f.write(" .RetiresOnSaturation();\n")
10298 elif state['type'] == 'NamedParameter':
10299 for item in state['states']:
10300 if 'extension_flag' in item:
10301 f.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10302 item['extension_flag'])
10303 f.write(" ")
10304 expect_value = item['default']
10305 if isinstance(expect_value, list):
10306 # TODO: Currently we do not check array values.
10307 expect_value = "_"
10309 f.write(
10310 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
10311 (state['func'],
10312 (item['enum_set']
10313 if 'enum_set' in item else item['enum']),
10314 expect_value))
10315 f.write(" .Times(1)\n")
10316 f.write(" .RetiresOnSaturation();\n")
10317 if 'extension_flag' in item:
10318 f.write(" }\n")
10319 else:
10320 if 'extension_flag' in state:
10321 f.write(" if (group_->feature_info()->feature_flags().%s) {\n" %
10322 state['extension_flag'])
10323 f.write(" ")
10324 args = []
10325 for item in state['states']:
10326 if 'expected' in item:
10327 args.append(item['expected'])
10328 else:
10329 args.append(item['default'])
10330 # TODO: Currently we do not check array values.
10331 args = ["_" if isinstance(arg, list) else arg for arg in args]
10332 f.write(" EXPECT_CALL(*gl_, %s(%s))\n" %
10333 (state['func'], ", ".join(args)))
10334 f.write(" .Times(1)\n")
10335 f.write(" .RetiresOnSaturation();\n")
10336 if 'extension_flag' in state:
10337 f.write(" }\n")
10338 f.write("}\n")
10339 self.generated_cpp_filenames.append(filename)
10341 def WriteServiceUnitTestsForExtensions(self, filename):
10342 """Writes the service decorder unit tests for functions with extension_flag.
10344 The functions are special in that they need a specific unit test
10345 baseclass to turn on the extension.
10347 functions = [f for f in self.functions if f.GetInfo('extension_flag')]
10348 comment = "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n"
10349 with CHeaderWriter(filename, comment) as f:
10350 for func in functions:
10351 if True:
10352 if func.GetInfo('unit_test') == False:
10353 f.write("// TODO(gman): %s\n" % func.name)
10354 else:
10355 extension = ToCamelCase(
10356 ToGLExtensionString(func.GetInfo('extension_flag')))
10357 func.WriteServiceUnitTest(f, {
10358 'test_name': 'GLES2DecoderTestWith%s' % extension
10360 self.generated_cpp_filenames.append(filename)
10362 def WriteGLES2Header(self, filename):
10363 """Writes the GLES2 header."""
10364 comment = "// This file contains Chromium-specific GLES2 declarations.\n\n"
10365 with CHeaderWriter(filename, comment) as f:
10366 for func in self.original_functions:
10367 func.WriteGLES2Header(f)
10368 f.write("\n")
10369 self.generated_cpp_filenames.append(filename)
10371 def WriteGLES2CLibImplementation(self, filename):
10372 """Writes the GLES2 c lib implementation."""
10373 comment = "// These functions emulate GLES2 over command buffers.\n"
10374 with CHeaderWriter(filename, comment) as f:
10375 for func in self.original_functions:
10376 func.WriteGLES2CLibImplementation(f)
10377 f.write("""
10378 namespace gles2 {
10380 extern const NameToFunc g_gles2_function_table[] = {
10381 """)
10382 for func in self.original_functions:
10383 f.write(
10384 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
10385 (func.name, func.name))
10386 f.write(""" { NULL, NULL, },
10389 } // namespace gles2
10390 """)
10391 self.generated_cpp_filenames.append(filename)
10393 def WriteGLES2InterfaceHeader(self, filename):
10394 """Writes the GLES2 interface header."""
10395 comment = ("// This file is included by gles2_interface.h to declare the\n"
10396 "// GL api functions.\n")
10397 with CHeaderWriter(filename, comment) as f:
10398 for func in self.original_functions:
10399 func.WriteGLES2InterfaceHeader(f)
10400 self.generated_cpp_filenames.append(filename)
10402 def WriteMojoGLES2ImplHeader(self, filename):
10403 """Writes the Mojo GLES2 implementation header."""
10404 comment = ("// This file is included by gles2_interface.h to declare the\n"
10405 "// GL api functions.\n")
10406 code = """
10407 #include "gpu/command_buffer/client/gles2_interface.h"
10408 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10410 namespace mojo {
10412 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10413 public:
10414 explicit MojoGLES2Impl(MojoGLES2Context context) {
10415 context_ = context;
10417 ~MojoGLES2Impl() override {}
10419 with CHeaderWriter(filename, comment) as f:
10420 f.write(code);
10421 for func in self.original_functions:
10422 func.WriteMojoGLES2ImplHeader(f)
10423 code = """
10424 private:
10425 MojoGLES2Context context_;
10428 } // namespace mojo
10430 f.write(code);
10431 self.generated_cpp_filenames.append(filename)
10433 def WriteMojoGLES2Impl(self, filename):
10434 """Writes the Mojo GLES2 implementation."""
10435 code = """
10436 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10438 #include "base/logging.h"
10439 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_copy_texture.h"
10440 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_image.h"
10441 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10442 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_pixel_transfer_buffer_object.h"
10443 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10444 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10445 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10446 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10447 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10449 namespace mojo {
10452 with CWriter(filename) as f:
10453 f.write(code);
10454 for func in self.original_functions:
10455 func.WriteMojoGLES2Impl(f)
10456 code = """
10458 } // namespace mojo
10460 f.write(code);
10461 self.generated_cpp_filenames.append(filename)
10463 def WriteGLES2InterfaceStub(self, filename):
10464 """Writes the GLES2 interface stub header."""
10465 comment = "// This file is included by gles2_interface_stub.h.\n"
10466 with CHeaderWriter(filename, comment) as f:
10467 for func in self.original_functions:
10468 func.WriteGLES2InterfaceStub(f)
10469 self.generated_cpp_filenames.append(filename)
10471 def WriteGLES2InterfaceStubImpl(self, filename):
10472 """Writes the GLES2 interface header."""
10473 comment = "// This file is included by gles2_interface_stub.cc.\n"
10474 with CHeaderWriter(filename, comment) as f:
10475 for func in self.original_functions:
10476 func.WriteGLES2InterfaceStubImpl(f)
10477 self.generated_cpp_filenames.append(filename)
10479 def WriteGLES2ImplementationHeader(self, filename):
10480 """Writes the GLES2 Implementation header."""
10481 comment = \
10482 ("// This file is included by gles2_implementation.h to declare the\n"
10483 "// GL api functions.\n")
10484 with CHeaderWriter(filename, comment) as f:
10485 for func in self.original_functions:
10486 func.WriteGLES2ImplementationHeader(f)
10487 self.generated_cpp_filenames.append(filename)
10489 def WriteGLES2Implementation(self, filename):
10490 """Writes the GLES2 Implementation."""
10491 comment = \
10492 ("// This file is included by gles2_implementation.cc to define the\n"
10493 "// GL api functions.\n")
10494 with CHeaderWriter(filename, comment) as f:
10495 for func in self.original_functions:
10496 func.WriteGLES2Implementation(f)
10497 self.generated_cpp_filenames.append(filename)
10499 def WriteGLES2TraceImplementationHeader(self, filename):
10500 """Writes the GLES2 Trace Implementation header."""
10501 comment = "// This file is included by gles2_trace_implementation.h\n"
10502 with CHeaderWriter(filename, comment) as f:
10503 for func in self.original_functions:
10504 func.WriteGLES2TraceImplementationHeader(f)
10505 self.generated_cpp_filenames.append(filename)
10507 def WriteGLES2TraceImplementation(self, filename):
10508 """Writes the GLES2 Trace Implementation."""
10509 comment = "// This file is included by gles2_trace_implementation.cc\n"
10510 with CHeaderWriter(filename, comment) as f:
10511 for func in self.original_functions:
10512 func.WriteGLES2TraceImplementation(f)
10513 self.generated_cpp_filenames.append(filename)
10515 def WriteGLES2ImplementationUnitTests(self, filename):
10516 """Writes the GLES2 helper header."""
10517 comment = \
10518 ("// This file is included by gles2_implementation.h to declare the\n"
10519 "// GL api functions.\n")
10520 with CHeaderWriter(filename, comment) as f:
10521 for func in self.original_functions:
10522 func.WriteGLES2ImplementationUnitTest(f)
10523 self.generated_cpp_filenames.append(filename)
10525 def WriteServiceUtilsHeader(self, filename):
10526 """Writes the gles2 auto generated utility header."""
10527 with CHeaderWriter(filename) as f:
10528 for name in sorted(_NAMED_TYPE_INFO.keys()):
10529 named_type = NamedType(_NAMED_TYPE_INFO[name])
10530 if named_type.IsConstant():
10531 continue
10532 f.write("ValueValidator<%s> %s;\n" %
10533 (named_type.GetType(), ToUnderscore(name)))
10534 f.write("\n")
10535 self.generated_cpp_filenames.append(filename)
10537 def WriteServiceUtilsImplementation(self, filename):
10538 """Writes the gles2 auto generated utility implementation."""
10539 with CHeaderWriter(filename) as f:
10540 names = sorted(_NAMED_TYPE_INFO.keys())
10541 for name in names:
10542 named_type = NamedType(_NAMED_TYPE_INFO[name])
10543 if named_type.IsConstant():
10544 continue
10545 if named_type.GetValidValues():
10546 f.write("static const %s valid_%s_table[] = {\n" %
10547 (named_type.GetType(), ToUnderscore(name)))
10548 for value in named_type.GetValidValues():
10549 f.write(" %s,\n" % value)
10550 f.write("};\n")
10551 f.write("\n")
10552 if named_type.GetValidValuesES3():
10553 f.write("static const %s valid_%s_table_es3[] = {\n" %
10554 (named_type.GetType(), ToUnderscore(name)))
10555 for value in named_type.GetValidValuesES3():
10556 f.write(" %s,\n" % value)
10557 f.write("};\n")
10558 f.write("\n")
10559 if named_type.GetDeprecatedValuesES3():
10560 f.write("static const %s deprecated_%s_table_es3[] = {\n" %
10561 (named_type.GetType(), ToUnderscore(name)))
10562 for value in named_type.GetDeprecatedValuesES3():
10563 f.write(" %s,\n" % value)
10564 f.write("};\n")
10565 f.write("\n")
10566 f.write("Validators::Validators()")
10567 pre = ' : '
10568 for count, name in enumerate(names):
10569 named_type = NamedType(_NAMED_TYPE_INFO[name])
10570 if named_type.IsConstant():
10571 continue
10572 if named_type.GetValidValues():
10573 code = """%(pre)s%(name)s(
10574 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10575 else:
10576 code = "%(pre)s%(name)s()"
10577 f.write(code % {
10578 'name': ToUnderscore(name),
10579 'pre': pre,
10581 pre = ',\n '
10582 f.write(" {\n");
10583 f.write("}\n\n");
10585 f.write("void Validators::UpdateValuesES3() {\n")
10586 for name in names:
10587 named_type = NamedType(_NAMED_TYPE_INFO[name])
10588 if named_type.GetDeprecatedValuesES3():
10589 code = """ %(name)s.RemoveValues(
10590 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10592 f.write(code % {
10593 'name': ToUnderscore(name),
10595 if named_type.GetValidValuesES3():
10596 code = """ %(name)s.AddValues(
10597 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10599 f.write(code % {
10600 'name': ToUnderscore(name),
10602 f.write("}\n\n");
10603 self.generated_cpp_filenames.append(filename)
10605 def WriteCommonUtilsHeader(self, filename):
10606 """Writes the gles2 common utility header."""
10607 with CHeaderWriter(filename) as f:
10608 type_infos = sorted(_NAMED_TYPE_INFO.keys())
10609 for type_info in type_infos:
10610 if _NAMED_TYPE_INFO[type_info]['type'] == 'GLenum':
10611 f.write("static std::string GetString%s(uint32_t value);\n" %
10612 type_info)
10613 f.write("\n")
10614 self.generated_cpp_filenames.append(filename)
10616 def WriteCommonUtilsImpl(self, filename):
10617 """Writes the gles2 common utility header."""
10618 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10619 dict = {}
10620 for fname in ['third_party/khronos/GLES2/gl2.h',
10621 'third_party/khronos/GLES2/gl2ext.h',
10622 'third_party/khronos/GLES3/gl3.h',
10623 'gpu/GLES2/gl2chromium.h',
10624 'gpu/GLES2/gl2extchromium.h']:
10625 lines = open(fname).readlines()
10626 for line in lines:
10627 m = enum_re.match(line)
10628 if m:
10629 name = m.group(1)
10630 value = m.group(2)
10631 if len(value) <= 10:
10632 if not value in dict:
10633 dict[value] = name
10634 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10635 elif dict[value] != name and (name.endswith('_CHROMIUM') or
10636 dict[value].endswith('_CHROMIUM')):
10637 self.Error("code collision: %s and %s have the same code %s" %
10638 (dict[value], name, value))
10640 with CHeaderWriter(filename) as f:
10641 f.write("static const GLES2Util::EnumToString "
10642 "enum_to_string_table[] = {\n")
10643 for value in dict:
10644 f.write(' { %s, "%s", },\n' % (value, dict[value]))
10645 f.write("""};
10647 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10648 enum_to_string_table;
10649 const size_t GLES2Util::enum_to_string_table_len_ =
10650 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10652 """)
10654 enums = sorted(_NAMED_TYPE_INFO.keys())
10655 for enum in enums:
10656 if _NAMED_TYPE_INFO[enum]['type'] == 'GLenum':
10657 f.write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10658 enum)
10659 valid_list = _NAMED_TYPE_INFO[enum]['valid']
10660 if 'valid_es3' in _NAMED_TYPE_INFO[enum]:
10661 valid_list = valid_list + _NAMED_TYPE_INFO[enum]['valid_es3']
10662 assert len(valid_list) == len(set(valid_list))
10663 if len(valid_list) > 0:
10664 f.write(" static const EnumToString string_table[] = {\n")
10665 for value in valid_list:
10666 f.write(' { %s, "%s" },\n' % (value, value))
10667 f.write(""" };
10668 return GLES2Util::GetQualifiedEnumString(
10669 string_table, arraysize(string_table), value);
10672 """)
10673 else:
10674 f.write(""" return GLES2Util::GetQualifiedEnumString(
10675 NULL, 0, value);
10678 """)
10679 self.generated_cpp_filenames.append(filename)
10681 def WritePepperGLES2Interface(self, filename, dev):
10682 """Writes the Pepper OpenGLES interface definition."""
10683 with CWriter(filename) as f:
10684 f.write("label Chrome {\n")
10685 f.write(" M39 = 1.0\n")
10686 f.write("};\n\n")
10688 if not dev:
10689 # Declare GL types.
10690 f.write("[version=1.0]\n")
10691 f.write("describe {\n")
10692 for gltype in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10693 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10694 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10695 'GLubyte', 'GLuint', 'GLushort']:
10696 f.write(" %s;\n" % gltype)
10697 f.write(" %s_ptr_t;\n" % gltype)
10698 f.write("};\n\n")
10700 # C level typedefs.
10701 f.write("#inline c\n")
10702 f.write("#include \"ppapi/c/pp_resource.h\"\n")
10703 if dev:
10704 f.write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10705 else:
10706 f.write("\n#ifndef __gl2_h_\n")
10707 for (k, v) in _GL_TYPES.iteritems():
10708 f.write("typedef %s %s;\n" % (v, k))
10709 f.write("#ifdef _WIN64\n")
10710 for (k, v) in _GL_TYPES_64.iteritems():
10711 f.write("typedef %s %s;\n" % (v, k))
10712 f.write("#else\n")
10713 for (k, v) in _GL_TYPES_32.iteritems():
10714 f.write("typedef %s %s;\n" % (v, k))
10715 f.write("#endif // _WIN64\n")
10716 f.write("#endif // __gl2_h_\n\n")
10717 f.write("#endinl\n")
10719 for interface in self.pepper_interfaces:
10720 if interface.dev != dev:
10721 continue
10722 # Historically, we provide OpenGLES2 interfaces with struct
10723 # namespace. Not to break code which uses the interface as
10724 # "struct OpenGLES2", we put it in struct namespace.
10725 f.write('\n[macro="%s", force_struct_namespace]\n' %
10726 interface.GetInterfaceName())
10727 f.write("interface %s {\n" % interface.GetStructName())
10728 for func in self.original_functions:
10729 if not func.InPepperInterface(interface):
10730 continue
10732 ret_type = func.MapCTypeToPepperIdlType(func.return_type,
10733 is_for_return_type=True)
10734 func_prefix = " %s %s(" % (ret_type, func.GetPepperName())
10735 f.write(func_prefix)
10736 f.write("[in] PP_Resource context")
10737 for arg in func.MakeTypedPepperIdlArgStrings():
10738 f.write(",\n" + " " * len(func_prefix) + arg)
10739 f.write(");\n")
10740 f.write("};\n\n")
10742 def WritePepperGLES2Implementation(self, filename):
10743 """Writes the Pepper OpenGLES interface implementation."""
10744 with CWriter(filename) as f:
10745 f.write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10746 f.write("#include \"base/logging.h\"\n")
10747 f.write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10748 f.write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10749 f.write("#include \"ppapi/thunk/enter.h\"\n\n")
10751 f.write("namespace ppapi {\n\n")
10752 f.write("namespace {\n\n")
10754 f.write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10755 " Enter3D;\n\n")
10757 f.write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10758 " enter) {\n")
10759 f.write(" DCHECK(enter);\n")
10760 f.write(" DCHECK(enter->succeeded());\n")
10761 f.write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10762 "gles2_impl();\n");
10763 f.write("}\n\n");
10765 for func in self.original_functions:
10766 if not func.InAnyPepperExtension():
10767 continue
10769 original_arg = func.MakeTypedPepperArgString("")
10770 context_arg = "PP_Resource context_id"
10771 if len(original_arg):
10772 arg = context_arg + ", " + original_arg
10773 else:
10774 arg = context_arg
10775 f.write("%s %s(%s) {\n" %
10776 (func.return_type, func.GetPepperName(), arg))
10777 f.write(" Enter3D enter(context_id, true);\n")
10778 f.write(" if (enter.succeeded()) {\n")
10780 return_str = "" if func.return_type == "void" else "return "
10781 f.write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10782 (return_str, func.original_name,
10783 func.MakeOriginalArgString("")))
10784 f.write(" }")
10785 if func.return_type == "void":
10786 f.write("\n")
10787 else:
10788 f.write(" else {\n")
10789 f.write(" return %s;\n" % func.GetErrorReturnString())
10790 f.write(" }\n")
10791 f.write("}\n\n")
10793 f.write("} // namespace\n")
10795 for interface in self.pepper_interfaces:
10796 f.write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10797 (interface.GetStructName(), interface.GetName()))
10798 f.write(" static const struct %s "
10799 "ppb_opengles2 = {\n" % interface.GetStructName())
10800 f.write(" &")
10801 f.write(",\n &".join(
10802 f.GetPepperName() for f in self.original_functions
10803 if f.InPepperInterface(interface)))
10804 f.write("\n")
10806 f.write(" };\n")
10807 f.write(" return &ppb_opengles2;\n")
10808 f.write("}\n")
10810 f.write("} // namespace ppapi\n")
10811 self.generated_cpp_filenames.append(filename)
10813 def WriteGLES2ToPPAPIBridge(self, filename):
10814 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10815 with CWriter(filename) as f:
10816 f.write("#ifndef GL_GLEXT_PROTOTYPES\n")
10817 f.write("#define GL_GLEXT_PROTOTYPES\n")
10818 f.write("#endif\n")
10819 f.write("#include <GLES2/gl2.h>\n")
10820 f.write("#include <GLES2/gl2ext.h>\n")
10821 f.write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10823 for func in self.original_functions:
10824 if not func.InAnyPepperExtension():
10825 continue
10827 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
10829 f.write("%s GL_APIENTRY gl%s(%s) {\n" %
10830 (func.return_type, func.GetPepperName(),
10831 func.MakeTypedPepperArgString("")))
10832 return_str = "" if func.return_type == "void" else "return "
10833 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
10834 original_arg = func.MakeOriginalArgString("")
10835 context_arg = "glGetCurrentContextPPAPI()"
10836 if len(original_arg):
10837 arg = context_arg + ", " + original_arg
10838 else:
10839 arg = context_arg
10840 if interface.GetName():
10841 f.write(" const struct %s* ext = %s;\n" %
10842 (interface.GetStructName(), interface_str))
10843 f.write(" if (ext)\n")
10844 f.write(" %sext->%s(%s);\n" %
10845 (return_str, func.GetPepperName(), arg))
10846 if return_str:
10847 f.write(" %s0;\n" % return_str)
10848 else:
10849 f.write(" %s%s->%s(%s);\n" %
10850 (return_str, interface_str, func.GetPepperName(), arg))
10851 f.write("}\n\n")
10852 self.generated_cpp_filenames.append(filename)
10854 def WriteMojoGLCallVisitor(self, filename):
10855 """Provides the GL implementation for mojo"""
10856 with CWriter(filename) as f:
10857 for func in self.original_functions:
10858 if not func.IsCoreGLFunction():
10859 continue
10860 f.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10861 (func.name, func.return_type,
10862 func.MakeTypedOriginalArgString(""),
10863 func.MakeOriginalArgString("")))
10864 self.generated_cpp_filenames.append(filename)
10866 def WriteMojoGLCallVisitorForExtension(self, filename, extension):
10867 """Provides the GL implementation for mojo for a particular extension"""
10868 with CWriter(filename) as f:
10869 for func in self.original_functions:
10870 if func.GetInfo("extension") != extension:
10871 continue
10872 f.write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10873 (func.name, func.return_type,
10874 func.MakeTypedOriginalArgString(""),
10875 func.MakeOriginalArgString("")))
10876 self.generated_cpp_filenames.append(filename)
10878 def Format(generated_files):
10879 formatter = "clang-format"
10880 if platform.system() == "Windows":
10881 formatter += ".bat"
10882 for filename in generated_files:
10883 call([formatter, "-i", "-style=chromium", filename])
10885 def main(argv):
10886 """This is the main function."""
10887 parser = OptionParser()
10888 parser.add_option(
10889 "--output-dir",
10890 help="base directory for resulting files, under chrome/src. default is "
10891 "empty. Use this if you want the result stored under gen.")
10892 parser.add_option(
10893 "-v", "--verbose", action="store_true",
10894 help="prints more output.")
10896 (options, args) = parser.parse_args(args=argv)
10898 # Add in states and capabilites to GLState
10899 gl_state_valid = _NAMED_TYPE_INFO['GLState']['valid']
10900 for state_name in sorted(_STATES.keys()):
10901 state = _STATES[state_name]
10902 if 'extension_flag' in state:
10903 continue
10904 if 'enum' in state:
10905 if not state['enum'] in gl_state_valid:
10906 gl_state_valid.append(state['enum'])
10907 else:
10908 for item in state['states']:
10909 if 'extension_flag' in item:
10910 continue
10911 if not item['enum'] in gl_state_valid:
10912 gl_state_valid.append(item['enum'])
10913 for capability in _CAPABILITY_FLAGS:
10914 valid_value = "GL_%s" % capability['name'].upper()
10915 if not valid_value in gl_state_valid:
10916 gl_state_valid.append(valid_value)
10918 # This script lives under gpu/command_buffer, cd to base directory.
10919 os.chdir(os.path.dirname(__file__) + "/../..")
10920 base_dir = os.getcwd()
10921 gen = GLGenerator(options.verbose)
10922 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10924 # Support generating files under gen/
10925 if options.output_dir != None:
10926 os.chdir(options.output_dir)
10928 gen.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10929 gen.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10930 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10931 gen.WritePepperGLES2Implementation(
10932 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10933 os.chdir(base_dir)
10934 gen.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10935 gen.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10936 gen.WriteFormatTest(
10937 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10938 gen.WriteGLES2InterfaceHeader(
10939 "gpu/command_buffer/client/gles2_interface_autogen.h")
10940 gen.WriteMojoGLES2ImplHeader(
10941 "mojo/gpu/mojo_gles2_impl_autogen.h")
10942 gen.WriteMojoGLES2Impl(
10943 "mojo/gpu/mojo_gles2_impl_autogen.cc")
10944 gen.WriteGLES2InterfaceStub(
10945 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10946 gen.WriteGLES2InterfaceStubImpl(
10947 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10948 gen.WriteGLES2ImplementationHeader(
10949 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10950 gen.WriteGLES2Implementation(
10951 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10952 gen.WriteGLES2ImplementationUnitTests(
10953 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10954 gen.WriteGLES2TraceImplementationHeader(
10955 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10956 gen.WriteGLES2TraceImplementation(
10957 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10958 gen.WriteGLES2CLibImplementation(
10959 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10960 gen.WriteCmdHelperHeader(
10961 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
10962 gen.WriteServiceImplementation(
10963 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
10964 gen.WriteServiceContextStateHeader(
10965 "gpu/command_buffer/service/context_state_autogen.h")
10966 gen.WriteServiceContextStateImpl(
10967 "gpu/command_buffer/service/context_state_impl_autogen.h")
10968 gen.WriteClientContextStateHeader(
10969 "gpu/command_buffer/client/client_context_state_autogen.h")
10970 gen.WriteClientContextStateImpl(
10971 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
10972 gen.WriteServiceUnitTests(
10973 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
10974 gen.WriteServiceUnitTestsForExtensions(
10975 "gpu/command_buffer/service/"
10976 "gles2_cmd_decoder_unittest_extensions_autogen.h")
10977 gen.WriteServiceUtilsHeader(
10978 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
10979 gen.WriteServiceUtilsImplementation(
10980 "gpu/command_buffer/service/"
10981 "gles2_cmd_validation_implementation_autogen.h")
10982 gen.WriteCommonUtilsHeader(
10983 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
10984 gen.WriteCommonUtilsImpl(
10985 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
10986 gen.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
10987 mojo_gles2_prefix = ("third_party/mojo/src/mojo/public/c/gles2/"
10988 "gles2_call_visitor")
10989 gen.WriteMojoGLCallVisitor(mojo_gles2_prefix + "_autogen.h")
10990 gen.WriteMojoGLCallVisitorForExtension(
10991 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
10992 "CHROMIUM_texture_mailbox")
10993 gen.WriteMojoGLCallVisitorForExtension(
10994 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
10995 "CHROMIUM_sync_point")
10996 gen.WriteMojoGLCallVisitorForExtension(
10997 mojo_gles2_prefix + "_chromium_sub_image_autogen.h",
10998 "CHROMIUM_sub_image")
10999 gen.WriteMojoGLCallVisitorForExtension(
11000 mojo_gles2_prefix + "_chromium_miscellaneous_autogen.h",
11001 "CHROMIUM_miscellaneous")
11002 gen.WriteMojoGLCallVisitorForExtension(
11003 mojo_gles2_prefix + "_occlusion_query_ext_autogen.h",
11004 "occlusion_query_EXT")
11005 gen.WriteMojoGLCallVisitorForExtension(
11006 mojo_gles2_prefix + "_chromium_image_autogen.h",
11007 "CHROMIUM_image")
11008 gen.WriteMojoGLCallVisitorForExtension(
11009 mojo_gles2_prefix + "_chromium_copy_texture_autogen.h",
11010 "CHROMIUM_copy_texture")
11011 gen.WriteMojoGLCallVisitorForExtension(
11012 mojo_gles2_prefix + "_chromium_pixel_transfer_buffer_object_autogen.h",
11013 "CHROMIUM_pixel_transfer_buffer_object")
11015 Format(gen.generated_cpp_filenames)
11017 if gen.errors > 0:
11018 print "%d errors" % gen.errors
11019 return 1
11020 return 0
11023 if __name__ == '__main__':
11024 sys.exit(main(sys.argv[1:]))