Fix bad field type in ScriptRequestIncident.
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blobaa7be79cbca34041a21142e4494e1a84a0dc15ac
1 #!/usr/bin/env python
2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """code generator for GLES2 command buffers."""
8 import itertools
9 import os
10 import os.path
11 import sys
12 import re
13 import platform
14 from optparse import OptionParser
15 from subprocess import call
17 _SIZE_OF_UINT32 = 4
18 _SIZE_OF_COMMAND_HEADER = 4
19 _FIRST_SPECIFIC_COMMAND_ID = 256
21 _LICENSE = """// Copyright 2014 The Chromium Authors. All rights reserved.
22 // Use of this source code is governed by a BSD-style license that can be
23 // found in the LICENSE file.
25 """
27 _DO_NOT_EDIT_WARNING = """// This file is auto-generated from
28 // gpu/command_buffer/build_gles2_cmd_buffer.py
29 // It's formatted by clang-format using chromium coding style:
30 // clang-format -i -style=chromium filename
31 // DO NOT EDIT!
33 """
35 # This string is copied directly out of the gl2.h file from GLES2.0
37 # Edits:
39 # *) Any argument that is a resourceID has been changed to GLid<Type>.
40 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
41 # If it's allowed to not exist it's GLidBind<Type>
43 # *) All GLenums have been changed to GLenumTypeOfEnum
45 _GL_TYPES = {
46 'GLenum': 'unsigned int',
47 'GLboolean': 'unsigned char',
48 'GLbitfield': 'unsigned int',
49 'GLbyte': 'signed char',
50 'GLshort': 'short',
51 'GLint': 'int',
52 'GLsizei': 'int',
53 'GLubyte': 'unsigned char',
54 'GLushort': 'unsigned short',
55 'GLuint': 'unsigned int',
56 'GLfloat': 'float',
57 'GLclampf': 'float',
58 'GLvoid': 'void',
59 'GLfixed': 'int',
60 'GLclampx': 'int'
63 _GL_TYPES_32 = {
64 'GLintptr': 'long int',
65 'GLsizeiptr': 'long int'
68 _GL_TYPES_64 = {
69 'GLintptr': 'long long int',
70 'GLsizeiptr': 'long long int'
73 # Capabilites selected with glEnable
74 _CAPABILITY_FLAGS = [
75 {'name': 'blend'},
76 {'name': 'cull_face'},
77 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
78 {'name': 'dither', 'default': True},
79 {'name': 'polygon_offset_fill'},
80 {'name': 'sample_alpha_to_coverage'},
81 {'name': 'sample_coverage'},
82 {'name': 'scissor_test'},
83 {'name': 'stencil_test',
84 'state_flag': 'framebuffer_state_.clear_state_dirty'},
85 {'name': 'rasterizer_discard', 'es3': True},
88 _STATES = {
89 'ClearColor': {
90 'type': 'Normal',
91 'func': 'ClearColor',
92 'enum': 'GL_COLOR_CLEAR_VALUE',
93 'states': [
94 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
95 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
97 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
100 'ClearDepthf': {
101 'type': 'Normal',
102 'func': 'ClearDepth',
103 'enum': 'GL_DEPTH_CLEAR_VALUE',
104 'states': [
105 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
108 'ColorMask': {
109 'type': 'Normal',
110 'func': 'ColorMask',
111 'enum': 'GL_COLOR_WRITEMASK',
112 'states': [
114 'name': 'color_mask_red',
115 'type': 'GLboolean',
116 'default': 'true',
117 'cached': True
120 'name': 'color_mask_green',
121 'type': 'GLboolean',
122 'default': 'true',
123 'cached': True
126 'name': 'color_mask_blue',
127 'type': 'GLboolean',
128 'default': 'true',
129 'cached': True
132 'name': 'color_mask_alpha',
133 'type': 'GLboolean',
134 'default': 'true',
135 'cached': True
138 'state_flag': 'framebuffer_state_.clear_state_dirty',
140 'ClearStencil': {
141 'type': 'Normal',
142 'func': 'ClearStencil',
143 'enum': 'GL_STENCIL_CLEAR_VALUE',
144 'states': [
145 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
148 'BlendColor': {
149 'type': 'Normal',
150 'func': 'BlendColor',
151 'enum': 'GL_BLEND_COLOR',
152 'states': [
153 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
154 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
155 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
156 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
159 'BlendEquation': {
160 'type': 'SrcDst',
161 'func': 'BlendEquationSeparate',
162 'states': [
164 'name': 'blend_equation_rgb',
165 'type': 'GLenum',
166 'enum': 'GL_BLEND_EQUATION_RGB',
167 'default': 'GL_FUNC_ADD',
170 'name': 'blend_equation_alpha',
171 'type': 'GLenum',
172 'enum': 'GL_BLEND_EQUATION_ALPHA',
173 'default': 'GL_FUNC_ADD',
177 'BlendFunc': {
178 'type': 'SrcDst',
179 'func': 'BlendFuncSeparate',
180 'states': [
182 'name': 'blend_source_rgb',
183 'type': 'GLenum',
184 'enum': 'GL_BLEND_SRC_RGB',
185 'default': 'GL_ONE',
188 'name': 'blend_dest_rgb',
189 'type': 'GLenum',
190 'enum': 'GL_BLEND_DST_RGB',
191 'default': 'GL_ZERO',
194 'name': 'blend_source_alpha',
195 'type': 'GLenum',
196 'enum': 'GL_BLEND_SRC_ALPHA',
197 'default': 'GL_ONE',
200 'name': 'blend_dest_alpha',
201 'type': 'GLenum',
202 'enum': 'GL_BLEND_DST_ALPHA',
203 'default': 'GL_ZERO',
207 'PolygonOffset': {
208 'type': 'Normal',
209 'func': 'PolygonOffset',
210 'states': [
212 'name': 'polygon_offset_factor',
213 'type': 'GLfloat',
214 'enum': 'GL_POLYGON_OFFSET_FACTOR',
215 'default': '0.0f',
218 'name': 'polygon_offset_units',
219 'type': 'GLfloat',
220 'enum': 'GL_POLYGON_OFFSET_UNITS',
221 'default': '0.0f',
225 'CullFace': {
226 'type': 'Normal',
227 'func': 'CullFace',
228 'enum': 'GL_CULL_FACE_MODE',
229 'states': [
231 'name': 'cull_mode',
232 'type': 'GLenum',
233 'default': 'GL_BACK',
237 'FrontFace': {
238 'type': 'Normal',
239 'func': 'FrontFace',
240 'enum': 'GL_FRONT_FACE',
241 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
243 'DepthFunc': {
244 'type': 'Normal',
245 'func': 'DepthFunc',
246 'enum': 'GL_DEPTH_FUNC',
247 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
249 'DepthRange': {
250 'type': 'Normal',
251 'func': 'DepthRange',
252 'enum': 'GL_DEPTH_RANGE',
253 'states': [
254 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
255 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
258 'SampleCoverage': {
259 'type': 'Normal',
260 'func': 'SampleCoverage',
261 'states': [
263 'name': 'sample_coverage_value',
264 'type': 'GLclampf',
265 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
266 'default': '1.0f',
269 'name': 'sample_coverage_invert',
270 'type': 'GLboolean',
271 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
272 'default': 'false',
276 'StencilMask': {
277 'type': 'FrontBack',
278 'func': 'StencilMaskSeparate',
279 'state_flag': 'framebuffer_state_.clear_state_dirty',
280 'states': [
282 'name': 'stencil_front_writemask',
283 'type': 'GLuint',
284 'enum': 'GL_STENCIL_WRITEMASK',
285 'default': '0xFFFFFFFFU',
286 'cached': True,
289 'name': 'stencil_back_writemask',
290 'type': 'GLuint',
291 'enum': 'GL_STENCIL_BACK_WRITEMASK',
292 'default': '0xFFFFFFFFU',
293 'cached': True,
297 'StencilOp': {
298 'type': 'FrontBack',
299 'func': 'StencilOpSeparate',
300 'states': [
302 'name': 'stencil_front_fail_op',
303 'type': 'GLenum',
304 'enum': 'GL_STENCIL_FAIL',
305 'default': 'GL_KEEP',
308 'name': 'stencil_front_z_fail_op',
309 'type': 'GLenum',
310 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
311 'default': 'GL_KEEP',
314 'name': 'stencil_front_z_pass_op',
315 'type': 'GLenum',
316 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
317 'default': 'GL_KEEP',
320 'name': 'stencil_back_fail_op',
321 'type': 'GLenum',
322 'enum': 'GL_STENCIL_BACK_FAIL',
323 'default': 'GL_KEEP',
326 'name': 'stencil_back_z_fail_op',
327 'type': 'GLenum',
328 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
329 'default': 'GL_KEEP',
332 'name': 'stencil_back_z_pass_op',
333 'type': 'GLenum',
334 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
335 'default': 'GL_KEEP',
339 'StencilFunc': {
340 'type': 'FrontBack',
341 'func': 'StencilFuncSeparate',
342 'states': [
344 'name': 'stencil_front_func',
345 'type': 'GLenum',
346 'enum': 'GL_STENCIL_FUNC',
347 'default': 'GL_ALWAYS',
350 'name': 'stencil_front_ref',
351 'type': 'GLint',
352 'enum': 'GL_STENCIL_REF',
353 'default': '0',
356 'name': 'stencil_front_mask',
357 'type': 'GLuint',
358 'enum': 'GL_STENCIL_VALUE_MASK',
359 'default': '0xFFFFFFFFU',
362 'name': 'stencil_back_func',
363 'type': 'GLenum',
364 'enum': 'GL_STENCIL_BACK_FUNC',
365 'default': 'GL_ALWAYS',
368 'name': 'stencil_back_ref',
369 'type': 'GLint',
370 'enum': 'GL_STENCIL_BACK_REF',
371 'default': '0',
374 'name': 'stencil_back_mask',
375 'type': 'GLuint',
376 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
377 'default': '0xFFFFFFFFU',
381 'Hint': {
382 'type': 'NamedParameter',
383 'func': 'Hint',
384 'states': [
386 'name': 'hint_generate_mipmap',
387 'type': 'GLenum',
388 'enum': 'GL_GENERATE_MIPMAP_HINT',
389 'default': 'GL_DONT_CARE'
392 'name': 'hint_fragment_shader_derivative',
393 'type': 'GLenum',
394 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
395 'default': 'GL_DONT_CARE',
396 'extension_flag': 'oes_standard_derivatives'
400 'PixelStore': {
401 'type': 'NamedParameter',
402 'func': 'PixelStorei',
403 'states': [
405 'name': 'pack_alignment',
406 'type': 'GLint',
407 'enum': 'GL_PACK_ALIGNMENT',
408 'default': '4'
411 'name': 'unpack_alignment',
412 'type': 'GLint',
413 'enum': 'GL_UNPACK_ALIGNMENT',
414 'default': '4'
418 # TODO: Consider implemenenting these states
419 # GL_ACTIVE_TEXTURE
420 'LineWidth': {
421 'type': 'Normal',
422 'func': 'LineWidth',
423 'enum': 'GL_LINE_WIDTH',
424 'states': [
426 'name': 'line_width',
427 'type': 'GLfloat',
428 'default': '1.0f',
429 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
430 'nan_check': True,
433 'DepthMask': {
434 'type': 'Normal',
435 'func': 'DepthMask',
436 'enum': 'GL_DEPTH_WRITEMASK',
437 'states': [
439 'name': 'depth_mask',
440 'type': 'GLboolean',
441 'default': 'true',
442 'cached': True
445 'state_flag': 'framebuffer_state_.clear_state_dirty',
447 'Scissor': {
448 'type': 'Normal',
449 'func': 'Scissor',
450 'enum': 'GL_SCISSOR_BOX',
451 'states': [
452 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
454 'name': 'scissor_x',
455 'type': 'GLint',
456 'default': '0',
457 'expected': 'kViewportX',
460 'name': 'scissor_y',
461 'type': 'GLint',
462 'default': '0',
463 'expected': 'kViewportY',
466 'name': 'scissor_width',
467 'type': 'GLsizei',
468 'default': '1',
469 'expected': 'kViewportWidth',
472 'name': 'scissor_height',
473 'type': 'GLsizei',
474 'default': '1',
475 'expected': 'kViewportHeight',
479 'Viewport': {
480 'type': 'Normal',
481 'func': 'Viewport',
482 'enum': 'GL_VIEWPORT',
483 'states': [
484 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
486 'name': 'viewport_x',
487 'type': 'GLint',
488 'default': '0',
489 'expected': 'kViewportX',
492 'name': 'viewport_y',
493 'type': 'GLint',
494 'default': '0',
495 'expected': 'kViewportY',
498 'name': 'viewport_width',
499 'type': 'GLsizei',
500 'default': '1',
501 'expected': 'kViewportWidth',
504 'name': 'viewport_height',
505 'type': 'GLsizei',
506 'default': '1',
507 'expected': 'kViewportHeight',
511 'MatrixValuesCHROMIUM': {
512 'type': 'NamedParameter',
513 'func': 'MatrixLoadfEXT',
514 'states': [
515 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
516 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
517 'name': 'modelview_matrix',
518 'type': 'GLfloat',
519 'default': [
520 '1.0f', '0.0f','0.0f','0.0f',
521 '0.0f', '1.0f','0.0f','0.0f',
522 '0.0f', '0.0f','1.0f','0.0f',
523 '0.0f', '0.0f','0.0f','1.0f',
525 'extension_flag': 'chromium_path_rendering',
527 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
528 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
529 'name': 'projection_matrix',
530 'type': 'GLfloat',
531 'default': [
532 '1.0f', '0.0f','0.0f','0.0f',
533 '0.0f', '1.0f','0.0f','0.0f',
534 '0.0f', '0.0f','1.0f','0.0f',
535 '0.0f', '0.0f','0.0f','1.0f',
537 'extension_flag': 'chromium_path_rendering',
543 # Named type info object represents a named type that is used in OpenGL call
544 # arguments. Each named type defines a set of valid OpenGL call arguments. The
545 # named types are used in 'cmd_buffer_functions.txt'.
546 # type: The actual GL type of the named type.
547 # valid: The list of values that are valid for both the client and the service.
548 # valid_es3: The list of values that are valid in OpenGL ES 3, but not ES 2.
549 # invalid: Examples of invalid values for the type. At least these values
550 # should be tested to be invalid.
551 # deprecated_es3: The list of values that are valid in OpenGL ES 2, but
552 # deprecated in ES 3.
553 # is_complete: The list of valid values of type are final and will not be
554 # modified during runtime.
555 _NAMED_TYPE_INFO = {
556 'BlitFilter': {
557 'type': 'GLenum',
558 'valid': [
559 'GL_NEAREST',
560 'GL_LINEAR',
562 'invalid': [
563 'GL_LINEAR_MIPMAP_LINEAR',
566 'FrameBufferTarget': {
567 'type': 'GLenum',
568 'valid': [
569 'GL_FRAMEBUFFER',
571 'invalid': [
572 'GL_DRAW_FRAMEBUFFER' ,
573 'GL_READ_FRAMEBUFFER' ,
576 'RenderBufferTarget': {
577 'type': 'GLenum',
578 'valid': [
579 'GL_RENDERBUFFER',
581 'invalid': [
582 'GL_FRAMEBUFFER',
585 'BufferTarget': {
586 'type': 'GLenum',
587 'valid': [
588 'GL_ARRAY_BUFFER',
589 'GL_ELEMENT_ARRAY_BUFFER',
591 'valid_es3': [
592 'GL_COPY_READ_BUFFER',
593 'GL_COPY_WRITE_BUFFER',
594 'GL_PIXEL_PACK_BUFFER',
595 'GL_PIXEL_UNPACK_BUFFER',
596 'GL_TRANSFORM_FEEDBACK_BUFFER',
597 'GL_UNIFORM_BUFFER',
599 'invalid': [
600 'GL_RENDERBUFFER',
603 'IndexedBufferTarget': {
604 'type': 'GLenum',
605 'valid': [
606 'GL_TRANSFORM_FEEDBACK_BUFFER',
607 'GL_UNIFORM_BUFFER',
609 'invalid': [
610 'GL_RENDERBUFFER',
613 'MapBufferAccess': {
614 'type': 'GLenum',
615 'valid': [
616 'GL_MAP_READ_BIT',
617 'GL_MAP_WRITE_BIT',
618 'GL_MAP_INVALIDATE_RANGE_BIT',
619 'GL_MAP_INVALIDATE_BUFFER_BIT',
620 'GL_MAP_FLUSH_EXPLICIT_BIT',
621 'GL_MAP_UNSYNCHRONIZED_BIT',
623 'invalid': [
624 'GL_SYNC_FLUSH_COMMANDS_BIT',
627 'Bufferiv': {
628 'type': 'GLenum',
629 'valid': [
630 'GL_COLOR',
631 'GL_STENCIL',
633 'invalid': [
634 'GL_RENDERBUFFER',
637 'Bufferuiv': {
638 'type': 'GLenum',
639 'valid': [
640 'GL_COLOR',
642 'invalid': [
643 'GL_RENDERBUFFER',
646 'Bufferfv': {
647 'type': 'GLenum',
648 'valid': [
649 'GL_COLOR',
650 'GL_DEPTH',
652 'invalid': [
653 'GL_RENDERBUFFER',
656 'Bufferfi': {
657 'type': 'GLenum',
658 'valid': [
659 'GL_DEPTH_STENCIL',
661 'invalid': [
662 'GL_RENDERBUFFER',
665 'BufferUsage': {
666 'type': 'GLenum',
667 'valid': [
668 'GL_STREAM_DRAW',
669 'GL_STATIC_DRAW',
670 'GL_DYNAMIC_DRAW',
672 'invalid': [
673 'GL_STATIC_READ',
676 'CompressedTextureFormat': {
677 'type': 'GLenum',
678 'valid': [
681 'GLState': {
682 'type': 'GLenum',
683 'valid': [
684 # NOTE: State an Capability entries added later.
685 'GL_ACTIVE_TEXTURE',
686 'GL_ALIASED_LINE_WIDTH_RANGE',
687 'GL_ALIASED_POINT_SIZE_RANGE',
688 'GL_ALPHA_BITS',
689 'GL_ARRAY_BUFFER_BINDING',
690 'GL_BLUE_BITS',
691 'GL_COMPRESSED_TEXTURE_FORMATS',
692 'GL_CURRENT_PROGRAM',
693 'GL_DEPTH_BITS',
694 'GL_DEPTH_RANGE',
695 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
696 'GL_FRAMEBUFFER_BINDING',
697 'GL_GENERATE_MIPMAP_HINT',
698 'GL_GREEN_BITS',
699 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
700 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
701 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
702 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
703 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
704 'GL_MAX_RENDERBUFFER_SIZE',
705 'GL_MAX_TEXTURE_IMAGE_UNITS',
706 'GL_MAX_TEXTURE_SIZE',
707 'GL_MAX_VARYING_VECTORS',
708 'GL_MAX_VERTEX_ATTRIBS',
709 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
710 'GL_MAX_VERTEX_UNIFORM_VECTORS',
711 'GL_MAX_VIEWPORT_DIMS',
712 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
713 'GL_NUM_SHADER_BINARY_FORMATS',
714 'GL_PACK_ALIGNMENT',
715 'GL_RED_BITS',
716 'GL_RENDERBUFFER_BINDING',
717 'GL_SAMPLE_BUFFERS',
718 'GL_SAMPLE_COVERAGE_INVERT',
719 'GL_SAMPLE_COVERAGE_VALUE',
720 'GL_SAMPLES',
721 'GL_SCISSOR_BOX',
722 'GL_SHADER_BINARY_FORMATS',
723 'GL_SHADER_COMPILER',
724 'GL_SUBPIXEL_BITS',
725 'GL_STENCIL_BITS',
726 'GL_TEXTURE_BINDING_2D',
727 'GL_TEXTURE_BINDING_CUBE_MAP',
728 'GL_UNPACK_ALIGNMENT',
729 'GL_UNPACK_FLIP_Y_CHROMIUM',
730 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
731 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
732 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
733 # we can add this because we emulate it if the driver does not support it.
734 'GL_VERTEX_ARRAY_BINDING_OES',
735 'GL_VIEWPORT',
737 'invalid': [
738 'GL_FOG_HINT',
741 'GetTexParamTarget': {
742 'type': 'GLenum',
743 'valid': [
744 'GL_TEXTURE_2D',
745 'GL_TEXTURE_CUBE_MAP',
747 'invalid': [
748 'GL_PROXY_TEXTURE_CUBE_MAP',
751 'TextureTarget': {
752 'type': 'GLenum',
753 'valid': [
754 'GL_TEXTURE_2D',
755 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
756 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
757 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
758 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
759 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
760 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
762 'invalid': [
763 'GL_PROXY_TEXTURE_CUBE_MAP',
766 'Texture3DTarget': {
767 'type': 'GLenum',
768 'valid': [
769 'GL_TEXTURE_3D',
770 'GL_TEXTURE_2D_ARRAY',
772 'invalid': [
773 'GL_TEXTURE_2D',
776 'TextureBindTarget': {
777 'type': 'GLenum',
778 'valid': [
779 'GL_TEXTURE_2D',
780 'GL_TEXTURE_CUBE_MAP',
782 'valid_es3': [
783 'GL_TEXTURE_3D',
784 'GL_TEXTURE_2D_ARRAY',
786 'invalid': [
787 'GL_TEXTURE_1D',
788 'GL_TEXTURE_3D',
791 'TransformFeedbackBindTarget': {
792 'type': 'GLenum',
793 'valid': [
794 'GL_TRANSFORM_FEEDBACK',
796 'invalid': [
797 'GL_TEXTURE_2D',
800 'TransformFeedbackPrimitiveMode': {
801 'type': 'GLenum',
802 'valid': [
803 'GL_POINTS',
804 'GL_LINES',
805 'GL_TRIANGLES',
807 'invalid': [
808 'GL_LINE_LOOP',
811 'ShaderType': {
812 'type': 'GLenum',
813 'valid': [
814 'GL_VERTEX_SHADER',
815 'GL_FRAGMENT_SHADER',
817 'invalid': [
818 'GL_GEOMETRY_SHADER',
821 'FaceType': {
822 'type': 'GLenum',
823 'valid': [
824 'GL_FRONT',
825 'GL_BACK',
826 'GL_FRONT_AND_BACK',
829 'FaceMode': {
830 'type': 'GLenum',
831 'valid': [
832 'GL_CW',
833 'GL_CCW',
836 'CmpFunction': {
837 'type': 'GLenum',
838 'valid': [
839 'GL_NEVER',
840 'GL_LESS',
841 'GL_EQUAL',
842 'GL_LEQUAL',
843 'GL_GREATER',
844 'GL_NOTEQUAL',
845 'GL_GEQUAL',
846 'GL_ALWAYS',
849 'Equation': {
850 'type': 'GLenum',
851 'valid': [
852 'GL_FUNC_ADD',
853 'GL_FUNC_SUBTRACT',
854 'GL_FUNC_REVERSE_SUBTRACT',
856 'invalid': [
857 'GL_MIN',
858 'GL_MAX',
861 'SrcBlendFactor': {
862 'type': 'GLenum',
863 'valid': [
864 'GL_ZERO',
865 'GL_ONE',
866 'GL_SRC_COLOR',
867 'GL_ONE_MINUS_SRC_COLOR',
868 'GL_DST_COLOR',
869 'GL_ONE_MINUS_DST_COLOR',
870 'GL_SRC_ALPHA',
871 'GL_ONE_MINUS_SRC_ALPHA',
872 'GL_DST_ALPHA',
873 'GL_ONE_MINUS_DST_ALPHA',
874 'GL_CONSTANT_COLOR',
875 'GL_ONE_MINUS_CONSTANT_COLOR',
876 'GL_CONSTANT_ALPHA',
877 'GL_ONE_MINUS_CONSTANT_ALPHA',
878 'GL_SRC_ALPHA_SATURATE',
881 'DstBlendFactor': {
882 'type': 'GLenum',
883 'valid': [
884 'GL_ZERO',
885 'GL_ONE',
886 'GL_SRC_COLOR',
887 'GL_ONE_MINUS_SRC_COLOR',
888 'GL_DST_COLOR',
889 'GL_ONE_MINUS_DST_COLOR',
890 'GL_SRC_ALPHA',
891 'GL_ONE_MINUS_SRC_ALPHA',
892 'GL_DST_ALPHA',
893 'GL_ONE_MINUS_DST_ALPHA',
894 'GL_CONSTANT_COLOR',
895 'GL_ONE_MINUS_CONSTANT_COLOR',
896 'GL_CONSTANT_ALPHA',
897 'GL_ONE_MINUS_CONSTANT_ALPHA',
900 'Capability': {
901 'type': 'GLenum',
902 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
903 if 'es3' not in cap or cap['es3'] != True],
904 'valid_es3': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS
905 if 'es3' in cap and cap['es3'] == True],
906 'invalid': [
907 'GL_CLIP_PLANE0',
908 'GL_POINT_SPRITE',
911 'DrawMode': {
912 'type': 'GLenum',
913 'valid': [
914 'GL_POINTS',
915 'GL_LINE_STRIP',
916 'GL_LINE_LOOP',
917 'GL_LINES',
918 'GL_TRIANGLE_STRIP',
919 'GL_TRIANGLE_FAN',
920 'GL_TRIANGLES',
922 'invalid': [
923 'GL_QUADS',
924 'GL_POLYGON',
927 'IndexType': {
928 'type': 'GLenum',
929 'valid': [
930 'GL_UNSIGNED_BYTE',
931 'GL_UNSIGNED_SHORT',
933 'invalid': [
934 'GL_UNSIGNED_INT',
935 'GL_INT',
938 'GetMaxIndexType': {
939 'type': 'GLenum',
940 'valid': [
941 'GL_UNSIGNED_BYTE',
942 'GL_UNSIGNED_SHORT',
943 'GL_UNSIGNED_INT',
945 'invalid': [
946 'GL_INT',
949 'Attachment': {
950 'type': 'GLenum',
951 'valid': [
952 'GL_COLOR_ATTACHMENT0',
953 'GL_DEPTH_ATTACHMENT',
954 'GL_STENCIL_ATTACHMENT',
957 'BackbufferAttachment': {
958 'type': 'GLenum',
959 'valid': [
960 'GL_COLOR_EXT',
961 'GL_DEPTH_EXT',
962 'GL_STENCIL_EXT',
965 'BufferParameter': {
966 'type': 'GLenum',
967 'valid': [
968 'GL_BUFFER_SIZE',
969 'GL_BUFFER_USAGE',
971 'invalid': [
972 'GL_PIXEL_PACK_BUFFER',
975 'BufferMode': {
976 'type': 'GLenum',
977 'valid': [
978 'GL_INTERLEAVED_ATTRIBS',
979 'GL_SEPARATE_ATTRIBS',
981 'invalid': [
982 'GL_PIXEL_PACK_BUFFER',
985 'FrameBufferParameter': {
986 'type': 'GLenum',
987 'valid': [
988 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
989 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
990 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
991 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
994 'MatrixMode': {
995 'type': 'GLenum',
996 'valid': [
997 'GL_PATH_PROJECTION_CHROMIUM',
998 'GL_PATH_MODELVIEW_CHROMIUM',
1001 'ProgramParameter': {
1002 'type': 'GLenum',
1003 'valid': [
1004 'GL_DELETE_STATUS',
1005 'GL_LINK_STATUS',
1006 'GL_VALIDATE_STATUS',
1007 'GL_INFO_LOG_LENGTH',
1008 'GL_ATTACHED_SHADERS',
1009 'GL_ACTIVE_ATTRIBUTES',
1010 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1011 'GL_ACTIVE_UNIFORMS',
1012 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1015 'QueryObjectParameter': {
1016 'type': 'GLenum',
1017 'valid': [
1018 'GL_QUERY_RESULT_EXT',
1019 'GL_QUERY_RESULT_AVAILABLE_EXT',
1022 'QueryParameter': {
1023 'type': 'GLenum',
1024 'valid': [
1025 'GL_CURRENT_QUERY_EXT',
1028 'QueryTarget': {
1029 'type': 'GLenum',
1030 'valid': [
1031 'GL_ANY_SAMPLES_PASSED_EXT',
1032 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1033 'GL_COMMANDS_ISSUED_CHROMIUM',
1034 'GL_LATENCY_QUERY_CHROMIUM',
1035 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1036 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1037 'GL_COMMANDS_COMPLETED_CHROMIUM',
1040 'RenderBufferParameter': {
1041 'type': 'GLenum',
1042 'valid': [
1043 'GL_RENDERBUFFER_RED_SIZE',
1044 'GL_RENDERBUFFER_GREEN_SIZE',
1045 'GL_RENDERBUFFER_BLUE_SIZE',
1046 'GL_RENDERBUFFER_ALPHA_SIZE',
1047 'GL_RENDERBUFFER_DEPTH_SIZE',
1048 'GL_RENDERBUFFER_STENCIL_SIZE',
1049 'GL_RENDERBUFFER_WIDTH',
1050 'GL_RENDERBUFFER_HEIGHT',
1051 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1054 'SamplerParameter': {
1055 'type': 'GLenum',
1056 'valid': [
1057 'GL_TEXTURE_MAG_FILTER',
1058 'GL_TEXTURE_MIN_FILTER',
1059 'GL_TEXTURE_MIN_LOD',
1060 'GL_TEXTURE_MAX_LOD',
1061 'GL_TEXTURE_WRAP_S',
1062 'GL_TEXTURE_WRAP_T',
1063 'GL_TEXTURE_WRAP_R',
1064 'GL_TEXTURE_COMPARE_MODE',
1065 'GL_TEXTURE_COMPARE_FUNC',
1067 'invalid': [
1068 'GL_GENERATE_MIPMAP',
1071 'ShaderParameter': {
1072 'type': 'GLenum',
1073 'valid': [
1074 'GL_SHADER_TYPE',
1075 'GL_DELETE_STATUS',
1076 'GL_COMPILE_STATUS',
1077 'GL_INFO_LOG_LENGTH',
1078 'GL_SHADER_SOURCE_LENGTH',
1079 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1082 'ShaderPrecision': {
1083 'type': 'GLenum',
1084 'valid': [
1085 'GL_LOW_FLOAT',
1086 'GL_MEDIUM_FLOAT',
1087 'GL_HIGH_FLOAT',
1088 'GL_LOW_INT',
1089 'GL_MEDIUM_INT',
1090 'GL_HIGH_INT',
1093 'StringType': {
1094 'type': 'GLenum',
1095 'valid': [
1096 'GL_VENDOR',
1097 'GL_RENDERER',
1098 'GL_VERSION',
1099 'GL_SHADING_LANGUAGE_VERSION',
1100 'GL_EXTENSIONS',
1103 'TextureParameter': {
1104 'type': 'GLenum',
1105 'valid': [
1106 'GL_TEXTURE_MAG_FILTER',
1107 'GL_TEXTURE_MIN_FILTER',
1108 'GL_TEXTURE_POOL_CHROMIUM',
1109 'GL_TEXTURE_WRAP_S',
1110 'GL_TEXTURE_WRAP_T',
1112 'invalid': [
1113 'GL_GENERATE_MIPMAP',
1116 'TexturePool': {
1117 'type': 'GLenum',
1118 'valid': [
1119 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1120 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1123 'TextureWrapMode': {
1124 'type': 'GLenum',
1125 'valid': [
1126 'GL_CLAMP_TO_EDGE',
1127 'GL_MIRRORED_REPEAT',
1128 'GL_REPEAT',
1131 'TextureMinFilterMode': {
1132 'type': 'GLenum',
1133 'valid': [
1134 'GL_NEAREST',
1135 'GL_LINEAR',
1136 'GL_NEAREST_MIPMAP_NEAREST',
1137 'GL_LINEAR_MIPMAP_NEAREST',
1138 'GL_NEAREST_MIPMAP_LINEAR',
1139 'GL_LINEAR_MIPMAP_LINEAR',
1142 'TextureMagFilterMode': {
1143 'type': 'GLenum',
1144 'valid': [
1145 'GL_NEAREST',
1146 'GL_LINEAR',
1149 'TextureUsage': {
1150 'type': 'GLenum',
1151 'valid': [
1152 'GL_NONE',
1153 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1156 'VertexAttribute': {
1157 'type': 'GLenum',
1158 'valid': [
1159 # some enum that the decoder actually passes through to GL needs
1160 # to be the first listed here since it's used in unit tests.
1161 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1162 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1163 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1164 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1165 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1166 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1167 'GL_CURRENT_VERTEX_ATTRIB',
1170 'VertexPointer': {
1171 'type': 'GLenum',
1172 'valid': [
1173 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1176 'HintTarget': {
1177 'type': 'GLenum',
1178 'valid': [
1179 'GL_GENERATE_MIPMAP_HINT',
1181 'invalid': [
1182 'GL_PERSPECTIVE_CORRECTION_HINT',
1185 'HintMode': {
1186 'type': 'GLenum',
1187 'valid': [
1188 'GL_FASTEST',
1189 'GL_NICEST',
1190 'GL_DONT_CARE',
1193 'PixelStore': {
1194 'type': 'GLenum',
1195 'valid': [
1196 'GL_PACK_ALIGNMENT',
1197 'GL_UNPACK_ALIGNMENT',
1198 'GL_UNPACK_FLIP_Y_CHROMIUM',
1199 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
1200 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
1202 'invalid': [
1203 'GL_PACK_SWAP_BYTES',
1204 'GL_UNPACK_SWAP_BYTES',
1207 'PixelStoreAlignment': {
1208 'type': 'GLint',
1209 'valid': [
1210 '1',
1211 '2',
1212 '4',
1213 '8',
1215 'invalid': [
1216 '3',
1217 '9',
1220 'ReadPixelFormat': {
1221 'type': 'GLenum',
1222 'valid': [
1223 'GL_ALPHA',
1224 'GL_RGB',
1225 'GL_RGBA',
1228 'PixelType': {
1229 'type': 'GLenum',
1230 'valid': [
1231 'GL_UNSIGNED_BYTE',
1232 'GL_UNSIGNED_SHORT_5_6_5',
1233 'GL_UNSIGNED_SHORT_4_4_4_4',
1234 'GL_UNSIGNED_SHORT_5_5_5_1',
1236 'valid_es3': [
1237 'GL_BYTE',
1238 'GL_UNSIGNED_SHORT',
1239 'GL_SHORT',
1240 'GL_UNSIGNED_INT',
1241 'GL_INT',
1242 'GL_HALF_FLOAT',
1243 'GL_FLOAT',
1244 'GL_UNSIGNED_INT_2_10_10_10_REV',
1245 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1246 'GL_UNSIGNED_INT_5_9_9_9_REV',
1247 'GL_UNSIGNED_INT_24_8',
1248 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1250 'invalid': [
1251 'GL_UNSIGNED_BYTE_3_3_2',
1254 'ReadPixelType': {
1255 'type': 'GLenum',
1256 'valid': [
1257 'GL_UNSIGNED_BYTE',
1258 'GL_UNSIGNED_SHORT_5_6_5',
1259 'GL_UNSIGNED_SHORT_4_4_4_4',
1260 'GL_UNSIGNED_SHORT_5_5_5_1',
1262 'invalid': [
1263 'GL_SHORT',
1264 'GL_INT',
1267 'RenderBufferFormat': {
1268 'type': 'GLenum',
1269 'valid': [
1270 'GL_RGBA4',
1271 'GL_RGB565',
1272 'GL_RGB5_A1',
1273 'GL_DEPTH_COMPONENT16',
1274 'GL_STENCIL_INDEX8',
1277 'ShaderBinaryFormat': {
1278 'type': 'GLenum',
1279 'valid': [
1282 'StencilOp': {
1283 'type': 'GLenum',
1284 'valid': [
1285 'GL_KEEP',
1286 'GL_ZERO',
1287 'GL_REPLACE',
1288 'GL_INCR',
1289 'GL_INCR_WRAP',
1290 'GL_DECR',
1291 'GL_DECR_WRAP',
1292 'GL_INVERT',
1295 'TextureFormat': {
1296 'type': 'GLenum',
1297 'valid': [
1298 'GL_ALPHA',
1299 'GL_LUMINANCE',
1300 'GL_LUMINANCE_ALPHA',
1301 'GL_RGB',
1302 'GL_RGBA',
1304 'valid_es3': [
1305 'GL_RED',
1306 'GL_RED_INTEGER',
1307 'GL_RG',
1308 'GL_RG_INTEGER',
1309 'GL_RGB_INTEGER',
1310 'GL_RGBA_INTEGER',
1311 'GL_DEPTH_COMPONENT',
1312 'GL_DEPTH_STENCIL',
1314 'invalid': [
1315 'GL_BGRA',
1316 'GL_BGR',
1319 'TextureInternalFormat': {
1320 'type': 'GLenum',
1321 'valid': [
1322 'GL_ALPHA',
1323 'GL_LUMINANCE',
1324 'GL_LUMINANCE_ALPHA',
1325 'GL_RGB',
1326 'GL_RGBA',
1328 'valid_es3': [
1329 'GL_R8',
1330 'GL_R8_SNORM',
1331 'GL_R16F',
1332 'GL_R32F',
1333 'GL_R8UI',
1334 'GL_R8I',
1335 'GL_R16UI',
1336 'GL_R16I',
1337 'GL_R32UI',
1338 'GL_R32I',
1339 'GL_RG8',
1340 'GL_RG8_SNORM',
1341 'GL_RG16F',
1342 'GL_RG32F',
1343 'GL_RG8UI',
1344 'GL_RG8I',
1345 'GL_RG16UI',
1346 'GL_RG16I',
1347 'GL_RG32UI',
1348 'GL_RG32I',
1349 'GL_RGB8',
1350 'GL_SRGB8',
1351 'GL_RGB565',
1352 'GL_RGB8_SNORM',
1353 'GL_R11F_G11F_B10F',
1354 'GL_RGB9_E5',
1355 'GL_RGB16F',
1356 'GL_RGB32F',
1357 'GL_RGB8UI',
1358 'GL_RGB8I',
1359 'GL_RGB16UI',
1360 'GL_RGB16I',
1361 'GL_RGB32UI',
1362 'GL_RGB32I',
1363 'GL_RGBA8',
1364 'GL_SRGB8_ALPHA8',
1365 'GL_RGBA8_SNORM',
1366 'GL_RGB5_A1',
1367 'GL_RGBA4',
1368 'GL_RGB10_A2',
1369 'GL_RGBA16F',
1370 'GL_RGBA32F',
1371 'GL_RGBA8UI',
1372 'GL_RGBA8I',
1373 'GL_RGB10_A2UI',
1374 'GL_RGBA16UI',
1375 'GL_RGBA16I',
1376 'GL_RGBA32UI',
1377 'GL_RGBA32I',
1378 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1379 # We will reject them dynamically in GPU command buffer.
1380 'GL_DEPTH_COMPONENT16',
1381 'GL_DEPTH_COMPONENT24',
1382 'GL_DEPTH_COMPONENT32F',
1383 'GL_DEPTH24_STENCIL8',
1384 'GL_DEPTH32F_STENCIL8',
1386 'invalid': [
1387 'GL_BGRA',
1388 'GL_BGR',
1391 'TextureInternalFormatStorage': {
1392 'type': 'GLenum',
1393 'valid': [
1394 'GL_RGB565',
1395 'GL_RGBA4',
1396 'GL_RGB5_A1',
1397 'GL_ALPHA8_EXT',
1398 'GL_LUMINANCE8_EXT',
1399 'GL_LUMINANCE8_ALPHA8_EXT',
1400 'GL_RGB8_OES',
1401 'GL_RGBA8_OES',
1403 'valid_es3': [
1404 'GL_R8',
1405 'GL_R8_SNORM',
1406 'GL_R16F',
1407 'GL_R32F',
1408 'GL_R8UI',
1409 'GL_R8I',
1410 'GL_R16UI',
1411 'GL_R16I',
1412 'GL_R32UI',
1413 'GL_R32I',
1414 'GL_RG8',
1415 'GL_RG8_SNORM',
1416 'GL_RG16F',
1417 'GL_RG32F',
1418 'GL_RG8UI',
1419 'GL_RG8I',
1420 'GL_RG16UI',
1421 'GL_RG16I',
1422 'GL_RG32UI',
1423 'GL_RG32I',
1424 'GL_SRGB8',
1425 'GL_RGB8_SNORM',
1426 'GL_R11F_G11F_B10F',
1427 'GL_RGB9_E5',
1428 'GL_RGB16F',
1429 'GL_RGB32F',
1430 'GL_RGB8UI',
1431 'GL_RGB8I',
1432 'GL_RGB16UI',
1433 'GL_RGB16I',
1434 'GL_RGB32UI',
1435 'GL_RGB32I',
1436 'GL_SRGB8_ALPHA8',
1437 'GL_RGBA8_SNORM',
1438 'GL_RGB10_A2',
1439 'GL_RGBA16F',
1440 'GL_RGBA32F',
1441 'GL_RGBA8UI',
1442 'GL_RGBA8I',
1443 'GL_RGB10_A2UI',
1444 'GL_RGBA16UI',
1445 'GL_RGBA16I',
1446 'GL_RGBA32UI',
1447 'GL_RGBA32I',
1448 'GL_DEPTH_COMPONENT16',
1449 'GL_DEPTH_COMPONENT24',
1450 'GL_DEPTH_COMPONENT32F',
1451 'GL_DEPTH24_STENCIL8',
1452 'GL_DEPTH32F_STENCIL8',
1453 'GL_COMPRESSED_R11_EAC',
1454 'GL_COMPRESSED_SIGNED_R11_EAC',
1455 'GL_COMPRESSED_RG11_EAC',
1456 'GL_COMPRESSED_SIGNED_RG11_EAC',
1457 'GL_COMPRESSED_RGB8_ETC2',
1458 'GL_COMPRESSED_SRGB8_ETC2',
1459 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1460 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1461 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1462 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1464 'deprecated_es3': [
1465 'GL_ALPHA8_EXT',
1466 'GL_LUMINANCE8_EXT',
1467 'GL_LUMINANCE8_ALPHA8_EXT',
1468 'GL_ALPHA16F_EXT',
1469 'GL_LUMINANCE16F_EXT',
1470 'GL_LUMINANCE_ALPHA16F_EXT',
1471 'GL_ALPHA32F_EXT',
1472 'GL_LUMINANCE32F_EXT',
1473 'GL_LUMINANCE_ALPHA32F_EXT',
1476 'ImageInternalFormat': {
1477 'type': 'GLenum',
1478 'valid': [
1479 'GL_RGB',
1480 'GL_RGBA',
1483 'ImageUsage': {
1484 'type': 'GLenum',
1485 'valid': [
1486 'GL_MAP_CHROMIUM',
1487 'GL_SCANOUT_CHROMIUM'
1490 'ValueBufferTarget': {
1491 'type': 'GLenum',
1492 'valid': [
1493 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1496 'SubscriptionTarget': {
1497 'type': 'GLenum',
1498 'valid': [
1499 'GL_MOUSE_POSITION_CHROMIUM',
1502 'UniformParameter': {
1503 'type': 'GLenum',
1504 'valid': [
1505 'GL_UNIFORM_SIZE',
1506 'GL_UNIFORM_TYPE',
1507 'GL_UNIFORM_NAME_LENGTH',
1508 'GL_UNIFORM_BLOCK_INDEX',
1509 'GL_UNIFORM_OFFSET',
1510 'GL_UNIFORM_ARRAY_STRIDE',
1511 'GL_UNIFORM_MATRIX_STRIDE',
1512 'GL_UNIFORM_IS_ROW_MAJOR',
1514 'invalid': [
1515 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1518 'UniformBlockParameter': {
1519 'type': 'GLenum',
1520 'valid': [
1521 'GL_UNIFORM_BLOCK_BINDING',
1522 'GL_UNIFORM_BLOCK_DATA_SIZE',
1523 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1524 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1525 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1526 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1527 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1529 'invalid': [
1530 'GL_NEAREST',
1533 'VertexAttribType': {
1534 'type': 'GLenum',
1535 'valid': [
1536 'GL_BYTE',
1537 'GL_UNSIGNED_BYTE',
1538 'GL_SHORT',
1539 'GL_UNSIGNED_SHORT',
1540 # 'GL_FIXED', // This is not available on Desktop GL.
1541 'GL_FLOAT',
1543 'invalid': [
1544 'GL_DOUBLE',
1547 'TextureBorder': {
1548 'type': 'GLint',
1549 'is_complete': True,
1550 'valid': [
1551 '0',
1553 'invalid': [
1554 '1',
1557 'VertexAttribSize': {
1558 'type': 'GLint',
1559 'valid': [
1560 '1',
1561 '2',
1562 '3',
1563 '4',
1565 'invalid': [
1566 '0',
1567 '5',
1570 'ZeroOnly': {
1571 'type': 'GLint',
1572 'is_complete': True,
1573 'valid': [
1574 '0',
1576 'invalid': [
1577 '1',
1580 'FalseOnly': {
1581 'type': 'GLboolean',
1582 'is_complete': True,
1583 'valid': [
1584 'false',
1586 'invalid': [
1587 'true',
1590 'ResetStatus': {
1591 'type': 'GLenum',
1592 'valid': [
1593 'GL_GUILTY_CONTEXT_RESET_ARB',
1594 'GL_INNOCENT_CONTEXT_RESET_ARB',
1595 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1598 'SyncCondition': {
1599 'type': 'GLenum',
1600 'is_complete': True,
1601 'valid': [
1602 'GL_SYNC_GPU_COMMANDS_COMPLETE',
1604 'invalid': [
1605 '0',
1608 'SyncFlags': {
1609 'type': 'GLbitfield',
1610 'is_complete': True,
1611 'valid': [
1612 '0',
1614 'invalid': [
1615 '1',
1618 'SyncFlushFlags': {
1619 'type': 'GLbitfield',
1620 'valid': [
1621 'GL_SYNC_FLUSH_COMMANDS_BIT',
1622 '0',
1624 'invalid': [
1625 '0xFFFFFFFF',
1628 'SyncParameter': {
1629 'type': 'GLenum',
1630 'valid': [
1631 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
1632 'GL_OBJECT_TYPE',
1633 'GL_SYNC_CONDITION',
1634 'GL_SYNC_FLAGS',
1636 'invalid': [
1637 'GL_SYNC_FENCE',
1642 # This table specifies the different pepper interfaces that are supported for
1643 # GL commands. 'dev' is true if it's a dev interface.
1644 _PEPPER_INTERFACES = [
1645 {'name': '', 'dev': False},
1646 {'name': 'InstancedArrays', 'dev': False},
1647 {'name': 'FramebufferBlit', 'dev': False},
1648 {'name': 'FramebufferMultisample', 'dev': False},
1649 {'name': 'ChromiumEnableFeature', 'dev': False},
1650 {'name': 'ChromiumMapSub', 'dev': False},
1651 {'name': 'Query', 'dev': False},
1652 {'name': 'VertexArrayObject', 'dev': False},
1653 {'name': 'DrawBuffers', 'dev': True},
1656 # A function info object specifies the type and other special data for the
1657 # command that will be generated. A base function info object is generated by
1658 # parsing the "cmd_buffer_functions.txt", one for each function in the
1659 # file. These function info objects can be augmented and their values can be
1660 # overridden by adding an object to the table below.
1662 # Must match function names specified in "cmd_buffer_functions.txt".
1664 # cmd_comment: A comment added to the cmd format.
1665 # type: defines which handler will be used to generate code.
1666 # decoder_func: defines which function to call in the decoder to execute the
1667 # corresponding GL command. If not specified the GL command will
1668 # be called directly.
1669 # gl_test_func: GL function that is expected to be called when testing.
1670 # cmd_args: The arguments to use for the command. This overrides generating
1671 # them based on the GL function arguments.
1672 # gen_cmd: Whether or not this function geneates a command. Default = True.
1673 # data_transfer_methods: Array of methods that are used for transfering the
1674 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1675 # The default is 'immediate' if the command has one pointer
1676 # argument, otherwise 'shm'. One command is generated for each
1677 # transfer method. Affects only commands which are not of type
1678 # 'HandWritten', 'GETn' or 'GLcharN'.
1679 # Note: the command arguments that affect this are the final args,
1680 # taking cmd_args override into consideration.
1681 # impl_func: Whether or not to generate the GLES2Implementation part of this
1682 # command.
1683 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1684 # for this command.
1685 # needs_size: If True a data_size field is added to the command.
1686 # count: The number of units per element. For PUTn or PUT types.
1687 # use_count_func: If True the actual data count needs to be computed; the count
1688 # argument specifies the maximum count.
1689 # unit_test: If False no service side unit test will be generated.
1690 # client_test: If False no client side unit test will be generated.
1691 # expectation: If False the unit test will have no expected calls.
1692 # gen_func: Name of function that generates GL resource for corresponding
1693 # bind function.
1694 # states: array of states that get set by this function corresponding to
1695 # the given arguments
1696 # state_flag: name of flag that is set to true when function is called.
1697 # no_gl: no GL function is called.
1698 # valid_args: A dictionary of argument indices to args to use in unit tests
1699 # when they can not be automatically determined.
1700 # pepper_interface: The pepper interface that is used for this extension
1701 # pepper_name: The name of the function as exposed to pepper.
1702 # pepper_args: A string representing the argument list (what would appear in
1703 # C/C++ between the parentheses for the function declaration)
1704 # that the Pepper API expects for this function. Use this only if
1705 # the stable Pepper API differs from the GLES2 argument list.
1706 # invalid_test: False if no invalid test needed.
1707 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1708 # first_element_only: For PUT types, True if only the first element of an
1709 # array is used and we end up calling the single value
1710 # corresponding function. eg. TexParameteriv -> TexParameteri
1711 # extension: Function is an extension to GL and should not be exposed to
1712 # pepper unless pepper_interface is defined.
1713 # extension_flag: Function is an extension and should be enabled only when
1714 # the corresponding feature info flag is enabled. Implies
1715 # 'extension': True.
1716 # not_shared: For GENn types, True if objects can't be shared between contexts
1717 # unsafe: True = no validation is implemented on the service side and the
1718 # command is only available with --enable-unsafe-es3-apis.
1719 # id_mapping: A list of resource type names whose client side IDs need to be
1720 # mapped to service side IDs. This is only used for unsafe APIs.
1722 _FUNCTION_INFO = {
1723 'ActiveTexture': {
1724 'decoder_func': 'DoActiveTexture',
1725 'unit_test': False,
1726 'impl_func': False,
1727 'client_test': False,
1729 'AttachShader': {'decoder_func': 'DoAttachShader'},
1730 'BindAttribLocation': {
1731 'type': 'GLchar',
1732 'data_transfer_methods': ['bucket'],
1733 'needs_size': True,
1735 'BindBuffer': {
1736 'type': 'Bind',
1737 'decoder_func': 'DoBindBuffer',
1738 'gen_func': 'GenBuffersARB',
1740 'BindBufferBase': {
1741 'type': 'Bind',
1742 'id_mapping': [ 'Buffer' ],
1743 'gen_func': 'GenBuffersARB',
1744 'unsafe': True,
1746 'BindBufferRange': {
1747 'type': 'Bind',
1748 'id_mapping': [ 'Buffer' ],
1749 'gen_func': 'GenBuffersARB',
1750 'valid_args': {
1751 '3': '4',
1752 '4': '4'
1754 'unsafe': True,
1756 'BindFramebuffer': {
1757 'type': 'Bind',
1758 'decoder_func': 'DoBindFramebuffer',
1759 'gl_test_func': 'glBindFramebufferEXT',
1760 'gen_func': 'GenFramebuffersEXT',
1761 'trace_level': 1,
1763 'BindRenderbuffer': {
1764 'type': 'Bind',
1765 'decoder_func': 'DoBindRenderbuffer',
1766 'gl_test_func': 'glBindRenderbufferEXT',
1767 'gen_func': 'GenRenderbuffersEXT',
1769 'BindSampler': {
1770 'type': 'Bind',
1771 'id_mapping': [ 'Sampler' ],
1772 'unsafe': True,
1774 'BindTexture': {
1775 'type': 'Bind',
1776 'decoder_func': 'DoBindTexture',
1777 'gen_func': 'GenTextures',
1778 # TODO(gman): remove this once client side caching works.
1779 'client_test': False,
1780 'trace_level': 1,
1782 'BindTransformFeedback': {
1783 'type': 'Bind',
1784 'id_mapping': [ 'TransformFeedback' ],
1785 'unsafe': True,
1787 'BlitFramebufferCHROMIUM': {
1788 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1789 'unit_test': False,
1790 'extension_flag': 'chromium_framebuffer_multisample',
1791 'pepper_interface': 'FramebufferBlit',
1792 'pepper_name': 'BlitFramebufferEXT',
1793 'defer_reads': True,
1794 'defer_draws': True,
1795 'trace_level': 1,
1797 'BufferData': {
1798 'type': 'Manual',
1799 'data_transfer_methods': ['shm'],
1800 'client_test': False,
1802 'BufferSubData': {
1803 'type': 'Data',
1804 'client_test': False,
1805 'decoder_func': 'DoBufferSubData',
1806 'data_transfer_methods': ['shm'],
1808 'CheckFramebufferStatus': {
1809 'type': 'Is',
1810 'decoder_func': 'DoCheckFramebufferStatus',
1811 'gl_test_func': 'glCheckFramebufferStatusEXT',
1812 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1813 'result': ['GLenum'],
1815 'Clear': {
1816 'decoder_func': 'DoClear',
1817 'defer_draws': True,
1818 'trace_level': 1,
1820 'ClearBufferiv': {
1821 'type': 'PUT',
1822 'use_count_func': True,
1823 'count': 4,
1824 'unsafe': True,
1826 'ClearBufferuiv': {
1827 'type': 'PUT',
1828 'count': 4,
1829 'unsafe': True,
1831 'ClearBufferfv': {
1832 'type': 'PUT',
1833 'use_count_func': True,
1834 'count': 4,
1835 'unsafe': True,
1837 'ClearBufferfi': {
1838 'unsafe': True,
1840 'ClearColor': {
1841 'type': 'StateSet',
1842 'state': 'ClearColor',
1844 'ClearDepthf': {
1845 'type': 'StateSet',
1846 'state': 'ClearDepthf',
1847 'decoder_func': 'glClearDepth',
1848 'gl_test_func': 'glClearDepth',
1849 'valid_args': {
1850 '0': '0.5f'
1853 'ClientWaitSync': {
1854 'type': 'Custom',
1855 'data_transfer_methods': ['shm'],
1856 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
1857 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
1858 'unsafe': True,
1859 'result': ['GLenum'],
1861 'ColorMask': {
1862 'type': 'StateSet',
1863 'state': 'ColorMask',
1864 'no_gl': True,
1865 'expectation': False,
1867 'ConsumeTextureCHROMIUM': {
1868 'decoder_func': 'DoConsumeTextureCHROMIUM',
1869 'impl_func': False,
1870 'type': 'PUT',
1871 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1872 'unit_test': False,
1873 'client_test': False,
1874 'extension': "CHROMIUM_texture_mailbox",
1875 'chromium': True,
1876 'trace_level': 1,
1878 'CopyBufferSubData': {
1879 'unsafe': True,
1881 'CreateAndConsumeTextureCHROMIUM': {
1882 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
1883 'impl_func': False,
1884 'type': 'HandWritten',
1885 'data_transfer_methods': ['immediate'],
1886 'unit_test': False,
1887 'client_test': False,
1888 'extension': "CHROMIUM_texture_mailbox",
1889 'chromium': True,
1891 'GenValuebuffersCHROMIUM': {
1892 'type': 'GENn',
1893 'gl_test_func': 'glGenValuebuffersCHROMIUM',
1894 'resource_type': 'Valuebuffer',
1895 'resource_types': 'Valuebuffers',
1896 'unit_test': False,
1897 'extension': True,
1898 'chromium': True,
1900 'DeleteValuebuffersCHROMIUM': {
1901 'type': 'DELn',
1902 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
1903 'resource_type': 'Valuebuffer',
1904 'resource_types': 'Valuebuffers',
1905 'unit_test': False,
1906 'extension': True,
1907 'chromium': True,
1909 'IsValuebufferCHROMIUM': {
1910 'type': 'Is',
1911 'decoder_func': 'DoIsValuebufferCHROMIUM',
1912 'expectation': False,
1913 'extension': True,
1914 'chromium': True,
1916 'BindValuebufferCHROMIUM': {
1917 'type': 'Bind',
1918 'decoder_func': 'DoBindValueBufferCHROMIUM',
1919 'gen_func': 'GenValueBuffersCHROMIUM',
1920 'unit_test': False,
1921 'extension': True,
1922 'chromium': True,
1924 'SubscribeValueCHROMIUM': {
1925 'decoder_func': 'DoSubscribeValueCHROMIUM',
1926 'unit_test': False,
1927 'extension': True,
1928 'chromium': True,
1930 'PopulateSubscribedValuesCHROMIUM': {
1931 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
1932 'unit_test': False,
1933 'extension': True,
1934 'chromium': True,
1936 'UniformValuebufferCHROMIUM': {
1937 'decoder_func': 'DoUniformValueBufferCHROMIUM',
1938 'unit_test': False,
1939 'extension': True,
1940 'chromium': True,
1942 'ClearStencil': {
1943 'type': 'StateSet',
1944 'state': 'ClearStencil',
1946 'EnableFeatureCHROMIUM': {
1947 'type': 'Custom',
1948 'data_transfer_methods': ['shm'],
1949 'decoder_func': 'DoEnableFeatureCHROMIUM',
1950 'expectation': False,
1951 'cmd_args': 'GLuint bucket_id, GLint* result',
1952 'result': ['GLint'],
1953 'extension': True,
1954 'chromium': True,
1955 'pepper_interface': 'ChromiumEnableFeature',
1957 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1958 'CompressedTexImage2D': {
1959 'type': 'Manual',
1960 'data_transfer_methods': ['bucket', 'shm'],
1962 'CompressedTexSubImage2D': {
1963 'type': 'Data',
1964 'data_transfer_methods': ['bucket', 'shm'],
1965 'decoder_func': 'DoCompressedTexSubImage2D',
1967 'CopyTexImage2D': {
1968 'decoder_func': 'DoCopyTexImage2D',
1969 'unit_test': False,
1970 'defer_reads': True,
1972 'CopyTexSubImage2D': {
1973 'decoder_func': 'DoCopyTexSubImage2D',
1974 'defer_reads': True,
1976 'CopyTexSubImage3D': {
1977 'defer_reads': True,
1978 'unsafe': True,
1980 'CreateImageCHROMIUM': {
1981 'type': 'Manual',
1982 'cmd_args':
1983 'ClientBuffer buffer, GLsizei width, GLsizei height, '
1984 'GLenum internalformat',
1985 'result': ['GLuint'],
1986 'client_test': False,
1987 'gen_cmd': False,
1988 'expectation': False,
1989 'extension': True,
1990 'chromium': True,
1992 'DestroyImageCHROMIUM': {
1993 'type': 'Manual',
1994 'client_test': False,
1995 'gen_cmd': False,
1996 'extension': True,
1997 'chromium': True,
1999 'CreateGpuMemoryBufferImageCHROMIUM': {
2000 'type': 'Manual',
2001 'cmd_args':
2002 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
2003 'result': ['GLuint'],
2004 'client_test': False,
2005 'gen_cmd': False,
2006 'expectation': False,
2007 'extension': True,
2008 'chromium': True,
2010 'CreateProgram': {
2011 'type': 'Create',
2012 'client_test': False,
2014 'CreateShader': {
2015 'type': 'Create',
2016 'client_test': False,
2018 'BlendColor': {
2019 'type': 'StateSet',
2020 'state': 'BlendColor',
2022 'BlendEquation': {
2023 'type': 'StateSetRGBAlpha',
2024 'state': 'BlendEquation',
2025 'valid_args': {
2026 '0': 'GL_FUNC_SUBTRACT'
2029 'BlendEquationSeparate': {
2030 'type': 'StateSet',
2031 'state': 'BlendEquation',
2032 'valid_args': {
2033 '0': 'GL_FUNC_SUBTRACT'
2036 'BlendFunc': {
2037 'type': 'StateSetRGBAlpha',
2038 'state': 'BlendFunc',
2040 'BlendFuncSeparate': {
2041 'type': 'StateSet',
2042 'state': 'BlendFunc',
2044 'BlendBarrierKHR': {
2045 'gl_test_func': 'glBlendBarrierKHR',
2046 'extension': True,
2047 'extension_flag': 'blend_equation_advanced',
2048 'client_test': False,
2050 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2051 'StencilFunc': {
2052 'type': 'StateSetFrontBack',
2053 'state': 'StencilFunc',
2055 'StencilFuncSeparate': {
2056 'type': 'StateSetFrontBackSeparate',
2057 'state': 'StencilFunc',
2059 'StencilOp': {
2060 'type': 'StateSetFrontBack',
2061 'state': 'StencilOp',
2062 'valid_args': {
2063 '1': 'GL_INCR'
2066 'StencilOpSeparate': {
2067 'type': 'StateSetFrontBackSeparate',
2068 'state': 'StencilOp',
2069 'valid_args': {
2070 '1': 'GL_INCR'
2073 'Hint': {
2074 'type': 'StateSetNamedParameter',
2075 'state': 'Hint',
2077 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2078 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2079 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2080 'LineWidth': {
2081 'type': 'StateSet',
2082 'state': 'LineWidth',
2083 'valid_args': {
2084 '0': '0.5f'
2087 'PolygonOffset': {
2088 'type': 'StateSet',
2089 'state': 'PolygonOffset',
2091 'DeleteBuffers': {
2092 'type': 'DELn',
2093 'gl_test_func': 'glDeleteBuffersARB',
2094 'resource_type': 'Buffer',
2095 'resource_types': 'Buffers',
2097 'DeleteFramebuffers': {
2098 'type': 'DELn',
2099 'gl_test_func': 'glDeleteFramebuffersEXT',
2100 'resource_type': 'Framebuffer',
2101 'resource_types': 'Framebuffers',
2103 'DeleteProgram': { 'type': 'Delete' },
2104 'DeleteRenderbuffers': {
2105 'type': 'DELn',
2106 'gl_test_func': 'glDeleteRenderbuffersEXT',
2107 'resource_type': 'Renderbuffer',
2108 'resource_types': 'Renderbuffers',
2110 'DeleteSamplers': {
2111 'type': 'DELn',
2112 'resource_type': 'Sampler',
2113 'resource_types': 'Samplers',
2114 'unsafe': True,
2116 'DeleteShader': { 'type': 'Delete' },
2117 'DeleteSync': {
2118 'type': 'Delete',
2119 'cmd_args': 'GLuint sync',
2120 'resource_type': 'Sync',
2121 'unsafe': True,
2123 'DeleteTextures': {
2124 'type': 'DELn',
2125 'resource_type': 'Texture',
2126 'resource_types': 'Textures',
2128 'DeleteTransformFeedbacks': {
2129 'type': 'DELn',
2130 'resource_type': 'TransformFeedback',
2131 'resource_types': 'TransformFeedbacks',
2132 'unsafe': True,
2134 'DepthRangef': {
2135 'decoder_func': 'DoDepthRangef',
2136 'gl_test_func': 'glDepthRange',
2138 'DepthMask': {
2139 'type': 'StateSet',
2140 'state': 'DepthMask',
2141 'no_gl': True,
2142 'expectation': False,
2144 'DetachShader': {'decoder_func': 'DoDetachShader'},
2145 'Disable': {
2146 'decoder_func': 'DoDisable',
2147 'impl_func': False,
2148 'client_test': False,
2150 'DisableVertexAttribArray': {
2151 'decoder_func': 'DoDisableVertexAttribArray',
2152 'impl_decl': False,
2154 'DrawArrays': {
2155 'type': 'Manual',
2156 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2157 'defer_draws': True,
2158 'trace_level': 2,
2160 'DrawElements': {
2161 'type': 'Manual',
2162 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2163 'GLenumIndexType type, GLuint index_offset',
2164 'client_test': False,
2165 'defer_draws': True,
2166 'trace_level': 2,
2168 'DrawRangeElements': {
2169 'type': 'Manual',
2170 'gen_cmd': 'False',
2171 'unsafe': True,
2173 'Enable': {
2174 'decoder_func': 'DoEnable',
2175 'impl_func': False,
2176 'client_test': False,
2178 'EnableVertexAttribArray': {
2179 'decoder_func': 'DoEnableVertexAttribArray',
2180 'impl_decl': False,
2182 'FenceSync': {
2183 'type': 'Create',
2184 'client_test': False,
2185 'unsafe': True,
2187 'Finish': {
2188 'impl_func': False,
2189 'client_test': False,
2190 'decoder_func': 'DoFinish',
2191 'defer_reads': True,
2193 'Flush': {
2194 'impl_func': False,
2195 'decoder_func': 'DoFlush',
2197 'FramebufferRenderbuffer': {
2198 'decoder_func': 'DoFramebufferRenderbuffer',
2199 'gl_test_func': 'glFramebufferRenderbufferEXT',
2201 'FramebufferTexture2D': {
2202 'decoder_func': 'DoFramebufferTexture2D',
2203 'gl_test_func': 'glFramebufferTexture2DEXT',
2204 'trace_level': 1,
2206 'FramebufferTexture2DMultisampleEXT': {
2207 'decoder_func': 'DoFramebufferTexture2DMultisample',
2208 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2209 'expectation': False,
2210 'unit_test': False,
2211 'extension_flag': 'multisampled_render_to_texture',
2212 'trace_level': 1,
2214 'FramebufferTextureLayer': {
2215 'decoder_func': 'DoFramebufferTextureLayer',
2216 'unsafe': True,
2218 'GenerateMipmap': {
2219 'decoder_func': 'DoGenerateMipmap',
2220 'gl_test_func': 'glGenerateMipmapEXT',
2222 'GenBuffers': {
2223 'type': 'GENn',
2224 'gl_test_func': 'glGenBuffersARB',
2225 'resource_type': 'Buffer',
2226 'resource_types': 'Buffers',
2228 'GenMailboxCHROMIUM': {
2229 'type': 'HandWritten',
2230 'impl_func': False,
2231 'extension': "CHROMIUM_texture_mailbox",
2232 'chromium': True,
2234 'GenFramebuffers': {
2235 'type': 'GENn',
2236 'gl_test_func': 'glGenFramebuffersEXT',
2237 'resource_type': 'Framebuffer',
2238 'resource_types': 'Framebuffers',
2240 'GenRenderbuffers': {
2241 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2242 'resource_type': 'Renderbuffer',
2243 'resource_types': 'Renderbuffers',
2245 'GenSamplers': {
2246 'type': 'GENn',
2247 'gl_test_func': 'glGenSamplers',
2248 'resource_type': 'Sampler',
2249 'resource_types': 'Samplers',
2250 'unsafe': True,
2252 'GenTextures': {
2253 'type': 'GENn',
2254 'gl_test_func': 'glGenTextures',
2255 'resource_type': 'Texture',
2256 'resource_types': 'Textures',
2258 'GenTransformFeedbacks': {
2259 'type': 'GENn',
2260 'gl_test_func': 'glGenTransformFeedbacks',
2261 'resource_type': 'TransformFeedback',
2262 'resource_types': 'TransformFeedbacks',
2263 'unsafe': True,
2265 'GetActiveAttrib': {
2266 'type': 'Custom',
2267 'data_transfer_methods': ['shm'],
2268 'cmd_args':
2269 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2270 'void* result',
2271 'result': [
2272 'int32_t success',
2273 'int32_t size',
2274 'uint32_t type',
2277 'GetActiveUniform': {
2278 'type': 'Custom',
2279 'data_transfer_methods': ['shm'],
2280 'cmd_args':
2281 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2282 'void* result',
2283 'result': [
2284 'int32_t success',
2285 'int32_t size',
2286 'uint32_t type',
2289 'GetActiveUniformBlockiv': {
2290 'type': 'Custom',
2291 'data_transfer_methods': ['shm'],
2292 'result': ['SizedResult<GLint>'],
2293 'unsafe': True,
2295 'GetActiveUniformBlockName': {
2296 'type': 'Custom',
2297 'data_transfer_methods': ['shm'],
2298 'cmd_args':
2299 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2300 'void* result',
2301 'result': ['int32_t'],
2302 'unsafe': True,
2304 'GetActiveUniformsiv': {
2305 'type': 'Custom',
2306 'data_transfer_methods': ['shm'],
2307 'cmd_args':
2308 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2309 'GLint* params',
2310 'result': ['SizedResult<GLint>'],
2311 'unsafe': True,
2313 'GetAttachedShaders': {
2314 'type': 'Custom',
2315 'data_transfer_methods': ['shm'],
2316 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2317 'result': ['SizedResult<GLuint>'],
2319 'GetAttribLocation': {
2320 'type': 'Custom',
2321 'data_transfer_methods': ['shm'],
2322 'cmd_args':
2323 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2324 'result': ['GLint'],
2325 'error_return': -1,
2327 'GetFragDataLocation': {
2328 'type': 'Custom',
2329 'data_transfer_methods': ['shm'],
2330 'cmd_args':
2331 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2332 'result': ['GLint'],
2333 'error_return': -1,
2334 'unsafe': True,
2336 'GetBooleanv': {
2337 'type': 'GETn',
2338 'result': ['SizedResult<GLboolean>'],
2339 'decoder_func': 'DoGetBooleanv',
2340 'gl_test_func': 'glGetBooleanv',
2342 'GetBufferParameteriv': {
2343 'type': 'GETn',
2344 'result': ['SizedResult<GLint>'],
2345 'decoder_func': 'DoGetBufferParameteriv',
2346 'expectation': False,
2347 'shadowed': True,
2349 'GetError': {
2350 'type': 'Is',
2351 'decoder_func': 'GetErrorState()->GetGLError',
2352 'impl_func': False,
2353 'result': ['GLenum'],
2354 'client_test': False,
2356 'GetFloatv': {
2357 'type': 'GETn',
2358 'result': ['SizedResult<GLfloat>'],
2359 'decoder_func': 'DoGetFloatv',
2360 'gl_test_func': 'glGetFloatv',
2362 'GetFramebufferAttachmentParameteriv': {
2363 'type': 'GETn',
2364 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2365 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2366 'result': ['SizedResult<GLint>'],
2368 'GetIntegerv': {
2369 'type': 'GETn',
2370 'result': ['SizedResult<GLint>'],
2371 'decoder_func': 'DoGetIntegerv',
2372 'client_test': False,
2374 'GetInternalformativ': {
2375 'type': 'GETn',
2376 'result': ['SizedResult<GLint>'],
2377 'unsafe': True,
2379 'GetMaxValueInBufferCHROMIUM': {
2380 'type': 'Is',
2381 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2382 'result': ['GLuint'],
2383 'unit_test': False,
2384 'client_test': False,
2385 'extension': True,
2386 'chromium': True,
2387 'impl_func': False,
2389 'GetProgramiv': {
2390 'type': 'GETn',
2391 'decoder_func': 'DoGetProgramiv',
2392 'result': ['SizedResult<GLint>'],
2393 'expectation': False,
2395 'GetProgramInfoCHROMIUM': {
2396 'type': 'Custom',
2397 'expectation': False,
2398 'impl_func': False,
2399 'extension': True,
2400 'chromium': True,
2401 'client_test': False,
2402 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2403 'result': [
2404 'uint32_t link_status',
2405 'uint32_t num_attribs',
2406 'uint32_t num_uniforms',
2409 'GetProgramInfoLog': {
2410 'type': 'STRn',
2411 'expectation': False,
2413 'GetRenderbufferParameteriv': {
2414 'type': 'GETn',
2415 'decoder_func': 'DoGetRenderbufferParameteriv',
2416 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2417 'result': ['SizedResult<GLint>'],
2419 'GetSamplerParameterfv': {
2420 'type': 'GETn',
2421 'result': ['SizedResult<GLfloat>'],
2422 'id_mapping': [ 'Sampler' ],
2423 'unsafe': True,
2425 'GetSamplerParameteriv': {
2426 'type': 'GETn',
2427 'result': ['SizedResult<GLint>'],
2428 'id_mapping': [ 'Sampler' ],
2429 'unsafe': True,
2431 'GetShaderiv': {
2432 'type': 'GETn',
2433 'decoder_func': 'DoGetShaderiv',
2434 'result': ['SizedResult<GLint>'],
2436 'GetShaderInfoLog': {
2437 'type': 'STRn',
2438 'get_len_func': 'glGetShaderiv',
2439 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2440 'unit_test': False,
2442 'GetShaderPrecisionFormat': {
2443 'type': 'Custom',
2444 'data_transfer_methods': ['shm'],
2445 'cmd_args':
2446 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2447 'void* result',
2448 'result': [
2449 'int32_t success',
2450 'int32_t min_range',
2451 'int32_t max_range',
2452 'int32_t precision',
2455 'GetShaderSource': {
2456 'type': 'STRn',
2457 'get_len_func': 'DoGetShaderiv',
2458 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2459 'unit_test': False,
2460 'client_test': False,
2462 'GetString': {
2463 'type': 'Custom',
2464 'client_test': False,
2465 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2467 'GetSynciv': {
2468 'type': 'GETn',
2469 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2470 'result': ['SizedResult<GLint>'],
2471 'id_mapping': ['Sync'],
2472 'unsafe': True,
2474 'GetTexParameterfv': {
2475 'type': 'GETn',
2476 'decoder_func': 'DoGetTexParameterfv',
2477 'result': ['SizedResult<GLfloat>']
2479 'GetTexParameteriv': {
2480 'type': 'GETn',
2481 'decoder_func': 'DoGetTexParameteriv',
2482 'result': ['SizedResult<GLint>']
2484 'GetTranslatedShaderSourceANGLE': {
2485 'type': 'STRn',
2486 'get_len_func': 'DoGetShaderiv',
2487 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2488 'unit_test': False,
2489 'extension': True,
2491 'GetUniformBlockIndex': {
2492 'type': 'Custom',
2493 'data_transfer_methods': ['shm'],
2494 'cmd_args':
2495 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2496 'result': ['GLuint'],
2497 'error_return': 'GL_INVALID_INDEX',
2498 'unsafe': True,
2500 'GetUniformBlocksCHROMIUM': {
2501 'type': 'Custom',
2502 'expectation': False,
2503 'impl_func': False,
2504 'extension': True,
2505 'chromium': True,
2506 'client_test': False,
2507 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2508 'result': ['uint32_t'],
2509 'unsafe': True,
2511 'GetUniformsES3CHROMIUM': {
2512 'type': 'Custom',
2513 'expectation': False,
2514 'impl_func': False,
2515 'extension': True,
2516 'chromium': True,
2517 'client_test': False,
2518 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2519 'result': ['uint32_t'],
2520 'unsafe': True,
2522 'GetTransformFeedbackVarying': {
2523 'type': 'Custom',
2524 'data_transfer_methods': ['shm'],
2525 'cmd_args':
2526 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2527 'void* result',
2528 'result': [
2529 'int32_t success',
2530 'int32_t size',
2531 'uint32_t type',
2533 'unsafe': True,
2535 'GetTransformFeedbackVaryingsCHROMIUM': {
2536 'type': 'Custom',
2537 'expectation': False,
2538 'impl_func': False,
2539 'extension': True,
2540 'chromium': True,
2541 'client_test': False,
2542 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2543 'result': ['uint32_t'],
2544 'unsafe': True,
2546 'GetUniformfv': {
2547 'type': 'Custom',
2548 'data_transfer_methods': ['shm'],
2549 'result': ['SizedResult<GLfloat>'],
2551 'GetUniformiv': {
2552 'type': 'Custom',
2553 'data_transfer_methods': ['shm'],
2554 'result': ['SizedResult<GLint>'],
2556 'GetUniformIndices': {
2557 'type': 'Custom',
2558 'data_transfer_methods': ['shm'],
2559 'result': ['SizedResult<GLuint>'],
2560 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
2561 'GLuint* indices',
2562 'unsafe': True,
2564 'GetUniformLocation': {
2565 'type': 'Custom',
2566 'data_transfer_methods': ['shm'],
2567 'cmd_args':
2568 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2569 'result': ['GLint'],
2570 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
2572 'GetVertexAttribfv': {
2573 'type': 'GETn',
2574 'result': ['SizedResult<GLfloat>'],
2575 'impl_decl': False,
2576 'decoder_func': 'DoGetVertexAttribfv',
2577 'expectation': False,
2578 'client_test': False,
2580 'GetVertexAttribiv': {
2581 'type': 'GETn',
2582 'result': ['SizedResult<GLint>'],
2583 'impl_decl': False,
2584 'decoder_func': 'DoGetVertexAttribiv',
2585 'expectation': False,
2586 'client_test': False,
2588 'GetVertexAttribPointerv': {
2589 'type': 'Custom',
2590 'data_transfer_methods': ['shm'],
2591 'result': ['SizedResult<GLuint>'],
2592 'client_test': False,
2594 'InvalidateFramebuffer': {
2595 'type': 'PUTn',
2596 'count': 1,
2597 'client_test': False,
2598 'unit_test': False,
2599 'unsafe': True,
2601 'InvalidateSubFramebuffer': {
2602 'type': 'PUTn',
2603 'count': 1,
2604 'client_test': False,
2605 'unit_test': False,
2606 'unsafe': True,
2608 'IsBuffer': {
2609 'type': 'Is',
2610 'decoder_func': 'DoIsBuffer',
2611 'expectation': False,
2613 'IsEnabled': {
2614 'type': 'Is',
2615 'decoder_func': 'DoIsEnabled',
2616 'client_test': False,
2617 'impl_func': False,
2618 'expectation': False,
2620 'IsFramebuffer': {
2621 'type': 'Is',
2622 'decoder_func': 'DoIsFramebuffer',
2623 'expectation': False,
2625 'IsProgram': {
2626 'type': 'Is',
2627 'decoder_func': 'DoIsProgram',
2628 'expectation': False,
2630 'IsRenderbuffer': {
2631 'type': 'Is',
2632 'decoder_func': 'DoIsRenderbuffer',
2633 'expectation': False,
2635 'IsShader': {
2636 'type': 'Is',
2637 'decoder_func': 'DoIsShader',
2638 'expectation': False,
2640 'IsSampler': {
2641 'type': 'Is',
2642 'id_mapping': [ 'Sampler' ],
2643 'expectation': False,
2644 'unsafe': True,
2646 'IsSync': {
2647 'type': 'Is',
2648 'id_mapping': [ 'Sync' ],
2649 'cmd_args': 'GLuint sync',
2650 'expectation': False,
2651 'unsafe': True,
2653 'IsTexture': {
2654 'type': 'Is',
2655 'decoder_func': 'DoIsTexture',
2656 'expectation': False,
2658 'IsTransformFeedback': {
2659 'type': 'Is',
2660 'id_mapping': [ 'TransformFeedback' ],
2661 'expectation': False,
2662 'unsafe': True,
2664 'LinkProgram': {
2665 'decoder_func': 'DoLinkProgram',
2666 'impl_func': False,
2668 'MapBufferCHROMIUM': {
2669 'gen_cmd': False,
2670 'extension': True,
2671 'chromium': True,
2672 'client_test': False,
2674 'MapBufferSubDataCHROMIUM': {
2675 'gen_cmd': False,
2676 'extension': True,
2677 'chromium': True,
2678 'client_test': False,
2679 'pepper_interface': 'ChromiumMapSub',
2681 'MapTexSubImage2DCHROMIUM': {
2682 'gen_cmd': False,
2683 'extension': "CHROMIUM_sub_image",
2684 'chromium': True,
2685 'client_test': False,
2686 'pepper_interface': 'ChromiumMapSub',
2688 'MapBufferRange': {
2689 'type': 'Custom',
2690 'data_transfer_methods': ['shm'],
2691 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
2692 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
2693 'uint32_t data_shm_id, uint32_t data_shm_offset, '
2694 'uint32_t result_shm_id, uint32_t result_shm_offset',
2695 'unsafe': True,
2696 'result': ['uint32_t'],
2698 'PauseTransformFeedback': {
2699 'unsafe': True,
2701 'PixelStorei': {'type': 'Manual'},
2702 'PostSubBufferCHROMIUM': {
2703 'type': 'Custom',
2704 'impl_func': False,
2705 'unit_test': False,
2706 'client_test': False,
2707 'extension': True,
2708 'chromium': True,
2710 'ProduceTextureCHROMIUM': {
2711 'decoder_func': 'DoProduceTextureCHROMIUM',
2712 'impl_func': False,
2713 'type': 'PUT',
2714 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2715 'unit_test': False,
2716 'client_test': False,
2717 'extension': "CHROMIUM_texture_mailbox",
2718 'chromium': True,
2719 'trace_level': 1,
2721 'ProduceTextureDirectCHROMIUM': {
2722 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
2723 'impl_func': False,
2724 'type': 'PUT',
2725 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2726 'unit_test': False,
2727 'client_test': False,
2728 'extension': "CHROMIUM_texture_mailbox",
2729 'chromium': True,
2730 'trace_level': 1,
2732 'RenderbufferStorage': {
2733 'decoder_func': 'DoRenderbufferStorage',
2734 'gl_test_func': 'glRenderbufferStorageEXT',
2735 'expectation': False,
2737 'RenderbufferStorageMultisampleCHROMIUM': {
2738 'cmd_comment':
2739 '// GL_CHROMIUM_framebuffer_multisample\n',
2740 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
2741 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
2742 'expectation': False,
2743 'unit_test': False,
2744 'extension_flag': 'chromium_framebuffer_multisample',
2745 'pepper_interface': 'FramebufferMultisample',
2746 'pepper_name': 'RenderbufferStorageMultisampleEXT',
2748 'RenderbufferStorageMultisampleEXT': {
2749 'cmd_comment':
2750 '// GL_EXT_multisampled_render_to_texture\n',
2751 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
2752 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
2753 'expectation': False,
2754 'unit_test': False,
2755 'extension_flag': 'multisampled_render_to_texture',
2757 'ReadBuffer': {
2758 'unsafe': True,
2760 'ReadPixels': {
2761 'cmd_comment':
2762 '// ReadPixels has the result separated from the pixel buffer so that\n'
2763 '// it is easier to specify the result going to some specific place\n'
2764 '// that exactly fits the rectangle of pixels.\n',
2765 'type': 'Custom',
2766 'data_transfer_methods': ['shm'],
2767 'impl_func': False,
2768 'client_test': False,
2769 'cmd_args':
2770 'GLint x, GLint y, GLsizei width, GLsizei height, '
2771 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
2772 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
2773 'uint32_t result_shm_id, uint32_t result_shm_offset, '
2774 'GLboolean async',
2775 'result': ['uint32_t'],
2776 'defer_reads': True,
2778 'ReleaseShaderCompiler': {
2779 'decoder_func': 'DoReleaseShaderCompiler',
2780 'unit_test': False,
2782 'ResumeTransformFeedback': {
2783 'unsafe': True,
2785 'SamplerParameterf': {
2786 'valid_args': {
2787 '2': 'GL_NEAREST'
2789 'id_mapping': [ 'Sampler' ],
2790 'unsafe': True,
2792 'SamplerParameterfv': {
2793 'type': 'PUT',
2794 'data_value': 'GL_NEAREST',
2795 'count': 1,
2796 'gl_test_func': 'glSamplerParameterf',
2797 'decoder_func': 'DoSamplerParameterfv',
2798 'first_element_only': True,
2799 'id_mapping': [ 'Sampler' ],
2800 'unsafe': True,
2802 'SamplerParameteri': {
2803 'valid_args': {
2804 '2': 'GL_NEAREST'
2806 'id_mapping': [ 'Sampler' ],
2807 'unsafe': True,
2809 'SamplerParameteriv': {
2810 'type': 'PUT',
2811 'data_value': 'GL_NEAREST',
2812 'count': 1,
2813 'gl_test_func': 'glSamplerParameteri',
2814 'decoder_func': 'DoSamplerParameteriv',
2815 'first_element_only': True,
2816 'unsafe': True,
2818 'ShaderBinary': {
2819 'type': 'Custom',
2820 'client_test': False,
2822 'ShaderSource': {
2823 'type': 'PUTSTR',
2824 'decoder_func': 'DoShaderSource',
2825 'expectation': False,
2826 'data_transfer_methods': ['bucket'],
2827 'cmd_args':
2828 'GLuint shader, const char** str',
2829 'pepper_args':
2830 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2832 'StencilMask': {
2833 'type': 'StateSetFrontBack',
2834 'state': 'StencilMask',
2835 'no_gl': True,
2836 'expectation': False,
2838 'StencilMaskSeparate': {
2839 'type': 'StateSetFrontBackSeparate',
2840 'state': 'StencilMask',
2841 'no_gl': True,
2842 'expectation': False,
2844 'SwapBuffers': {
2845 'impl_func': False,
2846 'decoder_func': 'DoSwapBuffers',
2847 'unit_test': False,
2848 'client_test': False,
2849 'extension': True,
2850 'trace_level': 1,
2852 'SwapInterval': {
2853 'impl_func': False,
2854 'decoder_func': 'DoSwapInterval',
2855 'unit_test': False,
2856 'client_test': False,
2857 'extension': True,
2858 'trace_level': 1,
2860 'TexImage2D': {
2861 'type': 'Manual',
2862 'data_transfer_methods': ['shm'],
2863 'client_test': False,
2865 'TexImage3D': {
2866 'type': 'Manual',
2867 'data_transfer_methods': ['shm'],
2868 'client_test': False,
2869 'unsafe': True,
2871 'TexParameterf': {
2872 'decoder_func': 'DoTexParameterf',
2873 'valid_args': {
2874 '2': 'GL_NEAREST'
2877 'TexParameteri': {
2878 'decoder_func': 'DoTexParameteri',
2879 'valid_args': {
2880 '2': 'GL_NEAREST'
2883 'TexParameterfv': {
2884 'type': 'PUT',
2885 'data_value': 'GL_NEAREST',
2886 'count': 1,
2887 'decoder_func': 'DoTexParameterfv',
2888 'gl_test_func': 'glTexParameterf',
2889 'first_element_only': True,
2891 'TexParameteriv': {
2892 'type': 'PUT',
2893 'data_value': 'GL_NEAREST',
2894 'count': 1,
2895 'decoder_func': 'DoTexParameteriv',
2896 'gl_test_func': 'glTexParameteri',
2897 'first_element_only': True,
2899 'TexStorage3D': {
2900 'unsafe': True,
2902 'TexSubImage2D': {
2903 'type': 'Manual',
2904 'data_transfer_methods': ['shm'],
2905 'client_test': False,
2906 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2907 'GLint xoffset, GLint yoffset, '
2908 'GLsizei width, GLsizei height, '
2909 'GLenumTextureFormat format, GLenumPixelType type, '
2910 'const void* pixels, GLboolean internal'
2912 'TexSubImage3D': {
2913 'type': 'Manual',
2914 'data_transfer_methods': ['shm'],
2915 'client_test': False,
2916 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2917 'GLint xoffset, GLint yoffset, GLint zoffset, '
2918 'GLsizei width, GLsizei height, GLsizei depth, '
2919 'GLenumTextureFormat format, GLenumPixelType type, '
2920 'const void* pixels, GLboolean internal',
2921 'unsafe': True,
2923 'TransformFeedbackVaryings': {
2924 'type': 'PUTSTR',
2925 'data_transfer_methods': ['bucket'],
2926 'decoder_func': 'DoTransformFeedbackVaryings',
2927 'cmd_args':
2928 'GLuint program, const char** varyings, GLenum buffermode',
2929 'unsafe': True,
2931 'Uniform1f': {'type': 'PUTXn', 'count': 1},
2932 'Uniform1fv': {
2933 'type': 'PUTn',
2934 'count': 1,
2935 'decoder_func': 'DoUniform1fv',
2937 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2938 'Uniform1iv': {
2939 'type': 'PUTn',
2940 'count': 1,
2941 'decoder_func': 'DoUniform1iv',
2942 'unit_test': False,
2944 'Uniform1ui': {
2945 'type': 'PUTXn',
2946 'count': 1,
2947 'unsafe': True,
2949 'Uniform1uiv': {
2950 'type': 'PUTn',
2951 'count': 1,
2952 'unsafe': True,
2954 'Uniform2i': {'type': 'PUTXn', 'count': 2},
2955 'Uniform2f': {'type': 'PUTXn', 'count': 2},
2956 'Uniform2fv': {
2957 'type': 'PUTn',
2958 'count': 2,
2959 'decoder_func': 'DoUniform2fv',
2961 'Uniform2iv': {
2962 'type': 'PUTn',
2963 'count': 2,
2964 'decoder_func': 'DoUniform2iv',
2966 'Uniform2ui': {
2967 'type': 'PUTXn',
2968 'count': 2,
2969 'unsafe': True,
2971 'Uniform2uiv': {
2972 'type': 'PUTn',
2973 'count': 2,
2974 'unsafe': True,
2976 'Uniform3i': {'type': 'PUTXn', 'count': 3},
2977 'Uniform3f': {'type': 'PUTXn', 'count': 3},
2978 'Uniform3fv': {
2979 'type': 'PUTn',
2980 'count': 3,
2981 'decoder_func': 'DoUniform3fv',
2983 'Uniform3iv': {
2984 'type': 'PUTn',
2985 'count': 3,
2986 'decoder_func': 'DoUniform3iv',
2988 'Uniform3ui': {
2989 'type': 'PUTXn',
2990 'count': 3,
2991 'unsafe': True,
2993 'Uniform3uiv': {
2994 'type': 'PUTn',
2995 'count': 3,
2996 'unsafe': True,
2998 'Uniform4i': {'type': 'PUTXn', 'count': 4},
2999 'Uniform4f': {'type': 'PUTXn', 'count': 4},
3000 'Uniform4fv': {
3001 'type': 'PUTn',
3002 'count': 4,
3003 'decoder_func': 'DoUniform4fv',
3005 'Uniform4iv': {
3006 'type': 'PUTn',
3007 'count': 4,
3008 'decoder_func': 'DoUniform4iv',
3010 'Uniform4ui': {
3011 'type': 'PUTXn',
3012 'count': 4,
3013 'unsafe': True,
3015 'Uniform4uiv': {
3016 'type': 'PUTn',
3017 'count': 4,
3018 'unsafe': True,
3020 'UniformMatrix2fv': {
3021 'type': 'PUTn',
3022 'count': 4,
3023 'decoder_func': 'DoUniformMatrix2fv',
3025 'UniformMatrix2x3fv': {
3026 'type': 'PUTn',
3027 'count': 6,
3028 'unsafe': True,
3030 'UniformMatrix2x4fv': {
3031 'type': 'PUTn',
3032 'count': 8,
3033 'unsafe': True,
3035 'UniformMatrix3fv': {
3036 'type': 'PUTn',
3037 'count': 9,
3038 'decoder_func': 'DoUniformMatrix3fv',
3040 'UniformMatrix3x2fv': {
3041 'type': 'PUTn',
3042 'count': 6,
3043 'unsafe': True,
3045 'UniformMatrix3x4fv': {
3046 'type': 'PUTn',
3047 'count': 12,
3048 'unsafe': True,
3050 'UniformMatrix4fv': {
3051 'type': 'PUTn',
3052 'count': 16,
3053 'decoder_func': 'DoUniformMatrix4fv',
3055 'UniformMatrix4x2fv': {
3056 'type': 'PUTn',
3057 'count': 8,
3058 'unsafe': True,
3060 'UniformMatrix4x3fv': {
3061 'type': 'PUTn',
3062 'count': 12,
3063 'unsafe': True,
3065 'UniformBlockBinding': {
3066 'type': 'Custom',
3067 'impl_func': False,
3068 'unsafe': True,
3070 'UnmapBufferCHROMIUM': {
3071 'gen_cmd': False,
3072 'extension': True,
3073 'chromium': True,
3074 'client_test': False,
3076 'UnmapBufferSubDataCHROMIUM': {
3077 'gen_cmd': False,
3078 'extension': True,
3079 'chromium': True,
3080 'client_test': False,
3081 'pepper_interface': 'ChromiumMapSub',
3083 'UnmapBuffer': {
3084 'type': 'Custom',
3085 'unsafe': True,
3087 'UnmapTexSubImage2DCHROMIUM': {
3088 'gen_cmd': False,
3089 'extension': "CHROMIUM_sub_image",
3090 'chromium': True,
3091 'client_test': False,
3092 'pepper_interface': 'ChromiumMapSub',
3094 'UseProgram': {
3095 'type': 'Bind',
3096 'decoder_func': 'DoUseProgram',
3098 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3099 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3100 'VertexAttrib1fv': {
3101 'type': 'PUT',
3102 'count': 1,
3103 'decoder_func': 'DoVertexAttrib1fv',
3105 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3106 'VertexAttrib2fv': {
3107 'type': 'PUT',
3108 'count': 2,
3109 'decoder_func': 'DoVertexAttrib2fv',
3111 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3112 'VertexAttrib3fv': {
3113 'type': 'PUT',
3114 'count': 3,
3115 'decoder_func': 'DoVertexAttrib3fv',
3117 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3118 'VertexAttrib4fv': {
3119 'type': 'PUT',
3120 'count': 4,
3121 'decoder_func': 'DoVertexAttrib4fv',
3123 'VertexAttribI4i': {
3124 'unsafe': True,
3126 'VertexAttribI4iv': {
3127 'type': 'PUT',
3128 'count': 4,
3129 'unsafe': True,
3131 'VertexAttribI4ui': {
3132 'unsafe': True,
3134 'VertexAttribI4uiv': {
3135 'type': 'PUT',
3136 'count': 4,
3137 'unsafe': True,
3139 'VertexAttribIPointer': {
3140 'type': 'Manual',
3141 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3142 'GLenumVertexAttribType type, GLsizei stride, '
3143 'GLuint offset',
3144 'client_test': False,
3145 'unsafe': True,
3147 'VertexAttribPointer': {
3148 'type': 'Manual',
3149 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3150 'GLenumVertexAttribType type, GLboolean normalized, '
3151 'GLsizei stride, GLuint offset',
3152 'client_test': False,
3154 'WaitSync': {
3155 'type': 'Custom',
3156 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3157 'GLuint timeout_0, GLuint timeout_1',
3158 'impl_func': False,
3159 'client_test': False,
3160 'unsafe': True,
3162 'Scissor': {
3163 'type': 'StateSet',
3164 'state': 'Scissor',
3166 'Viewport': {
3167 'decoder_func': 'DoViewport',
3169 'ResizeCHROMIUM': {
3170 'type': 'Custom',
3171 'impl_func': False,
3172 'unit_test': False,
3173 'extension': True,
3174 'chromium': True,
3176 'GetRequestableExtensionsCHROMIUM': {
3177 'type': 'Custom',
3178 'impl_func': False,
3179 'cmd_args': 'uint32_t bucket_id',
3180 'extension': True,
3181 'chromium': True,
3183 'RequestExtensionCHROMIUM': {
3184 'type': 'Custom',
3185 'impl_func': False,
3186 'client_test': False,
3187 'cmd_args': 'uint32_t bucket_id',
3188 'extension': True,
3189 'chromium': True,
3191 'RateLimitOffscreenContextCHROMIUM': {
3192 'gen_cmd': False,
3193 'extension': True,
3194 'chromium': True,
3195 'client_test': False,
3197 'CreateStreamTextureCHROMIUM': {
3198 'type': 'HandWritten',
3199 'impl_func': False,
3200 'gen_cmd': False,
3201 'extension': True,
3202 'chromium': True,
3204 'TexImageIOSurface2DCHROMIUM': {
3205 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3206 'unit_test': False,
3207 'extension': True,
3208 'chromium': True,
3210 'CopyTextureCHROMIUM': {
3211 'decoder_func': 'DoCopyTextureCHROMIUM',
3212 'unit_test': False,
3213 'extension': True,
3214 'chromium': True,
3216 'CopySubTextureCHROMIUM': {
3217 'decoder_func': 'DoCopySubTextureCHROMIUM',
3218 'unit_test': False,
3219 'extension': True,
3220 'chromium': True,
3222 'TexStorage2DEXT': {
3223 'unit_test': False,
3224 'extension': True,
3225 'decoder_func': 'DoTexStorage2DEXT',
3227 'DrawArraysInstancedANGLE': {
3228 'type': 'Manual',
3229 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3230 'GLsizei primcount',
3231 'extension': True,
3232 'unit_test': False,
3233 'pepper_interface': 'InstancedArrays',
3234 'defer_draws': True,
3236 'DrawBuffersEXT': {
3237 'type': 'PUTn',
3238 'decoder_func': 'DoDrawBuffersEXT',
3239 'count': 1,
3240 'client_test': False,
3241 'unit_test': False,
3242 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3243 # work without.
3244 'extension': True,
3245 'pepper_interface': 'DrawBuffers',
3247 'DrawElementsInstancedANGLE': {
3248 'type': 'Manual',
3249 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3250 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3251 'extension': True,
3252 'unit_test': False,
3253 'client_test': False,
3254 'pepper_interface': 'InstancedArrays',
3255 'defer_draws': True,
3257 'VertexAttribDivisorANGLE': {
3258 'type': 'Manual',
3259 'cmd_args': 'GLuint index, GLuint divisor',
3260 'extension': True,
3261 'unit_test': False,
3262 'pepper_interface': 'InstancedArrays',
3264 'GenQueriesEXT': {
3265 'type': 'GENn',
3266 'gl_test_func': 'glGenQueriesARB',
3267 'resource_type': 'Query',
3268 'resource_types': 'Queries',
3269 'unit_test': False,
3270 'pepper_interface': 'Query',
3271 'not_shared': 'True',
3272 'extension': "occlusion_query_EXT",
3274 'DeleteQueriesEXT': {
3275 'type': 'DELn',
3276 'gl_test_func': 'glDeleteQueriesARB',
3277 'resource_type': 'Query',
3278 'resource_types': 'Queries',
3279 'unit_test': False,
3280 'pepper_interface': 'Query',
3281 'extension': "occlusion_query_EXT",
3283 'IsQueryEXT': {
3284 'gen_cmd': False,
3285 'client_test': False,
3286 'pepper_interface': 'Query',
3287 'extension': "occlusion_query_EXT",
3289 'BeginQueryEXT': {
3290 'type': 'Manual',
3291 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3292 'data_transfer_methods': ['shm'],
3293 'gl_test_func': 'glBeginQuery',
3294 'pepper_interface': 'Query',
3295 'extension': "occlusion_query_EXT",
3297 'BeginTransformFeedback': {
3298 'unsafe': True,
3300 'EndQueryEXT': {
3301 'type': 'Manual',
3302 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3303 'gl_test_func': 'glEndnQuery',
3304 'client_test': False,
3305 'pepper_interface': 'Query',
3306 'extension': "occlusion_query_EXT",
3308 'EndTransformFeedback': {
3309 'unsafe': True,
3311 'GetQueryivEXT': {
3312 'gen_cmd': False,
3313 'client_test': False,
3314 'gl_test_func': 'glGetQueryiv',
3315 'pepper_interface': 'Query',
3316 'extension': "occlusion_query_EXT",
3318 'GetQueryObjectuivEXT': {
3319 'gen_cmd': False,
3320 'client_test': False,
3321 'gl_test_func': 'glGetQueryObjectuiv',
3322 'pepper_interface': 'Query',
3323 'extension': "occlusion_query_EXT",
3325 'BindUniformLocationCHROMIUM': {
3326 'type': 'GLchar',
3327 'extension': True,
3328 'data_transfer_methods': ['bucket'],
3329 'needs_size': True,
3330 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3332 'InsertEventMarkerEXT': {
3333 'type': 'GLcharN',
3334 'decoder_func': 'DoInsertEventMarkerEXT',
3335 'expectation': False,
3336 'extension': True,
3338 'PushGroupMarkerEXT': {
3339 'type': 'GLcharN',
3340 'decoder_func': 'DoPushGroupMarkerEXT',
3341 'expectation': False,
3342 'extension': True,
3344 'PopGroupMarkerEXT': {
3345 'decoder_func': 'DoPopGroupMarkerEXT',
3346 'expectation': False,
3347 'extension': True,
3348 'impl_func': False,
3351 'GenVertexArraysOES': {
3352 'type': 'GENn',
3353 'extension': True,
3354 'gl_test_func': 'glGenVertexArraysOES',
3355 'resource_type': 'VertexArray',
3356 'resource_types': 'VertexArrays',
3357 'unit_test': False,
3358 'pepper_interface': 'VertexArrayObject',
3360 'BindVertexArrayOES': {
3361 'type': 'Bind',
3362 'extension': True,
3363 'gl_test_func': 'glBindVertexArrayOES',
3364 'decoder_func': 'DoBindVertexArrayOES',
3365 'gen_func': 'GenVertexArraysOES',
3366 'unit_test': False,
3367 'client_test': False,
3368 'pepper_interface': 'VertexArrayObject',
3370 'DeleteVertexArraysOES': {
3371 'type': 'DELn',
3372 'extension': True,
3373 'gl_test_func': 'glDeleteVertexArraysOES',
3374 'resource_type': 'VertexArray',
3375 'resource_types': 'VertexArrays',
3376 'unit_test': False,
3377 'pepper_interface': 'VertexArrayObject',
3379 'IsVertexArrayOES': {
3380 'type': 'Is',
3381 'extension': True,
3382 'gl_test_func': 'glIsVertexArrayOES',
3383 'decoder_func': 'DoIsVertexArrayOES',
3384 'expectation': False,
3385 'unit_test': False,
3386 'pepper_interface': 'VertexArrayObject',
3388 'BindTexImage2DCHROMIUM': {
3389 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3390 'unit_test': False,
3391 'extension': True,
3392 'chromium': True,
3394 'ReleaseTexImage2DCHROMIUM': {
3395 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3396 'unit_test': False,
3397 'extension': True,
3398 'chromium': True,
3400 'ShallowFinishCHROMIUM': {
3401 'impl_func': False,
3402 'gen_cmd': False,
3403 'extension': True,
3404 'chromium': True,
3405 'client_test': False,
3407 'ShallowFlushCHROMIUM': {
3408 'impl_func': False,
3409 'gen_cmd': False,
3410 'extension': "CHROMIUM_miscellaneous",
3411 'chromium': True,
3412 'client_test': False,
3414 'OrderingBarrierCHROMIUM': {
3415 'impl_func': False,
3416 'gen_cmd': False,
3417 'extension': True,
3418 'chromium': True,
3419 'client_test': False,
3421 'TraceBeginCHROMIUM': {
3422 'type': 'Custom',
3423 'impl_func': False,
3424 'client_test': False,
3425 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3426 'extension': True,
3427 'chromium': True,
3429 'TraceEndCHROMIUM': {
3430 'impl_func': False,
3431 'client_test': False,
3432 'decoder_func': 'DoTraceEndCHROMIUM',
3433 'unit_test': False,
3434 'extension': True,
3435 'chromium': True,
3437 'AsyncTexImage2DCHROMIUM': {
3438 'type': 'Manual',
3439 'data_transfer_methods': ['shm'],
3440 'client_test': False,
3441 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3442 'GLintTextureInternalFormat internalformat, '
3443 'GLsizei width, GLsizei height, '
3444 'GLintTextureBorder border, '
3445 'GLenumTextureFormat format, GLenumPixelType type, '
3446 'const void* pixels, '
3447 'uint32_t async_upload_token, '
3448 'void* sync_data',
3449 'extension': True,
3450 'chromium': True,
3452 'AsyncTexSubImage2DCHROMIUM': {
3453 'type': 'Manual',
3454 'data_transfer_methods': ['shm'],
3455 'client_test': False,
3456 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3457 'GLint xoffset, GLint yoffset, '
3458 'GLsizei width, GLsizei height, '
3459 'GLenumTextureFormat format, GLenumPixelType type, '
3460 'const void* data, '
3461 'uint32_t async_upload_token, '
3462 'void* sync_data',
3463 'extension': True,
3464 'chromium': True,
3466 'WaitAsyncTexImage2DCHROMIUM': {
3467 'type': 'Manual',
3468 'client_test': False,
3469 'extension': True,
3470 'chromium': True,
3472 'WaitAllAsyncTexImage2DCHROMIUM': {
3473 'type': 'Manual',
3474 'client_test': False,
3475 'extension': True,
3476 'chromium': True,
3478 'DiscardFramebufferEXT': {
3479 'type': 'PUTn',
3480 'count': 1,
3481 'decoder_func': 'DoDiscardFramebufferEXT',
3482 'unit_test': False,
3483 'client_test': False,
3484 'extension_flag': 'ext_discard_framebuffer',
3486 'LoseContextCHROMIUM': {
3487 'decoder_func': 'DoLoseContextCHROMIUM',
3488 'unit_test': False,
3489 'extension': True,
3490 'chromium': True,
3492 'InsertSyncPointCHROMIUM': {
3493 'type': 'HandWritten',
3494 'impl_func': False,
3495 'extension': "CHROMIUM_sync_point",
3496 'chromium': True,
3498 'WaitSyncPointCHROMIUM': {
3499 'type': 'Custom',
3500 'impl_func': True,
3501 'extension': "CHROMIUM_sync_point",
3502 'chromium': True,
3503 'trace_level': 1,
3505 'DiscardBackbufferCHROMIUM': {
3506 'type': 'Custom',
3507 'impl_func': True,
3508 'extension': True,
3509 'chromium': True,
3511 'ScheduleOverlayPlaneCHROMIUM': {
3512 'type': 'Custom',
3513 'impl_func': True,
3514 'unit_test': False,
3515 'client_test': False,
3516 'extension': True,
3517 'chromium': True,
3519 'MatrixLoadfCHROMIUM': {
3520 'type': 'PUT',
3521 'count': 16,
3522 'data_type': 'GLfloat',
3523 'decoder_func': 'DoMatrixLoadfCHROMIUM',
3524 'gl_test_func': 'glMatrixLoadfEXT',
3525 'chromium': True,
3526 'extension': True,
3527 'extension_flag': 'chromium_path_rendering',
3529 'MatrixLoadIdentityCHROMIUM': {
3530 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
3531 'gl_test_func': 'glMatrixLoadIdentityEXT',
3532 'chromium': True,
3533 'extension': True,
3534 'extension_flag': 'chromium_path_rendering',
3539 def Grouper(n, iterable, fillvalue=None):
3540 """Collect data into fixed-length chunks or blocks"""
3541 args = [iter(iterable)] * n
3542 return itertools.izip_longest(fillvalue=fillvalue, *args)
3545 def SplitWords(input_string):
3546 """Transforms a input_string into a list of lower-case components.
3548 Args:
3549 input_string: the input string.
3551 Returns:
3552 a list of lower-case words.
3554 if input_string.find('_') > -1:
3555 # 'some_TEXT_' -> 'some text'
3556 return input_string.replace('_', ' ').strip().lower().split()
3557 else:
3558 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
3559 # mixed case.
3560 # look for capitalization to cut input_strings
3561 # 'SomeText' -> 'Some Text'
3562 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
3563 # 'Vector3' -> 'Vector 3'
3564 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
3565 return input_string.lower().split()
3568 def Lower(words):
3569 """Makes a lower-case identifier from words.
3571 Args:
3572 words: a list of lower-case words.
3574 Returns:
3575 the lower-case identifier.
3577 return '_'.join(words)
3580 def ToUnderscore(input_string):
3581 """converts CamelCase to camel_case."""
3582 words = SplitWords(input_string)
3583 return Lower(words)
3585 def CachedStateName(item):
3586 if item.get('cached', False):
3587 return 'cached_' + item['name']
3588 return item['name']
3590 def ToGLExtensionString(extension_flag):
3591 """Returns GL-type extension string of a extension flag."""
3592 if extension_flag == "oes_compressed_etc1_rgb8_texture":
3593 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
3594 # unfortunate.
3595 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
3596 'egl', 'atc', 'etc1', 'angle']
3597 parts = extension_flag.split('_')
3598 return "_".join(
3599 [part.upper() if part in uppercase_words else part for part in parts])
3601 def ToCamelCase(input_string):
3602 """converts ABC_underscore_case to ABCUnderscoreCase."""
3603 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
3605 def GetGLGetTypeConversion(result_type, value_type, value):
3606 """Makes a gl compatible type conversion string for accessing state variables.
3608 Useful when accessing state variables through glGetXXX calls.
3609 glGet documetation (for example, the manual pages):
3610 [...] If glGetIntegerv is called, [...] most floating-point values are
3611 rounded to the nearest integer value. [...]
3613 Args:
3614 result_type: the gl type to be obtained
3615 value_type: the GL type of the state variable
3616 value: the name of the state variable
3618 Returns:
3619 String that converts the state variable to desired GL type according to GL
3620 rules.
3623 if result_type == 'GLint':
3624 if value_type == 'GLfloat':
3625 return 'static_cast<GLint>(round(%s))' % value
3626 return 'static_cast<%s>(%s)' % (result_type, value)
3628 class CWriter(object):
3629 """Writes to a file formatting it for Google's style guidelines."""
3631 def __init__(self, filename):
3632 self.filename = filename
3633 self.content = []
3635 def Write(self, string):
3636 """Writes a string to a file spliting if it's > 80 characters."""
3637 lines = string.splitlines()
3638 num_lines = len(lines)
3639 for ii in range(0, num_lines):
3640 self.content.append(lines[ii])
3641 if ii < (num_lines - 1) or string[-1] == '\n':
3642 self.content.append('\n')
3644 def Close(self):
3645 """Close the file."""
3646 content = "".join(self.content)
3647 write_file = True
3648 if os.path.exists(self.filename):
3649 old_file = open(self.filename, "rb");
3650 old_content = old_file.read()
3651 old_file.close();
3652 if content == old_content:
3653 write_file = False
3654 if write_file:
3655 file = open(self.filename, "wb")
3656 file.write(content)
3657 file.close()
3660 class CHeaderWriter(CWriter):
3661 """Writes a C Header file."""
3663 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
3665 def __init__(self, filename, file_comment = None):
3666 CWriter.__init__(self, filename)
3668 base = os.path.abspath(filename)
3669 while os.path.basename(base) != 'src':
3670 new_base = os.path.dirname(base)
3671 assert new_base != base # Prevent infinite loop.
3672 base = new_base
3674 hpath = os.path.relpath(filename, base)
3675 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
3677 self.Write(_LICENSE)
3678 self.Write(_DO_NOT_EDIT_WARNING)
3679 if not file_comment == None:
3680 self.Write(file_comment)
3681 self.Write("#ifndef %s\n" % self.guard)
3682 self.Write("#define %s\n\n" % self.guard)
3684 def Close(self):
3685 self.Write("#endif // %s\n\n" % self.guard)
3686 CWriter.Close(self)
3688 class TypeHandler(object):
3689 """This class emits code for a particular type of function."""
3691 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
3693 def __init__(self):
3694 pass
3696 def InitFunction(self, func):
3697 """Add or adjust anything type specific for this function."""
3698 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
3699 func.AddCmdArg(DataSizeArgument('data_size'))
3701 def NeedsDataTransferFunction(self, func):
3702 """Overriden from TypeHandler."""
3703 return func.num_pointer_args >= 1
3705 def WriteStruct(self, func, file):
3706 """Writes a structure that matches the arguments to a function."""
3707 comment = func.GetInfo('cmd_comment')
3708 if not comment == None:
3709 file.Write(comment)
3710 file.Write("struct %s {\n" % func.name)
3711 file.Write(" typedef %s ValueType;\n" % func.name)
3712 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
3713 func.WriteCmdArgFlag(file)
3714 func.WriteCmdFlag(file)
3715 file.Write("\n")
3716 result = func.GetInfo('result')
3717 if not result == None:
3718 if len(result) == 1:
3719 file.Write(" typedef %s Result;\n\n" % result[0])
3720 else:
3721 file.Write(" struct Result {\n")
3722 for line in result:
3723 file.Write(" %s;\n" % line)
3724 file.Write(" };\n\n")
3726 func.WriteCmdComputeSize(file)
3727 func.WriteCmdSetHeader(file)
3728 func.WriteCmdInit(file)
3729 func.WriteCmdSet(file)
3731 file.Write(" gpu::CommandHeader header;\n")
3732 args = func.GetCmdArgs()
3733 for arg in args:
3734 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
3736 consts = func.GetCmdConstants()
3737 for const in consts:
3738 file.Write(" static const %s %s = %s;\n" %
3739 (const.cmd_type, const.name, const.GetConstantValue()))
3741 file.Write("};\n")
3742 file.Write("\n")
3744 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
3745 file.Write("static_assert(sizeof(%s) == %d,\n" % (func.name, size))
3746 file.Write(" \"size of %s should be %d\");\n" %
3747 (func.name, size))
3748 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func.name)
3749 file.Write(" \"offset of %s header should be 0\");\n" %
3750 func.name)
3751 offset = _SIZE_OF_COMMAND_HEADER
3752 for arg in args:
3753 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
3754 (func.name, arg.name, offset))
3755 file.Write(" \"offset of %s %s should be %d\");\n" %
3756 (func.name, arg.name, offset))
3757 offset += _SIZE_OF_UINT32
3758 if not result == None and len(result) > 1:
3759 offset = 0;
3760 for line in result:
3761 parts = line.split()
3762 name = parts[-1]
3763 check = """
3764 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
3765 "offset of %(cmd_name)s Result %(field_name)s should be "
3766 "%(offset)d");
3768 file.Write((check.strip() + "\n") % {
3769 'cmd_name': func.name,
3770 'field_name': name,
3771 'offset': offset,
3773 offset += _SIZE_OF_UINT32
3774 file.Write("\n")
3776 def WriteHandlerImplementation(self, func, file):
3777 """Writes the handler implementation for this command."""
3778 if func.IsUnsafe() and func.GetInfo('id_mapping'):
3779 code_no_gen = """ if (!group_->Get%(type)sServiceId(
3780 %(var)s, &%(service_var)s)) {
3781 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3782 return error::kNoError;
3785 code_gen = """ if (!group_->Get%(type)sServiceId(
3786 %(var)s, &%(service_var)s)) {
3787 if (!group_->bind_generates_resource()) {
3788 LOCAL_SET_GL_ERROR(
3789 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3790 return error::kNoError;
3792 GLuint client_id = %(var)s;
3793 gl%(gen_func)s(1, &%(service_var)s);
3794 Create%(type)s(client_id, %(service_var)s);
3797 gen_func = func.GetInfo('gen_func')
3798 for id_type in func.GetInfo('id_mapping'):
3799 service_var = id_type.lower()
3800 if id_type == 'Sync':
3801 service_var = "service_%s" % service_var
3802 file.Write(" GLsync %s = 0;\n" % service_var)
3803 if gen_func and id_type in gen_func:
3804 file.Write(code_gen % { 'type': id_type,
3805 'var': id_type.lower(),
3806 'service_var': service_var,
3807 'func': func.GetGLFunctionName(),
3808 'gen_func': gen_func })
3809 else:
3810 file.Write(code_no_gen % { 'type': id_type,
3811 'var': id_type.lower(),
3812 'service_var': service_var,
3813 'func': func.GetGLFunctionName() })
3814 args = []
3815 for arg in func.GetOriginalArgs():
3816 if arg.type == "GLsync":
3817 args.append("service_%s" % arg.name)
3818 elif arg.name.endswith("size") and arg.type == "GLsizei":
3819 args.append("num_%s" % func.GetLastOriginalArg().name)
3820 elif arg.name == "length":
3821 args.append("nullptr")
3822 else:
3823 args.append(arg.name)
3824 file.Write(" %s(%s);\n" %
3825 (func.GetGLFunctionName(), ", ".join(args)))
3827 def WriteCmdSizeTest(self, func, file):
3828 """Writes the size test for a command."""
3829 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3831 def WriteFormatTest(self, func, file):
3832 """Writes a format test for a command."""
3833 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
3834 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
3835 (func.name, func.name))
3836 file.Write(" void* next_cmd = cmd.Set(\n")
3837 file.Write(" &cmd")
3838 args = func.GetCmdArgs()
3839 for value, arg in enumerate(args):
3840 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
3841 file.Write(");\n")
3842 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
3843 func.name)
3844 file.Write(" cmd.header.command);\n")
3845 func.type_handler.WriteCmdSizeTest(func, file)
3846 for value, arg in enumerate(args):
3847 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
3848 (arg.type, value + 11, arg.name))
3849 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
3850 file.Write(" next_cmd, sizeof(cmd));\n")
3851 file.Write("}\n")
3852 file.Write("\n")
3854 def WriteImmediateFormatTest(self, func, file):
3855 """Writes a format test for an immediate version of a command."""
3856 pass
3858 def WriteBucketFormatTest(self, func, file):
3859 """Writes a format test for a bucket version of a command."""
3860 pass
3862 def WriteGetDataSizeCode(self, func, file):
3863 """Writes the code to set data_size used in validation"""
3864 pass
3866 def WriteImmediateCmdSizeTest(self, func, file):
3867 """Writes a size test for an immediate version of a command."""
3868 file.Write(" // TODO(gman): Compute correct size.\n")
3869 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3871 def __WriteIdMapping(self, func, file):
3872 """Writes client side / service side ID mapping."""
3873 if not func.IsUnsafe() or not func.GetInfo('id_mapping'):
3874 return
3875 for id_type in func.GetInfo('id_mapping'):
3876 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
3877 (id_type, id_type.lower(), id_type.lower()))
3879 def WriteImmediateHandlerImplementation (self, func, file):
3880 """Writes the handler impl for the immediate version of a command."""
3881 self.__WriteIdMapping(func, file)
3882 file.Write(" %s(%s);\n" %
3883 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3885 def WriteBucketHandlerImplementation (self, func, file):
3886 """Writes the handler impl for the bucket version of a command."""
3887 self.__WriteIdMapping(func, file)
3888 file.Write(" %s(%s);\n" %
3889 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3891 def WriteServiceHandlerFunctionHeader(self, func, file):
3892 """Writes function header for service implementation handlers."""
3893 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
3894 uint32_t immediate_data_size, const void* cmd_data) {
3895 """ % {'name': func.name})
3896 if func.IsUnsafe():
3897 file.Write("""if (!unsafe_es3_apis_enabled())
3898 return error::kUnknownCommand;
3899 """)
3900 file.Write("""const gles2::cmds::%(name)s& c =
3901 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
3902 (void)c;
3903 """ % {'name': func.name})
3905 def WriteServiceImplementation(self, func, file):
3906 """Writes the service implementation for a command."""
3907 self.WriteServiceHandlerFunctionHeader(func, file)
3908 self.WriteHandlerExtensionCheck(func, file)
3909 self.WriteHandlerDeferReadWrite(func, file);
3910 if len(func.GetOriginalArgs()) > 0:
3911 last_arg = func.GetLastOriginalArg()
3912 all_but_last_arg = func.GetOriginalArgs()[:-1]
3913 for arg in all_but_last_arg:
3914 arg.WriteGetCode(file)
3915 self.WriteGetDataSizeCode(func, file)
3916 last_arg.WriteGetCode(file)
3917 func.WriteHandlerValidation(file)
3918 func.WriteHandlerImplementation(file)
3919 file.Write(" return error::kNoError;\n")
3920 file.Write("}\n")
3921 file.Write("\n")
3923 def WriteImmediateServiceImplementation(self, func, file):
3924 """Writes the service implementation for an immediate version of command."""
3925 self.WriteServiceHandlerFunctionHeader(func, file)
3926 self.WriteHandlerExtensionCheck(func, file)
3927 self.WriteHandlerDeferReadWrite(func, file);
3928 for arg in func.GetOriginalArgs():
3929 if arg.IsPointer():
3930 self.WriteGetDataSizeCode(func, file)
3931 arg.WriteGetCode(file)
3932 func.WriteHandlerValidation(file)
3933 func.WriteHandlerImplementation(file)
3934 file.Write(" return error::kNoError;\n")
3935 file.Write("}\n")
3936 file.Write("\n")
3938 def WriteBucketServiceImplementation(self, func, file):
3939 """Writes the service implementation for a bucket version of command."""
3940 self.WriteServiceHandlerFunctionHeader(func, file)
3941 self.WriteHandlerExtensionCheck(func, file)
3942 self.WriteHandlerDeferReadWrite(func, file);
3943 for arg in func.GetCmdArgs():
3944 arg.WriteGetCode(file)
3945 func.WriteHandlerValidation(file)
3946 func.WriteHandlerImplementation(file)
3947 file.Write(" return error::kNoError;\n")
3948 file.Write("}\n")
3949 file.Write("\n")
3951 def WriteHandlerExtensionCheck(self, func, file):
3952 if func.GetInfo('extension_flag'):
3953 file.Write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
3954 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
3955 " \"function not available\");\n" % func.original_name)
3956 file.Write(" return error::kNoError;")
3957 file.Write(" }\n\n")
3959 def WriteHandlerDeferReadWrite(self, func, file):
3960 """Writes the code to handle deferring reads or writes."""
3961 defer_draws = func.GetInfo('defer_draws')
3962 defer_reads = func.GetInfo('defer_reads')
3963 if defer_draws or defer_reads:
3964 file.Write(" error::Error error;\n")
3965 if defer_draws:
3966 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
3967 file.Write(" if (error != error::kNoError)\n")
3968 file.Write(" return error;\n")
3969 if defer_reads:
3970 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
3971 file.Write(" if (error != error::kNoError)\n")
3972 file.Write(" return error;\n")
3974 def WriteValidUnitTest(self, func, file, test, *extras):
3975 """Writes a valid unit test for the service implementation."""
3976 if func.GetInfo('expectation') == False:
3977 test = self._remove_expected_call_re.sub('', test)
3978 name = func.name
3979 arg_strings = [
3980 arg.GetValidArg(func) \
3981 for arg in func.GetOriginalArgs() if not arg.IsConstant()
3983 gl_arg_strings = [
3984 arg.GetValidGLArg(func) \
3985 for arg in func.GetOriginalArgs()
3987 gl_func_name = func.GetGLTestFunctionName()
3988 vars = {
3989 'name':name,
3990 'gl_func_name': gl_func_name,
3991 'args': ", ".join(arg_strings),
3992 'gl_args': ", ".join(gl_arg_strings),
3994 for extra in extras:
3995 vars.update(extra)
3996 old_test = ""
3997 while (old_test != test):
3998 old_test = test
3999 test = test % vars
4000 file.Write(test % vars)
4002 def WriteInvalidUnitTest(self, func, file, test, *extras):
4003 """Writes an invalid unit test for the service implementation."""
4004 if func.IsUnsafe():
4005 return
4006 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
4007 # Service implementation does not test constants, as they are not part of
4008 # the call in the service side.
4009 if invalid_arg.IsConstant():
4010 continue
4012 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
4013 for value_index in range(0, num_invalid_values):
4014 arg_strings = []
4015 parse_result = "kNoError"
4016 gl_error = None
4017 for arg in func.GetOriginalArgs():
4018 if arg.IsConstant():
4019 continue
4020 if invalid_arg is arg:
4021 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
4022 value_index)
4023 else:
4024 arg_string = arg.GetValidArg(func)
4025 arg_strings.append(arg_string)
4026 gl_arg_strings = []
4027 for arg in func.GetOriginalArgs():
4028 gl_arg_strings.append("_")
4029 gl_func_name = func.GetGLTestFunctionName()
4030 gl_error_test = ''
4031 if not gl_error == None:
4032 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4034 vars = {
4035 'name': func.name,
4036 'arg_index': invalid_arg_index,
4037 'value_index': value_index,
4038 'gl_func_name': gl_func_name,
4039 'args': ", ".join(arg_strings),
4040 'all_but_last_args': ", ".join(arg_strings[:-1]),
4041 'gl_args': ", ".join(gl_arg_strings),
4042 'parse_result': parse_result,
4043 'gl_error_test': gl_error_test,
4045 for extra in extras:
4046 vars.update(extra)
4047 file.Write(test % vars)
4049 def WriteServiceUnitTest(self, func, file, *extras):
4050 """Writes the service unit test for a command."""
4052 if func.name == 'Enable':
4053 valid_test = """
4054 TEST_P(%(test_name)s, %(name)sValidArgs) {
4055 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4056 SpecializedSetup<cmds::%(name)s, 0>(true);
4057 cmds::%(name)s cmd;
4058 cmd.Init(%(args)s);"""
4059 elif func.name == 'Disable':
4060 valid_test = """
4061 TEST_P(%(test_name)s, %(name)sValidArgs) {
4062 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4063 SpecializedSetup<cmds::%(name)s, 0>(true);
4064 cmds::%(name)s cmd;
4065 cmd.Init(%(args)s);"""
4066 else:
4067 valid_test = """
4068 TEST_P(%(test_name)s, %(name)sValidArgs) {
4069 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4070 SpecializedSetup<cmds::%(name)s, 0>(true);
4071 cmds::%(name)s cmd;
4072 cmd.Init(%(args)s);"""
4073 if func.IsUnsafe():
4074 valid_test += """
4075 decoder_->set_unsafe_es3_apis_enabled(true);
4076 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4077 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4078 decoder_->set_unsafe_es3_apis_enabled(false);
4079 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4082 else:
4083 valid_test += """
4084 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4085 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4088 self.WriteValidUnitTest(func, file, valid_test, *extras)
4090 if not func.IsUnsafe():
4091 invalid_test = """
4092 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4093 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4094 SpecializedSetup<cmds::%(name)s, 0>(false);
4095 cmds::%(name)s cmd;
4096 cmd.Init(%(args)s);
4097 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4100 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
4102 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4103 """Writes the service unit test for an immediate command."""
4104 file.Write("// TODO(gman): %s\n" % func.name)
4106 def WriteImmediateValidationCode(self, func, file):
4107 """Writes the validation code for an immediate version of a command."""
4108 pass
4110 def WriteBucketServiceUnitTest(self, func, file, *extras):
4111 """Writes the service unit test for a bucket command."""
4112 file.Write("// TODO(gman): %s\n" % func.name)
4114 def WriteBucketValidationCode(self, func, file):
4115 """Writes the validation code for a bucket version of a command."""
4116 file.Write("// TODO(gman): %s\n" % func.name)
4118 def WriteGLES2ImplementationDeclaration(self, func, file):
4119 """Writes the GLES2 Implemention declaration."""
4120 impl_decl = func.GetInfo('impl_decl')
4121 if impl_decl == None or impl_decl == True:
4122 file.Write("%s %s(%s) override;\n" %
4123 (func.return_type, func.original_name,
4124 func.MakeTypedOriginalArgString("")))
4125 file.Write("\n")
4127 def WriteGLES2CLibImplementation(self, func, file):
4128 file.Write("%s GLES2%s(%s) {\n" %
4129 (func.return_type, func.name,
4130 func.MakeTypedOriginalArgString("")))
4131 result_string = "return "
4132 if func.return_type == "void":
4133 result_string = ""
4134 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
4135 (result_string, func.original_name,
4136 func.MakeOriginalArgString("")))
4137 file.Write("}\n")
4139 def WriteGLES2Header(self, func, file):
4140 """Writes a re-write macro for GLES"""
4141 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
4143 def WriteClientGLCallLog(self, func, file):
4144 """Writes a logging macro for the client side code."""
4145 comma = ""
4146 if len(func.GetOriginalArgs()):
4147 comma = " << "
4148 file.Write(
4149 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4150 (func.original_name, comma, func.MakeLogArgString()))
4152 def WriteClientGLReturnLog(self, func, file):
4153 """Writes the return value logging code."""
4154 if func.return_type != "void":
4155 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
4157 def WriteGLES2ImplementationHeader(self, func, file):
4158 """Writes the GLES2 Implemention."""
4159 self.WriteGLES2ImplementationDeclaration(func, file)
4161 def WriteGLES2TraceImplementationHeader(self, func, file):
4162 """Writes the GLES2 Trace Implemention header."""
4163 file.Write("%s %s(%s) override;\n" %
4164 (func.return_type, func.original_name,
4165 func.MakeTypedOriginalArgString("")))
4167 def WriteGLES2TraceImplementation(self, func, file):
4168 """Writes the GLES2 Trace Implemention."""
4169 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
4170 (func.return_type, func.original_name,
4171 func.MakeTypedOriginalArgString("")))
4172 result_string = "return "
4173 if func.return_type == "void":
4174 result_string = ""
4175 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4176 func.name)
4177 file.Write(" %sgl_->%s(%s);\n" %
4178 (result_string, func.name, func.MakeOriginalArgString("")))
4179 file.Write("}\n")
4180 file.Write("\n")
4182 def WriteGLES2Implementation(self, func, file):
4183 """Writes the GLES2 Implemention."""
4184 impl_func = func.GetInfo('impl_func')
4185 impl_decl = func.GetInfo('impl_decl')
4186 gen_cmd = func.GetInfo('gen_cmd')
4187 if (func.can_auto_generate and
4188 (impl_func == None or impl_func == True) and
4189 (impl_decl == None or impl_decl == True) and
4190 (gen_cmd == None or gen_cmd == True)):
4191 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4192 (func.return_type, func.original_name,
4193 func.MakeTypedOriginalArgString("")))
4194 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4195 self.WriteClientGLCallLog(func, file)
4196 func.WriteDestinationInitalizationValidation(file)
4197 for arg in func.GetOriginalArgs():
4198 arg.WriteClientSideValidationCode(file, func)
4199 file.Write(" helper_->%s(%s);\n" %
4200 (func.name, func.MakeHelperArgString("")))
4201 file.Write(" CheckGLError();\n")
4202 self.WriteClientGLReturnLog(func, file)
4203 file.Write("}\n")
4204 file.Write("\n")
4206 def WriteGLES2InterfaceHeader(self, func, file):
4207 """Writes the GLES2 Interface."""
4208 file.Write("virtual %s %s(%s) = 0;\n" %
4209 (func.return_type, func.original_name,
4210 func.MakeTypedOriginalArgString("")))
4212 def WriteMojoGLES2ImplHeader(self, func, file):
4213 """Writes the Mojo GLES2 implementation header."""
4214 file.Write("%s %s(%s) override;\n" %
4215 (func.return_type, func.original_name,
4216 func.MakeTypedOriginalArgString("")))
4218 def WriteMojoGLES2Impl(self, func, file):
4219 """Writes the Mojo GLES2 implementation."""
4220 file.Write("%s MojoGLES2Impl::%s(%s) {\n" %
4221 (func.return_type, func.original_name,
4222 func.MakeTypedOriginalArgString("")))
4223 extensions = ["CHROMIUM_sync_point", "CHROMIUM_texture_mailbox",
4224 "CHROMIUM_sub_image", "CHROMIUM_miscellaneous",
4225 "occlusion_query_EXT"]
4226 if func.IsCoreGLFunction() or func.GetInfo("extension") in extensions:
4227 file.Write("MojoGLES2MakeCurrent(context_);");
4228 func_return = "gl" + func.original_name + "(" + \
4229 func.MakeOriginalArgString("") + ");"
4230 if func.return_type == "void":
4231 file.Write(func_return);
4232 else:
4233 file.Write("return " + func_return);
4234 else:
4235 file.Write("NOTREACHED() << \"Unimplemented %s.\";\n" %
4236 func.original_name);
4237 if func.return_type != "void":
4238 file.Write("return 0;")
4239 file.Write("}")
4241 def WriteGLES2InterfaceStub(self, func, file):
4242 """Writes the GLES2 Interface stub declaration."""
4243 file.Write("%s %s(%s) override;\n" %
4244 (func.return_type, func.original_name,
4245 func.MakeTypedOriginalArgString("")))
4247 def WriteGLES2InterfaceStubImpl(self, func, file):
4248 """Writes the GLES2 Interface stub declaration."""
4249 args = func.GetOriginalArgs()
4250 arg_string = ", ".join(
4251 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
4252 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
4253 (func.return_type, func.original_name, arg_string))
4254 if func.return_type != "void":
4255 file.Write(" return 0;\n")
4256 file.Write("}\n")
4258 def WriteGLES2ImplementationUnitTest(self, func, file):
4259 """Writes the GLES2 Implemention unit test."""
4260 client_test = func.GetInfo('client_test')
4261 if (func.can_auto_generate and
4262 (client_test == None or client_test == True)):
4263 code = """
4264 TEST_F(GLES2ImplementationTest, %(name)s) {
4265 struct Cmds {
4266 cmds::%(name)s cmd;
4268 Cmds expected;
4269 expected.cmd.Init(%(cmd_args)s);
4271 gl_->%(name)s(%(args)s);
4272 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4275 cmd_arg_strings = [
4276 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4279 gl_arg_strings = [
4280 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4283 file.Write(code % {
4284 'name': func.name,
4285 'args': ", ".join(gl_arg_strings),
4286 'cmd_args': ", ".join(cmd_arg_strings),
4289 # Test constants for invalid values, as they are not tested by the
4290 # service.
4291 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
4292 if constants:
4293 code = """
4294 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4295 gl_->%(name)s(%(args)s);
4296 EXPECT_TRUE(NoCommandsWritten());
4297 EXPECT_EQ(%(gl_error)s, CheckError());
4300 for invalid_arg in constants:
4301 gl_arg_strings = []
4302 invalid = invalid_arg.GetInvalidArg(func)
4303 for arg in func.GetOriginalArgs():
4304 if arg is invalid_arg:
4305 gl_arg_strings.append(invalid[0])
4306 else:
4307 gl_arg_strings.append(arg.GetValidClientSideArg(func))
4309 file.Write(code % {
4310 'name': func.name,
4311 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
4312 'args': ", ".join(gl_arg_strings),
4313 'gl_error': invalid[2],
4315 else:
4316 if client_test != False:
4317 file.Write("// TODO(zmo): Implement unit test for %s\n" % func.name)
4319 def WriteDestinationInitalizationValidation(self, func, file):
4320 """Writes the client side destintion initialization validation."""
4321 for arg in func.GetOriginalArgs():
4322 arg.WriteDestinationInitalizationValidation(file, func)
4324 def WriteTraceEvent(self, func, file):
4325 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4326 func.original_name)
4328 def WriteImmediateCmdComputeSize(self, func, file):
4329 """Writes the size computation code for the immediate version of a cmd."""
4330 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4331 file.Write(" return static_cast<uint32_t>(\n")
4332 file.Write(" sizeof(ValueType) + // NOLINT\n")
4333 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4334 file.Write(" }\n")
4335 file.Write("\n")
4337 def WriteImmediateCmdSetHeader(self, func, file):
4338 """Writes the SetHeader function for the immediate version of a cmd."""
4339 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
4340 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4341 file.Write(" }\n")
4342 file.Write("\n")
4344 def WriteImmediateCmdInit(self, func, file):
4345 """Writes the Init function for the immediate version of a command."""
4346 raise NotImplementedError(func.name)
4348 def WriteImmediateCmdSet(self, func, file):
4349 """Writes the Set function for the immediate version of a command."""
4350 raise NotImplementedError(func.name)
4352 def WriteCmdHelper(self, func, file):
4353 """Writes the cmd helper definition for a cmd."""
4354 code = """ void %(name)s(%(typed_args)s) {
4355 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4356 if (c) {
4357 c->Init(%(args)s);
4362 file.Write(code % {
4363 "name": func.name,
4364 "typed_args": func.MakeTypedCmdArgString(""),
4365 "args": func.MakeCmdArgString(""),
4368 def WriteImmediateCmdHelper(self, func, file):
4369 """Writes the cmd helper definition for the immediate version of a cmd."""
4370 code = """ void %(name)s(%(typed_args)s) {
4371 const uint32_t s = 0; // TODO(gman): compute correct size
4372 gles2::cmds::%(name)s* c =
4373 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4374 if (c) {
4375 c->Init(%(args)s);
4380 file.Write(code % {
4381 "name": func.name,
4382 "typed_args": func.MakeTypedCmdArgString(""),
4383 "args": func.MakeCmdArgString(""),
4387 class StateSetHandler(TypeHandler):
4388 """Handler for commands that simply set state."""
4390 def __init__(self):
4391 TypeHandler.__init__(self)
4393 def WriteHandlerImplementation(self, func, file):
4394 """Overrriden from TypeHandler."""
4395 state_name = func.GetInfo('state')
4396 state = _STATES[state_name]
4397 states = state['states']
4398 args = func.GetOriginalArgs()
4399 for ndx,item in enumerate(states):
4400 code = []
4401 if 'range_checks' in item:
4402 for range_check in item['range_checks']:
4403 code.append("%s %s" % (args[ndx].name, range_check['check']))
4404 if 'nan_check' in item:
4405 # Drivers might generate an INVALID_VALUE error when a value is set
4406 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
4407 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
4408 # Make this behavior consistent within Chromium, and avoid leaking GL
4409 # errors by generating the error in the command buffer instead of
4410 # letting the GL driver generate it.
4411 code.append("base::IsNaN(%s)" % args[ndx].name)
4412 if len(code):
4413 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4414 file.Write(
4415 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
4416 ' "%s", "%s out of range");\n' %
4417 (func.name, args[ndx].name))
4418 file.Write(" return error::kNoError;\n")
4419 file.Write(" }\n")
4420 code = []
4421 for ndx,item in enumerate(states):
4422 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
4423 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4424 for ndx,item in enumerate(states):
4425 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
4426 if 'state_flag' in state:
4427 file.Write(" %s = true;\n" % state['state_flag'])
4428 if not func.GetInfo("no_gl"):
4429 for ndx,item in enumerate(states):
4430 if item.get('cached', False):
4431 file.Write(" state_.%s = %s;\n" %
4432 (CachedStateName(item), args[ndx].name))
4433 file.Write(" %s(%s);\n" %
4434 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4435 file.Write(" }\n")
4437 def WriteServiceUnitTest(self, func, file, *extras):
4438 """Overrriden from TypeHandler."""
4439 TypeHandler.WriteServiceUnitTest(self, func, file, *extras)
4440 state_name = func.GetInfo('state')
4441 state = _STATES[state_name]
4442 states = state['states']
4443 for ndx,item in enumerate(states):
4444 if 'range_checks' in item:
4445 for check_ndx, range_check in enumerate(item['range_checks']):
4446 valid_test = """
4447 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
4448 SpecializedSetup<cmds::%(name)s, 0>(false);
4449 cmds::%(name)s cmd;
4450 cmd.Init(%(args)s);
4451 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4452 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4455 name = func.name
4456 arg_strings = [
4457 arg.GetValidArg(func) \
4458 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4461 arg_strings[ndx] = range_check['test_value']
4462 vars = {
4463 'name': name,
4464 'ndx': ndx,
4465 'check_ndx': check_ndx,
4466 'args': ", ".join(arg_strings),
4468 for extra in extras:
4469 vars.update(extra)
4470 file.Write(valid_test % vars)
4471 if 'nan_check' in item:
4472 valid_test = """
4473 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
4474 SpecializedSetup<cmds::%(name)s, 0>(false);
4475 cmds::%(name)s cmd;
4476 cmd.Init(%(args)s);
4477 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4478 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4481 name = func.name
4482 arg_strings = [
4483 arg.GetValidArg(func) \
4484 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4487 arg_strings[ndx] = 'nanf("")'
4488 vars = {
4489 'name': name,
4490 'ndx': ndx,
4491 'args': ", ".join(arg_strings),
4493 for extra in extras:
4494 vars.update(extra)
4495 file.Write(valid_test % vars)
4498 class StateSetRGBAlphaHandler(TypeHandler):
4499 """Handler for commands that simply set state that have rgb/alpha."""
4501 def __init__(self):
4502 TypeHandler.__init__(self)
4504 def WriteHandlerImplementation(self, func, file):
4505 """Overrriden from TypeHandler."""
4506 state_name = func.GetInfo('state')
4507 state = _STATES[state_name]
4508 states = state['states']
4509 args = func.GetOriginalArgs()
4510 num_args = len(args)
4511 code = []
4512 for ndx,item in enumerate(states):
4513 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
4514 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4515 for ndx, item in enumerate(states):
4516 file.Write(" state_.%s = %s;\n" %
4517 (item['name'], args[ndx % num_args].name))
4518 if 'state_flag' in state:
4519 file.Write(" %s = true;\n" % state['state_flag'])
4520 if not func.GetInfo("no_gl"):
4521 file.Write(" %s(%s);\n" %
4522 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4523 file.Write(" }\n")
4526 class StateSetFrontBackSeparateHandler(TypeHandler):
4527 """Handler for commands that simply set state that have front/back."""
4529 def __init__(self):
4530 TypeHandler.__init__(self)
4532 def WriteHandlerImplementation(self, func, file):
4533 """Overrriden from TypeHandler."""
4534 state_name = func.GetInfo('state')
4535 state = _STATES[state_name]
4536 states = state['states']
4537 args = func.GetOriginalArgs()
4538 face = args[0].name
4539 num_args = len(args)
4540 file.Write(" bool changed = false;\n")
4541 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4542 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4543 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4544 code = []
4545 for ndx, item in enumerate(group):
4546 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
4547 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
4548 file.Write(" }\n")
4549 file.Write(" if (changed) {\n")
4550 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4551 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4552 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4553 for ndx, item in enumerate(group):
4554 file.Write(" state_.%s = %s;\n" %
4555 (item['name'], args[ndx + 1].name))
4556 file.Write(" }\n")
4557 if 'state_flag' in state:
4558 file.Write(" %s = true;\n" % state['state_flag'])
4559 if not func.GetInfo("no_gl"):
4560 file.Write(" %s(%s);\n" %
4561 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4562 file.Write(" }\n")
4565 class StateSetFrontBackHandler(TypeHandler):
4566 """Handler for commands that simply set state that set both front/back."""
4568 def __init__(self):
4569 TypeHandler.__init__(self)
4571 def WriteHandlerImplementation(self, func, file):
4572 """Overrriden from TypeHandler."""
4573 state_name = func.GetInfo('state')
4574 state = _STATES[state_name]
4575 states = state['states']
4576 args = func.GetOriginalArgs()
4577 num_args = len(args)
4578 code = []
4579 for group_ndx, group in enumerate(Grouper(num_args, states)):
4580 for ndx, item in enumerate(group):
4581 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
4582 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4583 for group_ndx, group in enumerate(Grouper(num_args, states)):
4584 for ndx, item in enumerate(group):
4585 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
4586 if 'state_flag' in state:
4587 file.Write(" %s = true;\n" % state['state_flag'])
4588 if not func.GetInfo("no_gl"):
4589 file.Write(" %s(%s);\n" %
4590 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4591 file.Write(" }\n")
4594 class StateSetNamedParameter(TypeHandler):
4595 """Handler for commands that set a state chosen with an enum parameter."""
4597 def __init__(self):
4598 TypeHandler.__init__(self)
4600 def WriteHandlerImplementation(self, func, file):
4601 """Overridden from TypeHandler."""
4602 state_name = func.GetInfo('state')
4603 state = _STATES[state_name]
4604 states = state['states']
4605 args = func.GetOriginalArgs()
4606 num_args = len(args)
4607 assert num_args == 2
4608 file.Write(" switch (%s) {\n" % args[0].name)
4609 for state in states:
4610 file.Write(" case %s:\n" % state['enum'])
4611 file.Write(" if (state_.%s != %s) {\n" %
4612 (state['name'], args[1].name))
4613 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
4614 if not func.GetInfo("no_gl"):
4615 file.Write(" %s(%s);\n" %
4616 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4617 file.Write(" }\n")
4618 file.Write(" break;\n")
4619 file.Write(" default:\n")
4620 file.Write(" NOTREACHED();\n")
4621 file.Write(" }\n")
4624 class CustomHandler(TypeHandler):
4625 """Handler for commands that are auto-generated but require minor tweaks."""
4627 def __init__(self):
4628 TypeHandler.__init__(self)
4630 def WriteServiceImplementation(self, func, file):
4631 """Overrriden from TypeHandler."""
4632 pass
4634 def WriteImmediateServiceImplementation(self, func, file):
4635 """Overrriden from TypeHandler."""
4636 pass
4638 def WriteBucketServiceImplementation(self, func, file):
4639 """Overrriden from TypeHandler."""
4640 pass
4642 def WriteServiceUnitTest(self, func, file, *extras):
4643 """Overrriden from TypeHandler."""
4644 file.Write("// TODO(gman): %s\n\n" % func.name)
4646 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4647 """Overrriden from TypeHandler."""
4648 file.Write("// TODO(gman): %s\n\n" % func.name)
4650 def WriteImmediateCmdGetTotalSize(self, func, file):
4651 """Overrriden from TypeHandler."""
4652 file.Write(
4653 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
4655 def WriteImmediateCmdInit(self, func, file):
4656 """Overrriden from TypeHandler."""
4657 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
4658 self.WriteImmediateCmdGetTotalSize(func, file)
4659 file.Write(" SetHeader(total_size);\n")
4660 args = func.GetCmdArgs()
4661 for arg in args:
4662 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4663 file.Write(" }\n")
4664 file.Write("\n")
4666 def WriteImmediateCmdSet(self, func, file):
4667 """Overrriden from TypeHandler."""
4668 copy_args = func.MakeCmdArgString("_", False)
4669 file.Write(" void* Set(void* cmd%s) {\n" %
4670 func.MakeTypedCmdArgString("_", True))
4671 self.WriteImmediateCmdGetTotalSize(func, file)
4672 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
4673 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4674 "cmd, total_size);\n")
4675 file.Write(" }\n")
4676 file.Write("\n")
4679 class TodoHandler(CustomHandler):
4680 """Handle for commands that are not yet implemented."""
4682 def NeedsDataTransferFunction(self, func):
4683 """Overriden from TypeHandler."""
4684 return False
4686 def WriteImmediateFormatTest(self, func, file):
4687 """Overrriden from TypeHandler."""
4688 pass
4690 def WriteGLES2ImplementationUnitTest(self, func, file):
4691 """Overrriden from TypeHandler."""
4692 pass
4694 def WriteGLES2Implementation(self, func, file):
4695 """Overrriden from TypeHandler."""
4696 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4697 (func.return_type, func.original_name,
4698 func.MakeTypedOriginalArgString("")))
4699 file.Write(" // TODO: for now this is a no-op\n")
4700 file.Write(
4701 " SetGLError("
4702 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4703 func.name)
4704 if func.return_type != "void":
4705 file.Write(" return 0;\n")
4706 file.Write("}\n")
4707 file.Write("\n")
4709 def WriteServiceImplementation(self, func, file):
4710 """Overrriden from TypeHandler."""
4711 self.WriteServiceHandlerFunctionHeader(func, file)
4712 file.Write(" // TODO: for now this is a no-op\n")
4713 file.Write(
4714 " LOCAL_SET_GL_ERROR("
4715 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4716 func.name)
4717 file.Write(" return error::kNoError;\n")
4718 file.Write("}\n")
4719 file.Write("\n")
4722 class HandWrittenHandler(CustomHandler):
4723 """Handler for comands where everything must be written by hand."""
4725 def InitFunction(self, func):
4726 """Add or adjust anything type specific for this function."""
4727 CustomHandler.InitFunction(self, func)
4728 func.can_auto_generate = False
4730 def NeedsDataTransferFunction(self, func):
4731 """Overriden from TypeHandler."""
4732 # If specified explicitly, force the data transfer method.
4733 if func.GetInfo('data_transfer_methods'):
4734 return True
4735 return False
4737 def WriteStruct(self, func, file):
4738 """Overrriden from TypeHandler."""
4739 pass
4741 def WriteDocs(self, func, file):
4742 """Overrriden from TypeHandler."""
4743 pass
4745 def WriteServiceUnitTest(self, func, file, *extras):
4746 """Overrriden from TypeHandler."""
4747 file.Write("// TODO(gman): %s\n\n" % func.name)
4749 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4750 """Overrriden from TypeHandler."""
4751 file.Write("// TODO(gman): %s\n\n" % func.name)
4753 def WriteBucketServiceUnitTest(self, func, file, *extras):
4754 """Overrriden from TypeHandler."""
4755 file.Write("// TODO(gman): %s\n\n" % func.name)
4757 def WriteServiceImplementation(self, func, file):
4758 """Overrriden from TypeHandler."""
4759 pass
4761 def WriteImmediateServiceImplementation(self, func, file):
4762 """Overrriden from TypeHandler."""
4763 pass
4765 def WriteBucketServiceImplementation(self, func, file):
4766 """Overrriden from TypeHandler."""
4767 pass
4769 def WriteImmediateCmdHelper(self, func, file):
4770 """Overrriden from TypeHandler."""
4771 pass
4773 def WriteCmdHelper(self, func, file):
4774 """Overrriden from TypeHandler."""
4775 pass
4777 def WriteFormatTest(self, func, file):
4778 """Overrriden from TypeHandler."""
4779 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4781 def WriteImmediateFormatTest(self, func, file):
4782 """Overrriden from TypeHandler."""
4783 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4785 def WriteBucketFormatTest(self, func, file):
4786 """Overrriden from TypeHandler."""
4787 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4791 class ManualHandler(CustomHandler):
4792 """Handler for commands who's handlers must be written by hand."""
4794 def __init__(self):
4795 CustomHandler.__init__(self)
4797 def InitFunction(self, func):
4798 """Overrriden from TypeHandler."""
4799 if (func.name == 'CompressedTexImage2DBucket'):
4800 func.cmd_args = func.cmd_args[:-1]
4801 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
4802 else:
4803 CustomHandler.InitFunction(self, func)
4805 def WriteServiceImplementation(self, func, file):
4806 """Overrriden from TypeHandler."""
4807 pass
4809 def WriteBucketServiceImplementation(self, func, file):
4810 """Overrriden from TypeHandler."""
4811 pass
4813 def WriteServiceUnitTest(self, func, file, *extras):
4814 """Overrriden from TypeHandler."""
4815 file.Write("// TODO(gman): %s\n\n" % func.name)
4817 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4818 """Overrriden from TypeHandler."""
4819 file.Write("// TODO(gman): %s\n\n" % func.name)
4821 def WriteImmediateServiceImplementation(self, func, file):
4822 """Overrriden from TypeHandler."""
4823 pass
4825 def WriteImmediateFormatTest(self, func, file):
4826 """Overrriden from TypeHandler."""
4827 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
4829 def WriteGLES2Implementation(self, func, file):
4830 """Overrriden from TypeHandler."""
4831 if func.GetInfo('impl_func'):
4832 super(ManualHandler, self).WriteGLES2Implementation(func, file)
4834 def WriteGLES2ImplementationHeader(self, func, file):
4835 """Overrriden from TypeHandler."""
4836 file.Write("%s %s(%s) override;\n" %
4837 (func.return_type, func.original_name,
4838 func.MakeTypedOriginalArgString("")))
4839 file.Write("\n")
4841 def WriteImmediateCmdGetTotalSize(self, func, file):
4842 """Overrriden from TypeHandler."""
4843 # TODO(gman): Move this data to _FUNCTION_INFO?
4844 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
4847 class DataHandler(TypeHandler):
4848 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
4849 glCompressedTexImage2D, glCompressedTexImageSub2D."""
4850 def __init__(self):
4851 TypeHandler.__init__(self)
4853 def InitFunction(self, func):
4854 """Overrriden from TypeHandler."""
4855 if func.name == 'CompressedTexSubImage2DBucket':
4856 func.cmd_args = func.cmd_args[:-1]
4857 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
4859 def WriteGetDataSizeCode(self, func, file):
4860 """Overrriden from TypeHandler."""
4861 # TODO(gman): Move this data to _FUNCTION_INFO?
4862 name = func.name
4863 if name.endswith("Immediate"):
4864 name = name[0:-9]
4865 if name == 'BufferData' or name == 'BufferSubData':
4866 file.Write(" uint32_t data_size = size;\n")
4867 elif (name == 'CompressedTexImage2D' or
4868 name == 'CompressedTexSubImage2D'):
4869 file.Write(" uint32_t data_size = imageSize;\n")
4870 elif (name == 'CompressedTexSubImage2DBucket'):
4871 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
4872 file.Write(" uint32_t data_size = bucket->size();\n")
4873 file.Write(" GLsizei imageSize = data_size;\n")
4874 elif name == 'TexImage2D' or name == 'TexSubImage2D':
4875 code = """ uint32_t data_size;
4876 if (!GLES2Util::ComputeImageDataSize(
4877 width, height, format, type, unpack_alignment_, &data_size)) {
4878 return error::kOutOfBounds;
4881 file.Write(code)
4882 else:
4883 file.Write(
4884 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
4886 def WriteImmediateCmdGetTotalSize(self, func, file):
4887 """Overrriden from TypeHandler."""
4888 pass
4890 def WriteImmediateCmdSizeTest(self, func, file):
4891 """Overrriden from TypeHandler."""
4892 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
4894 def WriteImmediateCmdInit(self, func, file):
4895 """Overrriden from TypeHandler."""
4896 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
4897 self.WriteImmediateCmdGetTotalSize(func, file)
4898 file.Write(" SetHeader(total_size);\n")
4899 args = func.GetCmdArgs()
4900 for arg in args:
4901 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4902 file.Write(" }\n")
4903 file.Write("\n")
4905 def WriteImmediateCmdSet(self, func, file):
4906 """Overrriden from TypeHandler."""
4907 copy_args = func.MakeCmdArgString("_", False)
4908 file.Write(" void* Set(void* cmd%s) {\n" %
4909 func.MakeTypedCmdArgString("_", True))
4910 self.WriteImmediateCmdGetTotalSize(func, file)
4911 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
4912 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4913 "cmd, total_size);\n")
4914 file.Write(" }\n")
4915 file.Write("\n")
4917 def WriteImmediateFormatTest(self, func, file):
4918 """Overrriden from TypeHandler."""
4919 # TODO(gman): Remove this exception.
4920 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
4921 return
4923 def WriteServiceUnitTest(self, func, file, *extras):
4924 """Overrriden from TypeHandler."""
4925 file.Write("// TODO(gman): %s\n\n" % func.name)
4927 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4928 """Overrriden from TypeHandler."""
4929 file.Write("// TODO(gman): %s\n\n" % func.name)
4931 def WriteBucketServiceImplementation(self, func, file):
4932 """Overrriden from TypeHandler."""
4933 if not func.name == 'CompressedTexSubImage2DBucket':
4934 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
4937 class BindHandler(TypeHandler):
4938 """Handler for glBind___ type functions."""
4940 def __init__(self):
4941 TypeHandler.__init__(self)
4943 def WriteServiceUnitTest(self, func, file, *extras):
4944 """Overrriden from TypeHandler."""
4946 if len(func.GetOriginalArgs()) == 1:
4947 valid_test = """
4948 TEST_P(%(test_name)s, %(name)sValidArgs) {
4949 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4950 SpecializedSetup<cmds::%(name)s, 0>(true);
4951 cmds::%(name)s cmd;
4952 cmd.Init(%(args)s);"""
4953 if func.IsUnsafe():
4954 valid_test += """
4955 decoder_->set_unsafe_es3_apis_enabled(true);
4956 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4957 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4958 decoder_->set_unsafe_es3_apis_enabled(false);
4959 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4962 else:
4963 valid_test += """
4964 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4965 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4968 if func.GetInfo("gen_func"):
4969 valid_test += """
4970 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
4971 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
4972 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
4973 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4974 SpecializedSetup<cmds::%(name)s, 0>(true);
4975 cmds::%(name)s cmd;
4976 cmd.Init(kNewClientId);
4977 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4978 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4979 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4982 self.WriteValidUnitTest(func, file, valid_test, {
4983 'resource_type': func.GetOriginalArgs()[0].resource_type,
4984 'gl_gen_func_name': func.GetInfo("gen_func"),
4985 }, *extras)
4986 else:
4987 valid_test = """
4988 TEST_P(%(test_name)s, %(name)sValidArgs) {
4989 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4990 SpecializedSetup<cmds::%(name)s, 0>(true);
4991 cmds::%(name)s cmd;
4992 cmd.Init(%(args)s);"""
4993 if func.IsUnsafe():
4994 valid_test += """
4995 decoder_->set_unsafe_es3_apis_enabled(true);
4996 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4997 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4998 decoder_->set_unsafe_es3_apis_enabled(false);
4999 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5002 else:
5003 valid_test += """
5004 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5005 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5008 if func.GetInfo("gen_func"):
5009 valid_test += """
5010 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
5011 EXPECT_CALL(*gl_,
5012 %(gl_func_name)s(%(gl_args_with_new_id)s));
5013 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
5014 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5015 SpecializedSetup<cmds::%(name)s, 0>(true);
5016 cmds::%(name)s cmd;
5017 cmd.Init(%(args_with_new_id)s);"""
5018 if func.IsUnsafe():
5019 valid_test += """
5020 decoder_->set_unsafe_es3_apis_enabled(true);
5021 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5022 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5023 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5024 decoder_->set_unsafe_es3_apis_enabled(false);
5025 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5028 else:
5029 valid_test += """
5030 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5031 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5032 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
5036 gl_args_with_new_id = []
5037 args_with_new_id = []
5038 for arg in func.GetOriginalArgs():
5039 if hasattr(arg, 'resource_type'):
5040 gl_args_with_new_id.append('kNewServiceId')
5041 args_with_new_id.append('kNewClientId')
5042 else:
5043 gl_args_with_new_id.append(arg.GetValidGLArg(func))
5044 args_with_new_id.append(arg.GetValidArg(func))
5045 self.WriteValidUnitTest(func, file, valid_test, {
5046 'args_with_new_id': ", ".join(args_with_new_id),
5047 'gl_args_with_new_id': ", ".join(gl_args_with_new_id),
5048 'resource_type': func.GetResourceIdArg().resource_type,
5049 'gl_gen_func_name': func.GetInfo("gen_func"),
5050 }, *extras)
5052 invalid_test = """
5053 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5054 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5055 SpecializedSetup<cmds::%(name)s, 0>(false);
5056 cmds::%(name)s cmd;
5057 cmd.Init(%(args)s);
5058 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5061 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
5063 def WriteGLES2Implementation(self, func, file):
5064 """Writes the GLES2 Implemention."""
5066 impl_func = func.GetInfo('impl_func')
5067 impl_decl = func.GetInfo('impl_decl')
5069 if (func.can_auto_generate and
5070 (impl_func == None or impl_func == True) and
5071 (impl_decl == None or impl_decl == True)):
5073 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5074 (func.return_type, func.original_name,
5075 func.MakeTypedOriginalArgString("")))
5076 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5077 func.WriteDestinationInitalizationValidation(file)
5078 self.WriteClientGLCallLog(func, file)
5079 for arg in func.GetOriginalArgs():
5080 arg.WriteClientSideValidationCode(file, func)
5082 code = """ if (Is%(type)sReservedId(%(id)s)) {
5083 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5084 return;
5086 %(name)sHelper(%(arg_string)s);
5087 CheckGLError();
5091 name_arg = func.GetResourceIdArg()
5092 file.Write(code % {
5093 'name': func.name,
5094 'arg_string': func.MakeOriginalArgString(""),
5095 'id': name_arg.name,
5096 'type': name_arg.resource_type,
5097 'lc_type': name_arg.resource_type.lower(),
5100 def WriteGLES2ImplementationUnitTest(self, func, file):
5101 """Overrriden from TypeHandler."""
5102 client_test = func.GetInfo('client_test')
5103 if client_test == False:
5104 return
5105 code = """
5106 TEST_F(GLES2ImplementationTest, %(name)s) {
5107 struct Cmds {
5108 cmds::%(name)s cmd;
5110 Cmds expected;
5111 expected.cmd.Init(%(cmd_args)s);
5113 gl_->%(name)s(%(args)s);
5114 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5115 if not func.IsUnsafe():
5116 code += """
5117 ClearCommands();
5118 gl_->%(name)s(%(args)s);
5119 EXPECT_TRUE(NoCommandsWritten());"""
5120 code += """
5123 cmd_arg_strings = [
5124 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
5126 gl_arg_strings = [
5127 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
5130 file.Write(code % {
5131 'name': func.name,
5132 'args': ", ".join(gl_arg_strings),
5133 'cmd_args': ", ".join(cmd_arg_strings),
5137 class GENnHandler(TypeHandler):
5138 """Handler for glGen___ type functions."""
5140 def __init__(self):
5141 TypeHandler.__init__(self)
5143 def InitFunction(self, func):
5144 """Overrriden from TypeHandler."""
5145 pass
5147 def WriteGetDataSizeCode(self, func, file):
5148 """Overrriden from TypeHandler."""
5149 code = """ uint32_t data_size;
5150 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5151 return error::kOutOfBounds;
5154 file.Write(code)
5156 def WriteHandlerImplementation (self, func, file):
5157 """Overrriden from TypeHandler."""
5158 file.Write(" if (!%sHelper(n, %s)) {\n"
5159 " return error::kInvalidArguments;\n"
5160 " }\n" %
5161 (func.name, func.GetLastOriginalArg().name))
5163 def WriteImmediateHandlerImplementation(self, func, file):
5164 """Overrriden from TypeHandler."""
5165 if func.IsUnsafe():
5166 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5167 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5168 return error::kInvalidArguments;
5171 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5172 gl%(func_name)s(n, service_ids.get());
5173 for (GLsizei ii = 0; ii < n; ++ii) {
5174 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5176 """ % { 'func_name': func.original_name,
5177 'last_arg_name': func.GetLastOriginalArg().name,
5178 'resource_name': func.GetInfo('resource_type') })
5179 else:
5180 file.Write(" if (!%sHelper(n, %s)) {\n"
5181 " return error::kInvalidArguments;\n"
5182 " }\n" %
5183 (func.original_name, func.GetLastOriginalArg().name))
5185 def WriteGLES2Implementation(self, func, file):
5186 """Overrriden from TypeHandler."""
5187 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
5188 for (GLsizei i = 0; i < n; ++i) {
5189 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5191 });""" % func.GetOriginalArgs()[1].name)
5192 args = {
5193 'log_code': log_code,
5194 'return_type': func.return_type,
5195 'name': func.original_name,
5196 'typed_args': func.MakeTypedOriginalArgString(""),
5197 'args': func.MakeOriginalArgString(""),
5198 'resource_types': func.GetInfo('resource_types'),
5199 'count_name': func.GetOriginalArgs()[0].name,
5201 file.Write(
5202 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5203 args)
5204 func.WriteDestinationInitalizationValidation(file)
5205 self.WriteClientGLCallLog(func, file)
5206 for arg in func.GetOriginalArgs():
5207 arg.WriteClientSideValidationCode(file, func)
5208 not_shared = func.GetInfo('not_shared')
5209 if not_shared:
5210 alloc_code = (
5212 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5213 for (GLsizei ii = 0; ii < n; ++ii)
5214 %s[ii] = id_allocator->AllocateID();""" %
5215 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
5216 else:
5217 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5218 MakeIds(this, 0, %(args)s);""" % args)
5219 args['alloc_code'] = alloc_code
5221 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5222 %(alloc_code)s
5223 %(name)sHelper(%(args)s);
5224 helper_->%(name)sImmediate(%(args)s);
5225 if (share_group_->bind_generates_resource())
5226 helper_->CommandBufferHelper::Flush();
5227 %(log_code)s
5228 CheckGLError();
5232 file.Write(code % args)
5234 def WriteGLES2ImplementationUnitTest(self, func, file):
5235 """Overrriden from TypeHandler."""
5236 code = """
5237 TEST_F(GLES2ImplementationTest, %(name)s) {
5238 GLuint ids[2] = { 0, };
5239 struct Cmds {
5240 cmds::%(name)sImmediate gen;
5241 GLuint data[2];
5243 Cmds expected;
5244 expected.gen.Init(arraysize(ids), &ids[0]);
5245 expected.data[0] = k%(types)sStartId;
5246 expected.data[1] = k%(types)sStartId + 1;
5247 gl_->%(name)s(arraysize(ids), &ids[0]);
5248 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5249 EXPECT_EQ(k%(types)sStartId, ids[0]);
5250 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5253 file.Write(code % {
5254 'name': func.name,
5255 'types': func.GetInfo('resource_types'),
5258 def WriteServiceUnitTest(self, func, file, *extras):
5259 """Overrriden from TypeHandler."""
5260 valid_test = """
5261 TEST_P(%(test_name)s, %(name)sValidArgs) {
5262 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5263 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5264 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5265 SpecializedSetup<cmds::%(name)s, 0>(true);
5266 cmds::%(name)s cmd;
5267 cmd.Init(%(args)s);
5268 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5269 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5270 if func.IsUnsafe():
5271 valid_test += """
5272 GLuint service_id;
5273 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5274 EXPECT_EQ(kNewServiceId, service_id)
5277 else:
5278 valid_test += """
5279 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5282 self.WriteValidUnitTest(func, file, valid_test, {
5283 'resource_name': func.GetInfo('resource_type'),
5284 }, *extras)
5285 invalid_test = """
5286 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5287 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5288 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5289 SpecializedSetup<cmds::%(name)s, 0>(false);
5290 cmds::%(name)s cmd;
5291 cmd.Init(%(args)s);
5292 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5295 self.WriteValidUnitTest(func, file, invalid_test, {
5296 'resource_name': func.GetInfo('resource_type').lower(),
5297 }, *extras)
5299 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5300 """Overrriden from TypeHandler."""
5301 valid_test = """
5302 TEST_P(%(test_name)s, %(name)sValidArgs) {
5303 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5304 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5305 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5306 GLuint temp = kNewClientId;
5307 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5308 if func.IsUnsafe():
5309 valid_test += """
5310 decoder_->set_unsafe_es3_apis_enabled(true);"""
5311 valid_test += """
5312 cmd->Init(1, &temp);
5313 EXPECT_EQ(error::kNoError,
5314 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5315 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5316 if func.IsUnsafe():
5317 valid_test += """
5318 GLuint service_id;
5319 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5320 EXPECT_EQ(kNewServiceId, service_id);
5321 decoder_->set_unsafe_es3_apis_enabled(false);
5322 EXPECT_EQ(error::kUnknownCommand,
5323 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5326 else:
5327 valid_test += """
5328 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5331 self.WriteValidUnitTest(func, file, valid_test, {
5332 'resource_name': func.GetInfo('resource_type'),
5333 }, *extras)
5334 invalid_test = """
5335 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5336 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5337 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5338 SpecializedSetup<cmds::%(name)s, 0>(false);
5339 cmd->Init(1, &client_%(resource_name)s_id_);"""
5340 if func.IsUnsafe():
5341 invalid_test += """
5342 decoder_->set_unsafe_es3_apis_enabled(true);
5343 EXPECT_EQ(error::kInvalidArguments,
5344 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5345 decoder_->set_unsafe_es3_apis_enabled(false);
5348 else:
5349 invalid_test += """
5350 EXPECT_EQ(error::kInvalidArguments,
5351 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5354 self.WriteValidUnitTest(func, file, invalid_test, {
5355 'resource_name': func.GetInfo('resource_type').lower(),
5356 }, *extras)
5358 def WriteImmediateCmdComputeSize(self, func, file):
5359 """Overrriden from TypeHandler."""
5360 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5361 file.Write(
5362 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5363 file.Write(" }\n")
5364 file.Write("\n")
5365 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5366 file.Write(" return static_cast<uint32_t>(\n")
5367 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5368 file.Write(" }\n")
5369 file.Write("\n")
5371 def WriteImmediateCmdSetHeader(self, func, file):
5372 """Overrriden from TypeHandler."""
5373 file.Write(" void SetHeader(GLsizei n) {\n")
5374 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5375 file.Write(" }\n")
5376 file.Write("\n")
5378 def WriteImmediateCmdInit(self, func, file):
5379 """Overrriden from TypeHandler."""
5380 last_arg = func.GetLastOriginalArg()
5381 file.Write(" void Init(%s, %s _%s) {\n" %
5382 (func.MakeTypedCmdArgString("_"),
5383 last_arg.type, last_arg.name))
5384 file.Write(" SetHeader(_n);\n")
5385 args = func.GetCmdArgs()
5386 for arg in args:
5387 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5388 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5389 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5390 file.Write(" }\n")
5391 file.Write("\n")
5393 def WriteImmediateCmdSet(self, func, file):
5394 """Overrriden from TypeHandler."""
5395 last_arg = func.GetLastOriginalArg()
5396 copy_args = func.MakeCmdArgString("_", False)
5397 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5398 (func.MakeTypedCmdArgString("_", True),
5399 last_arg.type, last_arg.name))
5400 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5401 (copy_args, last_arg.name))
5402 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5403 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5404 "cmd, size);\n")
5405 file.Write(" }\n")
5406 file.Write("\n")
5408 def WriteImmediateCmdHelper(self, func, file):
5409 """Overrriden from TypeHandler."""
5410 code = """ void %(name)s(%(typed_args)s) {
5411 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5412 gles2::cmds::%(name)s* c =
5413 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5414 if (c) {
5415 c->Init(%(args)s);
5420 file.Write(code % {
5421 "name": func.name,
5422 "typed_args": func.MakeTypedOriginalArgString(""),
5423 "args": func.MakeOriginalArgString(""),
5426 def WriteImmediateFormatTest(self, func, file):
5427 """Overrriden from TypeHandler."""
5428 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5429 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5430 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5431 (func.name, func.name))
5432 file.Write(" void* next_cmd = cmd.Set(\n")
5433 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5434 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5435 func.name)
5436 file.Write(" cmd.header.command);\n")
5437 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5438 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5439 file.Write(" cmd.header.size * 4u);\n")
5440 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5441 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5442 file.Write(" next_cmd, sizeof(cmd) +\n")
5443 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5444 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5445 file.Write("}\n")
5446 file.Write("\n")
5449 class CreateHandler(TypeHandler):
5450 """Handler for glCreate___ type functions."""
5452 def __init__(self):
5453 TypeHandler.__init__(self)
5455 def InitFunction(self, func):
5456 """Overrriden from TypeHandler."""
5457 func.AddCmdArg(Argument("client_id", 'uint32_t'))
5459 def __GetResourceType(self, func):
5460 if func.return_type == "GLsync":
5461 return "Sync"
5462 else:
5463 return func.name[6:] # Create*
5465 def WriteServiceUnitTest(self, func, file, *extras):
5466 """Overrriden from TypeHandler."""
5467 valid_test = """
5468 TEST_P(%(test_name)s, %(name)sValidArgs) {
5469 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5470 .WillOnce(Return(%(const_service_id)s));
5471 SpecializedSetup<cmds::%(name)s, 0>(true);
5472 cmds::%(name)s cmd;
5473 cmd.Init(%(args)s%(comma)skNewClientId);"""
5474 if func.IsUnsafe():
5475 valid_test += """
5476 decoder_->set_unsafe_es3_apis_enabled(true);"""
5477 valid_test += """
5478 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5479 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5480 if func.IsUnsafe():
5481 valid_test += """
5482 %(return_type)s service_id = 0;
5483 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
5484 EXPECT_EQ(%(const_service_id)s, service_id);
5485 decoder_->set_unsafe_es3_apis_enabled(false);
5486 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5489 else:
5490 valid_test += """
5491 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
5494 comma = ""
5495 cmd_arg_count = 0
5496 for arg in func.GetOriginalArgs():
5497 if not arg.IsConstant():
5498 cmd_arg_count += 1
5499 if cmd_arg_count:
5500 comma = ", "
5501 if func.return_type == 'GLsync':
5502 id_type_cast = ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
5503 "<GLsync>(kNewServiceId);\n ")
5504 const_service_id = "kNewServiceIdGLuint"
5505 else:
5506 id_type_cast = ""
5507 const_service_id = "kNewServiceId"
5508 self.WriteValidUnitTest(func, file, valid_test, {
5509 'comma': comma,
5510 'resource_type': self.__GetResourceType(func),
5511 'return_type': func.return_type,
5512 'id_type_cast': id_type_cast,
5513 'const_service_id': const_service_id,
5514 }, *extras)
5515 invalid_test = """
5516 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5517 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5518 SpecializedSetup<cmds::%(name)s, 0>(false);
5519 cmds::%(name)s cmd;
5520 cmd.Init(%(args)s%(comma)skNewClientId);
5521 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
5524 self.WriteInvalidUnitTest(func, file, invalid_test, {
5525 'comma': comma,
5526 }, *extras)
5528 def WriteHandlerImplementation (self, func, file):
5529 """Overrriden from TypeHandler."""
5530 if func.IsUnsafe():
5531 code = """ uint32_t client_id = c.client_id;
5532 %(return_type)s service_id = 0;
5533 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
5534 return error::kInvalidArguments;
5536 service_id = %(gl_func_name)s(%(gl_args)s);
5537 if (service_id) {
5538 group_->Add%(resource_name)sId(client_id, service_id);
5541 else:
5542 code = """ uint32_t client_id = c.client_id;
5543 if (Get%(resource_name)s(client_id)) {
5544 return error::kInvalidArguments;
5546 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
5547 if (service_id) {
5548 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
5551 file.Write(code % {
5552 'resource_name': self.__GetResourceType(func),
5553 'return_type': func.return_type,
5554 'gl_func_name': func.GetGLFunctionName(),
5555 'gl_args': func.MakeOriginalArgString(""),
5556 'gl_args_with_comma': func.MakeOriginalArgString("", True) })
5558 def WriteGLES2Implementation(self, func, file):
5559 """Overrriden from TypeHandler."""
5560 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5561 (func.return_type, func.original_name,
5562 func.MakeTypedOriginalArgString("")))
5563 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5564 func.WriteDestinationInitalizationValidation(file)
5565 self.WriteClientGLCallLog(func, file)
5566 for arg in func.GetOriginalArgs():
5567 arg.WriteClientSideValidationCode(file, func)
5568 file.Write(" GLuint client_id;\n")
5569 if func.return_type == "GLsync":
5570 file.Write(
5571 " GetIdHandler(id_namespaces::kSyncs)->\n")
5572 else:
5573 file.Write(
5574 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
5575 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
5576 file.Write(" helper_->%s(%s);\n" %
5577 (func.name, func.MakeCmdArgString("")))
5578 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
5579 file.Write(" CheckGLError();\n")
5580 if func.return_type == "GLsync":
5581 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
5582 else:
5583 file.Write(" return client_id;\n")
5584 file.Write("}\n")
5585 file.Write("\n")
5588 class DeleteHandler(TypeHandler):
5589 """Handler for glDelete___ single resource type functions."""
5591 def __init__(self):
5592 TypeHandler.__init__(self)
5594 def WriteServiceImplementation(self, func, file):
5595 """Overrriden from TypeHandler."""
5596 if func.IsUnsafe():
5597 TypeHandler.WriteServiceImplementation(self, func, file)
5598 # HandleDeleteShader and HandleDeleteProgram are manually written.
5599 pass
5601 def WriteGLES2Implementation(self, func, file):
5602 """Overrriden from TypeHandler."""
5603 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5604 (func.return_type, func.original_name,
5605 func.MakeTypedOriginalArgString("")))
5606 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5607 func.WriteDestinationInitalizationValidation(file)
5608 self.WriteClientGLCallLog(func, file)
5609 for arg in func.GetOriginalArgs():
5610 arg.WriteClientSideValidationCode(file, func)
5611 file.Write(
5612 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
5613 file.Write(" %sHelper(%s);\n" %
5614 (func.original_name, func.GetOriginalArgs()[-1].name))
5615 file.Write(" CheckGLError();\n")
5616 file.Write("}\n")
5617 file.Write("\n")
5619 def WriteHandlerImplementation (self, func, file):
5620 """Overrriden from TypeHandler."""
5621 assert len(func.GetOriginalArgs()) == 1
5622 arg = func.GetOriginalArgs()[0]
5623 if func.IsUnsafe():
5624 file.Write(""" %(arg_type)s service_id = 0;
5625 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
5626 glDelete%(resource_type)s(service_id);
5627 group_->Remove%(resource_type)sId(%(arg_name)s);
5628 } else {
5629 LOCAL_SET_GL_ERROR(
5630 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
5632 """ % { 'resource_type': func.GetInfo('resource_type'),
5633 'arg_name': arg.name,
5634 'arg_type': arg.type,
5635 'func_name': func.original_name })
5636 else:
5637 file.Write(" %sHelper(%s);\n" % (func.original_name, arg.name))
5639 class DELnHandler(TypeHandler):
5640 """Handler for glDelete___ type functions."""
5642 def __init__(self):
5643 TypeHandler.__init__(self)
5645 def WriteGetDataSizeCode(self, func, file):
5646 """Overrriden from TypeHandler."""
5647 code = """ uint32_t data_size;
5648 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5649 return error::kOutOfBounds;
5652 file.Write(code)
5654 def WriteGLES2ImplementationUnitTest(self, func, file):
5655 """Overrriden from TypeHandler."""
5656 code = """
5657 TEST_F(GLES2ImplementationTest, %(name)s) {
5658 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
5659 struct Cmds {
5660 cmds::%(name)sImmediate del;
5661 GLuint data[2];
5663 Cmds expected;
5664 expected.del.Init(arraysize(ids), &ids[0]);
5665 expected.data[0] = k%(types)sStartId;
5666 expected.data[1] = k%(types)sStartId + 1;
5667 gl_->%(name)s(arraysize(ids), &ids[0]);
5668 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5671 file.Write(code % {
5672 'name': func.name,
5673 'types': func.GetInfo('resource_types'),
5676 def WriteServiceUnitTest(self, func, file, *extras):
5677 """Overrriden from TypeHandler."""
5678 valid_test = """
5679 TEST_P(%(test_name)s, %(name)sValidArgs) {
5680 EXPECT_CALL(
5681 *gl_,
5682 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5683 .Times(1);
5684 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5685 SpecializedSetup<cmds::%(name)s, 0>(true);
5686 cmds::%(name)s cmd;
5687 cmd.Init(%(args)s);
5688 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5689 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5690 EXPECT_TRUE(
5691 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5694 self.WriteValidUnitTest(func, file, valid_test, {
5695 'resource_name': func.GetInfo('resource_type').lower(),
5696 'upper_resource_name': func.GetInfo('resource_type'),
5697 }, *extras)
5698 invalid_test = """
5699 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5700 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
5701 SpecializedSetup<cmds::%(name)s, 0>(false);
5702 cmds::%(name)s cmd;
5703 cmd.Init(%(args)s);
5704 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5707 self.WriteValidUnitTest(func, file, invalid_test, *extras)
5709 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5710 """Overrriden from TypeHandler."""
5711 valid_test = """
5712 TEST_P(%(test_name)s, %(name)sValidArgs) {
5713 EXPECT_CALL(
5714 *gl_,
5715 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5716 .Times(1);
5717 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5718 SpecializedSetup<cmds::%(name)s, 0>(true);
5719 cmd.Init(1, &client_%(resource_name)s_id_);"""
5720 if func.IsUnsafe():
5721 valid_test += """
5722 decoder_->set_unsafe_es3_apis_enabled(true);"""
5723 valid_test += """
5724 EXPECT_EQ(error::kNoError,
5725 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5726 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5727 if func.IsUnsafe():
5728 valid_test += """
5729 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
5730 client_%(resource_name)s_id_, NULL));
5731 decoder_->set_unsafe_es3_apis_enabled(false);
5732 EXPECT_EQ(error::kUnknownCommand,
5733 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5736 else:
5737 valid_test += """
5738 EXPECT_TRUE(
5739 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5742 self.WriteValidUnitTest(func, file, valid_test, {
5743 'resource_name': func.GetInfo('resource_type').lower(),
5744 'upper_resource_name': func.GetInfo('resource_type'),
5745 }, *extras)
5746 invalid_test = """
5747 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5748 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5749 SpecializedSetup<cmds::%(name)s, 0>(false);
5750 GLuint temp = kInvalidClientId;
5751 cmd.Init(1, &temp);"""
5752 if func.IsUnsafe():
5753 invalid_test += """
5754 decoder_->set_unsafe_es3_apis_enabled(true);
5755 EXPECT_EQ(error::kNoError,
5756 ExecuteImmediateCmd(cmd, sizeof(temp)));
5757 decoder_->set_unsafe_es3_apis_enabled(false);
5758 EXPECT_EQ(error::kUnknownCommand,
5759 ExecuteImmediateCmd(cmd, sizeof(temp)));
5762 else:
5763 invalid_test += """
5764 EXPECT_EQ(error::kNoError,
5765 ExecuteImmediateCmd(cmd, sizeof(temp)));
5768 self.WriteValidUnitTest(func, file, invalid_test, *extras)
5770 def WriteHandlerImplementation (self, func, file):
5771 """Overrriden from TypeHandler."""
5772 file.Write(" %sHelper(n, %s);\n" %
5773 (func.name, func.GetLastOriginalArg().name))
5775 def WriteImmediateHandlerImplementation (self, func, file):
5776 """Overrriden from TypeHandler."""
5777 if func.IsUnsafe():
5778 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5779 GLuint service_id = 0;
5780 if (group_->Get%(resource_type)sServiceId(
5781 %(last_arg_name)s[ii], &service_id)) {
5782 glDelete%(resource_type)ss(1, &service_id);
5783 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
5786 """ % { 'resource_type': func.GetInfo('resource_type'),
5787 'last_arg_name': func.GetLastOriginalArg().name })
5788 else:
5789 file.Write(" %sHelper(n, %s);\n" %
5790 (func.original_name, func.GetLastOriginalArg().name))
5792 def WriteGLES2Implementation(self, func, file):
5793 """Overrriden from TypeHandler."""
5794 impl_decl = func.GetInfo('impl_decl')
5795 if impl_decl == None or impl_decl == True:
5796 args = {
5797 'return_type': func.return_type,
5798 'name': func.original_name,
5799 'typed_args': func.MakeTypedOriginalArgString(""),
5800 'args': func.MakeOriginalArgString(""),
5801 'resource_type': func.GetInfo('resource_type').lower(),
5802 'count_name': func.GetOriginalArgs()[0].name,
5804 file.Write(
5805 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5806 args)
5807 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5808 func.WriteDestinationInitalizationValidation(file)
5809 self.WriteClientGLCallLog(func, file)
5810 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5811 for (GLsizei i = 0; i < n; ++i) {
5812 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5815 """ % func.GetOriginalArgs()[1].name)
5816 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
5817 for (GLsizei i = 0; i < n; ++i) {
5818 DCHECK(%s[i] != 0);
5821 """ % func.GetOriginalArgs()[1].name)
5822 for arg in func.GetOriginalArgs():
5823 arg.WriteClientSideValidationCode(file, func)
5824 code = """ %(name)sHelper(%(args)s);
5825 CheckGLError();
5829 file.Write(code % args)
5831 def WriteImmediateCmdComputeSize(self, func, file):
5832 """Overrriden from TypeHandler."""
5833 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5834 file.Write(
5835 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5836 file.Write(" }\n")
5837 file.Write("\n")
5838 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5839 file.Write(" return static_cast<uint32_t>(\n")
5840 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5841 file.Write(" }\n")
5842 file.Write("\n")
5844 def WriteImmediateCmdSetHeader(self, func, file):
5845 """Overrriden from TypeHandler."""
5846 file.Write(" void SetHeader(GLsizei n) {\n")
5847 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5848 file.Write(" }\n")
5849 file.Write("\n")
5851 def WriteImmediateCmdInit(self, func, file):
5852 """Overrriden from TypeHandler."""
5853 last_arg = func.GetLastOriginalArg()
5854 file.Write(" void Init(%s, %s _%s) {\n" %
5855 (func.MakeTypedCmdArgString("_"),
5856 last_arg.type, last_arg.name))
5857 file.Write(" SetHeader(_n);\n")
5858 args = func.GetCmdArgs()
5859 for arg in args:
5860 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5861 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5862 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5863 file.Write(" }\n")
5864 file.Write("\n")
5866 def WriteImmediateCmdSet(self, func, file):
5867 """Overrriden from TypeHandler."""
5868 last_arg = func.GetLastOriginalArg()
5869 copy_args = func.MakeCmdArgString("_", False)
5870 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5871 (func.MakeTypedCmdArgString("_", True),
5872 last_arg.type, last_arg.name))
5873 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5874 (copy_args, last_arg.name))
5875 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5876 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5877 "cmd, size);\n")
5878 file.Write(" }\n")
5879 file.Write("\n")
5881 def WriteImmediateCmdHelper(self, func, file):
5882 """Overrriden from TypeHandler."""
5883 code = """ void %(name)s(%(typed_args)s) {
5884 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5885 gles2::cmds::%(name)s* c =
5886 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5887 if (c) {
5888 c->Init(%(args)s);
5893 file.Write(code % {
5894 "name": func.name,
5895 "typed_args": func.MakeTypedOriginalArgString(""),
5896 "args": func.MakeOriginalArgString(""),
5899 def WriteImmediateFormatTest(self, func, file):
5900 """Overrriden from TypeHandler."""
5901 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5902 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5903 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5904 (func.name, func.name))
5905 file.Write(" void* next_cmd = cmd.Set(\n")
5906 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5907 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5908 func.name)
5909 file.Write(" cmd.header.command);\n")
5910 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5911 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5912 file.Write(" cmd.header.size * 4u);\n")
5913 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5914 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5915 file.Write(" next_cmd, sizeof(cmd) +\n")
5916 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5917 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5918 file.Write("}\n")
5919 file.Write("\n")
5922 class GETnHandler(TypeHandler):
5923 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
5925 def __init__(self):
5926 TypeHandler.__init__(self)
5928 def NeedsDataTransferFunction(self, func):
5929 """Overriden from TypeHandler."""
5930 return False
5932 def WriteServiceImplementation(self, func, file):
5933 """Overrriden from TypeHandler."""
5934 self.WriteServiceHandlerFunctionHeader(func, file)
5935 last_arg = func.GetLastOriginalArg()
5936 # All except shm_id and shm_offset.
5937 all_but_last_args = func.GetCmdArgs()[:-2]
5938 for arg in all_but_last_args:
5939 arg.WriteGetCode(file)
5941 code = """ typedef cmds::%(func_name)s::Result Result;
5942 GLsizei num_values = 0;
5943 GetNumValuesReturnedForGLGet(pname, &num_values);
5944 Result* result = GetSharedMemoryAs<Result*>(
5945 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
5946 Result::ComputeSize(num_values));
5947 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
5949 file.Write(code % {
5950 'last_arg_type': last_arg.type,
5951 'last_arg_name': last_arg.name,
5952 'func_name': func.name,
5954 func.WriteHandlerValidation(file)
5955 code = """ // Check that the client initialized the result.
5956 if (result->size != 0) {
5957 return error::kInvalidArguments;
5960 shadowed = func.GetInfo('shadowed')
5961 if not shadowed:
5962 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
5963 file.Write(code)
5964 func.WriteHandlerImplementation(file)
5965 if shadowed:
5966 code = """ result->SetNumResults(num_values);
5967 return error::kNoError;
5970 else:
5971 code = """ GLenum error = glGetError();
5972 if (error == GL_NO_ERROR) {
5973 result->SetNumResults(num_values);
5974 } else {
5975 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
5977 return error::kNoError;
5981 file.Write(code % {'func_name': func.name})
5983 def WriteGLES2Implementation(self, func, file):
5984 """Overrriden from TypeHandler."""
5985 impl_decl = func.GetInfo('impl_decl')
5986 if impl_decl == None or impl_decl == True:
5987 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5988 (func.return_type, func.original_name,
5989 func.MakeTypedOriginalArgString("")))
5990 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5991 func.WriteDestinationInitalizationValidation(file)
5992 self.WriteClientGLCallLog(func, file)
5993 for arg in func.GetOriginalArgs():
5994 arg.WriteClientSideValidationCode(file, func)
5995 all_but_last_args = func.GetOriginalArgs()[:-1]
5996 args = []
5997 has_length_arg = False
5998 for arg in all_but_last_args:
5999 if arg.type == 'GLsync':
6000 args.append('ToGLuint(%s)' % arg.name)
6001 elif arg.name.endswith('size') and arg.type == 'GLsizei':
6002 continue
6003 elif arg.name == 'length':
6004 has_length_arg = True
6005 continue
6006 else:
6007 args.append(arg.name)
6008 arg_string = ", ".join(args)
6009 all_arg_string = (
6010 ", ".join([
6011 "%s" % arg.name
6012 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
6013 self.WriteTraceEvent(func, file)
6014 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
6015 return;
6017 typedef cmds::%(func_name)s::Result Result;
6018 Result* result = GetResultAs<Result*>();
6019 if (!result) {
6020 return;
6022 result->SetNumResults(0);
6023 helper_->%(func_name)s(%(arg_string)s,
6024 GetResultShmId(), GetResultShmOffset());
6025 WaitForCmd();
6026 result->CopyResult(%(last_arg_name)s);
6027 GPU_CLIENT_LOG_CODE_BLOCK({
6028 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
6029 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
6031 });"""
6032 if has_length_arg:
6033 code += """
6034 if (length) {
6035 *length = result->GetNumResults();
6036 }"""
6037 code += """
6038 CheckGLError();
6041 file.Write(code % {
6042 'func_name': func.name,
6043 'arg_string': arg_string,
6044 'all_arg_string': all_arg_string,
6045 'last_arg_name': func.GetLastOriginalArg().name,
6048 def WriteGLES2ImplementationUnitTest(self, func, file):
6049 """Writes the GLES2 Implemention unit test."""
6050 code = """
6051 TEST_F(GLES2ImplementationTest, %(name)s) {
6052 struct Cmds {
6053 cmds::%(name)s cmd;
6055 typedef cmds::%(name)s::Result Result;
6056 Result::Type result = 0;
6057 Cmds expected;
6058 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
6059 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6060 EXPECT_CALL(*command_buffer(), OnFlush())
6061 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
6062 .RetiresOnSaturation();
6063 gl_->%(name)s(%(args)s, &result);
6064 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6065 EXPECT_EQ(static_cast<Result::Type>(1), result);
6068 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
6069 if not first_cmd_arg:
6070 return
6072 first_gl_arg = func.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6073 func)
6075 cmd_arg_strings = [first_cmd_arg]
6076 for arg in func.GetCmdArgs()[1:-2]:
6077 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6078 gl_arg_strings = [first_gl_arg]
6079 for arg in func.GetOriginalArgs()[1:-1]:
6080 gl_arg_strings.append(arg.GetValidClientSideArg(func))
6082 file.Write(code % {
6083 'name': func.name,
6084 'args': ", ".join(gl_arg_strings),
6085 'cmd_args': ", ".join(cmd_arg_strings),
6088 def WriteServiceUnitTest(self, func, file, *extras):
6089 """Overrriden from TypeHandler."""
6090 valid_test = """
6091 TEST_P(%(test_name)s, %(name)sValidArgs) {
6092 EXPECT_CALL(*gl_, GetError())
6093 .WillOnce(Return(GL_NO_ERROR))
6094 .WillOnce(Return(GL_NO_ERROR))
6095 .RetiresOnSaturation();
6096 SpecializedSetup<cmds::%(name)s, 0>(true);
6097 typedef cmds::%(name)s::Result Result;
6098 Result* result = static_cast<Result*>(shared_memory_address_);
6099 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6100 result->size = 0;
6101 cmds::%(name)s cmd;
6102 cmd.Init(%(cmd_args)s);"""
6103 if func.IsUnsafe():
6104 valid_test += """
6105 decoder_->set_unsafe_es3_apis_enabled(true);"""
6106 valid_test += """
6107 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6108 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6109 %(valid_pname)s),
6110 result->GetNumResults());
6111 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6112 if func.IsUnsafe():
6113 valid_test += """
6114 decoder_->set_unsafe_es3_apis_enabled(false);
6115 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6116 valid_test += """
6119 gl_arg_strings = []
6120 cmd_arg_strings = []
6121 valid_pname = ''
6122 for arg in func.GetOriginalArgs()[:-1]:
6123 if arg.name == 'length':
6124 gl_arg_value = 'nullptr'
6125 elif arg.name.endswith('size'):
6126 gl_arg_value = ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6127 valid_pname)
6128 elif arg.type == 'GLsync':
6129 gl_arg_value = 'reinterpret_cast<GLsync>(kServiceSyncId)'
6130 else:
6131 gl_arg_value = arg.GetValidGLArg(func)
6132 gl_arg_strings.append(gl_arg_value)
6133 if arg.name == 'pname':
6134 valid_pname = gl_arg_value
6135 if arg.name.endswith('size') or arg.name == 'length':
6136 continue
6137 if arg.type == 'GLsync':
6138 arg_value = 'client_sync_id_'
6139 else:
6140 arg_value = arg.GetValidArg(func)
6141 cmd_arg_strings.append(arg_value)
6142 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
6143 gl_arg_strings.append("_")
6144 else:
6145 gl_arg_strings.append("result->GetData()")
6146 cmd_arg_strings.append("shared_memory_id_")
6147 cmd_arg_strings.append("shared_memory_offset_")
6149 self.WriteValidUnitTest(func, file, valid_test, {
6150 'local_gl_args': ", ".join(gl_arg_strings),
6151 'cmd_args': ", ".join(cmd_arg_strings),
6152 'valid_pname': valid_pname,
6153 }, *extras)
6155 if not func.IsUnsafe():
6156 invalid_test = """
6157 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6158 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6159 SpecializedSetup<cmds::%(name)s, 0>(false);
6160 cmds::%(name)s::Result* result =
6161 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6162 result->size = 0;
6163 cmds::%(name)s cmd;
6164 cmd.Init(%(args)s);
6165 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6166 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6169 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
6171 class ArrayArgTypeHandler(TypeHandler):
6172 """Base class for type handlers that handle args that are arrays"""
6174 def __init__(self):
6175 TypeHandler.__init__(self)
6177 def GetArrayType(self, func):
6178 """Returns the type of the element in the element array being PUT to."""
6179 for arg in func.GetOriginalArgs():
6180 if arg.IsPointer():
6181 element_type = arg.GetPointedType()
6182 return element_type
6184 # Special case: array type handler is used for a function that is forwarded
6185 # to the actual array type implementation
6186 element_type = func.GetOriginalArgs()[-1].type
6187 assert all(arg.type == element_type \
6188 for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
6189 return element_type
6191 def GetArrayCount(self, func):
6192 """Returns the count of the elements in the array being PUT to."""
6193 return func.GetInfo('count')
6195 class PUTHandler(ArrayArgTypeHandler):
6196 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6198 def __init__(self):
6199 ArrayArgTypeHandler.__init__(self)
6201 def WriteServiceUnitTest(self, func, file, *extras):
6202 """Writes the service unit test for a command."""
6203 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6204 if func.GetInfo("first_element_only"):
6205 gl_arg_strings = [
6206 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
6208 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
6209 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6210 ", ".join(gl_arg_strings))
6211 valid_test = """
6212 TEST_P(%(test_name)s, %(name)sValidArgs) {
6213 SpecializedSetup<cmds::%(name)s, 0>(true);
6214 cmds::%(name)s cmd;
6215 cmd.Init(%(args)s);
6216 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6217 %(expected_call)s
6218 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6219 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6222 extra = {
6223 'data_type': self.GetArrayType(func),
6224 'data_value': func.GetInfo('data_value') or '0',
6225 'expected_call': expected_call,
6227 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6229 invalid_test = """
6230 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6231 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6232 SpecializedSetup<cmds::%(name)s, 0>(false);
6233 cmds::%(name)s cmd;
6234 cmd.Init(%(args)s);
6235 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6236 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6239 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6241 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6242 """Writes the service unit test for a command."""
6243 valid_test = """
6244 TEST_P(%(test_name)s, %(name)sValidArgs) {
6245 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6246 SpecializedSetup<cmds::%(name)s, 0>(true);
6247 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6248 cmd.Init(%(gl_args)s, &temp[0]);
6249 EXPECT_CALL(
6250 *gl_,
6251 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6252 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6253 if func.IsUnsafe():
6254 valid_test += """
6255 decoder_->set_unsafe_es3_apis_enabled(true);"""
6256 valid_test += """
6257 EXPECT_EQ(error::kNoError,
6258 ExecuteImmediateCmd(cmd, sizeof(temp)));
6259 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6260 if func.IsUnsafe():
6261 valid_test += """
6262 decoder_->set_unsafe_es3_apis_enabled(false);
6263 EXPECT_EQ(error::kUnknownCommand,
6264 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6265 valid_test += """
6268 gl_arg_strings = [
6269 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
6271 gl_any_strings = ["_"] * len(gl_arg_strings)
6273 extra = {
6274 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
6275 'data_type': self.GetArrayType(func),
6276 'data_count': self.GetArrayCount(func),
6277 'data_value': func.GetInfo('data_value') or '0',
6278 'gl_args': ", ".join(gl_arg_strings),
6279 'gl_any_args': ", ".join(gl_any_strings),
6281 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6283 invalid_test = """
6284 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6285 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6286 if func.IsUnsafe():
6287 invalid_test += """
6288 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6290 else:
6291 invalid_test += """
6292 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6294 invalid_test += """
6295 SpecializedSetup<cmds::%(name)s, 0>(false);
6296 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6297 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6298 if func.IsUnsafe():
6299 invalid_test += """
6300 decoder_->set_unsafe_es3_apis_enabled(true);
6301 EXPECT_EQ(error::%(parse_result)s,
6302 ExecuteImmediateCmd(cmd, sizeof(temp)));
6303 decoder_->set_unsafe_es3_apis_enabled(false);
6306 else:
6307 invalid_test += """
6308 EXPECT_EQ(error::%(parse_result)s,
6309 ExecuteImmediateCmd(cmd, sizeof(temp)));
6310 %(gl_error_test)s
6313 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6315 def WriteGetDataSizeCode(self, func, file):
6316 """Overrriden from TypeHandler."""
6317 code = """ uint32_t data_size;
6318 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6319 return error::kOutOfBounds;
6322 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6323 if func.IsImmediate():
6324 file.Write(" if (data_size > immediate_data_size) {\n")
6325 file.Write(" return error::kOutOfBounds;\n")
6326 file.Write(" }\n")
6328 def __NeedsToCalcDataCount(self, func):
6329 use_count_func = func.GetInfo('use_count_func')
6330 return use_count_func != None and use_count_func != False
6332 def WriteGLES2Implementation(self, func, file):
6333 """Overrriden from TypeHandler."""
6334 impl_func = func.GetInfo('impl_func')
6335 if (impl_func != None and impl_func != True):
6336 return;
6337 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6338 (func.return_type, func.original_name,
6339 func.MakeTypedOriginalArgString("")))
6340 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6341 func.WriteDestinationInitalizationValidation(file)
6342 self.WriteClientGLCallLog(func, file)
6344 if self.__NeedsToCalcDataCount(func):
6345 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6346 (func.name, func.GetOriginalArgs()[0].name))
6347 file.Write(" DCHECK_LE(count, %du);\n" % self.GetArrayCount(func))
6348 else:
6349 file.Write(" size_t count = %d;" % self.GetArrayCount(func))
6350 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
6351 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6352 func.GetLastOriginalArg().name)
6353 for arg in func.GetOriginalArgs():
6354 arg.WriteClientSideValidationCode(file, func)
6355 file.Write(" helper_->%sImmediate(%s);\n" %
6356 (func.name, func.MakeOriginalArgString("")))
6357 file.Write(" CheckGLError();\n")
6358 file.Write("}\n")
6359 file.Write("\n")
6361 def WriteGLES2ImplementationUnitTest(self, func, file):
6362 """Writes the GLES2 Implemention unit test."""
6363 client_test = func.GetInfo('client_test')
6364 if (client_test != None and client_test != True):
6365 return;
6366 code = """
6367 TEST_F(GLES2ImplementationTest, %(name)s) {
6368 %(type)s data[%(count)d] = {0};
6369 struct Cmds {
6370 cmds::%(name)sImmediate cmd;
6371 %(type)s data[%(count)d];
6374 for (int jj = 0; jj < %(count)d; ++jj) {
6375 data[jj] = static_cast<%(type)s>(jj);
6377 Cmds expected;
6378 expected.cmd.Init(%(cmd_args)s, &data[0]);
6379 gl_->%(name)s(%(args)s, &data[0]);
6380 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6383 cmd_arg_strings = [
6384 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
6386 gl_arg_strings = [
6387 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
6390 file.Write(code % {
6391 'name': func.name,
6392 'type': self.GetArrayType(func),
6393 'count': self.GetArrayCount(func),
6394 'args': ", ".join(gl_arg_strings),
6395 'cmd_args': ", ".join(cmd_arg_strings),
6398 def WriteImmediateCmdComputeSize(self, func, file):
6399 """Overrriden from TypeHandler."""
6400 file.Write(" static uint32_t ComputeDataSize() {\n")
6401 file.Write(" return static_cast<uint32_t>(\n")
6402 file.Write(" sizeof(%s) * %d);\n" %
6403 (self.GetArrayType(func), self.GetArrayCount(func)))
6404 file.Write(" }\n")
6405 file.Write("\n")
6406 if self.__NeedsToCalcDataCount(func):
6407 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6408 (func.GetOriginalArgs()[0].type,
6409 func.GetOriginalArgs()[0].name))
6410 file.Write(" return static_cast<uint32_t>(\n")
6411 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6412 (self.GetArrayType(func), func.original_name,
6413 func.GetOriginalArgs()[0].name))
6414 file.Write(" }\n")
6415 file.Write("\n")
6416 file.Write(" static uint32_t ComputeSize() {\n")
6417 file.Write(" return static_cast<uint32_t>(\n")
6418 file.Write(
6419 " sizeof(ValueType) + ComputeDataSize());\n")
6420 file.Write(" }\n")
6421 file.Write("\n")
6423 def WriteImmediateCmdSetHeader(self, func, file):
6424 """Overrriden from TypeHandler."""
6425 file.Write(" void SetHeader() {\n")
6426 file.Write(
6427 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6428 file.Write(" }\n")
6429 file.Write("\n")
6431 def WriteImmediateCmdInit(self, func, file):
6432 """Overrriden from TypeHandler."""
6433 last_arg = func.GetLastOriginalArg()
6434 file.Write(" void Init(%s, %s _%s) {\n" %
6435 (func.MakeTypedCmdArgString("_"),
6436 last_arg.type, last_arg.name))
6437 file.Write(" SetHeader();\n")
6438 args = func.GetCmdArgs()
6439 for arg in args:
6440 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6441 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6442 if self.__NeedsToCalcDataCount(func):
6443 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
6444 (last_arg.name, func.GetOriginalArgs()[0].name))
6445 file.Write("""
6446 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6447 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6448 ComputeEffectiveDataSize(%(arg)s);
6449 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6450 """ % { 'arg': func.GetOriginalArgs()[0].name, })
6451 else:
6452 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
6453 file.Write(" }\n")
6454 file.Write("\n")
6456 def WriteImmediateCmdSet(self, func, file):
6457 """Overrriden from TypeHandler."""
6458 last_arg = func.GetLastOriginalArg()
6459 copy_args = func.MakeCmdArgString("_", False)
6460 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6461 (func.MakeTypedCmdArgString("_", True),
6462 last_arg.type, last_arg.name))
6463 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6464 (copy_args, last_arg.name))
6465 file.Write(" const uint32_t size = ComputeSize();\n")
6466 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6467 "cmd, size);\n")
6468 file.Write(" }\n")
6469 file.Write("\n")
6471 def WriteImmediateCmdHelper(self, func, file):
6472 """Overrriden from TypeHandler."""
6473 code = """ void %(name)s(%(typed_args)s) {
6474 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
6475 gles2::cmds::%(name)s* c =
6476 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6477 if (c) {
6478 c->Init(%(args)s);
6483 file.Write(code % {
6484 "name": func.name,
6485 "typed_args": func.MakeTypedOriginalArgString(""),
6486 "args": func.MakeOriginalArgString(""),
6489 def WriteImmediateFormatTest(self, func, file):
6490 """Overrriden from TypeHandler."""
6491 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6492 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6493 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
6494 for v in range(0, self.GetArrayCount(func)):
6495 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6496 (self.GetArrayType(func), v))
6497 file.Write(" };\n")
6498 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6499 (func.name, func.name))
6500 file.Write(" void* next_cmd = cmd.Set(\n")
6501 file.Write(" &cmd")
6502 args = func.GetCmdArgs()
6503 for value, arg in enumerate(args):
6504 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
6505 file.Write(",\n data);\n")
6506 args = func.GetCmdArgs()
6507 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
6508 % func.name)
6509 file.Write(" cmd.header.command);\n")
6510 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6511 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
6512 file.Write(" cmd.header.size * 4u);\n")
6513 for value, arg in enumerate(args):
6514 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6515 (arg.type, value + 11, arg.name))
6516 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6517 file.Write(" next_cmd, sizeof(cmd) +\n")
6518 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6519 file.Write(" // TODO(gman): Check that data was inserted;\n")
6520 file.Write("}\n")
6521 file.Write("\n")
6524 class PUTnHandler(ArrayArgTypeHandler):
6525 """Handler for PUTn 'glUniform__v' type functions."""
6527 def __init__(self):
6528 ArrayArgTypeHandler.__init__(self)
6530 def WriteServiceUnitTest(self, func, file, *extras):
6531 """Overridden from TypeHandler."""
6532 ArrayArgTypeHandler.WriteServiceUnitTest(self, func, file, *extras)
6534 valid_test = """
6535 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
6536 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6537 SpecializedSetup<cmds::%(name)s, 0>(true);
6538 cmds::%(name)s cmd;
6539 cmd.Init(%(args)s);
6540 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6541 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6544 gl_arg_strings = []
6545 arg_strings = []
6546 for count, arg in enumerate(func.GetOriginalArgs()):
6547 # hardcoded to match unit tests.
6548 if count == 0:
6549 # the location of the second element of the 2nd uniform.
6550 # defined in GLES2DecoderBase::SetupShaderForUniform
6551 gl_arg_strings.append("3")
6552 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
6553 elif count == 1:
6554 # the number of elements that gl will be called with.
6555 gl_arg_strings.append("3")
6556 # the number of elements requested in the command.
6557 arg_strings.append("5")
6558 else:
6559 gl_arg_strings.append(arg.GetValidGLArg(func))
6560 if not arg.IsConstant():
6561 arg_strings.append(arg.GetValidArg(func))
6562 extra = {
6563 'gl_args': ", ".join(gl_arg_strings),
6564 'args': ", ".join(arg_strings),
6566 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6568 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6569 """Overridden from TypeHandler."""
6570 valid_test = """
6571 TEST_P(%(test_name)s, %(name)sValidArgs) {
6572 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6573 EXPECT_CALL(
6574 *gl_,
6575 %(gl_func_name)s(%(gl_args)s,
6576 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
6577 SpecializedSetup<cmds::%(name)s, 0>(true);
6578 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6579 cmd.Init(%(args)s, &temp[0]);"""
6580 if func.IsUnsafe():
6581 valid_test += """
6582 decoder_->set_unsafe_es3_apis_enabled(true);"""
6583 valid_test += """
6584 EXPECT_EQ(error::kNoError,
6585 ExecuteImmediateCmd(cmd, sizeof(temp)));
6586 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6587 if func.IsUnsafe():
6588 valid_test += """
6589 decoder_->set_unsafe_es3_apis_enabled(false);
6590 EXPECT_EQ(error::kUnknownCommand,
6591 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6592 valid_test += """
6595 gl_arg_strings = []
6596 gl_any_strings = []
6597 arg_strings = []
6598 for arg in func.GetOriginalArgs()[0:-1]:
6599 gl_arg_strings.append(arg.GetValidGLArg(func))
6600 gl_any_strings.append("_")
6601 if not arg.IsConstant():
6602 arg_strings.append(arg.GetValidArg(func))
6603 extra = {
6604 'data_type': self.GetArrayType(func),
6605 'data_count': self.GetArrayCount(func),
6606 'args': ", ".join(arg_strings),
6607 'gl_args': ", ".join(gl_arg_strings),
6608 'gl_any_args': ", ".join(gl_any_strings),
6610 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6612 invalid_test = """
6613 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6614 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6615 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6616 SpecializedSetup<cmds::%(name)s, 0>(false);
6617 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6618 cmd.Init(%(all_but_last_args)s, &temp[0]);
6619 EXPECT_EQ(error::%(parse_result)s,
6620 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
6623 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6625 def WriteGetDataSizeCode(self, func, file):
6626 """Overrriden from TypeHandler."""
6627 code = """ uint32_t data_size;
6628 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
6629 return error::kOutOfBounds;
6632 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6633 if func.IsImmediate():
6634 file.Write(" if (data_size > immediate_data_size) {\n")
6635 file.Write(" return error::kOutOfBounds;\n")
6636 file.Write(" }\n")
6638 def WriteGLES2Implementation(self, func, file):
6639 """Overrriden from TypeHandler."""
6640 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6641 (func.return_type, func.original_name,
6642 func.MakeTypedOriginalArgString("")))
6643 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6644 func.WriteDestinationInitalizationValidation(file)
6645 self.WriteClientGLCallLog(func, file)
6646 last_pointer_name = func.GetLastOriginalPointerArg().name
6647 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6648 for (GLsizei i = 0; i < count; ++i) {
6649 """)
6650 values_str = ' << ", " << '.join(
6651 ["%s[%d + i * %d]" % (
6652 last_pointer_name, ndx, self.GetArrayCount(func)) for ndx in range(
6653 0, self.GetArrayCount(func))])
6654 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
6655 file.Write(" }\n });\n")
6656 for arg in func.GetOriginalArgs():
6657 arg.WriteClientSideValidationCode(file, func)
6658 file.Write(" helper_->%sImmediate(%s);\n" %
6659 (func.name, func.MakeInitString("")))
6660 file.Write(" CheckGLError();\n")
6661 file.Write("}\n")
6662 file.Write("\n")
6664 def WriteGLES2ImplementationUnitTest(self, func, file):
6665 """Writes the GLES2 Implemention unit test."""
6666 code = """
6667 TEST_F(GLES2ImplementationTest, %(name)s) {
6668 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6669 struct Cmds {
6670 cmds::%(name)sImmediate cmd;
6671 %(type)s data[%(count_param)d][%(count)d];
6674 Cmds expected;
6675 for (int ii = 0; ii < %(count_param)d; ++ii) {
6676 for (int jj = 0; jj < %(count)d; ++jj) {
6677 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6680 expected.cmd.Init(%(cmd_args)s);
6681 gl_->%(name)s(%(args)s);
6682 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6685 cmd_arg_strings = []
6686 for arg in func.GetCmdArgs():
6687 if arg.name.endswith("_shm_id"):
6688 cmd_arg_strings.append("&data[0][0]")
6689 elif arg.name.endswith("_shm_offset"):
6690 continue
6691 else:
6692 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6693 gl_arg_strings = []
6694 count_param = 0
6695 for arg in func.GetOriginalArgs():
6696 if arg.IsPointer():
6697 valid_value = "&data[0][0]"
6698 else:
6699 valid_value = arg.GetValidClientSideArg(func)
6700 gl_arg_strings.append(valid_value)
6701 if arg.name == "count":
6702 count_param = int(valid_value)
6703 file.Write(code % {
6704 'name': func.name,
6705 'type': self.GetArrayType(func),
6706 'count': self.GetArrayCount(func),
6707 'args': ", ".join(gl_arg_strings),
6708 'cmd_args': ", ".join(cmd_arg_strings),
6709 'count_param': count_param,
6712 # Test constants for invalid values, as they are not tested by the
6713 # service.
6714 constants = [
6715 arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
6717 if not constants:
6718 return
6720 code = """
6721 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
6722 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6723 for (int ii = 0; ii < %(count_param)d; ++ii) {
6724 for (int jj = 0; jj < %(count)d; ++jj) {
6725 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6728 gl_->%(name)s(%(args)s);
6729 EXPECT_TRUE(NoCommandsWritten());
6730 EXPECT_EQ(%(gl_error)s, CheckError());
6733 for invalid_arg in constants:
6734 gl_arg_strings = []
6735 invalid = invalid_arg.GetInvalidArg(func)
6736 for arg in func.GetOriginalArgs():
6737 if arg is invalid_arg:
6738 gl_arg_strings.append(invalid[0])
6739 elif arg.IsPointer():
6740 gl_arg_strings.append("&data[0][0]")
6741 else:
6742 valid_value = arg.GetValidClientSideArg(func)
6743 gl_arg_strings.append(valid_value)
6744 if arg.name == "count":
6745 count_param = int(valid_value)
6747 file.Write(code % {
6748 'name': func.name,
6749 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
6750 'type': self.GetArrayType(func),
6751 'count': self.GetArrayCount(func),
6752 'args': ", ".join(gl_arg_strings),
6753 'gl_error': invalid[2],
6754 'count_param': count_param,
6758 def WriteImmediateCmdComputeSize(self, func, file):
6759 """Overrriden from TypeHandler."""
6760 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
6761 file.Write(" return static_cast<uint32_t>(\n")
6762 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
6763 (self.GetArrayType(func), self.GetArrayCount(func)))
6764 file.Write(" }\n")
6765 file.Write("\n")
6766 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
6767 file.Write(" return static_cast<uint32_t>(\n")
6768 file.Write(
6769 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
6770 file.Write(" }\n")
6771 file.Write("\n")
6773 def WriteImmediateCmdSetHeader(self, func, file):
6774 """Overrriden from TypeHandler."""
6775 file.Write(" void SetHeader(GLsizei count) {\n")
6776 file.Write(
6777 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
6778 file.Write(" }\n")
6779 file.Write("\n")
6781 def WriteImmediateCmdInit(self, func, file):
6782 """Overrriden from TypeHandler."""
6783 file.Write(" void Init(%s) {\n" %
6784 func.MakeTypedInitString("_"))
6785 file.Write(" SetHeader(_count);\n")
6786 args = func.GetCmdArgs()
6787 for arg in args:
6788 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6789 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6790 pointer_arg = func.GetLastOriginalPointerArg()
6791 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg.name)
6792 file.Write(" }\n")
6793 file.Write("\n")
6795 def WriteImmediateCmdSet(self, func, file):
6796 """Overrriden from TypeHandler."""
6797 file.Write(" void* Set(void* cmd%s) {\n" %
6798 func.MakeTypedInitString("_", True))
6799 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
6800 func.MakeInitString("_"))
6801 file.Write(" const uint32_t size = ComputeSize(_count);\n")
6802 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6803 "cmd, size);\n")
6804 file.Write(" }\n")
6805 file.Write("\n")
6807 def WriteImmediateCmdHelper(self, func, file):
6808 """Overrriden from TypeHandler."""
6809 code = """ void %(name)s(%(typed_args)s) {
6810 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
6811 gles2::cmds::%(name)s* c =
6812 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6813 if (c) {
6814 c->Init(%(args)s);
6819 file.Write(code % {
6820 "name": func.name,
6821 "typed_args": func.MakeTypedInitString(""),
6822 "args": func.MakeInitString("")
6825 def WriteImmediateFormatTest(self, func, file):
6826 """Overrriden from TypeHandler."""
6827 args = func.GetOriginalArgs()
6828 count_param = 0
6829 for arg in args:
6830 if arg.name == "count":
6831 count_param = int(arg.GetValidClientSideCmdArg(func))
6832 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6833 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6834 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
6835 for v in range(0, self.GetArrayCount(func) * count_param):
6836 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6837 (self.GetArrayType(func), v))
6838 file.Write(" };\n")
6839 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6840 (func.name, func.name))
6841 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
6842 file.Write(" const size_t kExpectedCmdSize =\n")
6843 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
6844 (self.GetArrayType(func), self.GetArrayCount(func)))
6845 file.Write(" void* next_cmd = cmd.Set(\n")
6846 file.Write(" &cmd")
6847 for value, arg in enumerate(args):
6848 if arg.IsPointer():
6849 file.Write(",\n data")
6850 elif arg.IsConstant():
6851 continue
6852 else:
6853 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
6854 file.Write(");\n")
6855 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6856 func.name)
6857 file.Write(" cmd.header.command);\n")
6858 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
6859 for value, arg in enumerate(args):
6860 if arg.IsPointer() or arg.IsConstant():
6861 continue
6862 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6863 (arg.type, value + 1, arg.name))
6864 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6865 file.Write(" next_cmd, sizeof(cmd) +\n")
6866 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6867 file.Write(" // TODO(gman): Check that data was inserted;\n")
6868 file.Write("}\n")
6869 file.Write("\n")
6871 class PUTSTRHandler(ArrayArgTypeHandler):
6872 """Handler for functions that pass a string array."""
6874 def __init__(self):
6875 ArrayArgTypeHandler.__init__(self)
6877 def __GetDataArg(self, func):
6878 """Return the argument that points to the 2D char arrays"""
6879 for arg in func.GetOriginalArgs():
6880 if arg.IsPointer2D():
6881 return arg
6882 return None
6884 def __GetLengthArg(self, func):
6885 """Return the argument that holds length for each char array"""
6886 for arg in func.GetOriginalArgs():
6887 if arg.IsPointer() and not arg.IsPointer2D():
6888 return arg
6889 return None
6891 def WriteGLES2Implementation(self, func, file):
6892 """Overrriden from TypeHandler."""
6893 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6894 (func.return_type, func.original_name,
6895 func.MakeTypedOriginalArgString("")))
6896 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6897 func.WriteDestinationInitalizationValidation(file)
6898 self.WriteClientGLCallLog(func, file)
6899 data_arg = self.__GetDataArg(func)
6900 length_arg = self.__GetLengthArg(func)
6901 log_code_block = """ GPU_CLIENT_LOG_CODE_BLOCK({
6902 for (GLsizei ii = 0; ii < count; ++ii) {
6903 if (%(data)s[ii]) {"""
6904 if length_arg == None:
6905 log_code_block += """
6906 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
6907 else:
6908 log_code_block += """
6909 if (%(length)s && %(length)s[ii] >= 0) {
6910 const std::string my_str(%(data)s[ii], %(length)s[ii]);
6911 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
6912 } else {
6913 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
6914 }"""
6915 log_code_block += """
6916 } else {
6917 GPU_CLIENT_LOG(" " << ii << ": NULL");
6922 file.Write(log_code_block % {
6923 'data': data_arg.name,
6924 'length': length_arg.name if not length_arg == None else ''
6926 for arg in func.GetOriginalArgs():
6927 arg.WriteClientSideValidationCode(file, func)
6929 bucket_args = []
6930 for arg in func.GetOriginalArgs():
6931 if arg.name == 'count' or arg == self.__GetLengthArg(func):
6932 continue
6933 if arg == self.__GetDataArg(func):
6934 bucket_args.append('kResultBucketId')
6935 else:
6936 bucket_args.append(arg.name)
6937 code_block = """
6938 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
6939 return;
6941 helper_->%(func_name)sBucket(%(bucket_args)s);
6942 helper_->SetBucketSize(kResultBucketId, 0);
6943 CheckGLError();
6947 file.Write(code_block % {
6948 'data': data_arg.name,
6949 'length': length_arg.name if not length_arg == None else 'NULL',
6950 'func_name': func.name,
6951 'bucket_args': ', '.join(bucket_args),
6954 def WriteGLES2ImplementationUnitTest(self, func, file):
6955 """Overrriden from TypeHandler."""
6956 code = """
6957 TEST_F(GLES2ImplementationTest, %(name)s) {
6958 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
6959 const char* kString1 = "happy";
6960 const char* kString2 = "ending";
6961 const size_t kString1Size = ::strlen(kString1) + 1;
6962 const size_t kString2Size = ::strlen(kString2) + 1;
6963 const size_t kHeaderSize = sizeof(GLint) * 3;
6964 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
6965 const size_t kPaddedHeaderSize =
6966 transfer_buffer_->RoundToAlignment(kHeaderSize);
6967 const size_t kPaddedString1Size =
6968 transfer_buffer_->RoundToAlignment(kString1Size);
6969 const size_t kPaddedString2Size =
6970 transfer_buffer_->RoundToAlignment(kString2Size);
6971 struct Cmds {
6972 cmd::SetBucketSize set_bucket_size;
6973 cmd::SetBucketData set_bucket_header;
6974 cmd::SetToken set_token1;
6975 cmd::SetBucketData set_bucket_data1;
6976 cmd::SetToken set_token2;
6977 cmd::SetBucketData set_bucket_data2;
6978 cmd::SetToken set_token3;
6979 cmds::%(name)sBucket cmd_bucket;
6980 cmd::SetBucketSize clear_bucket_size;
6983 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
6984 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
6985 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
6987 Cmds expected;
6988 expected.set_bucket_size.Init(kBucketId, kSourceSize);
6989 expected.set_bucket_header.Init(
6990 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
6991 expected.set_token1.Init(GetNextToken());
6992 expected.set_bucket_data1.Init(
6993 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
6994 expected.set_token2.Init(GetNextToken());
6995 expected.set_bucket_data2.Init(
6996 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
6997 mem2.offset);
6998 expected.set_token3.Init(GetNextToken());
6999 expected.cmd_bucket.Init(%(bucket_args)s);
7000 expected.clear_bucket_size.Init(kBucketId, 0);
7001 const char* kStrings[] = { kString1, kString2 };
7002 gl_->%(name)s(%(gl_args)s);
7003 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7006 gl_args = []
7007 bucket_args = []
7008 for arg in func.GetOriginalArgs():
7009 if arg == self.__GetDataArg(func):
7010 gl_args.append('kStrings')
7011 bucket_args.append('kBucketId')
7012 elif arg == self.__GetLengthArg(func):
7013 gl_args.append('NULL')
7014 elif arg.name == 'count':
7015 gl_args.append('2')
7016 else:
7017 gl_args.append(arg.GetValidClientSideArg(func))
7018 bucket_args.append(arg.GetValidClientSideArg(func))
7019 file.Write(code % {
7020 'name': func.name,
7021 'gl_args': ", ".join(gl_args),
7022 'bucket_args': ", ".join(bucket_args),
7025 if self.__GetLengthArg(func) == None:
7026 return
7027 code = """
7028 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
7029 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
7030 const char* kString = "foobar******";
7031 const size_t kStringSize = 6; // We only need "foobar".
7032 const size_t kHeaderSize = sizeof(GLint) * 2;
7033 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
7034 const size_t kPaddedHeaderSize =
7035 transfer_buffer_->RoundToAlignment(kHeaderSize);
7036 const size_t kPaddedStringSize =
7037 transfer_buffer_->RoundToAlignment(kStringSize + 1);
7038 struct Cmds {
7039 cmd::SetBucketSize set_bucket_size;
7040 cmd::SetBucketData set_bucket_header;
7041 cmd::SetToken set_token1;
7042 cmd::SetBucketData set_bucket_data;
7043 cmd::SetToken set_token2;
7044 cmds::ShaderSourceBucket shader_source_bucket;
7045 cmd::SetBucketSize clear_bucket_size;
7048 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7049 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7051 Cmds expected;
7052 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7053 expected.set_bucket_header.Init(
7054 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7055 expected.set_token1.Init(GetNextToken());
7056 expected.set_bucket_data.Init(
7057 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7058 expected.set_token2.Init(GetNextToken());
7059 expected.shader_source_bucket.Init(%(bucket_args)s);
7060 expected.clear_bucket_size.Init(kBucketId, 0);
7061 const char* kStrings[] = { kString };
7062 const GLint kLength[] = { kStringSize };
7063 gl_->%(name)s(%(gl_args)s);
7064 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7067 gl_args = []
7068 for arg in func.GetOriginalArgs():
7069 if arg == self.__GetDataArg(func):
7070 gl_args.append('kStrings')
7071 elif arg == self.__GetLengthArg(func):
7072 gl_args.append('kLength')
7073 elif arg.name == 'count':
7074 gl_args.append('1')
7075 else:
7076 gl_args.append(arg.GetValidClientSideArg(func))
7077 file.Write(code % {
7078 'name': func.name,
7079 'gl_args': ", ".join(gl_args),
7080 'bucket_args': ", ".join(bucket_args),
7083 def WriteBucketServiceUnitTest(self, func, file, *extras):
7084 """Overrriden from TypeHandler."""
7085 cmd_args = []
7086 cmd_args_with_invalid_id = []
7087 gl_args = []
7088 for index, arg in enumerate(func.GetOriginalArgs()):
7089 if arg == self.__GetLengthArg(func):
7090 gl_args.append('_')
7091 elif arg.name == 'count':
7092 gl_args.append('1')
7093 elif arg == self.__GetDataArg(func):
7094 cmd_args.append('kBucketId')
7095 cmd_args_with_invalid_id.append('kBucketId')
7096 gl_args.append('_')
7097 elif index == 0: # Resource ID arg
7098 cmd_args.append(arg.GetValidArg(func))
7099 cmd_args_with_invalid_id.append('kInvalidClientId')
7100 gl_args.append(arg.GetValidGLArg(func))
7101 else:
7102 cmd_args.append(arg.GetValidArg(func))
7103 cmd_args_with_invalid_id.append(arg.GetValidArg(func))
7104 gl_args.append(arg.GetValidGLArg(func))
7106 test = """
7107 TEST_P(%(test_name)s, %(name)sValidArgs) {
7108 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7109 const uint32 kBucketId = 123;
7110 const char kSource0[] = "hello";
7111 const char* kSource[] = { kSource0 };
7112 const char kValidStrEnd = 0;
7113 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7114 cmds::%(name)s cmd;
7115 cmd.Init(%(cmd_args)s);
7116 decoder_->set_unsafe_es3_apis_enabled(true);
7117 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7118 if func.IsUnsafe():
7119 test += """
7120 decoder_->set_unsafe_es3_apis_enabled(false);
7121 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7123 test += """
7126 self.WriteValidUnitTest(func, file, test, {
7127 'cmd_args': ", ".join(cmd_args),
7128 'gl_args': ", ".join(gl_args),
7129 }, *extras)
7131 test = """
7132 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7133 const uint32 kBucketId = 123;
7134 const char kSource0[] = "hello";
7135 const char* kSource[] = { kSource0 };
7136 const char kValidStrEnd = 0;
7137 decoder_->set_unsafe_es3_apis_enabled(true);
7138 cmds::%(name)s cmd;
7139 // Test no bucket.
7140 cmd.Init(%(cmd_args)s);
7141 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7142 // Test invalid client.
7143 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7144 cmd.Init(%(cmd_args_with_invalid_id)s);
7145 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7146 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7149 self.WriteValidUnitTest(func, file, test, {
7150 'cmd_args': ", ".join(cmd_args),
7151 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id),
7152 }, *extras)
7154 test = """
7155 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7156 const uint32 kBucketId = 123;
7157 const char kSource0[] = "hello";
7158 const char* kSource[] = { kSource0 };
7159 const char kValidStrEnd = 0;
7160 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7161 const GLsizei kTests[] = {
7162 kCount + 1,
7164 std::numeric_limits<GLsizei>::max(),
7167 decoder_->set_unsafe_es3_apis_enabled(true);
7168 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7169 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7170 cmds::%(name)s cmd;
7171 cmd.Init(%(cmd_args)s);
7172 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7176 self.WriteValidUnitTest(func, file, test, {
7177 'cmd_args': ", ".join(cmd_args),
7178 }, *extras)
7180 test = """
7181 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7182 const uint32 kBucketId = 123;
7183 const char kSource0[] = "hello";
7184 const char* kSource[] = { kSource0 };
7185 const char kInvalidStrEnd = '*';
7186 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7187 cmds::%(name)s cmd;
7188 cmd.Init(%(cmd_args)s);
7189 decoder_->set_unsafe_es3_apis_enabled(true);
7190 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7193 self.WriteValidUnitTest(func, file, test, {
7194 'cmd_args': ", ".join(cmd_args),
7195 }, *extras)
7198 class PUTXnHandler(ArrayArgTypeHandler):
7199 """Handler for glUniform?f functions."""
7200 def __init__(self):
7201 ArrayArgTypeHandler.__init__(self)
7203 def WriteHandlerImplementation(self, func, file):
7204 """Overrriden from TypeHandler."""
7205 code = """ %(type)s temp[%(count)s] = { %(values)s};"""
7206 if func.IsUnsafe():
7207 code += """
7208 gl%(name)sv(%(location)s, 1, &temp[0]);
7210 else:
7211 code += """
7212 Do%(name)sv(%(location)s, 1, &temp[0]);
7214 values = ""
7215 args = func.GetOriginalArgs()
7216 count = int(self.GetArrayCount(func))
7217 num_args = len(args)
7218 for ii in range(count):
7219 values += "%s, " % args[len(args) - count + ii].name
7221 file.Write(code % {
7222 'name': func.name,
7223 'count': self.GetArrayCount(func),
7224 'type': self.GetArrayType(func),
7225 'location': args[0].name,
7226 'args': func.MakeOriginalArgString(""),
7227 'values': values,
7230 def WriteServiceUnitTest(self, func, file, *extras):
7231 """Overrriden from TypeHandler."""
7232 valid_test = """
7233 TEST_P(%(test_name)s, %(name)sValidArgs) {
7234 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7235 SpecializedSetup<cmds::%(name)s, 0>(true);
7236 cmds::%(name)s cmd;
7237 cmd.Init(%(args)s);"""
7238 if func.IsUnsafe():
7239 valid_test += """
7240 decoder_->set_unsafe_es3_apis_enabled(true);"""
7241 valid_test += """
7242 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7243 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7244 if func.IsUnsafe():
7245 valid_test += """
7246 decoder_->set_unsafe_es3_apis_enabled(false);
7247 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7248 valid_test += """
7251 args = func.GetOriginalArgs()
7252 local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
7253 self.WriteValidUnitTest(func, file, valid_test, {
7254 'name': func.name,
7255 'count': self.GetArrayCount(func),
7256 'local_args': local_args,
7257 }, *extras)
7259 invalid_test = """
7260 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7261 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7262 SpecializedSetup<cmds::%(name)s, 0>(false);
7263 cmds::%(name)s cmd;
7264 cmd.Init(%(args)s);
7265 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7268 self.WriteInvalidUnitTest(func, file, invalid_test, {
7269 'name': func.GetInfo('name'),
7270 'count': self.GetArrayCount(func),
7274 class GLcharHandler(CustomHandler):
7275 """Handler for functions that pass a single string ."""
7277 def __init__(self):
7278 CustomHandler.__init__(self)
7280 def WriteImmediateCmdComputeSize(self, func, file):
7281 """Overrriden from TypeHandler."""
7282 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7283 file.Write(" return static_cast<uint32_t>(\n")
7284 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
7285 file.Write(" }\n")
7287 def WriteImmediateCmdSetHeader(self, func, file):
7288 """Overrriden from TypeHandler."""
7289 code = """
7290 void SetHeader(uint32_t data_size) {
7291 header.SetCmdBySize<ValueType>(data_size);
7294 file.Write(code)
7296 def WriteImmediateCmdInit(self, func, file):
7297 """Overrriden from TypeHandler."""
7298 last_arg = func.GetLastOriginalArg()
7299 args = func.GetCmdArgs()
7300 set_code = []
7301 for arg in args:
7302 set_code.append(" %s = _%s;" % (arg.name, arg.name))
7303 code = """
7304 void Init(%(typed_args)s, uint32_t _data_size) {
7305 SetHeader(_data_size);
7306 %(set_code)s
7307 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7311 file.Write(code % {
7312 "typed_args": func.MakeTypedArgString("_"),
7313 "set_code": "\n".join(set_code),
7314 "last_arg": last_arg.name
7317 def WriteImmediateCmdSet(self, func, file):
7318 """Overrriden from TypeHandler."""
7319 last_arg = func.GetLastOriginalArg()
7320 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7321 func.MakeTypedCmdArgString("_", True))
7322 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7323 func.MakeCmdArgString("_"))
7324 file.Write(" return NextImmediateCmdAddress<ValueType>("
7325 "cmd, _data_size);\n")
7326 file.Write(" }\n")
7327 file.Write("\n")
7329 def WriteImmediateCmdHelper(self, func, file):
7330 """Overrriden from TypeHandler."""
7331 code = """ void %(name)s(%(typed_args)s) {
7332 const uint32_t data_size = strlen(name);
7333 gles2::cmds::%(name)s* c =
7334 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7335 if (c) {
7336 c->Init(%(args)s, data_size);
7341 file.Write(code % {
7342 "name": func.name,
7343 "typed_args": func.MakeTypedOriginalArgString(""),
7344 "args": func.MakeOriginalArgString(""),
7348 def WriteImmediateFormatTest(self, func, file):
7349 """Overrriden from TypeHandler."""
7350 init_code = []
7351 check_code = []
7352 all_but_last_arg = func.GetCmdArgs()[:-1]
7353 for value, arg in enumerate(all_but_last_arg):
7354 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
7355 for value, arg in enumerate(all_but_last_arg):
7356 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7357 (arg.type, value + 11, arg.name))
7358 code = """
7359 TEST_F(GLES2FormatTest, %(func_name)s) {
7360 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7361 static const char* const test_str = \"test string\";
7362 void* next_cmd = cmd.Set(
7363 &cmd,
7364 %(init_code)s
7365 test_str,
7366 strlen(test_str));
7367 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7368 cmd.header.command);
7369 EXPECT_EQ(sizeof(cmd) +
7370 RoundSizeToMultipleOfEntries(strlen(test_str)),
7371 cmd.header.size * 4u);
7372 EXPECT_EQ(static_cast<char*>(next_cmd),
7373 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7374 RoundSizeToMultipleOfEntries(strlen(test_str)));
7375 %(check_code)s
7376 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7377 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7378 CheckBytesWritten(
7379 next_cmd,
7380 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7381 sizeof(cmd) + strlen(test_str));
7385 file.Write(code % {
7386 'func_name': func.name,
7387 'init_code': "\n".join(init_code),
7388 'check_code': "\n".join(check_code),
7392 class GLcharNHandler(CustomHandler):
7393 """Handler for functions that pass a single string with an optional len."""
7395 def __init__(self):
7396 CustomHandler.__init__(self)
7398 def InitFunction(self, func):
7399 """Overrriden from TypeHandler."""
7400 func.cmd_args = []
7401 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
7403 def NeedsDataTransferFunction(self, func):
7404 """Overriden from TypeHandler."""
7405 return False
7407 def AddBucketFunction(self, generator, func):
7408 """Overrriden from TypeHandler."""
7409 pass
7411 def WriteServiceImplementation(self, func, file):
7412 """Overrriden from TypeHandler."""
7413 self.WriteServiceHandlerFunctionHeader(func, file)
7414 file.Write("""
7415 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7416 Bucket* bucket = GetBucket(bucket_id);
7417 if (!bucket || bucket->size() == 0) {
7418 return error::kInvalidArguments;
7420 std::string str;
7421 if (!bucket->GetAsString(&str)) {
7422 return error::kInvalidArguments;
7424 %(gl_func_name)s(0, str.c_str());
7425 return error::kNoError;
7428 """ % {
7429 'name': func.name,
7430 'gl_func_name': func.GetGLFunctionName(),
7431 'bucket_id': func.cmd_args[0].name,
7435 class IsHandler(TypeHandler):
7436 """Handler for glIs____ type and glGetError functions."""
7438 def __init__(self):
7439 TypeHandler.__init__(self)
7441 def InitFunction(self, func):
7442 """Overrriden from TypeHandler."""
7443 func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7444 func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7445 if func.GetInfo('result') == None:
7446 func.AddInfo('result', ['uint32_t'])
7448 def WriteServiceUnitTest(self, func, file, *extras):
7449 """Overrriden from TypeHandler."""
7450 valid_test = """
7451 TEST_P(%(test_name)s, %(name)sValidArgs) {
7452 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7453 SpecializedSetup<cmds::%(name)s, 0>(true);
7454 cmds::%(name)s cmd;
7455 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7456 if func.IsUnsafe():
7457 valid_test += """
7458 decoder_->set_unsafe_es3_apis_enabled(true);"""
7459 valid_test += """
7460 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7461 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7462 if func.IsUnsafe():
7463 valid_test += """
7464 decoder_->set_unsafe_es3_apis_enabled(false);
7465 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7466 valid_test += """
7469 comma = ""
7470 if len(func.GetOriginalArgs()):
7471 comma =", "
7472 self.WriteValidUnitTest(func, file, valid_test, {
7473 'comma': comma,
7474 }, *extras)
7476 invalid_test = """
7477 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7478 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7479 SpecializedSetup<cmds::%(name)s, 0>(false);
7480 cmds::%(name)s cmd;
7481 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7482 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7485 self.WriteInvalidUnitTest(func, file, invalid_test, {
7486 'comma': comma,
7487 }, *extras)
7489 invalid_test = """
7490 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
7491 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7492 SpecializedSetup<cmds::%(name)s, 0>(false);"""
7493 if func.IsUnsafe():
7494 invalid_test += """
7495 decoder_->set_unsafe_es3_apis_enabled(true);"""
7496 invalid_test += """
7497 cmds::%(name)s cmd;
7498 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
7499 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
7500 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
7501 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
7502 if func.IsUnsafe():
7503 invalid_test += """
7504 decoder_->set_unsafe_es3_apis_enabled(true);"""
7505 invalid_test += """
7508 self.WriteValidUnitTest(func, file, invalid_test, {
7509 'comma': comma,
7510 }, *extras)
7512 def WriteServiceImplementation(self, func, file):
7513 """Overrriden from TypeHandler."""
7514 self.WriteServiceHandlerFunctionHeader(func, file)
7515 args = func.GetOriginalArgs()
7516 for arg in args:
7517 arg.WriteGetCode(file)
7519 code = """ typedef cmds::%(func_name)s::Result Result;
7520 Result* result_dst = GetSharedMemoryAs<Result*>(
7521 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
7522 if (!result_dst) {
7523 return error::kOutOfBounds;
7526 file.Write(code % {'func_name': func.name})
7527 func.WriteHandlerValidation(file)
7528 if func.IsUnsafe():
7529 assert func.GetInfo('id_mapping')
7530 assert len(func.GetInfo('id_mapping')) == 1
7531 assert len(args) == 1
7532 id_type = func.GetInfo('id_mapping')[0]
7533 file.Write(" %s service_%s = 0;\n" % (args[0].type, id_type.lower()))
7534 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
7535 (id_type, id_type.lower(), id_type.lower()))
7536 else:
7537 file.Write(" *result_dst = %s(%s);\n" %
7538 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
7539 file.Write(" return error::kNoError;\n")
7540 file.Write("}\n")
7541 file.Write("\n")
7543 def WriteGLES2Implementation(self, func, file):
7544 """Overrriden from TypeHandler."""
7545 impl_func = func.GetInfo('impl_func')
7546 if impl_func == None or impl_func == True:
7547 error_value = func.GetInfo("error_value") or "GL_FALSE"
7548 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7549 (func.return_type, func.original_name,
7550 func.MakeTypedOriginalArgString("")))
7551 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7552 self.WriteTraceEvent(func, file)
7553 func.WriteDestinationInitalizationValidation(file)
7554 self.WriteClientGLCallLog(func, file)
7555 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
7556 file.Write(" Result* result = GetResultAs<Result*>();\n")
7557 file.Write(" if (!result) {\n")
7558 file.Write(" return %s;\n" % error_value)
7559 file.Write(" }\n")
7560 file.Write(" *result = 0;\n")
7561 assert len(func.GetOriginalArgs()) == 1
7562 id_arg = func.GetOriginalArgs()[0]
7563 if id_arg.type == 'GLsync':
7564 arg_string = "ToGLuint(%s)" % func.MakeOriginalArgString("")
7565 else:
7566 arg_string = func.MakeOriginalArgString("")
7567 file.Write(
7568 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
7569 (func.name, arg_string))
7570 file.Write(" WaitForCmd();\n")
7571 file.Write(" %s result_value = *result" % func.return_type)
7572 if func.return_type == "GLboolean":
7573 file.Write(" != 0")
7574 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
7575 file.Write(" CheckGLError();\n")
7576 file.Write(" return result_value;\n")
7577 file.Write("}\n")
7578 file.Write("\n")
7580 def WriteGLES2ImplementationUnitTest(self, func, file):
7581 """Overrriden from TypeHandler."""
7582 client_test = func.GetInfo('client_test')
7583 if client_test == None or client_test == True:
7584 code = """
7585 TEST_F(GLES2ImplementationTest, %(name)s) {
7586 struct Cmds {
7587 cmds::%(name)s cmd;
7590 Cmds expected;
7591 ExpectedMemoryInfo result1 =
7592 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
7593 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
7595 EXPECT_CALL(*command_buffer(), OnFlush())
7596 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
7597 .RetiresOnSaturation();
7599 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
7600 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7601 EXPECT_TRUE(result);
7604 args = func.GetOriginalArgs()
7605 assert len(args) == 1
7606 file.Write(code % {
7607 'name': func.name,
7608 'cmd_id_value': args[0].GetValidClientSideCmdArg(func),
7609 'gl_id_value': args[0].GetValidClientSideArg(func) })
7612 class STRnHandler(TypeHandler):
7613 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
7614 GetTranslatedShaderSourceANGLE."""
7616 def __init__(self):
7617 TypeHandler.__init__(self)
7619 def InitFunction(self, func):
7620 """Overrriden from TypeHandler."""
7621 # remove all but the first cmd args.
7622 cmd_args = func.GetCmdArgs()
7623 func.ClearCmdArgs()
7624 func.AddCmdArg(cmd_args[0])
7625 # add on a bucket id.
7626 func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
7628 def WriteGLES2Implementation(self, func, file):
7629 """Overrriden from TypeHandler."""
7630 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
7631 GPU_CLIENT_SINGLE_THREAD_CHECK();
7633 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
7634 << "] gl%(func_name)s" << "("
7635 << %(arg0)s << ", "
7636 << %(arg1)s << ", "
7637 << static_cast<void*>(%(arg2)s) << ", "
7638 << static_cast<void*>(%(arg3)s) << ")");
7639 helper_->SetBucketSize(kResultBucketId, 0);
7640 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
7641 std::string str;
7642 GLsizei max_size = 0;
7643 if (GetBucketAsString(kResultBucketId, &str)) {
7644 if (bufsize > 0) {
7645 max_size =
7646 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
7647 memcpy(%(dest_name)s, str.c_str(), max_size);
7648 %(dest_name)s[max_size] = '\\0';
7649 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
7652 if (%(length_name)s != NULL) {
7653 *%(length_name)s = max_size;
7655 CheckGLError();
7658 args = func.GetOriginalArgs()
7659 str_args = {
7660 'return_type': func.return_type,
7661 'func_name': func.original_name,
7662 'args': func.MakeTypedOriginalArgString(""),
7663 'id_name': args[0].name,
7664 'bufsize_name': args[1].name,
7665 'length_name': args[2].name,
7666 'dest_name': args[3].name,
7667 'arg0': args[0].name,
7668 'arg1': args[1].name,
7669 'arg2': args[2].name,
7670 'arg3': args[3].name,
7672 file.Write(code_1 % str_args)
7673 func.WriteDestinationInitalizationValidation(file)
7674 file.Write(code_2 % str_args)
7676 def WriteServiceUnitTest(self, func, file, *extras):
7677 """Overrriden from TypeHandler."""
7678 valid_test = """
7679 TEST_P(%(test_name)s, %(name)sValidArgs) {
7680 const char* kInfo = "hello";
7681 const uint32_t kBucketId = 123;
7682 SpecializedSetup<cmds::%(name)s, 0>(true);
7683 %(expect_len_code)s
7684 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
7685 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
7686 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
7687 cmds::%(name)s cmd;
7688 cmd.Init(%(args)s);
7689 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7690 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
7691 ASSERT_TRUE(bucket != NULL);
7692 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
7693 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
7694 bucket->size()));
7695 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7698 args = func.GetOriginalArgs()
7699 id_name = args[0].GetValidGLArg(func)
7700 get_len_func = func.GetInfo('get_len_func')
7701 get_len_enum = func.GetInfo('get_len_enum')
7702 sub = {
7703 'id_name': id_name,
7704 'get_len_func': get_len_func,
7705 'get_len_enum': get_len_enum,
7706 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
7707 args[0].GetValidGLArg(func),
7708 'args': '%s, kBucketId' % args[0].GetValidArg(func),
7709 'expect_len_code': '',
7711 if get_len_func and get_len_func[0:2] == 'gl':
7712 sub['expect_len_code'] = (
7713 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
7714 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
7715 get_len_func[2:], id_name, get_len_enum)
7716 self.WriteValidUnitTest(func, file, valid_test, sub, *extras)
7718 invalid_test = """
7719 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7720 const uint32_t kBucketId = 123;
7721 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
7722 .Times(0);
7723 cmds::%(name)s cmd;
7724 cmd.Init(kInvalidClientId, kBucketId);
7725 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7726 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7729 self.WriteValidUnitTest(func, file, invalid_test, *extras)
7731 def WriteServiceImplementation(self, func, file):
7732 """Overrriden from TypeHandler."""
7733 pass
7735 class NamedType(object):
7736 """A class that represents a type of an argument in a client function.
7738 A type of an argument that is to be passed through in the command buffer
7739 command. Currently used only for the arguments that are specificly named in
7740 the 'cmd_buffer_functions.txt' file, mostly enums.
7743 def __init__(self, info):
7744 assert not 'is_complete' in info or info['is_complete'] == True
7745 self.info = info
7746 self.valid = info['valid']
7747 if 'invalid' in info:
7748 self.invalid = info['invalid']
7749 else:
7750 self.invalid = []
7751 if 'valid_es3' in info:
7752 self.valid_es3 = info['valid_es3']
7753 else:
7754 self.valid_es3 = []
7755 if 'deprecated_es3' in info:
7756 self.deprecated_es3 = info['deprecated_es3']
7757 else:
7758 self.deprecated_es3 = []
7760 def GetType(self):
7761 return self.info['type']
7763 def GetInvalidValues(self):
7764 return self.invalid
7766 def GetValidValues(self):
7767 return self.valid
7769 def GetValidValuesES3(self):
7770 return self.valid_es3
7772 def GetDeprecatedValuesES3(self):
7773 return self.deprecated_es3
7775 def IsConstant(self):
7776 if not 'is_complete' in self.info:
7777 return False
7779 return len(self.GetValidValues()) == 1
7781 def GetConstantValue(self):
7782 return self.GetValidValues()[0]
7784 class Argument(object):
7785 """A class that represents a function argument."""
7787 cmd_type_map_ = {
7788 'GLenum': 'uint32_t',
7789 'GLint': 'int32_t',
7790 'GLintptr': 'int32_t',
7791 'GLsizei': 'int32_t',
7792 'GLsizeiptr': 'int32_t',
7793 'GLfloat': 'float',
7794 'GLclampf': 'float',
7796 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
7798 def __init__(self, name, type):
7799 self.name = name
7800 self.optional = type.endswith("Optional*")
7801 if self.optional:
7802 type = type[:-9] + "*"
7803 self.type = type
7805 if type in self.cmd_type_map_:
7806 self.cmd_type = self.cmd_type_map_[type]
7807 else:
7808 self.cmd_type = 'uint32_t'
7810 def IsPointer(self):
7811 """Returns true if argument is a pointer."""
7812 return False
7814 def IsPointer2D(self):
7815 """Returns true if argument is a 2D pointer."""
7816 return False
7818 def IsConstant(self):
7819 """Returns true if the argument has only one valid value."""
7820 return False
7822 def AddCmdArgs(self, args):
7823 """Adds command arguments for this argument to the given list."""
7824 if not self.IsConstant():
7825 return args.append(self)
7827 def AddInitArgs(self, args):
7828 """Adds init arguments for this argument to the given list."""
7829 if not self.IsConstant():
7830 return args.append(self)
7832 def GetValidArg(self, func):
7833 """Gets a valid value for this argument."""
7834 valid_arg = func.GetValidArg(self)
7835 if valid_arg != None:
7836 return valid_arg
7838 index = func.GetOriginalArgs().index(self)
7839 return str(index + 1)
7841 def GetValidClientSideArg(self, func):
7842 """Gets a valid value for this argument."""
7843 valid_arg = func.GetValidArg(self)
7844 if valid_arg != None:
7845 return valid_arg
7847 if self.IsPointer():
7848 return 'nullptr'
7849 index = func.GetOriginalArgs().index(self)
7850 if self.type == 'GLsync':
7851 return ("reinterpret_cast<GLsync>(%d)" % (index + 1))
7852 return str(index + 1)
7854 def GetValidClientSideCmdArg(self, func):
7855 """Gets a valid value for this argument."""
7856 valid_arg = func.GetValidArg(self)
7857 if valid_arg != None:
7858 return valid_arg
7859 try:
7860 index = func.GetOriginalArgs().index(self)
7861 return str(index + 1)
7862 except ValueError:
7863 pass
7864 index = func.GetCmdArgs().index(self)
7865 return str(index + 1)
7867 def GetValidGLArg(self, func):
7868 """Gets a valid GL value for this argument."""
7869 value = self.GetValidArg(func)
7870 if self.type == 'GLsync':
7871 return ("reinterpret_cast<GLsync>(%s)" % value)
7872 return value
7874 def GetValidNonCachedClientSideArg(self, func):
7875 """Returns a valid value for this argument in a GL call.
7876 Using the value will produce a command buffer service invocation.
7877 Returns None if there is no such value."""
7878 value = '123'
7879 if self.type == 'GLsync':
7880 return ("reinterpret_cast<GLsync>(%s)" % value)
7881 return value
7883 def GetValidNonCachedClientSideCmdArg(self, func):
7884 """Returns a valid value for this argument in a command buffer command.
7885 Calling the GL function with the value returned by
7886 GetValidNonCachedClientSideArg will result in a command buffer command
7887 that contains the value returned by this function. """
7888 return '123'
7890 def GetNumInvalidValues(self, func):
7891 """returns the number of invalid values to be tested."""
7892 return 0
7894 def GetInvalidArg(self, index):
7895 """returns an invalid value and expected parse result by index."""
7896 return ("---ERROR0---", "---ERROR2---", None)
7898 def GetLogArg(self):
7899 """Get argument appropriate for LOG macro."""
7900 if self.type == 'GLboolean':
7901 return 'GLES2Util::GetStringBool(%s)' % self.name
7902 if self.type == 'GLenum':
7903 return 'GLES2Util::GetStringEnum(%s)' % self.name
7904 return self.name
7906 def WriteGetCode(self, file):
7907 """Writes the code to get an argument from a command structure."""
7908 if self.type == 'GLsync':
7909 my_type = 'GLuint'
7910 else:
7911 my_type = self.type
7912 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
7913 (my_type, self.name, my_type, self.name))
7915 def WriteValidationCode(self, file, func):
7916 """Writes the validation code for an argument."""
7917 pass
7919 def WriteClientSideValidationCode(self, file, func):
7920 """Writes the validation code for an argument."""
7921 pass
7923 def WriteDestinationInitalizationValidation(self, file, func):
7924 """Writes the client side destintion initialization validation."""
7925 pass
7927 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
7928 """Writes the client side destintion initialization validation if needed."""
7929 parts = self.type.split(" ")
7930 if len(parts) > 1:
7931 return
7932 if parts[0] in self.need_validation_:
7933 file.Write(
7934 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
7935 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
7938 def WriteGetAddress(self, file):
7939 """Writes the code to get the address this argument refers to."""
7940 pass
7942 def GetImmediateVersion(self):
7943 """Gets the immediate version of this argument."""
7944 return self
7946 def GetBucketVersion(self):
7947 """Gets the bucket version of this argument."""
7948 return self
7951 class BoolArgument(Argument):
7952 """class for GLboolean"""
7954 def __init__(self, name, type):
7955 Argument.__init__(self, name, 'GLboolean')
7957 def GetValidArg(self, func):
7958 """Gets a valid value for this argument."""
7959 return 'true'
7961 def GetValidClientSideArg(self, func):
7962 """Gets a valid value for this argument."""
7963 return 'true'
7965 def GetValidClientSideCmdArg(self, func):
7966 """Gets a valid value for this argument."""
7967 return 'true'
7969 def GetValidGLArg(self, func):
7970 """Gets a valid GL value for this argument."""
7971 return 'true'
7974 class UniformLocationArgument(Argument):
7975 """class for uniform locations."""
7977 def __init__(self, name):
7978 Argument.__init__(self, name, "GLint")
7980 def WriteGetCode(self, file):
7981 """Writes the code to get an argument from a command structure."""
7982 code = """ %s %s = static_cast<%s>(c.%s);
7984 file.Write(code % (self.type, self.name, self.type, self.name))
7986 class DataSizeArgument(Argument):
7987 """class for data_size which Bucket commands do not need."""
7989 def __init__(self, name):
7990 Argument.__init__(self, name, "uint32_t")
7992 def GetBucketVersion(self):
7993 return None
7996 class SizeArgument(Argument):
7997 """class for GLsizei and GLsizeiptr."""
7999 def __init__(self, name, type):
8000 Argument.__init__(self, name, type)
8002 def GetNumInvalidValues(self, func):
8003 """overridden from Argument."""
8004 if func.IsImmediate():
8005 return 0
8006 return 1
8008 def GetInvalidArg(self, index):
8009 """overridden from Argument."""
8010 return ("-1", "kNoError", "GL_INVALID_VALUE")
8012 def WriteValidationCode(self, file, func):
8013 """overridden from Argument."""
8014 if func.IsUnsafe():
8015 return
8016 code = """ if (%(var_name)s < 0) {
8017 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8018 return error::kNoError;
8021 file.Write(code % {
8022 "var_name": self.name,
8023 "func_name": func.original_name,
8026 def WriteClientSideValidationCode(self, file, func):
8027 """overridden from Argument."""
8028 code = """ if (%(var_name)s < 0) {
8029 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
8030 return;
8033 file.Write(code % {
8034 "var_name": self.name,
8035 "func_name": func.original_name,
8039 class SizeNotNegativeArgument(SizeArgument):
8040 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8042 def __init__(self, name, type, gl_type):
8043 SizeArgument.__init__(self, name, gl_type)
8045 def GetInvalidArg(self, index):
8046 """overridden from SizeArgument."""
8047 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8049 def WriteValidationCode(self, file, func):
8050 """overridden from SizeArgument."""
8051 pass
8054 class EnumBaseArgument(Argument):
8055 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8056 ValidatedBoolArgument."""
8058 def __init__(self, name, gl_type, type, gl_error):
8059 Argument.__init__(self, name, gl_type)
8061 self.local_type = type
8062 self.gl_error = gl_error
8063 name = type[len(gl_type):]
8064 self.type_name = name
8065 self.named_type = NamedType(_NAMED_TYPE_INFO[name])
8067 def IsConstant(self):
8068 return self.named_type.IsConstant()
8070 def GetConstantValue(self):
8071 return self.named_type.GetConstantValue()
8073 def WriteValidationCode(self, file, func):
8074 if func.IsUnsafe():
8075 return
8076 if self.named_type.IsConstant():
8077 return
8078 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
8079 (ToUnderscore(self.type_name), self.name))
8080 if self.gl_error == "GL_INVALID_ENUM":
8081 file.Write(
8082 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8083 (func.original_name, self.name, self.name))
8084 else:
8085 file.Write(
8086 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8087 (self.gl_error, func.original_name, self.name, self.gl_error))
8088 file.Write(" return error::kNoError;\n")
8089 file.Write(" }\n")
8091 def WriteClientSideValidationCode(self, file, func):
8092 if not self.named_type.IsConstant():
8093 return
8094 file.Write(" if (%s != %s) {" % (self.name,
8095 self.GetConstantValue()))
8096 file.Write(
8097 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8098 (self.gl_error, func.original_name, self.name, self.gl_error))
8099 if func.return_type == "void":
8100 file.Write(" return;\n")
8101 else:
8102 file.Write(" return %s;\n" % func.GetErrorReturnString())
8103 file.Write(" }\n")
8105 def GetValidArg(self, func):
8106 valid_arg = func.GetValidArg(self)
8107 if valid_arg != None:
8108 return valid_arg
8109 valid = self.named_type.GetValidValues()
8110 if valid:
8111 num_valid = len(valid)
8112 return valid[0]
8114 index = func.GetOriginalArgs().index(self)
8115 return str(index + 1)
8117 def GetValidClientSideArg(self, func):
8118 """Gets a valid value for this argument."""
8119 return self.GetValidArg(func)
8121 def GetValidClientSideCmdArg(self, func):
8122 """Gets a valid value for this argument."""
8123 valid_arg = func.GetValidArg(self)
8124 if valid_arg != None:
8125 return valid_arg
8127 valid = self.named_type.GetValidValues()
8128 if valid:
8129 num_valid = len(valid)
8130 return valid[0]
8132 try:
8133 index = func.GetOriginalArgs().index(self)
8134 return str(index + 1)
8135 except ValueError:
8136 pass
8137 index = func.GetCmdArgs().index(self)
8138 return str(index + 1)
8140 def GetValidGLArg(self, func):
8141 """Gets a valid value for this argument."""
8142 return self.GetValidArg(func)
8144 def GetNumInvalidValues(self, func):
8145 """returns the number of invalid values to be tested."""
8146 return len(self.named_type.GetInvalidValues())
8148 def GetInvalidArg(self, index):
8149 """returns an invalid value by index."""
8150 invalid = self.named_type.GetInvalidValues()
8151 if invalid:
8152 num_invalid = len(invalid)
8153 if index >= num_invalid:
8154 index = num_invalid - 1
8155 return (invalid[index], "kNoError", self.gl_error)
8156 return ("---ERROR1---", "kNoError", self.gl_error)
8159 class EnumArgument(EnumBaseArgument):
8160 """A class that represents a GLenum argument"""
8162 def __init__(self, name, type):
8163 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
8165 def GetLogArg(self):
8166 """Overridden from Argument."""
8167 return ("GLES2Util::GetString%s(%s)" %
8168 (self.type_name, self.name))
8171 class IntArgument(EnumBaseArgument):
8172 """A class for a GLint argument that can only accept specific values.
8174 For example glTexImage2D takes a GLint for its internalformat
8175 argument instead of a GLenum.
8178 def __init__(self, name, type):
8179 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
8182 class ValidatedBoolArgument(EnumBaseArgument):
8183 """A class for a GLboolean argument that can only accept specific values.
8185 For example glUniformMatrix takes a GLboolean for it's transpose but it
8186 must be false.
8189 def __init__(self, name, type):
8190 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
8192 def GetLogArg(self):
8193 """Overridden from Argument."""
8194 return 'GLES2Util::GetStringBool(%s)' % self.name
8197 class BitFieldArgument(EnumBaseArgument):
8198 """A class for a GLbitfield argument that can only accept specific values.
8200 For example glFenceSync takes a GLbitfield for its flags argument bit it
8201 must be 0.
8204 def __init__(self, name, type):
8205 EnumBaseArgument.__init__(self, name, "GLbitfield", type,
8206 "GL_INVALID_VALUE")
8209 class ImmediatePointerArgument(Argument):
8210 """A class that represents an immediate argument to a function.
8212 An immediate argument is one where the data follows the command.
8215 def __init__(self, name, type):
8216 Argument.__init__(self, name, type)
8218 def IsPointer(self):
8219 return True
8221 def GetPointedType(self):
8222 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8223 assert match
8224 return match.groupdict()['element_type']
8226 def AddCmdArgs(self, args):
8227 """Overridden from Argument."""
8228 pass
8230 def WriteGetCode(self, file):
8231 """Overridden from Argument."""
8232 file.Write(
8233 " %s %s = GetImmediateDataAs<%s>(\n" %
8234 (self.type, self.name, self.type))
8235 file.Write(" c, data_size, immediate_data_size);\n")
8237 def WriteValidationCode(self, file, func):
8238 """Overridden from Argument."""
8239 if self.optional:
8240 return
8241 file.Write(" if (%s == NULL) {\n" % self.name)
8242 file.Write(" return error::kOutOfBounds;\n")
8243 file.Write(" }\n")
8245 def GetImmediateVersion(self):
8246 """Overridden from Argument."""
8247 return None
8249 def WriteDestinationInitalizationValidation(self, file, func):
8250 """Overridden from Argument."""
8251 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8253 def GetLogArg(self):
8254 """Overridden from Argument."""
8255 return "static_cast<const void*>(%s)" % self.name
8258 class PointerArgument(Argument):
8259 """A class that represents a pointer argument to a function."""
8261 def __init__(self, name, type):
8262 Argument.__init__(self, name, type)
8264 def IsPointer(self):
8265 """Overridden from Argument."""
8266 return True
8268 def IsPointer2D(self):
8269 """Overridden from Argument."""
8270 return self.type.count('*') == 2
8272 def GetPointedType(self):
8273 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8274 assert match
8275 return match.groupdict()['element_type']
8277 def GetValidArg(self, func):
8278 """Overridden from Argument."""
8279 return "shared_memory_id_, shared_memory_offset_"
8281 def GetValidGLArg(self, func):
8282 """Overridden from Argument."""
8283 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
8285 def GetNumInvalidValues(self, func):
8286 """Overridden from Argument."""
8287 return 2
8289 def GetInvalidArg(self, index):
8290 """Overridden from Argument."""
8291 if index == 0:
8292 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8293 else:
8294 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8295 "kOutOfBounds", None)
8297 def GetLogArg(self):
8298 """Overridden from Argument."""
8299 return "static_cast<const void*>(%s)" % self.name
8301 def AddCmdArgs(self, args):
8302 """Overridden from Argument."""
8303 args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
8304 args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
8306 def WriteGetCode(self, file):
8307 """Overridden from Argument."""
8308 file.Write(
8309 " %s %s = GetSharedMemoryAs<%s>(\n" %
8310 (self.type, self.name, self.type))
8311 file.Write(
8312 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8313 (self.name, self.name))
8315 def WriteGetAddress(self, file):
8316 """Overridden from Argument."""
8317 file.Write(
8318 " %s %s = GetSharedMemoryAs<%s>(\n" %
8319 (self.type, self.name, self.type))
8320 file.Write(
8321 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8322 (self.name, self.name, self.name))
8324 def WriteValidationCode(self, file, func):
8325 """Overridden from Argument."""
8326 if self.optional:
8327 return
8328 file.Write(" if (%s == NULL) {\n" % self.name)
8329 file.Write(" return error::kOutOfBounds;\n")
8330 file.Write(" }\n")
8332 def GetImmediateVersion(self):
8333 """Overridden from Argument."""
8334 return ImmediatePointerArgument(self.name, self.type)
8336 def GetBucketVersion(self):
8337 """Overridden from Argument."""
8338 if self.type.find('char') >= 0:
8339 if self.IsPointer2D():
8340 return InputStringArrayBucketArgument(self.name, self.type)
8341 return InputStringBucketArgument(self.name, self.type)
8342 return BucketPointerArgument(self.name, self.type)
8344 def WriteDestinationInitalizationValidation(self, file, func):
8345 """Overridden from Argument."""
8346 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8349 class BucketPointerArgument(PointerArgument):
8350 """A class that represents an bucket argument to a function."""
8352 def __init__(self, name, type):
8353 Argument.__init__(self, name, type)
8355 def AddCmdArgs(self, args):
8356 """Overridden from Argument."""
8357 pass
8359 def WriteGetCode(self, file):
8360 """Overridden from Argument."""
8361 file.Write(
8362 " %s %s = bucket->GetData(0, data_size);\n" %
8363 (self.type, self.name))
8365 def WriteValidationCode(self, file, func):
8366 """Overridden from Argument."""
8367 pass
8369 def GetImmediateVersion(self):
8370 """Overridden from Argument."""
8371 return None
8373 def WriteDestinationInitalizationValidation(self, file, func):
8374 """Overridden from Argument."""
8375 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8377 def GetLogArg(self):
8378 """Overridden from Argument."""
8379 return "static_cast<const void*>(%s)" % self.name
8382 class InputStringBucketArgument(Argument):
8383 """A string input argument where the string is passed in a bucket."""
8385 def __init__(self, name, type):
8386 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8388 def IsPointer(self):
8389 """Overridden from Argument."""
8390 return True
8392 def IsPointer2D(self):
8393 """Overridden from Argument."""
8394 return False
8397 class InputStringArrayBucketArgument(Argument):
8398 """A string array input argument where the strings are passed in a bucket."""
8400 def __init__(self, name, type):
8401 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8402 self._original_name = name
8404 def WriteGetCode(self, file):
8405 """Overridden from Argument."""
8406 code = """
8407 Bucket* bucket = GetBucket(c.%(name)s);
8408 if (!bucket) {
8409 return error::kInvalidArguments;
8411 GLsizei count = 0;
8412 std::vector<char*> strs;
8413 std::vector<GLint> len;
8414 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8415 return error::kInvalidArguments;
8417 const char** %(original_name)s =
8418 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8419 const GLint* length =
8420 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8421 (void)length;
8423 file.Write(code % {
8424 'name': self.name,
8425 'original_name': self._original_name,
8428 def GetValidArg(self, func):
8429 return "kNameBucketId"
8431 def GetValidGLArg(self, func):
8432 return "_"
8434 def IsPointer(self):
8435 """Overridden from Argument."""
8436 return True
8438 def IsPointer2D(self):
8439 """Overridden from Argument."""
8440 return True
8443 class ResourceIdArgument(Argument):
8444 """A class that represents a resource id argument to a function."""
8446 def __init__(self, name, type):
8447 match = re.match("(GLid\w+)", type)
8448 self.resource_type = match.group(1)[4:]
8449 if self.resource_type == "Sync":
8450 type = type.replace(match.group(1), "GLsync")
8451 else:
8452 type = type.replace(match.group(1), "GLuint")
8453 Argument.__init__(self, name, type)
8455 def WriteGetCode(self, file):
8456 """Overridden from Argument."""
8457 if self.type == "GLsync":
8458 my_type = "GLuint"
8459 else:
8460 my_type = self.type
8461 file.Write(" %s %s = c.%s;\n" % (my_type, self.name, self.name))
8463 def GetValidArg(self, func):
8464 return "client_%s_id_" % self.resource_type.lower()
8466 def GetValidGLArg(self, func):
8467 if self.resource_type == "Sync":
8468 return "reinterpret_cast<GLsync>(kService%sId)" % self.resource_type
8469 return "kService%sId" % self.resource_type
8472 class ResourceIdBindArgument(Argument):
8473 """Represents a resource id argument to a bind function."""
8475 def __init__(self, name, type):
8476 match = re.match("(GLidBind\w+)", type)
8477 self.resource_type = match.group(1)[8:]
8478 type = type.replace(match.group(1), "GLuint")
8479 Argument.__init__(self, name, type)
8481 def WriteGetCode(self, file):
8482 """Overridden from Argument."""
8483 code = """ %(type)s %(name)s = c.%(name)s;
8485 file.Write(code % {'type': self.type, 'name': self.name})
8487 def GetValidArg(self, func):
8488 return "client_%s_id_" % self.resource_type.lower()
8490 def GetValidGLArg(self, func):
8491 return "kService%sId" % self.resource_type
8494 class ResourceIdZeroArgument(Argument):
8495 """Represents a resource id argument to a function that can be zero."""
8497 def __init__(self, name, type):
8498 match = re.match("(GLidZero\w+)", type)
8499 self.resource_type = match.group(1)[8:]
8500 type = type.replace(match.group(1), "GLuint")
8501 Argument.__init__(self, name, type)
8503 def WriteGetCode(self, file):
8504 """Overridden from Argument."""
8505 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
8507 def GetValidArg(self, func):
8508 return "client_%s_id_" % self.resource_type.lower()
8510 def GetValidGLArg(self, func):
8511 return "kService%sId" % self.resource_type
8513 def GetNumInvalidValues(self, func):
8514 """returns the number of invalid values to be tested."""
8515 return 1
8517 def GetInvalidArg(self, index):
8518 """returns an invalid value by index."""
8519 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
8522 class Function(object):
8523 """A class that represents a function."""
8525 type_handlers = {
8526 '': TypeHandler(),
8527 'Bind': BindHandler(),
8528 'Create': CreateHandler(),
8529 'Custom': CustomHandler(),
8530 'Data': DataHandler(),
8531 'Delete': DeleteHandler(),
8532 'DELn': DELnHandler(),
8533 'GENn': GENnHandler(),
8534 'GETn': GETnHandler(),
8535 'GLchar': GLcharHandler(),
8536 'GLcharN': GLcharNHandler(),
8537 'HandWritten': HandWrittenHandler(),
8538 'Is': IsHandler(),
8539 'Manual': ManualHandler(),
8540 'PUT': PUTHandler(),
8541 'PUTn': PUTnHandler(),
8542 'PUTSTR': PUTSTRHandler(),
8543 'PUTXn': PUTXnHandler(),
8544 'StateSet': StateSetHandler(),
8545 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
8546 'StateSetFrontBack': StateSetFrontBackHandler(),
8547 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
8548 'StateSetNamedParameter': StateSetNamedParameter(),
8549 'STRn': STRnHandler(),
8550 'Todo': TodoHandler(),
8553 def __init__(self, name, info):
8554 self.name = name
8555 self.original_name = info['original_name']
8557 self.original_args = self.ParseArgs(info['original_args'])
8559 if 'cmd_args' in info:
8560 self.args_for_cmds = self.ParseArgs(info['cmd_args'])
8561 else:
8562 self.args_for_cmds = self.original_args[:]
8564 self.return_type = info['return_type']
8565 if self.return_type != 'void':
8566 self.return_arg = CreateArg(info['return_type'] + " result")
8567 else:
8568 self.return_arg = None
8570 self.num_pointer_args = sum(
8571 [1 for arg in self.args_for_cmds if arg.IsPointer()])
8572 if self.num_pointer_args > 0:
8573 for arg in reversed(self.original_args):
8574 if arg.IsPointer():
8575 self.last_original_pointer_arg = arg
8576 break
8577 else:
8578 self.last_original_pointer_arg = None
8579 self.info = info
8580 self.type_handler = self.type_handlers[info['type']]
8581 self.can_auto_generate = (self.num_pointer_args == 0 and
8582 info['return_type'] == "void")
8583 self.InitFunction()
8585 def ParseArgs(self, arg_string):
8586 """Parses a function arg string."""
8587 args = []
8588 parts = arg_string.split(',')
8589 for arg_string in parts:
8590 arg = CreateArg(arg_string)
8591 if arg:
8592 args.append(arg)
8593 return args
8595 def IsType(self, type_name):
8596 """Returns true if function is a certain type."""
8597 return self.info['type'] == type_name
8599 def InitFunction(self):
8600 """Creates command args and calls the init function for the type handler.
8602 Creates argument lists for command buffer commands, eg. self.cmd_args and
8603 self.init_args.
8604 Calls the type function initialization.
8605 Override to create different kind of command buffer command argument lists.
8607 self.cmd_args = []
8608 for arg in self.args_for_cmds:
8609 arg.AddCmdArgs(self.cmd_args)
8611 self.init_args = []
8612 for arg in self.args_for_cmds:
8613 arg.AddInitArgs(self.init_args)
8615 if self.return_arg:
8616 self.init_args.append(self.return_arg)
8618 self.type_handler.InitFunction(self)
8620 def IsImmediate(self):
8621 """Returns whether the function is immediate data function or not."""
8622 return False
8624 def IsUnsafe(self):
8625 """Returns whether the function has service side validation or not."""
8626 return self.GetInfo('unsafe', False)
8628 def GetInfo(self, name, default = None):
8629 """Returns a value from the function info for this function."""
8630 if name in self.info:
8631 return self.info[name]
8632 return default
8634 def GetValidArg(self, arg):
8635 """Gets a valid argument value for the parameter arg from the function info
8636 if one exists."""
8637 try:
8638 index = self.GetOriginalArgs().index(arg)
8639 except ValueError:
8640 return None
8642 valid_args = self.GetInfo('valid_args')
8643 if valid_args and str(index) in valid_args:
8644 return valid_args[str(index)]
8645 return None
8647 def AddInfo(self, name, value):
8648 """Adds an info."""
8649 self.info[name] = value
8651 def IsExtension(self):
8652 return self.GetInfo('extension') or self.GetInfo('extension_flag')
8654 def IsCoreGLFunction(self):
8655 return (not self.IsExtension() and
8656 not self.GetInfo('pepper_interface') and
8657 not self.IsUnsafe())
8659 def InPepperInterface(self, interface):
8660 ext = self.GetInfo('pepper_interface')
8661 if not interface.GetName():
8662 return self.IsCoreGLFunction()
8663 return ext == interface.GetName()
8665 def InAnyPepperExtension(self):
8666 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
8668 def GetErrorReturnString(self):
8669 if self.GetInfo("error_return"):
8670 return self.GetInfo("error_return")
8671 elif self.return_type == "GLboolean":
8672 return "GL_FALSE"
8673 elif "*" in self.return_type:
8674 return "NULL"
8675 return "0"
8677 def GetGLFunctionName(self):
8678 """Gets the function to call to execute GL for this command."""
8679 if self.GetInfo('decoder_func'):
8680 return self.GetInfo('decoder_func')
8681 return "gl%s" % self.original_name
8683 def GetGLTestFunctionName(self):
8684 gl_func_name = self.GetInfo('gl_test_func')
8685 if gl_func_name == None:
8686 gl_func_name = self.GetGLFunctionName()
8687 if gl_func_name.startswith("gl"):
8688 gl_func_name = gl_func_name[2:]
8689 else:
8690 gl_func_name = self.original_name
8691 return gl_func_name
8693 def GetDataTransferMethods(self):
8694 return self.GetInfo('data_transfer_methods',
8695 ['immediate' if self.num_pointer_args == 1 else 'shm'])
8697 def AddCmdArg(self, arg):
8698 """Adds a cmd argument to this function."""
8699 self.cmd_args.append(arg)
8701 def GetCmdArgs(self):
8702 """Gets the command args for this function."""
8703 return self.cmd_args
8705 def ClearCmdArgs(self):
8706 """Clears the command args for this function."""
8707 self.cmd_args = []
8709 def GetCmdConstants(self):
8710 """Gets the constants for this function."""
8711 return [arg for arg in self.args_for_cmds if arg.IsConstant()]
8713 def GetInitArgs(self):
8714 """Gets the init args for this function."""
8715 return self.init_args
8717 def GetOriginalArgs(self):
8718 """Gets the original arguments to this function."""
8719 return self.original_args
8721 def GetLastOriginalArg(self):
8722 """Gets the last original argument to this function."""
8723 return self.original_args[len(self.original_args) - 1]
8725 def GetLastOriginalPointerArg(self):
8726 return self.last_original_pointer_arg
8728 def GetResourceIdArg(self):
8729 for arg in self.original_args:
8730 if hasattr(arg, 'resource_type'):
8731 return arg
8732 return None
8734 def _MaybePrependComma(self, arg_string, add_comma):
8735 """Adds a comma if arg_string is not empty and add_comma is true."""
8736 comma = ""
8737 if add_comma and len(arg_string):
8738 comma = ", "
8739 return "%s%s" % (comma, arg_string)
8741 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
8742 """Gets a list of arguments as they are in GL."""
8743 args = self.GetOriginalArgs()
8744 arg_string = ", ".join(
8745 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8746 return self._MaybePrependComma(arg_string, add_comma)
8748 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
8749 """Gets the list of arguments as they are in GL."""
8750 args = self.GetOriginalArgs()
8751 arg_string = separator.join(
8752 ["%s%s" % (prefix, arg.name) for arg in args])
8753 return self._MaybePrependComma(arg_string, add_comma)
8755 def MakeTypedHelperArgString(self, prefix, add_comma = False):
8756 """Gets a list of typed GL arguments after removing unneeded arguments."""
8757 args = self.GetOriginalArgs()
8758 arg_string = ", ".join(
8759 ["%s %s%s" % (
8760 arg.type,
8761 prefix,
8762 arg.name,
8763 ) for arg in args if not arg.IsConstant()])
8764 return self._MaybePrependComma(arg_string, add_comma)
8766 def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
8767 """Gets a list of GL arguments after removing unneeded arguments."""
8768 args = self.GetOriginalArgs()
8769 arg_string = separator.join(
8770 ["%s%s" % (prefix, arg.name)
8771 for arg in args if not arg.IsConstant()])
8772 return self._MaybePrependComma(arg_string, add_comma)
8774 def MakeTypedPepperArgString(self, prefix):
8775 """Gets a list of arguments as they need to be for Pepper."""
8776 if self.GetInfo("pepper_args"):
8777 return self.GetInfo("pepper_args")
8778 else:
8779 return self.MakeTypedOriginalArgString(prefix, False)
8781 def MapCTypeToPepperIdlType(self, ctype, is_for_return_type=False):
8782 """Converts a C type name to the corresponding Pepper IDL type."""
8783 idltype = {
8784 'char*': '[out] str_t',
8785 'const GLchar* const*': '[out] cstr_t',
8786 'const char*': 'cstr_t',
8787 'const void*': 'mem_t',
8788 'void*': '[out] mem_t',
8789 'void**': '[out] mem_ptr_t',
8790 }.get(ctype, ctype)
8791 # We use "GLxxx_ptr_t" for "GLxxx*".
8792 matched = re.match(r'(const )?(GL\w+)\*$', ctype)
8793 if matched:
8794 idltype = matched.group(2) + '_ptr_t'
8795 if not matched.group(1):
8796 idltype = '[out] ' + idltype
8797 # If an in/out specifier is not specified yet, prepend [in].
8798 if idltype[0] != '[':
8799 idltype = '[in] ' + idltype
8800 # Strip the in/out specifier for a return type.
8801 if is_for_return_type:
8802 idltype = re.sub(r'\[\w+\] ', '', idltype)
8803 return idltype
8805 def MakeTypedPepperIdlArgStrings(self):
8806 """Gets a list of arguments as they need to be for Pepper IDL."""
8807 args = self.GetOriginalArgs()
8808 return ["%s %s" % (self.MapCTypeToPepperIdlType(arg.type), arg.name)
8809 for arg in args]
8811 def GetPepperName(self):
8812 if self.GetInfo("pepper_name"):
8813 return self.GetInfo("pepper_name")
8814 return self.name
8816 def MakeTypedCmdArgString(self, prefix, add_comma = False):
8817 """Gets a typed list of arguments as they need to be for command buffers."""
8818 args = self.GetCmdArgs()
8819 arg_string = ", ".join(
8820 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8821 return self._MaybePrependComma(arg_string, add_comma)
8823 def MakeCmdArgString(self, prefix, add_comma = False):
8824 """Gets the list of arguments as they need to be for command buffers."""
8825 args = self.GetCmdArgs()
8826 arg_string = ", ".join(
8827 ["%s%s" % (prefix, arg.name) for arg in args])
8828 return self._MaybePrependComma(arg_string, add_comma)
8830 def MakeTypedInitString(self, prefix, add_comma = False):
8831 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
8832 args = self.GetInitArgs()
8833 arg_string = ", ".join(
8834 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8835 return self._MaybePrependComma(arg_string, add_comma)
8837 def MakeInitString(self, prefix, add_comma = False):
8838 """Gets the list of arguments as they need to be for cmd Init/Set."""
8839 args = self.GetInitArgs()
8840 arg_string = ", ".join(
8841 ["%s%s" % (prefix, arg.name) for arg in args])
8842 return self._MaybePrependComma(arg_string, add_comma)
8844 def MakeLogArgString(self):
8845 """Makes a string of the arguments for the LOG macros"""
8846 args = self.GetOriginalArgs()
8847 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
8849 def WriteCommandDescription(self, file):
8850 """Writes a description of the command."""
8851 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
8853 def WriteHandlerValidation(self, file):
8854 """Writes validation code for the function."""
8855 for arg in self.GetOriginalArgs():
8856 arg.WriteValidationCode(file, self)
8857 self.WriteValidationCode(file)
8859 def WriteHandlerImplementation(self, file):
8860 """Writes the handler implementation for this command."""
8861 self.type_handler.WriteHandlerImplementation(self, file)
8863 def WriteValidationCode(self, file):
8864 """Writes the validation code for a command."""
8865 pass
8867 def WriteCmdFlag(self, file):
8868 """Writes the cmd cmd_flags constant."""
8869 flags = []
8870 # By default trace only at the highest level 3.
8871 trace_level = int(self.GetInfo('trace_level', default = 3))
8872 if trace_level not in xrange(0, 4):
8873 raise KeyError("Unhandled trace_level: %d" % trace_level)
8875 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
8877 if len(flags) > 0:
8878 cmd_flags = ' | '.join(flags)
8879 else:
8880 cmd_flags = 0
8882 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
8885 def WriteCmdArgFlag(self, file):
8886 """Writes the cmd kArgFlags constant."""
8887 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
8889 def WriteCmdComputeSize(self, file):
8890 """Writes the ComputeSize function for the command."""
8891 file.Write(" static uint32_t ComputeSize() {\n")
8892 file.Write(
8893 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
8894 file.Write(" }\n")
8895 file.Write("\n")
8897 def WriteCmdSetHeader(self, file):
8898 """Writes the cmd's SetHeader function."""
8899 file.Write(" void SetHeader() {\n")
8900 file.Write(" header.SetCmd<ValueType>();\n")
8901 file.Write(" }\n")
8902 file.Write("\n")
8904 def WriteCmdInit(self, file):
8905 """Writes the cmd's Init function."""
8906 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
8907 file.Write(" SetHeader();\n")
8908 args = self.GetCmdArgs()
8909 for arg in args:
8910 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
8911 file.Write(" }\n")
8912 file.Write("\n")
8914 def WriteCmdSet(self, file):
8915 """Writes the cmd's Set function."""
8916 copy_args = self.MakeCmdArgString("_", False)
8917 file.Write(" void* Set(void* cmd%s) {\n" %
8918 self.MakeTypedCmdArgString("_", True))
8919 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
8920 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
8921 file.Write(" }\n")
8922 file.Write("\n")
8924 def WriteStruct(self, file):
8925 self.type_handler.WriteStruct(self, file)
8927 def WriteDocs(self, file):
8928 self.type_handler.WriteDocs(self, file)
8930 def WriteCmdHelper(self, file):
8931 """Writes the cmd's helper."""
8932 self.type_handler.WriteCmdHelper(self, file)
8934 def WriteServiceImplementation(self, file):
8935 """Writes the service implementation for a command."""
8936 self.type_handler.WriteServiceImplementation(self, file)
8938 def WriteServiceUnitTest(self, file, *extras):
8939 """Writes the service implementation for a command."""
8940 self.type_handler.WriteServiceUnitTest(self, file, *extras)
8942 def WriteGLES2CLibImplementation(self, file):
8943 """Writes the GLES2 C Lib Implemention."""
8944 self.type_handler.WriteGLES2CLibImplementation(self, file)
8946 def WriteGLES2InterfaceHeader(self, file):
8947 """Writes the GLES2 Interface declaration."""
8948 self.type_handler.WriteGLES2InterfaceHeader(self, file)
8950 def WriteMojoGLES2ImplHeader(self, file):
8951 """Writes the Mojo GLES2 implementation header declaration."""
8952 self.type_handler.WriteMojoGLES2ImplHeader(self, file)
8954 def WriteMojoGLES2Impl(self, file):
8955 """Writes the Mojo GLES2 implementation declaration."""
8956 self.type_handler.WriteMojoGLES2Impl(self, file)
8958 def WriteGLES2InterfaceStub(self, file):
8959 """Writes the GLES2 Interface Stub declaration."""
8960 self.type_handler.WriteGLES2InterfaceStub(self, file)
8962 def WriteGLES2InterfaceStubImpl(self, file):
8963 """Writes the GLES2 Interface Stub declaration."""
8964 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
8966 def WriteGLES2ImplementationHeader(self, file):
8967 """Writes the GLES2 Implemention declaration."""
8968 self.type_handler.WriteGLES2ImplementationHeader(self, file)
8970 def WriteGLES2Implementation(self, file):
8971 """Writes the GLES2 Implemention definition."""
8972 self.type_handler.WriteGLES2Implementation(self, file)
8974 def WriteGLES2TraceImplementationHeader(self, file):
8975 """Writes the GLES2 Trace Implemention declaration."""
8976 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
8978 def WriteGLES2TraceImplementation(self, file):
8979 """Writes the GLES2 Trace Implemention definition."""
8980 self.type_handler.WriteGLES2TraceImplementation(self, file)
8982 def WriteGLES2Header(self, file):
8983 """Writes the GLES2 Implemention unit test."""
8984 self.type_handler.WriteGLES2Header(self, file)
8986 def WriteGLES2ImplementationUnitTest(self, file):
8987 """Writes the GLES2 Implemention unit test."""
8988 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
8990 def WriteDestinationInitalizationValidation(self, file):
8991 """Writes the client side destintion initialization validation."""
8992 self.type_handler.WriteDestinationInitalizationValidation(self, file)
8994 def WriteFormatTest(self, file):
8995 """Writes the cmd's format test."""
8996 self.type_handler.WriteFormatTest(self, file)
8999 class PepperInterface(object):
9000 """A class that represents a function."""
9002 def __init__(self, info):
9003 self.name = info["name"]
9004 self.dev = info["dev"]
9006 def GetName(self):
9007 return self.name
9009 def GetInterfaceName(self):
9010 upperint = ""
9011 dev = ""
9012 if self.name:
9013 upperint = "_" + self.name.upper()
9014 if self.dev:
9015 dev = "_DEV"
9016 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
9018 def GetInterfaceString(self):
9019 dev = ""
9020 if self.dev:
9021 dev = "(Dev)"
9022 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9024 def GetStructName(self):
9025 dev = ""
9026 if self.dev:
9027 dev = "_Dev"
9028 return "PPB_OpenGLES2%s%s" % (self.name, dev)
9031 class ImmediateFunction(Function):
9032 """A class that represnets an immediate function command."""
9034 def __init__(self, func):
9035 Function.__init__(
9036 self,
9037 "%sImmediate" % func.name,
9038 func.info)
9040 def InitFunction(self):
9041 # Override args in original_args and args_for_cmds with immediate versions
9042 # of the args.
9044 new_original_args = []
9045 for arg in self.original_args:
9046 new_arg = arg.GetImmediateVersion()
9047 if new_arg:
9048 new_original_args.append(new_arg)
9049 self.original_args = new_original_args
9051 new_args_for_cmds = []
9052 for arg in self.args_for_cmds:
9053 new_arg = arg.GetImmediateVersion()
9054 if new_arg:
9055 new_args_for_cmds.append(new_arg)
9057 self.args_for_cmds = new_args_for_cmds
9059 Function.InitFunction(self)
9061 def IsImmediate(self):
9062 return True
9064 def WriteCommandDescription(self, file):
9065 """Overridden from Function"""
9066 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
9067 self.original_name)
9069 def WriteServiceImplementation(self, file):
9070 """Overridden from Function"""
9071 self.type_handler.WriteImmediateServiceImplementation(self, file)
9073 def WriteHandlerImplementation(self, file):
9074 """Overridden from Function"""
9075 self.type_handler.WriteImmediateHandlerImplementation(self, file)
9077 def WriteServiceUnitTest(self, file, *extras):
9078 """Writes the service implementation for a command."""
9079 self.type_handler.WriteImmediateServiceUnitTest(self, file, *extras)
9081 def WriteValidationCode(self, file):
9082 """Overridden from Function"""
9083 self.type_handler.WriteImmediateValidationCode(self, file)
9085 def WriteCmdArgFlag(self, file):
9086 """Overridden from Function"""
9087 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9089 def WriteCmdComputeSize(self, file):
9090 """Overridden from Function"""
9091 self.type_handler.WriteImmediateCmdComputeSize(self, file)
9093 def WriteCmdSetHeader(self, file):
9094 """Overridden from Function"""
9095 self.type_handler.WriteImmediateCmdSetHeader(self, file)
9097 def WriteCmdInit(self, file):
9098 """Overridden from Function"""
9099 self.type_handler.WriteImmediateCmdInit(self, file)
9101 def WriteCmdSet(self, file):
9102 """Overridden from Function"""
9103 self.type_handler.WriteImmediateCmdSet(self, file)
9105 def WriteCmdHelper(self, file):
9106 """Overridden from Function"""
9107 self.type_handler.WriteImmediateCmdHelper(self, file)
9109 def WriteFormatTest(self, file):
9110 """Overridden from Function"""
9111 self.type_handler.WriteImmediateFormatTest(self, file)
9114 class BucketFunction(Function):
9115 """A class that represnets a bucket version of a function command."""
9117 def __init__(self, func):
9118 Function.__init__(
9119 self,
9120 "%sBucket" % func.name,
9121 func.info)
9123 def InitFunction(self):
9124 # Override args in original_args and args_for_cmds with bucket versions
9125 # of the args.
9127 new_original_args = []
9128 for arg in self.original_args:
9129 new_arg = arg.GetBucketVersion()
9130 if new_arg:
9131 new_original_args.append(new_arg)
9132 self.original_args = new_original_args
9134 new_args_for_cmds = []
9135 for arg in self.args_for_cmds:
9136 new_arg = arg.GetBucketVersion()
9137 if new_arg:
9138 new_args_for_cmds.append(new_arg)
9140 self.args_for_cmds = new_args_for_cmds
9142 Function.InitFunction(self)
9144 def WriteCommandDescription(self, file):
9145 """Overridden from Function"""
9146 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
9147 self.original_name)
9149 def WriteServiceImplementation(self, file):
9150 """Overridden from Function"""
9151 self.type_handler.WriteBucketServiceImplementation(self, file)
9153 def WriteHandlerImplementation(self, file):
9154 """Overridden from Function"""
9155 self.type_handler.WriteBucketHandlerImplementation(self, file)
9157 def WriteServiceUnitTest(self, file, *extras):
9158 """Overridden from Function"""
9159 self.type_handler.WriteBucketServiceUnitTest(self, file, *extras)
9161 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9162 """Overridden from Function"""
9163 args = self.GetOriginalArgs()
9164 arg_string = separator.join(
9165 ["%s%s" % (prefix, arg.name[0:-10] if arg.name.endswith("_bucket_id")
9166 else arg.name) for arg in args])
9167 return super(BucketFunction, self)._MaybePrependComma(arg_string, add_comma)
9170 def CreateArg(arg_string):
9171 """Creates an Argument."""
9172 arg_parts = arg_string.split()
9173 if len(arg_parts) == 1 and arg_parts[0] == 'void':
9174 return None
9175 # Is this a pointer argument?
9176 elif arg_string.find('*') >= 0:
9177 return PointerArgument(
9178 arg_parts[-1],
9179 " ".join(arg_parts[0:-1]))
9180 # Is this a resource argument? Must come after pointer check.
9181 elif arg_parts[0].startswith('GLidBind'):
9182 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9183 elif arg_parts[0].startswith('GLidZero'):
9184 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9185 elif arg_parts[0].startswith('GLid'):
9186 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9187 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
9188 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9189 elif arg_parts[0].startswith('GLbitfield') and len(arg_parts[0]) > 10:
9190 return BitFieldArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9191 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
9192 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9193 elif arg_parts[0].startswith('GLboolean'):
9194 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9195 elif arg_parts[0].startswith('GLintUniformLocation'):
9196 return UniformLocationArgument(arg_parts[-1])
9197 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
9198 not arg_parts[0].startswith('GLintptr')):
9199 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9200 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
9201 arg_parts[0].startswith('GLintptrNotNegative')):
9202 return SizeNotNegativeArgument(arg_parts[-1],
9203 " ".join(arg_parts[0:-1]),
9204 arg_parts[0][0:-11])
9205 elif arg_parts[0].startswith('GLsize'):
9206 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9207 else:
9208 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9211 class GLGenerator(object):
9212 """A class to generate GL command buffers."""
9214 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9216 def __init__(self, verbose):
9217 self.original_functions = []
9218 self.functions = []
9219 self.verbose = verbose
9220 self.errors = 0
9221 self.pepper_interfaces = []
9222 self.interface_info = {}
9223 self.generated_cpp_filenames = []
9225 for interface in _PEPPER_INTERFACES:
9226 interface = PepperInterface(interface)
9227 self.pepper_interfaces.append(interface)
9228 self.interface_info[interface.GetName()] = interface
9230 def AddFunction(self, func):
9231 """Adds a function."""
9232 self.functions.append(func)
9234 def GetFunctionInfo(self, name):
9235 """Gets a type info for the given function name."""
9236 if name in _FUNCTION_INFO:
9237 func_info = _FUNCTION_INFO[name].copy()
9238 else:
9239 func_info = {}
9241 if not 'type' in func_info:
9242 func_info['type'] = ''
9244 return func_info
9246 def Log(self, msg):
9247 """Prints something if verbose is true."""
9248 if self.verbose:
9249 print msg
9251 def Error(self, msg):
9252 """Prints an error."""
9253 print "Error: %s" % msg
9254 self.errors += 1
9256 def WriteLicense(self, file):
9257 """Writes the license."""
9258 file.Write(_LICENSE)
9260 def WriteNamespaceOpen(self, file):
9261 """Writes the code for the namespace."""
9262 file.Write("namespace gpu {\n")
9263 file.Write("namespace gles2 {\n")
9264 file.Write("\n")
9266 def WriteNamespaceClose(self, file):
9267 """Writes the code to close the namespace."""
9268 file.Write("} // namespace gles2\n")
9269 file.Write("} // namespace gpu\n")
9270 file.Write("\n")
9272 def ParseGLH(self, filename):
9273 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9274 f = open(filename, "r")
9275 functions = f.read()
9276 f.close()
9277 for line in functions.splitlines():
9278 match = self._function_re.match(line)
9279 if match:
9280 func_name = match.group(2)[2:]
9281 func_info = self.GetFunctionInfo(func_name)
9282 if func_info['type'] == 'Noop':
9283 continue
9285 parsed_func_info = {
9286 'original_name': func_name,
9287 'original_args': match.group(3),
9288 'return_type': match.group(1).strip(),
9291 for k in parsed_func_info.keys():
9292 if not k in func_info:
9293 func_info[k] = parsed_func_info[k]
9295 f = Function(func_name, func_info)
9296 self.original_functions.append(f)
9298 #for arg in f.GetOriginalArgs():
9299 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9300 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9302 gen_cmd = f.GetInfo('gen_cmd')
9303 if gen_cmd == True or gen_cmd == None:
9304 if f.type_handler.NeedsDataTransferFunction(f):
9305 methods = f.GetDataTransferMethods()
9306 if 'immediate' in methods:
9307 self.AddFunction(ImmediateFunction(f))
9308 if 'bucket' in methods:
9309 self.AddFunction(BucketFunction(f))
9310 if 'shm' in methods:
9311 self.AddFunction(f)
9312 else:
9313 self.AddFunction(f)
9315 self.Log("Auto Generated Functions : %d" %
9316 len([f for f in self.functions if f.can_auto_generate or
9317 (not f.IsType('') and not f.IsType('Custom') and
9318 not f.IsType('Todo'))]))
9320 funcs = [f for f in self.functions if not f.can_auto_generate and
9321 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
9322 self.Log("Non Auto Generated Functions: %d" % len(funcs))
9324 for f in funcs:
9325 self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
9327 def WriteCommandIds(self, filename):
9328 """Writes the command buffer format"""
9329 file = CHeaderWriter(filename)
9330 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
9331 id = 256
9332 for func in self.functions:
9333 file.Write(" %-60s /* %d */ \\\n" %
9334 ("OP(%s)" % func.name, id))
9335 id += 1
9336 file.Write("\n")
9338 file.Write("enum CommandId {\n")
9339 file.Write(" kStartPoint = cmd::kLastCommonId, "
9340 "// All GLES2 commands start after this.\n")
9341 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
9342 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9343 file.Write("#undef GLES2_CMD_OP\n")
9344 file.Write(" kNumCommands\n")
9345 file.Write("};\n")
9346 file.Write("\n")
9347 file.Close()
9348 self.generated_cpp_filenames.append(file.filename)
9350 def WriteFormat(self, filename):
9351 """Writes the command buffer format"""
9352 file = CHeaderWriter(filename)
9353 # Forward declaration of a few enums used in constant argument
9354 # to avoid including GL header files.
9355 enum_defines = {
9356 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9357 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9359 file.Write('\n')
9360 for enum in enum_defines:
9361 file.Write("#define %s %s\n" % (enum, enum_defines[enum]))
9362 file.Write('\n')
9363 for func in self.functions:
9364 if True:
9365 #gen_cmd = func.GetInfo('gen_cmd')
9366 #if gen_cmd == True or gen_cmd == None:
9367 func.WriteStruct(file)
9368 file.Write("\n")
9369 file.Close()
9370 self.generated_cpp_filenames.append(file.filename)
9372 def WriteDocs(self, filename):
9373 """Writes the command buffer doc version of the commands"""
9374 file = CWriter(filename)
9375 for func in self.functions:
9376 if True:
9377 #gen_cmd = func.GetInfo('gen_cmd')
9378 #if gen_cmd == True or gen_cmd == None:
9379 func.WriteDocs(file)
9380 file.Write("\n")
9381 file.Close()
9382 self.generated_cpp_filenames.append(file.filename)
9384 def WriteFormatTest(self, filename):
9385 """Writes the command buffer format test."""
9386 file = CHeaderWriter(
9387 filename,
9388 "// This file contains unit tests for gles2 commmands\n"
9389 "// It is included by gles2_cmd_format_test.cc\n"
9390 "\n")
9392 for func in self.functions:
9393 if True:
9394 #gen_cmd = func.GetInfo('gen_cmd')
9395 #if gen_cmd == True or gen_cmd == None:
9396 func.WriteFormatTest(file)
9398 file.Close()
9399 self.generated_cpp_filenames.append(file.filename)
9401 def WriteCmdHelperHeader(self, filename):
9402 """Writes the gles2 command helper."""
9403 file = CHeaderWriter(filename)
9405 for func in self.functions:
9406 if True:
9407 #gen_cmd = func.GetInfo('gen_cmd')
9408 #if gen_cmd == True or gen_cmd == None:
9409 func.WriteCmdHelper(file)
9411 file.Close()
9412 self.generated_cpp_filenames.append(file.filename)
9414 def WriteServiceContextStateHeader(self, filename):
9415 """Writes the service context state header."""
9416 file = CHeaderWriter(
9417 filename,
9418 "// It is included by context_state.h\n")
9419 file.Write("struct EnableFlags {\n")
9420 file.Write(" EnableFlags();\n")
9421 for capability in _CAPABILITY_FLAGS:
9422 file.Write(" bool %s;\n" % capability['name'])
9423 file.Write(" bool cached_%s;\n" % capability['name'])
9424 file.Write("};\n\n")
9426 for state_name in sorted(_STATES.keys()):
9427 state = _STATES[state_name]
9428 for item in state['states']:
9429 if isinstance(item['default'], list):
9430 file.Write("%s %s[%d];\n" % (item['type'], item['name'],
9431 len(item['default'])))
9432 else:
9433 file.Write("%s %s;\n" % (item['type'], item['name']))
9435 if item.get('cached', False):
9436 if isinstance(item['default'], list):
9437 file.Write("%s cached_%s[%d];\n" % (item['type'], item['name'],
9438 len(item['default'])))
9439 else:
9440 file.Write("%s cached_%s;\n" % (item['type'], item['name']))
9442 file.Write("\n")
9444 file.Write("""
9445 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9446 switch (cap) {
9447 """)
9448 for capability in _CAPABILITY_FLAGS:
9449 file.Write("""\
9450 case GL_%s:
9451 """ % capability['name'].upper())
9452 file.Write("""\
9453 if (enable_flags.cached_%(name)s == enable &&
9454 !ignore_cached_state)
9455 return;
9456 enable_flags.cached_%(name)s = enable;
9457 break;
9458 """ % capability)
9460 file.Write("""\
9461 default:
9462 NOTREACHED();
9463 return;
9465 if (enable)
9466 glEnable(cap);
9467 else
9468 glDisable(cap);
9470 """)
9472 file.Close()
9473 self.generated_cpp_filenames.append(file.filename)
9475 def WriteClientContextStateHeader(self, filename):
9476 """Writes the client context state header."""
9477 file = CHeaderWriter(
9478 filename,
9479 "// It is included by client_context_state.h\n")
9480 file.Write("struct EnableFlags {\n")
9481 file.Write(" EnableFlags();\n")
9482 for capability in _CAPABILITY_FLAGS:
9483 file.Write(" bool %s;\n" % capability['name'])
9484 file.Write("};\n\n")
9486 file.Close()
9487 self.generated_cpp_filenames.append(file.filename)
9489 def WriteContextStateGetters(self, file, class_name):
9490 """Writes the state getters."""
9491 for gl_type in ["GLint", "GLfloat"]:
9492 file.Write("""
9493 bool %s::GetStateAs%s(
9494 GLenum pname, %s* params, GLsizei* num_written) const {
9495 switch (pname) {
9496 """ % (class_name, gl_type, gl_type))
9497 for state_name in sorted(_STATES.keys()):
9498 state = _STATES[state_name]
9499 if 'enum' in state:
9500 file.Write(" case %s:\n" % state['enum'])
9501 file.Write(" *num_written = %d;\n" % len(state['states']))
9502 file.Write(" if (params) {\n")
9503 for ndx,item in enumerate(state['states']):
9504 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
9505 (ndx, gl_type, item['name']))
9506 file.Write(" }\n")
9507 file.Write(" return true;\n")
9508 else:
9509 for item in state['states']:
9510 file.Write(" case %s:\n" % item['enum'])
9511 if isinstance(item['default'], list):
9512 item_len = len(item['default'])
9513 file.Write(" *num_written = %d;\n" % item_len)
9514 file.Write(" if (params) {\n")
9515 if item['type'] == gl_type:
9516 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9517 (item['name'], item['type'], item_len))
9518 else:
9519 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
9520 item_len)
9521 file.Write(" params[i] = %s;\n" %
9522 (GetGLGetTypeConversion(gl_type, item['type'],
9523 "%s[i]" % item['name'])))
9524 file.Write(" }\n");
9525 else:
9526 file.Write(" *num_written = 1;\n")
9527 file.Write(" if (params) {\n")
9528 file.Write(" params[0] = %s;\n" %
9529 (GetGLGetTypeConversion(gl_type, item['type'],
9530 item['name'])))
9531 file.Write(" }\n")
9532 file.Write(" return true;\n")
9533 for capability in _CAPABILITY_FLAGS:
9534 file.Write(" case GL_%s:\n" % capability['name'].upper())
9535 file.Write(" *num_written = 1;\n")
9536 file.Write(" if (params) {\n")
9537 file.Write(
9538 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9539 (gl_type, capability['name']))
9540 file.Write(" }\n")
9541 file.Write(" return true;\n")
9542 file.Write(""" default:
9543 return false;
9546 """)
9548 def WriteServiceContextStateImpl(self, filename):
9549 """Writes the context state service implementation."""
9550 file = CHeaderWriter(
9551 filename,
9552 "// It is included by context_state.cc\n")
9553 code = []
9554 for capability in _CAPABILITY_FLAGS:
9555 code.append("%s(%s)" %
9556 (capability['name'],
9557 ('false', 'true')['default' in capability]))
9558 code.append("cached_%s(%s)" %
9559 (capability['name'],
9560 ('false', 'true')['default' in capability]))
9561 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9562 ",\n ".join(code))
9563 file.Write("\n")
9565 file.Write("void ContextState::Initialize() {\n")
9566 for state_name in sorted(_STATES.keys()):
9567 state = _STATES[state_name]
9568 for item in state['states']:
9569 if isinstance(item['default'], list):
9570 for ndx, value in enumerate(item['default']):
9571 file.Write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
9572 else:
9573 file.Write(" %s = %s;\n" % (item['name'], item['default']))
9574 if item.get('cached', False):
9575 if isinstance(item['default'], list):
9576 for ndx, value in enumerate(item['default']):
9577 file.Write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
9578 else:
9579 file.Write(" cached_%s = %s;\n" % (item['name'], item['default']))
9580 file.Write("}\n")
9582 file.Write("""
9583 void ContextState::InitCapabilities(const ContextState* prev_state) const {
9584 """)
9585 def WriteCapabilities(test_prev, es3_caps):
9586 for capability in _CAPABILITY_FLAGS:
9587 capability_name = capability['name']
9588 capability_es3 = 'es3' in capability and capability['es3'] == True
9589 if capability_es3 and not es3_caps or not capability_es3 and es3_caps:
9590 continue
9591 if test_prev:
9592 file.Write(""" if (prev_state->enable_flags.cached_%s !=
9593 enable_flags.cached_%s) {\n""" %
9594 (capability_name, capability_name))
9595 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
9596 (capability_name.upper(), capability_name))
9597 if test_prev:
9598 file.Write(" }")
9600 file.Write(" if (prev_state) {")
9601 WriteCapabilities(True, False)
9602 file.Write(" if (feature_info_->IsES3Capable()) {\n")
9603 WriteCapabilities(True, True)
9604 file.Write(" }\n")
9605 file.Write(" } else {")
9606 WriteCapabilities(False, False)
9607 file.Write(" if (feature_info_->IsES3Capable()) {\n")
9608 WriteCapabilities(False, True)
9609 file.Write(" }\n")
9610 file.Write(" }")
9612 file.Write("""}
9614 void ContextState::InitState(const ContextState *prev_state) const {
9615 """)
9617 def WriteStates(test_prev):
9618 # We need to sort the keys so the expectations match
9619 for state_name in sorted(_STATES.keys()):
9620 state = _STATES[state_name]
9621 if state['type'] == 'FrontBack':
9622 num_states = len(state['states'])
9623 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
9624 if test_prev:
9625 file.Write(" if (")
9626 args = []
9627 for place, item in enumerate(group):
9628 item_name = CachedStateName(item)
9629 args.append('%s' % item_name)
9630 if test_prev:
9631 if place > 0:
9632 file.Write(' ||\n')
9633 file.Write("(%s != prev_state->%s)" % (item_name, item_name))
9634 if test_prev:
9635 file.Write(")\n")
9636 file.Write(
9637 " gl%s(%s, %s);\n" %
9638 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
9639 elif state['type'] == 'NamedParameter':
9640 for item in state['states']:
9641 item_name = CachedStateName(item)
9643 if 'extension_flag' in item:
9644 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
9645 item['extension_flag'])
9646 if test_prev:
9647 if isinstance(item['default'], list):
9648 file.Write(" if (memcmp(prev_state->%s, %s, "
9649 "sizeof(%s) * %d)) {\n" %
9650 (item_name, item_name, item['type'],
9651 len(item['default'])))
9652 else:
9653 file.Write(" if (prev_state->%s != %s) {\n " %
9654 (item_name, item_name))
9655 file.Write(" gl%s(%s, %s);\n" %
9656 (state['func'],
9657 (item['enum_set']
9658 if 'enum_set' in item else item['enum']),
9659 item['name']))
9660 if test_prev:
9661 if 'extension_flag' in item:
9662 file.Write(" ")
9663 file.Write(" }")
9664 if 'extension_flag' in item:
9665 file.Write(" }")
9666 else:
9667 if 'extension_flag' in state:
9668 file.Write(" if (feature_info_->feature_flags().%s)\n " %
9669 state['extension_flag'])
9670 if test_prev:
9671 file.Write(" if (")
9672 args = []
9673 for place, item in enumerate(state['states']):
9674 item_name = CachedStateName(item)
9675 args.append('%s' % item_name)
9676 if test_prev:
9677 if place > 0:
9678 file.Write(' ||\n')
9679 file.Write("(%s != prev_state->%s)" %
9680 (item_name, item_name))
9681 if test_prev:
9682 file.Write(" )\n")
9683 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
9685 file.Write(" if (prev_state) {")
9686 WriteStates(True)
9687 file.Write(" } else {")
9688 WriteStates(False)
9689 file.Write(" }")
9690 file.Write("}\n")
9692 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
9693 switch (cap) {
9694 """)
9695 for capability in _CAPABILITY_FLAGS:
9696 file.Write(" case GL_%s:\n" % capability['name'].upper())
9697 file.Write(" return enable_flags.%s;\n" % capability['name'])
9698 file.Write(""" default:
9699 NOTREACHED();
9700 return false;
9703 """)
9705 self.WriteContextStateGetters(file, "ContextState")
9706 file.Close()
9707 self.generated_cpp_filenames.append(file.filename)
9709 def WriteClientContextStateImpl(self, filename):
9710 """Writes the context state client side implementation."""
9711 file = CHeaderWriter(
9712 filename,
9713 "// It is included by client_context_state.cc\n")
9714 code = []
9715 for capability in _CAPABILITY_FLAGS:
9716 code.append("%s(%s)" %
9717 (capability['name'],
9718 ('false', 'true')['default' in capability]))
9719 file.Write(
9720 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9721 ",\n ".join(code))
9722 file.Write("\n")
9724 file.Write("""
9725 bool ClientContextState::SetCapabilityState(
9726 GLenum cap, bool enabled, bool* changed) {
9727 *changed = false;
9728 switch (cap) {
9729 """)
9730 for capability in _CAPABILITY_FLAGS:
9731 file.Write(" case GL_%s:\n" % capability['name'].upper())
9732 file.Write(""" if (enable_flags.%(name)s != enabled) {
9733 *changed = true;
9734 enable_flags.%(name)s = enabled;
9736 return true;
9737 """ % capability)
9738 file.Write(""" default:
9739 return false;
9742 """)
9743 file.Write("""bool ClientContextState::GetEnabled(
9744 GLenum cap, bool* enabled) const {
9745 switch (cap) {
9746 """)
9747 for capability in _CAPABILITY_FLAGS:
9748 file.Write(" case GL_%s:\n" % capability['name'].upper())
9749 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
9750 file.Write(" return true;\n")
9751 file.Write(""" default:
9752 return false;
9755 """)
9756 file.Close()
9757 self.generated_cpp_filenames.append(file.filename)
9759 def WriteServiceImplementation(self, filename):
9760 """Writes the service decorder implementation."""
9761 file = CHeaderWriter(
9762 filename,
9763 "// It is included by gles2_cmd_decoder.cc\n")
9765 for func in self.functions:
9766 if True:
9767 #gen_cmd = func.GetInfo('gen_cmd')
9768 #if gen_cmd == True or gen_cmd == None:
9769 func.WriteServiceImplementation(file)
9771 file.Write("""
9772 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
9773 switch (cap) {
9774 """)
9775 for capability in _CAPABILITY_FLAGS:
9776 file.Write(" case GL_%s:\n" % capability['name'].upper())
9777 if 'state_flag' in capability:
9779 file.Write("""\
9780 state_.enable_flags.%(name)s = enabled;
9781 if (state_.enable_flags.cached_%(name)s != enabled
9782 || state_.ignore_cached_state) {
9783 %(state_flag)s = true;
9785 return false;
9786 """ % capability)
9787 else:
9788 file.Write("""\
9789 state_.enable_flags.%(name)s = enabled;
9790 if (state_.enable_flags.cached_%(name)s != enabled
9791 || state_.ignore_cached_state) {
9792 state_.enable_flags.cached_%(name)s = enabled;
9793 return true;
9795 return false;
9796 """ % capability)
9797 file.Write(""" default:
9798 NOTREACHED();
9799 return false;
9802 """)
9803 file.Close()
9804 self.generated_cpp_filenames.append(file.filename)
9806 def WriteServiceUnitTests(self, filename):
9807 """Writes the service decorder unit tests."""
9808 num_tests = len(self.functions)
9809 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
9810 count = 0
9811 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
9812 count += 1
9813 name = filename % count
9814 file = CHeaderWriter(
9815 name,
9816 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
9817 test_name = 'GLES2DecoderTest%d' % count
9818 end = test_num + FUNCTIONS_PER_FILE
9819 if end > num_tests:
9820 end = num_tests
9821 for idx in range(test_num, end):
9822 func = self.functions[idx]
9824 # Do any filtering of the functions here, so that the functions
9825 # will not move between the numbered files if filtering properties
9826 # are changed.
9827 if func.GetInfo('extension_flag'):
9828 continue
9830 if True:
9831 #gen_cmd = func.GetInfo('gen_cmd')
9832 #if gen_cmd == True or gen_cmd == None:
9833 if func.GetInfo('unit_test') == False:
9834 file.Write("// TODO(gman): %s\n" % func.name)
9835 else:
9836 func.WriteServiceUnitTest(file, {
9837 'test_name': test_name
9839 file.Close()
9840 self.generated_cpp_filenames.append(file.filename)
9841 file = CHeaderWriter(
9842 filename % 0,
9843 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
9844 file.Write(
9845 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations(
9846 bool es3_capable) {""")
9847 for capability in _CAPABILITY_FLAGS:
9848 capability_es3 = 'es3' in capability and capability['es3'] == True
9849 if not capability_es3:
9850 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
9851 (capability['name'].upper(),
9852 ('false', 'true')['default' in capability]))
9854 file.Write(" if (es3_capable) {")
9855 for capability in _CAPABILITY_FLAGS:
9856 capability_es3 = 'es3' in capability and capability['es3'] == True
9857 if capability_es3:
9858 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
9859 (capability['name'].upper(),
9860 ('false', 'true')['default' in capability]))
9861 file.Write(""" }
9864 void GLES2DecoderTestBase::SetupInitStateExpectations() {
9865 """)
9867 # We need to sort the keys so the expectations match
9868 for state_name in sorted(_STATES.keys()):
9869 state = _STATES[state_name]
9870 if state['type'] == 'FrontBack':
9871 num_states = len(state['states'])
9872 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
9873 args = []
9874 for item in group:
9875 if 'expected' in item:
9876 args.append(item['expected'])
9877 else:
9878 args.append(item['default'])
9879 file.Write(
9880 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
9881 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
9882 file.Write(" .Times(1)\n")
9883 file.Write(" .RetiresOnSaturation();\n")
9884 elif state['type'] == 'NamedParameter':
9885 for item in state['states']:
9886 if 'extension_flag' in item:
9887 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
9888 item['extension_flag'])
9889 file.Write(" ")
9890 expect_value = item['default']
9891 if isinstance(expect_value, list):
9892 # TODO: Currently we do not check array values.
9893 expect_value = "_"
9895 file.Write(
9896 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
9897 (state['func'],
9898 (item['enum_set']
9899 if 'enum_set' in item else item['enum']),
9900 expect_value))
9901 file.Write(" .Times(1)\n")
9902 file.Write(" .RetiresOnSaturation();\n")
9903 if 'extension_flag' in item:
9904 file.Write(" }\n")
9905 else:
9906 if 'extension_flag' in state:
9907 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
9908 state['extension_flag'])
9909 file.Write(" ")
9910 args = []
9911 for item in state['states']:
9912 if 'expected' in item:
9913 args.append(item['expected'])
9914 else:
9915 args.append(item['default'])
9916 # TODO: Currently we do not check array values.
9917 args = ["_" if isinstance(arg, list) else arg for arg in args]
9918 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
9919 (state['func'], ", ".join(args)))
9920 file.Write(" .Times(1)\n")
9921 file.Write(" .RetiresOnSaturation();\n")
9922 if 'extension_flag' in state:
9923 file.Write(" }\n")
9924 file.Write("""}
9925 """)
9926 file.Close()
9927 self.generated_cpp_filenames.append(file.filename)
9929 def WriteServiceUnitTestsForExtensions(self, filename):
9930 """Writes the service decorder unit tests for functions with extension_flag.
9932 The functions are special in that they need a specific unit test
9933 baseclass to turn on the extension.
9935 functions = [f for f in self.functions if f.GetInfo('extension_flag')]
9936 file = CHeaderWriter(
9937 filename,
9938 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
9939 for func in functions:
9940 if True:
9941 if func.GetInfo('unit_test') == False:
9942 file.Write("// TODO(gman): %s\n" % func.name)
9943 else:
9944 extension = ToCamelCase(
9945 ToGLExtensionString(func.GetInfo('extension_flag')))
9946 func.WriteServiceUnitTest(file, {
9947 'test_name': 'GLES2DecoderTestWith%s' % extension
9950 file.Close()
9951 self.generated_cpp_filenames.append(file.filename)
9953 def WriteGLES2Header(self, filename):
9954 """Writes the GLES2 header."""
9955 file = CHeaderWriter(
9956 filename,
9957 "// This file contains Chromium-specific GLES2 declarations.\n\n")
9959 for func in self.original_functions:
9960 func.WriteGLES2Header(file)
9962 file.Write("\n")
9963 file.Close()
9964 self.generated_cpp_filenames.append(file.filename)
9966 def WriteGLES2CLibImplementation(self, filename):
9967 """Writes the GLES2 c lib implementation."""
9968 file = CHeaderWriter(
9969 filename,
9970 "// These functions emulate GLES2 over command buffers.\n")
9972 for func in self.original_functions:
9973 func.WriteGLES2CLibImplementation(file)
9975 file.Write("""
9976 namespace gles2 {
9978 extern const NameToFunc g_gles2_function_table[] = {
9979 """)
9980 for func in self.original_functions:
9981 file.Write(
9982 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
9983 (func.name, func.name))
9984 file.Write(""" { NULL, NULL, },
9987 } // namespace gles2
9988 """)
9989 file.Close()
9990 self.generated_cpp_filenames.append(file.filename)
9992 def WriteGLES2InterfaceHeader(self, filename):
9993 """Writes the GLES2 interface header."""
9994 file = CHeaderWriter(
9995 filename,
9996 "// This file is included by gles2_interface.h to declare the\n"
9997 "// GL api functions.\n")
9998 for func in self.original_functions:
9999 func.WriteGLES2InterfaceHeader(file)
10000 file.Close()
10001 self.generated_cpp_filenames.append(file.filename)
10003 def WriteMojoGLES2ImplHeader(self, filename):
10004 """Writes the Mojo GLES2 implementation header."""
10005 file = CHeaderWriter(
10006 filename,
10007 "// This file is included by gles2_interface.h to declare the\n"
10008 "// GL api functions.\n")
10010 code = """
10011 #include "gpu/command_buffer/client/gles2_interface.h"
10012 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10014 namespace mojo {
10016 class MojoGLES2Impl : public gpu::gles2::GLES2Interface {
10017 public:
10018 explicit MojoGLES2Impl(MojoGLES2Context context) {
10019 context_ = context;
10021 ~MojoGLES2Impl() override {}
10023 file.Write(code);
10024 for func in self.original_functions:
10025 func.WriteMojoGLES2ImplHeader(file)
10026 code = """
10027 private:
10028 MojoGLES2Context context_;
10031 } // namespace mojo
10033 file.Write(code);
10034 file.Close()
10035 self.generated_cpp_filenames.append(file.filename)
10037 def WriteMojoGLES2Impl(self, filename):
10038 """Writes the Mojo GLES2 implementation."""
10039 file = CWriter(filename)
10040 file.Write(_LICENSE)
10041 file.Write(_DO_NOT_EDIT_WARNING)
10043 code = """
10044 #include "mojo/gpu/mojo_gles2_impl_autogen.h"
10046 #include "base/logging.h"
10047 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_miscellaneous.h"
10048 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sub_image.h"
10049 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_sync_point.h"
10050 #include "third_party/mojo/src/mojo/public/c/gles2/chromium_texture_mailbox.h"
10051 #include "third_party/mojo/src/mojo/public/c/gles2/gles2.h"
10052 #include "third_party/mojo/src/mojo/public/c/gles2/occlusion_query_ext.h"
10054 namespace mojo {
10057 file.Write(code);
10058 for func in self.original_functions:
10059 func.WriteMojoGLES2Impl(file)
10060 code = """
10062 } // namespace mojo
10064 file.Write(code);
10065 file.Close()
10066 self.generated_cpp_filenames.append(file.filename)
10068 def WriteGLES2InterfaceStub(self, filename):
10069 """Writes the GLES2 interface stub header."""
10070 file = CHeaderWriter(
10071 filename,
10072 "// This file is included by gles2_interface_stub.h.\n")
10073 for func in self.original_functions:
10074 func.WriteGLES2InterfaceStub(file)
10075 file.Close()
10076 self.generated_cpp_filenames.append(file.filename)
10078 def WriteGLES2InterfaceStubImpl(self, filename):
10079 """Writes the GLES2 interface header."""
10080 file = CHeaderWriter(
10081 filename,
10082 "// This file is included by gles2_interface_stub.cc.\n")
10083 for func in self.original_functions:
10084 func.WriteGLES2InterfaceStubImpl(file)
10085 file.Close()
10086 self.generated_cpp_filenames.append(file.filename)
10088 def WriteGLES2ImplementationHeader(self, filename):
10089 """Writes the GLES2 Implementation header."""
10090 file = CHeaderWriter(
10091 filename,
10092 "// This file is included by gles2_implementation.h to declare the\n"
10093 "// GL api functions.\n")
10094 for func in self.original_functions:
10095 func.WriteGLES2ImplementationHeader(file)
10096 file.Close()
10097 self.generated_cpp_filenames.append(file.filename)
10099 def WriteGLES2Implementation(self, filename):
10100 """Writes the GLES2 Implementation."""
10101 file = CHeaderWriter(
10102 filename,
10103 "// This file is included by gles2_implementation.cc to define the\n"
10104 "// GL api functions.\n")
10105 for func in self.original_functions:
10106 func.WriteGLES2Implementation(file)
10107 file.Close()
10108 self.generated_cpp_filenames.append(file.filename)
10110 def WriteGLES2TraceImplementationHeader(self, filename):
10111 """Writes the GLES2 Trace Implementation header."""
10112 file = CHeaderWriter(
10113 filename,
10114 "// This file is included by gles2_trace_implementation.h\n")
10115 for func in self.original_functions:
10116 func.WriteGLES2TraceImplementationHeader(file)
10117 file.Close()
10118 self.generated_cpp_filenames.append(file.filename)
10120 def WriteGLES2TraceImplementation(self, filename):
10121 """Writes the GLES2 Trace Implementation."""
10122 file = CHeaderWriter(
10123 filename,
10124 "// This file is included by gles2_trace_implementation.cc\n")
10125 for func in self.original_functions:
10126 func.WriteGLES2TraceImplementation(file)
10127 file.Close()
10128 self.generated_cpp_filenames.append(file.filename)
10130 def WriteGLES2ImplementationUnitTests(self, filename):
10131 """Writes the GLES2 helper header."""
10132 file = CHeaderWriter(
10133 filename,
10134 "// This file is included by gles2_implementation.h to declare the\n"
10135 "// GL api functions.\n")
10136 for func in self.original_functions:
10137 func.WriteGLES2ImplementationUnitTest(file)
10138 file.Close()
10139 self.generated_cpp_filenames.append(file.filename)
10141 def WriteServiceUtilsHeader(self, filename):
10142 """Writes the gles2 auto generated utility header."""
10143 file = CHeaderWriter(filename)
10144 for name in sorted(_NAMED_TYPE_INFO.keys()):
10145 named_type = NamedType(_NAMED_TYPE_INFO[name])
10146 if named_type.IsConstant():
10147 continue
10148 file.Write("ValueValidator<%s> %s;\n" %
10149 (named_type.GetType(), ToUnderscore(name)))
10150 file.Write("\n")
10151 file.Close()
10152 self.generated_cpp_filenames.append(file.filename)
10154 def WriteServiceUtilsImplementation(self, filename):
10155 """Writes the gles2 auto generated utility implementation."""
10156 file = CHeaderWriter(filename)
10157 names = sorted(_NAMED_TYPE_INFO.keys())
10158 for name in names:
10159 named_type = NamedType(_NAMED_TYPE_INFO[name])
10160 if named_type.IsConstant():
10161 continue
10162 if named_type.GetValidValues():
10163 file.Write("static const %s valid_%s_table[] = {\n" %
10164 (named_type.GetType(), ToUnderscore(name)))
10165 for value in named_type.GetValidValues():
10166 file.Write(" %s,\n" % value)
10167 file.Write("};\n")
10168 file.Write("\n")
10169 if named_type.GetValidValuesES3():
10170 file.Write("static const %s valid_%s_table_es3[] = {\n" %
10171 (named_type.GetType(), ToUnderscore(name)))
10172 for value in named_type.GetValidValuesES3():
10173 file.Write(" %s,\n" % value)
10174 file.Write("};\n")
10175 file.Write("\n")
10176 if named_type.GetDeprecatedValuesES3():
10177 file.Write("static const %s deprecated_%s_table_es3[] = {\n" %
10178 (named_type.GetType(), ToUnderscore(name)))
10179 for value in named_type.GetDeprecatedValuesES3():
10180 file.Write(" %s,\n" % value)
10181 file.Write("};\n")
10182 file.Write("\n")
10183 file.Write("Validators::Validators()")
10184 pre = ' : '
10185 for count, name in enumerate(names):
10186 named_type = NamedType(_NAMED_TYPE_INFO[name])
10187 if named_type.IsConstant():
10188 continue
10189 if named_type.GetValidValues():
10190 code = """%(pre)s%(name)s(
10191 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10192 else:
10193 code = "%(pre)s%(name)s()"
10194 file.Write(code % {
10195 'name': ToUnderscore(name),
10196 'pre': pre,
10198 pre = ',\n '
10199 file.Write(" {\n");
10200 file.Write("}\n\n");
10202 file.Write("void Validators::UpdateValuesES3() {\n")
10203 for name in names:
10204 named_type = NamedType(_NAMED_TYPE_INFO[name])
10205 if named_type.GetDeprecatedValuesES3():
10206 code = """ %(name)s.RemoveValues(
10207 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10209 file.Write(code % {
10210 'name': ToUnderscore(name),
10212 if named_type.GetValidValuesES3():
10213 code = """ %(name)s.AddValues(
10214 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10216 file.Write(code % {
10217 'name': ToUnderscore(name),
10219 file.Write("}\n\n");
10220 file.Close()
10221 self.generated_cpp_filenames.append(file.filename)
10223 def WriteCommonUtilsHeader(self, filename):
10224 """Writes the gles2 common utility header."""
10225 file = CHeaderWriter(filename)
10226 type_infos = sorted(_NAMED_TYPE_INFO.keys())
10227 for type_info in type_infos:
10228 if _NAMED_TYPE_INFO[type_info]['type'] == 'GLenum':
10229 file.Write("static std::string GetString%s(uint32_t value);\n" %
10230 type_info)
10231 file.Write("\n")
10232 file.Close()
10233 self.generated_cpp_filenames.append(file.filename)
10235 def WriteCommonUtilsImpl(self, filename):
10236 """Writes the gles2 common utility header."""
10237 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10238 dict = {}
10239 for fname in ['third_party/khronos/GLES2/gl2.h',
10240 'third_party/khronos/GLES2/gl2ext.h',
10241 'third_party/khronos/GLES3/gl3.h',
10242 'gpu/GLES2/gl2chromium.h',
10243 'gpu/GLES2/gl2extchromium.h']:
10244 lines = open(fname).readlines()
10245 for line in lines:
10246 m = enum_re.match(line)
10247 if m:
10248 name = m.group(1)
10249 value = m.group(2)
10250 if len(value) <= 10:
10251 if not value in dict:
10252 dict[value] = name
10253 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10254 elif dict[value] != name and (name.endswith('_CHROMIUM') or
10255 dict[value].endswith('_CHROMIUM')):
10256 self.Error("code collision: %s and %s have the same code %s" %
10257 (dict[value], name, value))
10259 file = CHeaderWriter(filename)
10260 file.Write("static const GLES2Util::EnumToString "
10261 "enum_to_string_table[] = {\n")
10262 for value in dict:
10263 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
10264 file.Write("""};
10266 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10267 enum_to_string_table;
10268 const size_t GLES2Util::enum_to_string_table_len_ =
10269 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10271 """)
10273 enums = sorted(_NAMED_TYPE_INFO.keys())
10274 for enum in enums:
10275 if _NAMED_TYPE_INFO[enum]['type'] == 'GLenum':
10276 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10277 enum)
10278 valid_list = _NAMED_TYPE_INFO[enum]['valid']
10279 if 'valid_es3' in _NAMED_TYPE_INFO[enum]:
10280 valid_list = valid_list + _NAMED_TYPE_INFO[enum]['valid_es3']
10281 assert len(valid_list) == len(set(valid_list))
10282 if len(valid_list) > 0:
10283 file.Write(" static const EnumToString string_table[] = {\n")
10284 for value in valid_list:
10285 file.Write(' { %s, "%s" },\n' % (value, value))
10286 file.Write(""" };
10287 return GLES2Util::GetQualifiedEnumString(
10288 string_table, arraysize(string_table), value);
10291 """)
10292 else:
10293 file.Write(""" return GLES2Util::GetQualifiedEnumString(
10294 NULL, 0, value);
10297 """)
10298 file.Close()
10299 self.generated_cpp_filenames.append(file.filename)
10301 def WritePepperGLES2Interface(self, filename, dev):
10302 """Writes the Pepper OpenGLES interface definition."""
10303 file = CWriter(filename)
10304 file.Write(_LICENSE)
10305 file.Write(_DO_NOT_EDIT_WARNING)
10307 file.Write("label Chrome {\n")
10308 file.Write(" M39 = 1.0\n")
10309 file.Write("};\n\n")
10311 if not dev:
10312 # Declare GL types.
10313 file.Write("[version=1.0]\n")
10314 file.Write("describe {\n")
10315 for gltype in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10316 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10317 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10318 'GLubyte', 'GLuint', 'GLushort']:
10319 file.Write(" %s;\n" % gltype)
10320 file.Write(" %s_ptr_t;\n" % gltype)
10321 file.Write("};\n\n")
10323 # C level typedefs.
10324 file.Write("#inline c\n")
10325 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
10326 if dev:
10327 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10328 else:
10329 file.Write("\n#ifndef __gl2_h_\n")
10330 for (k, v) in _GL_TYPES.iteritems():
10331 file.Write("typedef %s %s;\n" % (v, k))
10332 file.Write("#ifdef _WIN64\n")
10333 for (k, v) in _GL_TYPES_64.iteritems():
10334 file.Write("typedef %s %s;\n" % (v, k))
10335 file.Write("#else\n")
10336 for (k, v) in _GL_TYPES_32.iteritems():
10337 file.Write("typedef %s %s;\n" % (v, k))
10338 file.Write("#endif // _WIN64\n")
10339 file.Write("#endif // __gl2_h_\n\n")
10340 file.Write("#endinl\n")
10342 for interface in self.pepper_interfaces:
10343 if interface.dev != dev:
10344 continue
10345 # Historically, we provide OpenGLES2 interfaces with struct
10346 # namespace. Not to break code which uses the interface as
10347 # "struct OpenGLES2", we put it in struct namespace.
10348 file.Write('\n[macro="%s", force_struct_namespace]\n' %
10349 interface.GetInterfaceName())
10350 file.Write("interface %s {\n" % interface.GetStructName())
10351 for func in self.original_functions:
10352 if not func.InPepperInterface(interface):
10353 continue
10355 ret_type = func.MapCTypeToPepperIdlType(func.return_type,
10356 is_for_return_type=True)
10357 func_prefix = " %s %s(" % (ret_type, func.GetPepperName())
10358 file.Write(func_prefix)
10359 file.Write("[in] PP_Resource context")
10360 for arg in func.MakeTypedPepperIdlArgStrings():
10361 file.Write(",\n" + " " * len(func_prefix) + arg)
10362 file.Write(");\n")
10363 file.Write("};\n\n")
10366 file.Close()
10368 def WritePepperGLES2Implementation(self, filename):
10369 """Writes the Pepper OpenGLES interface implementation."""
10371 file = CWriter(filename)
10372 file.Write(_LICENSE)
10373 file.Write(_DO_NOT_EDIT_WARNING)
10375 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10376 file.Write("#include \"base/logging.h\"\n")
10377 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10378 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10379 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
10381 file.Write("namespace ppapi {\n\n")
10382 file.Write("namespace {\n\n")
10384 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10385 " Enter3D;\n\n")
10387 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10388 " enter) {\n")
10389 file.Write(" DCHECK(enter);\n")
10390 file.Write(" DCHECK(enter->succeeded());\n")
10391 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10392 "gles2_impl();\n");
10393 file.Write("}\n\n");
10395 for func in self.original_functions:
10396 if not func.InAnyPepperExtension():
10397 continue
10399 original_arg = func.MakeTypedPepperArgString("")
10400 context_arg = "PP_Resource context_id"
10401 if len(original_arg):
10402 arg = context_arg + ", " + original_arg
10403 else:
10404 arg = context_arg
10405 file.Write("%s %s(%s) {\n" %
10406 (func.return_type, func.GetPepperName(), arg))
10407 file.Write(" Enter3D enter(context_id, true);\n")
10408 file.Write(" if (enter.succeeded()) {\n")
10410 return_str = "" if func.return_type == "void" else "return "
10411 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10412 (return_str, func.original_name,
10413 func.MakeOriginalArgString("")))
10414 file.Write(" }")
10415 if func.return_type == "void":
10416 file.Write("\n")
10417 else:
10418 file.Write(" else {\n")
10419 file.Write(" return %s;\n" % func.GetErrorReturnString())
10420 file.Write(" }\n")
10421 file.Write("}\n\n")
10423 file.Write("} // namespace\n")
10425 for interface in self.pepper_interfaces:
10426 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10427 (interface.GetStructName(), interface.GetName()))
10428 file.Write(" static const struct %s "
10429 "ppb_opengles2 = {\n" % interface.GetStructName())
10430 file.Write(" &")
10431 file.Write(",\n &".join(
10432 f.GetPepperName() for f in self.original_functions
10433 if f.InPepperInterface(interface)))
10434 file.Write("\n")
10436 file.Write(" };\n")
10437 file.Write(" return &ppb_opengles2;\n")
10438 file.Write("}\n")
10440 file.Write("} // namespace ppapi\n")
10441 file.Close()
10442 self.generated_cpp_filenames.append(file.filename)
10444 def WriteGLES2ToPPAPIBridge(self, filename):
10445 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10447 file = CWriter(filename)
10448 file.Write(_LICENSE)
10449 file.Write(_DO_NOT_EDIT_WARNING)
10451 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
10452 file.Write("#define GL_GLEXT_PROTOTYPES\n")
10453 file.Write("#endif\n")
10454 file.Write("#include <GLES2/gl2.h>\n")
10455 file.Write("#include <GLES2/gl2ext.h>\n")
10456 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10458 for func in self.original_functions:
10459 if not func.InAnyPepperExtension():
10460 continue
10462 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
10464 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
10465 (func.return_type, func.GetPepperName(),
10466 func.MakeTypedPepperArgString("")))
10467 return_str = "" if func.return_type == "void" else "return "
10468 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
10469 original_arg = func.MakeOriginalArgString("")
10470 context_arg = "glGetCurrentContextPPAPI()"
10471 if len(original_arg):
10472 arg = context_arg + ", " + original_arg
10473 else:
10474 arg = context_arg
10475 if interface.GetName():
10476 file.Write(" const struct %s* ext = %s;\n" %
10477 (interface.GetStructName(), interface_str))
10478 file.Write(" if (ext)\n")
10479 file.Write(" %sext->%s(%s);\n" %
10480 (return_str, func.GetPepperName(), arg))
10481 if return_str:
10482 file.Write(" %s0;\n" % return_str)
10483 else:
10484 file.Write(" %s%s->%s(%s);\n" %
10485 (return_str, interface_str, func.GetPepperName(), arg))
10486 file.Write("}\n\n")
10487 file.Close()
10488 self.generated_cpp_filenames.append(file.filename)
10490 def WriteMojoGLCallVisitor(self, filename):
10491 """Provides the GL implementation for mojo"""
10492 file = CWriter(filename)
10493 file.Write(_LICENSE)
10494 file.Write(_DO_NOT_EDIT_WARNING)
10496 for func in self.original_functions:
10497 if not func.IsCoreGLFunction():
10498 continue
10499 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10500 (func.name, func.return_type,
10501 func.MakeTypedOriginalArgString(""),
10502 func.MakeOriginalArgString("")))
10504 file.Close()
10505 self.generated_cpp_filenames.append(file.filename)
10507 def WriteMojoGLCallVisitorForExtension(self, filename, extension):
10508 """Provides the GL implementation for mojo for a particular extension"""
10509 file = CWriter(filename)
10510 file.Write(_LICENSE)
10511 file.Write(_DO_NOT_EDIT_WARNING)
10513 for func in self.original_functions:
10514 if func.GetInfo("extension") != extension:
10515 continue
10516 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10517 (func.name, func.return_type,
10518 func.MakeTypedOriginalArgString(""),
10519 func.MakeOriginalArgString("")))
10521 file.Close()
10522 self.generated_cpp_filenames.append(file.filename)
10524 def Format(generated_files):
10525 formatter = "clang-format"
10526 if platform.system() == "Windows":
10527 formatter += ".bat"
10528 for filename in generated_files:
10529 call([formatter, "-i", "-style=chromium", filename])
10531 def main(argv):
10532 """This is the main function."""
10533 parser = OptionParser()
10534 parser.add_option(
10535 "--output-dir",
10536 help="base directory for resulting files, under chrome/src. default is "
10537 "empty. Use this if you want the result stored under gen.")
10538 parser.add_option(
10539 "-v", "--verbose", action="store_true",
10540 help="prints more output.")
10542 (options, args) = parser.parse_args(args=argv)
10544 # Add in states and capabilites to GLState
10545 gl_state_valid = _NAMED_TYPE_INFO['GLState']['valid']
10546 for state_name in sorted(_STATES.keys()):
10547 state = _STATES[state_name]
10548 if 'extension_flag' in state:
10549 continue
10550 if 'enum' in state:
10551 if not state['enum'] in gl_state_valid:
10552 gl_state_valid.append(state['enum'])
10553 else:
10554 for item in state['states']:
10555 if 'extension_flag' in item:
10556 continue
10557 if not item['enum'] in gl_state_valid:
10558 gl_state_valid.append(item['enum'])
10559 for capability in _CAPABILITY_FLAGS:
10560 valid_value = "GL_%s" % capability['name'].upper()
10561 if not valid_value in gl_state_valid:
10562 gl_state_valid.append(valid_value)
10564 # This script lives under gpu/command_buffer, cd to base directory.
10565 os.chdir(os.path.dirname(__file__) + "/../..")
10566 base_dir = os.getcwd()
10567 gen = GLGenerator(options.verbose)
10568 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10570 # Support generating files under gen/
10571 if options.output_dir != None:
10572 os.chdir(options.output_dir)
10574 gen.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10575 gen.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10576 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10577 gen.WritePepperGLES2Implementation(
10578 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10579 os.chdir(base_dir)
10580 gen.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10581 gen.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10582 gen.WriteFormatTest(
10583 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10584 gen.WriteGLES2InterfaceHeader(
10585 "gpu/command_buffer/client/gles2_interface_autogen.h")
10586 gen.WriteMojoGLES2ImplHeader(
10587 "mojo/gpu/mojo_gles2_impl_autogen.h")
10588 gen.WriteMojoGLES2Impl(
10589 "mojo/gpu/mojo_gles2_impl_autogen.cc")
10590 gen.WriteGLES2InterfaceStub(
10591 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10592 gen.WriteGLES2InterfaceStubImpl(
10593 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10594 gen.WriteGLES2ImplementationHeader(
10595 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10596 gen.WriteGLES2Implementation(
10597 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10598 gen.WriteGLES2ImplementationUnitTests(
10599 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10600 gen.WriteGLES2TraceImplementationHeader(
10601 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10602 gen.WriteGLES2TraceImplementation(
10603 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10604 gen.WriteGLES2CLibImplementation(
10605 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10606 gen.WriteCmdHelperHeader(
10607 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
10608 gen.WriteServiceImplementation(
10609 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
10610 gen.WriteServiceContextStateHeader(
10611 "gpu/command_buffer/service/context_state_autogen.h")
10612 gen.WriteServiceContextStateImpl(
10613 "gpu/command_buffer/service/context_state_impl_autogen.h")
10614 gen.WriteClientContextStateHeader(
10615 "gpu/command_buffer/client/client_context_state_autogen.h")
10616 gen.WriteClientContextStateImpl(
10617 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
10618 gen.WriteServiceUnitTests(
10619 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
10620 gen.WriteServiceUnitTestsForExtensions(
10621 "gpu/command_buffer/service/"
10622 "gles2_cmd_decoder_unittest_extensions_autogen.h")
10623 gen.WriteServiceUtilsHeader(
10624 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
10625 gen.WriteServiceUtilsImplementation(
10626 "gpu/command_buffer/service/"
10627 "gles2_cmd_validation_implementation_autogen.h")
10628 gen.WriteCommonUtilsHeader(
10629 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
10630 gen.WriteCommonUtilsImpl(
10631 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
10632 gen.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
10633 mojo_gles2_prefix = ("third_party/mojo/src/mojo/public/c/gles2/"
10634 "gles2_call_visitor")
10635 gen.WriteMojoGLCallVisitor(mojo_gles2_prefix + "_autogen.h")
10636 gen.WriteMojoGLCallVisitorForExtension(
10637 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
10638 "CHROMIUM_texture_mailbox")
10639 gen.WriteMojoGLCallVisitorForExtension(
10640 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
10641 "CHROMIUM_sync_point")
10642 gen.WriteMojoGLCallVisitorForExtension(
10643 mojo_gles2_prefix + "_chromium_sub_image_autogen.h",
10644 "CHROMIUM_sub_image")
10645 gen.WriteMojoGLCallVisitorForExtension(
10646 mojo_gles2_prefix + "_chromium_miscellaneous_autogen.h",
10647 "CHROMIUM_miscellaneous")
10648 gen.WriteMojoGLCallVisitorForExtension(
10649 mojo_gles2_prefix + "_occlusion_query_ext_autogen.h",
10650 "occlusion_query_EXT")
10652 Format(gen.generated_cpp_filenames)
10654 if gen.errors > 0:
10655 print "%d errors" % gen.errors
10656 return 1
10657 return 0
10660 if __name__ == '__main__':
10661 sys.exit(main(sys.argv[1:]))