[MacViews] Show comboboxes with a native NSMenu
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blob7780a83261fd78c6dc5f059292592b3a93694aad
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_GPU_DISJOINT_EXT',
816 'GL_MAJOR_VERSION',
817 'GL_MAX_3D_TEXTURE_SIZE',
818 'GL_MAX_ARRAY_TEXTURE_LAYERS',
819 'GL_MAX_COLOR_ATTACHMENTS',
820 'GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS',
821 'GL_MAX_COMBINED_UNIFORM_BLOCKS',
822 'GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS',
823 'GL_MAX_DRAW_BUFFERS',
824 'GL_MAX_ELEMENT_INDEX',
825 'GL_MAX_ELEMENTS_INDICES',
826 'GL_MAX_ELEMENTS_VERTICES',
827 'GL_MAX_FRAGMENT_INPUT_COMPONENTS',
828 'GL_MAX_FRAGMENT_UNIFORM_BLOCKS',
829 'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS',
830 'GL_MAX_PROGRAM_TEXEL_OFFSET',
831 'GL_MAX_SAMPLES',
832 'GL_MAX_SERVER_WAIT_TIMEOUT',
833 'GL_MAX_TEXTURE_LOD_BIAS',
834 'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS',
835 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS',
836 'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS',
837 'GL_MAX_UNIFORM_BLOCK_SIZE',
838 'GL_MAX_UNIFORM_BUFFER_BINDINGS',
839 'GL_MAX_VARYING_COMPONENTS',
840 'GL_MAX_VERTEX_OUTPUT_COMPONENTS',
841 'GL_MAX_VERTEX_UNIFORM_BLOCKS',
842 'GL_MAX_VERTEX_UNIFORM_COMPONENTS',
843 'GL_MIN_PROGRAM_TEXEL_OFFSET',
844 'GL_MINOR_VERSION',
845 'GL_NUM_EXTENSIONS',
846 'GL_NUM_PROGRAM_BINARY_FORMATS',
847 'GL_PACK_ROW_LENGTH',
848 'GL_PACK_SKIP_PIXELS',
849 'GL_PACK_SKIP_ROWS',
850 'GL_PIXEL_PACK_BUFFER_BINDING',
851 'GL_PIXEL_UNPACK_BUFFER_BINDING',
852 'GL_PROGRAM_BINARY_FORMATS',
853 'GL_READ_BUFFER',
854 'GL_READ_FRAMEBUFFER_BINDING',
855 'GL_SAMPLER_BINDING',
856 'GL_TIMESTAMP_EXT',
857 'GL_TEXTURE_BINDING_2D_ARRAY',
858 'GL_TEXTURE_BINDING_3D',
859 'GL_TRANSFORM_FEEDBACK_BINDING',
860 'GL_TRANSFORM_FEEDBACK_ACTIVE',
861 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
862 'GL_TRANSFORM_FEEDBACK_PAUSED',
863 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
864 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
865 'GL_UNIFORM_BUFFER_BINDING',
866 'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT',
867 'GL_UNIFORM_BUFFER_SIZE',
868 'GL_UNIFORM_BUFFER_START',
869 'GL_UNPACK_IMAGE_HEIGHT',
870 'GL_UNPACK_ROW_LENGTH',
871 'GL_UNPACK_SKIP_IMAGES',
872 'GL_UNPACK_SKIP_PIXELS',
873 'GL_UNPACK_SKIP_ROWS',
874 # GL_VERTEX_ARRAY_BINDING is the same as GL_VERTEX_ARRAY_BINDING_OES
875 # 'GL_VERTEX_ARRAY_BINDING',
877 'invalid': [
878 'GL_FOG_HINT',
881 'IndexedGLState': {
882 'type': 'GLenum',
883 'valid': [
884 'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING',
885 'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE',
886 'GL_TRANSFORM_FEEDBACK_BUFFER_START',
887 'GL_UNIFORM_BUFFER_BINDING',
888 'GL_UNIFORM_BUFFER_SIZE',
889 'GL_UNIFORM_BUFFER_START',
891 'invalid': [
892 'GL_FOG_HINT',
895 'GetTexParamTarget': {
896 'type': 'GLenum',
897 'valid': [
898 'GL_TEXTURE_2D',
899 'GL_TEXTURE_CUBE_MAP',
901 'valid_es3': [
902 'GL_TEXTURE_2D_ARRAY',
903 'GL_TEXTURE_3D',
905 'invalid': [
906 'GL_PROXY_TEXTURE_CUBE_MAP',
909 'ReadBuffer': {
910 'type': 'GLenum',
911 'valid': [
912 'GL_NONE',
913 'GL_BACK',
914 'GL_COLOR_ATTACHMENT0',
915 'GL_COLOR_ATTACHMENT1',
916 'GL_COLOR_ATTACHMENT2',
917 'GL_COLOR_ATTACHMENT3',
918 'GL_COLOR_ATTACHMENT4',
919 'GL_COLOR_ATTACHMENT5',
920 'GL_COLOR_ATTACHMENT6',
921 'GL_COLOR_ATTACHMENT7',
922 'GL_COLOR_ATTACHMENT8',
923 'GL_COLOR_ATTACHMENT9',
924 'GL_COLOR_ATTACHMENT10',
925 'GL_COLOR_ATTACHMENT11',
926 'GL_COLOR_ATTACHMENT12',
927 'GL_COLOR_ATTACHMENT13',
928 'GL_COLOR_ATTACHMENT14',
929 'GL_COLOR_ATTACHMENT15',
931 'invalid': [
932 'GL_RENDERBUFFER',
935 'TextureTarget': {
936 'type': 'GLenum',
937 'valid': [
938 'GL_TEXTURE_2D',
939 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
940 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
941 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
942 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
943 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
944 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
946 'invalid': [
947 'GL_PROXY_TEXTURE_CUBE_MAP',
950 'Texture3DTarget': {
951 'type': 'GLenum',
952 'valid': [
953 'GL_TEXTURE_3D',
954 'GL_TEXTURE_2D_ARRAY',
956 'invalid': [
957 'GL_TEXTURE_2D',
960 'TextureBindTarget': {
961 'type': 'GLenum',
962 'valid': [
963 'GL_TEXTURE_2D',
964 'GL_TEXTURE_CUBE_MAP',
966 'valid_es3': [
967 'GL_TEXTURE_3D',
968 'GL_TEXTURE_2D_ARRAY',
970 'invalid': [
971 'GL_TEXTURE_1D',
972 'GL_TEXTURE_3D',
975 'TransformFeedbackBindTarget': {
976 'type': 'GLenum',
977 'valid': [
978 'GL_TRANSFORM_FEEDBACK',
980 'invalid': [
981 'GL_TEXTURE_2D',
984 'TransformFeedbackPrimitiveMode': {
985 'type': 'GLenum',
986 'valid': [
987 'GL_POINTS',
988 'GL_LINES',
989 'GL_TRIANGLES',
991 'invalid': [
992 'GL_LINE_LOOP',
995 'ShaderType': {
996 'type': 'GLenum',
997 'valid': [
998 'GL_VERTEX_SHADER',
999 'GL_FRAGMENT_SHADER',
1001 'invalid': [
1002 'GL_GEOMETRY_SHADER',
1005 'FaceType': {
1006 'type': 'GLenum',
1007 'valid': [
1008 'GL_FRONT',
1009 'GL_BACK',
1010 'GL_FRONT_AND_BACK',
1013 'FaceMode': {
1014 'type': 'GLenum',
1015 'valid': [
1016 'GL_CW',
1017 'GL_CCW',
1020 'CmpFunction': {
1021 'type': 'GLenum',
1022 'valid': [
1023 'GL_NEVER',
1024 'GL_LESS',
1025 'GL_EQUAL',
1026 'GL_LEQUAL',
1027 'GL_GREATER',
1028 'GL_NOTEQUAL',
1029 'GL_GEQUAL',
1030 'GL_ALWAYS',
1033 'Equation': {
1034 'type': 'GLenum',
1035 'valid': [
1036 'GL_FUNC_ADD',
1037 'GL_FUNC_SUBTRACT',
1038 'GL_FUNC_REVERSE_SUBTRACT',
1040 'valid_es3': [
1041 'GL_MIN',
1042 'GL_MAX',
1044 'invalid': [
1045 'GL_NONE',
1048 'SrcBlendFactor': {
1049 'type': 'GLenum',
1050 'valid': [
1051 'GL_ZERO',
1052 'GL_ONE',
1053 'GL_SRC_COLOR',
1054 'GL_ONE_MINUS_SRC_COLOR',
1055 'GL_DST_COLOR',
1056 'GL_ONE_MINUS_DST_COLOR',
1057 'GL_SRC_ALPHA',
1058 'GL_ONE_MINUS_SRC_ALPHA',
1059 'GL_DST_ALPHA',
1060 'GL_ONE_MINUS_DST_ALPHA',
1061 'GL_CONSTANT_COLOR',
1062 'GL_ONE_MINUS_CONSTANT_COLOR',
1063 'GL_CONSTANT_ALPHA',
1064 'GL_ONE_MINUS_CONSTANT_ALPHA',
1065 'GL_SRC_ALPHA_SATURATE',
1068 'DstBlendFactor': {
1069 'type': 'GLenum',
1070 'valid': [
1071 'GL_ZERO',
1072 'GL_ONE',
1073 'GL_SRC_COLOR',
1074 'GL_ONE_MINUS_SRC_COLOR',
1075 'GL_DST_COLOR',
1076 'GL_ONE_MINUS_DST_COLOR',
1077 'GL_SRC_ALPHA',
1078 'GL_ONE_MINUS_SRC_ALPHA',
1079 'GL_DST_ALPHA',
1080 'GL_ONE_MINUS_DST_ALPHA',
1081 'GL_CONSTANT_COLOR',
1082 'GL_ONE_MINUS_CONSTANT_COLOR',
1083 'GL_CONSTANT_ALPHA',
1084 'GL_ONE_MINUS_CONSTANT_ALPHA',
1087 'Capability': {
1088 'type': 'GLenum',
1089 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
1090 if 'es3' not in cap or cap['es3'] != True],
1091 'valid_es3': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
1092 if 'es3' in cap and cap['es3'] == True],
1093 'invalid': [
1094 'GL_CLIP_PLANE0',
1095 'GL_POINT_SPRITE',
1098 'DrawMode': {
1099 'type': 'GLenum',
1100 'valid': [
1101 'GL_POINTS',
1102 'GL_LINE_STRIP',
1103 'GL_LINE_LOOP',
1104 'GL_LINES',
1105 'GL_TRIANGLE_STRIP',
1106 'GL_TRIANGLE_FAN',
1107 'GL_TRIANGLES',
1109 'invalid': [
1110 'GL_QUADS',
1111 'GL_POLYGON',
1114 'IndexType': {
1115 'type': 'GLenum',
1116 'valid': [
1117 'GL_UNSIGNED_BYTE',
1118 'GL_UNSIGNED_SHORT',
1120 'valid_es3': [
1121 'GL_UNSIGNED_INT',
1123 'invalid': [
1124 'GL_INT',
1127 'GetMaxIndexType': {
1128 'type': 'GLenum',
1129 'valid': [
1130 'GL_UNSIGNED_BYTE',
1131 'GL_UNSIGNED_SHORT',
1132 'GL_UNSIGNED_INT',
1134 'invalid': [
1135 'GL_INT',
1138 'Attachment': {
1139 'type': 'GLenum',
1140 'valid': [
1141 'GL_COLOR_ATTACHMENT0',
1142 'GL_DEPTH_ATTACHMENT',
1143 'GL_STENCIL_ATTACHMENT',
1145 'valid_es3': [
1146 'GL_DEPTH_STENCIL_ATTACHMENT',
1147 # For backbuffer.
1148 'GL_COLOR_EXT',
1149 'GL_DEPTH_EXT',
1150 'GL_STENCIL_EXT',
1153 'BackbufferAttachment': {
1154 'type': 'GLenum',
1155 'valid': [
1156 'GL_COLOR_EXT',
1157 'GL_DEPTH_EXT',
1158 'GL_STENCIL_EXT',
1161 'BufferParameter': {
1162 'type': 'GLenum',
1163 'valid': [
1164 'GL_BUFFER_SIZE',
1165 'GL_BUFFER_USAGE',
1167 'valid_es3': [
1168 'GL_BUFFER_ACCESS_FLAGS',
1169 'GL_BUFFER_MAPPED',
1171 'invalid': [
1172 'GL_PIXEL_PACK_BUFFER',
1175 'BufferParameter64': {
1176 'type': 'GLenum',
1177 'valid': [
1178 'GL_BUFFER_SIZE',
1179 'GL_BUFFER_MAP_LENGTH',
1180 'GL_BUFFER_MAP_OFFSET',
1182 'invalid': [
1183 'GL_PIXEL_PACK_BUFFER',
1186 'BufferMode': {
1187 'type': 'GLenum',
1188 'valid': [
1189 'GL_INTERLEAVED_ATTRIBS',
1190 'GL_SEPARATE_ATTRIBS',
1192 'invalid': [
1193 'GL_PIXEL_PACK_BUFFER',
1196 'FrameBufferParameter': {
1197 'type': 'GLenum',
1198 'valid': [
1199 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
1200 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
1201 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
1202 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
1204 'valid_es3': [
1205 'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE',
1206 'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE',
1207 'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE',
1208 'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE',
1209 'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE',
1210 'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE',
1211 'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE',
1212 'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING',
1213 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER',
1216 'MatrixMode': {
1217 'type': 'GLenum',
1218 'valid': [
1219 'GL_PATH_PROJECTION_CHROMIUM',
1220 'GL_PATH_MODELVIEW_CHROMIUM',
1223 'ProgramParameter': {
1224 'type': 'GLenum',
1225 'valid': [
1226 'GL_DELETE_STATUS',
1227 'GL_LINK_STATUS',
1228 'GL_VALIDATE_STATUS',
1229 'GL_INFO_LOG_LENGTH',
1230 'GL_ATTACHED_SHADERS',
1231 'GL_ACTIVE_ATTRIBUTES',
1232 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1233 'GL_ACTIVE_UNIFORMS',
1234 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1236 'valid_es3': [
1237 'GL_ACTIVE_UNIFORM_BLOCKS',
1238 'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH',
1239 'GL_TRANSFORM_FEEDBACK_BUFFER_MODE',
1240 'GL_TRANSFORM_FEEDBACK_VARYINGS',
1241 'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH',
1243 'invalid': [
1244 'GL_PROGRAM_BINARY_RETRIEVABLE_HINT', # not supported in Chromium.
1247 'QueryObjectParameter': {
1248 'type': 'GLenum',
1249 'valid': [
1250 'GL_QUERY_RESULT_EXT',
1251 'GL_QUERY_RESULT_AVAILABLE_EXT',
1254 'QueryParameter': {
1255 'type': 'GLenum',
1256 'valid': [
1257 'GL_CURRENT_QUERY_EXT',
1260 'QueryTarget': {
1261 'type': 'GLenum',
1262 'valid': [
1263 'GL_ANY_SAMPLES_PASSED_EXT',
1264 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1265 'GL_COMMANDS_ISSUED_CHROMIUM',
1266 'GL_LATENCY_QUERY_CHROMIUM',
1267 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1268 'GL_COMMANDS_COMPLETED_CHROMIUM',
1271 'RenderBufferParameter': {
1272 'type': 'GLenum',
1273 'valid': [
1274 'GL_RENDERBUFFER_RED_SIZE',
1275 'GL_RENDERBUFFER_GREEN_SIZE',
1276 'GL_RENDERBUFFER_BLUE_SIZE',
1277 'GL_RENDERBUFFER_ALPHA_SIZE',
1278 'GL_RENDERBUFFER_DEPTH_SIZE',
1279 'GL_RENDERBUFFER_STENCIL_SIZE',
1280 'GL_RENDERBUFFER_WIDTH',
1281 'GL_RENDERBUFFER_HEIGHT',
1282 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1284 'valid_es3': [
1285 'GL_RENDERBUFFER_SAMPLES',
1288 'InternalFormatParameter': {
1289 'type': 'GLenum',
1290 'valid': [
1291 'GL_NUM_SAMPLE_COUNTS',
1292 'GL_SAMPLES',
1295 'SamplerParameter': {
1296 'type': 'GLenum',
1297 'valid': [
1298 'GL_TEXTURE_MAG_FILTER',
1299 'GL_TEXTURE_MIN_FILTER',
1300 'GL_TEXTURE_MIN_LOD',
1301 'GL_TEXTURE_MAX_LOD',
1302 'GL_TEXTURE_WRAP_S',
1303 'GL_TEXTURE_WRAP_T',
1304 'GL_TEXTURE_WRAP_R',
1305 'GL_TEXTURE_COMPARE_MODE',
1306 'GL_TEXTURE_COMPARE_FUNC',
1308 'invalid': [
1309 'GL_GENERATE_MIPMAP',
1312 'ShaderParameter': {
1313 'type': 'GLenum',
1314 'valid': [
1315 'GL_SHADER_TYPE',
1316 'GL_DELETE_STATUS',
1317 'GL_COMPILE_STATUS',
1318 'GL_INFO_LOG_LENGTH',
1319 'GL_SHADER_SOURCE_LENGTH',
1320 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1323 'ShaderPrecision': {
1324 'type': 'GLenum',
1325 'valid': [
1326 'GL_LOW_FLOAT',
1327 'GL_MEDIUM_FLOAT',
1328 'GL_HIGH_FLOAT',
1329 'GL_LOW_INT',
1330 'GL_MEDIUM_INT',
1331 'GL_HIGH_INT',
1334 'StringType': {
1335 'type': 'GLenum',
1336 'valid': [
1337 'GL_VENDOR',
1338 'GL_RENDERER',
1339 'GL_VERSION',
1340 'GL_SHADING_LANGUAGE_VERSION',
1341 'GL_EXTENSIONS',
1344 'TextureParameter': {
1345 'type': 'GLenum',
1346 'valid': [
1347 'GL_TEXTURE_MAG_FILTER',
1348 'GL_TEXTURE_MIN_FILTER',
1349 'GL_TEXTURE_POOL_CHROMIUM',
1350 'GL_TEXTURE_WRAP_S',
1351 'GL_TEXTURE_WRAP_T',
1353 'valid_es3': [
1354 'GL_TEXTURE_BASE_LEVEL',
1355 'GL_TEXTURE_COMPARE_FUNC',
1356 'GL_TEXTURE_COMPARE_MODE',
1357 'GL_TEXTURE_IMMUTABLE_FORMAT',
1358 'GL_TEXTURE_IMMUTABLE_LEVELS',
1359 'GL_TEXTURE_MAX_LEVEL',
1360 'GL_TEXTURE_MAX_LOD',
1361 'GL_TEXTURE_MIN_LOD',
1362 'GL_TEXTURE_WRAP_R',
1364 'invalid': [
1365 'GL_GENERATE_MIPMAP',
1368 'TexturePool': {
1369 'type': 'GLenum',
1370 'valid': [
1371 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1372 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1375 'TextureWrapMode': {
1376 'type': 'GLenum',
1377 'valid': [
1378 'GL_CLAMP_TO_EDGE',
1379 'GL_MIRRORED_REPEAT',
1380 'GL_REPEAT',
1383 'TextureMinFilterMode': {
1384 'type': 'GLenum',
1385 'valid': [
1386 'GL_NEAREST',
1387 'GL_LINEAR',
1388 'GL_NEAREST_MIPMAP_NEAREST',
1389 'GL_LINEAR_MIPMAP_NEAREST',
1390 'GL_NEAREST_MIPMAP_LINEAR',
1391 'GL_LINEAR_MIPMAP_LINEAR',
1394 'TextureMagFilterMode': {
1395 'type': 'GLenum',
1396 'valid': [
1397 'GL_NEAREST',
1398 'GL_LINEAR',
1401 'TextureCompareFunc': {
1402 'type': 'GLenum',
1403 'valid': [
1404 'GL_LEQUAL',
1405 'GL_GEQUAL',
1406 'GL_LESS',
1407 'GL_GREATER',
1408 'GL_EQUAL',
1409 'GL_NOTEQUAL',
1410 'GL_ALWAYS',
1411 'GL_NEVER',
1414 'TextureCompareMode': {
1415 'type': 'GLenum',
1416 'valid': [
1417 'GL_NONE',
1418 'GL_COMPARE_REF_TO_TEXTURE',
1421 'TextureUsage': {
1422 'type': 'GLenum',
1423 'valid': [
1424 'GL_NONE',
1425 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1428 'VertexAttribute': {
1429 'type': 'GLenum',
1430 'valid': [
1431 # some enum that the decoder actually passes through to GL needs
1432 # to be the first listed here since it's used in unit tests.
1433 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1434 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1435 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1436 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1437 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1438 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1439 'GL_CURRENT_VERTEX_ATTRIB',
1441 'valid_es3': [
1442 'GL_VERTEX_ATTRIB_ARRAY_INTEGER',
1443 'GL_VERTEX_ATTRIB_ARRAY_DIVISOR',
1446 'VertexPointer': {
1447 'type': 'GLenum',
1448 'valid': [
1449 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1452 'HintTarget': {
1453 'type': 'GLenum',
1454 'valid': [
1455 'GL_GENERATE_MIPMAP_HINT',
1457 'valid_es3': [
1458 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT',
1460 'invalid': [
1461 'GL_PERSPECTIVE_CORRECTION_HINT',
1464 'HintMode': {
1465 'type': 'GLenum',
1466 'valid': [
1467 'GL_FASTEST',
1468 'GL_NICEST',
1469 'GL_DONT_CARE',
1472 'PixelStore': {
1473 'type': 'GLenum',
1474 'valid': [
1475 'GL_PACK_ALIGNMENT',
1476 'GL_UNPACK_ALIGNMENT',
1478 'valid_es3': [
1479 'GL_PACK_ROW_LENGTH',
1480 'GL_PACK_SKIP_PIXELS',
1481 'GL_PACK_SKIP_ROWS',
1482 'GL_UNPACK_ROW_LENGTH',
1483 'GL_UNPACK_IMAGE_HEIGHT',
1484 'GL_UNPACK_SKIP_PIXELS',
1485 'GL_UNPACK_SKIP_ROWS',
1486 'GL_UNPACK_SKIP_IMAGES',
1488 'invalid': [
1489 'GL_PACK_SWAP_BYTES',
1490 'GL_UNPACK_SWAP_BYTES',
1493 'PixelStoreAlignment': {
1494 'type': 'GLint',
1495 'valid': [
1496 '1',
1497 '2',
1498 '4',
1499 '8',
1501 'invalid': [
1502 '3',
1503 '9',
1506 'ReadPixelFormat': {
1507 'type': 'GLenum',
1508 'valid': [
1509 'GL_ALPHA',
1510 'GL_RGB',
1511 'GL_RGBA',
1513 'valid_es3': [
1514 'GL_RED',
1515 'GL_RED_INTEGER',
1516 'GL_RG',
1517 'GL_RG_INTEGER',
1518 'GL_RGB_INTEGER',
1519 'GL_RGBA_INTEGER',
1522 'PixelType': {
1523 'type': 'GLenum',
1524 'valid': [
1525 'GL_UNSIGNED_BYTE',
1526 'GL_UNSIGNED_SHORT_5_6_5',
1527 'GL_UNSIGNED_SHORT_4_4_4_4',
1528 'GL_UNSIGNED_SHORT_5_5_5_1',
1530 'valid_es3': [
1531 'GL_BYTE',
1532 'GL_UNSIGNED_SHORT',
1533 'GL_SHORT',
1534 'GL_UNSIGNED_INT',
1535 'GL_INT',
1536 'GL_HALF_FLOAT',
1537 'GL_FLOAT',
1538 'GL_UNSIGNED_INT_2_10_10_10_REV',
1539 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1540 'GL_UNSIGNED_INT_5_9_9_9_REV',
1541 'GL_UNSIGNED_INT_24_8',
1542 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1544 'invalid': [
1545 'GL_UNSIGNED_BYTE_3_3_2',
1548 'PathCoordType': {
1549 'type': 'GLenum',
1550 'valid': [
1551 'GL_BYTE',
1552 'GL_UNSIGNED_BYTE',
1553 'GL_SHORT',
1554 'GL_UNSIGNED_SHORT',
1555 'GL_FLOAT',
1558 'PathCoverMode': {
1559 'type': 'GLenum',
1560 'valid': [
1561 'GL_CONVEX_HULL_CHROMIUM',
1562 'GL_BOUNDING_BOX_CHROMIUM',
1565 'PathFillMode': {
1566 'type': 'GLenum',
1567 'valid': [
1568 'GL_INVERT',
1569 'GL_COUNT_UP_CHROMIUM',
1570 'GL_COUNT_DOWN_CHROMIUM',
1573 'PathParameter': {
1574 'type': 'GLenum',
1575 'valid': [
1576 'GL_PATH_STROKE_WIDTH_CHROMIUM',
1577 'GL_PATH_END_CAPS_CHROMIUM',
1578 'GL_PATH_JOIN_STYLE_CHROMIUM',
1579 'GL_PATH_MITER_LIMIT_CHROMIUM',
1580 'GL_PATH_STROKE_BOUND_CHROMIUM',
1583 'PathParameterCapValues': {
1584 'type': 'GLint',
1585 'valid': [
1586 'GL_FLAT',
1587 'GL_SQUARE_CHROMIUM',
1588 'GL_ROUND_CHROMIUM',
1591 'PathParameterJoinValues': {
1592 'type': 'GLint',
1593 'valid': [
1594 'GL_MITER_REVERT_CHROMIUM',
1595 'GL_BEVEL_CHROMIUM',
1596 'GL_ROUND_CHROMIUM',
1599 'ReadPixelType': {
1600 'type': 'GLenum',
1601 'valid': [
1602 'GL_UNSIGNED_BYTE',
1603 'GL_UNSIGNED_SHORT_5_6_5',
1604 'GL_UNSIGNED_SHORT_4_4_4_4',
1605 'GL_UNSIGNED_SHORT_5_5_5_1',
1607 'valid_es3': [
1608 'GL_BYTE',
1609 'GL_UNSIGNED_SHORT',
1610 'GL_SHORT',
1611 'GL_UNSIGNED_INT',
1612 'GL_INT',
1613 'GL_HALF_FLOAT',
1614 'GL_FLOAT',
1615 'GL_UNSIGNED_INT_2_10_10_10_REV',
1618 'RenderBufferFormat': {
1619 'type': 'GLenum',
1620 'valid': [
1621 'GL_RGBA4',
1622 'GL_RGB565',
1623 'GL_RGB5_A1',
1624 'GL_DEPTH_COMPONENT16',
1625 'GL_STENCIL_INDEX8',
1627 'valid_es3': [
1628 'GL_R8',
1629 'GL_R8UI',
1630 'GL_R8I',
1631 'GL_R16UI',
1632 'GL_R16I',
1633 'GL_R32UI',
1634 'GL_R32I',
1635 'GL_RG8',
1636 'GL_RG8UI',
1637 'GL_RG8I',
1638 'GL_RG16UI',
1639 'GL_RG16I',
1640 'GL_RG32UI',
1641 'GL_RG32I',
1642 'GL_RGB8',
1643 'GL_RGBA8',
1644 'GL_SRGB8_ALPHA8',
1645 'GL_RGB10_A2',
1646 'GL_RGBA8UI',
1647 'GL_RGBA8I',
1648 'GL_RGB10_A2UI',
1649 'GL_RGBA16UI',
1650 'GL_RGBA16I',
1651 'GL_RGBA32UI',
1652 'GL_RGBA32I',
1653 'GL_DEPTH_COMPONENT24',
1654 'GL_DEPTH_COMPONENT32F',
1655 'GL_DEPTH24_STENCIL8',
1656 'GL_DEPTH32F_STENCIL8',
1659 'ShaderBinaryFormat': {
1660 'type': 'GLenum',
1661 'valid': [
1664 'StencilOp': {
1665 'type': 'GLenum',
1666 'valid': [
1667 'GL_KEEP',
1668 'GL_ZERO',
1669 'GL_REPLACE',
1670 'GL_INCR',
1671 'GL_INCR_WRAP',
1672 'GL_DECR',
1673 'GL_DECR_WRAP',
1674 'GL_INVERT',
1677 'TextureFormat': {
1678 'type': 'GLenum',
1679 'valid': [
1680 'GL_ALPHA',
1681 'GL_LUMINANCE',
1682 'GL_LUMINANCE_ALPHA',
1683 'GL_RGB',
1684 'GL_RGBA',
1686 'valid_es3': [
1687 'GL_RED',
1688 'GL_RED_INTEGER',
1689 'GL_RG',
1690 'GL_RG_INTEGER',
1691 'GL_RGB_INTEGER',
1692 'GL_RGBA_INTEGER',
1693 'GL_DEPTH_COMPONENT',
1694 'GL_DEPTH_STENCIL',
1696 'invalid': [
1697 'GL_BGRA',
1698 'GL_BGR',
1701 'TextureInternalFormat': {
1702 'type': 'GLenum',
1703 'valid': [
1704 'GL_ALPHA',
1705 'GL_LUMINANCE',
1706 'GL_LUMINANCE_ALPHA',
1707 'GL_RGB',
1708 'GL_RGBA',
1710 'valid_es3': [
1711 'GL_R8',
1712 'GL_R8_SNORM',
1713 'GL_R16F',
1714 'GL_R32F',
1715 'GL_R8UI',
1716 'GL_R8I',
1717 'GL_R16UI',
1718 'GL_R16I',
1719 'GL_R32UI',
1720 'GL_R32I',
1721 'GL_RG8',
1722 'GL_RG8_SNORM',
1723 'GL_RG16F',
1724 'GL_RG32F',
1725 'GL_RG8UI',
1726 'GL_RG8I',
1727 'GL_RG16UI',
1728 'GL_RG16I',
1729 'GL_RG32UI',
1730 'GL_RG32I',
1731 'GL_RGB8',
1732 'GL_SRGB8',
1733 'GL_RGB565',
1734 'GL_RGB8_SNORM',
1735 'GL_R11F_G11F_B10F',
1736 'GL_RGB9_E5',
1737 'GL_RGB16F',
1738 'GL_RGB32F',
1739 'GL_RGB8UI',
1740 'GL_RGB8I',
1741 'GL_RGB16UI',
1742 'GL_RGB16I',
1743 'GL_RGB32UI',
1744 'GL_RGB32I',
1745 'GL_RGBA8',
1746 'GL_SRGB8_ALPHA8',
1747 'GL_RGBA8_SNORM',
1748 'GL_RGB5_A1',
1749 'GL_RGBA4',
1750 'GL_RGB10_A2',
1751 'GL_RGBA16F',
1752 'GL_RGBA32F',
1753 'GL_RGBA8UI',
1754 'GL_RGBA8I',
1755 'GL_RGB10_A2UI',
1756 'GL_RGBA16UI',
1757 'GL_RGBA16I',
1758 'GL_RGBA32UI',
1759 'GL_RGBA32I',
1760 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1761 # We will reject them dynamically in GPU command buffer.
1762 'GL_DEPTH_COMPONENT16',
1763 'GL_DEPTH_COMPONENT24',
1764 'GL_DEPTH_COMPONENT32F',
1765 'GL_DEPTH24_STENCIL8',
1766 'GL_DEPTH32F_STENCIL8',
1768 'invalid': [
1769 'GL_BGRA',
1770 'GL_BGR',
1773 'TextureInternalFormatStorage': {
1774 'type': 'GLenum',
1775 'valid': [
1776 'GL_RGB565',
1777 'GL_RGBA4',
1778 'GL_RGB5_A1',
1779 'GL_ALPHA8_EXT',
1780 'GL_LUMINANCE8_EXT',
1781 'GL_LUMINANCE8_ALPHA8_EXT',
1782 'GL_RGB8_OES',
1783 'GL_RGBA8_OES',
1785 'valid_es3': [
1786 'GL_R8',
1787 'GL_R8_SNORM',
1788 'GL_R16F',
1789 'GL_R32F',
1790 'GL_R8UI',
1791 'GL_R8I',
1792 'GL_R16UI',
1793 'GL_R16I',
1794 'GL_R32UI',
1795 'GL_R32I',
1796 'GL_RG8',
1797 'GL_RG8_SNORM',
1798 'GL_RG16F',
1799 'GL_RG32F',
1800 'GL_RG8UI',
1801 'GL_RG8I',
1802 'GL_RG16UI',
1803 'GL_RG16I',
1804 'GL_RG32UI',
1805 'GL_RG32I',
1806 'GL_RGB8',
1807 'GL_SRGB8',
1808 'GL_RGB8_SNORM',
1809 'GL_R11F_G11F_B10F',
1810 'GL_RGB9_E5',
1811 'GL_RGB16F',
1812 'GL_RGB32F',
1813 'GL_RGB8UI',
1814 'GL_RGB8I',
1815 'GL_RGB16UI',
1816 'GL_RGB16I',
1817 'GL_RGB32UI',
1818 'GL_RGB32I',
1819 'GL_RGBA8',
1820 'GL_SRGB8_ALPHA8',
1821 'GL_RGBA8_SNORM',
1822 'GL_RGB10_A2',
1823 'GL_RGBA16F',
1824 'GL_RGBA32F',
1825 'GL_RGBA8UI',
1826 'GL_RGBA8I',
1827 'GL_RGB10_A2UI',
1828 'GL_RGBA16UI',
1829 'GL_RGBA16I',
1830 'GL_RGBA32UI',
1831 'GL_RGBA32I',
1832 'GL_DEPTH_COMPONENT16',
1833 'GL_DEPTH_COMPONENT24',
1834 'GL_DEPTH_COMPONENT32F',
1835 'GL_DEPTH24_STENCIL8',
1836 'GL_DEPTH32F_STENCIL8',
1837 'GL_COMPRESSED_R11_EAC',
1838 'GL_COMPRESSED_SIGNED_R11_EAC',
1839 'GL_COMPRESSED_RG11_EAC',
1840 'GL_COMPRESSED_SIGNED_RG11_EAC',
1841 'GL_COMPRESSED_RGB8_ETC2',
1842 'GL_COMPRESSED_SRGB8_ETC2',
1843 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1844 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1845 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1846 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1848 'deprecated_es3': [
1849 'GL_ALPHA8_EXT',
1850 'GL_LUMINANCE8_EXT',
1851 'GL_LUMINANCE8_ALPHA8_EXT',
1852 'GL_ALPHA16F_EXT',
1853 'GL_LUMINANCE16F_EXT',
1854 'GL_LUMINANCE_ALPHA16F_EXT',
1855 'GL_ALPHA32F_EXT',
1856 'GL_LUMINANCE32F_EXT',
1857 'GL_LUMINANCE_ALPHA32F_EXT',
1860 'ImageInternalFormat': {
1861 'type': 'GLenum',
1862 'valid': [
1863 'GL_RGB',
1864 'GL_RGB_YUV_420_CHROMIUM',
1865 'GL_RGB_YCBCR_422_CHROMIUM',
1866 'GL_RGBA',
1869 'ImageUsage': {
1870 'type': 'GLenum',
1871 'valid': [
1872 'GL_MAP_CHROMIUM',
1873 'GL_SCANOUT_CHROMIUM'
1876 'ValueBufferTarget': {
1877 'type': 'GLenum',
1878 'valid': [
1879 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1882 'SubscriptionTarget': {
1883 'type': 'GLenum',
1884 'valid': [
1885 'GL_MOUSE_POSITION_CHROMIUM',
1888 'UniformParameter': {
1889 'type': 'GLenum',
1890 'valid': [
1891 'GL_UNIFORM_SIZE',
1892 'GL_UNIFORM_TYPE',
1893 'GL_UNIFORM_NAME_LENGTH',
1894 'GL_UNIFORM_BLOCK_INDEX',
1895 'GL_UNIFORM_OFFSET',
1896 'GL_UNIFORM_ARRAY_STRIDE',
1897 'GL_UNIFORM_MATRIX_STRIDE',
1898 'GL_UNIFORM_IS_ROW_MAJOR',
1900 'invalid': [
1901 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1904 'UniformBlockParameter': {
1905 'type': 'GLenum',
1906 'valid': [
1907 'GL_UNIFORM_BLOCK_BINDING',
1908 'GL_UNIFORM_BLOCK_DATA_SIZE',
1909 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1910 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1911 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1912 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1913 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1915 'invalid': [
1916 'GL_NEAREST',
1919 'VertexAttribType': {
1920 'type': 'GLenum',
1921 'valid': [
1922 'GL_BYTE',
1923 'GL_UNSIGNED_BYTE',
1924 'GL_SHORT',
1925 'GL_UNSIGNED_SHORT',
1926 # 'GL_FIXED', // This is not available on Desktop GL.
1927 'GL_FLOAT',
1929 'valid_es3': [
1930 'GL_INT',
1931 'GL_UNSIGNED_INT',
1932 'GL_HALF_FLOAT',
1933 'GL_INT_2_10_10_10_REV',
1934 'GL_UNSIGNED_INT_2_10_10_10_REV',
1936 'invalid': [
1937 'GL_DOUBLE',
1940 'VertexAttribIType': {
1941 'type': 'GLenum',
1942 'valid': [
1943 'GL_BYTE',
1944 'GL_UNSIGNED_BYTE',
1945 'GL_SHORT',
1946 'GL_UNSIGNED_SHORT',
1947 'GL_INT',
1948 'GL_UNSIGNED_INT',
1950 'invalid': [
1951 'GL_FLOAT',
1952 'GL_DOUBLE',
1955 'TextureBorder': {
1956 'type': 'GLint',
1957 'is_complete': True,
1958 'valid': [
1959 '0',
1961 'invalid': [
1962 '1',
1965 'VertexAttribSize': {
1966 'type': 'GLint',
1967 'valid': [
1968 '1',
1969 '2',
1970 '3',
1971 '4',
1973 'invalid': [
1974 '0',
1975 '5',
1978 'ZeroOnly': {
1979 'type': 'GLint',
1980 'is_complete': True,
1981 'valid': [
1982 '0',
1984 'invalid': [
1985 '1',
1988 'FalseOnly': {
1989 'type': 'GLboolean',
1990 'is_complete': True,
1991 'valid': [
1992 'false',
1994 'invalid': [
1995 'true',
1998 'ResetStatus': {
1999 'type': 'GLenum',
2000 'valid': [
2001 'GL_GUILTY_CONTEXT_RESET_ARB',
2002 'GL_INNOCENT_CONTEXT_RESET_ARB',
2003 'GL_UNKNOWN_CONTEXT_RESET_ARB',
2006 'SyncCondition': {
2007 'type': 'GLenum',
2008 'is_complete': True,
2009 'valid': [
2010 'GL_SYNC_GPU_COMMANDS_COMPLETE',
2012 'invalid': [
2013 '0',
2016 'SyncFlags': {
2017 'type': 'GLbitfield',
2018 'is_complete': True,
2019 'valid': [
2020 '0',
2022 'invalid': [
2023 '1',
2026 'SyncFlushFlags': {
2027 'type': 'GLbitfield',
2028 'valid': [
2029 'GL_SYNC_FLUSH_COMMANDS_BIT',
2030 '0',
2032 'invalid': [
2033 '0xFFFFFFFF',
2036 'SyncParameter': {
2037 'type': 'GLenum',
2038 'valid': [
2039 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
2040 'GL_OBJECT_TYPE',
2041 'GL_SYNC_CONDITION',
2042 'GL_SYNC_FLAGS',
2044 'invalid': [
2045 'GL_SYNC_FENCE',
2050 # This table specifies the different pepper interfaces that are supported for
2051 # GL commands. 'dev' is true if it's a dev interface.
2052 _PEPPER_INTERFACES = [
2053 {'name': '', 'dev': False},
2054 {'name': 'InstancedArrays', 'dev': False},
2055 {'name': 'FramebufferBlit', 'dev': False},
2056 {'name': 'FramebufferMultisample', 'dev': False},
2057 {'name': 'ChromiumEnableFeature', 'dev': False},
2058 {'name': 'ChromiumMapSub', 'dev': False},
2059 {'name': 'Query', 'dev': False},
2060 {'name': 'VertexArrayObject', 'dev': False},
2061 {'name': 'DrawBuffers', 'dev': True},
2064 # A function info object specifies the type and other special data for the
2065 # command that will be generated. A base function info object is generated by
2066 # parsing the "cmd_buffer_functions.txt", one for each function in the
2067 # file. These function info objects can be augmented and their values can be
2068 # overridden by adding an object to the table below.
2070 # Must match function names specified in "cmd_buffer_functions.txt".
2072 # cmd_comment: A comment added to the cmd format.
2073 # type: defines which handler will be used to generate code.
2074 # decoder_func: defines which function to call in the decoder to execute the
2075 # corresponding GL command. If not specified the GL command will
2076 # be called directly.
2077 # gl_test_func: GL function that is expected to be called when testing.
2078 # cmd_args: The arguments to use for the command. This overrides generating
2079 # them based on the GL function arguments.
2080 # gen_cmd: Whether or not this function geneates a command. Default = True.
2081 # data_transfer_methods: Array of methods that are used for transfering the
2082 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
2083 # The default is 'immediate' if the command has one pointer
2084 # argument, otherwise 'shm'. One command is generated for each
2085 # transfer method. Affects only commands which are not of type
2086 # 'HandWritten', 'GETn' or 'GLcharN'.
2087 # Note: the command arguments that affect this are the final args,
2088 # taking cmd_args override into consideration.
2089 # impl_func: Whether or not to generate the GLES2Implementation part of this
2090 # command.
2091 # impl_decl: Whether or not to generate the GLES2Implementation declaration
2092 # for this command.
2093 # needs_size: If True a data_size field is added to the command.
2094 # count: The number of units per element. For PUTn or PUT types.
2095 # use_count_func: If True the actual data count needs to be computed; the count
2096 # argument specifies the maximum count.
2097 # unit_test: If False no service side unit test will be generated.
2098 # client_test: If False no client side unit test will be generated.
2099 # expectation: If False the unit test will have no expected calls.
2100 # gen_func: Name of function that generates GL resource for corresponding
2101 # bind function.
2102 # states: array of states that get set by this function corresponding to
2103 # the given arguments
2104 # state_flag: name of flag that is set to true when function is called.
2105 # no_gl: no GL function is called.
2106 # valid_args: A dictionary of argument indices to args to use in unit tests
2107 # when they can not be automatically determined.
2108 # pepper_interface: The pepper interface that is used for this extension
2109 # pepper_name: The name of the function as exposed to pepper.
2110 # pepper_args: A string representing the argument list (what would appear in
2111 # C/C++ between the parentheses for the function declaration)
2112 # that the Pepper API expects for this function. Use this only if
2113 # the stable Pepper API differs from the GLES2 argument list.
2114 # invalid_test: False if no invalid test needed.
2115 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
2116 # first_element_only: For PUT types, True if only the first element of an
2117 # array is used and we end up calling the single value
2118 # corresponding function. eg. TexParameteriv -> TexParameteri
2119 # extension: Function is an extension to GL and should not be exposed to
2120 # pepper unless pepper_interface is defined.
2121 # extension_flag: Function is an extension and should be enabled only when
2122 # the corresponding feature info flag is enabled. Implies
2123 # 'extension': True.
2124 # not_shared: For GENn types, True if objects can't be shared between contexts
2125 # unsafe: True = no validation is implemented on the service side and the
2126 # command is only available with --enable-unsafe-es3-apis.
2127 # id_mapping: A list of resource type names whose client side IDs need to be
2128 # mapped to service side IDs. This is only used for unsafe APIs.
2130 _FUNCTION_INFO = {
2131 'ActiveTexture': {
2132 'decoder_func': 'DoActiveTexture',
2133 'unit_test': False,
2134 'impl_func': False,
2135 'client_test': False,
2137 'AttachShader': {'decoder_func': 'DoAttachShader'},
2138 'BindAttribLocation': {
2139 'type': 'GLchar',
2140 'data_transfer_methods': ['bucket'],
2141 'needs_size': True,
2143 'BindBuffer': {
2144 'type': 'Bind',
2145 'decoder_func': 'DoBindBuffer',
2146 'gen_func': 'GenBuffersARB',
2148 'BindBufferBase': {
2149 'type': 'Bind',
2150 'decoder_func': 'DoBindBufferBase',
2151 'gen_func': 'GenBuffersARB',
2152 'unsafe': True,
2154 'BindBufferRange': {
2155 'type': 'Bind',
2156 'decoder_func': 'DoBindBufferRange',
2157 'gen_func': 'GenBuffersARB',
2158 'valid_args': {
2159 '3': '4',
2160 '4': '4'
2162 'unsafe': True,
2164 'BindFramebuffer': {
2165 'type': 'Bind',
2166 'decoder_func': 'DoBindFramebuffer',
2167 'gl_test_func': 'glBindFramebufferEXT',
2168 'gen_func': 'GenFramebuffersEXT',
2169 'trace_level': 1,
2171 'BindRenderbuffer': {
2172 'type': 'Bind',
2173 'decoder_func': 'DoBindRenderbuffer',
2174 'gl_test_func': 'glBindRenderbufferEXT',
2175 'gen_func': 'GenRenderbuffersEXT',
2177 'BindSampler': {
2178 'type': 'Bind',
2179 'id_mapping': [ 'Sampler' ],
2180 'unsafe': True,
2182 'BindTexture': {
2183 'type': 'Bind',
2184 'decoder_func': 'DoBindTexture',
2185 'gen_func': 'GenTextures',
2186 # TODO(gman): remove this once client side caching works.
2187 'client_test': False,
2188 'trace_level': 2,
2190 'BindTransformFeedback': {
2191 'type': 'Bind',
2192 'id_mapping': [ 'TransformFeedback' ],
2193 'unsafe': True,
2195 'BlitFramebufferCHROMIUM': {
2196 'decoder_func': 'DoBlitFramebufferCHROMIUM',
2197 'unit_test': False,
2198 'extension_flag': 'chromium_framebuffer_multisample',
2199 'pepper_interface': 'FramebufferBlit',
2200 'pepper_name': 'BlitFramebufferEXT',
2201 'defer_reads': True,
2202 'defer_draws': True,
2203 'trace_level': 1,
2205 'BufferData': {
2206 'type': 'Manual',
2207 'data_transfer_methods': ['shm'],
2208 'client_test': False,
2209 'trace_level': 2,
2211 'BufferSubData': {
2212 'type': 'Data',
2213 'client_test': False,
2214 'decoder_func': 'DoBufferSubData',
2215 'data_transfer_methods': ['shm'],
2216 'trace_level': 2,
2218 'CheckFramebufferStatus': {
2219 'type': 'Is',
2220 'decoder_func': 'DoCheckFramebufferStatus',
2221 'gl_test_func': 'glCheckFramebufferStatusEXT',
2222 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
2223 'result': ['GLenum'],
2225 'Clear': {
2226 'decoder_func': 'DoClear',
2227 'defer_draws': True,
2228 'trace_level': 2,
2230 'ClearBufferiv': {
2231 'type': 'PUT',
2232 'use_count_func': True,
2233 'count': 4,
2234 'decoder_func': 'DoClearBufferiv',
2235 'unit_test': False,
2236 'unsafe': True,
2237 'trace_level': 2,
2239 'ClearBufferuiv': {
2240 'type': 'PUT',
2241 'count': 4,
2242 'decoder_func': 'DoClearBufferuiv',
2243 'unit_test': False,
2244 'unsafe': True,
2245 'trace_level': 2,
2247 'ClearBufferfv': {
2248 'type': 'PUT',
2249 'use_count_func': True,
2250 'count': 4,
2251 'decoder_func': 'DoClearBufferfv',
2252 'unit_test': False,
2253 'unsafe': True,
2254 'trace_level': 2,
2256 'ClearBufferfi': {
2257 'unsafe': True,
2258 'decoder_func': 'DoClearBufferfi',
2259 'unit_test': False,
2260 'trace_level': 2,
2262 'ClearColor': {
2263 'type': 'StateSet',
2264 'state': 'ClearColor',
2266 'ClearDepthf': {
2267 'type': 'StateSet',
2268 'state': 'ClearDepthf',
2269 'decoder_func': 'glClearDepth',
2270 'gl_test_func': 'glClearDepth',
2271 'valid_args': {
2272 '0': '0.5f'
2275 'ClientWaitSync': {
2276 'type': 'Custom',
2277 'data_transfer_methods': ['shm'],
2278 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
2279 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
2280 'unsafe': True,
2281 'result': ['GLenum'],
2282 'trace_level': 2,
2284 'ColorMask': {
2285 'type': 'StateSet',
2286 'state': 'ColorMask',
2287 'no_gl': True,
2288 'expectation': False,
2290 'ConsumeTextureCHROMIUM': {
2291 'decoder_func': 'DoConsumeTextureCHROMIUM',
2292 'impl_func': False,
2293 'type': 'PUT',
2294 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2295 'unit_test': False,
2296 'client_test': False,
2297 'extension': "CHROMIUM_texture_mailbox",
2298 'chromium': True,
2299 'trace_level': 2,
2301 'CopyBufferSubData': {
2302 'unsafe': True,
2304 'CreateAndConsumeTextureCHROMIUM': {
2305 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
2306 'impl_func': False,
2307 'type': 'HandWritten',
2308 'data_transfer_methods': ['immediate'],
2309 'unit_test': False,
2310 'client_test': False,
2311 'extension': "CHROMIUM_texture_mailbox",
2312 'chromium': True,
2313 'trace_level': 2,
2315 'GenValuebuffersCHROMIUM': {
2316 'type': 'GENn',
2317 'gl_test_func': 'glGenValuebuffersCHROMIUM',
2318 'resource_type': 'Valuebuffer',
2319 'resource_types': 'Valuebuffers',
2320 'unit_test': False,
2321 'extension': True,
2322 'chromium': True,
2324 'DeleteValuebuffersCHROMIUM': {
2325 'type': 'DELn',
2326 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
2327 'resource_type': 'Valuebuffer',
2328 'resource_types': 'Valuebuffers',
2329 'unit_test': False,
2330 'extension': True,
2331 'chromium': True,
2333 'IsValuebufferCHROMIUM': {
2334 'type': 'Is',
2335 'decoder_func': 'DoIsValuebufferCHROMIUM',
2336 'expectation': False,
2337 'extension': True,
2338 'chromium': True,
2340 'BindValuebufferCHROMIUM': {
2341 'type': 'Bind',
2342 'decoder_func': 'DoBindValueBufferCHROMIUM',
2343 'gen_func': 'GenValueBuffersCHROMIUM',
2344 'unit_test': False,
2345 'extension': True,
2346 'chromium': True,
2348 'SubscribeValueCHROMIUM': {
2349 'decoder_func': 'DoSubscribeValueCHROMIUM',
2350 'unit_test': False,
2351 'extension': True,
2352 'chromium': True,
2354 'PopulateSubscribedValuesCHROMIUM': {
2355 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
2356 'unit_test': False,
2357 'extension': True,
2358 'chromium': True,
2360 'UniformValuebufferCHROMIUM': {
2361 'decoder_func': 'DoUniformValueBufferCHROMIUM',
2362 'unit_test': False,
2363 'extension': True,
2364 'chromium': True,
2366 'ClearStencil': {
2367 'type': 'StateSet',
2368 'state': 'ClearStencil',
2370 'EnableFeatureCHROMIUM': {
2371 'type': 'Custom',
2372 'data_transfer_methods': ['shm'],
2373 'decoder_func': 'DoEnableFeatureCHROMIUM',
2374 'expectation': False,
2375 'cmd_args': 'GLuint bucket_id, GLint* result',
2376 'result': ['GLint'],
2377 'extension': True,
2378 'chromium': True,
2379 'pepper_interface': 'ChromiumEnableFeature',
2381 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
2382 'CompressedTexImage2D': {
2383 'type': 'Manual',
2384 'data_transfer_methods': ['bucket', 'shm'],
2385 'trace_level': 1,
2387 'CompressedTexSubImage2D': {
2388 'type': 'Data',
2389 'data_transfer_methods': ['bucket', 'shm'],
2390 'decoder_func': 'DoCompressedTexSubImage2D',
2391 'trace_level': 1,
2393 'CopyTexImage2D': {
2394 'decoder_func': 'DoCopyTexImage2D',
2395 'unit_test': False,
2396 'defer_reads': True,
2397 'trace_level': 1,
2399 'CopyTexSubImage2D': {
2400 'decoder_func': 'DoCopyTexSubImage2D',
2401 'defer_reads': True,
2402 'trace_level': 1,
2404 'CompressedTexImage3D': {
2405 'type': 'Manual',
2406 'data_transfer_methods': ['bucket', 'shm'],
2407 'unsafe': True,
2408 'trace_level': 1,
2410 'CompressedTexSubImage3D': {
2411 'type': 'Data',
2412 'data_transfer_methods': ['bucket', 'shm'],
2413 'decoder_func': 'DoCompressedTexSubImage3D',
2414 'unsafe': True,
2415 'trace_level': 1,
2417 'CopyTexSubImage3D': {
2418 'defer_reads': True,
2419 'unsafe': True,
2420 'trace_level': 1,
2422 'CreateImageCHROMIUM': {
2423 'type': 'Manual',
2424 'cmd_args':
2425 'ClientBuffer buffer, GLsizei width, GLsizei height, '
2426 'GLenum internalformat',
2427 'result': ['GLuint'],
2428 'client_test': False,
2429 'gen_cmd': False,
2430 'expectation': False,
2431 'extension': "CHROMIUM_image",
2432 'chromium': True,
2433 'trace_level': 1,
2435 'DestroyImageCHROMIUM': {
2436 'type': 'Manual',
2437 'client_test': False,
2438 'gen_cmd': False,
2439 'extension': "CHROMIUM_image",
2440 'chromium': True,
2441 'trace_level': 1,
2443 'CreateGpuMemoryBufferImageCHROMIUM': {
2444 'type': 'Manual',
2445 'cmd_args':
2446 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2447 'result': ['GLuint'],
2448 'client_test': False,
2449 'gen_cmd': False,
2450 'expectation': False,
2451 'extension': "CHROMIUM_image",
2452 'chromium': True,
2453 'trace_level': 1,
2455 'CreateProgram': {
2456 'type': 'Create',
2457 'client_test': False,
2459 'CreateShader': {
2460 'type': 'Create',
2461 'client_test': False,
2463 'BlendColor': {
2464 'type': 'StateSet',
2465 'state': 'BlendColor',
2467 'BlendEquation': {
2468 'type': 'StateSetRGBAlpha',
2469 'state': 'BlendEquation',
2470 'valid_args': {
2471 '0': 'GL_FUNC_SUBTRACT'
2474 'BlendEquationSeparate': {
2475 'type': 'StateSet',
2476 'state': 'BlendEquation',
2477 'valid_args': {
2478 '0': 'GL_FUNC_SUBTRACT'
2481 'BlendFunc': {
2482 'type': 'StateSetRGBAlpha',
2483 'state': 'BlendFunc',
2485 'BlendFuncSeparate': {
2486 'type': 'StateSet',
2487 'state': 'BlendFunc',
2489 'BlendBarrierKHR': {
2490 'gl_test_func': 'glBlendBarrierKHR',
2491 'extension': True,
2492 'extension_flag': 'blend_equation_advanced',
2493 'client_test': False,
2495 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2496 'StencilFunc': {
2497 'type': 'StateSetFrontBack',
2498 'state': 'StencilFunc',
2500 'StencilFuncSeparate': {
2501 'type': 'StateSetFrontBackSeparate',
2502 'state': 'StencilFunc',
2504 'StencilOp': {
2505 'type': 'StateSetFrontBack',
2506 'state': 'StencilOp',
2507 'valid_args': {
2508 '1': 'GL_INCR'
2511 'StencilOpSeparate': {
2512 'type': 'StateSetFrontBackSeparate',
2513 'state': 'StencilOp',
2514 'valid_args': {
2515 '1': 'GL_INCR'
2518 'Hint': {
2519 'type': 'StateSetNamedParameter',
2520 'state': 'Hint',
2522 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2523 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2524 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2525 'LineWidth': {
2526 'type': 'StateSet',
2527 'state': 'LineWidth',
2528 'valid_args': {
2529 '0': '0.5f'
2532 'PolygonOffset': {
2533 'type': 'StateSet',
2534 'state': 'PolygonOffset',
2536 'DeleteBuffers': {
2537 'type': 'DELn',
2538 'gl_test_func': 'glDeleteBuffersARB',
2539 'resource_type': 'Buffer',
2540 'resource_types': 'Buffers',
2542 'DeleteFramebuffers': {
2543 'type': 'DELn',
2544 'gl_test_func': 'glDeleteFramebuffersEXT',
2545 'resource_type': 'Framebuffer',
2546 'resource_types': 'Framebuffers',
2547 'trace_level': 2,
2549 'DeleteProgram': { 'type': 'Delete' },
2550 'DeleteRenderbuffers': {
2551 'type': 'DELn',
2552 'gl_test_func': 'glDeleteRenderbuffersEXT',
2553 'resource_type': 'Renderbuffer',
2554 'resource_types': 'Renderbuffers',
2555 'trace_level': 2,
2557 'DeleteSamplers': {
2558 'type': 'DELn',
2559 'resource_type': 'Sampler',
2560 'resource_types': 'Samplers',
2561 'unsafe': True,
2563 'DeleteShader': { 'type': 'Delete' },
2564 'DeleteSync': {
2565 'type': 'Delete',
2566 'cmd_args': 'GLuint sync',
2567 'resource_type': 'Sync',
2568 'unsafe': True,
2570 'DeleteTextures': {
2571 'type': 'DELn',
2572 'resource_type': 'Texture',
2573 'resource_types': 'Textures',
2575 'DeleteTransformFeedbacks': {
2576 'type': 'DELn',
2577 'resource_type': 'TransformFeedback',
2578 'resource_types': 'TransformFeedbacks',
2579 'unsafe': True,
2581 'DepthRangef': {
2582 'decoder_func': 'DoDepthRangef',
2583 'gl_test_func': 'glDepthRange',
2585 'DepthMask': {
2586 'type': 'StateSet',
2587 'state': 'DepthMask',
2588 'no_gl': True,
2589 'expectation': False,
2591 'DetachShader': {'decoder_func': 'DoDetachShader'},
2592 'Disable': {
2593 'decoder_func': 'DoDisable',
2594 'impl_func': False,
2595 'client_test': False,
2597 'DisableVertexAttribArray': {
2598 'decoder_func': 'DoDisableVertexAttribArray',
2599 'impl_decl': False,
2601 'DrawArrays': {
2602 'type': 'Manual',
2603 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2604 'defer_draws': True,
2605 'trace_level': 2,
2607 'DrawElements': {
2608 'type': 'Manual',
2609 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2610 'GLenumIndexType type, GLuint index_offset',
2611 'client_test': False,
2612 'defer_draws': True,
2613 'trace_level': 2,
2615 'DrawRangeElements': {
2616 'type': 'Manual',
2617 'gen_cmd': 'False',
2618 'unsafe': True,
2620 'Enable': {
2621 'decoder_func': 'DoEnable',
2622 'impl_func': False,
2623 'client_test': False,
2625 'EnableVertexAttribArray': {
2626 'decoder_func': 'DoEnableVertexAttribArray',
2627 'impl_decl': False,
2629 'FenceSync': {
2630 'type': 'Create',
2631 'client_test': False,
2632 'unsafe': True,
2633 'trace_level': 1,
2635 'Finish': {
2636 'impl_func': False,
2637 'client_test': False,
2638 'decoder_func': 'DoFinish',
2639 'defer_reads': True,
2640 'trace_level': 1,
2642 'Flush': {
2643 'impl_func': False,
2644 'decoder_func': 'DoFlush',
2645 'trace_level': 1,
2647 'FramebufferRenderbuffer': {
2648 'decoder_func': 'DoFramebufferRenderbuffer',
2649 'gl_test_func': 'glFramebufferRenderbufferEXT',
2650 'trace_level': 1,
2652 'FramebufferTexture2D': {
2653 'decoder_func': 'DoFramebufferTexture2D',
2654 'gl_test_func': 'glFramebufferTexture2DEXT',
2655 'trace_level': 1,
2657 'FramebufferTexture2DMultisampleEXT': {
2658 'decoder_func': 'DoFramebufferTexture2DMultisample',
2659 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2660 'expectation': False,
2661 'unit_test': False,
2662 'extension_flag': 'multisampled_render_to_texture',
2663 'trace_level': 1,
2665 'FramebufferTextureLayer': {
2666 'decoder_func': 'DoFramebufferTextureLayer',
2667 'unsafe': True,
2668 'trace_level': 1,
2670 'GenerateMipmap': {
2671 'decoder_func': 'DoGenerateMipmap',
2672 'gl_test_func': 'glGenerateMipmapEXT',
2673 'trace_level': 1,
2675 'GenBuffers': {
2676 'type': 'GENn',
2677 'gl_test_func': 'glGenBuffersARB',
2678 'resource_type': 'Buffer',
2679 'resource_types': 'Buffers',
2681 'GenMailboxCHROMIUM': {
2682 'type': 'HandWritten',
2683 'impl_func': False,
2684 'extension': "CHROMIUM_texture_mailbox",
2685 'chromium': True,
2687 'GenFramebuffers': {
2688 'type': 'GENn',
2689 'gl_test_func': 'glGenFramebuffersEXT',
2690 'resource_type': 'Framebuffer',
2691 'resource_types': 'Framebuffers',
2693 'GenRenderbuffers': {
2694 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2695 'resource_type': 'Renderbuffer',
2696 'resource_types': 'Renderbuffers',
2698 'GenSamplers': {
2699 'type': 'GENn',
2700 'gl_test_func': 'glGenSamplers',
2701 'resource_type': 'Sampler',
2702 'resource_types': 'Samplers',
2703 'unsafe': True,
2705 'GenTextures': {
2706 'type': 'GENn',
2707 'gl_test_func': 'glGenTextures',
2708 'resource_type': 'Texture',
2709 'resource_types': 'Textures',
2711 'GenTransformFeedbacks': {
2712 'type': 'GENn',
2713 'gl_test_func': 'glGenTransformFeedbacks',
2714 'resource_type': 'TransformFeedback',
2715 'resource_types': 'TransformFeedbacks',
2716 'unsafe': True,
2718 'GetActiveAttrib': {
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 'GetActiveUniform': {
2731 'type': 'Custom',
2732 'data_transfer_methods': ['shm'],
2733 'cmd_args':
2734 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2735 'void* result',
2736 'result': [
2737 'int32_t success',
2738 'int32_t size',
2739 'uint32_t type',
2742 'GetActiveUniformBlockiv': {
2743 'type': 'Custom',
2744 'data_transfer_methods': ['shm'],
2745 'result': ['SizedResult<GLint>'],
2746 'unsafe': True,
2748 'GetActiveUniformBlockName': {
2749 'type': 'Custom',
2750 'data_transfer_methods': ['shm'],
2751 'cmd_args':
2752 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2753 'void* result',
2754 'result': ['int32_t'],
2755 'unsafe': True,
2757 'GetActiveUniformsiv': {
2758 'type': 'Custom',
2759 'data_transfer_methods': ['shm'],
2760 'cmd_args':
2761 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2762 'GLint* params',
2763 'result': ['SizedResult<GLint>'],
2764 'unsafe': True,
2766 'GetAttachedShaders': {
2767 'type': 'Custom',
2768 'data_transfer_methods': ['shm'],
2769 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2770 'result': ['SizedResult<GLuint>'],
2772 'GetAttribLocation': {
2773 'type': 'Custom',
2774 'data_transfer_methods': ['shm'],
2775 'cmd_args':
2776 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2777 'result': ['GLint'],
2778 'error_return': -1,
2780 'GetFragDataLocation': {
2781 'type': 'Custom',
2782 'data_transfer_methods': ['shm'],
2783 'cmd_args':
2784 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2785 'result': ['GLint'],
2786 'error_return': -1,
2787 'unsafe': True,
2789 'GetBooleanv': {
2790 'type': 'GETn',
2791 'result': ['SizedResult<GLboolean>'],
2792 'decoder_func': 'DoGetBooleanv',
2793 'gl_test_func': 'glGetBooleanv',
2795 'GetBufferParameteri64v': {
2796 'type': 'GETn',
2797 'result': ['SizedResult<GLint64>'],
2798 'decoder_func': 'DoGetBufferParameteri64v',
2799 'expectation': False,
2800 'shadowed': True,
2801 'unsafe': True,
2803 'GetBufferParameteriv': {
2804 'type': 'GETn',
2805 'result': ['SizedResult<GLint>'],
2806 'decoder_func': 'DoGetBufferParameteriv',
2807 'expectation': False,
2808 'shadowed': True,
2810 'GetError': {
2811 'type': 'Is',
2812 'decoder_func': 'GetErrorState()->GetGLError',
2813 'impl_func': False,
2814 'result': ['GLenum'],
2815 'client_test': False,
2817 'GetFloatv': {
2818 'type': 'GETn',
2819 'result': ['SizedResult<GLfloat>'],
2820 'decoder_func': 'DoGetFloatv',
2821 'gl_test_func': 'glGetFloatv',
2823 'GetFramebufferAttachmentParameteriv': {
2824 'type': 'GETn',
2825 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2826 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2827 'result': ['SizedResult<GLint>'],
2829 'GetGraphicsResetStatusKHR': {
2830 'extension': True,
2831 'client_test': False,
2832 'gen_cmd': False,
2833 'trace_level': 1,
2835 'GetInteger64v': {
2836 'type': 'GETn',
2837 'result': ['SizedResult<GLint64>'],
2838 'client_test': False,
2839 'decoder_func': 'DoGetInteger64v',
2840 'unsafe': True
2842 'GetIntegerv': {
2843 'type': 'GETn',
2844 'result': ['SizedResult<GLint>'],
2845 'decoder_func': 'DoGetIntegerv',
2846 'client_test': False,
2848 'GetInteger64i_v': {
2849 'type': 'GETn',
2850 'result': ['SizedResult<GLint64>'],
2851 'client_test': False,
2852 'unsafe': True
2854 'GetIntegeri_v': {
2855 'type': 'GETn',
2856 'result': ['SizedResult<GLint>'],
2857 'client_test': False,
2858 'unsafe': True
2860 'GetInternalformativ': {
2861 'type': 'Custom',
2862 'data_transfer_methods': ['shm'],
2863 'result': ['SizedResult<GLint>'],
2864 'cmd_args':
2865 'GLenumRenderBufferTarget target, GLenumRenderBufferFormat format, '
2866 'GLenumInternalFormatParameter pname, GLint* params',
2867 'unsafe': True,
2869 'GetMaxValueInBufferCHROMIUM': {
2870 'type': 'Is',
2871 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2872 'result': ['GLuint'],
2873 'unit_test': False,
2874 'client_test': False,
2875 'extension': True,
2876 'chromium': True,
2877 'impl_func': False,
2879 'GetProgramiv': {
2880 'type': 'GETn',
2881 'decoder_func': 'DoGetProgramiv',
2882 'result': ['SizedResult<GLint>'],
2883 'expectation': False,
2885 'GetProgramInfoCHROMIUM': {
2886 'type': 'Custom',
2887 'expectation': False,
2888 'impl_func': False,
2889 'extension': True,
2890 'chromium': True,
2891 'client_test': False,
2892 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2893 'result': [
2894 'uint32_t link_status',
2895 'uint32_t num_attribs',
2896 'uint32_t num_uniforms',
2899 'GetProgramInfoLog': {
2900 'type': 'STRn',
2901 'expectation': False,
2903 'GetRenderbufferParameteriv': {
2904 'type': 'GETn',
2905 'decoder_func': 'DoGetRenderbufferParameteriv',
2906 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2907 'result': ['SizedResult<GLint>'],
2909 'GetSamplerParameterfv': {
2910 'type': 'GETn',
2911 'result': ['SizedResult<GLfloat>'],
2912 'id_mapping': [ 'Sampler' ],
2913 'unsafe': True,
2915 'GetSamplerParameteriv': {
2916 'type': 'GETn',
2917 'result': ['SizedResult<GLint>'],
2918 'id_mapping': [ 'Sampler' ],
2919 'unsafe': True,
2921 'GetShaderiv': {
2922 'type': 'GETn',
2923 'decoder_func': 'DoGetShaderiv',
2924 'result': ['SizedResult<GLint>'],
2926 'GetShaderInfoLog': {
2927 'type': 'STRn',
2928 'get_len_func': 'glGetShaderiv',
2929 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2930 'unit_test': False,
2932 'GetShaderPrecisionFormat': {
2933 'type': 'Custom',
2934 'data_transfer_methods': ['shm'],
2935 'cmd_args':
2936 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2937 'void* result',
2938 'result': [
2939 'int32_t success',
2940 'int32_t min_range',
2941 'int32_t max_range',
2942 'int32_t precision',
2945 'GetShaderSource': {
2946 'type': 'STRn',
2947 'get_len_func': 'DoGetShaderiv',
2948 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2949 'unit_test': False,
2950 'client_test': False,
2952 'GetString': {
2953 'type': 'Custom',
2954 'client_test': False,
2955 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2957 'GetSynciv': {
2958 'type': 'GETn',
2959 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2960 'result': ['SizedResult<GLint>'],
2961 'id_mapping': ['Sync'],
2962 'unsafe': True,
2964 'GetTexParameterfv': {
2965 'type': 'GETn',
2966 'decoder_func': 'DoGetTexParameterfv',
2967 'result': ['SizedResult<GLfloat>']
2969 'GetTexParameteriv': {
2970 'type': 'GETn',
2971 'decoder_func': 'DoGetTexParameteriv',
2972 'result': ['SizedResult<GLint>']
2974 'GetTranslatedShaderSourceANGLE': {
2975 'type': 'STRn',
2976 'get_len_func': 'DoGetShaderiv',
2977 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2978 'unit_test': False,
2979 'extension': True,
2981 'GetUniformBlockIndex': {
2982 'type': 'Custom',
2983 'data_transfer_methods': ['shm'],
2984 'cmd_args':
2985 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2986 'result': ['GLuint'],
2987 'error_return': 'GL_INVALID_INDEX',
2988 'unsafe': True,
2990 'GetUniformBlocksCHROMIUM': {
2991 'type': 'Custom',
2992 'expectation': False,
2993 'impl_func': False,
2994 'extension': True,
2995 'chromium': True,
2996 'client_test': False,
2997 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2998 'result': ['uint32_t'],
2999 'unsafe': True,
3001 'GetUniformsES3CHROMIUM': {
3002 'type': 'Custom',
3003 'expectation': False,
3004 'impl_func': False,
3005 'extension': True,
3006 'chromium': True,
3007 'client_test': False,
3008 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3009 'result': ['uint32_t'],
3010 'unsafe': True,
3012 'GetTransformFeedbackVarying': {
3013 'type': 'Custom',
3014 'data_transfer_methods': ['shm'],
3015 'cmd_args':
3016 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
3017 'void* result',
3018 'result': [
3019 'int32_t success',
3020 'int32_t size',
3021 'uint32_t type',
3023 'unsafe': True,
3025 'GetTransformFeedbackVaryingsCHROMIUM': {
3026 'type': 'Custom',
3027 'expectation': False,
3028 'impl_func': False,
3029 'extension': True,
3030 'chromium': True,
3031 'client_test': False,
3032 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
3033 'result': ['uint32_t'],
3034 'unsafe': True,
3036 'GetUniformfv': {
3037 'type': 'Custom',
3038 'data_transfer_methods': ['shm'],
3039 'result': ['SizedResult<GLfloat>'],
3041 'GetUniformiv': {
3042 'type': 'Custom',
3043 'data_transfer_methods': ['shm'],
3044 'result': ['SizedResult<GLint>'],
3046 'GetUniformuiv': {
3047 'type': 'Custom',
3048 'data_transfer_methods': ['shm'],
3049 'result': ['SizedResult<GLuint>'],
3050 'unsafe': True,
3052 'GetUniformIndices': {
3053 'type': 'Custom',
3054 'data_transfer_methods': ['shm'],
3055 'result': ['SizedResult<GLuint>'],
3056 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
3057 'GLuint* indices',
3058 'unsafe': True,
3060 'GetUniformLocation': {
3061 'type': 'Custom',
3062 'data_transfer_methods': ['shm'],
3063 'cmd_args':
3064 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
3065 'result': ['GLint'],
3066 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
3068 'GetVertexAttribfv': {
3069 'type': 'GETn',
3070 'result': ['SizedResult<GLfloat>'],
3071 'impl_decl': False,
3072 'decoder_func': 'DoGetVertexAttribfv',
3073 'expectation': False,
3074 'client_test': False,
3076 'GetVertexAttribiv': {
3077 'type': 'GETn',
3078 'result': ['SizedResult<GLint>'],
3079 'impl_decl': False,
3080 'decoder_func': 'DoGetVertexAttribiv',
3081 'expectation': False,
3082 'client_test': False,
3084 'GetVertexAttribIiv': {
3085 'type': 'GETn',
3086 'result': ['SizedResult<GLint>'],
3087 'impl_decl': False,
3088 'decoder_func': 'DoGetVertexAttribIiv',
3089 'expectation': False,
3090 'client_test': False,
3091 'unsafe': True,
3093 'GetVertexAttribIuiv': {
3094 'type': 'GETn',
3095 'result': ['SizedResult<GLuint>'],
3096 'impl_decl': False,
3097 'decoder_func': 'DoGetVertexAttribIuiv',
3098 'expectation': False,
3099 'client_test': False,
3100 'unsafe': True,
3102 'GetVertexAttribPointerv': {
3103 'type': 'Custom',
3104 'data_transfer_methods': ['shm'],
3105 'result': ['SizedResult<GLuint>'],
3106 'client_test': False,
3108 'InvalidateFramebuffer': {
3109 'type': 'PUTn',
3110 'count': 1,
3111 'client_test': False,
3112 'unit_test': False,
3113 'unsafe': True,
3115 'InvalidateSubFramebuffer': {
3116 'type': 'PUTn',
3117 'count': 1,
3118 'client_test': False,
3119 'unit_test': False,
3120 'unsafe': True,
3122 'IsBuffer': {
3123 'type': 'Is',
3124 'decoder_func': 'DoIsBuffer',
3125 'expectation': False,
3127 'IsEnabled': {
3128 'type': 'Is',
3129 'decoder_func': 'DoIsEnabled',
3130 'client_test': False,
3131 'impl_func': False,
3132 'expectation': False,
3134 'IsFramebuffer': {
3135 'type': 'Is',
3136 'decoder_func': 'DoIsFramebuffer',
3137 'expectation': False,
3139 'IsProgram': {
3140 'type': 'Is',
3141 'decoder_func': 'DoIsProgram',
3142 'expectation': False,
3144 'IsRenderbuffer': {
3145 'type': 'Is',
3146 'decoder_func': 'DoIsRenderbuffer',
3147 'expectation': False,
3149 'IsShader': {
3150 'type': 'Is',
3151 'decoder_func': 'DoIsShader',
3152 'expectation': False,
3154 'IsSampler': {
3155 'type': 'Is',
3156 'id_mapping': [ 'Sampler' ],
3157 'expectation': False,
3158 'unsafe': True,
3160 'IsSync': {
3161 'type': 'Is',
3162 'id_mapping': [ 'Sync' ],
3163 'cmd_args': 'GLuint sync',
3164 'expectation': False,
3165 'unsafe': True,
3167 'IsTexture': {
3168 'type': 'Is',
3169 'decoder_func': 'DoIsTexture',
3170 'expectation': False,
3172 'IsTransformFeedback': {
3173 'type': 'Is',
3174 'id_mapping': [ 'TransformFeedback' ],
3175 'expectation': False,
3176 'unsafe': True,
3178 'LinkProgram': {
3179 'decoder_func': 'DoLinkProgram',
3180 'impl_func': False,
3181 'trace_level': 1,
3183 'MapBufferCHROMIUM': {
3184 'gen_cmd': False,
3185 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3186 'chromium': True,
3187 'client_test': False,
3188 'trace_level': 1,
3190 'MapBufferSubDataCHROMIUM': {
3191 'gen_cmd': False,
3192 'extension': True,
3193 'chromium': True,
3194 'client_test': False,
3195 'pepper_interface': 'ChromiumMapSub',
3196 'trace_level': 1,
3198 'MapTexSubImage2DCHROMIUM': {
3199 'gen_cmd': False,
3200 'extension': "CHROMIUM_sub_image",
3201 'chromium': True,
3202 'client_test': False,
3203 'pepper_interface': 'ChromiumMapSub',
3204 'trace_level': 1,
3206 'MapBufferRange': {
3207 'type': 'Custom',
3208 'data_transfer_methods': ['shm'],
3209 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
3210 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
3211 'uint32_t data_shm_id, uint32_t data_shm_offset, '
3212 'uint32_t result_shm_id, uint32_t result_shm_offset',
3213 'unsafe': True,
3214 'result': ['uint32_t'],
3215 'trace_level': 1,
3217 'PauseTransformFeedback': {
3218 'unsafe': True,
3220 'PixelStorei': {'type': 'Manual'},
3221 'PostSubBufferCHROMIUM': {
3222 'type': 'Custom',
3223 'impl_func': False,
3224 'unit_test': False,
3225 'client_test': False,
3226 'extension': True,
3227 'chromium': True,
3229 'ProduceTextureCHROMIUM': {
3230 'decoder_func': 'DoProduceTextureCHROMIUM',
3231 'impl_func': False,
3232 'type': 'PUT',
3233 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3234 'unit_test': False,
3235 'client_test': False,
3236 'extension': "CHROMIUM_texture_mailbox",
3237 'chromium': True,
3238 'trace_level': 1,
3240 'ProduceTextureDirectCHROMIUM': {
3241 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
3242 'impl_func': False,
3243 'type': 'PUT',
3244 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
3245 'unit_test': False,
3246 'client_test': False,
3247 'extension': "CHROMIUM_texture_mailbox",
3248 'chromium': True,
3249 'trace_level': 1,
3251 'RenderbufferStorage': {
3252 'decoder_func': 'DoRenderbufferStorage',
3253 'gl_test_func': 'glRenderbufferStorageEXT',
3254 'expectation': False,
3255 'trace_level': 1,
3257 'RenderbufferStorageMultisampleCHROMIUM': {
3258 'cmd_comment':
3259 '// GL_CHROMIUM_framebuffer_multisample\n',
3260 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
3261 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
3262 'expectation': False,
3263 'unit_test': False,
3264 'extension_flag': 'chromium_framebuffer_multisample',
3265 'pepper_interface': 'FramebufferMultisample',
3266 'pepper_name': 'RenderbufferStorageMultisampleEXT',
3267 'trace_level': 1,
3269 'RenderbufferStorageMultisampleEXT': {
3270 'cmd_comment':
3271 '// GL_EXT_multisampled_render_to_texture\n',
3272 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
3273 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
3274 'expectation': False,
3275 'unit_test': False,
3276 'extension_flag': 'multisampled_render_to_texture',
3277 'trace_level': 1,
3279 'ReadBuffer': {
3280 'unsafe': True,
3281 'decoder_func': 'DoReadBuffer',
3282 'trace_level': 1,
3284 'ReadPixels': {
3285 'cmd_comment':
3286 '// ReadPixels has the result separated from the pixel buffer so that\n'
3287 '// it is easier to specify the result going to some specific place\n'
3288 '// that exactly fits the rectangle of pixels.\n',
3289 'type': 'Custom',
3290 'data_transfer_methods': ['shm'],
3291 'impl_func': False,
3292 'client_test': False,
3293 'cmd_args':
3294 'GLint x, GLint y, GLsizei width, GLsizei height, '
3295 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
3296 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
3297 'uint32_t result_shm_id, uint32_t result_shm_offset, '
3298 'GLboolean async',
3299 'result': ['uint32_t'],
3300 'defer_reads': True,
3301 'trace_level': 1,
3303 'ReleaseShaderCompiler': {
3304 'decoder_func': 'DoReleaseShaderCompiler',
3305 'unit_test': False,
3307 'ResumeTransformFeedback': {
3308 'unsafe': True,
3310 'SamplerParameterf': {
3311 'valid_args': {
3312 '2': 'GL_NEAREST'
3314 'id_mapping': [ 'Sampler' ],
3315 'unsafe': True,
3317 'SamplerParameterfv': {
3318 'type': 'PUT',
3319 'data_value': 'GL_NEAREST',
3320 'count': 1,
3321 'gl_test_func': 'glSamplerParameterf',
3322 'decoder_func': 'DoSamplerParameterfv',
3323 'first_element_only': True,
3324 'id_mapping': [ 'Sampler' ],
3325 'unsafe': True,
3327 'SamplerParameteri': {
3328 'valid_args': {
3329 '2': 'GL_NEAREST'
3331 'id_mapping': [ 'Sampler' ],
3332 'unsafe': True,
3334 'SamplerParameteriv': {
3335 'type': 'PUT',
3336 'data_value': 'GL_NEAREST',
3337 'count': 1,
3338 'gl_test_func': 'glSamplerParameteri',
3339 'decoder_func': 'DoSamplerParameteriv',
3340 'first_element_only': True,
3341 'unsafe': True,
3343 'ShaderBinary': {
3344 'type': 'Custom',
3345 'client_test': False,
3347 'ShaderSource': {
3348 'type': 'PUTSTR',
3349 'decoder_func': 'DoShaderSource',
3350 'expectation': False,
3351 'data_transfer_methods': ['bucket'],
3352 'cmd_args':
3353 'GLuint shader, const char** str',
3354 'pepper_args':
3355 'GLuint shader, GLsizei count, const char** str, const GLint* length',
3357 'StencilMask': {
3358 'type': 'StateSetFrontBack',
3359 'state': 'StencilMask',
3360 'no_gl': True,
3361 'expectation': False,
3363 'StencilMaskSeparate': {
3364 'type': 'StateSetFrontBackSeparate',
3365 'state': 'StencilMask',
3366 'no_gl': True,
3367 'expectation': False,
3369 'SwapBuffers': {
3370 'impl_func': False,
3371 'decoder_func': 'DoSwapBuffers',
3372 'unit_test': False,
3373 'client_test': False,
3374 'extension': True,
3375 'trace_level': 1,
3377 'SwapInterval': {
3378 'impl_func': False,
3379 'decoder_func': 'DoSwapInterval',
3380 'unit_test': False,
3381 'client_test': False,
3382 'extension': True,
3383 'trace_level': 1,
3385 'TexImage2D': {
3386 'type': 'Manual',
3387 'data_transfer_methods': ['shm'],
3388 'client_test': False,
3389 'trace_level': 2,
3391 'TexImage3D': {
3392 'type': 'Manual',
3393 'data_transfer_methods': ['shm'],
3394 'client_test': False,
3395 'unsafe': True,
3396 'trace_level': 2,
3398 'TexParameterf': {
3399 'decoder_func': 'DoTexParameterf',
3400 'valid_args': {
3401 '2': 'GL_NEAREST'
3404 'TexParameteri': {
3405 'decoder_func': 'DoTexParameteri',
3406 'valid_args': {
3407 '2': 'GL_NEAREST'
3410 'TexParameterfv': {
3411 'type': 'PUT',
3412 'data_value': 'GL_NEAREST',
3413 'count': 1,
3414 'decoder_func': 'DoTexParameterfv',
3415 'gl_test_func': 'glTexParameterf',
3416 'first_element_only': True,
3418 'TexParameteriv': {
3419 'type': 'PUT',
3420 'data_value': 'GL_NEAREST',
3421 'count': 1,
3422 'decoder_func': 'DoTexParameteriv',
3423 'gl_test_func': 'glTexParameteri',
3424 'first_element_only': True,
3426 'TexStorage3D': {
3427 'unsafe': True,
3428 'trace_level': 2,
3430 'TexSubImage2D': {
3431 'type': 'Manual',
3432 'data_transfer_methods': ['shm'],
3433 'client_test': False,
3434 'trace_level': 2,
3435 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3436 'GLint xoffset, GLint yoffset, '
3437 'GLsizei width, GLsizei height, '
3438 'GLenumTextureFormat format, GLenumPixelType type, '
3439 'const void* pixels, GLboolean internal'
3441 'TexSubImage3D': {
3442 'type': 'Manual',
3443 'data_transfer_methods': ['shm'],
3444 'client_test': False,
3445 'trace_level': 2,
3446 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3447 'GLint xoffset, GLint yoffset, GLint zoffset, '
3448 'GLsizei width, GLsizei height, GLsizei depth, '
3449 'GLenumTextureFormat format, GLenumPixelType type, '
3450 'const void* pixels, GLboolean internal',
3451 'unsafe': True,
3453 'TransformFeedbackVaryings': {
3454 'type': 'PUTSTR',
3455 'data_transfer_methods': ['bucket'],
3456 'decoder_func': 'DoTransformFeedbackVaryings',
3457 'cmd_args':
3458 'GLuint program, const char** varyings, GLenum buffermode',
3459 'unsafe': True,
3461 'Uniform1f': {'type': 'PUTXn', 'count': 1},
3462 'Uniform1fv': {
3463 'type': 'PUTn',
3464 'count': 1,
3465 'decoder_func': 'DoUniform1fv',
3467 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
3468 'Uniform1iv': {
3469 'type': 'PUTn',
3470 'count': 1,
3471 'decoder_func': 'DoUniform1iv',
3472 'unit_test': False,
3474 'Uniform1ui': {
3475 'type': 'PUTXn',
3476 'count': 1,
3477 'unsafe': True,
3479 'Uniform1uiv': {
3480 'type': 'PUTn',
3481 'count': 1,
3482 'unsafe': True,
3484 'Uniform2i': {'type': 'PUTXn', 'count': 2},
3485 'Uniform2f': {'type': 'PUTXn', 'count': 2},
3486 'Uniform2fv': {
3487 'type': 'PUTn',
3488 'count': 2,
3489 'decoder_func': 'DoUniform2fv',
3491 'Uniform2iv': {
3492 'type': 'PUTn',
3493 'count': 2,
3494 'decoder_func': 'DoUniform2iv',
3496 'Uniform2ui': {
3497 'type': 'PUTXn',
3498 'count': 2,
3499 'unsafe': True,
3501 'Uniform2uiv': {
3502 'type': 'PUTn',
3503 'count': 2,
3504 'unsafe': True,
3506 'Uniform3i': {'type': 'PUTXn', 'count': 3},
3507 'Uniform3f': {'type': 'PUTXn', 'count': 3},
3508 'Uniform3fv': {
3509 'type': 'PUTn',
3510 'count': 3,
3511 'decoder_func': 'DoUniform3fv',
3513 'Uniform3iv': {
3514 'type': 'PUTn',
3515 'count': 3,
3516 'decoder_func': 'DoUniform3iv',
3518 'Uniform3ui': {
3519 'type': 'PUTXn',
3520 'count': 3,
3521 'unsafe': True,
3523 'Uniform3uiv': {
3524 'type': 'PUTn',
3525 'count': 3,
3526 'unsafe': True,
3528 'Uniform4i': {'type': 'PUTXn', 'count': 4},
3529 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3530 'Uniform4fv': {
3531 'type': 'PUTn',
3532 'count': 4,
3533 'decoder_func': 'DoUniform4fv',
3535 'Uniform4iv': {
3536 'type': 'PUTn',
3537 'count': 4,
3538 'decoder_func': 'DoUniform4iv',
3540 'Uniform4ui': {
3541 'type': 'PUTXn',
3542 'count': 4,
3543 'unsafe': True,
3545 'Uniform4uiv': {
3546 'type': 'PUTn',
3547 'count': 4,
3548 'unsafe': True,
3550 'UniformMatrix2fv': {
3551 'type': 'PUTn',
3552 'count': 4,
3553 'decoder_func': 'DoUniformMatrix2fv',
3555 'UniformMatrix2x3fv': {
3556 'type': 'PUTn',
3557 'count': 6,
3558 'unsafe': True,
3560 'UniformMatrix2x4fv': {
3561 'type': 'PUTn',
3562 'count': 8,
3563 'unsafe': True,
3565 'UniformMatrix3fv': {
3566 'type': 'PUTn',
3567 'count': 9,
3568 'decoder_func': 'DoUniformMatrix3fv',
3570 'UniformMatrix3x2fv': {
3571 'type': 'PUTn',
3572 'count': 6,
3573 'unsafe': True,
3575 'UniformMatrix3x4fv': {
3576 'type': 'PUTn',
3577 'count': 12,
3578 'unsafe': True,
3580 'UniformMatrix4fv': {
3581 'type': 'PUTn',
3582 'count': 16,
3583 'decoder_func': 'DoUniformMatrix4fv',
3585 'UniformMatrix4x2fv': {
3586 'type': 'PUTn',
3587 'count': 8,
3588 'unsafe': True,
3590 'UniformMatrix4x3fv': {
3591 'type': 'PUTn',
3592 'count': 12,
3593 'unsafe': True,
3595 'UniformBlockBinding': {
3596 'type': 'Custom',
3597 'impl_func': False,
3598 'unsafe': True,
3600 'UnmapBufferCHROMIUM': {
3601 'gen_cmd': False,
3602 'extension': "CHROMIUM_pixel_transfer_buffer_object",
3603 'chromium': True,
3604 'client_test': False,
3605 'trace_level': 1,
3607 'UnmapBufferSubDataCHROMIUM': {
3608 'gen_cmd': False,
3609 'extension': True,
3610 'chromium': True,
3611 'client_test': False,
3612 'pepper_interface': 'ChromiumMapSub',
3613 'trace_level': 1,
3615 'UnmapBuffer': {
3616 'type': 'Custom',
3617 'unsafe': True,
3618 'trace_level': 1,
3620 'UnmapTexSubImage2DCHROMIUM': {
3621 'gen_cmd': False,
3622 'extension': "CHROMIUM_sub_image",
3623 'chromium': True,
3624 'client_test': False,
3625 'pepper_interface': 'ChromiumMapSub',
3626 'trace_level': 1,
3628 'UseProgram': {
3629 'type': 'Bind',
3630 'decoder_func': 'DoUseProgram',
3632 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3633 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3634 'VertexAttrib1fv': {
3635 'type': 'PUT',
3636 'count': 1,
3637 'decoder_func': 'DoVertexAttrib1fv',
3639 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3640 'VertexAttrib2fv': {
3641 'type': 'PUT',
3642 'count': 2,
3643 'decoder_func': 'DoVertexAttrib2fv',
3645 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3646 'VertexAttrib3fv': {
3647 'type': 'PUT',
3648 'count': 3,
3649 'decoder_func': 'DoVertexAttrib3fv',
3651 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3652 'VertexAttrib4fv': {
3653 'type': 'PUT',
3654 'count': 4,
3655 'decoder_func': 'DoVertexAttrib4fv',
3657 'VertexAttribI4i': {
3658 'unsafe': True,
3659 'decoder_func': 'DoVertexAttribI4i',
3661 'VertexAttribI4iv': {
3662 'type': 'PUT',
3663 'count': 4,
3664 'unsafe': True,
3665 'decoder_func': 'DoVertexAttribI4iv',
3667 'VertexAttribI4ui': {
3668 'unsafe': True,
3669 'decoder_func': 'DoVertexAttribI4ui',
3671 'VertexAttribI4uiv': {
3672 'type': 'PUT',
3673 'count': 4,
3674 'unsafe': True,
3675 'decoder_func': 'DoVertexAttribI4uiv',
3677 'VertexAttribIPointer': {
3678 'type': 'Manual',
3679 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3680 'GLenumVertexAttribIType type, GLsizei stride, '
3681 'GLuint offset',
3682 'client_test': False,
3683 'unsafe': True,
3685 'VertexAttribPointer': {
3686 'type': 'Manual',
3687 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3688 'GLenumVertexAttribType type, GLboolean normalized, '
3689 'GLsizei stride, GLuint offset',
3690 'client_test': False,
3692 'WaitSync': {
3693 'type': 'Custom',
3694 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3695 'GLuint timeout_0, GLuint timeout_1',
3696 'impl_func': False,
3697 'client_test': False,
3698 'unsafe': True,
3699 'trace_level': 1,
3701 'Scissor': {
3702 'type': 'StateSet',
3703 'state': 'Scissor',
3705 'Viewport': {
3706 'decoder_func': 'DoViewport',
3708 'ResizeCHROMIUM': {
3709 'type': 'Custom',
3710 'impl_func': False,
3711 'unit_test': False,
3712 'extension': True,
3713 'chromium': True,
3714 'trace_level': 1,
3716 'GetRequestableExtensionsCHROMIUM': {
3717 'type': 'Custom',
3718 'impl_func': False,
3719 'cmd_args': 'uint32_t bucket_id',
3720 'extension': True,
3721 'chromium': True,
3723 'RequestExtensionCHROMIUM': {
3724 'type': 'Custom',
3725 'impl_func': False,
3726 'client_test': False,
3727 'cmd_args': 'uint32_t bucket_id',
3728 'extension': True,
3729 'chromium': True,
3731 'RateLimitOffscreenContextCHROMIUM': {
3732 'gen_cmd': False,
3733 'extension': True,
3734 'chromium': True,
3735 'client_test': False,
3737 'CreateStreamTextureCHROMIUM': {
3738 'type': 'HandWritten',
3739 'impl_func': False,
3740 'gen_cmd': False,
3741 'extension': True,
3742 'chromium': True,
3743 'trace_level': 1,
3745 'TexImageIOSurface2DCHROMIUM': {
3746 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3747 'unit_test': False,
3748 'extension': True,
3749 'chromium': True,
3750 'trace_level': 1,
3752 'CopyTextureCHROMIUM': {
3753 'decoder_func': 'DoCopyTextureCHROMIUM',
3754 'unit_test': False,
3755 'extension': "CHROMIUM_copy_texture",
3756 'chromium': True,
3757 'trace_level': 2,
3759 'CopySubTextureCHROMIUM': {
3760 'decoder_func': 'DoCopySubTextureCHROMIUM',
3761 'unit_test': False,
3762 'extension': "CHROMIUM_copy_texture",
3763 'chromium': True,
3764 'trace_level': 2,
3766 'CompressedCopyTextureCHROMIUM': {
3767 'decoder_func': 'DoCompressedCopyTextureCHROMIUM',
3768 'unit_test': False,
3769 'extension': True,
3770 'chromium': True,
3772 'CompressedCopySubTextureCHROMIUM': {
3773 'decoder_func': 'DoCompressedCopySubTextureCHROMIUM',
3774 'unit_test': False,
3775 'extension': True,
3776 'chromium': True,
3778 'TexStorage2DEXT': {
3779 'unit_test': False,
3780 'extension': True,
3781 'decoder_func': 'DoTexStorage2DEXT',
3782 'trace_level': 2,
3784 'DrawArraysInstancedANGLE': {
3785 'type': 'Manual',
3786 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3787 'GLsizei primcount',
3788 'extension': True,
3789 'unit_test': False,
3790 'pepper_interface': 'InstancedArrays',
3791 'defer_draws': True,
3792 'trace_level': 2,
3794 'DrawBuffersEXT': {
3795 'type': 'PUTn',
3796 'decoder_func': 'DoDrawBuffersEXT',
3797 'count': 1,
3798 'client_test': False,
3799 'unit_test': False,
3800 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3801 # work without.
3802 'extension': True,
3803 'pepper_interface': 'DrawBuffers',
3804 'trace_level': 2,
3806 'DrawElementsInstancedANGLE': {
3807 'type': 'Manual',
3808 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3809 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3810 'extension': True,
3811 'unit_test': False,
3812 'client_test': False,
3813 'pepper_interface': 'InstancedArrays',
3814 'defer_draws': True,
3815 'trace_level': 2,
3817 'VertexAttribDivisorANGLE': {
3818 'type': 'Manual',
3819 'cmd_args': 'GLuint index, GLuint divisor',
3820 'extension': True,
3821 'unit_test': False,
3822 'pepper_interface': 'InstancedArrays',
3824 'GenQueriesEXT': {
3825 'type': 'GENn',
3826 'gl_test_func': 'glGenQueriesARB',
3827 'resource_type': 'Query',
3828 'resource_types': 'Queries',
3829 'unit_test': False,
3830 'pepper_interface': 'Query',
3831 'not_shared': 'True',
3832 'extension': "occlusion_query_EXT",
3834 'DeleteQueriesEXT': {
3835 'type': 'DELn',
3836 'gl_test_func': 'glDeleteQueriesARB',
3837 'resource_type': 'Query',
3838 'resource_types': 'Queries',
3839 'unit_test': False,
3840 'pepper_interface': 'Query',
3841 'extension': "occlusion_query_EXT",
3843 'IsQueryEXT': {
3844 'gen_cmd': False,
3845 'client_test': False,
3846 'pepper_interface': 'Query',
3847 'extension': "occlusion_query_EXT",
3849 'BeginQueryEXT': {
3850 'type': 'Manual',
3851 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3852 'data_transfer_methods': ['shm'],
3853 'gl_test_func': 'glBeginQuery',
3854 'pepper_interface': 'Query',
3855 'extension': "occlusion_query_EXT",
3857 'BeginTransformFeedback': {
3858 'unsafe': True,
3860 'EndQueryEXT': {
3861 'type': 'Manual',
3862 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3863 'gl_test_func': 'glEndnQuery',
3864 'client_test': False,
3865 'pepper_interface': 'Query',
3866 'extension': "occlusion_query_EXT",
3868 'EndTransformFeedback': {
3869 'unsafe': True,
3871 'FlushDriverCachesCHROMIUM': {
3872 'decoder_func': 'DoFlushDriverCachesCHROMIUM',
3873 'unit_test': False,
3874 'extension': True,
3875 'chromium': True,
3876 'trace_level': 1,
3878 'GetQueryivEXT': {
3879 'gen_cmd': False,
3880 'client_test': False,
3881 'gl_test_func': 'glGetQueryiv',
3882 'pepper_interface': 'Query',
3883 'extension': "occlusion_query_EXT",
3885 'QueryCounterEXT' : {
3886 'type': 'Manual',
3887 'cmd_args': 'GLidQuery id, GLenumQueryTarget target, '
3888 'void* sync_data, GLuint submit_count',
3889 'data_transfer_methods': ['shm'],
3890 'gl_test_func': 'glQueryCounter',
3891 'extension': "disjoint_timer_query_EXT",
3893 'GetQueryObjectivEXT': {
3894 'gen_cmd': False,
3895 'client_test': False,
3896 'gl_test_func': 'glGetQueryObjectiv',
3897 'extension': "disjoint_timer_query_EXT",
3899 'GetQueryObjectuivEXT': {
3900 'gen_cmd': False,
3901 'client_test': False,
3902 'gl_test_func': 'glGetQueryObjectuiv',
3903 'pepper_interface': 'Query',
3904 'extension': "occlusion_query_EXT",
3906 'GetQueryObjecti64vEXT': {
3907 'gen_cmd': False,
3908 'client_test': False,
3909 'gl_test_func': 'glGetQueryObjecti64v',
3910 'extension': "disjoint_timer_query_EXT",
3912 'GetQueryObjectui64vEXT': {
3913 'gen_cmd': False,
3914 'client_test': False,
3915 'gl_test_func': 'glGetQueryObjectui64v',
3916 'extension': "disjoint_timer_query_EXT",
3918 'SetDisjointValueSyncCHROMIUM': {
3919 'type': 'Manual',
3920 'data_transfer_methods': ['shm'],
3921 'client_test': False,
3922 'cmd_args': 'void* sync_data',
3923 'extension': True,
3924 'chromium': True,
3926 'BindUniformLocationCHROMIUM': {
3927 'type': 'GLchar',
3928 'extension': True,
3929 'data_transfer_methods': ['bucket'],
3930 'needs_size': True,
3931 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3933 'InsertEventMarkerEXT': {
3934 'type': 'GLcharN',
3935 'decoder_func': 'DoInsertEventMarkerEXT',
3936 'expectation': False,
3937 'extension': True,
3939 'PushGroupMarkerEXT': {
3940 'type': 'GLcharN',
3941 'decoder_func': 'DoPushGroupMarkerEXT',
3942 'expectation': False,
3943 'extension': True,
3945 'PopGroupMarkerEXT': {
3946 'decoder_func': 'DoPopGroupMarkerEXT',
3947 'expectation': False,
3948 'extension': True,
3949 'impl_func': False,
3952 'GenVertexArraysOES': {
3953 'type': 'GENn',
3954 'extension': True,
3955 'gl_test_func': 'glGenVertexArraysOES',
3956 'resource_type': 'VertexArray',
3957 'resource_types': 'VertexArrays',
3958 'unit_test': False,
3959 'pepper_interface': 'VertexArrayObject',
3961 'BindVertexArrayOES': {
3962 'type': 'Bind',
3963 'extension': True,
3964 'gl_test_func': 'glBindVertexArrayOES',
3965 'decoder_func': 'DoBindVertexArrayOES',
3966 'gen_func': 'GenVertexArraysOES',
3967 'unit_test': False,
3968 'client_test': False,
3969 'pepper_interface': 'VertexArrayObject',
3971 'DeleteVertexArraysOES': {
3972 'type': 'DELn',
3973 'extension': True,
3974 'gl_test_func': 'glDeleteVertexArraysOES',
3975 'resource_type': 'VertexArray',
3976 'resource_types': 'VertexArrays',
3977 'unit_test': False,
3978 'pepper_interface': 'VertexArrayObject',
3980 'IsVertexArrayOES': {
3981 'type': 'Is',
3982 'extension': True,
3983 'gl_test_func': 'glIsVertexArrayOES',
3984 'decoder_func': 'DoIsVertexArrayOES',
3985 'expectation': False,
3986 'unit_test': False,
3987 'pepper_interface': 'VertexArrayObject',
3989 'BindTexImage2DCHROMIUM': {
3990 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3991 'unit_test': False,
3992 'extension': "CHROMIUM_image",
3993 'chromium': True,
3995 'ReleaseTexImage2DCHROMIUM': {
3996 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3997 'unit_test': False,
3998 'extension': "CHROMIUM_image",
3999 'chromium': True,
4001 'ShallowFinishCHROMIUM': {
4002 'impl_func': False,
4003 'gen_cmd': False,
4004 'extension': True,
4005 'chromium': True,
4006 'client_test': False,
4008 'ShallowFlushCHROMIUM': {
4009 'impl_func': False,
4010 'gen_cmd': False,
4011 'extension': "CHROMIUM_miscellaneous",
4012 'chromium': True,
4013 'client_test': False,
4015 'OrderingBarrierCHROMIUM': {
4016 'impl_func': False,
4017 'gen_cmd': False,
4018 'extension': "CHROMIUM_miscellaneous",
4019 'chromium': True,
4020 'client_test': False,
4022 'TraceBeginCHROMIUM': {
4023 'type': 'Custom',
4024 'impl_func': False,
4025 'client_test': False,
4026 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
4027 'extension': True,
4028 'chromium': True,
4030 'TraceEndCHROMIUM': {
4031 'impl_func': False,
4032 'client_test': False,
4033 'decoder_func': 'DoTraceEndCHROMIUM',
4034 'unit_test': False,
4035 'extension': True,
4036 'chromium': True,
4038 'DiscardFramebufferEXT': {
4039 'type': 'PUTn',
4040 'count': 1,
4041 'decoder_func': 'DoDiscardFramebufferEXT',
4042 'unit_test': False,
4043 'client_test': False,
4044 'extension_flag': 'ext_discard_framebuffer',
4045 'trace_level': 2,
4047 'LoseContextCHROMIUM': {
4048 'decoder_func': 'DoLoseContextCHROMIUM',
4049 'unit_test': False,
4050 'extension': True,
4051 'chromium': True,
4052 'trace_level': 1,
4054 'InsertSyncPointCHROMIUM': {
4055 'type': 'HandWritten',
4056 'impl_func': False,
4057 'extension': "CHROMIUM_sync_point",
4058 'chromium': True,
4059 'trace_level': 1,
4061 'WaitSyncPointCHROMIUM': {
4062 'type': 'Custom',
4063 'impl_func': True,
4064 'extension': "CHROMIUM_sync_point",
4065 'chromium': True,
4066 'trace_level': 1,
4068 'DiscardBackbufferCHROMIUM': {
4069 'type': 'Custom',
4070 'impl_func': True,
4071 'extension': True,
4072 'chromium': True,
4073 'trace_level': 2,
4075 'ScheduleOverlayPlaneCHROMIUM': {
4076 'type': 'Custom',
4077 'impl_func': True,
4078 'unit_test': False,
4079 'client_test': False,
4080 'extension': True,
4081 'chromium': True,
4083 'MatrixLoadfCHROMIUM': {
4084 'type': 'PUT',
4085 'count': 16,
4086 'data_type': 'GLfloat',
4087 'decoder_func': 'DoMatrixLoadfCHROMIUM',
4088 'gl_test_func': 'glMatrixLoadfEXT',
4089 'chromium': True,
4090 'extension': True,
4091 'extension_flag': 'chromium_path_rendering',
4093 'MatrixLoadIdentityCHROMIUM': {
4094 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
4095 'gl_test_func': 'glMatrixLoadIdentityEXT',
4096 'chromium': True,
4097 'extension': True,
4098 'extension_flag': 'chromium_path_rendering',
4100 'GenPathsCHROMIUM': {
4101 'type': 'Custom',
4102 'cmd_args': 'GLuint first_client_id, GLsizei range',
4103 'chromium': True,
4104 'extension': True,
4105 'extension_flag': 'chromium_path_rendering',
4107 'DeletePathsCHROMIUM': {
4108 'type': 'Custom',
4109 'cmd_args': 'GLuint first_client_id, GLsizei range',
4110 'impl_func': False,
4111 'unit_test': False,
4112 'chromium': True,
4113 'extension': True,
4114 'extension_flag': 'chromium_path_rendering',
4116 'IsPathCHROMIUM': {
4117 'type': 'Is',
4118 'decoder_func': 'DoIsPathCHROMIUM',
4119 'gl_test_func': 'glIsPathNV',
4120 'chromium': True,
4121 'extension': True,
4122 'extension_flag': 'chromium_path_rendering',
4124 'PathCommandsCHROMIUM': {
4125 'type': 'Manual',
4126 'immediate': False,
4127 'chromium': True,
4128 'extension': True,
4129 'extension_flag': 'chromium_path_rendering',
4131 'PathParameterfCHROMIUM': {
4132 'type': 'Custom',
4133 'chromium': True,
4134 'extension': True,
4135 'extension_flag': 'chromium_path_rendering',
4137 'PathParameteriCHROMIUM': {
4138 'type': 'Custom',
4139 'chromium': True,
4140 'extension': True,
4141 'extension_flag': 'chromium_path_rendering',
4143 'PathStencilFuncCHROMIUM': {
4144 'type': 'StateSet',
4145 'state': 'PathStencilFuncCHROMIUM',
4146 'decoder_func': 'glPathStencilFuncNV',
4147 'chromium': True,
4148 'extension': True,
4149 'extension_flag': 'chromium_path_rendering',
4151 'StencilFillPathCHROMIUM': {
4152 'type': 'Custom',
4153 'chromium': True,
4154 'extension': True,
4155 'extension_flag': 'chromium_path_rendering',
4157 'StencilStrokePathCHROMIUM': {
4158 'type': 'Custom',
4159 'chromium': True,
4160 'extension': True,
4161 'extension_flag': 'chromium_path_rendering',
4163 'CoverFillPathCHROMIUM': {
4164 'type': 'Custom',
4165 'chromium': True,
4166 'extension': True,
4167 'extension_flag': 'chromium_path_rendering',
4169 'CoverStrokePathCHROMIUM': {
4170 'type': 'Custom',
4171 'chromium': True,
4172 'extension': True,
4173 'extension_flag': 'chromium_path_rendering',
4175 'StencilThenCoverFillPathCHROMIUM': {
4176 'type': 'Custom',
4177 'chromium': True,
4178 'extension': True,
4179 'extension_flag': 'chromium_path_rendering',
4181 'StencilThenCoverStrokePathCHROMIUM': {
4182 'type': 'Custom',
4183 'chromium': True,
4184 'extension': True,
4185 'extension_flag': 'chromium_path_rendering',
4191 def Grouper(n, iterable, fillvalue=None):
4192 """Collect data into fixed-length chunks or blocks"""
4193 args = [iter(iterable)] * n
4194 return itertools.izip_longest(fillvalue=fillvalue, *args)
4197 def SplitWords(input_string):
4198 """Split by '_' if found, otherwise split at uppercase/numeric chars.
4200 Will split "some_TEXT" into ["some", "TEXT"], "CamelCase" into ["Camel",
4201 "Case"], and "Vector3" into ["Vector", "3"].
4203 if input_string.find('_') > -1:
4204 # 'some_TEXT_' -> 'some TEXT'
4205 return input_string.replace('_', ' ').strip().split()
4206 else:
4207 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
4208 # mixed case.
4209 # look for capitalization to cut input_strings
4210 # 'SomeText' -> 'Some Text'
4211 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
4212 # 'Vector3' -> 'Vector 3'
4213 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
4214 return input_string.split()
4216 def ToUnderscore(input_string):
4217 """converts CamelCase to camel_case."""
4218 words = SplitWords(input_string)
4219 return '_'.join([word.lower() for word in words])
4221 def CachedStateName(item):
4222 if item.get('cached', False):
4223 return 'cached_' + item['name']
4224 return item['name']
4226 def ToGLExtensionString(extension_flag):
4227 """Returns GL-type extension string of a extension flag."""
4228 if extension_flag == "oes_compressed_etc1_rgb8_texture":
4229 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
4230 # unfortunate.
4231 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
4232 'egl', 'atc', 'etc1', 'angle']
4233 parts = extension_flag.split('_')
4234 return "_".join(
4235 [part.upper() if part in uppercase_words else part for part in parts])
4237 def ToCamelCase(input_string):
4238 """converts ABC_underscore_case to ABCUnderscoreCase."""
4239 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
4241 def GetGLGetTypeConversion(result_type, value_type, value):
4242 """Makes a gl compatible type conversion string for accessing state variables.
4244 Useful when accessing state variables through glGetXXX calls.
4245 glGet documetation (for example, the manual pages):
4246 [...] If glGetIntegerv is called, [...] most floating-point values are
4247 rounded to the nearest integer value. [...]
4249 Args:
4250 result_type: the gl type to be obtained
4251 value_type: the GL type of the state variable
4252 value: the name of the state variable
4254 Returns:
4255 String that converts the state variable to desired GL type according to GL
4256 rules.
4259 if result_type == 'GLint':
4260 if value_type == 'GLfloat':
4261 return 'static_cast<GLint>(round(%s))' % value
4262 return 'static_cast<%s>(%s)' % (result_type, value)
4265 class CWriter(object):
4266 """Context manager that creates a C source file.
4268 To be used with the `with` statement. Returns a normal `file` type, open only
4269 for writing - any existing files with that name will be overwritten. It will
4270 automatically write the contents of `_LICENSE` and `_DO_NOT_EDIT_WARNING`
4271 at the beginning.
4273 Example:
4274 with CWriter("file.cpp") as myfile:
4275 myfile.write("hello")
4276 # type(myfile) == file
4278 def __init__(self, filename):
4279 self.filename = filename
4280 self._file = open(filename, 'w')
4281 self._ENTER_MSG = _LICENSE + _DO_NOT_EDIT_WARNING
4282 self._EXIT_MSG = ""
4284 def __enter__(self):
4285 self._file.write(self._ENTER_MSG)
4286 return self._file
4288 def __exit__(self, exc_type, exc_value, traceback):
4289 self._file.write(self._EXIT_MSG)
4290 self._file.close()
4293 class CHeaderWriter(CWriter):
4294 """Context manager that creates a C header file.
4296 Works the same way as CWriter, except it will also add the #ifdef guard
4297 around it. If `file_comment` is set, it will write that before the #ifdef
4298 guard.
4300 def __init__(self, filename, file_comment=None):
4301 super(CHeaderWriter, self).__init__(filename)
4302 guard = self._get_guard()
4303 if file_comment is None:
4304 file_comment = ""
4305 self._ENTER_MSG = self._ENTER_MSG + file_comment \
4306 + "#ifndef %s\n#define %s\n\n" % (guard, guard)
4307 self._EXIT_MSG = self._EXIT_MSG + "#endif // %s\n" % guard
4309 def _get_guard(self):
4310 non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
4311 base = os.path.abspath(self.filename)
4312 while os.path.basename(base) != 'src':
4313 new_base = os.path.dirname(base)
4314 assert new_base != base # Prevent infinite loop.
4315 base = new_base
4316 hpath = os.path.relpath(self.filename, base)
4317 return non_alnum_re.sub('_', hpath).upper() + '_'
4320 class TypeHandler(object):
4321 """This class emits code for a particular type of function."""
4323 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
4325 def InitFunction(self, func):
4326 """Add or adjust anything type specific for this function."""
4327 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
4328 func.AddCmdArg(DataSizeArgument('data_size'))
4330 def NeedsDataTransferFunction(self, func):
4331 """Overriden from TypeHandler."""
4332 return func.num_pointer_args >= 1
4334 def WriteStruct(self, func, f):
4335 """Writes a structure that matches the arguments to a function."""
4336 comment = func.GetInfo('cmd_comment')
4337 if not comment == None:
4338 f.write(comment)
4339 f.write("struct %s {\n" % func.name)
4340 f.write(" typedef %s ValueType;\n" % func.name)
4341 f.write(" static const CommandId kCmdId = k%s;\n" % func.name)
4342 func.WriteCmdArgFlag(f)
4343 func.WriteCmdFlag(f)
4344 f.write("\n")
4345 result = func.GetInfo('result')
4346 if not result == None:
4347 if len(result) == 1:
4348 f.write(" typedef %s Result;\n\n" % result[0])
4349 else:
4350 f.write(" struct Result {\n")
4351 for line in result:
4352 f.write(" %s;\n" % line)
4353 f.write(" };\n\n")
4355 func.WriteCmdComputeSize(f)
4356 func.WriteCmdSetHeader(f)
4357 func.WriteCmdInit(f)
4358 func.WriteCmdSet(f)
4360 f.write(" gpu::CommandHeader header;\n")
4361 args = func.GetCmdArgs()
4362 for arg in args:
4363 f.write(" %s %s;\n" % (arg.cmd_type, arg.name))
4365 consts = func.GetCmdConstants()
4366 for const in consts:
4367 f.write(" static const %s %s = %s;\n" %
4368 (const.cmd_type, const.name, const.GetConstantValue()))
4370 f.write("};\n")
4371 f.write("\n")
4373 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
4374 f.write("static_assert(sizeof(%s) == %d,\n" % (func.name, size))
4375 f.write(" \"size of %s should be %d\");\n" %
4376 (func.name, size))
4377 f.write("static_assert(offsetof(%s, header) == 0,\n" % func.name)
4378 f.write(" \"offset of %s header should be 0\");\n" %
4379 func.name)
4380 offset = _SIZE_OF_COMMAND_HEADER
4381 for arg in args:
4382 f.write("static_assert(offsetof(%s, %s) == %d,\n" %
4383 (func.name, arg.name, offset))
4384 f.write(" \"offset of %s %s should be %d\");\n" %
4385 (func.name, arg.name, offset))
4386 offset += _SIZE_OF_UINT32
4387 if not result == None and len(result) > 1:
4388 offset = 0;
4389 for line in result:
4390 parts = line.split()
4391 name = parts[-1]
4392 check = """
4393 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
4394 "offset of %(cmd_name)s Result %(field_name)s should be "
4395 "%(offset)d");
4397 f.write((check.strip() + "\n") % {
4398 'cmd_name': func.name,
4399 'field_name': name,
4400 'offset': offset,
4402 offset += _SIZE_OF_UINT32
4403 f.write("\n")
4405 def WriteHandlerImplementation(self, func, f):
4406 """Writes the handler implementation for this command."""
4407 if func.IsUnsafe() and func.GetInfo('id_mapping'):
4408 code_no_gen = """ if (!group_->Get%(type)sServiceId(
4409 %(var)s, &%(service_var)s)) {
4410 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4411 return error::kNoError;
4414 code_gen = """ if (!group_->Get%(type)sServiceId(
4415 %(var)s, &%(service_var)s)) {
4416 if (!group_->bind_generates_resource()) {
4417 LOCAL_SET_GL_ERROR(
4418 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
4419 return error::kNoError;
4421 GLuint client_id = %(var)s;
4422 gl%(gen_func)s(1, &%(service_var)s);
4423 Create%(type)s(client_id, %(service_var)s);
4426 gen_func = func.GetInfo('gen_func')
4427 for id_type in func.GetInfo('id_mapping'):
4428 service_var = id_type.lower()
4429 if id_type == 'Sync':
4430 service_var = "service_%s" % service_var
4431 f.write(" GLsync %s = 0;\n" % service_var)
4432 if id_type == 'Sampler' and func.IsType('Bind'):
4433 # No error generated when binding a reserved zero sampler.
4434 args = [arg.name for arg in func.GetOriginalArgs()]
4435 f.write(""" if(%(var)s == 0) {
4436 %(func)s(%(args)s);
4437 return error::kNoError;
4438 }""" % { 'var': id_type.lower(),
4439 'func': func.GetGLFunctionName(),
4440 'args': ", ".join(args) })
4441 if gen_func and id_type in gen_func:
4442 f.write(code_gen % { 'type': id_type,
4443 'var': id_type.lower(),
4444 'service_var': service_var,
4445 'func': func.GetGLFunctionName(),
4446 'gen_func': gen_func })
4447 else:
4448 f.write(code_no_gen % { 'type': id_type,
4449 'var': id_type.lower(),
4450 'service_var': service_var,
4451 'func': func.GetGLFunctionName() })
4452 args = []
4453 for arg in func.GetOriginalArgs():
4454 if arg.type == "GLsync":
4455 args.append("service_%s" % arg.name)
4456 elif arg.name.endswith("size") and arg.type == "GLsizei":
4457 args.append("num_%s" % func.GetLastOriginalArg().name)
4458 elif arg.name == "length":
4459 args.append("nullptr")
4460 else:
4461 args.append(arg.name)
4462 f.write(" %s(%s);\n" %
4463 (func.GetGLFunctionName(), ", ".join(args)))
4465 def WriteCmdSizeTest(self, func, f):
4466 """Writes the size test for a command."""
4467 f.write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
4469 def WriteFormatTest(self, func, f):
4470 """Writes a format test for a command."""
4471 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
4472 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
4473 (func.name, func.name))
4474 f.write(" void* next_cmd = cmd.Set(\n")
4475 f.write(" &cmd")
4476 args = func.GetCmdArgs()
4477 for value, arg in enumerate(args):
4478 f.write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
4479 f.write(");\n")
4480 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
4481 func.name)
4482 f.write(" cmd.header.command);\n")
4483 func.type_handler.WriteCmdSizeTest(func, f)
4484 for value, arg in enumerate(args):
4485 f.write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
4486 (arg.type, value + 11, arg.name))
4487 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
4488 f.write(" next_cmd, sizeof(cmd));\n")
4489 f.write("}\n")
4490 f.write("\n")
4492 def WriteImmediateFormatTest(self, func, f):
4493 """Writes a format test for an immediate version of a command."""
4494 pass
4496 def WriteGetDataSizeCode(self, func, f):
4497 """Writes the code to set data_size used in validation"""
4498 pass
4500 def __WriteIdMapping(self, func, f):
4501 """Writes client side / service side ID mapping."""
4502 if not func.IsUnsafe() or not func.GetInfo('id_mapping'):
4503 return
4504 for id_type in func.GetInfo('id_mapping'):
4505 f.write(" group_->Get%sServiceId(%s, &%s);\n" %
4506 (id_type, id_type.lower(), id_type.lower()))
4508 def WriteImmediateHandlerImplementation (self, func, f):
4509 """Writes the handler impl for the immediate version of a command."""
4510 self.__WriteIdMapping(func, f)
4511 f.write(" %s(%s);\n" %
4512 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4514 def WriteBucketHandlerImplementation (self, func, f):
4515 """Writes the handler impl for the bucket version of a command."""
4516 self.__WriteIdMapping(func, f)
4517 f.write(" %s(%s);\n" %
4518 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4520 def WriteServiceHandlerFunctionHeader(self, func, f):
4521 """Writes function header for service implementation handlers."""
4522 f.write("""error::Error GLES2DecoderImpl::Handle%(name)s(
4523 uint32_t immediate_data_size, const void* cmd_data) {
4524 """ % {'name': func.name})
4525 if func.IsUnsafe():
4526 f.write("""if (!unsafe_es3_apis_enabled())
4527 return error::kUnknownCommand;
4528 """)
4529 f.write("""const gles2::cmds::%(name)s& c =
4530 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
4531 (void)c;
4532 """ % {'name': func.name})
4534 def WriteServiceImplementation(self, func, f):
4535 """Writes the service implementation for a command."""
4536 self.WriteServiceHandlerFunctionHeader(func, f)
4537 self.WriteHandlerExtensionCheck(func, f)
4538 self.WriteHandlerDeferReadWrite(func, f);
4539 if len(func.GetOriginalArgs()) > 0:
4540 last_arg = func.GetLastOriginalArg()
4541 all_but_last_arg = func.GetOriginalArgs()[:-1]
4542 for arg in all_but_last_arg:
4543 arg.WriteGetCode(f)
4544 self.WriteGetDataSizeCode(func, f)
4545 last_arg.WriteGetCode(f)
4546 func.WriteHandlerValidation(f)
4547 func.WriteHandlerImplementation(f)
4548 f.write(" return error::kNoError;\n")
4549 f.write("}\n")
4550 f.write("\n")
4552 def WriteImmediateServiceImplementation(self, func, f):
4553 """Writes the service implementation for an immediate version of command."""
4554 self.WriteServiceHandlerFunctionHeader(func, f)
4555 self.WriteHandlerExtensionCheck(func, f)
4556 self.WriteHandlerDeferReadWrite(func, f);
4557 for arg in func.GetOriginalArgs():
4558 if arg.IsPointer():
4559 self.WriteGetDataSizeCode(func, f)
4560 arg.WriteGetCode(f)
4561 func.WriteHandlerValidation(f)
4562 func.WriteHandlerImplementation(f)
4563 f.write(" return error::kNoError;\n")
4564 f.write("}\n")
4565 f.write("\n")
4567 def WriteBucketServiceImplementation(self, func, f):
4568 """Writes the service implementation for a bucket version of command."""
4569 self.WriteServiceHandlerFunctionHeader(func, f)
4570 self.WriteHandlerExtensionCheck(func, f)
4571 self.WriteHandlerDeferReadWrite(func, f);
4572 for arg in func.GetCmdArgs():
4573 arg.WriteGetCode(f)
4574 func.WriteHandlerValidation(f)
4575 func.WriteHandlerImplementation(f)
4576 f.write(" return error::kNoError;\n")
4577 f.write("}\n")
4578 f.write("\n")
4580 def WriteHandlerExtensionCheck(self, func, f):
4581 if func.GetInfo('extension_flag'):
4582 f.write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
4583 f.write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
4584 " \"function not available\");\n" % func.original_name)
4585 f.write(" return error::kNoError;")
4586 f.write(" }\n\n")
4588 def WriteHandlerDeferReadWrite(self, func, f):
4589 """Writes the code to handle deferring reads or writes."""
4590 defer_draws = func.GetInfo('defer_draws')
4591 defer_reads = func.GetInfo('defer_reads')
4592 if defer_draws or defer_reads:
4593 f.write(" error::Error error;\n")
4594 if defer_draws:
4595 f.write(" error = WillAccessBoundFramebufferForDraw();\n")
4596 f.write(" if (error != error::kNoError)\n")
4597 f.write(" return error;\n")
4598 if defer_reads:
4599 f.write(" error = WillAccessBoundFramebufferForRead();\n")
4600 f.write(" if (error != error::kNoError)\n")
4601 f.write(" return error;\n")
4603 def WriteValidUnitTest(self, func, f, test, *extras):
4604 """Writes a valid unit test for the service implementation."""
4605 if func.GetInfo('expectation') == False:
4606 test = self._remove_expected_call_re.sub('', test)
4607 name = func.name
4608 arg_strings = [
4609 arg.GetValidArg(func) \
4610 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4612 gl_arg_strings = [
4613 arg.GetValidGLArg(func) \
4614 for arg in func.GetOriginalArgs()
4616 gl_func_name = func.GetGLTestFunctionName()
4617 vars = {
4618 'name':name,
4619 'gl_func_name': gl_func_name,
4620 'args': ", ".join(arg_strings),
4621 'gl_args': ", ".join(gl_arg_strings),
4623 for extra in extras:
4624 vars.update(extra)
4625 old_test = ""
4626 while (old_test != test):
4627 old_test = test
4628 test = test % vars
4629 f.write(test % vars)
4631 def WriteInvalidUnitTest(self, func, f, test, *extras):
4632 """Writes an invalid unit test for the service implementation."""
4633 if func.IsUnsafe():
4634 return
4635 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
4636 # Service implementation does not test constants, as they are not part of
4637 # the call in the service side.
4638 if invalid_arg.IsConstant():
4639 continue
4641 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
4642 for value_index in range(0, num_invalid_values):
4643 arg_strings = []
4644 parse_result = "kNoError"
4645 gl_error = None
4646 for arg in func.GetOriginalArgs():
4647 if arg.IsConstant():
4648 continue
4649 if invalid_arg is arg:
4650 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
4651 value_index)
4652 else:
4653 arg_string = arg.GetValidArg(func)
4654 arg_strings.append(arg_string)
4655 gl_arg_strings = []
4656 for arg in func.GetOriginalArgs():
4657 gl_arg_strings.append("_")
4658 gl_func_name = func.GetGLTestFunctionName()
4659 gl_error_test = ''
4660 if not gl_error == None:
4661 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4663 vars = {
4664 'name': func.name,
4665 'arg_index': invalid_arg_index,
4666 'value_index': value_index,
4667 'gl_func_name': gl_func_name,
4668 'args': ", ".join(arg_strings),
4669 'all_but_last_args': ", ".join(arg_strings[:-1]),
4670 'gl_args': ", ".join(gl_arg_strings),
4671 'parse_result': parse_result,
4672 'gl_error_test': gl_error_test,
4674 for extra in extras:
4675 vars.update(extra)
4676 f.write(test % vars)
4678 def WriteServiceUnitTest(self, func, f, *extras):
4679 """Writes the service unit test for a command."""
4681 if func.name == 'Enable':
4682 valid_test = """
4683 TEST_P(%(test_name)s, %(name)sValidArgs) {
4684 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4685 SpecializedSetup<cmds::%(name)s, 0>(true);
4686 cmds::%(name)s cmd;
4687 cmd.Init(%(args)s);"""
4688 elif func.name == 'Disable':
4689 valid_test = """
4690 TEST_P(%(test_name)s, %(name)sValidArgs) {
4691 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4692 SpecializedSetup<cmds::%(name)s, 0>(true);
4693 cmds::%(name)s cmd;
4694 cmd.Init(%(args)s);"""
4695 else:
4696 valid_test = """
4697 TEST_P(%(test_name)s, %(name)sValidArgs) {
4698 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4699 SpecializedSetup<cmds::%(name)s, 0>(true);
4700 cmds::%(name)s cmd;
4701 cmd.Init(%(args)s);"""
4702 if func.IsUnsafe():
4703 valid_test += """
4704 decoder_->set_unsafe_es3_apis_enabled(true);
4705 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4706 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4707 decoder_->set_unsafe_es3_apis_enabled(false);
4708 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4711 else:
4712 valid_test += """
4713 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4714 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4717 self.WriteValidUnitTest(func, f, valid_test, *extras)
4719 if not func.IsUnsafe():
4720 invalid_test = """
4721 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4722 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4723 SpecializedSetup<cmds::%(name)s, 0>(false);
4724 cmds::%(name)s cmd;
4725 cmd.Init(%(args)s);
4726 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4729 self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
4731 def WriteImmediateServiceUnitTest(self, func, f, *extras):
4732 """Writes the service unit test for an immediate command."""
4733 f.write("// TODO(gman): %s\n" % func.name)
4735 def WriteImmediateValidationCode(self, func, f):
4736 """Writes the validation code for an immediate version of a command."""
4737 pass
4739 def WriteBucketServiceUnitTest(self, func, f, *extras):
4740 """Writes the service unit test for a bucket command."""
4741 f.write("// TODO(gman): %s\n" % func.name)
4743 def WriteGLES2ImplementationDeclaration(self, func, f):
4744 """Writes the GLES2 Implemention declaration."""
4745 impl_decl = func.GetInfo('impl_decl')
4746 if impl_decl == None or impl_decl == True:
4747 f.write("%s %s(%s) override;\n" %
4748 (func.return_type, func.original_name,
4749 func.MakeTypedOriginalArgString("")))
4750 f.write("\n")
4752 def WriteGLES2CLibImplementation(self, func, f):
4753 f.write("%s GL_APIENTRY GLES2%s(%s) {\n" %
4754 (func.return_type, func.name,
4755 func.MakeTypedOriginalArgString("")))
4756 result_string = "return "
4757 if func.return_type == "void":
4758 result_string = ""
4759 f.write(" %sgles2::GetGLContext()->%s(%s);\n" %
4760 (result_string, func.original_name,
4761 func.MakeOriginalArgString("")))
4762 f.write("}\n")
4764 def WriteGLES2Header(self, func, f):
4765 """Writes a re-write macro for GLES"""
4766 f.write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
4768 def WriteClientGLCallLog(self, func, f):
4769 """Writes a logging macro for the client side code."""
4770 comma = ""
4771 if len(func.GetOriginalArgs()):
4772 comma = " << "
4773 f.write(
4774 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4775 (func.original_name, comma, func.MakeLogArgString()))
4777 def WriteClientGLReturnLog(self, func, f):
4778 """Writes the return value logging code."""
4779 if func.return_type != "void":
4780 f.write(' GPU_CLIENT_LOG("return:" << result)\n')
4782 def WriteGLES2ImplementationHeader(self, func, f):
4783 """Writes the GLES2 Implemention."""
4784 self.WriteGLES2ImplementationDeclaration(func, f)
4786 def WriteGLES2TraceImplementationHeader(self, func, f):
4787 """Writes the GLES2 Trace Implemention header."""
4788 f.write("%s %s(%s) override;\n" %
4789 (func.return_type, func.original_name,
4790 func.MakeTypedOriginalArgString("")))
4792 def WriteGLES2TraceImplementation(self, func, f):
4793 """Writes the GLES2 Trace Implemention."""
4794 f.write("%s GLES2TraceImplementation::%s(%s) {\n" %
4795 (func.return_type, func.original_name,
4796 func.MakeTypedOriginalArgString("")))
4797 result_string = "return "
4798 if func.return_type == "void":
4799 result_string = ""
4800 f.write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4801 func.name)
4802 f.write(" %sgl_->%s(%s);\n" %
4803 (result_string, func.name, func.MakeOriginalArgString("")))
4804 f.write("}\n")
4805 f.write("\n")
4807 def WriteGLES2Implementation(self, func, f):
4808 """Writes the GLES2 Implemention."""
4809 impl_func = func.GetInfo('impl_func')
4810 impl_decl = func.GetInfo('impl_decl')
4811 gen_cmd = func.GetInfo('gen_cmd')
4812 if (func.can_auto_generate and
4813 (impl_func == None or impl_func == True) and
4814 (impl_decl == None or impl_decl == True) and
4815 (gen_cmd == None or gen_cmd == True)):
4816 f.write("%s GLES2Implementation::%s(%s) {\n" %
4817 (func.return_type, func.original_name,
4818 func.MakeTypedOriginalArgString("")))
4819 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4820 self.WriteClientGLCallLog(func, f)
4821 func.WriteDestinationInitalizationValidation(f)
4822 for arg in func.GetOriginalArgs():
4823 arg.WriteClientSideValidationCode(f, func)
4824 f.write(" helper_->%s(%s);\n" %
4825 (func.name, func.MakeHelperArgString("")))
4826 f.write(" CheckGLError();\n")
4827 self.WriteClientGLReturnLog(func, f)
4828 f.write("}\n")
4829 f.write("\n")
4831 def WriteGLES2InterfaceHeader(self, func, f):
4832 """Writes the GLES2 Interface."""
4833 f.write("virtual %s %s(%s) = 0;\n" %
4834 (func.return_type, func.original_name,
4835 func.MakeTypedOriginalArgString("")))
4837 def WriteMojoGLES2ImplHeader(self, func, f):
4838 """Writes the Mojo GLES2 implementation header."""
4839 f.write("%s %s(%s) override;\n" %
4840 (func.return_type, func.original_name,
4841 func.MakeTypedOriginalArgString("")))
4843 def WriteMojoGLES2Impl(self, func, f):
4844 """Writes the Mojo GLES2 implementation."""
4845 f.write("%s MojoGLES2Impl::%s(%s) {\n" %
4846 (func.return_type, func.original_name,
4847 func.MakeTypedOriginalArgString("")))
4848 extensions = ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4849 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4850 "occlusion_query_EXT", "CHROMIUM_image",
4851 "CHROMIUM_copy_texture",
4852 "CHROMIUM_pixel_transfer_buffer_object"]
4853 if func.IsCoreGLFunction() or func.GetInfo("extension") in extensions:
4854 f.write("MojoGLES2MakeCurrent(context_);");
4855 func_return = "gl" + func.original_name + "(" + \
4856 func.MakeOriginalArgString("") + ");"
4857 if func.return_type == "void":
4858 f.write(func_return);
4859 else:
4860 f.write("return " + func_return);
4861 else:
4862 f.write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4863 func.original_name);
4864 if func.return_type != "void":
4865 f.write("return 0;")
4866 f.write("}")
4868 def WriteGLES2InterfaceStub(self, func, f):
4869 """Writes the GLES2 Interface stub declaration."""
4870 f.write("%s %s(%s) override;\n" %
4871 (func.return_type, func.original_name,
4872 func.MakeTypedOriginalArgString("")))
4874 def WriteGLES2InterfaceStubImpl(self, func, f):
4875 """Writes the GLES2 Interface stub declaration."""
4876 args = func.GetOriginalArgs()
4877 arg_string = ", ".join(
4878 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
4879 f.write("%s GLES2InterfaceStub::%s(%s) {\n" %
4880 (func.return_type, func.original_name, arg_string))
4881 if func.return_type != "void":
4882 f.write(" return 0;\n")
4883 f.write("}\n")
4885 def WriteGLES2ImplementationUnitTest(self, func, f):
4886 """Writes the GLES2 Implemention unit test."""
4887 client_test = func.GetInfo('client_test')
4888 if (func.can_auto_generate and
4889 (client_test == None or client_test == True)):
4890 code = """
4891 TEST_F(GLES2ImplementationTest, %(name)s) {
4892 struct Cmds {
4893 cmds::%(name)s cmd;
4895 Cmds expected;
4896 expected.cmd.Init(%(cmd_args)s);
4898 gl_->%(name)s(%(args)s);
4899 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4902 cmd_arg_strings = [
4903 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4906 gl_arg_strings = [
4907 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4910 f.write(code % {
4911 'name': func.name,
4912 'args': ", ".join(gl_arg_strings),
4913 'cmd_args': ", ".join(cmd_arg_strings),
4916 # Test constants for invalid values, as they are not tested by the
4917 # service.
4918 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
4919 if constants:
4920 code = """
4921 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4922 gl_->%(name)s(%(args)s);
4923 EXPECT_TRUE(NoCommandsWritten());
4924 EXPECT_EQ(%(gl_error)s, CheckError());
4927 for invalid_arg in constants:
4928 gl_arg_strings = []
4929 invalid = invalid_arg.GetInvalidArg(func)
4930 for arg in func.GetOriginalArgs():
4931 if arg is invalid_arg:
4932 gl_arg_strings.append(invalid[0])
4933 else:
4934 gl_arg_strings.append(arg.GetValidClientSideArg(func))
4936 f.write(code % {
4937 'name': func.name,
4938 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
4939 'args': ", ".join(gl_arg_strings),
4940 'gl_error': invalid[2],
4942 else:
4943 if client_test != False:
4944 f.write("// TODO(zmo): Implement unit test for %s\n" % func.name)
4946 def WriteDestinationInitalizationValidation(self, func, f):
4947 """Writes the client side destintion initialization validation."""
4948 for arg in func.GetOriginalArgs():
4949 arg.WriteDestinationInitalizationValidation(f, func)
4951 def WriteTraceEvent(self, func, f):
4952 f.write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4953 func.original_name)
4955 def WriteImmediateCmdComputeSize(self, func, f):
4956 """Writes the size computation code for the immediate version of a cmd."""
4957 f.write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4958 f.write(" return static_cast<uint32_t>(\n")
4959 f.write(" sizeof(ValueType) + // NOLINT\n")
4960 f.write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4961 f.write(" }\n")
4962 f.write("\n")
4964 def WriteImmediateCmdSetHeader(self, func, f):
4965 """Writes the SetHeader function for the immediate version of a cmd."""
4966 f.write(" void SetHeader(uint32_t size_in_bytes) {\n")
4967 f.write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4968 f.write(" }\n")
4969 f.write("\n")
4971 def WriteImmediateCmdInit(self, func, f):
4972 """Writes the Init function for the immediate version of a command."""
4973 raise NotImplementedError(func.name)
4975 def WriteImmediateCmdSet(self, func, f):
4976 """Writes the Set function for the immediate version of a command."""
4977 raise NotImplementedError(func.name)
4979 def WriteCmdHelper(self, func, f):
4980 """Writes the cmd helper definition for a cmd."""
4981 code = """ void %(name)s(%(typed_args)s) {
4982 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4983 if (c) {
4984 c->Init(%(args)s);
4989 f.write(code % {
4990 "name": func.name,
4991 "typed_args": func.MakeTypedCmdArgString(""),
4992 "args": func.MakeCmdArgString(""),
4995 def WriteImmediateCmdHelper(self, func, f):
4996 """Writes the cmd helper definition for the immediate version of a cmd."""
4997 code = """ void %(name)s(%(typed_args)s) {
4998 const uint32_t s = 0; // TODO(gman): compute correct size
4999 gles2::cmds::%(name)s* c =
5000 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
5001 if (c) {
5002 c->Init(%(args)s);
5007 f.write(code % {
5008 "name": func.name,
5009 "typed_args": func.MakeTypedCmdArgString(""),
5010 "args": func.MakeCmdArgString(""),
5014 class StateSetHandler(TypeHandler):
5015 """Handler for commands that simply set state."""
5017 def WriteHandlerImplementation(self, func, f):
5018 """Overrriden from TypeHandler."""
5019 state_name = func.GetInfo('state')
5020 state = _STATES[state_name]
5021 states = state['states']
5022 args = func.GetOriginalArgs()
5023 for ndx,item in enumerate(states):
5024 code = []
5025 if 'range_checks' in item:
5026 for range_check in item['range_checks']:
5027 code.append("%s %s" % (args[ndx].name, range_check['check']))
5028 if 'nan_check' in item:
5029 # Drivers might generate an INVALID_VALUE error when a value is set
5030 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
5031 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
5032 # Make this behavior consistent within Chromium, and avoid leaking GL
5033 # errors by generating the error in the command buffer instead of
5034 # letting the GL driver generate it.
5035 code.append("std::isnan(%s)" % args[ndx].name)
5036 if len(code):
5037 f.write(" if (%s) {\n" % " ||\n ".join(code))
5038 f.write(
5039 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
5040 ' "%s", "%s out of range");\n' %
5041 (func.name, args[ndx].name))
5042 f.write(" return error::kNoError;\n")
5043 f.write(" }\n")
5044 code = []
5045 for ndx,item in enumerate(states):
5046 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
5047 f.write(" if (%s) {\n" % " ||\n ".join(code))
5048 for ndx,item in enumerate(states):
5049 f.write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
5050 if 'state_flag' in state:
5051 f.write(" %s = true;\n" % state['state_flag'])
5052 if not func.GetInfo("no_gl"):
5053 for ndx,item in enumerate(states):
5054 if item.get('cached', False):
5055 f.write(" state_.%s = %s;\n" %
5056 (CachedStateName(item), args[ndx].name))
5057 f.write(" %s(%s);\n" %
5058 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5059 f.write(" }\n")
5061 def WriteServiceUnitTest(self, func, f, *extras):
5062 """Overrriden from TypeHandler."""
5063 TypeHandler.WriteServiceUnitTest(self, func, f, *extras)
5064 state_name = func.GetInfo('state')
5065 state = _STATES[state_name]
5066 states = state['states']
5067 for ndx,item in enumerate(states):
5068 if 'range_checks' in item:
5069 for check_ndx, range_check in enumerate(item['range_checks']):
5070 valid_test = """
5071 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
5072 SpecializedSetup<cmds::%(name)s, 0>(false);
5073 cmds::%(name)s cmd;
5074 cmd.Init(%(args)s);
5075 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5076 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5079 name = func.name
5080 arg_strings = [
5081 arg.GetValidArg(func) \
5082 for arg in func.GetOriginalArgs() if not arg.IsConstant()
5085 arg_strings[ndx] = range_check['test_value']
5086 vars = {
5087 'name': name,
5088 'ndx': ndx,
5089 'check_ndx': check_ndx,
5090 'args': ", ".join(arg_strings),
5092 for extra in extras:
5093 vars.update(extra)
5094 f.write(valid_test % vars)
5095 if 'nan_check' in item:
5096 valid_test = """
5097 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
5098 SpecializedSetup<cmds::%(name)s, 0>(false);
5099 cmds::%(name)s cmd;
5100 cmd.Init(%(args)s);
5101 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5102 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
5105 name = func.name
5106 arg_strings = [
5107 arg.GetValidArg(func) \
5108 for arg in func.GetOriginalArgs() if not arg.IsConstant()
5111 arg_strings[ndx] = 'nanf("")'
5112 vars = {
5113 'name': name,
5114 'ndx': ndx,
5115 'args': ", ".join(arg_strings),
5117 for extra in extras:
5118 vars.update(extra)
5119 f.write(valid_test % vars)
5122 class StateSetRGBAlphaHandler(TypeHandler):
5123 """Handler for commands that simply set state that have rgb/alpha."""
5125 def WriteHandlerImplementation(self, func, f):
5126 """Overrriden from TypeHandler."""
5127 state_name = func.GetInfo('state')
5128 state = _STATES[state_name]
5129 states = state['states']
5130 args = func.GetOriginalArgs()
5131 num_args = len(args)
5132 code = []
5133 for ndx,item in enumerate(states):
5134 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
5135 f.write(" if (%s) {\n" % " ||\n ".join(code))
5136 for ndx, item in enumerate(states):
5137 f.write(" state_.%s = %s;\n" %
5138 (item['name'], args[ndx % num_args].name))
5139 if 'state_flag' in state:
5140 f.write(" %s = true;\n" % state['state_flag'])
5141 if not func.GetInfo("no_gl"):
5142 f.write(" %s(%s);\n" %
5143 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5144 f.write(" }\n")
5147 class StateSetFrontBackSeparateHandler(TypeHandler):
5148 """Handler for commands that simply set state that have front/back."""
5150 def WriteHandlerImplementation(self, func, f):
5151 """Overrriden from TypeHandler."""
5152 state_name = func.GetInfo('state')
5153 state = _STATES[state_name]
5154 states = state['states']
5155 args = func.GetOriginalArgs()
5156 face = args[0].name
5157 num_args = len(args)
5158 f.write(" bool changed = false;\n")
5159 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
5160 f.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5161 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
5162 code = []
5163 for ndx, item in enumerate(group):
5164 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
5165 f.write(" changed |= %s;\n" % " ||\n ".join(code))
5166 f.write(" }\n")
5167 f.write(" if (changed) {\n")
5168 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
5169 f.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
5170 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
5171 for ndx, item in enumerate(group):
5172 f.write(" state_.%s = %s;\n" %
5173 (item['name'], args[ndx + 1].name))
5174 f.write(" }\n")
5175 if 'state_flag' in state:
5176 f.write(" %s = true;\n" % state['state_flag'])
5177 if not func.GetInfo("no_gl"):
5178 f.write(" %s(%s);\n" %
5179 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5180 f.write(" }\n")
5183 class StateSetFrontBackHandler(TypeHandler):
5184 """Handler for commands that simply set state that set both front/back."""
5186 def WriteHandlerImplementation(self, func, f):
5187 """Overrriden from TypeHandler."""
5188 state_name = func.GetInfo('state')
5189 state = _STATES[state_name]
5190 states = state['states']
5191 args = func.GetOriginalArgs()
5192 num_args = len(args)
5193 code = []
5194 for group_ndx, group in enumerate(Grouper(num_args, states)):
5195 for ndx, item in enumerate(group):
5196 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
5197 f.write(" if (%s) {\n" % " ||\n ".join(code))
5198 for group_ndx, group in enumerate(Grouper(num_args, states)):
5199 for ndx, item in enumerate(group):
5200 f.write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
5201 if 'state_flag' in state:
5202 f.write(" %s = true;\n" % state['state_flag'])
5203 if not func.GetInfo("no_gl"):
5204 f.write(" %s(%s);\n" %
5205 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5206 f.write(" }\n")
5209 class StateSetNamedParameter(TypeHandler):
5210 """Handler for commands that set a state chosen with an enum parameter."""
5212 def WriteHandlerImplementation(self, func, f):
5213 """Overridden from TypeHandler."""
5214 state_name = func.GetInfo('state')
5215 state = _STATES[state_name]
5216 states = state['states']
5217 args = func.GetOriginalArgs()
5218 num_args = len(args)
5219 assert num_args == 2
5220 f.write(" switch (%s) {\n" % args[0].name)
5221 for state in states:
5222 f.write(" case %s:\n" % state['enum'])
5223 f.write(" if (state_.%s != %s) {\n" %
5224 (state['name'], args[1].name))
5225 f.write(" state_.%s = %s;\n" % (state['name'], args[1].name))
5226 if not func.GetInfo("no_gl"):
5227 f.write(" %s(%s);\n" %
5228 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
5229 f.write(" }\n")
5230 f.write(" break;\n")
5231 f.write(" default:\n")
5232 f.write(" NOTREACHED();\n")
5233 f.write(" }\n")
5236 class CustomHandler(TypeHandler):
5237 """Handler for commands that are auto-generated but require minor tweaks."""
5239 def WriteServiceImplementation(self, func, f):
5240 """Overrriden from TypeHandler."""
5241 pass
5243 def WriteImmediateServiceImplementation(self, func, f):
5244 """Overrriden from TypeHandler."""
5245 pass
5247 def WriteBucketServiceImplementation(self, func, f):
5248 """Overrriden from TypeHandler."""
5249 pass
5251 def WriteServiceUnitTest(self, func, f, *extras):
5252 """Overrriden from TypeHandler."""
5253 f.write("// TODO(gman): %s\n\n" % func.name)
5255 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5256 """Overrriden from TypeHandler."""
5257 f.write("// TODO(gman): %s\n\n" % func.name)
5259 def WriteImmediateCmdGetTotalSize(self, func, f):
5260 """Overrriden from TypeHandler."""
5261 f.write(
5262 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
5264 def WriteImmediateCmdInit(self, func, f):
5265 """Overrriden from TypeHandler."""
5266 f.write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5267 self.WriteImmediateCmdGetTotalSize(func, f)
5268 f.write(" SetHeader(total_size);\n")
5269 args = func.GetCmdArgs()
5270 for arg in args:
5271 f.write(" %s = _%s;\n" % (arg.name, arg.name))
5272 f.write(" }\n")
5273 f.write("\n")
5275 def WriteImmediateCmdSet(self, func, f):
5276 """Overrriden from TypeHandler."""
5277 copy_args = func.MakeCmdArgString("_", False)
5278 f.write(" void* Set(void* cmd%s) {\n" %
5279 func.MakeTypedCmdArgString("_", True))
5280 self.WriteImmediateCmdGetTotalSize(func, f)
5281 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5282 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5283 "cmd, total_size);\n")
5284 f.write(" }\n")
5285 f.write("\n")
5288 class HandWrittenHandler(CustomHandler):
5289 """Handler for comands where everything must be written by hand."""
5291 def InitFunction(self, func):
5292 """Add or adjust anything type specific for this function."""
5293 CustomHandler.InitFunction(self, func)
5294 func.can_auto_generate = False
5296 def NeedsDataTransferFunction(self, func):
5297 """Overriden from TypeHandler."""
5298 # If specified explicitly, force the data transfer method.
5299 if func.GetInfo('data_transfer_methods'):
5300 return True
5301 return False
5303 def WriteStruct(self, func, f):
5304 """Overrriden from TypeHandler."""
5305 pass
5307 def WriteDocs(self, func, f):
5308 """Overrriden from TypeHandler."""
5309 pass
5311 def WriteServiceUnitTest(self, func, f, *extras):
5312 """Overrriden from TypeHandler."""
5313 f.write("// TODO(gman): %s\n\n" % func.name)
5315 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5316 """Overrriden from TypeHandler."""
5317 f.write("// TODO(gman): %s\n\n" % func.name)
5319 def WriteBucketServiceUnitTest(self, func, f, *extras):
5320 """Overrriden from TypeHandler."""
5321 f.write("// TODO(gman): %s\n\n" % func.name)
5323 def WriteServiceImplementation(self, func, f):
5324 """Overrriden from TypeHandler."""
5325 pass
5327 def WriteImmediateServiceImplementation(self, func, f):
5328 """Overrriden from TypeHandler."""
5329 pass
5331 def WriteBucketServiceImplementation(self, func, f):
5332 """Overrriden from TypeHandler."""
5333 pass
5335 def WriteImmediateCmdHelper(self, func, f):
5336 """Overrriden from TypeHandler."""
5337 pass
5339 def WriteCmdHelper(self, func, f):
5340 """Overrriden from TypeHandler."""
5341 pass
5343 def WriteFormatTest(self, func, f):
5344 """Overrriden from TypeHandler."""
5345 f.write("// TODO(gman): Write test for %s\n" % func.name)
5347 def WriteImmediateFormatTest(self, func, f):
5348 """Overrriden from TypeHandler."""
5349 f.write("// TODO(gman): Write test for %s\n" % func.name)
5352 class ManualHandler(CustomHandler):
5353 """Handler for commands who's handlers must be written by hand."""
5355 def InitFunction(self, func):
5356 """Overrriden from TypeHandler."""
5357 if (func.name == 'CompressedTexImage2DBucket' or
5358 func.name == 'CompressedTexImage3DBucket'):
5359 func.cmd_args = func.cmd_args[:-1]
5360 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5361 else:
5362 CustomHandler.InitFunction(self, func)
5364 def WriteServiceImplementation(self, func, f):
5365 """Overrriden from TypeHandler."""
5366 pass
5368 def WriteBucketServiceImplementation(self, func, f):
5369 """Overrriden from TypeHandler."""
5370 pass
5372 def WriteServiceUnitTest(self, func, f, *extras):
5373 """Overrriden from TypeHandler."""
5374 f.write("// TODO(gman): %s\n\n" % func.name)
5376 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5377 """Overrriden from TypeHandler."""
5378 f.write("// TODO(gman): %s\n\n" % func.name)
5380 def WriteImmediateServiceImplementation(self, func, f):
5381 """Overrriden from TypeHandler."""
5382 pass
5384 def WriteImmediateFormatTest(self, func, f):
5385 """Overrriden from TypeHandler."""
5386 f.write("// TODO(gman): Implement test for %s\n" % func.name)
5388 def WriteGLES2Implementation(self, func, f):
5389 """Overrriden from TypeHandler."""
5390 if func.GetInfo('impl_func'):
5391 super(ManualHandler, self).WriteGLES2Implementation(func, f)
5393 def WriteGLES2ImplementationHeader(self, func, f):
5394 """Overrriden from TypeHandler."""
5395 f.write("%s %s(%s) override;\n" %
5396 (func.return_type, func.original_name,
5397 func.MakeTypedOriginalArgString("")))
5398 f.write("\n")
5400 def WriteImmediateCmdGetTotalSize(self, func, f):
5401 """Overrriden from TypeHandler."""
5402 # TODO(gman): Move this data to _FUNCTION_INFO?
5403 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, f)
5406 class DataHandler(TypeHandler):
5407 """Handler for glBufferData, glBufferSubData, glTexImage*D, glTexSubImage*D,
5408 glCompressedTexImage*D, glCompressedTexImageSub*D."""
5410 def InitFunction(self, func):
5411 """Overrriden from TypeHandler."""
5412 if (func.name == 'CompressedTexSubImage2DBucket' or
5413 func.name == 'CompressedTexSubImage3DBucket'):
5414 func.cmd_args = func.cmd_args[:-1]
5415 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
5417 def WriteGetDataSizeCode(self, func, f):
5418 """Overrriden from TypeHandler."""
5419 # TODO(gman): Move this data to _FUNCTION_INFO?
5420 name = func.name
5421 if name.endswith("Immediate"):
5422 name = name[0:-9]
5423 if name == 'BufferData' or name == 'BufferSubData':
5424 f.write(" uint32_t data_size = size;\n")
5425 elif (name == 'CompressedTexImage2D' or
5426 name == 'CompressedTexSubImage2D' or
5427 name == 'CompressedTexImage3D' or
5428 name == 'CompressedTexSubImage3D'):
5429 f.write(" uint32_t data_size = imageSize;\n")
5430 elif (name == 'CompressedTexSubImage2DBucket' or
5431 name == 'CompressedTexSubImage3DBucket'):
5432 f.write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
5433 f.write(" uint32_t data_size = bucket->size();\n")
5434 f.write(" GLsizei imageSize = data_size;\n")
5435 elif name == 'TexImage2D' or name == 'TexSubImage2D':
5436 code = """ uint32_t data_size;
5437 if (!GLES2Util::ComputeImageDataSize(
5438 width, height, format, type, unpack_alignment_, &data_size)) {
5439 return error::kOutOfBounds;
5442 f.write(code)
5443 else:
5444 f.write(
5445 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
5447 def WriteImmediateCmdGetTotalSize(self, func, f):
5448 """Overrriden from TypeHandler."""
5449 pass
5451 def WriteImmediateCmdInit(self, func, f):
5452 """Overrriden from TypeHandler."""
5453 f.write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
5454 self.WriteImmediateCmdGetTotalSize(func, f)
5455 f.write(" SetHeader(total_size);\n")
5456 args = func.GetCmdArgs()
5457 for arg in args:
5458 f.write(" %s = _%s;\n" % (arg.name, arg.name))
5459 f.write(" }\n")
5460 f.write("\n")
5462 def WriteImmediateCmdSet(self, func, f):
5463 """Overrriden from TypeHandler."""
5464 copy_args = func.MakeCmdArgString("_", False)
5465 f.write(" void* Set(void* cmd%s) {\n" %
5466 func.MakeTypedCmdArgString("_", True))
5467 self.WriteImmediateCmdGetTotalSize(func, f)
5468 f.write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
5469 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5470 "cmd, total_size);\n")
5471 f.write(" }\n")
5472 f.write("\n")
5474 def WriteImmediateFormatTest(self, func, f):
5475 """Overrriden from TypeHandler."""
5476 # TODO(gman): Remove this exception.
5477 f.write("// TODO(gman): Implement test for %s\n" % func.name)
5478 return
5480 def WriteServiceUnitTest(self, func, f, *extras):
5481 """Overrriden from TypeHandler."""
5482 f.write("// TODO(gman): %s\n\n" % func.name)
5484 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5485 """Overrriden from TypeHandler."""
5486 f.write("// TODO(gman): %s\n\n" % func.name)
5488 def WriteBucketServiceImplementation(self, func, f):
5489 """Overrriden from TypeHandler."""
5490 if ((not func.name == 'CompressedTexSubImage2DBucket') and
5491 (not func.name == 'CompressedTexSubImage3DBucket')):
5492 TypeHandler.WriteBucketServiceImplemenation(self, func, f)
5495 class BindHandler(TypeHandler):
5496 """Handler for glBind___ type functions."""
5498 def WriteServiceUnitTest(self, func, f, *extras):
5499 """Overrriden from TypeHandler."""
5501 if len(func.GetOriginalArgs()) == 1:
5502 valid_test = """
5503 TEST_P(%(test_name)s, %(name)sValidArgs) {
5504 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5505 SpecializedSetup<cmds::%(name)s, 0>(true);
5506 cmds::%(name)s cmd;
5507 cmd.Init(%(args)s);"""
5508 if func.IsUnsafe():
5509 valid_test += """
5510 decoder_->set_unsafe_es3_apis_enabled(true);
5511 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5512 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5513 decoder_->set_unsafe_es3_apis_enabled(false);
5514 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5517 else:
5518 valid_test += """
5519 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5520 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5523 if func.GetInfo("gen_func"):
5524 valid_test += """
5525 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5526 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
5527 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5528 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5529 SpecializedSetup<cmds::%(name)s, 0>(true);
5530 cmds::%(name)s cmd;
5531 cmd.Init(kNewClientId);
5532 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5533 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5534 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5537 self.WriteValidUnitTest(func, f, valid_test, {
5538 'resource_type': func.GetOriginalArgs()[0].resource_type,
5539 'gl_gen_func_name': func.GetInfo("gen_func"),
5540 }, *extras)
5541 else:
5542 valid_test = """
5543 TEST_P(%(test_name)s, %(name)sValidArgs) {
5544 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
5545 SpecializedSetup<cmds::%(name)s, 0>(true);
5546 cmds::%(name)s cmd;
5547 cmd.Init(%(args)s);"""
5548 if func.IsUnsafe():
5549 valid_test += """
5550 decoder_->set_unsafe_es3_apis_enabled(true);
5551 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5552 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5553 decoder_->set_unsafe_es3_apis_enabled(false);
5554 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5557 else:
5558 valid_test += """
5559 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5560 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5563 if func.GetInfo("gen_func"):
5564 valid_test += """
5565 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5566 EXPECT_CALL(*gl_,
5567 %(gl_func_name)s(%(gl_args_with_new_id)s));
5568 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5569 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5570 SpecializedSetup<cmds::%(name)s, 0>(true);
5571 cmds::%(name)s cmd;
5572 cmd.Init(%(args_with_new_id)s);"""
5573 if func.IsUnsafe():
5574 valid_test += """
5575 decoder_->set_unsafe_es3_apis_enabled(true);
5576 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5577 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5578 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5579 decoder_->set_unsafe_es3_apis_enabled(false);
5580 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5583 else:
5584 valid_test += """
5585 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5586 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5587 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5591 gl_args_with_new_id = []
5592 args_with_new_id = []
5593 for arg in func.GetOriginalArgs():
5594 if hasattr(arg, 'resource_type'):
5595 gl_args_with_new_id.append('kNewServiceId')
5596 args_with_new_id.append('kNewClientId')
5597 else:
5598 gl_args_with_new_id.append(arg.GetValidGLArg(func))
5599 args_with_new_id.append(arg.GetValidArg(func))
5600 self.WriteValidUnitTest(func, f, valid_test, {
5601 'args_with_new_id': ", ".join(args_with_new_id),
5602 'gl_args_with_new_id': ", ".join(gl_args_with_new_id),
5603 'resource_type': func.GetResourceIdArg().resource_type,
5604 'gl_gen_func_name': func.GetInfo("gen_func"),
5605 }, *extras)
5607 invalid_test = """
5608 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5609 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5610 SpecializedSetup<cmds::%(name)s, 0>(false);
5611 cmds::%(name)s cmd;
5612 cmd.Init(%(args)s);
5613 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5616 self.WriteInvalidUnitTest(func, f, invalid_test, *extras)
5618 def WriteGLES2Implementation(self, func, f):
5619 """Writes the GLES2 Implemention."""
5621 impl_func = func.GetInfo('impl_func')
5622 impl_decl = func.GetInfo('impl_decl')
5624 if (func.can_auto_generate and
5625 (impl_func == None or impl_func == True) and
5626 (impl_decl == None or impl_decl == True)):
5628 f.write("%s GLES2Implementation::%s(%s) {\n" %
5629 (func.return_type, func.original_name,
5630 func.MakeTypedOriginalArgString("")))
5631 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5632 func.WriteDestinationInitalizationValidation(f)
5633 self.WriteClientGLCallLog(func, f)
5634 for arg in func.GetOriginalArgs():
5635 arg.WriteClientSideValidationCode(f, func)
5637 code = """ if (Is%(type)sReservedId(%(id)s)) {
5638 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5639 return;
5641 %(name)sHelper(%(arg_string)s);
5642 CheckGLError();
5646 name_arg = func.GetResourceIdArg()
5647 f.write(code % {
5648 'name': func.name,
5649 'arg_string': func.MakeOriginalArgString(""),
5650 'id': name_arg.name,
5651 'type': name_arg.resource_type,
5652 'lc_type': name_arg.resource_type.lower(),
5655 def WriteGLES2ImplementationUnitTest(self, func, f):
5656 """Overrriden from TypeHandler."""
5657 client_test = func.GetInfo('client_test')
5658 if client_test == False:
5659 return
5660 code = """
5661 TEST_F(GLES2ImplementationTest, %(name)s) {
5662 struct Cmds {
5663 cmds::%(name)s cmd;
5665 Cmds expected;
5666 expected.cmd.Init(%(cmd_args)s);
5668 gl_->%(name)s(%(args)s);
5669 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5670 if not func.IsUnsafe():
5671 code += """
5672 ClearCommands();
5673 gl_->%(name)s(%(args)s);
5674 EXPECT_TRUE(NoCommandsWritten());"""
5675 code += """
5678 cmd_arg_strings = [
5679 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
5681 gl_arg_strings = [
5682 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
5685 f.write(code % {
5686 'name': func.name,
5687 'args': ", ".join(gl_arg_strings),
5688 'cmd_args': ", ".join(cmd_arg_strings),
5692 class GENnHandler(TypeHandler):
5693 """Handler for glGen___ type functions."""
5695 def InitFunction(self, func):
5696 """Overrriden from TypeHandler."""
5697 pass
5699 def WriteGetDataSizeCode(self, func, f):
5700 """Overrriden from TypeHandler."""
5701 code = """ uint32_t data_size;
5702 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5703 return error::kOutOfBounds;
5706 f.write(code)
5708 def WriteHandlerImplementation (self, func, f):
5709 """Overrriden from TypeHandler."""
5710 f.write(" if (!%sHelper(n, %s)) {\n"
5711 " return error::kInvalidArguments;\n"
5712 " }\n" %
5713 (func.name, func.GetLastOriginalArg().name))
5715 def WriteImmediateHandlerImplementation(self, func, f):
5716 """Overrriden from TypeHandler."""
5717 if func.IsUnsafe():
5718 f.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5719 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5720 return error::kInvalidArguments;
5723 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5724 gl%(func_name)s(n, service_ids.get());
5725 for (GLsizei ii = 0; ii < n; ++ii) {
5726 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5728 """ % { 'func_name': func.original_name,
5729 'last_arg_name': func.GetLastOriginalArg().name,
5730 'resource_name': func.GetInfo('resource_type') })
5731 else:
5732 f.write(" if (!%sHelper(n, %s)) {\n"
5733 " return error::kInvalidArguments;\n"
5734 " }\n" %
5735 (func.original_name, func.GetLastOriginalArg().name))
5737 def WriteGLES2Implementation(self, func, f):
5738 """Overrriden from TypeHandler."""
5739 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
5740 for (GLsizei i = 0; i < n; ++i) {
5741 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5743 });""" % func.GetOriginalArgs()[1].name)
5744 args = {
5745 'log_code': log_code,
5746 'return_type': func.return_type,
5747 'name': func.original_name,
5748 'typed_args': func.MakeTypedOriginalArgString(""),
5749 'args': func.MakeOriginalArgString(""),
5750 'resource_types': func.GetInfo('resource_types'),
5751 'count_name': func.GetOriginalArgs()[0].name,
5753 f.write(
5754 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5755 args)
5756 func.WriteDestinationInitalizationValidation(f)
5757 self.WriteClientGLCallLog(func, f)
5758 for arg in func.GetOriginalArgs():
5759 arg.WriteClientSideValidationCode(f, func)
5760 not_shared = func.GetInfo('not_shared')
5761 if not_shared:
5762 alloc_code = (
5764 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5765 for (GLsizei ii = 0; ii < n; ++ii)
5766 %s[ii] = id_allocator->AllocateID();""" %
5767 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
5768 else:
5769 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5770 MakeIds(this, 0, %(args)s);""" % args)
5771 args['alloc_code'] = alloc_code
5773 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5774 %(alloc_code)s
5775 %(name)sHelper(%(args)s);
5776 helper_->%(name)sImmediate(%(args)s);
5777 if (share_group_->bind_generates_resource())
5778 helper_->CommandBufferHelper::Flush();
5779 %(log_code)s
5780 CheckGLError();
5784 f.write(code % args)
5786 def WriteGLES2ImplementationUnitTest(self, func, f):
5787 """Overrriden from TypeHandler."""
5788 code = """
5789 TEST_F(GLES2ImplementationTest, %(name)s) {
5790 GLuint ids[2] = { 0, };
5791 struct Cmds {
5792 cmds::%(name)sImmediate gen;
5793 GLuint data[2];
5795 Cmds expected;
5796 expected.gen.Init(arraysize(ids), &ids[0]);
5797 expected.data[0] = k%(types)sStartId;
5798 expected.data[1] = k%(types)sStartId + 1;
5799 gl_->%(name)s(arraysize(ids), &ids[0]);
5800 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5801 EXPECT_EQ(k%(types)sStartId, ids[0]);
5802 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5805 f.write(code % {
5806 'name': func.name,
5807 'types': func.GetInfo('resource_types'),
5810 def WriteServiceUnitTest(self, func, f, *extras):
5811 """Overrriden from TypeHandler."""
5812 valid_test = """
5813 TEST_P(%(test_name)s, %(name)sValidArgs) {
5814 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5815 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5816 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5817 SpecializedSetup<cmds::%(name)s, 0>(true);
5818 cmds::%(name)s cmd;
5819 cmd.Init(%(args)s);
5820 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5821 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5822 if func.IsUnsafe():
5823 valid_test += """
5824 GLuint service_id;
5825 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5826 EXPECT_EQ(kNewServiceId, service_id)
5829 else:
5830 valid_test += """
5831 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5834 self.WriteValidUnitTest(func, f, valid_test, {
5835 'resource_name': func.GetInfo('resource_type'),
5836 }, *extras)
5837 invalid_test = """
5838 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5839 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5840 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5841 SpecializedSetup<cmds::%(name)s, 0>(false);
5842 cmds::%(name)s cmd;
5843 cmd.Init(%(args)s);
5844 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5847 self.WriteValidUnitTest(func, f, invalid_test, {
5848 'resource_name': func.GetInfo('resource_type').lower(),
5849 }, *extras)
5851 def WriteImmediateServiceUnitTest(self, func, f, *extras):
5852 """Overrriden from TypeHandler."""
5853 valid_test = """
5854 TEST_P(%(test_name)s, %(name)sValidArgs) {
5855 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5856 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5857 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5858 GLuint temp = kNewClientId;
5859 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5860 if func.IsUnsafe():
5861 valid_test += """
5862 decoder_->set_unsafe_es3_apis_enabled(true);"""
5863 valid_test += """
5864 cmd->Init(1, &temp);
5865 EXPECT_EQ(error::kNoError,
5866 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5867 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5868 if func.IsUnsafe():
5869 valid_test += """
5870 GLuint service_id;
5871 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5872 EXPECT_EQ(kNewServiceId, service_id);
5873 decoder_->set_unsafe_es3_apis_enabled(false);
5874 EXPECT_EQ(error::kUnknownCommand,
5875 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5878 else:
5879 valid_test += """
5880 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5883 self.WriteValidUnitTest(func, f, valid_test, {
5884 'resource_name': func.GetInfo('resource_type'),
5885 }, *extras)
5886 invalid_test = """
5887 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5888 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5889 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5890 SpecializedSetup<cmds::%(name)s, 0>(false);
5891 cmd->Init(1, &client_%(resource_name)s_id_);"""
5892 if func.IsUnsafe():
5893 invalid_test += """
5894 decoder_->set_unsafe_es3_apis_enabled(true);
5895 EXPECT_EQ(error::kInvalidArguments,
5896 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5897 decoder_->set_unsafe_es3_apis_enabled(false);
5900 else:
5901 invalid_test += """
5902 EXPECT_EQ(error::kInvalidArguments,
5903 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5906 self.WriteValidUnitTest(func, f, invalid_test, {
5907 'resource_name': func.GetInfo('resource_type').lower(),
5908 }, *extras)
5910 def WriteImmediateCmdComputeSize(self, func, f):
5911 """Overrriden from TypeHandler."""
5912 f.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5913 f.write(
5914 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5915 f.write(" }\n")
5916 f.write("\n")
5917 f.write(" static uint32_t ComputeSize(GLsizei n) {\n")
5918 f.write(" return static_cast<uint32_t>(\n")
5919 f.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5920 f.write(" }\n")
5921 f.write("\n")
5923 def WriteImmediateCmdSetHeader(self, func, f):
5924 """Overrriden from TypeHandler."""
5925 f.write(" void SetHeader(GLsizei n) {\n")
5926 f.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5927 f.write(" }\n")
5928 f.write("\n")
5930 def WriteImmediateCmdInit(self, func, f):
5931 """Overrriden from TypeHandler."""
5932 last_arg = func.GetLastOriginalArg()
5933 f.write(" void Init(%s, %s _%s) {\n" %
5934 (func.MakeTypedCmdArgString("_"),
5935 last_arg.type, last_arg.name))
5936 f.write(" SetHeader(_n);\n")
5937 args = func.GetCmdArgs()
5938 for arg in args:
5939 f.write(" %s = _%s;\n" % (arg.name, arg.name))
5940 f.write(" memcpy(ImmediateDataAddress(this),\n")
5941 f.write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5942 f.write(" }\n")
5943 f.write("\n")
5945 def WriteImmediateCmdSet(self, func, f):
5946 """Overrriden from TypeHandler."""
5947 last_arg = func.GetLastOriginalArg()
5948 copy_args = func.MakeCmdArgString("_", False)
5949 f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
5950 (func.MakeTypedCmdArgString("_", True),
5951 last_arg.type, last_arg.name))
5952 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5953 (copy_args, last_arg.name))
5954 f.write(" const uint32_t size = ComputeSize(_n);\n")
5955 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5956 "cmd, size);\n")
5957 f.write(" }\n")
5958 f.write("\n")
5960 def WriteImmediateCmdHelper(self, func, f):
5961 """Overrriden from TypeHandler."""
5962 code = """ void %(name)s(%(typed_args)s) {
5963 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5964 gles2::cmds::%(name)s* c =
5965 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5966 if (c) {
5967 c->Init(%(args)s);
5972 f.write(code % {
5973 "name": func.name,
5974 "typed_args": func.MakeTypedOriginalArgString(""),
5975 "args": func.MakeOriginalArgString(""),
5978 def WriteImmediateFormatTest(self, func, f):
5979 """Overrriden from TypeHandler."""
5980 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5981 f.write(" static GLuint ids[] = { 12, 23, 34, };\n")
5982 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5983 (func.name, func.name))
5984 f.write(" void* next_cmd = cmd.Set(\n")
5985 f.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5986 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5987 func.name)
5988 f.write(" cmd.header.command);\n")
5989 f.write(" EXPECT_EQ(sizeof(cmd) +\n")
5990 f.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5991 f.write(" cmd.header.size * 4u);\n")
5992 f.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5993 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
5994 f.write(" next_cmd, sizeof(cmd) +\n")
5995 f.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5996 f.write(" // TODO(gman): Check that ids were inserted;\n")
5997 f.write("}\n")
5998 f.write("\n")
6001 class CreateHandler(TypeHandler):
6002 """Handler for glCreate___ type functions."""
6004 def InitFunction(self, func):
6005 """Overrriden from TypeHandler."""
6006 func.AddCmdArg(Argument("client_id", 'uint32_t'))
6008 def __GetResourceType(self, func):
6009 if func.return_type == "GLsync":
6010 return "Sync"
6011 else:
6012 return func.name[6:] # Create*
6014 def WriteServiceUnitTest(self, func, f, *extras):
6015 """Overrriden from TypeHandler."""
6016 valid_test = """
6017 TEST_P(%(test_name)s, %(name)sValidArgs) {
6018 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
6019 .WillOnce(Return(%(const_service_id)s));
6020 SpecializedSetup<cmds::%(name)s, 0>(true);
6021 cmds::%(name)s cmd;
6022 cmd.Init(%(args)s%(comma)skNewClientId);"""
6023 if func.IsUnsafe():
6024 valid_test += """
6025 decoder_->set_unsafe_es3_apis_enabled(true);"""
6026 valid_test += """
6027 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6028 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6029 if func.IsUnsafe():
6030 valid_test += """
6031 %(return_type)s service_id = 0;
6032 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
6033 EXPECT_EQ(%(const_service_id)s, service_id);
6034 decoder_->set_unsafe_es3_apis_enabled(false);
6035 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
6038 else:
6039 valid_test += """
6040 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
6043 comma = ""
6044 cmd_arg_count = 0
6045 for arg in func.GetOriginalArgs():
6046 if not arg.IsConstant():
6047 cmd_arg_count += 1
6048 if cmd_arg_count:
6049 comma = ", "
6050 if func.return_type == 'GLsync':
6051 id_type_cast = ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
6052 "<GLsync>(kNewServiceId);\n ")
6053 const_service_id = "kNewServiceIdGLuint"
6054 else:
6055 id_type_cast = ""
6056 const_service_id = "kNewServiceId"
6057 self.WriteValidUnitTest(func, f, valid_test, {
6058 'comma': comma,
6059 'resource_type': self.__GetResourceType(func),
6060 'return_type': func.return_type,
6061 'id_type_cast': id_type_cast,
6062 'const_service_id': const_service_id,
6063 }, *extras)
6064 invalid_test = """
6065 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6066 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6067 SpecializedSetup<cmds::%(name)s, 0>(false);
6068 cmds::%(name)s cmd;
6069 cmd.Init(%(args)s%(comma)skNewClientId);
6070 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
6073 self.WriteInvalidUnitTest(func, f, invalid_test, {
6074 'comma': comma,
6075 }, *extras)
6077 def WriteHandlerImplementation (self, func, f):
6078 """Overrriden from TypeHandler."""
6079 if func.IsUnsafe():
6080 code = """ uint32_t client_id = c.client_id;
6081 %(return_type)s service_id = 0;
6082 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
6083 return error::kInvalidArguments;
6085 service_id = %(gl_func_name)s(%(gl_args)s);
6086 if (service_id) {
6087 group_->Add%(resource_name)sId(client_id, service_id);
6090 else:
6091 code = """ uint32_t client_id = c.client_id;
6092 if (Get%(resource_name)s(client_id)) {
6093 return error::kInvalidArguments;
6095 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
6096 if (service_id) {
6097 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
6100 f.write(code % {
6101 'resource_name': self.__GetResourceType(func),
6102 'return_type': func.return_type,
6103 'gl_func_name': func.GetGLFunctionName(),
6104 'gl_args': func.MakeOriginalArgString(""),
6105 'gl_args_with_comma': func.MakeOriginalArgString("", True) })
6107 def WriteGLES2Implementation(self, func, f):
6108 """Overrriden from TypeHandler."""
6109 f.write("%s GLES2Implementation::%s(%s) {\n" %
6110 (func.return_type, func.original_name,
6111 func.MakeTypedOriginalArgString("")))
6112 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6113 func.WriteDestinationInitalizationValidation(f)
6114 self.WriteClientGLCallLog(func, f)
6115 for arg in func.GetOriginalArgs():
6116 arg.WriteClientSideValidationCode(f, func)
6117 f.write(" GLuint client_id;\n")
6118 if func.return_type == "GLsync":
6119 f.write(
6120 " GetIdHandler(id_namespaces::kSyncs)->\n")
6121 else:
6122 f.write(
6123 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
6124 f.write(" MakeIds(this, 0, 1, &client_id);\n")
6125 f.write(" helper_->%s(%s);\n" %
6126 (func.name, func.MakeCmdArgString("")))
6127 f.write(' GPU_CLIENT_LOG("returned " << client_id);\n')
6128 f.write(" CheckGLError();\n")
6129 if func.return_type == "GLsync":
6130 f.write(" return reinterpret_cast<GLsync>(client_id);\n")
6131 else:
6132 f.write(" return client_id;\n")
6133 f.write("}\n")
6134 f.write("\n")
6137 class DeleteHandler(TypeHandler):
6138 """Handler for glDelete___ single resource type functions."""
6140 def WriteServiceImplementation(self, func, f):
6141 """Overrriden from TypeHandler."""
6142 if func.IsUnsafe():
6143 TypeHandler.WriteServiceImplementation(self, func, f)
6144 # HandleDeleteShader and HandleDeleteProgram are manually written.
6145 pass
6147 def WriteGLES2Implementation(self, func, f):
6148 """Overrriden from TypeHandler."""
6149 f.write("%s GLES2Implementation::%s(%s) {\n" %
6150 (func.return_type, func.original_name,
6151 func.MakeTypedOriginalArgString("")))
6152 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6153 func.WriteDestinationInitalizationValidation(f)
6154 self.WriteClientGLCallLog(func, f)
6155 for arg in func.GetOriginalArgs():
6156 arg.WriteClientSideValidationCode(f, func)
6157 f.write(
6158 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
6159 f.write(" %sHelper(%s);\n" %
6160 (func.original_name, func.GetOriginalArgs()[-1].name))
6161 f.write(" CheckGLError();\n")
6162 f.write("}\n")
6163 f.write("\n")
6165 def WriteHandlerImplementation (self, func, f):
6166 """Overrriden from TypeHandler."""
6167 assert len(func.GetOriginalArgs()) == 1
6168 arg = func.GetOriginalArgs()[0]
6169 if func.IsUnsafe():
6170 f.write(""" %(arg_type)s service_id = 0;
6171 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
6172 glDelete%(resource_type)s(service_id);
6173 group_->Remove%(resource_type)sId(%(arg_name)s);
6174 } else {
6175 LOCAL_SET_GL_ERROR(
6176 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
6178 """ % { 'resource_type': func.GetInfo('resource_type'),
6179 'arg_name': arg.name,
6180 'arg_type': arg.type,
6181 'func_name': func.original_name })
6182 else:
6183 f.write(" %sHelper(%s);\n" % (func.original_name, arg.name))
6185 class DELnHandler(TypeHandler):
6186 """Handler for glDelete___ type functions."""
6188 def WriteGetDataSizeCode(self, func, f):
6189 """Overrriden from TypeHandler."""
6190 code = """ uint32_t data_size;
6191 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
6192 return error::kOutOfBounds;
6195 f.write(code)
6197 def WriteGLES2ImplementationUnitTest(self, func, f):
6198 """Overrriden from TypeHandler."""
6199 code = """
6200 TEST_F(GLES2ImplementationTest, %(name)s) {
6201 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
6202 struct Cmds {
6203 cmds::%(name)sImmediate del;
6204 GLuint data[2];
6206 Cmds expected;
6207 expected.del.Init(arraysize(ids), &ids[0]);
6208 expected.data[0] = k%(types)sStartId;
6209 expected.data[1] = k%(types)sStartId + 1;
6210 gl_->%(name)s(arraysize(ids), &ids[0]);
6211 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6214 f.write(code % {
6215 'name': func.name,
6216 'types': func.GetInfo('resource_types'),
6219 def WriteServiceUnitTest(self, func, f, *extras):
6220 """Overrriden from TypeHandler."""
6221 valid_test = """
6222 TEST_P(%(test_name)s, %(name)sValidArgs) {
6223 EXPECT_CALL(
6224 *gl_,
6225 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6226 .Times(1);
6227 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
6228 SpecializedSetup<cmds::%(name)s, 0>(true);
6229 cmds::%(name)s cmd;
6230 cmd.Init(%(args)s);
6231 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6232 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6233 EXPECT_TRUE(
6234 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6237 self.WriteValidUnitTest(func, f, valid_test, {
6238 'resource_name': func.GetInfo('resource_type').lower(),
6239 'upper_resource_name': func.GetInfo('resource_type'),
6240 }, *extras)
6241 invalid_test = """
6242 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6243 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
6244 SpecializedSetup<cmds::%(name)s, 0>(false);
6245 cmds::%(name)s cmd;
6246 cmd.Init(%(args)s);
6247 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6250 self.WriteValidUnitTest(func, f, invalid_test, *extras)
6252 def WriteImmediateServiceUnitTest(self, func, f, *extras):
6253 """Overrriden from TypeHandler."""
6254 valid_test = """
6255 TEST_P(%(test_name)s, %(name)sValidArgs) {
6256 EXPECT_CALL(
6257 *gl_,
6258 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
6259 .Times(1);
6260 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6261 SpecializedSetup<cmds::%(name)s, 0>(true);
6262 cmd.Init(1, &client_%(resource_name)s_id_);"""
6263 if func.IsUnsafe():
6264 valid_test += """
6265 decoder_->set_unsafe_es3_apis_enabled(true);"""
6266 valid_test += """
6267 EXPECT_EQ(error::kNoError,
6268 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6269 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6270 if func.IsUnsafe():
6271 valid_test += """
6272 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
6273 client_%(resource_name)s_id_, NULL));
6274 decoder_->set_unsafe_es3_apis_enabled(false);
6275 EXPECT_EQ(error::kUnknownCommand,
6276 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
6279 else:
6280 valid_test += """
6281 EXPECT_TRUE(
6282 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
6285 self.WriteValidUnitTest(func, f, valid_test, {
6286 'resource_name': func.GetInfo('resource_type').lower(),
6287 'upper_resource_name': func.GetInfo('resource_type'),
6288 }, *extras)
6289 invalid_test = """
6290 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
6291 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6292 SpecializedSetup<cmds::%(name)s, 0>(false);
6293 GLuint temp = kInvalidClientId;
6294 cmd.Init(1, &temp);"""
6295 if func.IsUnsafe():
6296 invalid_test += """
6297 decoder_->set_unsafe_es3_apis_enabled(true);
6298 EXPECT_EQ(error::kNoError,
6299 ExecuteImmediateCmd(cmd, sizeof(temp)));
6300 decoder_->set_unsafe_es3_apis_enabled(false);
6301 EXPECT_EQ(error::kUnknownCommand,
6302 ExecuteImmediateCmd(cmd, sizeof(temp)));
6305 else:
6306 invalid_test += """
6307 EXPECT_EQ(error::kNoError,
6308 ExecuteImmediateCmd(cmd, sizeof(temp)));
6311 self.WriteValidUnitTest(func, f, invalid_test, *extras)
6313 def WriteHandlerImplementation (self, func, f):
6314 """Overrriden from TypeHandler."""
6315 f.write(" %sHelper(n, %s);\n" %
6316 (func.name, func.GetLastOriginalArg().name))
6318 def WriteImmediateHandlerImplementation (self, func, f):
6319 """Overrriden from TypeHandler."""
6320 if func.IsUnsafe():
6321 f.write(""" for (GLsizei ii = 0; ii < n; ++ii) {
6322 GLuint service_id = 0;
6323 if (group_->Get%(resource_type)sServiceId(
6324 %(last_arg_name)s[ii], &service_id)) {
6325 glDelete%(resource_type)ss(1, &service_id);
6326 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
6329 """ % { 'resource_type': func.GetInfo('resource_type'),
6330 'last_arg_name': func.GetLastOriginalArg().name })
6331 else:
6332 f.write(" %sHelper(n, %s);\n" %
6333 (func.original_name, func.GetLastOriginalArg().name))
6335 def WriteGLES2Implementation(self, func, f):
6336 """Overrriden from TypeHandler."""
6337 impl_decl = func.GetInfo('impl_decl')
6338 if impl_decl == None or impl_decl == True:
6339 args = {
6340 'return_type': func.return_type,
6341 'name': func.original_name,
6342 'typed_args': func.MakeTypedOriginalArgString(""),
6343 'args': func.MakeOriginalArgString(""),
6344 'resource_type': func.GetInfo('resource_type').lower(),
6345 'count_name': func.GetOriginalArgs()[0].name,
6347 f.write(
6348 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
6349 args)
6350 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6351 func.WriteDestinationInitalizationValidation(f)
6352 self.WriteClientGLCallLog(func, f)
6353 f.write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6354 for (GLsizei i = 0; i < n; ++i) {
6355 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
6358 """ % func.GetOriginalArgs()[1].name)
6359 f.write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
6360 for (GLsizei i = 0; i < n; ++i) {
6361 DCHECK(%s[i] != 0);
6364 """ % func.GetOriginalArgs()[1].name)
6365 for arg in func.GetOriginalArgs():
6366 arg.WriteClientSideValidationCode(f, func)
6367 code = """ %(name)sHelper(%(args)s);
6368 CheckGLError();
6372 f.write(code % args)
6374 def WriteImmediateCmdComputeSize(self, func, f):
6375 """Overrriden from TypeHandler."""
6376 f.write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
6377 f.write(
6378 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
6379 f.write(" }\n")
6380 f.write("\n")
6381 f.write(" static uint32_t ComputeSize(GLsizei n) {\n")
6382 f.write(" return static_cast<uint32_t>(\n")
6383 f.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
6384 f.write(" }\n")
6385 f.write("\n")
6387 def WriteImmediateCmdSetHeader(self, func, f):
6388 """Overrriden from TypeHandler."""
6389 f.write(" void SetHeader(GLsizei n) {\n")
6390 f.write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
6391 f.write(" }\n")
6392 f.write("\n")
6394 def WriteImmediateCmdInit(self, func, f):
6395 """Overrriden from TypeHandler."""
6396 last_arg = func.GetLastOriginalArg()
6397 f.write(" void Init(%s, %s _%s) {\n" %
6398 (func.MakeTypedCmdArgString("_"),
6399 last_arg.type, last_arg.name))
6400 f.write(" SetHeader(_n);\n")
6401 args = func.GetCmdArgs()
6402 for arg in args:
6403 f.write(" %s = _%s;\n" % (arg.name, arg.name))
6404 f.write(" memcpy(ImmediateDataAddress(this),\n")
6405 f.write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
6406 f.write(" }\n")
6407 f.write("\n")
6409 def WriteImmediateCmdSet(self, func, f):
6410 """Overrriden from TypeHandler."""
6411 last_arg = func.GetLastOriginalArg()
6412 copy_args = func.MakeCmdArgString("_", False)
6413 f.write(" void* Set(void* cmd%s, %s _%s) {\n" %
6414 (func.MakeTypedCmdArgString("_", True),
6415 last_arg.type, last_arg.name))
6416 f.write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6417 (copy_args, last_arg.name))
6418 f.write(" const uint32_t size = ComputeSize(_n);\n")
6419 f.write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6420 "cmd, size);\n")
6421 f.write(" }\n")
6422 f.write("\n")
6424 def WriteImmediateCmdHelper(self, func, f):
6425 """Overrriden from TypeHandler."""
6426 code = """ void %(name)s(%(typed_args)s) {
6427 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
6428 gles2::cmds::%(name)s* c =
6429 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6430 if (c) {
6431 c->Init(%(args)s);
6436 f.write(code % {
6437 "name": func.name,
6438 "typed_args": func.MakeTypedOriginalArgString(""),
6439 "args": func.MakeOriginalArgString(""),
6442 def WriteImmediateFormatTest(self, func, f):
6443 """Overrriden from TypeHandler."""
6444 f.write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6445 f.write(" static GLuint ids[] = { 12, 23, 34, };\n")
6446 f.write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6447 (func.name, func.name))
6448 f.write(" void* next_cmd = cmd.Set(\n")
6449 f.write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
6450 f.write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6451 func.name)
6452 f.write(" cmd.header.command);\n")
6453 f.write(" EXPECT_EQ(sizeof(cmd) +\n")
6454 f.write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
6455 f.write(" cmd.header.size * 4u);\n")
6456 f.write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
6457 f.write(" CheckBytesWrittenMatchesExpectedSize(\n")
6458 f.write(" next_cmd, sizeof(cmd) +\n")
6459 f.write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
6460 f.write(" // TODO(gman): Check that ids were inserted;\n")
6461 f.write("}\n")
6462 f.write("\n")
6465 class GETnHandler(TypeHandler):
6466 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
6468 def NeedsDataTransferFunction(self, func):
6469 """Overriden from TypeHandler."""
6470 return False
6472 def WriteServiceImplementation(self, func, f):
6473 """Overrriden from TypeHandler."""
6474 self.WriteServiceHandlerFunctionHeader(func, f)
6475 last_arg = func.GetLastOriginalArg()
6476 # All except shm_id and shm_offset.
6477 all_but_last_args = func.GetCmdArgs()[:-2]
6478 for arg in all_but_last_args:
6479 arg.WriteGetCode(f)
6481 code = """ typedef cmds::%(func_name)s::Result Result;
6482 GLsizei num_values = 0;
6483 GetNumValuesReturnedForGLGet(pname, &num_values);
6484 Result* result = GetSharedMemoryAs<Result*>(
6485 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
6486 Result::ComputeSize(num_values));
6487 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
6489 f.write(code % {
6490 'last_arg_type': last_arg.type,
6491 'last_arg_name': last_arg.name,
6492 'func_name': func.name,
6494 func.WriteHandlerValidation(f)
6495 code = """ // Check that the client initialized the result.
6496 if (result->size != 0) {
6497 return error::kInvalidArguments;
6500 shadowed = func.GetInfo('shadowed')
6501 if not shadowed:
6502 f.write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
6503 f.write(code)
6504 func.WriteHandlerImplementation(f)
6505 if shadowed:
6506 code = """ result->SetNumResults(num_values);
6507 return error::kNoError;
6510 else:
6511 code = """ GLenum error = LOCAL_PEEK_GL_ERROR("%(func_name)s");
6512 if (error == GL_NO_ERROR) {
6513 result->SetNumResults(num_values);
6515 return error::kNoError;
6519 f.write(code % {'func_name': func.name})
6521 def WriteGLES2Implementation(self, func, f):
6522 """Overrriden from TypeHandler."""
6523 impl_decl = func.GetInfo('impl_decl')
6524 if impl_decl == None or impl_decl == True:
6525 f.write("%s GLES2Implementation::%s(%s) {\n" %
6526 (func.return_type, func.original_name,
6527 func.MakeTypedOriginalArgString("")))
6528 f.write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6529 func.WriteDestinationInitalizationValidation(f)
6530 self.WriteClientGLCallLog(func, f)
6531 for arg in func.GetOriginalArgs():
6532 arg.WriteClientSideValidationCode(f, func)
6533 all_but_last_args = func.GetOriginalArgs()[:-1]
6534 args = []
6535 has_length_arg = False
6536 for arg in all_but_last_args:
6537 if arg.type == 'GLsync':
6538 args.append('ToGLuint(%s)' % arg.name)
6539 elif arg.name.endswith('size') and arg.type == 'GLsizei':
6540 continue
6541 elif arg.name == 'length':
6542 has_length_arg = True
6543 continue
6544 else:
6545 args.append(arg.name)
6546 arg_string = ", ".join(args)
6547 all_arg_string = (
6548 ", ".join([
6549 "%s" % arg.name
6550 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
6551 self.WriteTraceEvent(func, f)
6552 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6553 return;
6555 typedef cmds::%(func_name)s::Result Result;
6556 Result* result = GetResultAs<Result*>();
6557 if (!result) {
6558 return;
6560 result->SetNumResults(0);
6561 helper_->%(func_name)s(%(arg_string)s,
6562 GetResultShmId(), GetResultShmOffset());
6563 WaitForCmd();
6564 result->CopyResult(%(last_arg_name)s);
6565 GPU_CLIENT_LOG_CODE_BLOCK({
6566 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6567 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6569 });"""
6570 if has_length_arg:
6571 code += """
6572 if (length) {
6573 *length = result->GetNumResults();
6574 }"""
6575 code += """
6576 CheckGLError();
6579 f.write(code % {
6580 'func_name': func.name,
6581 'arg_string': arg_string,
6582 'all_arg_string': all_arg_string,
6583 'last_arg_name': func.GetLastOriginalArg().name,
6586 def WriteGLES2ImplementationUnitTest(self, func, f):
6587 """Writes the GLES2 Implemention unit test."""
6588 code = """
6589 TEST_F(GLES2ImplementationTest, %(name)s) {
6590 struct Cmds {
6591 cmds::%(name)s cmd;
6593 typedef cmds::%(name)s::Result::Type ResultType;
6594 ResultType result = 0;
6595 Cmds expected;
6596 ExpectedMemoryInfo result1 = GetExpectedResultMemory(
6597 sizeof(uint32_t) + sizeof(ResultType));
6598 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6599 EXPECT_CALL(*command_buffer(), OnFlush())
6600 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<ResultType>(1)))
6601 .RetiresOnSaturation();
6602 gl_->%(name)s(%(args)s, &result);
6603 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6604 EXPECT_EQ(static_cast<ResultType>(1), result);
6607 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
6608 if not first_cmd_arg:
6609 return
6611 first_gl_arg = func.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6612 func)
6614 cmd_arg_strings = [first_cmd_arg]
6615 for arg in func.GetCmdArgs()[1:-2]:
6616 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6617 gl_arg_strings = [first_gl_arg]
6618 for arg in func.GetOriginalArgs()[1:-1]:
6619 gl_arg_strings.append(arg.GetValidClientSideArg(func))
6621 f.write(code % {
6622 'name': func.name,
6623 'args': ", ".join(gl_arg_strings),
6624 'cmd_args': ", ".join(cmd_arg_strings),
6627 def WriteServiceUnitTest(self, func, f, *extras):
6628 """Overrriden from TypeHandler."""
6629 valid_test = """
6630 TEST_P(%(test_name)s, %(name)sValidArgs) {
6631 EXPECT_CALL(*gl_, GetError())
6632 .WillRepeatedly(Return(GL_NO_ERROR));
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:]))