Show Pages in chrome://md-settings
[chromium-blink-merge.git] / gpu / command_buffer / build_gles2_cmd_buffer.py
blobd5b799e5d855c5cab1677eacaaecc6994c8884a8
1 #!/usr/bin/env python
2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """code generator for GLES2 command buffers."""
8 import itertools
9 import os
10 import os.path
11 import sys
12 import re
13 import platform
14 from optparse import OptionParser
15 from subprocess import call
17 _SIZE_OF_UINT32 = 4
18 _SIZE_OF_COMMAND_HEADER = 4
19 _FIRST_SPECIFIC_COMMAND_ID = 256
21 _LICENSE = """// Copyright 2014 The Chromium Authors. All rights reserved.
22 // Use of this source code is governed by a BSD-style license that can be
23 // found in the LICENSE file.
25 """
27 _DO_NOT_EDIT_WARNING = """// This file is auto-generated from
28 // gpu/command_buffer/build_gles2_cmd_buffer.py
29 // It's formatted by clang-format using chromium coding style:
30 // clang-format -i -style=chromium filename
31 // DO NOT EDIT!
33 """
35 # This string is copied directly out of the gl2.h file from GLES2.0
37 # Edits:
39 # *) Any argument that is a resourceID has been changed to GLid<Type>.
40 # (not pointer arguments) and if it's allowed to be zero it's GLidZero<Type>
41 # If it's allowed to not exist it's GLidBind<Type>
43 # *) All GLenums have been changed to GLenumTypeOfEnum
45 _GL_TYPES = {
46 'GLenum': 'unsigned int',
47 'GLboolean': 'unsigned char',
48 'GLbitfield': 'unsigned int',
49 'GLbyte': 'signed char',
50 'GLshort': 'short',
51 'GLint': 'int',
52 'GLsizei': 'int',
53 'GLubyte': 'unsigned char',
54 'GLushort': 'unsigned short',
55 'GLuint': 'unsigned int',
56 'GLfloat': 'float',
57 'GLclampf': 'float',
58 'GLvoid': 'void',
59 'GLfixed': 'int',
60 'GLclampx': 'int'
63 _GL_TYPES_32 = {
64 'GLintptr': 'long int',
65 'GLsizeiptr': 'long int'
68 _GL_TYPES_64 = {
69 'GLintptr': 'long long int',
70 'GLsizeiptr': 'long long int'
73 # Capabilites selected with glEnable
74 _CAPABILITY_FLAGS = [
75 {'name': 'blend'},
76 {'name': 'cull_face'},
77 {'name': 'depth_test', 'state_flag': 'framebuffer_state_.clear_state_dirty'},
78 {'name': 'dither', 'default': True},
79 {'name': 'polygon_offset_fill'},
80 {'name': 'sample_alpha_to_coverage'},
81 {'name': 'sample_coverage'},
82 {'name': 'scissor_test'},
83 {'name': 'stencil_test',
84 'state_flag': 'framebuffer_state_.clear_state_dirty'},
87 _STATES = {
88 'ClearColor': {
89 'type': 'Normal',
90 'func': 'ClearColor',
91 'enum': 'GL_COLOR_CLEAR_VALUE',
92 'states': [
93 {'name': 'color_clear_red', 'type': 'GLfloat', 'default': '0.0f'},
94 {'name': 'color_clear_green', 'type': 'GLfloat', 'default': '0.0f'},
95 {'name': 'color_clear_blue', 'type': 'GLfloat', 'default': '0.0f'},
96 {'name': 'color_clear_alpha', 'type': 'GLfloat', 'default': '0.0f'},
99 'ClearDepthf': {
100 'type': 'Normal',
101 'func': 'ClearDepth',
102 'enum': 'GL_DEPTH_CLEAR_VALUE',
103 'states': [
104 {'name': 'depth_clear', 'type': 'GLclampf', 'default': '1.0f'},
107 'ColorMask': {
108 'type': 'Normal',
109 'func': 'ColorMask',
110 'enum': 'GL_COLOR_WRITEMASK',
111 'states': [
113 'name': 'color_mask_red',
114 'type': 'GLboolean',
115 'default': 'true',
116 'cached': True
119 'name': 'color_mask_green',
120 'type': 'GLboolean',
121 'default': 'true',
122 'cached': True
125 'name': 'color_mask_blue',
126 'type': 'GLboolean',
127 'default': 'true',
128 'cached': True
131 'name': 'color_mask_alpha',
132 'type': 'GLboolean',
133 'default': 'true',
134 'cached': True
137 'state_flag': 'framebuffer_state_.clear_state_dirty',
139 'ClearStencil': {
140 'type': 'Normal',
141 'func': 'ClearStencil',
142 'enum': 'GL_STENCIL_CLEAR_VALUE',
143 'states': [
144 {'name': 'stencil_clear', 'type': 'GLint', 'default': '0'},
147 'BlendColor': {
148 'type': 'Normal',
149 'func': 'BlendColor',
150 'enum': 'GL_BLEND_COLOR',
151 'states': [
152 {'name': 'blend_color_red', 'type': 'GLfloat', 'default': '0.0f'},
153 {'name': 'blend_color_green', 'type': 'GLfloat', 'default': '0.0f'},
154 {'name': 'blend_color_blue', 'type': 'GLfloat', 'default': '0.0f'},
155 {'name': 'blend_color_alpha', 'type': 'GLfloat', 'default': '0.0f'},
158 'BlendEquation': {
159 'type': 'SrcDst',
160 'func': 'BlendEquationSeparate',
161 'states': [
163 'name': 'blend_equation_rgb',
164 'type': 'GLenum',
165 'enum': 'GL_BLEND_EQUATION_RGB',
166 'default': 'GL_FUNC_ADD',
169 'name': 'blend_equation_alpha',
170 'type': 'GLenum',
171 'enum': 'GL_BLEND_EQUATION_ALPHA',
172 'default': 'GL_FUNC_ADD',
176 'BlendFunc': {
177 'type': 'SrcDst',
178 'func': 'BlendFuncSeparate',
179 'states': [
181 'name': 'blend_source_rgb',
182 'type': 'GLenum',
183 'enum': 'GL_BLEND_SRC_RGB',
184 'default': 'GL_ONE',
187 'name': 'blend_dest_rgb',
188 'type': 'GLenum',
189 'enum': 'GL_BLEND_DST_RGB',
190 'default': 'GL_ZERO',
193 'name': 'blend_source_alpha',
194 'type': 'GLenum',
195 'enum': 'GL_BLEND_SRC_ALPHA',
196 'default': 'GL_ONE',
199 'name': 'blend_dest_alpha',
200 'type': 'GLenum',
201 'enum': 'GL_BLEND_DST_ALPHA',
202 'default': 'GL_ZERO',
206 'PolygonOffset': {
207 'type': 'Normal',
208 'func': 'PolygonOffset',
209 'states': [
211 'name': 'polygon_offset_factor',
212 'type': 'GLfloat',
213 'enum': 'GL_POLYGON_OFFSET_FACTOR',
214 'default': '0.0f',
217 'name': 'polygon_offset_units',
218 'type': 'GLfloat',
219 'enum': 'GL_POLYGON_OFFSET_UNITS',
220 'default': '0.0f',
224 'CullFace': {
225 'type': 'Normal',
226 'func': 'CullFace',
227 'enum': 'GL_CULL_FACE_MODE',
228 'states': [
230 'name': 'cull_mode',
231 'type': 'GLenum',
232 'default': 'GL_BACK',
236 'FrontFace': {
237 'type': 'Normal',
238 'func': 'FrontFace',
239 'enum': 'GL_FRONT_FACE',
240 'states': [{'name': 'front_face', 'type': 'GLenum', 'default': 'GL_CCW'}],
242 'DepthFunc': {
243 'type': 'Normal',
244 'func': 'DepthFunc',
245 'enum': 'GL_DEPTH_FUNC',
246 'states': [{'name': 'depth_func', 'type': 'GLenum', 'default': 'GL_LESS'}],
248 'DepthRange': {
249 'type': 'Normal',
250 'func': 'DepthRange',
251 'enum': 'GL_DEPTH_RANGE',
252 'states': [
253 {'name': 'z_near', 'type': 'GLclampf', 'default': '0.0f'},
254 {'name': 'z_far', 'type': 'GLclampf', 'default': '1.0f'},
257 'SampleCoverage': {
258 'type': 'Normal',
259 'func': 'SampleCoverage',
260 'states': [
262 'name': 'sample_coverage_value',
263 'type': 'GLclampf',
264 'enum': 'GL_SAMPLE_COVERAGE_VALUE',
265 'default': '1.0f',
268 'name': 'sample_coverage_invert',
269 'type': 'GLboolean',
270 'enum': 'GL_SAMPLE_COVERAGE_INVERT',
271 'default': 'false',
275 'StencilMask': {
276 'type': 'FrontBack',
277 'func': 'StencilMaskSeparate',
278 'state_flag': 'framebuffer_state_.clear_state_dirty',
279 'states': [
281 'name': 'stencil_front_writemask',
282 'type': 'GLuint',
283 'enum': 'GL_STENCIL_WRITEMASK',
284 'default': '0xFFFFFFFFU',
285 'cached': True,
288 'name': 'stencil_back_writemask',
289 'type': 'GLuint',
290 'enum': 'GL_STENCIL_BACK_WRITEMASK',
291 'default': '0xFFFFFFFFU',
292 'cached': True,
296 'StencilOp': {
297 'type': 'FrontBack',
298 'func': 'StencilOpSeparate',
299 'states': [
301 'name': 'stencil_front_fail_op',
302 'type': 'GLenum',
303 'enum': 'GL_STENCIL_FAIL',
304 'default': 'GL_KEEP',
307 'name': 'stencil_front_z_fail_op',
308 'type': 'GLenum',
309 'enum': 'GL_STENCIL_PASS_DEPTH_FAIL',
310 'default': 'GL_KEEP',
313 'name': 'stencil_front_z_pass_op',
314 'type': 'GLenum',
315 'enum': 'GL_STENCIL_PASS_DEPTH_PASS',
316 'default': 'GL_KEEP',
319 'name': 'stencil_back_fail_op',
320 'type': 'GLenum',
321 'enum': 'GL_STENCIL_BACK_FAIL',
322 'default': 'GL_KEEP',
325 'name': 'stencil_back_z_fail_op',
326 'type': 'GLenum',
327 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_FAIL',
328 'default': 'GL_KEEP',
331 'name': 'stencil_back_z_pass_op',
332 'type': 'GLenum',
333 'enum': 'GL_STENCIL_BACK_PASS_DEPTH_PASS',
334 'default': 'GL_KEEP',
338 'StencilFunc': {
339 'type': 'FrontBack',
340 'func': 'StencilFuncSeparate',
341 'states': [
343 'name': 'stencil_front_func',
344 'type': 'GLenum',
345 'enum': 'GL_STENCIL_FUNC',
346 'default': 'GL_ALWAYS',
349 'name': 'stencil_front_ref',
350 'type': 'GLint',
351 'enum': 'GL_STENCIL_REF',
352 'default': '0',
355 'name': 'stencil_front_mask',
356 'type': 'GLuint',
357 'enum': 'GL_STENCIL_VALUE_MASK',
358 'default': '0xFFFFFFFFU',
361 'name': 'stencil_back_func',
362 'type': 'GLenum',
363 'enum': 'GL_STENCIL_BACK_FUNC',
364 'default': 'GL_ALWAYS',
367 'name': 'stencil_back_ref',
368 'type': 'GLint',
369 'enum': 'GL_STENCIL_BACK_REF',
370 'default': '0',
373 'name': 'stencil_back_mask',
374 'type': 'GLuint',
375 'enum': 'GL_STENCIL_BACK_VALUE_MASK',
376 'default': '0xFFFFFFFFU',
380 'Hint': {
381 'type': 'NamedParameter',
382 'func': 'Hint',
383 'states': [
385 'name': 'hint_generate_mipmap',
386 'type': 'GLenum',
387 'enum': 'GL_GENERATE_MIPMAP_HINT',
388 'default': 'GL_DONT_CARE'
391 'name': 'hint_fragment_shader_derivative',
392 'type': 'GLenum',
393 'enum': 'GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES',
394 'default': 'GL_DONT_CARE',
395 'extension_flag': 'oes_standard_derivatives'
399 'PixelStore': {
400 'type': 'NamedParameter',
401 'func': 'PixelStorei',
402 'states': [
404 'name': 'pack_alignment',
405 'type': 'GLint',
406 'enum': 'GL_PACK_ALIGNMENT',
407 'default': '4'
410 'name': 'unpack_alignment',
411 'type': 'GLint',
412 'enum': 'GL_UNPACK_ALIGNMENT',
413 'default': '4'
417 # TODO: Consider implemenenting these states
418 # GL_ACTIVE_TEXTURE
419 'LineWidth': {
420 'type': 'Normal',
421 'func': 'LineWidth',
422 'enum': 'GL_LINE_WIDTH',
423 'states': [
425 'name': 'line_width',
426 'type': 'GLfloat',
427 'default': '1.0f',
428 'range_checks': [{'check': "<= 0.0f", 'test_value': "0.0f"}],
429 'nan_check': True,
432 'DepthMask': {
433 'type': 'Normal',
434 'func': 'DepthMask',
435 'enum': 'GL_DEPTH_WRITEMASK',
436 'states': [
438 'name': 'depth_mask',
439 'type': 'GLboolean',
440 'default': 'true',
441 'cached': True
444 'state_flag': 'framebuffer_state_.clear_state_dirty',
446 'Scissor': {
447 'type': 'Normal',
448 'func': 'Scissor',
449 'enum': 'GL_SCISSOR_BOX',
450 'states': [
451 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
453 'name': 'scissor_x',
454 'type': 'GLint',
455 'default': '0',
456 'expected': 'kViewportX',
459 'name': 'scissor_y',
460 'type': 'GLint',
461 'default': '0',
462 'expected': 'kViewportY',
465 'name': 'scissor_width',
466 'type': 'GLsizei',
467 'default': '1',
468 'expected': 'kViewportWidth',
471 'name': 'scissor_height',
472 'type': 'GLsizei',
473 'default': '1',
474 'expected': 'kViewportHeight',
478 'Viewport': {
479 'type': 'Normal',
480 'func': 'Viewport',
481 'enum': 'GL_VIEWPORT',
482 'states': [
483 # NOTE: These defaults reset at GLES2DecoderImpl::Initialization.
485 'name': 'viewport_x',
486 'type': 'GLint',
487 'default': '0',
488 'expected': 'kViewportX',
491 'name': 'viewport_y',
492 'type': 'GLint',
493 'default': '0',
494 'expected': 'kViewportY',
497 'name': 'viewport_width',
498 'type': 'GLsizei',
499 'default': '1',
500 'expected': 'kViewportWidth',
503 'name': 'viewport_height',
504 'type': 'GLsizei',
505 'default': '1',
506 'expected': 'kViewportHeight',
510 'MatrixValuesCHROMIUM': {
511 'type': 'NamedParameter',
512 'func': 'MatrixLoadfEXT',
513 'states': [
514 { 'enum': 'GL_PATH_MODELVIEW_MATRIX_CHROMIUM',
515 'enum_set': 'GL_PATH_MODELVIEW_CHROMIUM',
516 'name': 'modelview_matrix',
517 'type': 'GLfloat',
518 'default': [
519 '1.0f', '0.0f','0.0f','0.0f',
520 '0.0f', '1.0f','0.0f','0.0f',
521 '0.0f', '0.0f','1.0f','0.0f',
522 '0.0f', '0.0f','0.0f','1.0f',
524 'extension_flag': 'chromium_path_rendering',
526 { 'enum': 'GL_PATH_PROJECTION_MATRIX_CHROMIUM',
527 'enum_set': 'GL_PATH_PROJECTION_CHROMIUM',
528 'name': 'projection_matrix',
529 'type': 'GLfloat',
530 'default': [
531 '1.0f', '0.0f','0.0f','0.0f',
532 '0.0f', '1.0f','0.0f','0.0f',
533 '0.0f', '0.0f','1.0f','0.0f',
534 '0.0f', '0.0f','0.0f','1.0f',
536 'extension_flag': 'chromium_path_rendering',
542 # Named type info object represents a named type that is used in OpenGL call
543 # arguments. Each named type defines a set of valid OpenGL call arguments. The
544 # named types are used in 'cmd_buffer_functions.txt'.
545 # type: The actual GL type of the named type.
546 # valid: The list of values that are valid for both the client and the service.
547 # valid_es3: The list of values that are valid in OpenGL ES 3, but not ES 2.
548 # invalid: Examples of invalid values for the type. At least these values
549 # should be tested to be invalid.
550 # deprecated_es3: The list of values that are valid in OpenGL ES 2, but
551 # deprecated in ES 3.
552 # is_complete: The list of valid values of type are final and will not be
553 # modified during runtime.
554 _NAMED_TYPE_INFO = {
555 'BlitFilter': {
556 'type': 'GLenum',
557 'valid': [
558 'GL_NEAREST',
559 'GL_LINEAR',
561 'invalid': [
562 'GL_LINEAR_MIPMAP_LINEAR',
565 'FrameBufferTarget': {
566 'type': 'GLenum',
567 'valid': [
568 'GL_FRAMEBUFFER',
570 'invalid': [
571 'GL_DRAW_FRAMEBUFFER' ,
572 'GL_READ_FRAMEBUFFER' ,
575 'RenderBufferTarget': {
576 'type': 'GLenum',
577 'valid': [
578 'GL_RENDERBUFFER',
580 'invalid': [
581 'GL_FRAMEBUFFER',
584 'BufferTarget': {
585 'type': 'GLenum',
586 'valid': [
587 'GL_ARRAY_BUFFER',
588 'GL_ELEMENT_ARRAY_BUFFER',
590 'valid_es3': [
591 'GL_COPY_READ_BUFFER',
592 'GL_COPY_WRITE_BUFFER',
593 'GL_PIXEL_PACK_BUFFER',
594 'GL_PIXEL_UNPACK_BUFFER',
595 'GL_TRANSFORM_FEEDBACK_BUFFER',
596 'GL_UNIFORM_BUFFER',
598 'invalid': [
599 'GL_RENDERBUFFER',
602 'IndexedBufferTarget': {
603 'type': 'GLenum',
604 'valid': [
605 'GL_TRANSFORM_FEEDBACK_BUFFER',
606 'GL_UNIFORM_BUFFER',
608 'invalid': [
609 'GL_RENDERBUFFER',
612 'MapBufferAccess': {
613 'type': 'GLenum',
614 'valid': [
615 'GL_MAP_READ_BIT',
616 'GL_MAP_WRITE_BIT',
617 'GL_MAP_INVALIDATE_RANGE_BIT',
618 'GL_MAP_INVALIDATE_BUFFER_BIT',
619 'GL_MAP_FLUSH_EXPLICIT_BIT',
620 'GL_MAP_UNSYNCHRONIZED_BIT',
622 'invalid': [
623 'GL_SYNC_FLUSH_COMMANDS_BIT',
626 'Bufferiv': {
627 'type': 'GLenum',
628 'valid': [
629 'GL_COLOR',
630 'GL_STENCIL',
632 'invalid': [
633 'GL_RENDERBUFFER',
636 'Bufferuiv': {
637 'type': 'GLenum',
638 'valid': [
639 'GL_COLOR',
641 'invalid': [
642 'GL_RENDERBUFFER',
645 'Bufferfv': {
646 'type': 'GLenum',
647 'valid': [
648 'GL_COLOR',
649 'GL_DEPTH',
651 'invalid': [
652 'GL_RENDERBUFFER',
655 'Bufferfi': {
656 'type': 'GLenum',
657 'valid': [
658 'GL_DEPTH_STENCIL',
660 'invalid': [
661 'GL_RENDERBUFFER',
664 'BufferUsage': {
665 'type': 'GLenum',
666 'valid': [
667 'GL_STREAM_DRAW',
668 'GL_STATIC_DRAW',
669 'GL_DYNAMIC_DRAW',
671 'invalid': [
672 'GL_STATIC_READ',
675 'CompressedTextureFormat': {
676 'type': 'GLenum',
677 'valid': [
680 'GLState': {
681 'type': 'GLenum',
682 'valid': [
683 # NOTE: State an Capability entries added later.
684 'GL_ACTIVE_TEXTURE',
685 'GL_ALIASED_LINE_WIDTH_RANGE',
686 'GL_ALIASED_POINT_SIZE_RANGE',
687 'GL_ALPHA_BITS',
688 'GL_ARRAY_BUFFER_BINDING',
689 'GL_BLUE_BITS',
690 'GL_COMPRESSED_TEXTURE_FORMATS',
691 'GL_CURRENT_PROGRAM',
692 'GL_DEPTH_BITS',
693 'GL_DEPTH_RANGE',
694 'GL_ELEMENT_ARRAY_BUFFER_BINDING',
695 'GL_FRAMEBUFFER_BINDING',
696 'GL_GENERATE_MIPMAP_HINT',
697 'GL_GREEN_BITS',
698 'GL_IMPLEMENTATION_COLOR_READ_FORMAT',
699 'GL_IMPLEMENTATION_COLOR_READ_TYPE',
700 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS',
701 'GL_MAX_CUBE_MAP_TEXTURE_SIZE',
702 'GL_MAX_FRAGMENT_UNIFORM_VECTORS',
703 'GL_MAX_RENDERBUFFER_SIZE',
704 'GL_MAX_TEXTURE_IMAGE_UNITS',
705 'GL_MAX_TEXTURE_SIZE',
706 'GL_MAX_VARYING_VECTORS',
707 'GL_MAX_VERTEX_ATTRIBS',
708 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS',
709 'GL_MAX_VERTEX_UNIFORM_VECTORS',
710 'GL_MAX_VIEWPORT_DIMS',
711 'GL_NUM_COMPRESSED_TEXTURE_FORMATS',
712 'GL_NUM_SHADER_BINARY_FORMATS',
713 'GL_PACK_ALIGNMENT',
714 'GL_RED_BITS',
715 'GL_RENDERBUFFER_BINDING',
716 'GL_SAMPLE_BUFFERS',
717 'GL_SAMPLE_COVERAGE_INVERT',
718 'GL_SAMPLE_COVERAGE_VALUE',
719 'GL_SAMPLES',
720 'GL_SCISSOR_BOX',
721 'GL_SHADER_BINARY_FORMATS',
722 'GL_SHADER_COMPILER',
723 'GL_SUBPIXEL_BITS',
724 'GL_STENCIL_BITS',
725 'GL_TEXTURE_BINDING_2D',
726 'GL_TEXTURE_BINDING_CUBE_MAP',
727 'GL_UNPACK_ALIGNMENT',
728 'GL_UNPACK_FLIP_Y_CHROMIUM',
729 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
730 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
731 'GL_BIND_GENERATES_RESOURCE_CHROMIUM',
732 # we can add this because we emulate it if the driver does not support it.
733 'GL_VERTEX_ARRAY_BINDING_OES',
734 'GL_VIEWPORT',
736 'invalid': [
737 'GL_FOG_HINT',
740 'GetTexParamTarget': {
741 'type': 'GLenum',
742 'valid': [
743 'GL_TEXTURE_2D',
744 'GL_TEXTURE_CUBE_MAP',
746 'invalid': [
747 'GL_PROXY_TEXTURE_CUBE_MAP',
750 'TextureTarget': {
751 'type': 'GLenum',
752 'valid': [
753 'GL_TEXTURE_2D',
754 'GL_TEXTURE_CUBE_MAP_POSITIVE_X',
755 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X',
756 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y',
757 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y',
758 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z',
759 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z',
761 'invalid': [
762 'GL_PROXY_TEXTURE_CUBE_MAP',
765 'Texture3DTarget': {
766 'type': 'GLenum',
767 'valid': [
768 'GL_TEXTURE_3D',
769 'GL_TEXTURE_2D_ARRAY',
771 'invalid': [
772 'GL_TEXTURE_2D',
775 'TextureBindTarget': {
776 'type': 'GLenum',
777 'valid': [
778 'GL_TEXTURE_2D',
779 'GL_TEXTURE_CUBE_MAP',
781 'valid_es3': [
782 'GL_TEXTURE_3D',
783 'GL_TEXTURE_2D_ARRAY',
785 'invalid': [
786 'GL_TEXTURE_1D',
787 'GL_TEXTURE_3D',
790 'TransformFeedbackBindTarget': {
791 'type': 'GLenum',
792 'valid': [
793 'GL_TRANSFORM_FEEDBACK',
795 'invalid': [
796 'GL_TEXTURE_2D',
799 'TransformFeedbackPrimitiveMode': {
800 'type': 'GLenum',
801 'valid': [
802 'GL_POINTS',
803 'GL_LINES',
804 'GL_TRIANGLES',
806 'invalid': [
807 'GL_LINE_LOOP',
810 'ShaderType': {
811 'type': 'GLenum',
812 'valid': [
813 'GL_VERTEX_SHADER',
814 'GL_FRAGMENT_SHADER',
816 'invalid': [
817 'GL_GEOMETRY_SHADER',
820 'FaceType': {
821 'type': 'GLenum',
822 'valid': [
823 'GL_FRONT',
824 'GL_BACK',
825 'GL_FRONT_AND_BACK',
828 'FaceMode': {
829 'type': 'GLenum',
830 'valid': [
831 'GL_CW',
832 'GL_CCW',
835 'CmpFunction': {
836 'type': 'GLenum',
837 'valid': [
838 'GL_NEVER',
839 'GL_LESS',
840 'GL_EQUAL',
841 'GL_LEQUAL',
842 'GL_GREATER',
843 'GL_NOTEQUAL',
844 'GL_GEQUAL',
845 'GL_ALWAYS',
848 'Equation': {
849 'type': 'GLenum',
850 'valid': [
851 'GL_FUNC_ADD',
852 'GL_FUNC_SUBTRACT',
853 'GL_FUNC_REVERSE_SUBTRACT',
855 'invalid': [
856 'GL_MIN',
857 'GL_MAX',
860 'SrcBlendFactor': {
861 'type': 'GLenum',
862 'valid': [
863 'GL_ZERO',
864 'GL_ONE',
865 'GL_SRC_COLOR',
866 'GL_ONE_MINUS_SRC_COLOR',
867 'GL_DST_COLOR',
868 'GL_ONE_MINUS_DST_COLOR',
869 'GL_SRC_ALPHA',
870 'GL_ONE_MINUS_SRC_ALPHA',
871 'GL_DST_ALPHA',
872 'GL_ONE_MINUS_DST_ALPHA',
873 'GL_CONSTANT_COLOR',
874 'GL_ONE_MINUS_CONSTANT_COLOR',
875 'GL_CONSTANT_ALPHA',
876 'GL_ONE_MINUS_CONSTANT_ALPHA',
877 'GL_SRC_ALPHA_SATURATE',
880 'DstBlendFactor': {
881 'type': 'GLenum',
882 'valid': [
883 'GL_ZERO',
884 'GL_ONE',
885 'GL_SRC_COLOR',
886 'GL_ONE_MINUS_SRC_COLOR',
887 'GL_DST_COLOR',
888 'GL_ONE_MINUS_DST_COLOR',
889 'GL_SRC_ALPHA',
890 'GL_ONE_MINUS_SRC_ALPHA',
891 'GL_DST_ALPHA',
892 'GL_ONE_MINUS_DST_ALPHA',
893 'GL_CONSTANT_COLOR',
894 'GL_ONE_MINUS_CONSTANT_COLOR',
895 'GL_CONSTANT_ALPHA',
896 'GL_ONE_MINUS_CONSTANT_ALPHA',
899 'Capability': {
900 'type': 'GLenum',
901 'valid': ["GL_%s" % cap['name'].upper() for cap in _CAPABILITY_FLAGS],
902 'invalid': [
903 'GL_CLIP_PLANE0',
904 'GL_POINT_SPRITE',
907 'DrawMode': {
908 'type': 'GLenum',
909 'valid': [
910 'GL_POINTS',
911 'GL_LINE_STRIP',
912 'GL_LINE_LOOP',
913 'GL_LINES',
914 'GL_TRIANGLE_STRIP',
915 'GL_TRIANGLE_FAN',
916 'GL_TRIANGLES',
918 'invalid': [
919 'GL_QUADS',
920 'GL_POLYGON',
923 'IndexType': {
924 'type': 'GLenum',
925 'valid': [
926 'GL_UNSIGNED_BYTE',
927 'GL_UNSIGNED_SHORT',
929 'invalid': [
930 'GL_UNSIGNED_INT',
931 'GL_INT',
934 'GetMaxIndexType': {
935 'type': 'GLenum',
936 'valid': [
937 'GL_UNSIGNED_BYTE',
938 'GL_UNSIGNED_SHORT',
939 'GL_UNSIGNED_INT',
941 'invalid': [
942 'GL_INT',
945 'Attachment': {
946 'type': 'GLenum',
947 'valid': [
948 'GL_COLOR_ATTACHMENT0',
949 'GL_DEPTH_ATTACHMENT',
950 'GL_STENCIL_ATTACHMENT',
953 'BackbufferAttachment': {
954 'type': 'GLenum',
955 'valid': [
956 'GL_COLOR_EXT',
957 'GL_DEPTH_EXT',
958 'GL_STENCIL_EXT',
961 'BufferParameter': {
962 'type': 'GLenum',
963 'valid': [
964 'GL_BUFFER_SIZE',
965 'GL_BUFFER_USAGE',
967 'invalid': [
968 'GL_PIXEL_PACK_BUFFER',
971 'BufferMode': {
972 'type': 'GLenum',
973 'valid': [
974 'GL_INTERLEAVED_ATTRIBS',
975 'GL_SEPARATE_ATTRIBS',
977 'invalid': [
978 'GL_PIXEL_PACK_BUFFER',
981 'FrameBufferParameter': {
982 'type': 'GLenum',
983 'valid': [
984 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
985 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
986 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
987 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
990 'MatrixMode': {
991 'type': 'GLenum',
992 'valid': [
993 'GL_PATH_PROJECTION_CHROMIUM',
994 'GL_PATH_MODELVIEW_CHROMIUM',
997 'ProgramParameter': {
998 'type': 'GLenum',
999 'valid': [
1000 'GL_DELETE_STATUS',
1001 'GL_LINK_STATUS',
1002 'GL_VALIDATE_STATUS',
1003 'GL_INFO_LOG_LENGTH',
1004 'GL_ATTACHED_SHADERS',
1005 'GL_ACTIVE_ATTRIBUTES',
1006 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH',
1007 'GL_ACTIVE_UNIFORMS',
1008 'GL_ACTIVE_UNIFORM_MAX_LENGTH',
1011 'QueryObjectParameter': {
1012 'type': 'GLenum',
1013 'valid': [
1014 'GL_QUERY_RESULT_EXT',
1015 'GL_QUERY_RESULT_AVAILABLE_EXT',
1018 'QueryParameter': {
1019 'type': 'GLenum',
1020 'valid': [
1021 'GL_CURRENT_QUERY_EXT',
1024 'QueryTarget': {
1025 'type': 'GLenum',
1026 'valid': [
1027 'GL_ANY_SAMPLES_PASSED_EXT',
1028 'GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT',
1029 'GL_COMMANDS_ISSUED_CHROMIUM',
1030 'GL_LATENCY_QUERY_CHROMIUM',
1031 'GL_ASYNC_PIXEL_UNPACK_COMPLETED_CHROMIUM',
1032 'GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM',
1033 'GL_COMMANDS_COMPLETED_CHROMIUM',
1036 'RenderBufferParameter': {
1037 'type': 'GLenum',
1038 'valid': [
1039 'GL_RENDERBUFFER_RED_SIZE',
1040 'GL_RENDERBUFFER_GREEN_SIZE',
1041 'GL_RENDERBUFFER_BLUE_SIZE',
1042 'GL_RENDERBUFFER_ALPHA_SIZE',
1043 'GL_RENDERBUFFER_DEPTH_SIZE',
1044 'GL_RENDERBUFFER_STENCIL_SIZE',
1045 'GL_RENDERBUFFER_WIDTH',
1046 'GL_RENDERBUFFER_HEIGHT',
1047 'GL_RENDERBUFFER_INTERNAL_FORMAT',
1050 'SamplerParameter': {
1051 'type': 'GLenum',
1052 'valid': [
1053 'GL_TEXTURE_MAG_FILTER',
1054 'GL_TEXTURE_MIN_FILTER',
1055 'GL_TEXTURE_MIN_LOD',
1056 'GL_TEXTURE_MAX_LOD',
1057 'GL_TEXTURE_WRAP_S',
1058 'GL_TEXTURE_WRAP_T',
1059 'GL_TEXTURE_WRAP_R',
1060 'GL_TEXTURE_COMPARE_MODE',
1061 'GL_TEXTURE_COMPARE_FUNC',
1063 'invalid': [
1064 'GL_GENERATE_MIPMAP',
1067 'ShaderParameter': {
1068 'type': 'GLenum',
1069 'valid': [
1070 'GL_SHADER_TYPE',
1071 'GL_DELETE_STATUS',
1072 'GL_COMPILE_STATUS',
1073 'GL_INFO_LOG_LENGTH',
1074 'GL_SHADER_SOURCE_LENGTH',
1075 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
1078 'ShaderPrecision': {
1079 'type': 'GLenum',
1080 'valid': [
1081 'GL_LOW_FLOAT',
1082 'GL_MEDIUM_FLOAT',
1083 'GL_HIGH_FLOAT',
1084 'GL_LOW_INT',
1085 'GL_MEDIUM_INT',
1086 'GL_HIGH_INT',
1089 'StringType': {
1090 'type': 'GLenum',
1091 'valid': [
1092 'GL_VENDOR',
1093 'GL_RENDERER',
1094 'GL_VERSION',
1095 'GL_SHADING_LANGUAGE_VERSION',
1096 'GL_EXTENSIONS',
1099 'TextureParameter': {
1100 'type': 'GLenum',
1101 'valid': [
1102 'GL_TEXTURE_MAG_FILTER',
1103 'GL_TEXTURE_MIN_FILTER',
1104 'GL_TEXTURE_POOL_CHROMIUM',
1105 'GL_TEXTURE_WRAP_S',
1106 'GL_TEXTURE_WRAP_T',
1108 'invalid': [
1109 'GL_GENERATE_MIPMAP',
1112 'TexturePool': {
1113 'type': 'GLenum',
1114 'valid': [
1115 'GL_TEXTURE_POOL_MANAGED_CHROMIUM',
1116 'GL_TEXTURE_POOL_UNMANAGED_CHROMIUM',
1119 'TextureWrapMode': {
1120 'type': 'GLenum',
1121 'valid': [
1122 'GL_CLAMP_TO_EDGE',
1123 'GL_MIRRORED_REPEAT',
1124 'GL_REPEAT',
1127 'TextureMinFilterMode': {
1128 'type': 'GLenum',
1129 'valid': [
1130 'GL_NEAREST',
1131 'GL_LINEAR',
1132 'GL_NEAREST_MIPMAP_NEAREST',
1133 'GL_LINEAR_MIPMAP_NEAREST',
1134 'GL_NEAREST_MIPMAP_LINEAR',
1135 'GL_LINEAR_MIPMAP_LINEAR',
1138 'TextureMagFilterMode': {
1139 'type': 'GLenum',
1140 'valid': [
1141 'GL_NEAREST',
1142 'GL_LINEAR',
1145 'TextureUsage': {
1146 'type': 'GLenum',
1147 'valid': [
1148 'GL_NONE',
1149 'GL_FRAMEBUFFER_ATTACHMENT_ANGLE',
1152 'VertexAttribute': {
1153 'type': 'GLenum',
1154 'valid': [
1155 # some enum that the decoder actually passes through to GL needs
1156 # to be the first listed here since it's used in unit tests.
1157 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED',
1158 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
1159 'GL_VERTEX_ATTRIB_ARRAY_ENABLED',
1160 'GL_VERTEX_ATTRIB_ARRAY_SIZE',
1161 'GL_VERTEX_ATTRIB_ARRAY_STRIDE',
1162 'GL_VERTEX_ATTRIB_ARRAY_TYPE',
1163 'GL_CURRENT_VERTEX_ATTRIB',
1166 'VertexPointer': {
1167 'type': 'GLenum',
1168 'valid': [
1169 'GL_VERTEX_ATTRIB_ARRAY_POINTER',
1172 'HintTarget': {
1173 'type': 'GLenum',
1174 'valid': [
1175 'GL_GENERATE_MIPMAP_HINT',
1177 'invalid': [
1178 'GL_PERSPECTIVE_CORRECTION_HINT',
1181 'HintMode': {
1182 'type': 'GLenum',
1183 'valid': [
1184 'GL_FASTEST',
1185 'GL_NICEST',
1186 'GL_DONT_CARE',
1189 'PixelStore': {
1190 'type': 'GLenum',
1191 'valid': [
1192 'GL_PACK_ALIGNMENT',
1193 'GL_UNPACK_ALIGNMENT',
1194 'GL_UNPACK_FLIP_Y_CHROMIUM',
1195 'GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM',
1196 'GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM',
1198 'invalid': [
1199 'GL_PACK_SWAP_BYTES',
1200 'GL_UNPACK_SWAP_BYTES',
1203 'PixelStoreAlignment': {
1204 'type': 'GLint',
1205 'valid': [
1206 '1',
1207 '2',
1208 '4',
1209 '8',
1211 'invalid': [
1212 '3',
1213 '9',
1216 'ReadPixelFormat': {
1217 'type': 'GLenum',
1218 'valid': [
1219 'GL_ALPHA',
1220 'GL_RGB',
1221 'GL_RGBA',
1224 'PixelType': {
1225 'type': 'GLenum',
1226 'valid': [
1227 'GL_UNSIGNED_BYTE',
1228 'GL_UNSIGNED_SHORT_5_6_5',
1229 'GL_UNSIGNED_SHORT_4_4_4_4',
1230 'GL_UNSIGNED_SHORT_5_5_5_1',
1232 'valid_es3': [
1233 'GL_BYTE',
1234 'GL_UNSIGNED_SHORT',
1235 'GL_SHORT',
1236 'GL_UNSIGNED_INT',
1237 'GL_INT',
1238 'GL_HALF_FLOAT',
1239 'GL_FLOAT',
1240 'GL_UNSIGNED_INT_2_10_10_10_REV',
1241 'GL_UNSIGNED_INT_10F_11F_11F_REV',
1242 'GL_UNSIGNED_INT_5_9_9_9_REV',
1243 'GL_UNSIGNED_INT_24_8',
1244 'GL_FLOAT_32_UNSIGNED_INT_24_8_REV',
1246 'invalid': [
1247 'GL_UNSIGNED_BYTE_3_3_2',
1250 'ReadPixelType': {
1251 'type': 'GLenum',
1252 'valid': [
1253 'GL_UNSIGNED_BYTE',
1254 'GL_UNSIGNED_SHORT_5_6_5',
1255 'GL_UNSIGNED_SHORT_4_4_4_4',
1256 'GL_UNSIGNED_SHORT_5_5_5_1',
1258 'invalid': [
1259 'GL_SHORT',
1260 'GL_INT',
1263 'RenderBufferFormat': {
1264 'type': 'GLenum',
1265 'valid': [
1266 'GL_RGBA4',
1267 'GL_RGB565',
1268 'GL_RGB5_A1',
1269 'GL_DEPTH_COMPONENT16',
1270 'GL_STENCIL_INDEX8',
1273 'ShaderBinaryFormat': {
1274 'type': 'GLenum',
1275 'valid': [
1278 'StencilOp': {
1279 'type': 'GLenum',
1280 'valid': [
1281 'GL_KEEP',
1282 'GL_ZERO',
1283 'GL_REPLACE',
1284 'GL_INCR',
1285 'GL_INCR_WRAP',
1286 'GL_DECR',
1287 'GL_DECR_WRAP',
1288 'GL_INVERT',
1291 'TextureFormat': {
1292 'type': 'GLenum',
1293 'valid': [
1294 'GL_ALPHA',
1295 'GL_LUMINANCE',
1296 'GL_LUMINANCE_ALPHA',
1297 'GL_RGB',
1298 'GL_RGBA',
1300 'valid_es3': [
1301 'GL_RED',
1302 'GL_RED_INTEGER',
1303 'GL_RG',
1304 'GL_RG_INTEGER',
1305 'GL_RGB_INTEGER',
1306 'GL_RGBA_INTEGER',
1307 'GL_DEPTH_COMPONENT',
1308 'GL_DEPTH_STENCIL',
1310 'invalid': [
1311 'GL_BGRA',
1312 'GL_BGR',
1315 'TextureInternalFormat': {
1316 'type': 'GLenum',
1317 'valid': [
1318 'GL_ALPHA',
1319 'GL_LUMINANCE',
1320 'GL_LUMINANCE_ALPHA',
1321 'GL_RGB',
1322 'GL_RGBA',
1324 'valid_es3': [
1325 'GL_R8',
1326 'GL_R8_SNORM',
1327 'GL_R16F',
1328 'GL_R32F',
1329 'GL_R8UI',
1330 'GL_R8I',
1331 'GL_R16UI',
1332 'GL_R16I',
1333 'GL_R32UI',
1334 'GL_R32I',
1335 'GL_RG8',
1336 'GL_RG8_SNORM',
1337 'GL_RG16F',
1338 'GL_RG32F',
1339 'GL_RG8UI',
1340 'GL_RG8I',
1341 'GL_RG16UI',
1342 'GL_RG16I',
1343 'GL_RG32UI',
1344 'GL_RG32I',
1345 'GL_RGB8',
1346 'GL_SRGB8',
1347 'GL_RGB565',
1348 'GL_RGB8_SNORM',
1349 'GL_R11F_G11F_B10F',
1350 'GL_RGB9_E5',
1351 'GL_RGB16F',
1352 'GL_RGB32F',
1353 'GL_RGB8UI',
1354 'GL_RGB8I',
1355 'GL_RGB16UI',
1356 'GL_RGB16I',
1357 'GL_RGB32UI',
1358 'GL_RGB32I',
1359 'GL_RGBA8',
1360 'GL_SRGB8_ALPHA8',
1361 'GL_RGBA8_SNORM',
1362 'GL_RGB5_A1',
1363 'GL_RGBA4',
1364 'GL_RGB10_A2',
1365 'GL_RGBA16F',
1366 'GL_RGBA32F',
1367 'GL_RGBA8UI',
1368 'GL_RGBA8I',
1369 'GL_RGB10_A2UI',
1370 'GL_RGBA16UI',
1371 'GL_RGBA16I',
1372 'GL_RGBA32UI',
1373 'GL_RGBA32I',
1374 # The DEPTH/STENCIL formats are not supported in CopyTexImage2D.
1375 # We will reject them dynamically in GPU command buffer.
1376 'GL_DEPTH_COMPONENT16',
1377 'GL_DEPTH_COMPONENT24',
1378 'GL_DEPTH_COMPONENT32F',
1379 'GL_DEPTH24_STENCIL8',
1380 'GL_DEPTH32F_STENCIL8',
1382 'invalid': [
1383 'GL_BGRA',
1384 'GL_BGR',
1387 'TextureInternalFormatStorage': {
1388 'type': 'GLenum',
1389 'valid': [
1390 'GL_RGB565',
1391 'GL_RGBA4',
1392 'GL_RGB5_A1',
1393 'GL_ALPHA8_EXT',
1394 'GL_LUMINANCE8_EXT',
1395 'GL_LUMINANCE8_ALPHA8_EXT',
1396 'GL_RGB8_OES',
1397 'GL_RGBA8_OES',
1399 'valid_es3': [
1400 'GL_R8',
1401 'GL_R8_SNORM',
1402 'GL_R16F',
1403 'GL_R32F',
1404 'GL_R8UI',
1405 'GL_R8I',
1406 'GL_R16UI',
1407 'GL_R16I',
1408 'GL_R32UI',
1409 'GL_R32I',
1410 'GL_RG8',
1411 'GL_RG8_SNORM',
1412 'GL_RG16F',
1413 'GL_RG32F',
1414 'GL_RG8UI',
1415 'GL_RG8I',
1416 'GL_RG16UI',
1417 'GL_RG16I',
1418 'GL_RG32UI',
1419 'GL_RG32I',
1420 'GL_SRGB8',
1421 'GL_RGB8_SNORM',
1422 'GL_R11F_G11F_B10F',
1423 'GL_RGB9_E5',
1424 'GL_RGB16F',
1425 'GL_RGB32F',
1426 'GL_RGB8UI',
1427 'GL_RGB8I',
1428 'GL_RGB16UI',
1429 'GL_RGB16I',
1430 'GL_RGB32UI',
1431 'GL_RGB32I',
1432 'GL_SRGB8_ALPHA8',
1433 'GL_RGBA8_SNORM',
1434 'GL_RGB10_A2',
1435 'GL_RGBA16F',
1436 'GL_RGBA32F',
1437 'GL_RGBA8UI',
1438 'GL_RGBA8I',
1439 'GL_RGB10_A2UI',
1440 'GL_RGBA16UI',
1441 'GL_RGBA16I',
1442 'GL_RGBA32UI',
1443 'GL_RGBA32I',
1444 'GL_DEPTH_COMPONENT16',
1445 'GL_DEPTH_COMPONENT24',
1446 'GL_DEPTH_COMPONENT32F',
1447 'GL_DEPTH24_STENCIL8',
1448 'GL_DEPTH32F_STENCIL8',
1449 'GL_COMPRESSED_R11_EAC',
1450 'GL_COMPRESSED_SIGNED_R11_EAC',
1451 'GL_COMPRESSED_RG11_EAC',
1452 'GL_COMPRESSED_SIGNED_RG11_EAC',
1453 'GL_COMPRESSED_RGB8_ETC2',
1454 'GL_COMPRESSED_SRGB8_ETC2',
1455 'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1456 'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2',
1457 'GL_COMPRESSED_RGBA8_ETC2_EAC',
1458 'GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC',
1460 'deprecated_es3': [
1461 'GL_ALPHA8_EXT',
1462 'GL_LUMINANCE8_EXT',
1463 'GL_LUMINANCE8_ALPHA8_EXT',
1464 'GL_ALPHA16F_EXT',
1465 'GL_LUMINANCE16F_EXT',
1466 'GL_LUMINANCE_ALPHA16F_EXT',
1467 'GL_ALPHA32F_EXT',
1468 'GL_LUMINANCE32F_EXT',
1469 'GL_LUMINANCE_ALPHA32F_EXT',
1472 'ImageInternalFormat': {
1473 'type': 'GLenum',
1474 'valid': [
1475 'GL_RGB',
1476 'GL_RGBA',
1479 'ImageUsage': {
1480 'type': 'GLenum',
1481 'valid': [
1482 'GL_MAP_CHROMIUM',
1483 'GL_SCANOUT_CHROMIUM'
1486 'ValueBufferTarget': {
1487 'type': 'GLenum',
1488 'valid': [
1489 'GL_SUBSCRIBED_VALUES_BUFFER_CHROMIUM',
1492 'SubscriptionTarget': {
1493 'type': 'GLenum',
1494 'valid': [
1495 'GL_MOUSE_POSITION_CHROMIUM',
1498 'UniformParameter': {
1499 'type': 'GLenum',
1500 'valid': [
1501 'GL_UNIFORM_SIZE',
1502 'GL_UNIFORM_TYPE',
1503 'GL_UNIFORM_NAME_LENGTH',
1504 'GL_UNIFORM_BLOCK_INDEX',
1505 'GL_UNIFORM_OFFSET',
1506 'GL_UNIFORM_ARRAY_STRIDE',
1507 'GL_UNIFORM_MATRIX_STRIDE',
1508 'GL_UNIFORM_IS_ROW_MAJOR',
1510 'invalid': [
1511 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1514 'UniformBlockParameter': {
1515 'type': 'GLenum',
1516 'valid': [
1517 'GL_UNIFORM_BLOCK_BINDING',
1518 'GL_UNIFORM_BLOCK_DATA_SIZE',
1519 'GL_UNIFORM_BLOCK_NAME_LENGTH',
1520 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS',
1521 'GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES',
1522 'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER',
1523 'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER',
1525 'invalid': [
1526 'GL_NEAREST',
1529 'VertexAttribType': {
1530 'type': 'GLenum',
1531 'valid': [
1532 'GL_BYTE',
1533 'GL_UNSIGNED_BYTE',
1534 'GL_SHORT',
1535 'GL_UNSIGNED_SHORT',
1536 # 'GL_FIXED', // This is not available on Desktop GL.
1537 'GL_FLOAT',
1539 'invalid': [
1540 'GL_DOUBLE',
1543 'TextureBorder': {
1544 'type': 'GLint',
1545 'is_complete': True,
1546 'valid': [
1547 '0',
1549 'invalid': [
1550 '1',
1553 'VertexAttribSize': {
1554 'type': 'GLint',
1555 'valid': [
1556 '1',
1557 '2',
1558 '3',
1559 '4',
1561 'invalid': [
1562 '0',
1563 '5',
1566 'ZeroOnly': {
1567 'type': 'GLint',
1568 'is_complete': True,
1569 'valid': [
1570 '0',
1572 'invalid': [
1573 '1',
1576 'FalseOnly': {
1577 'type': 'GLboolean',
1578 'is_complete': True,
1579 'valid': [
1580 'false',
1582 'invalid': [
1583 'true',
1586 'ResetStatus': {
1587 'type': 'GLenum',
1588 'valid': [
1589 'GL_GUILTY_CONTEXT_RESET_ARB',
1590 'GL_INNOCENT_CONTEXT_RESET_ARB',
1591 'GL_UNKNOWN_CONTEXT_RESET_ARB',
1594 'SyncCondition': {
1595 'type': 'GLenum',
1596 'is_complete': True,
1597 'valid': [
1598 'GL_SYNC_GPU_COMMANDS_COMPLETE',
1600 'invalid': [
1601 '0',
1604 'SyncFlags': {
1605 'type': 'GLbitfield',
1606 'is_complete': True,
1607 'valid': [
1608 '0',
1610 'invalid': [
1611 '1',
1614 'SyncFlushFlags': {
1615 'type': 'GLbitfield',
1616 'valid': [
1617 'GL_SYNC_FLUSH_COMMANDS_BIT',
1618 '0',
1620 'invalid': [
1621 '0xFFFFFFFF',
1624 'SyncParameter': {
1625 'type': 'GLenum',
1626 'valid': [
1627 'GL_SYNC_STATUS', # This needs to be the 1st; all others are cached.
1628 'GL_OBJECT_TYPE',
1629 'GL_SYNC_CONDITION',
1630 'GL_SYNC_FLAGS',
1632 'invalid': [
1633 'GL_SYNC_FENCE',
1638 # This table specifies the different pepper interfaces that are supported for
1639 # GL commands. 'dev' is true if it's a dev interface.
1640 _PEPPER_INTERFACES = [
1641 {'name': '', 'dev': False},
1642 {'name': 'InstancedArrays', 'dev': False},
1643 {'name': 'FramebufferBlit', 'dev': False},
1644 {'name': 'FramebufferMultisample', 'dev': False},
1645 {'name': 'ChromiumEnableFeature', 'dev': False},
1646 {'name': 'ChromiumMapSub', 'dev': False},
1647 {'name': 'Query', 'dev': False},
1648 {'name': 'VertexArrayObject', 'dev': False},
1649 {'name': 'DrawBuffers', 'dev': True},
1652 # A function info object specifies the type and other special data for the
1653 # command that will be generated. A base function info object is generated by
1654 # parsing the "cmd_buffer_functions.txt", one for each function in the
1655 # file. These function info objects can be augmented and their values can be
1656 # overridden by adding an object to the table below.
1658 # Must match function names specified in "cmd_buffer_functions.txt".
1660 # cmd_comment: A comment added to the cmd format.
1661 # type: defines which handler will be used to generate code.
1662 # decoder_func: defines which function to call in the decoder to execute the
1663 # corresponding GL command. If not specified the GL command will
1664 # be called directly.
1665 # gl_test_func: GL function that is expected to be called when testing.
1666 # cmd_args: The arguments to use for the command. This overrides generating
1667 # them based on the GL function arguments.
1668 # gen_cmd: Whether or not this function geneates a command. Default = True.
1669 # data_transfer_methods: Array of methods that are used for transfering the
1670 # pointer data. Possible values: 'immediate', 'shm', 'bucket'.
1671 # The default is 'immediate' if the command has one pointer
1672 # argument, otherwise 'shm'. One command is generated for each
1673 # transfer method. Affects only commands which are not of type
1674 # 'HandWritten', 'GETn' or 'GLcharN'.
1675 # Note: the command arguments that affect this are the final args,
1676 # taking cmd_args override into consideration.
1677 # impl_func: Whether or not to generate the GLES2Implementation part of this
1678 # command.
1679 # impl_decl: Whether or not to generate the GLES2Implementation declaration
1680 # for this command.
1681 # needs_size: If True a data_size field is added to the command.
1682 # count: The number of units per element. For PUTn or PUT types.
1683 # use_count_func: If True the actual data count needs to be computed; the count
1684 # argument specifies the maximum count.
1685 # unit_test: If False no service side unit test will be generated.
1686 # client_test: If False no client side unit test will be generated.
1687 # expectation: If False the unit test will have no expected calls.
1688 # gen_func: Name of function that generates GL resource for corresponding
1689 # bind function.
1690 # states: array of states that get set by this function corresponding to
1691 # the given arguments
1692 # state_flag: name of flag that is set to true when function is called.
1693 # no_gl: no GL function is called.
1694 # valid_args: A dictionary of argument indices to args to use in unit tests
1695 # when they can not be automatically determined.
1696 # pepper_interface: The pepper interface that is used for this extension
1697 # pepper_name: The name of the function as exposed to pepper.
1698 # pepper_args: A string representing the argument list (what would appear in
1699 # C/C++ between the parentheses for the function declaration)
1700 # that the Pepper API expects for this function. Use this only if
1701 # the stable Pepper API differs from the GLES2 argument list.
1702 # invalid_test: False if no invalid test needed.
1703 # shadowed: True = the value is shadowed so no glGetXXX call will be made.
1704 # first_element_only: For PUT types, True if only the first element of an
1705 # array is used and we end up calling the single value
1706 # corresponding function. eg. TexParameteriv -> TexParameteri
1707 # extension: Function is an extension to GL and should not be exposed to
1708 # pepper unless pepper_interface is defined.
1709 # extension_flag: Function is an extension and should be enabled only when
1710 # the corresponding feature info flag is enabled. Implies
1711 # 'extension': True.
1712 # not_shared: For GENn types, True if objects can't be shared between contexts
1713 # unsafe: True = no validation is implemented on the service side and the
1714 # command is only available with --enable-unsafe-es3-apis.
1715 # id_mapping: A list of resource type names whose client side IDs need to be
1716 # mapped to service side IDs. This is only used for unsafe APIs.
1718 _FUNCTION_INFO = {
1719 'ActiveTexture': {
1720 'decoder_func': 'DoActiveTexture',
1721 'unit_test': False,
1722 'impl_func': False,
1723 'client_test': False,
1725 'AttachShader': {'decoder_func': 'DoAttachShader'},
1726 'BindAttribLocation': {
1727 'type': 'GLchar',
1728 'data_transfer_methods': ['bucket'],
1729 'needs_size': True,
1731 'BindBuffer': {
1732 'type': 'Bind',
1733 'decoder_func': 'DoBindBuffer',
1734 'gen_func': 'GenBuffersARB',
1736 'BindBufferBase': {
1737 'type': 'Bind',
1738 'id_mapping': [ 'Buffer' ],
1739 'gen_func': 'GenBuffersARB',
1740 'unsafe': True,
1742 'BindBufferRange': {
1743 'type': 'Bind',
1744 'id_mapping': [ 'Buffer' ],
1745 'gen_func': 'GenBuffersARB',
1746 'valid_args': {
1747 '3': '4',
1748 '4': '4'
1750 'unsafe': True,
1752 'BindFramebuffer': {
1753 'type': 'Bind',
1754 'decoder_func': 'DoBindFramebuffer',
1755 'gl_test_func': 'glBindFramebufferEXT',
1756 'gen_func': 'GenFramebuffersEXT',
1757 'trace_level': 1,
1759 'BindRenderbuffer': {
1760 'type': 'Bind',
1761 'decoder_func': 'DoBindRenderbuffer',
1762 'gl_test_func': 'glBindRenderbufferEXT',
1763 'gen_func': 'GenRenderbuffersEXT',
1765 'BindSampler': {
1766 'type': 'Bind',
1767 'id_mapping': [ 'Sampler' ],
1768 'unsafe': True,
1770 'BindTexture': {
1771 'type': 'Bind',
1772 'decoder_func': 'DoBindTexture',
1773 'gen_func': 'GenTextures',
1774 # TODO(gman): remove this once client side caching works.
1775 'client_test': False,
1776 'trace_level': 1,
1778 'BindTransformFeedback': {
1779 'type': 'Bind',
1780 'id_mapping': [ 'TransformFeedback' ],
1781 'unsafe': True,
1783 'BlitFramebufferCHROMIUM': {
1784 'decoder_func': 'DoBlitFramebufferCHROMIUM',
1785 'unit_test': False,
1786 'extension_flag': 'chromium_framebuffer_multisample',
1787 'pepper_interface': 'FramebufferBlit',
1788 'pepper_name': 'BlitFramebufferEXT',
1789 'defer_reads': True,
1790 'defer_draws': True,
1791 'trace_level': 1,
1793 'BufferData': {
1794 'type': 'Manual',
1795 'data_transfer_methods': ['shm'],
1796 'client_test': False,
1798 'BufferSubData': {
1799 'type': 'Data',
1800 'client_test': False,
1801 'decoder_func': 'DoBufferSubData',
1802 'data_transfer_methods': ['shm'],
1804 'CheckFramebufferStatus': {
1805 'type': 'Is',
1806 'decoder_func': 'DoCheckFramebufferStatus',
1807 'gl_test_func': 'glCheckFramebufferStatusEXT',
1808 'error_value': 'GL_FRAMEBUFFER_UNSUPPORTED',
1809 'result': ['GLenum'],
1811 'Clear': {
1812 'decoder_func': 'DoClear',
1813 'defer_draws': True,
1814 'trace_level': 1,
1816 'ClearBufferiv': {
1817 'type': 'PUT',
1818 'use_count_func': True,
1819 'count': 4,
1820 'unsafe': True,
1822 'ClearBufferuiv': {
1823 'type': 'PUT',
1824 'count': 4,
1825 'unsafe': True,
1827 'ClearBufferfv': {
1828 'type': 'PUT',
1829 'use_count_func': True,
1830 'count': 4,
1831 'unsafe': True,
1833 'ClearBufferfi': {
1834 'unsafe': True,
1836 'ClearColor': {
1837 'type': 'StateSet',
1838 'state': 'ClearColor',
1840 'ClearDepthf': {
1841 'type': 'StateSet',
1842 'state': 'ClearDepthf',
1843 'decoder_func': 'glClearDepth',
1844 'gl_test_func': 'glClearDepth',
1845 'valid_args': {
1846 '0': '0.5f'
1849 'ClientWaitSync': {
1850 'type': 'Custom',
1851 'data_transfer_methods': ['shm'],
1852 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
1853 'GLuint timeout_0, GLuint timeout_1, GLenum* result',
1854 'unsafe': True,
1855 'result': ['GLenum'],
1857 'ColorMask': {
1858 'type': 'StateSet',
1859 'state': 'ColorMask',
1860 'no_gl': True,
1861 'expectation': False,
1863 'ConsumeTextureCHROMIUM': {
1864 'decoder_func': 'DoConsumeTextureCHROMIUM',
1865 'impl_func': False,
1866 'type': 'PUT',
1867 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
1868 'unit_test': False,
1869 'client_test': False,
1870 'extension': "CHROMIUM_texture_mailbox",
1871 'chromium': True,
1872 'trace_level': 1,
1874 'CopyBufferSubData': {
1875 'unsafe': True,
1877 'CreateAndConsumeTextureCHROMIUM': {
1878 'decoder_func': 'DoCreateAndConsumeTextureCHROMIUM',
1879 'impl_func': False,
1880 'type': 'HandWritten',
1881 'data_transfer_methods': ['immediate'],
1882 'unit_test': False,
1883 'client_test': False,
1884 'extension': "CHROMIUM_texture_mailbox",
1885 'chromium': True,
1887 'GenValuebuffersCHROMIUM': {
1888 'type': 'GENn',
1889 'gl_test_func': 'glGenValuebuffersCHROMIUM',
1890 'resource_type': 'Valuebuffer',
1891 'resource_types': 'Valuebuffers',
1892 'unit_test': False,
1893 'extension': True,
1894 'chromium': True,
1896 'DeleteValuebuffersCHROMIUM': {
1897 'type': 'DELn',
1898 'gl_test_func': 'glDeleteValuebuffersCHROMIUM',
1899 'resource_type': 'Valuebuffer',
1900 'resource_types': 'Valuebuffers',
1901 'unit_test': False,
1902 'extension': True,
1903 'chromium': True,
1905 'IsValuebufferCHROMIUM': {
1906 'type': 'Is',
1907 'decoder_func': 'DoIsValuebufferCHROMIUM',
1908 'expectation': False,
1909 'extension': True,
1910 'chromium': True,
1912 'BindValuebufferCHROMIUM': {
1913 'type': 'Bind',
1914 'decoder_func': 'DoBindValueBufferCHROMIUM',
1915 'gen_func': 'GenValueBuffersCHROMIUM',
1916 'unit_test': False,
1917 'extension': True,
1918 'chromium': True,
1920 'SubscribeValueCHROMIUM': {
1921 'decoder_func': 'DoSubscribeValueCHROMIUM',
1922 'unit_test': False,
1923 'extension': True,
1924 'chromium': True,
1926 'PopulateSubscribedValuesCHROMIUM': {
1927 'decoder_func': 'DoPopulateSubscribedValuesCHROMIUM',
1928 'unit_test': False,
1929 'extension': True,
1930 'chromium': True,
1932 'UniformValuebufferCHROMIUM': {
1933 'decoder_func': 'DoUniformValueBufferCHROMIUM',
1934 'unit_test': False,
1935 'extension': True,
1936 'chromium': True,
1938 'ClearStencil': {
1939 'type': 'StateSet',
1940 'state': 'ClearStencil',
1942 'EnableFeatureCHROMIUM': {
1943 'type': 'Custom',
1944 'data_transfer_methods': ['shm'],
1945 'decoder_func': 'DoEnableFeatureCHROMIUM',
1946 'expectation': False,
1947 'cmd_args': 'GLuint bucket_id, GLint* result',
1948 'result': ['GLint'],
1949 'extension': True,
1950 'chromium': True,
1951 'pepper_interface': 'ChromiumEnableFeature',
1953 'CompileShader': {'decoder_func': 'DoCompileShader', 'unit_test': False},
1954 'CompressedTexImage2D': {
1955 'type': 'Manual',
1956 'data_transfer_methods': ['bucket', 'shm'],
1958 'CompressedTexSubImage2D': {
1959 'type': 'Data',
1960 'data_transfer_methods': ['bucket', 'shm'],
1961 'decoder_func': 'DoCompressedTexSubImage2D',
1963 'CopyTexImage2D': {
1964 'decoder_func': 'DoCopyTexImage2D',
1965 'unit_test': False,
1966 'defer_reads': True,
1968 'CopyTexSubImage2D': {
1969 'decoder_func': 'DoCopyTexSubImage2D',
1970 'defer_reads': True,
1972 'CopyTexSubImage3D': {
1973 'defer_reads': True,
1974 'unsafe': True,
1976 'CreateImageCHROMIUM': {
1977 'type': 'Manual',
1978 'cmd_args':
1979 'ClientBuffer buffer, GLsizei width, GLsizei height, '
1980 'GLenum internalformat',
1981 'result': ['GLuint'],
1982 'client_test': False,
1983 'gen_cmd': False,
1984 'expectation': False,
1985 'extension': True,
1986 'chromium': True,
1988 'DestroyImageCHROMIUM': {
1989 'type': 'Manual',
1990 'client_test': False,
1991 'gen_cmd': False,
1992 'extension': True,
1993 'chromium': True,
1995 'CreateGpuMemoryBufferImageCHROMIUM': {
1996 'type': 'Manual',
1997 'cmd_args':
1998 'GLsizei width, GLsizei height, GLenum internalformat, GLenum usage',
1999 'result': ['GLuint'],
2000 'client_test': False,
2001 'gen_cmd': False,
2002 'expectation': False,
2003 'extension': True,
2004 'chromium': True,
2006 'CreateProgram': {
2007 'type': 'Create',
2008 'client_test': False,
2010 'CreateShader': {
2011 'type': 'Create',
2012 'client_test': False,
2014 'BlendColor': {
2015 'type': 'StateSet',
2016 'state': 'BlendColor',
2018 'BlendEquation': {
2019 'type': 'StateSetRGBAlpha',
2020 'state': 'BlendEquation',
2021 'valid_args': {
2022 '0': 'GL_FUNC_SUBTRACT'
2025 'BlendEquationSeparate': {
2026 'type': 'StateSet',
2027 'state': 'BlendEquation',
2028 'valid_args': {
2029 '0': 'GL_FUNC_SUBTRACT'
2032 'BlendFunc': {
2033 'type': 'StateSetRGBAlpha',
2034 'state': 'BlendFunc',
2036 'BlendFuncSeparate': {
2037 'type': 'StateSet',
2038 'state': 'BlendFunc',
2040 'BlendBarrierKHR': {
2041 'gl_test_func': 'glBlendBarrierKHR',
2042 'extension': True,
2043 'extension_flag': 'blend_equation_advanced',
2044 'client_test': False,
2046 'SampleCoverage': {'decoder_func': 'DoSampleCoverage'},
2047 'StencilFunc': {
2048 'type': 'StateSetFrontBack',
2049 'state': 'StencilFunc',
2051 'StencilFuncSeparate': {
2052 'type': 'StateSetFrontBackSeparate',
2053 'state': 'StencilFunc',
2055 'StencilOp': {
2056 'type': 'StateSetFrontBack',
2057 'state': 'StencilOp',
2058 'valid_args': {
2059 '1': 'GL_INCR'
2062 'StencilOpSeparate': {
2063 'type': 'StateSetFrontBackSeparate',
2064 'state': 'StencilOp',
2065 'valid_args': {
2066 '1': 'GL_INCR'
2069 'Hint': {
2070 'type': 'StateSetNamedParameter',
2071 'state': 'Hint',
2073 'CullFace': {'type': 'StateSet', 'state': 'CullFace'},
2074 'FrontFace': {'type': 'StateSet', 'state': 'FrontFace'},
2075 'DepthFunc': {'type': 'StateSet', 'state': 'DepthFunc'},
2076 'LineWidth': {
2077 'type': 'StateSet',
2078 'state': 'LineWidth',
2079 'valid_args': {
2080 '0': '0.5f'
2083 'PolygonOffset': {
2084 'type': 'StateSet',
2085 'state': 'PolygonOffset',
2087 'DeleteBuffers': {
2088 'type': 'DELn',
2089 'gl_test_func': 'glDeleteBuffersARB',
2090 'resource_type': 'Buffer',
2091 'resource_types': 'Buffers',
2093 'DeleteFramebuffers': {
2094 'type': 'DELn',
2095 'gl_test_func': 'glDeleteFramebuffersEXT',
2096 'resource_type': 'Framebuffer',
2097 'resource_types': 'Framebuffers',
2099 'DeleteProgram': { 'type': 'Delete' },
2100 'DeleteRenderbuffers': {
2101 'type': 'DELn',
2102 'gl_test_func': 'glDeleteRenderbuffersEXT',
2103 'resource_type': 'Renderbuffer',
2104 'resource_types': 'Renderbuffers',
2106 'DeleteSamplers': {
2107 'type': 'DELn',
2108 'resource_type': 'Sampler',
2109 'resource_types': 'Samplers',
2110 'unsafe': True,
2112 'DeleteShader': { 'type': 'Delete' },
2113 'DeleteSync': {
2114 'type': 'Delete',
2115 'cmd_args': 'GLuint sync',
2116 'resource_type': 'Sync',
2117 'unsafe': True,
2119 'DeleteTextures': {
2120 'type': 'DELn',
2121 'resource_type': 'Texture',
2122 'resource_types': 'Textures',
2124 'DeleteTransformFeedbacks': {
2125 'type': 'DELn',
2126 'resource_type': 'TransformFeedback',
2127 'resource_types': 'TransformFeedbacks',
2128 'unsafe': True,
2130 'DepthRangef': {
2131 'decoder_func': 'DoDepthRangef',
2132 'gl_test_func': 'glDepthRange',
2134 'DepthMask': {
2135 'type': 'StateSet',
2136 'state': 'DepthMask',
2137 'no_gl': True,
2138 'expectation': False,
2140 'DetachShader': {'decoder_func': 'DoDetachShader'},
2141 'Disable': {
2142 'decoder_func': 'DoDisable',
2143 'impl_func': False,
2144 'client_test': False,
2146 'DisableVertexAttribArray': {
2147 'decoder_func': 'DoDisableVertexAttribArray',
2148 'impl_decl': False,
2150 'DrawArrays': {
2151 'type': 'Manual',
2152 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count',
2153 'defer_draws': True,
2154 'trace_level': 2,
2156 'DrawElements': {
2157 'type': 'Manual',
2158 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
2159 'GLenumIndexType type, GLuint index_offset',
2160 'client_test': False,
2161 'defer_draws': True,
2162 'trace_level': 2,
2164 'DrawRangeElements': {
2165 'type': 'Manual',
2166 'gen_cmd': 'False',
2167 'unsafe': True,
2169 'Enable': {
2170 'decoder_func': 'DoEnable',
2171 'impl_func': False,
2172 'client_test': False,
2174 'EnableVertexAttribArray': {
2175 'decoder_func': 'DoEnableVertexAttribArray',
2176 'impl_decl': False,
2178 'FenceSync': {
2179 'type': 'Create',
2180 'client_test': False,
2181 'unsafe': True,
2183 'Finish': {
2184 'impl_func': False,
2185 'client_test': False,
2186 'decoder_func': 'DoFinish',
2187 'defer_reads': True,
2189 'Flush': {
2190 'impl_func': False,
2191 'decoder_func': 'DoFlush',
2193 'FramebufferRenderbuffer': {
2194 'decoder_func': 'DoFramebufferRenderbuffer',
2195 'gl_test_func': 'glFramebufferRenderbufferEXT',
2197 'FramebufferTexture2D': {
2198 'decoder_func': 'DoFramebufferTexture2D',
2199 'gl_test_func': 'glFramebufferTexture2DEXT',
2200 'trace_level': 1,
2202 'FramebufferTexture2DMultisampleEXT': {
2203 'decoder_func': 'DoFramebufferTexture2DMultisample',
2204 'gl_test_func': 'glFramebufferTexture2DMultisampleEXT',
2205 'expectation': False,
2206 'unit_test': False,
2207 'extension_flag': 'multisampled_render_to_texture',
2208 'trace_level': 1,
2210 'FramebufferTextureLayer': {
2211 'decoder_func': 'DoFramebufferTextureLayer',
2212 'unsafe': True,
2214 'GenerateMipmap': {
2215 'decoder_func': 'DoGenerateMipmap',
2216 'gl_test_func': 'glGenerateMipmapEXT',
2218 'GenBuffers': {
2219 'type': 'GENn',
2220 'gl_test_func': 'glGenBuffersARB',
2221 'resource_type': 'Buffer',
2222 'resource_types': 'Buffers',
2224 'GenMailboxCHROMIUM': {
2225 'type': 'HandWritten',
2226 'impl_func': False,
2227 'extension': "CHROMIUM_texture_mailbox",
2228 'chromium': True,
2230 'GenFramebuffers': {
2231 'type': 'GENn',
2232 'gl_test_func': 'glGenFramebuffersEXT',
2233 'resource_type': 'Framebuffer',
2234 'resource_types': 'Framebuffers',
2236 'GenRenderbuffers': {
2237 'type': 'GENn', 'gl_test_func': 'glGenRenderbuffersEXT',
2238 'resource_type': 'Renderbuffer',
2239 'resource_types': 'Renderbuffers',
2241 'GenSamplers': {
2242 'type': 'GENn',
2243 'gl_test_func': 'glGenSamplers',
2244 'resource_type': 'Sampler',
2245 'resource_types': 'Samplers',
2246 'unsafe': True,
2248 'GenTextures': {
2249 'type': 'GENn',
2250 'gl_test_func': 'glGenTextures',
2251 'resource_type': 'Texture',
2252 'resource_types': 'Textures',
2254 'GenTransformFeedbacks': {
2255 'type': 'GENn',
2256 'gl_test_func': 'glGenTransformFeedbacks',
2257 'resource_type': 'TransformFeedback',
2258 'resource_types': 'TransformFeedbacks',
2259 'unsafe': True,
2261 'GetActiveAttrib': {
2262 'type': 'Custom',
2263 'data_transfer_methods': ['shm'],
2264 'cmd_args':
2265 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2266 'void* result',
2267 'result': [
2268 'int32_t success',
2269 'int32_t size',
2270 'uint32_t type',
2273 'GetActiveUniform': {
2274 'type': 'Custom',
2275 'data_transfer_methods': ['shm'],
2276 'cmd_args':
2277 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2278 'void* result',
2279 'result': [
2280 'int32_t success',
2281 'int32_t size',
2282 'uint32_t type',
2285 'GetActiveUniformBlockiv': {
2286 'type': 'Custom',
2287 'data_transfer_methods': ['shm'],
2288 'result': ['SizedResult<GLint>'],
2289 'unsafe': True,
2291 'GetActiveUniformBlockName': {
2292 'type': 'Custom',
2293 'data_transfer_methods': ['shm'],
2294 'cmd_args':
2295 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2296 'void* result',
2297 'result': ['int32_t'],
2298 'unsafe': True,
2300 'GetActiveUniformsiv': {
2301 'type': 'Custom',
2302 'data_transfer_methods': ['shm'],
2303 'cmd_args':
2304 'GLidProgram program, uint32_t indices_bucket_id, GLenum pname, '
2305 'GLint* params',
2306 'result': ['SizedResult<GLint>'],
2307 'unsafe': True,
2309 'GetAttachedShaders': {
2310 'type': 'Custom',
2311 'data_transfer_methods': ['shm'],
2312 'cmd_args': 'GLidProgram program, void* result, uint32_t result_size',
2313 'result': ['SizedResult<GLuint>'],
2315 'GetAttribLocation': {
2316 'type': 'Custom',
2317 'data_transfer_methods': ['shm'],
2318 'cmd_args':
2319 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2320 'result': ['GLint'],
2321 'error_return': -1,
2323 'GetFragDataLocation': {
2324 'type': 'Custom',
2325 'data_transfer_methods': ['shm'],
2326 'cmd_args':
2327 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2328 'result': ['GLint'],
2329 'error_return': -1,
2330 'unsafe': True,
2332 'GetBooleanv': {
2333 'type': 'GETn',
2334 'result': ['SizedResult<GLboolean>'],
2335 'decoder_func': 'DoGetBooleanv',
2336 'gl_test_func': 'glGetBooleanv',
2338 'GetBufferParameteriv': {
2339 'type': 'GETn',
2340 'result': ['SizedResult<GLint>'],
2341 'decoder_func': 'DoGetBufferParameteriv',
2342 'expectation': False,
2343 'shadowed': True,
2345 'GetError': {
2346 'type': 'Is',
2347 'decoder_func': 'GetErrorState()->GetGLError',
2348 'impl_func': False,
2349 'result': ['GLenum'],
2350 'client_test': False,
2352 'GetFloatv': {
2353 'type': 'GETn',
2354 'result': ['SizedResult<GLfloat>'],
2355 'decoder_func': 'DoGetFloatv',
2356 'gl_test_func': 'glGetFloatv',
2358 'GetFramebufferAttachmentParameteriv': {
2359 'type': 'GETn',
2360 'decoder_func': 'DoGetFramebufferAttachmentParameteriv',
2361 'gl_test_func': 'glGetFramebufferAttachmentParameterivEXT',
2362 'result': ['SizedResult<GLint>'],
2364 'GetIntegerv': {
2365 'type': 'GETn',
2366 'result': ['SizedResult<GLint>'],
2367 'decoder_func': 'DoGetIntegerv',
2368 'client_test': False,
2370 'GetInternalformativ': {
2371 'type': 'GETn',
2372 'result': ['SizedResult<GLint>'],
2373 'unsafe': True,
2375 'GetMaxValueInBufferCHROMIUM': {
2376 'type': 'Is',
2377 'decoder_func': 'DoGetMaxValueInBufferCHROMIUM',
2378 'result': ['GLuint'],
2379 'unit_test': False,
2380 'client_test': False,
2381 'extension': True,
2382 'chromium': True,
2383 'impl_func': False,
2385 'GetProgramiv': {
2386 'type': 'GETn',
2387 'decoder_func': 'DoGetProgramiv',
2388 'result': ['SizedResult<GLint>'],
2389 'expectation': False,
2391 'GetProgramInfoCHROMIUM': {
2392 'type': 'Custom',
2393 'expectation': False,
2394 'impl_func': False,
2395 'extension': True,
2396 'chromium': True,
2397 'client_test': False,
2398 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2399 'result': [
2400 'uint32_t link_status',
2401 'uint32_t num_attribs',
2402 'uint32_t num_uniforms',
2405 'GetProgramInfoLog': {
2406 'type': 'STRn',
2407 'expectation': False,
2409 'GetRenderbufferParameteriv': {
2410 'type': 'GETn',
2411 'decoder_func': 'DoGetRenderbufferParameteriv',
2412 'gl_test_func': 'glGetRenderbufferParameterivEXT',
2413 'result': ['SizedResult<GLint>'],
2415 'GetSamplerParameterfv': {
2416 'type': 'GETn',
2417 'result': ['SizedResult<GLfloat>'],
2418 'id_mapping': [ 'Sampler' ],
2419 'unsafe': True,
2421 'GetSamplerParameteriv': {
2422 'type': 'GETn',
2423 'result': ['SizedResult<GLint>'],
2424 'id_mapping': [ 'Sampler' ],
2425 'unsafe': True,
2427 'GetShaderiv': {
2428 'type': 'GETn',
2429 'decoder_func': 'DoGetShaderiv',
2430 'result': ['SizedResult<GLint>'],
2432 'GetShaderInfoLog': {
2433 'type': 'STRn',
2434 'get_len_func': 'glGetShaderiv',
2435 'get_len_enum': 'GL_INFO_LOG_LENGTH',
2436 'unit_test': False,
2438 'GetShaderPrecisionFormat': {
2439 'type': 'Custom',
2440 'data_transfer_methods': ['shm'],
2441 'cmd_args':
2442 'GLenumShaderType shadertype, GLenumShaderPrecision precisiontype, '
2443 'void* result',
2444 'result': [
2445 'int32_t success',
2446 'int32_t min_range',
2447 'int32_t max_range',
2448 'int32_t precision',
2451 'GetShaderSource': {
2452 'type': 'STRn',
2453 'get_len_func': 'DoGetShaderiv',
2454 'get_len_enum': 'GL_SHADER_SOURCE_LENGTH',
2455 'unit_test': False,
2456 'client_test': False,
2458 'GetString': {
2459 'type': 'Custom',
2460 'client_test': False,
2461 'cmd_args': 'GLenumStringType name, uint32_t bucket_id',
2463 'GetSynciv': {
2464 'type': 'GETn',
2465 'cmd_args': 'GLuint sync, GLenumSyncParameter pname, void* values',
2466 'result': ['SizedResult<GLint>'],
2467 'id_mapping': ['Sync'],
2468 'unsafe': True,
2470 'GetTexParameterfv': {
2471 'type': 'GETn',
2472 'decoder_func': 'DoGetTexParameterfv',
2473 'result': ['SizedResult<GLfloat>']
2475 'GetTexParameteriv': {
2476 'type': 'GETn',
2477 'decoder_func': 'DoGetTexParameteriv',
2478 'result': ['SizedResult<GLint>']
2480 'GetTranslatedShaderSourceANGLE': {
2481 'type': 'STRn',
2482 'get_len_func': 'DoGetShaderiv',
2483 'get_len_enum': 'GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE',
2484 'unit_test': False,
2485 'extension': True,
2487 'GetUniformBlockIndex': {
2488 'type': 'Custom',
2489 'data_transfer_methods': ['shm'],
2490 'cmd_args':
2491 'GLidProgram program, uint32_t name_bucket_id, GLuint* index',
2492 'result': ['GLuint'],
2493 'error_return': 'GL_INVALID_INDEX',
2494 'unsafe': True,
2496 'GetUniformBlocksCHROMIUM': {
2497 'type': 'Custom',
2498 'expectation': False,
2499 'impl_func': False,
2500 'extension': True,
2501 'chromium': True,
2502 'client_test': False,
2503 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2504 'result': ['uint32_t'],
2505 'unsafe': True,
2507 'GetUniformsES3CHROMIUM': {
2508 'type': 'Custom',
2509 'expectation': False,
2510 'impl_func': False,
2511 'extension': True,
2512 'chromium': True,
2513 'client_test': False,
2514 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2515 'result': ['uint32_t'],
2516 'unsafe': True,
2518 'GetTransformFeedbackVarying': {
2519 'type': 'Custom',
2520 'data_transfer_methods': ['shm'],
2521 'cmd_args':
2522 'GLidProgram program, GLuint index, uint32_t name_bucket_id, '
2523 'void* result',
2524 'result': [
2525 'int32_t success',
2526 'int32_t size',
2527 'uint32_t type',
2529 'unsafe': True,
2531 'GetTransformFeedbackVaryingsCHROMIUM': {
2532 'type': 'Custom',
2533 'expectation': False,
2534 'impl_func': False,
2535 'extension': True,
2536 'chromium': True,
2537 'client_test': False,
2538 'cmd_args': 'GLidProgram program, uint32_t bucket_id',
2539 'result': ['uint32_t'],
2540 'unsafe': True,
2542 'GetUniformfv': {
2543 'type': 'Custom',
2544 'data_transfer_methods': ['shm'],
2545 'result': ['SizedResult<GLfloat>'],
2547 'GetUniformiv': {
2548 'type': 'Custom',
2549 'data_transfer_methods': ['shm'],
2550 'result': ['SizedResult<GLint>'],
2552 'GetUniformIndices': {
2553 'type': 'Custom',
2554 'data_transfer_methods': ['shm'],
2555 'result': ['SizedResult<GLuint>'],
2556 'cmd_args': 'GLidProgram program, uint32_t names_bucket_id, '
2557 'GLuint* indices',
2558 'unsafe': True,
2560 'GetUniformLocation': {
2561 'type': 'Custom',
2562 'data_transfer_methods': ['shm'],
2563 'cmd_args':
2564 'GLidProgram program, uint32_t name_bucket_id, GLint* location',
2565 'result': ['GLint'],
2566 'error_return': -1, # http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml
2568 'GetVertexAttribfv': {
2569 'type': 'GETn',
2570 'result': ['SizedResult<GLfloat>'],
2571 'impl_decl': False,
2572 'decoder_func': 'DoGetVertexAttribfv',
2573 'expectation': False,
2574 'client_test': False,
2576 'GetVertexAttribiv': {
2577 'type': 'GETn',
2578 'result': ['SizedResult<GLint>'],
2579 'impl_decl': False,
2580 'decoder_func': 'DoGetVertexAttribiv',
2581 'expectation': False,
2582 'client_test': False,
2584 'GetVertexAttribPointerv': {
2585 'type': 'Custom',
2586 'data_transfer_methods': ['shm'],
2587 'result': ['SizedResult<GLuint>'],
2588 'client_test': False,
2590 'InvalidateFramebuffer': {
2591 'type': 'PUTn',
2592 'count': 1,
2593 'client_test': False,
2594 'unit_test': False,
2595 'unsafe': True,
2597 'InvalidateSubFramebuffer': {
2598 'type': 'PUTn',
2599 'count': 1,
2600 'client_test': False,
2601 'unit_test': False,
2602 'unsafe': True,
2604 'IsBuffer': {
2605 'type': 'Is',
2606 'decoder_func': 'DoIsBuffer',
2607 'expectation': False,
2609 'IsEnabled': {
2610 'type': 'Is',
2611 'decoder_func': 'DoIsEnabled',
2612 'client_test': False,
2613 'impl_func': False,
2614 'expectation': False,
2616 'IsFramebuffer': {
2617 'type': 'Is',
2618 'decoder_func': 'DoIsFramebuffer',
2619 'expectation': False,
2621 'IsProgram': {
2622 'type': 'Is',
2623 'decoder_func': 'DoIsProgram',
2624 'expectation': False,
2626 'IsRenderbuffer': {
2627 'type': 'Is',
2628 'decoder_func': 'DoIsRenderbuffer',
2629 'expectation': False,
2631 'IsShader': {
2632 'type': 'Is',
2633 'decoder_func': 'DoIsShader',
2634 'expectation': False,
2636 'IsSampler': {
2637 'type': 'Is',
2638 'id_mapping': [ 'Sampler' ],
2639 'expectation': False,
2640 'unsafe': True,
2642 'IsSync': {
2643 'type': 'Is',
2644 'id_mapping': [ 'Sync' ],
2645 'cmd_args': 'GLuint sync',
2646 'expectation': False,
2647 'unsafe': True,
2649 'IsTexture': {
2650 'type': 'Is',
2651 'decoder_func': 'DoIsTexture',
2652 'expectation': False,
2654 'IsTransformFeedback': {
2655 'type': 'Is',
2656 'id_mapping': [ 'TransformFeedback' ],
2657 'expectation': False,
2658 'unsafe': True,
2660 'LinkProgram': {
2661 'decoder_func': 'DoLinkProgram',
2662 'impl_func': False,
2664 'MapBufferCHROMIUM': {
2665 'gen_cmd': False,
2666 'extension': True,
2667 'chromium': True,
2668 'client_test': False,
2670 'MapBufferSubDataCHROMIUM': {
2671 'gen_cmd': False,
2672 'extension': True,
2673 'chromium': True,
2674 'client_test': False,
2675 'pepper_interface': 'ChromiumMapSub',
2677 'MapTexSubImage2DCHROMIUM': {
2678 'gen_cmd': False,
2679 'extension': True,
2680 'chromium': True,
2681 'client_test': False,
2682 'pepper_interface': 'ChromiumMapSub',
2684 'MapBufferRange': {
2685 'type': 'Custom',
2686 'data_transfer_methods': ['shm'],
2687 'cmd_args': 'GLenumBufferTarget target, GLintptrNotNegative offset, '
2688 'GLsizeiptr size, GLbitfieldMapBufferAccess access, '
2689 'uint32_t data_shm_id, uint32_t data_shm_offset, '
2690 'uint32_t result_shm_id, uint32_t result_shm_offset',
2691 'unsafe': True,
2692 'result': ['uint32_t'],
2694 'PauseTransformFeedback': {
2695 'unsafe': True,
2697 'PixelStorei': {'type': 'Manual'},
2698 'PostSubBufferCHROMIUM': {
2699 'type': 'Custom',
2700 'impl_func': False,
2701 'unit_test': False,
2702 'client_test': False,
2703 'extension': True,
2704 'chromium': True,
2706 'ProduceTextureCHROMIUM': {
2707 'decoder_func': 'DoProduceTextureCHROMIUM',
2708 'impl_func': False,
2709 'type': 'PUT',
2710 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2711 'unit_test': False,
2712 'client_test': False,
2713 'extension': "CHROMIUM_texture_mailbox",
2714 'chromium': True,
2715 'trace_level': 1,
2717 'ProduceTextureDirectCHROMIUM': {
2718 'decoder_func': 'DoProduceTextureDirectCHROMIUM',
2719 'impl_func': False,
2720 'type': 'PUT',
2721 'count': 64, # GL_MAILBOX_SIZE_CHROMIUM
2722 'unit_test': False,
2723 'client_test': False,
2724 'extension': "CHROMIUM_texture_mailbox",
2725 'chromium': True,
2726 'trace_level': 1,
2728 'RenderbufferStorage': {
2729 'decoder_func': 'DoRenderbufferStorage',
2730 'gl_test_func': 'glRenderbufferStorageEXT',
2731 'expectation': False,
2733 'RenderbufferStorageMultisampleCHROMIUM': {
2734 'cmd_comment':
2735 '// GL_CHROMIUM_framebuffer_multisample\n',
2736 'decoder_func': 'DoRenderbufferStorageMultisampleCHROMIUM',
2737 'gl_test_func': 'glRenderbufferStorageMultisampleCHROMIUM',
2738 'expectation': False,
2739 'unit_test': False,
2740 'extension_flag': 'chromium_framebuffer_multisample',
2741 'pepper_interface': 'FramebufferMultisample',
2742 'pepper_name': 'RenderbufferStorageMultisampleEXT',
2744 'RenderbufferStorageMultisampleEXT': {
2745 'cmd_comment':
2746 '// GL_EXT_multisampled_render_to_texture\n',
2747 'decoder_func': 'DoRenderbufferStorageMultisampleEXT',
2748 'gl_test_func': 'glRenderbufferStorageMultisampleEXT',
2749 'expectation': False,
2750 'unit_test': False,
2751 'extension_flag': 'multisampled_render_to_texture',
2753 'ReadBuffer': {
2754 'unsafe': True,
2756 'ReadPixels': {
2757 'cmd_comment':
2758 '// ReadPixels has the result separated from the pixel buffer so that\n'
2759 '// it is easier to specify the result going to some specific place\n'
2760 '// that exactly fits the rectangle of pixels.\n',
2761 'type': 'Custom',
2762 'data_transfer_methods': ['shm'],
2763 'impl_func': False,
2764 'client_test': False,
2765 'cmd_args':
2766 'GLint x, GLint y, GLsizei width, GLsizei height, '
2767 'GLenumReadPixelFormat format, GLenumReadPixelType type, '
2768 'uint32_t pixels_shm_id, uint32_t pixels_shm_offset, '
2769 'uint32_t result_shm_id, uint32_t result_shm_offset, '
2770 'GLboolean async',
2771 'result': ['uint32_t'],
2772 'defer_reads': True,
2774 'ReleaseShaderCompiler': {
2775 'decoder_func': 'DoReleaseShaderCompiler',
2776 'unit_test': False,
2778 'ResumeTransformFeedback': {
2779 'unsafe': True,
2781 'SamplerParameterf': {
2782 'valid_args': {
2783 '2': 'GL_NEAREST'
2785 'id_mapping': [ 'Sampler' ],
2786 'unsafe': True,
2788 'SamplerParameterfv': {
2789 'type': 'PUT',
2790 'data_value': 'GL_NEAREST',
2791 'count': 1,
2792 'gl_test_func': 'glSamplerParameterf',
2793 'decoder_func': 'DoSamplerParameterfv',
2794 'first_element_only': True,
2795 'id_mapping': [ 'Sampler' ],
2796 'unsafe': True,
2798 'SamplerParameteri': {
2799 'valid_args': {
2800 '2': 'GL_NEAREST'
2802 'id_mapping': [ 'Sampler' ],
2803 'unsafe': True,
2805 'SamplerParameteriv': {
2806 'type': 'PUT',
2807 'data_value': 'GL_NEAREST',
2808 'count': 1,
2809 'gl_test_func': 'glSamplerParameteri',
2810 'decoder_func': 'DoSamplerParameteriv',
2811 'first_element_only': True,
2812 'unsafe': True,
2814 'ShaderBinary': {
2815 'type': 'Custom',
2816 'client_test': False,
2818 'ShaderSource': {
2819 'type': 'PUTSTR',
2820 'decoder_func': 'DoShaderSource',
2821 'expectation': False,
2822 'data_transfer_methods': ['bucket'],
2823 'cmd_args':
2824 'GLuint shader, const char** str',
2825 'pepper_args':
2826 'GLuint shader, GLsizei count, const char** str, const GLint* length',
2828 'StencilMask': {
2829 'type': 'StateSetFrontBack',
2830 'state': 'StencilMask',
2831 'no_gl': True,
2832 'expectation': False,
2834 'StencilMaskSeparate': {
2835 'type': 'StateSetFrontBackSeparate',
2836 'state': 'StencilMask',
2837 'no_gl': True,
2838 'expectation': False,
2840 'SwapBuffers': {
2841 'impl_func': False,
2842 'decoder_func': 'DoSwapBuffers',
2843 'unit_test': False,
2844 'client_test': False,
2845 'extension': True,
2846 'trace_level': 1,
2848 'SwapInterval': {
2849 'impl_func': False,
2850 'decoder_func': 'DoSwapInterval',
2851 'unit_test': False,
2852 'client_test': False,
2853 'extension': True,
2854 'trace_level': 1,
2856 'TexImage2D': {
2857 'type': 'Manual',
2858 'data_transfer_methods': ['shm'],
2859 'client_test': False,
2861 'TexImage3D': {
2862 'type': 'Manual',
2863 'data_transfer_methods': ['shm'],
2864 'client_test': False,
2865 'unsafe': True,
2867 'TexParameterf': {
2868 'decoder_func': 'DoTexParameterf',
2869 'valid_args': {
2870 '2': 'GL_NEAREST'
2873 'TexParameteri': {
2874 'decoder_func': 'DoTexParameteri',
2875 'valid_args': {
2876 '2': 'GL_NEAREST'
2879 'TexParameterfv': {
2880 'type': 'PUT',
2881 'data_value': 'GL_NEAREST',
2882 'count': 1,
2883 'decoder_func': 'DoTexParameterfv',
2884 'gl_test_func': 'glTexParameterf',
2885 'first_element_only': True,
2887 'TexParameteriv': {
2888 'type': 'PUT',
2889 'data_value': 'GL_NEAREST',
2890 'count': 1,
2891 'decoder_func': 'DoTexParameteriv',
2892 'gl_test_func': 'glTexParameteri',
2893 'first_element_only': True,
2895 'TexStorage3D': {
2896 'unsafe': True,
2898 'TexSubImage2D': {
2899 'type': 'Manual',
2900 'data_transfer_methods': ['shm'],
2901 'client_test': False,
2902 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2903 'GLint xoffset, GLint yoffset, '
2904 'GLsizei width, GLsizei height, '
2905 'GLenumTextureFormat format, GLenumPixelType type, '
2906 'const void* pixels, GLboolean internal'
2908 'TexSubImage3D': {
2909 'type': 'Manual',
2910 'data_transfer_methods': ['shm'],
2911 'client_test': False,
2912 'cmd_args': 'GLenumTextureTarget target, GLint level, '
2913 'GLint xoffset, GLint yoffset, GLint zoffset, '
2914 'GLsizei width, GLsizei height, GLsizei depth, '
2915 'GLenumTextureFormat format, GLenumPixelType type, '
2916 'const void* pixels, GLboolean internal',
2917 'unsafe': True,
2919 'TransformFeedbackVaryings': {
2920 'type': 'PUTSTR',
2921 'data_transfer_methods': ['bucket'],
2922 'decoder_func': 'DoTransformFeedbackVaryings',
2923 'cmd_args':
2924 'GLuint program, const char** varyings, GLenum buffermode',
2925 'unsafe': True,
2927 'Uniform1f': {'type': 'PUTXn', 'count': 1},
2928 'Uniform1fv': {
2929 'type': 'PUTn',
2930 'count': 1,
2931 'decoder_func': 'DoUniform1fv',
2933 'Uniform1i': {'decoder_func': 'DoUniform1i', 'unit_test': False},
2934 'Uniform1iv': {
2935 'type': 'PUTn',
2936 'count': 1,
2937 'decoder_func': 'DoUniform1iv',
2938 'unit_test': False,
2940 'Uniform1ui': {
2941 'type': 'PUTXn',
2942 'count': 1,
2943 'unsafe': True,
2945 'Uniform1uiv': {
2946 'type': 'PUTn',
2947 'count': 1,
2948 'unsafe': True,
2950 'Uniform2i': {'type': 'PUTXn', 'count': 2},
2951 'Uniform2f': {'type': 'PUTXn', 'count': 2},
2952 'Uniform2fv': {
2953 'type': 'PUTn',
2954 'count': 2,
2955 'decoder_func': 'DoUniform2fv',
2957 'Uniform2iv': {
2958 'type': 'PUTn',
2959 'count': 2,
2960 'decoder_func': 'DoUniform2iv',
2962 'Uniform2ui': {
2963 'type': 'PUTXn',
2964 'count': 2,
2965 'unsafe': True,
2967 'Uniform2uiv': {
2968 'type': 'PUTn',
2969 'count': 2,
2970 'unsafe': True,
2972 'Uniform3i': {'type': 'PUTXn', 'count': 3},
2973 'Uniform3f': {'type': 'PUTXn', 'count': 3},
2974 'Uniform3fv': {
2975 'type': 'PUTn',
2976 'count': 3,
2977 'decoder_func': 'DoUniform3fv',
2979 'Uniform3iv': {
2980 'type': 'PUTn',
2981 'count': 3,
2982 'decoder_func': 'DoUniform3iv',
2984 'Uniform3ui': {
2985 'type': 'PUTXn',
2986 'count': 3,
2987 'unsafe': True,
2989 'Uniform3uiv': {
2990 'type': 'PUTn',
2991 'count': 3,
2992 'unsafe': True,
2994 'Uniform4i': {'type': 'PUTXn', 'count': 4},
2995 'Uniform4f': {'type': 'PUTXn', 'count': 4},
2996 'Uniform4fv': {
2997 'type': 'PUTn',
2998 'count': 4,
2999 'decoder_func': 'DoUniform4fv',
3001 'Uniform4iv': {
3002 'type': 'PUTn',
3003 'count': 4,
3004 'decoder_func': 'DoUniform4iv',
3006 'Uniform4ui': {
3007 'type': 'PUTXn',
3008 'count': 4,
3009 'unsafe': True,
3011 'Uniform4uiv': {
3012 'type': 'PUTn',
3013 'count': 4,
3014 'unsafe': True,
3016 'UniformMatrix2fv': {
3017 'type': 'PUTn',
3018 'count': 4,
3019 'decoder_func': 'DoUniformMatrix2fv',
3021 'UniformMatrix2x3fv': {
3022 'type': 'PUTn',
3023 'count': 6,
3024 'unsafe': True,
3026 'UniformMatrix2x4fv': {
3027 'type': 'PUTn',
3028 'count': 8,
3029 'unsafe': True,
3031 'UniformMatrix3fv': {
3032 'type': 'PUTn',
3033 'count': 9,
3034 'decoder_func': 'DoUniformMatrix3fv',
3036 'UniformMatrix3x2fv': {
3037 'type': 'PUTn',
3038 'count': 6,
3039 'unsafe': True,
3041 'UniformMatrix3x4fv': {
3042 'type': 'PUTn',
3043 'count': 12,
3044 'unsafe': True,
3046 'UniformMatrix4fv': {
3047 'type': 'PUTn',
3048 'count': 16,
3049 'decoder_func': 'DoUniformMatrix4fv',
3051 'UniformMatrix4x2fv': {
3052 'type': 'PUTn',
3053 'count': 8,
3054 'unsafe': True,
3056 'UniformMatrix4x3fv': {
3057 'type': 'PUTn',
3058 'count': 12,
3059 'unsafe': True,
3061 'UniformBlockBinding': {
3062 'type': 'Custom',
3063 'impl_func': False,
3064 'unsafe': True,
3066 'UnmapBufferCHROMIUM': {
3067 'gen_cmd': False,
3068 'extension': True,
3069 'chromium': True,
3070 'client_test': False,
3072 'UnmapBufferSubDataCHROMIUM': {
3073 'gen_cmd': False,
3074 'extension': True,
3075 'chromium': True,
3076 'client_test': False,
3077 'pepper_interface': 'ChromiumMapSub',
3079 'UnmapBuffer': {
3080 'type': 'Custom',
3081 'unsafe': True,
3083 'UnmapTexSubImage2DCHROMIUM': {
3084 'gen_cmd': False,
3085 'extension': True,
3086 'chromium': True,
3087 'client_test': False,
3088 'pepper_interface': 'ChromiumMapSub',
3090 'UseProgram': {
3091 'type': 'Bind',
3092 'decoder_func': 'DoUseProgram',
3094 'ValidateProgram': {'decoder_func': 'DoValidateProgram'},
3095 'VertexAttrib1f': {'decoder_func': 'DoVertexAttrib1f'},
3096 'VertexAttrib1fv': {
3097 'type': 'PUT',
3098 'count': 1,
3099 'decoder_func': 'DoVertexAttrib1fv',
3101 'VertexAttrib2f': {'decoder_func': 'DoVertexAttrib2f'},
3102 'VertexAttrib2fv': {
3103 'type': 'PUT',
3104 'count': 2,
3105 'decoder_func': 'DoVertexAttrib2fv',
3107 'VertexAttrib3f': {'decoder_func': 'DoVertexAttrib3f'},
3108 'VertexAttrib3fv': {
3109 'type': 'PUT',
3110 'count': 3,
3111 'decoder_func': 'DoVertexAttrib3fv',
3113 'VertexAttrib4f': {'decoder_func': 'DoVertexAttrib4f'},
3114 'VertexAttrib4fv': {
3115 'type': 'PUT',
3116 'count': 4,
3117 'decoder_func': 'DoVertexAttrib4fv',
3119 'VertexAttribI4i': {
3120 'unsafe': True,
3122 'VertexAttribI4iv': {
3123 'type': 'PUT',
3124 'count': 4,
3125 'unsafe': True,
3127 'VertexAttribI4ui': {
3128 'unsafe': True,
3130 'VertexAttribI4uiv': {
3131 'type': 'PUT',
3132 'count': 4,
3133 'unsafe': True,
3135 'VertexAttribIPointer': {
3136 'type': 'Manual',
3137 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3138 'GLenumVertexAttribType type, GLsizei stride, '
3139 'GLuint offset',
3140 'client_test': False,
3141 'unsafe': True,
3143 'VertexAttribPointer': {
3144 'type': 'Manual',
3145 'cmd_args': 'GLuint indx, GLintVertexAttribSize size, '
3146 'GLenumVertexAttribType type, GLboolean normalized, '
3147 'GLsizei stride, GLuint offset',
3148 'client_test': False,
3150 'WaitSync': {
3151 'type': 'Custom',
3152 'cmd_args': 'GLuint sync, GLbitfieldSyncFlushFlags flags, '
3153 'GLuint timeout_0, GLuint timeout_1',
3154 'impl_func': False,
3155 'client_test': False,
3156 'unsafe': True,
3158 'Scissor': {
3159 'type': 'StateSet',
3160 'state': 'Scissor',
3162 'Viewport': {
3163 'decoder_func': 'DoViewport',
3165 'ResizeCHROMIUM': {
3166 'type': 'Custom',
3167 'impl_func': False,
3168 'unit_test': False,
3169 'extension': True,
3170 'chromium': True,
3172 'GetRequestableExtensionsCHROMIUM': {
3173 'type': 'Custom',
3174 'impl_func': False,
3175 'cmd_args': 'uint32_t bucket_id',
3176 'extension': True,
3177 'chromium': True,
3179 'RequestExtensionCHROMIUM': {
3180 'type': 'Custom',
3181 'impl_func': False,
3182 'client_test': False,
3183 'cmd_args': 'uint32_t bucket_id',
3184 'extension': True,
3185 'chromium': True,
3187 'RateLimitOffscreenContextCHROMIUM': {
3188 'gen_cmd': False,
3189 'extension': True,
3190 'chromium': True,
3191 'client_test': False,
3193 'CreateStreamTextureCHROMIUM': {
3194 'type': 'HandWritten',
3195 'impl_func': False,
3196 'gen_cmd': False,
3197 'extension': True,
3198 'chromium': True,
3200 'TexImageIOSurface2DCHROMIUM': {
3201 'decoder_func': 'DoTexImageIOSurface2DCHROMIUM',
3202 'unit_test': False,
3203 'extension': True,
3204 'chromium': True,
3206 'CopyTextureCHROMIUM': {
3207 'decoder_func': 'DoCopyTextureCHROMIUM',
3208 'unit_test': False,
3209 'extension': True,
3210 'chromium': True,
3212 'CopySubTextureCHROMIUM': {
3213 'decoder_func': 'DoCopySubTextureCHROMIUM',
3214 'unit_test': False,
3215 'extension': True,
3216 'chromium': True,
3218 'TexStorage2DEXT': {
3219 'unit_test': False,
3220 'extension': True,
3221 'decoder_func': 'DoTexStorage2DEXT',
3223 'DrawArraysInstancedANGLE': {
3224 'type': 'Manual',
3225 'cmd_args': 'GLenumDrawMode mode, GLint first, GLsizei count, '
3226 'GLsizei primcount',
3227 'extension': True,
3228 'unit_test': False,
3229 'pepper_interface': 'InstancedArrays',
3230 'defer_draws': True,
3232 'DrawBuffersEXT': {
3233 'type': 'PUTn',
3234 'decoder_func': 'DoDrawBuffersEXT',
3235 'count': 1,
3236 'client_test': False,
3237 'unit_test': False,
3238 # could use 'extension_flag': 'ext_draw_buffers' but currently expected to
3239 # work without.
3240 'extension': True,
3241 'pepper_interface': 'DrawBuffers',
3243 'DrawElementsInstancedANGLE': {
3244 'type': 'Manual',
3245 'cmd_args': 'GLenumDrawMode mode, GLsizei count, '
3246 'GLenumIndexType type, GLuint index_offset, GLsizei primcount',
3247 'extension': True,
3248 'unit_test': False,
3249 'client_test': False,
3250 'pepper_interface': 'InstancedArrays',
3251 'defer_draws': True,
3253 'VertexAttribDivisorANGLE': {
3254 'type': 'Manual',
3255 'cmd_args': 'GLuint index, GLuint divisor',
3256 'extension': True,
3257 'unit_test': False,
3258 'pepper_interface': 'InstancedArrays',
3260 'GenQueriesEXT': {
3261 'type': 'GENn',
3262 'gl_test_func': 'glGenQueriesARB',
3263 'resource_type': 'Query',
3264 'resource_types': 'Queries',
3265 'unit_test': False,
3266 'pepper_interface': 'Query',
3267 'not_shared': 'True',
3269 'DeleteQueriesEXT': {
3270 'type': 'DELn',
3271 'gl_test_func': 'glDeleteQueriesARB',
3272 'resource_type': 'Query',
3273 'resource_types': 'Queries',
3274 'unit_test': False,
3275 'pepper_interface': 'Query',
3277 'IsQueryEXT': {
3278 'gen_cmd': False,
3279 'client_test': False,
3280 'pepper_interface': 'Query',
3282 'BeginQueryEXT': {
3283 'type': 'Manual',
3284 'cmd_args': 'GLenumQueryTarget target, GLidQuery id, void* sync_data',
3285 'data_transfer_methods': ['shm'],
3286 'gl_test_func': 'glBeginQuery',
3287 'pepper_interface': 'Query',
3289 'BeginTransformFeedback': {
3290 'unsafe': True,
3292 'EndQueryEXT': {
3293 'type': 'Manual',
3294 'cmd_args': 'GLenumQueryTarget target, GLuint submit_count',
3295 'gl_test_func': 'glEndnQuery',
3296 'client_test': False,
3297 'pepper_interface': 'Query',
3299 'EndTransformFeedback': {
3300 'unsafe': True,
3302 'GetQueryivEXT': {
3303 'gen_cmd': False,
3304 'client_test': False,
3305 'gl_test_func': 'glGetQueryiv',
3306 'pepper_interface': 'Query',
3308 'GetQueryObjectuivEXT': {
3309 'gen_cmd': False,
3310 'client_test': False,
3311 'gl_test_func': 'glGetQueryObjectuiv',
3312 'pepper_interface': 'Query',
3314 'BindUniformLocationCHROMIUM': {
3315 'type': 'GLchar',
3316 'extension': True,
3317 'data_transfer_methods': ['bucket'],
3318 'needs_size': True,
3319 'gl_test_func': 'DoBindUniformLocationCHROMIUM',
3321 'InsertEventMarkerEXT': {
3322 'type': 'GLcharN',
3323 'decoder_func': 'DoInsertEventMarkerEXT',
3324 'expectation': False,
3325 'extension': True,
3327 'PushGroupMarkerEXT': {
3328 'type': 'GLcharN',
3329 'decoder_func': 'DoPushGroupMarkerEXT',
3330 'expectation': False,
3331 'extension': True,
3333 'PopGroupMarkerEXT': {
3334 'decoder_func': 'DoPopGroupMarkerEXT',
3335 'expectation': False,
3336 'extension': True,
3337 'impl_func': False,
3340 'GenVertexArraysOES': {
3341 'type': 'GENn',
3342 'extension': True,
3343 'gl_test_func': 'glGenVertexArraysOES',
3344 'resource_type': 'VertexArray',
3345 'resource_types': 'VertexArrays',
3346 'unit_test': False,
3347 'pepper_interface': 'VertexArrayObject',
3349 'BindVertexArrayOES': {
3350 'type': 'Bind',
3351 'extension': True,
3352 'gl_test_func': 'glBindVertexArrayOES',
3353 'decoder_func': 'DoBindVertexArrayOES',
3354 'gen_func': 'GenVertexArraysOES',
3355 'unit_test': False,
3356 'client_test': False,
3357 'pepper_interface': 'VertexArrayObject',
3359 'DeleteVertexArraysOES': {
3360 'type': 'DELn',
3361 'extension': True,
3362 'gl_test_func': 'glDeleteVertexArraysOES',
3363 'resource_type': 'VertexArray',
3364 'resource_types': 'VertexArrays',
3365 'unit_test': False,
3366 'pepper_interface': 'VertexArrayObject',
3368 'IsVertexArrayOES': {
3369 'type': 'Is',
3370 'extension': True,
3371 'gl_test_func': 'glIsVertexArrayOES',
3372 'decoder_func': 'DoIsVertexArrayOES',
3373 'expectation': False,
3374 'unit_test': False,
3375 'pepper_interface': 'VertexArrayObject',
3377 'BindTexImage2DCHROMIUM': {
3378 'decoder_func': 'DoBindTexImage2DCHROMIUM',
3379 'unit_test': False,
3380 'extension': True,
3381 'chromium': True,
3383 'ReleaseTexImage2DCHROMIUM': {
3384 'decoder_func': 'DoReleaseTexImage2DCHROMIUM',
3385 'unit_test': False,
3386 'extension': True,
3387 'chromium': True,
3389 'ShallowFinishCHROMIUM': {
3390 'impl_func': False,
3391 'gen_cmd': False,
3392 'extension': True,
3393 'chromium': True,
3394 'client_test': False,
3396 'ShallowFlushCHROMIUM': {
3397 'impl_func': False,
3398 'gen_cmd': False,
3399 'extension': True,
3400 'chromium': True,
3401 'client_test': False,
3403 'OrderingBarrierCHROMIUM': {
3404 'impl_func': False,
3405 'gen_cmd': False,
3406 'extension': True,
3407 'chromium': True,
3408 'client_test': False,
3410 'TraceBeginCHROMIUM': {
3411 'type': 'Custom',
3412 'impl_func': False,
3413 'client_test': False,
3414 'cmd_args': 'GLuint category_bucket_id, GLuint name_bucket_id',
3415 'extension': True,
3416 'chromium': True,
3418 'TraceEndCHROMIUM': {
3419 'impl_func': False,
3420 'client_test': False,
3421 'decoder_func': 'DoTraceEndCHROMIUM',
3422 'unit_test': False,
3423 'extension': True,
3424 'chromium': True,
3426 'AsyncTexImage2DCHROMIUM': {
3427 'type': 'Manual',
3428 'data_transfer_methods': ['shm'],
3429 'client_test': False,
3430 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3431 'GLintTextureInternalFormat internalformat, '
3432 'GLsizei width, GLsizei height, '
3433 'GLintTextureBorder border, '
3434 'GLenumTextureFormat format, GLenumPixelType type, '
3435 'const void* pixels, '
3436 'uint32_t async_upload_token, '
3437 'void* sync_data',
3438 'extension': True,
3439 'chromium': True,
3441 'AsyncTexSubImage2DCHROMIUM': {
3442 'type': 'Manual',
3443 'data_transfer_methods': ['shm'],
3444 'client_test': False,
3445 'cmd_args': 'GLenumTextureTarget target, GLint level, '
3446 'GLint xoffset, GLint yoffset, '
3447 'GLsizei width, GLsizei height, '
3448 'GLenumTextureFormat format, GLenumPixelType type, '
3449 'const void* data, '
3450 'uint32_t async_upload_token, '
3451 'void* sync_data',
3452 'extension': True,
3453 'chromium': True,
3455 'WaitAsyncTexImage2DCHROMIUM': {
3456 'type': 'Manual',
3457 'client_test': False,
3458 'extension': True,
3459 'chromium': True,
3461 'WaitAllAsyncTexImage2DCHROMIUM': {
3462 'type': 'Manual',
3463 'client_test': False,
3464 'extension': True,
3465 'chromium': True,
3467 'DiscardFramebufferEXT': {
3468 'type': 'PUTn',
3469 'count': 1,
3470 'decoder_func': 'DoDiscardFramebufferEXT',
3471 'unit_test': False,
3472 'client_test': False,
3473 'extension_flag': 'ext_discard_framebuffer',
3475 'LoseContextCHROMIUM': {
3476 'decoder_func': 'DoLoseContextCHROMIUM',
3477 'unit_test': False,
3478 'extension': True,
3479 'chromium': True,
3481 'InsertSyncPointCHROMIUM': {
3482 'type': 'HandWritten',
3483 'impl_func': False,
3484 'extension': "CHROMIUM_sync_point",
3485 'chromium': True,
3487 'WaitSyncPointCHROMIUM': {
3488 'type': 'Custom',
3489 'impl_func': True,
3490 'extension': "CHROMIUM_sync_point",
3491 'chromium': True,
3492 'trace_level': 1,
3494 'DiscardBackbufferCHROMIUM': {
3495 'type': 'Custom',
3496 'impl_func': True,
3497 'extension': True,
3498 'chromium': True,
3500 'ScheduleOverlayPlaneCHROMIUM': {
3501 'type': 'Custom',
3502 'impl_func': True,
3503 'unit_test': False,
3504 'client_test': False,
3505 'extension': True,
3506 'chromium': True,
3508 'MatrixLoadfCHROMIUM': {
3509 'type': 'PUT',
3510 'count': 16,
3511 'data_type': 'GLfloat',
3512 'decoder_func': 'DoMatrixLoadfCHROMIUM',
3513 'gl_test_func': 'glMatrixLoadfEXT',
3514 'chromium': True,
3515 'extension': True,
3516 'extension_flag': 'chromium_path_rendering',
3518 'MatrixLoadIdentityCHROMIUM': {
3519 'decoder_func': 'DoMatrixLoadIdentityCHROMIUM',
3520 'gl_test_func': 'glMatrixLoadIdentityEXT',
3521 'chromium': True,
3522 'extension': True,
3523 'extension_flag': 'chromium_path_rendering',
3528 def Grouper(n, iterable, fillvalue=None):
3529 """Collect data into fixed-length chunks or blocks"""
3530 args = [iter(iterable)] * n
3531 return itertools.izip_longest(fillvalue=fillvalue, *args)
3534 def SplitWords(input_string):
3535 """Transforms a input_string into a list of lower-case components.
3537 Args:
3538 input_string: the input string.
3540 Returns:
3541 a list of lower-case words.
3543 if input_string.find('_') > -1:
3544 # 'some_TEXT_' -> 'some text'
3545 return input_string.replace('_', ' ').strip().lower().split()
3546 else:
3547 if re.search('[A-Z]', input_string) and re.search('[a-z]', input_string):
3548 # mixed case.
3549 # look for capitalization to cut input_strings
3550 # 'SomeText' -> 'Some Text'
3551 input_string = re.sub('([A-Z])', r' \1', input_string).strip()
3552 # 'Vector3' -> 'Vector 3'
3553 input_string = re.sub('([^0-9])([0-9])', r'\1 \2', input_string)
3554 return input_string.lower().split()
3557 def Lower(words):
3558 """Makes a lower-case identifier from words.
3560 Args:
3561 words: a list of lower-case words.
3563 Returns:
3564 the lower-case identifier.
3566 return '_'.join(words)
3569 def ToUnderscore(input_string):
3570 """converts CamelCase to camel_case."""
3571 words = SplitWords(input_string)
3572 return Lower(words)
3574 def CachedStateName(item):
3575 if item.get('cached', False):
3576 return 'cached_' + item['name']
3577 return item['name']
3579 def ToGLExtensionString(extension_flag):
3580 """Returns GL-type extension string of a extension flag."""
3581 if extension_flag == "oes_compressed_etc1_rgb8_texture":
3582 return "OES_compressed_ETC1_RGB8_texture" # Fixup inconsitency with rgb8,
3583 # unfortunate.
3584 uppercase_words = [ 'img', 'ext', 'arb', 'chromium', 'oes', 'amd', 'bgra8888',
3585 'egl', 'atc', 'etc1', 'angle']
3586 parts = extension_flag.split('_')
3587 return "_".join(
3588 [part.upper() if part in uppercase_words else part for part in parts])
3590 def ToCamelCase(input_string):
3591 """converts ABC_underscore_case to ABCUnderscoreCase."""
3592 return ''.join(w[0].upper() + w[1:] for w in input_string.split('_'))
3594 def GetGLGetTypeConversion(result_type, value_type, value):
3595 """Makes a gl compatible type conversion string for accessing state variables.
3597 Useful when accessing state variables through glGetXXX calls.
3598 glGet documetation (for example, the manual pages):
3599 [...] If glGetIntegerv is called, [...] most floating-point values are
3600 rounded to the nearest integer value. [...]
3602 Args:
3603 result_type: the gl type to be obtained
3604 value_type: the GL type of the state variable
3605 value: the name of the state variable
3607 Returns:
3608 String that converts the state variable to desired GL type according to GL
3609 rules.
3612 if result_type == 'GLint':
3613 if value_type == 'GLfloat':
3614 return 'static_cast<GLint>(round(%s))' % value
3615 return 'static_cast<%s>(%s)' % (result_type, value)
3617 class CWriter(object):
3618 """Writes to a file formatting it for Google's style guidelines."""
3620 def __init__(self, filename):
3621 self.filename = filename
3622 self.content = []
3624 def Write(self, string):
3625 """Writes a string to a file spliting if it's > 80 characters."""
3626 lines = string.splitlines()
3627 num_lines = len(lines)
3628 for ii in range(0, num_lines):
3629 self.content.append(lines[ii])
3630 if ii < (num_lines - 1) or string[-1] == '\n':
3631 self.content.append('\n')
3633 def Close(self):
3634 """Close the file."""
3635 content = "".join(self.content)
3636 write_file = True
3637 if os.path.exists(self.filename):
3638 old_file = open(self.filename, "rb");
3639 old_content = old_file.read()
3640 old_file.close();
3641 if content == old_content:
3642 write_file = False
3643 if write_file:
3644 file = open(self.filename, "wb")
3645 file.write(content)
3646 file.close()
3649 class CHeaderWriter(CWriter):
3650 """Writes a C Header file."""
3652 _non_alnum_re = re.compile(r'[^a-zA-Z0-9]')
3654 def __init__(self, filename, file_comment = None):
3655 CWriter.__init__(self, filename)
3657 base = os.path.abspath(filename)
3658 while os.path.basename(base) != 'src':
3659 new_base = os.path.dirname(base)
3660 assert new_base != base # Prevent infinite loop.
3661 base = new_base
3663 hpath = os.path.relpath(filename, base)
3664 self.guard = self._non_alnum_re.sub('_', hpath).upper() + '_'
3666 self.Write(_LICENSE)
3667 self.Write(_DO_NOT_EDIT_WARNING)
3668 if not file_comment == None:
3669 self.Write(file_comment)
3670 self.Write("#ifndef %s\n" % self.guard)
3671 self.Write("#define %s\n\n" % self.guard)
3673 def Close(self):
3674 self.Write("#endif // %s\n\n" % self.guard)
3675 CWriter.Close(self)
3677 class TypeHandler(object):
3678 """This class emits code for a particular type of function."""
3680 _remove_expected_call_re = re.compile(r' EXPECT_CALL.*?;\n', re.S)
3682 def __init__(self):
3683 pass
3685 def InitFunction(self, func):
3686 """Add or adjust anything type specific for this function."""
3687 if func.GetInfo('needs_size') and not func.name.endswith('Bucket'):
3688 func.AddCmdArg(DataSizeArgument('data_size'))
3690 def NeedsDataTransferFunction(self, func):
3691 """Overriden from TypeHandler."""
3692 return func.num_pointer_args >= 1
3694 def WriteStruct(self, func, file):
3695 """Writes a structure that matches the arguments to a function."""
3696 comment = func.GetInfo('cmd_comment')
3697 if not comment == None:
3698 file.Write(comment)
3699 file.Write("struct %s {\n" % func.name)
3700 file.Write(" typedef %s ValueType;\n" % func.name)
3701 file.Write(" static const CommandId kCmdId = k%s;\n" % func.name)
3702 func.WriteCmdArgFlag(file)
3703 func.WriteCmdFlag(file)
3704 file.Write("\n")
3705 result = func.GetInfo('result')
3706 if not result == None:
3707 if len(result) == 1:
3708 file.Write(" typedef %s Result;\n\n" % result[0])
3709 else:
3710 file.Write(" struct Result {\n")
3711 for line in result:
3712 file.Write(" %s;\n" % line)
3713 file.Write(" };\n\n")
3715 func.WriteCmdComputeSize(file)
3716 func.WriteCmdSetHeader(file)
3717 func.WriteCmdInit(file)
3718 func.WriteCmdSet(file)
3720 file.Write(" gpu::CommandHeader header;\n")
3721 args = func.GetCmdArgs()
3722 for arg in args:
3723 file.Write(" %s %s;\n" % (arg.cmd_type, arg.name))
3725 consts = func.GetCmdConstants()
3726 for const in consts:
3727 file.Write(" static const %s %s = %s;\n" %
3728 (const.cmd_type, const.name, const.GetConstantValue()))
3730 file.Write("};\n")
3731 file.Write("\n")
3733 size = len(args) * _SIZE_OF_UINT32 + _SIZE_OF_COMMAND_HEADER
3734 file.Write("static_assert(sizeof(%s) == %d,\n" % (func.name, size))
3735 file.Write(" \"size of %s should be %d\");\n" %
3736 (func.name, size))
3737 file.Write("static_assert(offsetof(%s, header) == 0,\n" % func.name)
3738 file.Write(" \"offset of %s header should be 0\");\n" %
3739 func.name)
3740 offset = _SIZE_OF_COMMAND_HEADER
3741 for arg in args:
3742 file.Write("static_assert(offsetof(%s, %s) == %d,\n" %
3743 (func.name, arg.name, offset))
3744 file.Write(" \"offset of %s %s should be %d\");\n" %
3745 (func.name, arg.name, offset))
3746 offset += _SIZE_OF_UINT32
3747 if not result == None and len(result) > 1:
3748 offset = 0;
3749 for line in result:
3750 parts = line.split()
3751 name = parts[-1]
3752 check = """
3753 static_assert(offsetof(%(cmd_name)s::Result, %(field_name)s) == %(offset)d,
3754 "offset of %(cmd_name)s Result %(field_name)s should be "
3755 "%(offset)d");
3757 file.Write((check.strip() + "\n") % {
3758 'cmd_name': func.name,
3759 'field_name': name,
3760 'offset': offset,
3762 offset += _SIZE_OF_UINT32
3763 file.Write("\n")
3765 def WriteHandlerImplementation(self, func, file):
3766 """Writes the handler implementation for this command."""
3767 if func.IsUnsafe() and func.GetInfo('id_mapping'):
3768 code_no_gen = """ if (!group_->Get%(type)sServiceId(
3769 %(var)s, &%(service_var)s)) {
3770 LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3771 return error::kNoError;
3774 code_gen = """ if (!group_->Get%(type)sServiceId(
3775 %(var)s, &%(service_var)s)) {
3776 if (!group_->bind_generates_resource()) {
3777 LOCAL_SET_GL_ERROR(
3778 GL_INVALID_OPERATION, "%(func)s", "invalid %(var)s id");
3779 return error::kNoError;
3781 GLuint client_id = %(var)s;
3782 gl%(gen_func)s(1, &%(service_var)s);
3783 Create%(type)s(client_id, %(service_var)s);
3786 gen_func = func.GetInfo('gen_func')
3787 for id_type in func.GetInfo('id_mapping'):
3788 service_var = id_type.lower()
3789 if id_type == 'Sync':
3790 service_var = "service_%s" % service_var
3791 file.Write(" GLsync %s = 0;\n" % service_var)
3792 if gen_func and id_type in gen_func:
3793 file.Write(code_gen % { 'type': id_type,
3794 'var': id_type.lower(),
3795 'service_var': service_var,
3796 'func': func.GetGLFunctionName(),
3797 'gen_func': gen_func })
3798 else:
3799 file.Write(code_no_gen % { 'type': id_type,
3800 'var': id_type.lower(),
3801 'service_var': service_var,
3802 'func': func.GetGLFunctionName() })
3803 args = []
3804 for arg in func.GetOriginalArgs():
3805 if arg.type == "GLsync":
3806 args.append("service_%s" % arg.name)
3807 elif arg.name.endswith("size") and arg.type == "GLsizei":
3808 args.append("num_%s" % func.GetLastOriginalArg().name)
3809 elif arg.name == "length":
3810 args.append("nullptr")
3811 else:
3812 args.append(arg.name)
3813 file.Write(" %s(%s);\n" %
3814 (func.GetGLFunctionName(), ", ".join(args)))
3816 def WriteCmdSizeTest(self, func, file):
3817 """Writes the size test for a command."""
3818 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3820 def WriteFormatTest(self, func, file):
3821 """Writes a format test for a command."""
3822 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
3823 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
3824 (func.name, func.name))
3825 file.Write(" void* next_cmd = cmd.Set(\n")
3826 file.Write(" &cmd")
3827 args = func.GetCmdArgs()
3828 for value, arg in enumerate(args):
3829 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
3830 file.Write(");\n")
3831 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
3832 func.name)
3833 file.Write(" cmd.header.command);\n")
3834 func.type_handler.WriteCmdSizeTest(func, file)
3835 for value, arg in enumerate(args):
3836 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
3837 (arg.type, value + 11, arg.name))
3838 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
3839 file.Write(" next_cmd, sizeof(cmd));\n")
3840 file.Write("}\n")
3841 file.Write("\n")
3843 def WriteImmediateFormatTest(self, func, file):
3844 """Writes a format test for an immediate version of a command."""
3845 pass
3847 def WriteBucketFormatTest(self, func, file):
3848 """Writes a format test for a bucket version of a command."""
3849 pass
3851 def WriteGetDataSizeCode(self, func, file):
3852 """Writes the code to set data_size used in validation"""
3853 pass
3855 def WriteImmediateCmdSizeTest(self, func, file):
3856 """Writes a size test for an immediate version of a command."""
3857 file.Write(" // TODO(gman): Compute correct size.\n")
3858 file.Write(" EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u);\n")
3860 def __WriteIdMapping(self, func, file):
3861 """Writes client side / service side ID mapping."""
3862 if not func.IsUnsafe() or not func.GetInfo('id_mapping'):
3863 return
3864 for id_type in func.GetInfo('id_mapping'):
3865 file.Write(" group_->Get%sServiceId(%s, &%s);\n" %
3866 (id_type, id_type.lower(), id_type.lower()))
3868 def WriteImmediateHandlerImplementation (self, func, file):
3869 """Writes the handler impl for the immediate version of a command."""
3870 self.__WriteIdMapping(func, file)
3871 file.Write(" %s(%s);\n" %
3872 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3874 def WriteBucketHandlerImplementation (self, func, file):
3875 """Writes the handler impl for the bucket version of a command."""
3876 self.__WriteIdMapping(func, file)
3877 file.Write(" %s(%s);\n" %
3878 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
3880 def WriteServiceHandlerFunctionHeader(self, func, file):
3881 """Writes function header for service implementation handlers."""
3882 file.Write("""error::Error GLES2DecoderImpl::Handle%(name)s(
3883 uint32_t immediate_data_size, const void* cmd_data) {
3884 """ % {'name': func.name})
3885 if func.IsUnsafe():
3886 file.Write("""if (!unsafe_es3_apis_enabled())
3887 return error::kUnknownCommand;
3888 """)
3889 file.Write("""const gles2::cmds::%(name)s& c =
3890 *static_cast<const gles2::cmds::%(name)s*>(cmd_data);
3891 (void)c;
3892 """ % {'name': func.name})
3894 def WriteServiceImplementation(self, func, file):
3895 """Writes the service implementation for a command."""
3896 self.WriteServiceHandlerFunctionHeader(func, file)
3897 self.WriteHandlerExtensionCheck(func, file)
3898 self.WriteHandlerDeferReadWrite(func, file);
3899 if len(func.GetOriginalArgs()) > 0:
3900 last_arg = func.GetLastOriginalArg()
3901 all_but_last_arg = func.GetOriginalArgs()[:-1]
3902 for arg in all_but_last_arg:
3903 arg.WriteGetCode(file)
3904 self.WriteGetDataSizeCode(func, file)
3905 last_arg.WriteGetCode(file)
3906 func.WriteHandlerValidation(file)
3907 func.WriteHandlerImplementation(file)
3908 file.Write(" return error::kNoError;\n")
3909 file.Write("}\n")
3910 file.Write("\n")
3912 def WriteImmediateServiceImplementation(self, func, file):
3913 """Writes the service implementation for an immediate version of command."""
3914 self.WriteServiceHandlerFunctionHeader(func, file)
3915 self.WriteHandlerExtensionCheck(func, file)
3916 self.WriteHandlerDeferReadWrite(func, file);
3917 for arg in func.GetOriginalArgs():
3918 if arg.IsPointer():
3919 self.WriteGetDataSizeCode(func, file)
3920 arg.WriteGetCode(file)
3921 func.WriteHandlerValidation(file)
3922 func.WriteHandlerImplementation(file)
3923 file.Write(" return error::kNoError;\n")
3924 file.Write("}\n")
3925 file.Write("\n")
3927 def WriteBucketServiceImplementation(self, func, file):
3928 """Writes the service implementation for a bucket version of command."""
3929 self.WriteServiceHandlerFunctionHeader(func, file)
3930 self.WriteHandlerExtensionCheck(func, file)
3931 self.WriteHandlerDeferReadWrite(func, file);
3932 for arg in func.GetCmdArgs():
3933 arg.WriteGetCode(file)
3934 func.WriteHandlerValidation(file)
3935 func.WriteHandlerImplementation(file)
3936 file.Write(" return error::kNoError;\n")
3937 file.Write("}\n")
3938 file.Write("\n")
3940 def WriteHandlerExtensionCheck(self, func, file):
3941 if func.GetInfo('extension_flag'):
3942 file.Write(" if (!features().%s) {\n" % func.GetInfo('extension_flag'))
3943 file.Write(" LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, \"gl%s\","
3944 " \"function not available\");\n" % func.original_name)
3945 file.Write(" return error::kNoError;")
3946 file.Write(" }\n\n")
3948 def WriteHandlerDeferReadWrite(self, func, file):
3949 """Writes the code to handle deferring reads or writes."""
3950 defer_draws = func.GetInfo('defer_draws')
3951 defer_reads = func.GetInfo('defer_reads')
3952 if defer_draws or defer_reads:
3953 file.Write(" error::Error error;\n")
3954 if defer_draws:
3955 file.Write(" error = WillAccessBoundFramebufferForDraw();\n")
3956 file.Write(" if (error != error::kNoError)\n")
3957 file.Write(" return error;\n")
3958 if defer_reads:
3959 file.Write(" error = WillAccessBoundFramebufferForRead();\n")
3960 file.Write(" if (error != error::kNoError)\n")
3961 file.Write(" return error;\n")
3963 def WriteValidUnitTest(self, func, file, test, *extras):
3964 """Writes a valid unit test for the service implementation."""
3965 if func.GetInfo('expectation') == False:
3966 test = self._remove_expected_call_re.sub('', test)
3967 name = func.name
3968 arg_strings = [
3969 arg.GetValidArg(func) \
3970 for arg in func.GetOriginalArgs() if not arg.IsConstant()
3972 gl_arg_strings = [
3973 arg.GetValidGLArg(func) \
3974 for arg in func.GetOriginalArgs()
3976 gl_func_name = func.GetGLTestFunctionName()
3977 vars = {
3978 'name':name,
3979 'gl_func_name': gl_func_name,
3980 'args': ", ".join(arg_strings),
3981 'gl_args': ", ".join(gl_arg_strings),
3983 for extra in extras:
3984 vars.update(extra)
3985 old_test = ""
3986 while (old_test != test):
3987 old_test = test
3988 test = test % vars
3989 file.Write(test % vars)
3991 def WriteInvalidUnitTest(self, func, file, test, *extras):
3992 """Writes an invalid unit test for the service implementation."""
3993 if func.IsUnsafe():
3994 return
3995 for invalid_arg_index, invalid_arg in enumerate(func.GetOriginalArgs()):
3996 # Service implementation does not test constants, as they are not part of
3997 # the call in the service side.
3998 if invalid_arg.IsConstant():
3999 continue
4001 num_invalid_values = invalid_arg.GetNumInvalidValues(func)
4002 for value_index in range(0, num_invalid_values):
4003 arg_strings = []
4004 parse_result = "kNoError"
4005 gl_error = None
4006 for arg in func.GetOriginalArgs():
4007 if arg.IsConstant():
4008 continue
4009 if invalid_arg is arg:
4010 (arg_string, parse_result, gl_error) = arg.GetInvalidArg(
4011 value_index)
4012 else:
4013 arg_string = arg.GetValidArg(func)
4014 arg_strings.append(arg_string)
4015 gl_arg_strings = []
4016 for arg in func.GetOriginalArgs():
4017 gl_arg_strings.append("_")
4018 gl_func_name = func.GetGLTestFunctionName()
4019 gl_error_test = ''
4020 if not gl_error == None:
4021 gl_error_test = '\n EXPECT_EQ(%s, GetGLError());' % gl_error
4023 vars = {
4024 'name': func.name,
4025 'arg_index': invalid_arg_index,
4026 'value_index': value_index,
4027 'gl_func_name': gl_func_name,
4028 'args': ", ".join(arg_strings),
4029 'all_but_last_args': ", ".join(arg_strings[:-1]),
4030 'gl_args': ", ".join(gl_arg_strings),
4031 'parse_result': parse_result,
4032 'gl_error_test': gl_error_test,
4034 for extra in extras:
4035 vars.update(extra)
4036 file.Write(test % vars)
4038 def WriteServiceUnitTest(self, func, file, *extras):
4039 """Writes the service unit test for a command."""
4041 if func.name == 'Enable':
4042 valid_test = """
4043 TEST_P(%(test_name)s, %(name)sValidArgs) {
4044 SetupExpectationsForEnableDisable(%(gl_args)s, true);
4045 SpecializedSetup<cmds::%(name)s, 0>(true);
4046 cmds::%(name)s cmd;
4047 cmd.Init(%(args)s);"""
4048 elif func.name == 'Disable':
4049 valid_test = """
4050 TEST_P(%(test_name)s, %(name)sValidArgs) {
4051 SetupExpectationsForEnableDisable(%(gl_args)s, false);
4052 SpecializedSetup<cmds::%(name)s, 0>(true);
4053 cmds::%(name)s cmd;
4054 cmd.Init(%(args)s);"""
4055 else:
4056 valid_test = """
4057 TEST_P(%(test_name)s, %(name)sValidArgs) {
4058 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4059 SpecializedSetup<cmds::%(name)s, 0>(true);
4060 cmds::%(name)s cmd;
4061 cmd.Init(%(args)s);"""
4062 if func.IsUnsafe():
4063 valid_test += """
4064 decoder_->set_unsafe_es3_apis_enabled(true);
4065 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4066 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4067 decoder_->set_unsafe_es3_apis_enabled(false);
4068 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4071 else:
4072 valid_test += """
4073 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4074 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4077 self.WriteValidUnitTest(func, file, valid_test, *extras)
4079 if not func.IsUnsafe():
4080 invalid_test = """
4081 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
4082 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
4083 SpecializedSetup<cmds::%(name)s, 0>(false);
4084 cmds::%(name)s cmd;
4085 cmd.Init(%(args)s);
4086 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
4089 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
4091 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4092 """Writes the service unit test for an immediate command."""
4093 file.Write("// TODO(gman): %s\n" % func.name)
4095 def WriteImmediateValidationCode(self, func, file):
4096 """Writes the validation code for an immediate version of a command."""
4097 pass
4099 def WriteBucketServiceUnitTest(self, func, file, *extras):
4100 """Writes the service unit test for a bucket command."""
4101 file.Write("// TODO(gman): %s\n" % func.name)
4103 def WriteBucketValidationCode(self, func, file):
4104 """Writes the validation code for a bucket version of a command."""
4105 file.Write("// TODO(gman): %s\n" % func.name)
4107 def WriteGLES2ImplementationDeclaration(self, func, file):
4108 """Writes the GLES2 Implemention declaration."""
4109 impl_decl = func.GetInfo('impl_decl')
4110 if impl_decl == None or impl_decl == True:
4111 file.Write("%s %s(%s) override;\n" %
4112 (func.return_type, func.original_name,
4113 func.MakeTypedOriginalArgString("")))
4114 file.Write("\n")
4116 def WriteGLES2CLibImplementation(self, func, file):
4117 file.Write("%s GLES2%s(%s) {\n" %
4118 (func.return_type, func.name,
4119 func.MakeTypedOriginalArgString("")))
4120 result_string = "return "
4121 if func.return_type == "void":
4122 result_string = ""
4123 file.Write(" %sgles2::GetGLContext()->%s(%s);\n" %
4124 (result_string, func.original_name,
4125 func.MakeOriginalArgString("")))
4126 file.Write("}\n")
4128 def WriteGLES2Header(self, func, file):
4129 """Writes a re-write macro for GLES"""
4130 file.Write("#define gl%s GLES2_GET_FUN(%s)\n" %(func.name, func.name))
4132 def WriteClientGLCallLog(self, func, file):
4133 """Writes a logging macro for the client side code."""
4134 comma = ""
4135 if len(func.GetOriginalArgs()):
4136 comma = " << "
4137 file.Write(
4138 ' GPU_CLIENT_LOG("[" << GetLogPrefix() << "] gl%s("%s%s << ")");\n' %
4139 (func.original_name, comma, func.MakeLogArgString()))
4141 def WriteClientGLReturnLog(self, func, file):
4142 """Writes the return value logging code."""
4143 if func.return_type != "void":
4144 file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
4146 def WriteGLES2ImplementationHeader(self, func, file):
4147 """Writes the GLES2 Implemention."""
4148 self.WriteGLES2ImplementationDeclaration(func, file)
4150 def WriteGLES2TraceImplementationHeader(self, func, file):
4151 """Writes the GLES2 Trace Implemention header."""
4152 file.Write("%s %s(%s) override;\n" %
4153 (func.return_type, func.original_name,
4154 func.MakeTypedOriginalArgString("")))
4156 def WriteGLES2TraceImplementation(self, func, file):
4157 """Writes the GLES2 Trace Implemention."""
4158 file.Write("%s GLES2TraceImplementation::%s(%s) {\n" %
4159 (func.return_type, func.original_name,
4160 func.MakeTypedOriginalArgString("")))
4161 result_string = "return "
4162 if func.return_type == "void":
4163 result_string = ""
4164 file.Write(' TRACE_EVENT_BINARY_EFFICIENT0("gpu", "GLES2Trace::%s");\n' %
4165 func.name)
4166 file.Write(" %sgl_->%s(%s);\n" %
4167 (result_string, func.name, func.MakeOriginalArgString("")))
4168 file.Write("}\n")
4169 file.Write("\n")
4171 def WriteGLES2Implementation(self, func, file):
4172 """Writes the GLES2 Implemention."""
4173 impl_func = func.GetInfo('impl_func')
4174 impl_decl = func.GetInfo('impl_decl')
4175 gen_cmd = func.GetInfo('gen_cmd')
4176 if (func.can_auto_generate and
4177 (impl_func == None or impl_func == True) and
4178 (impl_decl == None or impl_decl == True) and
4179 (gen_cmd == None or gen_cmd == True)):
4180 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4181 (func.return_type, func.original_name,
4182 func.MakeTypedOriginalArgString("")))
4183 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
4184 self.WriteClientGLCallLog(func, file)
4185 func.WriteDestinationInitalizationValidation(file)
4186 for arg in func.GetOriginalArgs():
4187 arg.WriteClientSideValidationCode(file, func)
4188 file.Write(" helper_->%s(%s);\n" %
4189 (func.name, func.MakeHelperArgString("")))
4190 file.Write(" CheckGLError();\n")
4191 self.WriteClientGLReturnLog(func, file)
4192 file.Write("}\n")
4193 file.Write("\n")
4195 def WriteGLES2InterfaceHeader(self, func, file):
4196 """Writes the GLES2 Interface."""
4197 file.Write("virtual %s %s(%s) = 0;\n" %
4198 (func.return_type, func.original_name,
4199 func.MakeTypedOriginalArgString("")))
4201 def WriteGLES2InterfaceStub(self, func, file):
4202 """Writes the GLES2 Interface stub declaration."""
4203 file.Write("%s %s(%s) override;\n" %
4204 (func.return_type, func.original_name,
4205 func.MakeTypedOriginalArgString("")))
4207 def WriteGLES2InterfaceStubImpl(self, func, file):
4208 """Writes the GLES2 Interface stub declaration."""
4209 args = func.GetOriginalArgs()
4210 arg_string = ", ".join(
4211 ["%s /* %s */" % (arg.type, arg.name) for arg in args])
4212 file.Write("%s GLES2InterfaceStub::%s(%s) {\n" %
4213 (func.return_type, func.original_name, arg_string))
4214 if func.return_type != "void":
4215 file.Write(" return 0;\n")
4216 file.Write("}\n")
4218 def WriteGLES2ImplementationUnitTest(self, func, file):
4219 """Writes the GLES2 Implemention unit test."""
4220 client_test = func.GetInfo('client_test')
4221 if (func.can_auto_generate and
4222 (client_test == None or client_test == True)):
4223 code = """
4224 TEST_F(GLES2ImplementationTest, %(name)s) {
4225 struct Cmds {
4226 cmds::%(name)s cmd;
4228 Cmds expected;
4229 expected.cmd.Init(%(cmd_args)s);
4231 gl_->%(name)s(%(args)s);
4232 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
4235 cmd_arg_strings = [
4236 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
4239 gl_arg_strings = [
4240 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
4243 file.Write(code % {
4244 'name': func.name,
4245 'args': ", ".join(gl_arg_strings),
4246 'cmd_args': ", ".join(cmd_arg_strings),
4249 # Test constants for invalid values, as they are not tested by the
4250 # service.
4251 constants = [arg for arg in func.GetOriginalArgs() if arg.IsConstant()]
4252 if constants:
4253 code = """
4254 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
4255 gl_->%(name)s(%(args)s);
4256 EXPECT_TRUE(NoCommandsWritten());
4257 EXPECT_EQ(%(gl_error)s, CheckError());
4260 for invalid_arg in constants:
4261 gl_arg_strings = []
4262 invalid = invalid_arg.GetInvalidArg(func)
4263 for arg in func.GetOriginalArgs():
4264 if arg is invalid_arg:
4265 gl_arg_strings.append(invalid[0])
4266 else:
4267 gl_arg_strings.append(arg.GetValidClientSideArg(func))
4269 file.Write(code % {
4270 'name': func.name,
4271 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
4272 'args': ", ".join(gl_arg_strings),
4273 'gl_error': invalid[2],
4275 else:
4276 if client_test != False:
4277 file.Write("// TODO(zmo): Implement unit test for %s\n" % func.name)
4279 def WriteDestinationInitalizationValidation(self, func, file):
4280 """Writes the client side destintion initialization validation."""
4281 for arg in func.GetOriginalArgs():
4282 arg.WriteDestinationInitalizationValidation(file, func)
4284 def WriteTraceEvent(self, func, file):
4285 file.Write(' TRACE_EVENT0("gpu", "GLES2Implementation::%s");\n' %
4286 func.original_name)
4288 def WriteImmediateCmdComputeSize(self, func, file):
4289 """Writes the size computation code for the immediate version of a cmd."""
4290 file.Write(" static uint32_t ComputeSize(uint32_t size_in_bytes) {\n")
4291 file.Write(" return static_cast<uint32_t>(\n")
4292 file.Write(" sizeof(ValueType) + // NOLINT\n")
4293 file.Write(" RoundSizeToMultipleOfEntries(size_in_bytes));\n")
4294 file.Write(" }\n")
4295 file.Write("\n")
4297 def WriteImmediateCmdSetHeader(self, func, file):
4298 """Writes the SetHeader function for the immediate version of a cmd."""
4299 file.Write(" void SetHeader(uint32_t size_in_bytes) {\n")
4300 file.Write(" header.SetCmdByTotalSize<ValueType>(size_in_bytes);\n")
4301 file.Write(" }\n")
4302 file.Write("\n")
4304 def WriteImmediateCmdInit(self, func, file):
4305 """Writes the Init function for the immediate version of a command."""
4306 raise NotImplementedError(func.name)
4308 def WriteImmediateCmdSet(self, func, file):
4309 """Writes the Set function for the immediate version of a command."""
4310 raise NotImplementedError(func.name)
4312 def WriteCmdHelper(self, func, file):
4313 """Writes the cmd helper definition for a cmd."""
4314 code = """ void %(name)s(%(typed_args)s) {
4315 gles2::cmds::%(name)s* c = GetCmdSpace<gles2::cmds::%(name)s>();
4316 if (c) {
4317 c->Init(%(args)s);
4322 file.Write(code % {
4323 "name": func.name,
4324 "typed_args": func.MakeTypedCmdArgString(""),
4325 "args": func.MakeCmdArgString(""),
4328 def WriteImmediateCmdHelper(self, func, file):
4329 """Writes the cmd helper definition for the immediate version of a cmd."""
4330 code = """ void %(name)s(%(typed_args)s) {
4331 const uint32_t s = 0; // TODO(gman): compute correct size
4332 gles2::cmds::%(name)s* c =
4333 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(s);
4334 if (c) {
4335 c->Init(%(args)s);
4340 file.Write(code % {
4341 "name": func.name,
4342 "typed_args": func.MakeTypedCmdArgString(""),
4343 "args": func.MakeCmdArgString(""),
4347 class StateSetHandler(TypeHandler):
4348 """Handler for commands that simply set state."""
4350 def __init__(self):
4351 TypeHandler.__init__(self)
4353 def WriteHandlerImplementation(self, func, file):
4354 """Overrriden from TypeHandler."""
4355 state_name = func.GetInfo('state')
4356 state = _STATES[state_name]
4357 states = state['states']
4358 args = func.GetOriginalArgs()
4359 for ndx,item in enumerate(states):
4360 code = []
4361 if 'range_checks' in item:
4362 for range_check in item['range_checks']:
4363 code.append("%s %s" % (args[ndx].name, range_check['check']))
4364 if 'nan_check' in item:
4365 # Drivers might generate an INVALID_VALUE error when a value is set
4366 # to NaN. This is allowed behavior under GLES 3.0 section 2.1.1 or
4367 # OpenGL 4.5 section 2.3.4.1 - providing NaN allows undefined results.
4368 # Make this behavior consistent within Chromium, and avoid leaking GL
4369 # errors by generating the error in the command buffer instead of
4370 # letting the GL driver generate it.
4371 code.append("base::IsNaN(%s)" % args[ndx].name)
4372 if len(code):
4373 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4374 file.Write(
4375 ' LOCAL_SET_GL_ERROR(GL_INVALID_VALUE,'
4376 ' "%s", "%s out of range");\n' %
4377 (func.name, args[ndx].name))
4378 file.Write(" return error::kNoError;\n")
4379 file.Write(" }\n")
4380 code = []
4381 for ndx,item in enumerate(states):
4382 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
4383 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4384 for ndx,item in enumerate(states):
4385 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
4386 if 'state_flag' in state:
4387 file.Write(" %s = true;\n" % state['state_flag'])
4388 if not func.GetInfo("no_gl"):
4389 for ndx,item in enumerate(states):
4390 if item.get('cached', False):
4391 file.Write(" state_.%s = %s;\n" %
4392 (CachedStateName(item), args[ndx].name))
4393 file.Write(" %s(%s);\n" %
4394 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4395 file.Write(" }\n")
4397 def WriteServiceUnitTest(self, func, file, *extras):
4398 """Overrriden from TypeHandler."""
4399 TypeHandler.WriteServiceUnitTest(self, func, file, *extras)
4400 state_name = func.GetInfo('state')
4401 state = _STATES[state_name]
4402 states = state['states']
4403 for ndx,item in enumerate(states):
4404 if 'range_checks' in item:
4405 for check_ndx, range_check in enumerate(item['range_checks']):
4406 valid_test = """
4407 TEST_P(%(test_name)s, %(name)sInvalidValue%(ndx)d_%(check_ndx)d) {
4408 SpecializedSetup<cmds::%(name)s, 0>(false);
4409 cmds::%(name)s cmd;
4410 cmd.Init(%(args)s);
4411 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4412 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4415 name = func.name
4416 arg_strings = [
4417 arg.GetValidArg(func) \
4418 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4421 arg_strings[ndx] = range_check['test_value']
4422 vars = {
4423 'name': name,
4424 'ndx': ndx,
4425 'check_ndx': check_ndx,
4426 'args': ", ".join(arg_strings),
4428 for extra in extras:
4429 vars.update(extra)
4430 file.Write(valid_test % vars)
4431 if 'nan_check' in item:
4432 valid_test = """
4433 TEST_P(%(test_name)s, %(name)sNaNValue%(ndx)d) {
4434 SpecializedSetup<cmds::%(name)s, 0>(false);
4435 cmds::%(name)s cmd;
4436 cmd.Init(%(args)s);
4437 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4438 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
4441 name = func.name
4442 arg_strings = [
4443 arg.GetValidArg(func) \
4444 for arg in func.GetOriginalArgs() if not arg.IsConstant()
4447 arg_strings[ndx] = 'nanf("")'
4448 vars = {
4449 'name': name,
4450 'ndx': ndx,
4451 'args': ", ".join(arg_strings),
4453 for extra in extras:
4454 vars.update(extra)
4455 file.Write(valid_test % vars)
4458 class StateSetRGBAlphaHandler(TypeHandler):
4459 """Handler for commands that simply set state that have rgb/alpha."""
4461 def __init__(self):
4462 TypeHandler.__init__(self)
4464 def WriteHandlerImplementation(self, func, file):
4465 """Overrriden from TypeHandler."""
4466 state_name = func.GetInfo('state')
4467 state = _STATES[state_name]
4468 states = state['states']
4469 args = func.GetOriginalArgs()
4470 num_args = len(args)
4471 code = []
4472 for ndx,item in enumerate(states):
4473 code.append("state_.%s != %s" % (item['name'], args[ndx % num_args].name))
4474 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4475 for ndx, item in enumerate(states):
4476 file.Write(" state_.%s = %s;\n" %
4477 (item['name'], args[ndx % num_args].name))
4478 if 'state_flag' in state:
4479 file.Write(" %s = true;\n" % state['state_flag'])
4480 if not func.GetInfo("no_gl"):
4481 file.Write(" %s(%s);\n" %
4482 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4483 file.Write(" }\n")
4486 class StateSetFrontBackSeparateHandler(TypeHandler):
4487 """Handler for commands that simply set state that have front/back."""
4489 def __init__(self):
4490 TypeHandler.__init__(self)
4492 def WriteHandlerImplementation(self, func, file):
4493 """Overrriden from TypeHandler."""
4494 state_name = func.GetInfo('state')
4495 state = _STATES[state_name]
4496 states = state['states']
4497 args = func.GetOriginalArgs()
4498 face = args[0].name
4499 num_args = len(args)
4500 file.Write(" bool changed = false;\n")
4501 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4502 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4503 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4504 code = []
4505 for ndx, item in enumerate(group):
4506 code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name))
4507 file.Write(" changed |= %s;\n" % " ||\n ".join(code))
4508 file.Write(" }\n")
4509 file.Write(" if (changed) {\n")
4510 for group_ndx, group in enumerate(Grouper(num_args - 1, states)):
4511 file.Write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" %
4512 (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face))
4513 for ndx, item in enumerate(group):
4514 file.Write(" state_.%s = %s;\n" %
4515 (item['name'], args[ndx + 1].name))
4516 file.Write(" }\n")
4517 if 'state_flag' in state:
4518 file.Write(" %s = true;\n" % state['state_flag'])
4519 if not func.GetInfo("no_gl"):
4520 file.Write(" %s(%s);\n" %
4521 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4522 file.Write(" }\n")
4525 class StateSetFrontBackHandler(TypeHandler):
4526 """Handler for commands that simply set state that set both front/back."""
4528 def __init__(self):
4529 TypeHandler.__init__(self)
4531 def WriteHandlerImplementation(self, func, file):
4532 """Overrriden from TypeHandler."""
4533 state_name = func.GetInfo('state')
4534 state = _STATES[state_name]
4535 states = state['states']
4536 args = func.GetOriginalArgs()
4537 num_args = len(args)
4538 code = []
4539 for group_ndx, group in enumerate(Grouper(num_args, states)):
4540 for ndx, item in enumerate(group):
4541 code.append("state_.%s != %s" % (item['name'], args[ndx].name))
4542 file.Write(" if (%s) {\n" % " ||\n ".join(code))
4543 for group_ndx, group in enumerate(Grouper(num_args, states)):
4544 for ndx, item in enumerate(group):
4545 file.Write(" state_.%s = %s;\n" % (item['name'], args[ndx].name))
4546 if 'state_flag' in state:
4547 file.Write(" %s = true;\n" % state['state_flag'])
4548 if not func.GetInfo("no_gl"):
4549 file.Write(" %s(%s);\n" %
4550 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4551 file.Write(" }\n")
4554 class StateSetNamedParameter(TypeHandler):
4555 """Handler for commands that set a state chosen with an enum parameter."""
4557 def __init__(self):
4558 TypeHandler.__init__(self)
4560 def WriteHandlerImplementation(self, func, file):
4561 """Overridden from TypeHandler."""
4562 state_name = func.GetInfo('state')
4563 state = _STATES[state_name]
4564 states = state['states']
4565 args = func.GetOriginalArgs()
4566 num_args = len(args)
4567 assert num_args == 2
4568 file.Write(" switch (%s) {\n" % args[0].name)
4569 for state in states:
4570 file.Write(" case %s:\n" % state['enum'])
4571 file.Write(" if (state_.%s != %s) {\n" %
4572 (state['name'], args[1].name))
4573 file.Write(" state_.%s = %s;\n" % (state['name'], args[1].name))
4574 if not func.GetInfo("no_gl"):
4575 file.Write(" %s(%s);\n" %
4576 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
4577 file.Write(" }\n")
4578 file.Write(" break;\n")
4579 file.Write(" default:\n")
4580 file.Write(" NOTREACHED();\n")
4581 file.Write(" }\n")
4584 class CustomHandler(TypeHandler):
4585 """Handler for commands that are auto-generated but require minor tweaks."""
4587 def __init__(self):
4588 TypeHandler.__init__(self)
4590 def WriteServiceImplementation(self, func, file):
4591 """Overrriden from TypeHandler."""
4592 pass
4594 def WriteImmediateServiceImplementation(self, func, file):
4595 """Overrriden from TypeHandler."""
4596 pass
4598 def WriteBucketServiceImplementation(self, func, file):
4599 """Overrriden from TypeHandler."""
4600 pass
4602 def WriteServiceUnitTest(self, func, file, *extras):
4603 """Overrriden from TypeHandler."""
4604 file.Write("// TODO(gman): %s\n\n" % func.name)
4606 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4607 """Overrriden from TypeHandler."""
4608 file.Write("// TODO(gman): %s\n\n" % func.name)
4610 def WriteImmediateCmdGetTotalSize(self, func, file):
4611 """Overrriden from TypeHandler."""
4612 file.Write(
4613 " uint32_t total_size = 0; // TODO(gman): get correct size.\n")
4615 def WriteImmediateCmdInit(self, func, file):
4616 """Overrriden from TypeHandler."""
4617 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
4618 self.WriteImmediateCmdGetTotalSize(func, file)
4619 file.Write(" SetHeader(total_size);\n")
4620 args = func.GetCmdArgs()
4621 for arg in args:
4622 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4623 file.Write(" }\n")
4624 file.Write("\n")
4626 def WriteImmediateCmdSet(self, func, file):
4627 """Overrriden from TypeHandler."""
4628 copy_args = func.MakeCmdArgString("_", False)
4629 file.Write(" void* Set(void* cmd%s) {\n" %
4630 func.MakeTypedCmdArgString("_", True))
4631 self.WriteImmediateCmdGetTotalSize(func, file)
4632 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
4633 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4634 "cmd, total_size);\n")
4635 file.Write(" }\n")
4636 file.Write("\n")
4639 class TodoHandler(CustomHandler):
4640 """Handle for commands that are not yet implemented."""
4642 def NeedsDataTransferFunction(self, func):
4643 """Overriden from TypeHandler."""
4644 return False
4646 def WriteImmediateFormatTest(self, func, file):
4647 """Overrriden from TypeHandler."""
4648 pass
4650 def WriteGLES2ImplementationUnitTest(self, func, file):
4651 """Overrriden from TypeHandler."""
4652 pass
4654 def WriteGLES2Implementation(self, func, file):
4655 """Overrriden from TypeHandler."""
4656 file.Write("%s GLES2Implementation::%s(%s) {\n" %
4657 (func.return_type, func.original_name,
4658 func.MakeTypedOriginalArgString("")))
4659 file.Write(" // TODO: for now this is a no-op\n")
4660 file.Write(
4661 " SetGLError("
4662 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4663 func.name)
4664 if func.return_type != "void":
4665 file.Write(" return 0;\n")
4666 file.Write("}\n")
4667 file.Write("\n")
4669 def WriteServiceImplementation(self, func, file):
4670 """Overrriden from TypeHandler."""
4671 self.WriteServiceHandlerFunctionHeader(func, file)
4672 file.Write(" // TODO: for now this is a no-op\n")
4673 file.Write(
4674 " LOCAL_SET_GL_ERROR("
4675 "GL_INVALID_OPERATION, \"gl%s\", \"not implemented\");\n" %
4676 func.name)
4677 file.Write(" return error::kNoError;\n")
4678 file.Write("}\n")
4679 file.Write("\n")
4682 class HandWrittenHandler(CustomHandler):
4683 """Handler for comands where everything must be written by hand."""
4685 def InitFunction(self, func):
4686 """Add or adjust anything type specific for this function."""
4687 CustomHandler.InitFunction(self, func)
4688 func.can_auto_generate = False
4690 def NeedsDataTransferFunction(self, func):
4691 """Overriden from TypeHandler."""
4692 # If specified explicitly, force the data transfer method.
4693 if func.GetInfo('data_transfer_methods'):
4694 return True
4695 return False
4697 def WriteStruct(self, func, file):
4698 """Overrriden from TypeHandler."""
4699 pass
4701 def WriteDocs(self, func, file):
4702 """Overrriden from TypeHandler."""
4703 pass
4705 def WriteServiceUnitTest(self, func, file, *extras):
4706 """Overrriden from TypeHandler."""
4707 file.Write("// TODO(gman): %s\n\n" % func.name)
4709 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4710 """Overrriden from TypeHandler."""
4711 file.Write("// TODO(gman): %s\n\n" % func.name)
4713 def WriteBucketServiceUnitTest(self, func, file, *extras):
4714 """Overrriden from TypeHandler."""
4715 file.Write("// TODO(gman): %s\n\n" % func.name)
4717 def WriteServiceImplementation(self, func, file):
4718 """Overrriden from TypeHandler."""
4719 pass
4721 def WriteImmediateServiceImplementation(self, func, file):
4722 """Overrriden from TypeHandler."""
4723 pass
4725 def WriteBucketServiceImplementation(self, func, file):
4726 """Overrriden from TypeHandler."""
4727 pass
4729 def WriteImmediateCmdHelper(self, func, file):
4730 """Overrriden from TypeHandler."""
4731 pass
4733 def WriteCmdHelper(self, func, file):
4734 """Overrriden from TypeHandler."""
4735 pass
4737 def WriteFormatTest(self, func, file):
4738 """Overrriden from TypeHandler."""
4739 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4741 def WriteImmediateFormatTest(self, func, file):
4742 """Overrriden from TypeHandler."""
4743 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4745 def WriteBucketFormatTest(self, func, file):
4746 """Overrriden from TypeHandler."""
4747 file.Write("// TODO(gman): Write test for %s\n" % func.name)
4751 class ManualHandler(CustomHandler):
4752 """Handler for commands who's handlers must be written by hand."""
4754 def __init__(self):
4755 CustomHandler.__init__(self)
4757 def InitFunction(self, func):
4758 """Overrriden from TypeHandler."""
4759 if (func.name == 'CompressedTexImage2DBucket'):
4760 func.cmd_args = func.cmd_args[:-1]
4761 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
4762 else:
4763 CustomHandler.InitFunction(self, func)
4765 def WriteServiceImplementation(self, func, file):
4766 """Overrriden from TypeHandler."""
4767 pass
4769 def WriteBucketServiceImplementation(self, func, file):
4770 """Overrriden from TypeHandler."""
4771 pass
4773 def WriteServiceUnitTest(self, func, file, *extras):
4774 """Overrriden from TypeHandler."""
4775 file.Write("// TODO(gman): %s\n\n" % func.name)
4777 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4778 """Overrriden from TypeHandler."""
4779 file.Write("// TODO(gman): %s\n\n" % func.name)
4781 def WriteImmediateServiceImplementation(self, func, file):
4782 """Overrriden from TypeHandler."""
4783 pass
4785 def WriteImmediateFormatTest(self, func, file):
4786 """Overrriden from TypeHandler."""
4787 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
4789 def WriteGLES2Implementation(self, func, file):
4790 """Overrriden from TypeHandler."""
4791 if func.GetInfo('impl_func'):
4792 super(ManualHandler, self).WriteGLES2Implementation(func, file)
4794 def WriteGLES2ImplementationHeader(self, func, file):
4795 """Overrriden from TypeHandler."""
4796 file.Write("%s %s(%s) override;\n" %
4797 (func.return_type, func.original_name,
4798 func.MakeTypedOriginalArgString("")))
4799 file.Write("\n")
4801 def WriteImmediateCmdGetTotalSize(self, func, file):
4802 """Overrriden from TypeHandler."""
4803 # TODO(gman): Move this data to _FUNCTION_INFO?
4804 CustomHandler.WriteImmediateCmdGetTotalSize(self, func, file)
4807 class DataHandler(TypeHandler):
4808 """Handler for glBufferData, glBufferSubData, glTexImage2D, glTexSubImage2D,
4809 glCompressedTexImage2D, glCompressedTexImageSub2D."""
4810 def __init__(self):
4811 TypeHandler.__init__(self)
4813 def InitFunction(self, func):
4814 """Overrriden from TypeHandler."""
4815 if func.name == 'CompressedTexSubImage2DBucket':
4816 func.cmd_args = func.cmd_args[:-1]
4817 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
4819 def WriteGetDataSizeCode(self, func, file):
4820 """Overrriden from TypeHandler."""
4821 # TODO(gman): Move this data to _FUNCTION_INFO?
4822 name = func.name
4823 if name.endswith("Immediate"):
4824 name = name[0:-9]
4825 if name == 'BufferData' or name == 'BufferSubData':
4826 file.Write(" uint32_t data_size = size;\n")
4827 elif (name == 'CompressedTexImage2D' or
4828 name == 'CompressedTexSubImage2D'):
4829 file.Write(" uint32_t data_size = imageSize;\n")
4830 elif (name == 'CompressedTexSubImage2DBucket'):
4831 file.Write(" Bucket* bucket = GetBucket(c.bucket_id);\n")
4832 file.Write(" uint32_t data_size = bucket->size();\n")
4833 file.Write(" GLsizei imageSize = data_size;\n")
4834 elif name == 'TexImage2D' or name == 'TexSubImage2D':
4835 code = """ uint32_t data_size;
4836 if (!GLES2Util::ComputeImageDataSize(
4837 width, height, format, type, unpack_alignment_, &data_size)) {
4838 return error::kOutOfBounds;
4841 file.Write(code)
4842 else:
4843 file.Write(
4844 "// uint32_t data_size = 0; // TODO(gman): get correct size!\n")
4846 def WriteImmediateCmdGetTotalSize(self, func, file):
4847 """Overrriden from TypeHandler."""
4848 pass
4850 def WriteImmediateCmdSizeTest(self, func, file):
4851 """Overrriden from TypeHandler."""
4852 file.Write(" EXPECT_EQ(sizeof(cmd), total_size);\n")
4854 def WriteImmediateCmdInit(self, func, file):
4855 """Overrriden from TypeHandler."""
4856 file.Write(" void Init(%s) {\n" % func.MakeTypedCmdArgString("_"))
4857 self.WriteImmediateCmdGetTotalSize(func, file)
4858 file.Write(" SetHeader(total_size);\n")
4859 args = func.GetCmdArgs()
4860 for arg in args:
4861 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
4862 file.Write(" }\n")
4863 file.Write("\n")
4865 def WriteImmediateCmdSet(self, func, file):
4866 """Overrriden from TypeHandler."""
4867 copy_args = func.MakeCmdArgString("_", False)
4868 file.Write(" void* Set(void* cmd%s) {\n" %
4869 func.MakeTypedCmdArgString("_", True))
4870 self.WriteImmediateCmdGetTotalSize(func, file)
4871 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
4872 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
4873 "cmd, total_size);\n")
4874 file.Write(" }\n")
4875 file.Write("\n")
4877 def WriteImmediateFormatTest(self, func, file):
4878 """Overrriden from TypeHandler."""
4879 # TODO(gman): Remove this exception.
4880 file.Write("// TODO(gman): Implement test for %s\n" % func.name)
4881 return
4883 def WriteServiceUnitTest(self, func, file, *extras):
4884 """Overrriden from TypeHandler."""
4885 file.Write("// TODO(gman): %s\n\n" % func.name)
4887 def WriteImmediateServiceUnitTest(self, func, file, *extras):
4888 """Overrriden from TypeHandler."""
4889 file.Write("// TODO(gman): %s\n\n" % func.name)
4891 def WriteBucketServiceImplementation(self, func, file):
4892 """Overrriden from TypeHandler."""
4893 if not func.name == 'CompressedTexSubImage2DBucket':
4894 TypeHandler.WriteBucketServiceImplemenation(self, func, file)
4897 class BindHandler(TypeHandler):
4898 """Handler for glBind___ type functions."""
4900 def __init__(self):
4901 TypeHandler.__init__(self)
4903 def WriteServiceUnitTest(self, func, file, *extras):
4904 """Overrriden from TypeHandler."""
4906 if len(func.GetOriginalArgs()) == 1:
4907 valid_test = """
4908 TEST_P(%(test_name)s, %(name)sValidArgs) {
4909 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
4910 SpecializedSetup<cmds::%(name)s, 0>(true);
4911 cmds::%(name)s cmd;
4912 cmd.Init(%(args)s);"""
4913 if func.IsUnsafe():
4914 valid_test += """
4915 decoder_->set_unsafe_es3_apis_enabled(true);
4916 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4917 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4918 decoder_->set_unsafe_es3_apis_enabled(false);
4919 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4922 else:
4923 valid_test += """
4924 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4925 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4928 if func.GetInfo("gen_func"):
4929 valid_test += """
4930 TEST_P(%(test_name)s, %(name)sValidArgsNewId) {
4931 EXPECT_CALL(*gl_, %(gl_func_name)s(kNewServiceId));
4932 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
4933 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4934 SpecializedSetup<cmds::%(name)s, 0>(true);
4935 cmds::%(name)s cmd;
4936 cmd.Init(kNewClientId);
4937 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4938 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4939 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4942 self.WriteValidUnitTest(func, file, valid_test, {
4943 'resource_type': func.GetOriginalArgs()[0].resource_type,
4944 'gl_gen_func_name': func.GetInfo("gen_func"),
4945 }, *extras)
4946 else:
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_,
4972 %(gl_func_name)s(%(gl_args_with_new_id)s));
4973 EXPECT_CALL(*gl_, %(gl_gen_func_name)s(1, _))
4974 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
4975 SpecializedSetup<cmds::%(name)s, 0>(true);
4976 cmds::%(name)s cmd;
4977 cmd.Init(%(args_with_new_id)s);"""
4978 if func.IsUnsafe():
4979 valid_test += """
4980 decoder_->set_unsafe_es3_apis_enabled(true);
4981 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4982 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4983 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4984 decoder_->set_unsafe_es3_apis_enabled(false);
4985 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
4988 else:
4989 valid_test += """
4990 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
4991 EXPECT_EQ(GL_NO_ERROR, GetGLError());
4992 EXPECT_TRUE(Get%(resource_type)s(kNewClientId) != NULL);
4996 gl_args_with_new_id = []
4997 args_with_new_id = []
4998 for arg in func.GetOriginalArgs():
4999 if hasattr(arg, 'resource_type'):
5000 gl_args_with_new_id.append('kNewServiceId')
5001 args_with_new_id.append('kNewClientId')
5002 else:
5003 gl_args_with_new_id.append(arg.GetValidGLArg(func))
5004 args_with_new_id.append(arg.GetValidArg(func))
5005 self.WriteValidUnitTest(func, file, valid_test, {
5006 'args_with_new_id': ", ".join(args_with_new_id),
5007 'gl_args_with_new_id': ", ".join(gl_args_with_new_id),
5008 'resource_type': func.GetResourceIdArg().resource_type,
5009 'gl_gen_func_name': func.GetInfo("gen_func"),
5010 }, *extras)
5012 invalid_test = """
5013 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5014 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5015 SpecializedSetup<cmds::%(name)s, 0>(false);
5016 cmds::%(name)s cmd;
5017 cmd.Init(%(args)s);
5018 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
5021 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
5023 def WriteGLES2Implementation(self, func, file):
5024 """Writes the GLES2 Implemention."""
5026 impl_func = func.GetInfo('impl_func')
5027 impl_decl = func.GetInfo('impl_decl')
5029 if (func.can_auto_generate and
5030 (impl_func == None or impl_func == True) and
5031 (impl_decl == None or impl_decl == True)):
5033 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5034 (func.return_type, func.original_name,
5035 func.MakeTypedOriginalArgString("")))
5036 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5037 func.WriteDestinationInitalizationValidation(file)
5038 self.WriteClientGLCallLog(func, file)
5039 for arg in func.GetOriginalArgs():
5040 arg.WriteClientSideValidationCode(file, func)
5042 code = """ if (Is%(type)sReservedId(%(id)s)) {
5043 SetGLError(GL_INVALID_OPERATION, "%(name)s\", \"%(id)s reserved id");
5044 return;
5046 %(name)sHelper(%(arg_string)s);
5047 CheckGLError();
5051 name_arg = func.GetResourceIdArg()
5052 file.Write(code % {
5053 'name': func.name,
5054 'arg_string': func.MakeOriginalArgString(""),
5055 'id': name_arg.name,
5056 'type': name_arg.resource_type,
5057 'lc_type': name_arg.resource_type.lower(),
5060 def WriteGLES2ImplementationUnitTest(self, func, file):
5061 """Overrriden from TypeHandler."""
5062 client_test = func.GetInfo('client_test')
5063 if client_test == False:
5064 return
5065 code = """
5066 TEST_F(GLES2ImplementationTest, %(name)s) {
5067 struct Cmds {
5068 cmds::%(name)s cmd;
5070 Cmds expected;
5071 expected.cmd.Init(%(cmd_args)s);
5073 gl_->%(name)s(%(args)s);
5074 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));"""
5075 if not func.IsUnsafe():
5076 code += """
5077 ClearCommands();
5078 gl_->%(name)s(%(args)s);
5079 EXPECT_TRUE(NoCommandsWritten());"""
5080 code += """
5083 cmd_arg_strings = [
5084 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()
5086 gl_arg_strings = [
5087 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()
5090 file.Write(code % {
5091 'name': func.name,
5092 'args': ", ".join(gl_arg_strings),
5093 'cmd_args': ", ".join(cmd_arg_strings),
5097 class GENnHandler(TypeHandler):
5098 """Handler for glGen___ type functions."""
5100 def __init__(self):
5101 TypeHandler.__init__(self)
5103 def InitFunction(self, func):
5104 """Overrriden from TypeHandler."""
5105 pass
5107 def WriteGetDataSizeCode(self, func, file):
5108 """Overrriden from TypeHandler."""
5109 code = """ uint32_t data_size;
5110 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5111 return error::kOutOfBounds;
5114 file.Write(code)
5116 def WriteHandlerImplementation (self, func, file):
5117 """Overrriden from TypeHandler."""
5118 file.Write(" if (!%sHelper(n, %s)) {\n"
5119 " return error::kInvalidArguments;\n"
5120 " }\n" %
5121 (func.name, func.GetLastOriginalArg().name))
5123 def WriteImmediateHandlerImplementation(self, func, file):
5124 """Overrriden from TypeHandler."""
5125 if func.IsUnsafe():
5126 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5127 if (group_->Get%(resource_name)sServiceId(%(last_arg_name)s[ii], NULL)) {
5128 return error::kInvalidArguments;
5131 scoped_ptr<GLuint[]> service_ids(new GLuint[n]);
5132 gl%(func_name)s(n, service_ids.get());
5133 for (GLsizei ii = 0; ii < n; ++ii) {
5134 group_->Add%(resource_name)sId(%(last_arg_name)s[ii], service_ids[ii]);
5136 """ % { 'func_name': func.original_name,
5137 'last_arg_name': func.GetLastOriginalArg().name,
5138 'resource_name': func.GetInfo('resource_type') })
5139 else:
5140 file.Write(" if (!%sHelper(n, %s)) {\n"
5141 " return error::kInvalidArguments;\n"
5142 " }\n" %
5143 (func.original_name, func.GetLastOriginalArg().name))
5145 def WriteGLES2Implementation(self, func, file):
5146 """Overrriden from TypeHandler."""
5147 log_code = (""" GPU_CLIENT_LOG_CODE_BLOCK({
5148 for (GLsizei i = 0; i < n; ++i) {
5149 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5151 });""" % func.GetOriginalArgs()[1].name)
5152 args = {
5153 'log_code': log_code,
5154 'return_type': func.return_type,
5155 'name': func.original_name,
5156 'typed_args': func.MakeTypedOriginalArgString(""),
5157 'args': func.MakeOriginalArgString(""),
5158 'resource_types': func.GetInfo('resource_types'),
5159 'count_name': func.GetOriginalArgs()[0].name,
5161 file.Write(
5162 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5163 args)
5164 func.WriteDestinationInitalizationValidation(file)
5165 self.WriteClientGLCallLog(func, file)
5166 for arg in func.GetOriginalArgs():
5167 arg.WriteClientSideValidationCode(file, func)
5168 not_shared = func.GetInfo('not_shared')
5169 if not_shared:
5170 alloc_code = (
5172 """ IdAllocator* id_allocator = GetIdAllocator(id_namespaces::k%s);
5173 for (GLsizei ii = 0; ii < n; ++ii)
5174 %s[ii] = id_allocator->AllocateID();""" %
5175 (func.GetInfo('resource_types'), func.GetOriginalArgs()[1].name))
5176 else:
5177 alloc_code = (""" GetIdHandler(id_namespaces::k%(resource_types)s)->
5178 MakeIds(this, 0, %(args)s);""" % args)
5179 args['alloc_code'] = alloc_code
5181 code = """ GPU_CLIENT_SINGLE_THREAD_CHECK();
5182 %(alloc_code)s
5183 %(name)sHelper(%(args)s);
5184 helper_->%(name)sImmediate(%(args)s);
5185 if (share_group_->bind_generates_resource())
5186 helper_->CommandBufferHelper::Flush();
5187 %(log_code)s
5188 CheckGLError();
5192 file.Write(code % args)
5194 def WriteGLES2ImplementationUnitTest(self, func, file):
5195 """Overrriden from TypeHandler."""
5196 code = """
5197 TEST_F(GLES2ImplementationTest, %(name)s) {
5198 GLuint ids[2] = { 0, };
5199 struct Cmds {
5200 cmds::%(name)sImmediate gen;
5201 GLuint data[2];
5203 Cmds expected;
5204 expected.gen.Init(arraysize(ids), &ids[0]);
5205 expected.data[0] = k%(types)sStartId;
5206 expected.data[1] = k%(types)sStartId + 1;
5207 gl_->%(name)s(arraysize(ids), &ids[0]);
5208 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5209 EXPECT_EQ(k%(types)sStartId, ids[0]);
5210 EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
5213 file.Write(code % {
5214 'name': func.name,
5215 'types': func.GetInfo('resource_types'),
5218 def WriteServiceUnitTest(self, func, file, *extras):
5219 """Overrriden from TypeHandler."""
5220 valid_test = """
5221 TEST_P(%(test_name)s, %(name)sValidArgs) {
5222 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5223 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5224 GetSharedMemoryAs<GLuint*>()[0] = kNewClientId;
5225 SpecializedSetup<cmds::%(name)s, 0>(true);
5226 cmds::%(name)s cmd;
5227 cmd.Init(%(args)s);
5228 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5229 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5230 if func.IsUnsafe():
5231 valid_test += """
5232 GLuint service_id;
5233 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5234 EXPECT_EQ(kNewServiceId, service_id)
5237 else:
5238 valid_test += """
5239 EXPECT_TRUE(Get%(resource_name)s(kNewClientId, &service_id) != NULL);
5242 self.WriteValidUnitTest(func, file, valid_test, {
5243 'resource_name': func.GetInfo('resource_type'),
5244 }, *extras)
5245 invalid_test = """
5246 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5247 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5248 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5249 SpecializedSetup<cmds::%(name)s, 0>(false);
5250 cmds::%(name)s cmd;
5251 cmd.Init(%(args)s);
5252 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
5255 self.WriteValidUnitTest(func, file, invalid_test, {
5256 'resource_name': func.GetInfo('resource_type').lower(),
5257 }, *extras)
5259 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5260 """Overrriden from TypeHandler."""
5261 valid_test = """
5262 TEST_P(%(test_name)s, %(name)sValidArgs) {
5263 EXPECT_CALL(*gl_, %(gl_func_name)s(1, _))
5264 .WillOnce(SetArgumentPointee<1>(kNewServiceId));
5265 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5266 GLuint temp = kNewClientId;
5267 SpecializedSetup<cmds::%(name)s, 0>(true);"""
5268 if func.IsUnsafe():
5269 valid_test += """
5270 decoder_->set_unsafe_es3_apis_enabled(true);"""
5271 valid_test += """
5272 cmd->Init(1, &temp);
5273 EXPECT_EQ(error::kNoError,
5274 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5275 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5276 if func.IsUnsafe():
5277 valid_test += """
5278 GLuint service_id;
5279 EXPECT_TRUE(Get%(resource_name)sServiceId(kNewClientId, &service_id));
5280 EXPECT_EQ(kNewServiceId, service_id);
5281 decoder_->set_unsafe_es3_apis_enabled(false);
5282 EXPECT_EQ(error::kUnknownCommand,
5283 ExecuteImmediateCmd(*cmd, sizeof(temp)));
5286 else:
5287 valid_test += """
5288 EXPECT_TRUE(Get%(resource_name)s(kNewClientId) != NULL);
5291 self.WriteValidUnitTest(func, file, valid_test, {
5292 'resource_name': func.GetInfo('resource_type'),
5293 }, *extras)
5294 invalid_test = """
5295 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5296 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _)).Times(0);
5297 cmds::%(name)s* cmd = GetImmediateAs<cmds::%(name)s>();
5298 SpecializedSetup<cmds::%(name)s, 0>(false);
5299 cmd->Init(1, &client_%(resource_name)s_id_);"""
5300 if func.IsUnsafe():
5301 invalid_test += """
5302 decoder_->set_unsafe_es3_apis_enabled(true);
5303 EXPECT_EQ(error::kInvalidArguments,
5304 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5305 decoder_->set_unsafe_es3_apis_enabled(false);
5308 else:
5309 invalid_test += """
5310 EXPECT_EQ(error::kInvalidArguments,
5311 ExecuteImmediateCmd(*cmd, sizeof(&client_%(resource_name)s_id_)));
5314 self.WriteValidUnitTest(func, file, invalid_test, {
5315 'resource_name': func.GetInfo('resource_type').lower(),
5316 }, *extras)
5318 def WriteImmediateCmdComputeSize(self, func, file):
5319 """Overrriden from TypeHandler."""
5320 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5321 file.Write(
5322 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5323 file.Write(" }\n")
5324 file.Write("\n")
5325 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5326 file.Write(" return static_cast<uint32_t>(\n")
5327 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5328 file.Write(" }\n")
5329 file.Write("\n")
5331 def WriteImmediateCmdSetHeader(self, func, file):
5332 """Overrriden from TypeHandler."""
5333 file.Write(" void SetHeader(GLsizei n) {\n")
5334 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5335 file.Write(" }\n")
5336 file.Write("\n")
5338 def WriteImmediateCmdInit(self, func, file):
5339 """Overrriden from TypeHandler."""
5340 last_arg = func.GetLastOriginalArg()
5341 file.Write(" void Init(%s, %s _%s) {\n" %
5342 (func.MakeTypedCmdArgString("_"),
5343 last_arg.type, last_arg.name))
5344 file.Write(" SetHeader(_n);\n")
5345 args = func.GetCmdArgs()
5346 for arg in args:
5347 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5348 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5349 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5350 file.Write(" }\n")
5351 file.Write("\n")
5353 def WriteImmediateCmdSet(self, func, file):
5354 """Overrriden from TypeHandler."""
5355 last_arg = func.GetLastOriginalArg()
5356 copy_args = func.MakeCmdArgString("_", False)
5357 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5358 (func.MakeTypedCmdArgString("_", True),
5359 last_arg.type, last_arg.name))
5360 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5361 (copy_args, last_arg.name))
5362 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5363 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5364 "cmd, size);\n")
5365 file.Write(" }\n")
5366 file.Write("\n")
5368 def WriteImmediateCmdHelper(self, func, file):
5369 """Overrriden from TypeHandler."""
5370 code = """ void %(name)s(%(typed_args)s) {
5371 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5372 gles2::cmds::%(name)s* c =
5373 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5374 if (c) {
5375 c->Init(%(args)s);
5380 file.Write(code % {
5381 "name": func.name,
5382 "typed_args": func.MakeTypedOriginalArgString(""),
5383 "args": func.MakeOriginalArgString(""),
5386 def WriteImmediateFormatTest(self, func, file):
5387 """Overrriden from TypeHandler."""
5388 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5389 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5390 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5391 (func.name, func.name))
5392 file.Write(" void* next_cmd = cmd.Set(\n")
5393 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5394 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5395 func.name)
5396 file.Write(" cmd.header.command);\n")
5397 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5398 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5399 file.Write(" cmd.header.size * 4u);\n")
5400 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5401 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5402 file.Write(" next_cmd, sizeof(cmd) +\n")
5403 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5404 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5405 file.Write("}\n")
5406 file.Write("\n")
5409 class CreateHandler(TypeHandler):
5410 """Handler for glCreate___ type functions."""
5412 def __init__(self):
5413 TypeHandler.__init__(self)
5415 def InitFunction(self, func):
5416 """Overrriden from TypeHandler."""
5417 func.AddCmdArg(Argument("client_id", 'uint32_t'))
5419 def __GetResourceType(self, func):
5420 if func.return_type == "GLsync":
5421 return "Sync"
5422 else:
5423 return func.name[6:] # Create*
5425 def WriteServiceUnitTest(self, func, file, *extras):
5426 """Overrriden from TypeHandler."""
5427 valid_test = """
5428 TEST_P(%(test_name)s, %(name)sValidArgs) {
5429 %(id_type_cast)sEXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
5430 .WillOnce(Return(%(const_service_id)s));
5431 SpecializedSetup<cmds::%(name)s, 0>(true);
5432 cmds::%(name)s cmd;
5433 cmd.Init(%(args)s%(comma)skNewClientId);"""
5434 if func.IsUnsafe():
5435 valid_test += """
5436 decoder_->set_unsafe_es3_apis_enabled(true);"""
5437 valid_test += """
5438 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5439 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5440 if func.IsUnsafe():
5441 valid_test += """
5442 %(return_type)s service_id = 0;
5443 EXPECT_TRUE(Get%(resource_type)sServiceId(kNewClientId, &service_id));
5444 EXPECT_EQ(%(const_service_id)s, service_id);
5445 decoder_->set_unsafe_es3_apis_enabled(false);
5446 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
5449 else:
5450 valid_test += """
5451 EXPECT_TRUE(Get%(resource_type)s(kNewClientId));
5454 comma = ""
5455 cmd_arg_count = 0
5456 for arg in func.GetOriginalArgs():
5457 if not arg.IsConstant():
5458 cmd_arg_count += 1
5459 if cmd_arg_count:
5460 comma = ", "
5461 if func.return_type == 'GLsync':
5462 id_type_cast = ("const GLsync kNewServiceIdGLuint = reinterpret_cast"
5463 "<GLsync>(kNewServiceId);\n ")
5464 const_service_id = "kNewServiceIdGLuint"
5465 else:
5466 id_type_cast = ""
5467 const_service_id = "kNewServiceId"
5468 self.WriteValidUnitTest(func, file, valid_test, {
5469 'comma': comma,
5470 'resource_type': self.__GetResourceType(func),
5471 'return_type': func.return_type,
5472 'id_type_cast': id_type_cast,
5473 'const_service_id': const_service_id,
5474 }, *extras)
5475 invalid_test = """
5476 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
5477 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
5478 SpecializedSetup<cmds::%(name)s, 0>(false);
5479 cmds::%(name)s cmd;
5480 cmd.Init(%(args)s%(comma)skNewClientId);
5481 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));%(gl_error_test)s
5484 self.WriteInvalidUnitTest(func, file, invalid_test, {
5485 'comma': comma,
5486 }, *extras)
5488 def WriteHandlerImplementation (self, func, file):
5489 """Overrriden from TypeHandler."""
5490 if func.IsUnsafe():
5491 code = """ uint32_t client_id = c.client_id;
5492 %(return_type)s service_id = 0;
5493 if (group_->Get%(resource_name)sServiceId(client_id, &service_id)) {
5494 return error::kInvalidArguments;
5496 service_id = %(gl_func_name)s(%(gl_args)s);
5497 if (service_id) {
5498 group_->Add%(resource_name)sId(client_id, service_id);
5501 else:
5502 code = """ uint32_t client_id = c.client_id;
5503 if (Get%(resource_name)s(client_id)) {
5504 return error::kInvalidArguments;
5506 %(return_type)s service_id = %(gl_func_name)s(%(gl_args)s);
5507 if (service_id) {
5508 Create%(resource_name)s(client_id, service_id%(gl_args_with_comma)s);
5511 file.Write(code % {
5512 'resource_name': self.__GetResourceType(func),
5513 'return_type': func.return_type,
5514 'gl_func_name': func.GetGLFunctionName(),
5515 'gl_args': func.MakeOriginalArgString(""),
5516 'gl_args_with_comma': func.MakeOriginalArgString("", True) })
5518 def WriteGLES2Implementation(self, func, file):
5519 """Overrriden from TypeHandler."""
5520 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5521 (func.return_type, func.original_name,
5522 func.MakeTypedOriginalArgString("")))
5523 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5524 func.WriteDestinationInitalizationValidation(file)
5525 self.WriteClientGLCallLog(func, file)
5526 for arg in func.GetOriginalArgs():
5527 arg.WriteClientSideValidationCode(file, func)
5528 file.Write(" GLuint client_id;\n")
5529 if func.return_type == "GLsync":
5530 file.Write(
5531 " GetIdHandler(id_namespaces::kSyncs)->\n")
5532 else:
5533 file.Write(
5534 " GetIdHandler(id_namespaces::kProgramsAndShaders)->\n")
5535 file.Write(" MakeIds(this, 0, 1, &client_id);\n")
5536 file.Write(" helper_->%s(%s);\n" %
5537 (func.name, func.MakeCmdArgString("")))
5538 file.Write(' GPU_CLIENT_LOG("returned " << client_id);\n')
5539 file.Write(" CheckGLError();\n")
5540 if func.return_type == "GLsync":
5541 file.Write(" return reinterpret_cast<GLsync>(client_id);\n")
5542 else:
5543 file.Write(" return client_id;\n")
5544 file.Write("}\n")
5545 file.Write("\n")
5548 class DeleteHandler(TypeHandler):
5549 """Handler for glDelete___ single resource type functions."""
5551 def __init__(self):
5552 TypeHandler.__init__(self)
5554 def WriteServiceImplementation(self, func, file):
5555 """Overrriden from TypeHandler."""
5556 if func.IsUnsafe():
5557 TypeHandler.WriteServiceImplementation(self, func, file)
5558 # HandleDeleteShader and HandleDeleteProgram are manually written.
5559 pass
5561 def WriteGLES2Implementation(self, func, file):
5562 """Overrriden from TypeHandler."""
5563 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5564 (func.return_type, func.original_name,
5565 func.MakeTypedOriginalArgString("")))
5566 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5567 func.WriteDestinationInitalizationValidation(file)
5568 self.WriteClientGLCallLog(func, file)
5569 for arg in func.GetOriginalArgs():
5570 arg.WriteClientSideValidationCode(file, func)
5571 file.Write(
5572 " GPU_CLIENT_DCHECK(%s != 0);\n" % func.GetOriginalArgs()[-1].name)
5573 file.Write(" %sHelper(%s);\n" %
5574 (func.original_name, func.GetOriginalArgs()[-1].name))
5575 file.Write(" CheckGLError();\n")
5576 file.Write("}\n")
5577 file.Write("\n")
5579 def WriteHandlerImplementation (self, func, file):
5580 """Overrriden from TypeHandler."""
5581 assert len(func.GetOriginalArgs()) == 1
5582 arg = func.GetOriginalArgs()[0]
5583 if func.IsUnsafe():
5584 file.Write(""" %(arg_type)s service_id = 0;
5585 if (group_->Get%(resource_type)sServiceId(%(arg_name)s, &service_id)) {
5586 glDelete%(resource_type)s(service_id);
5587 group_->Remove%(resource_type)sId(%(arg_name)s);
5588 } else {
5589 LOCAL_SET_GL_ERROR(
5590 GL_INVALID_VALUE, "gl%(func_name)s", "unknown %(arg_name)s");
5592 """ % { 'resource_type': func.GetInfo('resource_type'),
5593 'arg_name': arg.name,
5594 'arg_type': arg.type,
5595 'func_name': func.original_name })
5596 else:
5597 file.Write(" %sHelper(%s);\n" % (func.original_name, arg.name))
5599 class DELnHandler(TypeHandler):
5600 """Handler for glDelete___ type functions."""
5602 def __init__(self):
5603 TypeHandler.__init__(self)
5605 def WriteGetDataSizeCode(self, func, file):
5606 """Overrriden from TypeHandler."""
5607 code = """ uint32_t data_size;
5608 if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {
5609 return error::kOutOfBounds;
5612 file.Write(code)
5614 def WriteGLES2ImplementationUnitTest(self, func, file):
5615 """Overrriden from TypeHandler."""
5616 code = """
5617 TEST_F(GLES2ImplementationTest, %(name)s) {
5618 GLuint ids[2] = { k%(types)sStartId, k%(types)sStartId + 1 };
5619 struct Cmds {
5620 cmds::%(name)sImmediate del;
5621 GLuint data[2];
5623 Cmds expected;
5624 expected.del.Init(arraysize(ids), &ids[0]);
5625 expected.data[0] = k%(types)sStartId;
5626 expected.data[1] = k%(types)sStartId + 1;
5627 gl_->%(name)s(arraysize(ids), &ids[0]);
5628 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
5631 file.Write(code % {
5632 'name': func.name,
5633 'types': func.GetInfo('resource_types'),
5636 def WriteServiceUnitTest(self, func, file, *extras):
5637 """Overrriden from TypeHandler."""
5638 valid_test = """
5639 TEST_P(%(test_name)s, %(name)sValidArgs) {
5640 EXPECT_CALL(
5641 *gl_,
5642 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5643 .Times(1);
5644 GetSharedMemoryAs<GLuint*>()[0] = client_%(resource_name)s_id_;
5645 SpecializedSetup<cmds::%(name)s, 0>(true);
5646 cmds::%(name)s cmd;
5647 cmd.Init(%(args)s);
5648 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5649 EXPECT_EQ(GL_NO_ERROR, GetGLError());
5650 EXPECT_TRUE(
5651 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5654 self.WriteValidUnitTest(func, file, valid_test, {
5655 'resource_name': func.GetInfo('resource_type').lower(),
5656 'upper_resource_name': func.GetInfo('resource_type'),
5657 }, *extras)
5658 invalid_test = """
5659 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5660 GetSharedMemoryAs<GLuint*>()[0] = kInvalidClientId;
5661 SpecializedSetup<cmds::%(name)s, 0>(false);
5662 cmds::%(name)s cmd;
5663 cmd.Init(%(args)s);
5664 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
5667 self.WriteValidUnitTest(func, file, invalid_test, *extras)
5669 def WriteImmediateServiceUnitTest(self, func, file, *extras):
5670 """Overrriden from TypeHandler."""
5671 valid_test = """
5672 TEST_P(%(test_name)s, %(name)sValidArgs) {
5673 EXPECT_CALL(
5674 *gl_,
5675 %(gl_func_name)s(1, Pointee(kService%(upper_resource_name)sId)))
5676 .Times(1);
5677 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5678 SpecializedSetup<cmds::%(name)s, 0>(true);
5679 cmd.Init(1, &client_%(resource_name)s_id_);"""
5680 if func.IsUnsafe():
5681 valid_test += """
5682 decoder_->set_unsafe_es3_apis_enabled(true);"""
5683 valid_test += """
5684 EXPECT_EQ(error::kNoError,
5685 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5686 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
5687 if func.IsUnsafe():
5688 valid_test += """
5689 EXPECT_FALSE(Get%(upper_resource_name)sServiceId(
5690 client_%(resource_name)s_id_, NULL));
5691 decoder_->set_unsafe_es3_apis_enabled(false);
5692 EXPECT_EQ(error::kUnknownCommand,
5693 ExecuteImmediateCmd(cmd, sizeof(client_%(resource_name)s_id_)));
5696 else:
5697 valid_test += """
5698 EXPECT_TRUE(
5699 Get%(upper_resource_name)s(client_%(resource_name)s_id_) == NULL);
5702 self.WriteValidUnitTest(func, file, valid_test, {
5703 'resource_name': func.GetInfo('resource_type').lower(),
5704 'upper_resource_name': func.GetInfo('resource_type'),
5705 }, *extras)
5706 invalid_test = """
5707 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
5708 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
5709 SpecializedSetup<cmds::%(name)s, 0>(false);
5710 GLuint temp = kInvalidClientId;
5711 cmd.Init(1, &temp);"""
5712 if func.IsUnsafe():
5713 invalid_test += """
5714 decoder_->set_unsafe_es3_apis_enabled(true);
5715 EXPECT_EQ(error::kNoError,
5716 ExecuteImmediateCmd(cmd, sizeof(temp)));
5717 decoder_->set_unsafe_es3_apis_enabled(false);
5718 EXPECT_EQ(error::kUnknownCommand,
5719 ExecuteImmediateCmd(cmd, sizeof(temp)));
5722 else:
5723 invalid_test += """
5724 EXPECT_EQ(error::kNoError,
5725 ExecuteImmediateCmd(cmd, sizeof(temp)));
5728 self.WriteValidUnitTest(func, file, invalid_test, *extras)
5730 def WriteHandlerImplementation (self, func, file):
5731 """Overrriden from TypeHandler."""
5732 file.Write(" %sHelper(n, %s);\n" %
5733 (func.name, func.GetLastOriginalArg().name))
5735 def WriteImmediateHandlerImplementation (self, func, file):
5736 """Overrriden from TypeHandler."""
5737 if func.IsUnsafe():
5738 file.Write(""" for (GLsizei ii = 0; ii < n; ++ii) {
5739 GLuint service_id = 0;
5740 if (group_->Get%(resource_type)sServiceId(
5741 %(last_arg_name)s[ii], &service_id)) {
5742 glDelete%(resource_type)ss(1, &service_id);
5743 group_->Remove%(resource_type)sId(%(last_arg_name)s[ii]);
5746 """ % { 'resource_type': func.GetInfo('resource_type'),
5747 'last_arg_name': func.GetLastOriginalArg().name })
5748 else:
5749 file.Write(" %sHelper(n, %s);\n" %
5750 (func.original_name, func.GetLastOriginalArg().name))
5752 def WriteGLES2Implementation(self, func, file):
5753 """Overrriden from TypeHandler."""
5754 impl_decl = func.GetInfo('impl_decl')
5755 if impl_decl == None or impl_decl == True:
5756 args = {
5757 'return_type': func.return_type,
5758 'name': func.original_name,
5759 'typed_args': func.MakeTypedOriginalArgString(""),
5760 'args': func.MakeOriginalArgString(""),
5761 'resource_type': func.GetInfo('resource_type').lower(),
5762 'count_name': func.GetOriginalArgs()[0].name,
5764 file.Write(
5765 "%(return_type)s GLES2Implementation::%(name)s(%(typed_args)s) {\n" %
5766 args)
5767 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5768 func.WriteDestinationInitalizationValidation(file)
5769 self.WriteClientGLCallLog(func, file)
5770 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
5771 for (GLsizei i = 0; i < n; ++i) {
5772 GPU_CLIENT_LOG(" " << i << ": " << %s[i]);
5775 """ % func.GetOriginalArgs()[1].name)
5776 file.Write(""" GPU_CLIENT_DCHECK_CODE_BLOCK({
5777 for (GLsizei i = 0; i < n; ++i) {
5778 DCHECK(%s[i] != 0);
5781 """ % func.GetOriginalArgs()[1].name)
5782 for arg in func.GetOriginalArgs():
5783 arg.WriteClientSideValidationCode(file, func)
5784 code = """ %(name)sHelper(%(args)s);
5785 CheckGLError();
5789 file.Write(code % args)
5791 def WriteImmediateCmdComputeSize(self, func, file):
5792 """Overrriden from TypeHandler."""
5793 file.Write(" static uint32_t ComputeDataSize(GLsizei n) {\n")
5794 file.Write(
5795 " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n")
5796 file.Write(" }\n")
5797 file.Write("\n")
5798 file.Write(" static uint32_t ComputeSize(GLsizei n) {\n")
5799 file.Write(" return static_cast<uint32_t>(\n")
5800 file.Write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n")
5801 file.Write(" }\n")
5802 file.Write("\n")
5804 def WriteImmediateCmdSetHeader(self, func, file):
5805 """Overrriden from TypeHandler."""
5806 file.Write(" void SetHeader(GLsizei n) {\n")
5807 file.Write(" header.SetCmdByTotalSize<ValueType>(ComputeSize(n));\n")
5808 file.Write(" }\n")
5809 file.Write("\n")
5811 def WriteImmediateCmdInit(self, func, file):
5812 """Overrriden from TypeHandler."""
5813 last_arg = func.GetLastOriginalArg()
5814 file.Write(" void Init(%s, %s _%s) {\n" %
5815 (func.MakeTypedCmdArgString("_"),
5816 last_arg.type, last_arg.name))
5817 file.Write(" SetHeader(_n);\n")
5818 args = func.GetCmdArgs()
5819 for arg in args:
5820 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
5821 file.Write(" memcpy(ImmediateDataAddress(this),\n")
5822 file.Write(" _%s, ComputeDataSize(_n));\n" % last_arg.name)
5823 file.Write(" }\n")
5824 file.Write("\n")
5826 def WriteImmediateCmdSet(self, func, file):
5827 """Overrriden from TypeHandler."""
5828 last_arg = func.GetLastOriginalArg()
5829 copy_args = func.MakeCmdArgString("_", False)
5830 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
5831 (func.MakeTypedCmdArgString("_", True),
5832 last_arg.type, last_arg.name))
5833 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
5834 (copy_args, last_arg.name))
5835 file.Write(" const uint32_t size = ComputeSize(_n);\n")
5836 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
5837 "cmd, size);\n")
5838 file.Write(" }\n")
5839 file.Write("\n")
5841 def WriteImmediateCmdHelper(self, func, file):
5842 """Overrriden from TypeHandler."""
5843 code = """ void %(name)s(%(typed_args)s) {
5844 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(n);
5845 gles2::cmds::%(name)s* c =
5846 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
5847 if (c) {
5848 c->Init(%(args)s);
5853 file.Write(code % {
5854 "name": func.name,
5855 "typed_args": func.MakeTypedOriginalArgString(""),
5856 "args": func.MakeOriginalArgString(""),
5859 def WriteImmediateFormatTest(self, func, file):
5860 """Overrriden from TypeHandler."""
5861 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
5862 file.Write(" static GLuint ids[] = { 12, 23, 34, };\n")
5863 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
5864 (func.name, func.name))
5865 file.Write(" void* next_cmd = cmd.Set(\n")
5866 file.Write(" &cmd, static_cast<GLsizei>(arraysize(ids)), ids);\n")
5867 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
5868 func.name)
5869 file.Write(" cmd.header.command);\n")
5870 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
5871 file.Write(" RoundSizeToMultipleOfEntries(cmd.n * 4u),\n")
5872 file.Write(" cmd.header.size * 4u);\n")
5873 file.Write(" EXPECT_EQ(static_cast<GLsizei>(arraysize(ids)), cmd.n);\n");
5874 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
5875 file.Write(" next_cmd, sizeof(cmd) +\n")
5876 file.Write(" RoundSizeToMultipleOfEntries(arraysize(ids) * 4u));\n")
5877 file.Write(" // TODO(gman): Check that ids were inserted;\n")
5878 file.Write("}\n")
5879 file.Write("\n")
5882 class GETnHandler(TypeHandler):
5883 """Handler for GETn for glGetBooleanv, glGetFloatv, ... type functions."""
5885 def __init__(self):
5886 TypeHandler.__init__(self)
5888 def NeedsDataTransferFunction(self, func):
5889 """Overriden from TypeHandler."""
5890 return False
5892 def WriteServiceImplementation(self, func, file):
5893 """Overrriden from TypeHandler."""
5894 self.WriteServiceHandlerFunctionHeader(func, file)
5895 last_arg = func.GetLastOriginalArg()
5896 # All except shm_id and shm_offset.
5897 all_but_last_args = func.GetCmdArgs()[:-2]
5898 for arg in all_but_last_args:
5899 arg.WriteGetCode(file)
5901 code = """ typedef cmds::%(func_name)s::Result Result;
5902 GLsizei num_values = 0;
5903 GetNumValuesReturnedForGLGet(pname, &num_values);
5904 Result* result = GetSharedMemoryAs<Result*>(
5905 c.%(last_arg_name)s_shm_id, c.%(last_arg_name)s_shm_offset,
5906 Result::ComputeSize(num_values));
5907 %(last_arg_type)s %(last_arg_name)s = result ? result->GetData() : NULL;
5909 file.Write(code % {
5910 'last_arg_type': last_arg.type,
5911 'last_arg_name': last_arg.name,
5912 'func_name': func.name,
5914 func.WriteHandlerValidation(file)
5915 code = """ // Check that the client initialized the result.
5916 if (result->size != 0) {
5917 return error::kInvalidArguments;
5920 shadowed = func.GetInfo('shadowed')
5921 if not shadowed:
5922 file.Write(' LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("%s");\n' % func.name)
5923 file.Write(code)
5924 func.WriteHandlerImplementation(file)
5925 if shadowed:
5926 code = """ result->SetNumResults(num_values);
5927 return error::kNoError;
5930 else:
5931 code = """ GLenum error = glGetError();
5932 if (error == GL_NO_ERROR) {
5933 result->SetNumResults(num_values);
5934 } else {
5935 LOCAL_SET_GL_ERROR(error, "%(func_name)s", "");
5937 return error::kNoError;
5941 file.Write(code % {'func_name': func.name})
5943 def WriteGLES2Implementation(self, func, file):
5944 """Overrriden from TypeHandler."""
5945 impl_decl = func.GetInfo('impl_decl')
5946 if impl_decl == None or impl_decl == True:
5947 file.Write("%s GLES2Implementation::%s(%s) {\n" %
5948 (func.return_type, func.original_name,
5949 func.MakeTypedOriginalArgString("")))
5950 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
5951 func.WriteDestinationInitalizationValidation(file)
5952 self.WriteClientGLCallLog(func, file)
5953 for arg in func.GetOriginalArgs():
5954 arg.WriteClientSideValidationCode(file, func)
5955 all_but_last_args = func.GetOriginalArgs()[:-1]
5956 args = []
5957 has_length_arg = False
5958 for arg in all_but_last_args:
5959 if arg.type == 'GLsync':
5960 args.append('ToGLuint(%s)' % arg.name)
5961 elif arg.name.endswith('size') and arg.type == 'GLsizei':
5962 continue
5963 elif arg.name == 'length':
5964 has_length_arg = True
5965 continue
5966 else:
5967 args.append(arg.name)
5968 arg_string = ", ".join(args)
5969 all_arg_string = (
5970 ", ".join([
5971 "%s" % arg.name
5972 for arg in func.GetOriginalArgs() if not arg.IsConstant()]))
5973 self.WriteTraceEvent(func, file)
5974 code = """ if (%(func_name)sHelper(%(all_arg_string)s)) {
5975 return;
5977 typedef cmds::%(func_name)s::Result Result;
5978 Result* result = GetResultAs<Result*>();
5979 if (!result) {
5980 return;
5982 result->SetNumResults(0);
5983 helper_->%(func_name)s(%(arg_string)s,
5984 GetResultShmId(), GetResultShmOffset());
5985 WaitForCmd();
5986 result->CopyResult(%(last_arg_name)s);
5987 GPU_CLIENT_LOG_CODE_BLOCK({
5988 for (int32_t i = 0; i < result->GetNumResults(); ++i) {
5989 GPU_CLIENT_LOG(" " << i << ": " << result->GetData()[i]);
5991 });"""
5992 if has_length_arg:
5993 code += """
5994 if (length) {
5995 *length = result->GetNumResults();
5996 }"""
5997 code += """
5998 CheckGLError();
6001 file.Write(code % {
6002 'func_name': func.name,
6003 'arg_string': arg_string,
6004 'all_arg_string': all_arg_string,
6005 'last_arg_name': func.GetLastOriginalArg().name,
6008 def WriteGLES2ImplementationUnitTest(self, func, file):
6009 """Writes the GLES2 Implemention unit test."""
6010 code = """
6011 TEST_F(GLES2ImplementationTest, %(name)s) {
6012 struct Cmds {
6013 cmds::%(name)s cmd;
6015 typedef cmds::%(name)s::Result Result;
6016 Result::Type result = 0;
6017 Cmds expected;
6018 ExpectedMemoryInfo result1 = GetExpectedResultMemory(4);
6019 expected.cmd.Init(%(cmd_args)s, result1.id, result1.offset);
6020 EXPECT_CALL(*command_buffer(), OnFlush())
6021 .WillOnce(SetMemory(result1.ptr, SizedResultHelper<Result::Type>(1)))
6022 .RetiresOnSaturation();
6023 gl_->%(name)s(%(args)s, &result);
6024 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6025 EXPECT_EQ(static_cast<Result::Type>(1), result);
6028 first_cmd_arg = func.GetCmdArgs()[0].GetValidNonCachedClientSideCmdArg(func)
6029 if not first_cmd_arg:
6030 return
6032 first_gl_arg = func.GetOriginalArgs()[0].GetValidNonCachedClientSideArg(
6033 func)
6035 cmd_arg_strings = [first_cmd_arg]
6036 for arg in func.GetCmdArgs()[1:-2]:
6037 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6038 gl_arg_strings = [first_gl_arg]
6039 for arg in func.GetOriginalArgs()[1:-1]:
6040 gl_arg_strings.append(arg.GetValidClientSideArg(func))
6042 file.Write(code % {
6043 'name': func.name,
6044 'args': ", ".join(gl_arg_strings),
6045 'cmd_args': ", ".join(cmd_arg_strings),
6048 def WriteServiceUnitTest(self, func, file, *extras):
6049 """Overrriden from TypeHandler."""
6050 valid_test = """
6051 TEST_P(%(test_name)s, %(name)sValidArgs) {
6052 EXPECT_CALL(*gl_, GetError())
6053 .WillOnce(Return(GL_NO_ERROR))
6054 .WillOnce(Return(GL_NO_ERROR))
6055 .RetiresOnSaturation();
6056 SpecializedSetup<cmds::%(name)s, 0>(true);
6057 typedef cmds::%(name)s::Result Result;
6058 Result* result = static_cast<Result*>(shared_memory_address_);
6059 EXPECT_CALL(*gl_, %(gl_func_name)s(%(local_gl_args)s));
6060 result->size = 0;
6061 cmds::%(name)s cmd;
6062 cmd.Init(%(cmd_args)s);"""
6063 if func.IsUnsafe():
6064 valid_test += """
6065 decoder_->set_unsafe_es3_apis_enabled(true);"""
6066 valid_test += """
6067 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6068 EXPECT_EQ(decoder_->GetGLES2Util()->GLGetNumValuesReturned(
6069 %(valid_pname)s),
6070 result->GetNumResults());
6071 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6072 if func.IsUnsafe():
6073 valid_test += """
6074 decoder_->set_unsafe_es3_apis_enabled(false);
6075 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
6076 valid_test += """
6079 gl_arg_strings = []
6080 cmd_arg_strings = []
6081 valid_pname = ''
6082 for arg in func.GetOriginalArgs()[:-1]:
6083 if arg.name == 'length':
6084 gl_arg_value = 'nullptr'
6085 elif arg.name.endswith('size'):
6086 gl_arg_value = ("decoder_->GetGLES2Util()->GLGetNumValuesReturned(%s)" %
6087 valid_pname)
6088 elif arg.type == 'GLsync':
6089 gl_arg_value = 'reinterpret_cast<GLsync>(kServiceSyncId)'
6090 else:
6091 gl_arg_value = arg.GetValidGLArg(func)
6092 gl_arg_strings.append(gl_arg_value)
6093 if arg.name == 'pname':
6094 valid_pname = gl_arg_value
6095 if arg.name.endswith('size') or arg.name == 'length':
6096 continue
6097 if arg.type == 'GLsync':
6098 arg_value = 'client_sync_id_'
6099 else:
6100 arg_value = arg.GetValidArg(func)
6101 cmd_arg_strings.append(arg_value)
6102 if func.GetInfo('gl_test_func') == 'glGetIntegerv':
6103 gl_arg_strings.append("_")
6104 else:
6105 gl_arg_strings.append("result->GetData()")
6106 cmd_arg_strings.append("shared_memory_id_")
6107 cmd_arg_strings.append("shared_memory_offset_")
6109 self.WriteValidUnitTest(func, file, valid_test, {
6110 'local_gl_args': ", ".join(gl_arg_strings),
6111 'cmd_args': ", ".join(cmd_arg_strings),
6112 'valid_pname': valid_pname,
6113 }, *extras)
6115 if not func.IsUnsafe():
6116 invalid_test = """
6117 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6118 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6119 SpecializedSetup<cmds::%(name)s, 0>(false);
6120 cmds::%(name)s::Result* result =
6121 static_cast<cmds::%(name)s::Result*>(shared_memory_address_);
6122 result->size = 0;
6123 cmds::%(name)s cmd;
6124 cmd.Init(%(args)s);
6125 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));
6126 EXPECT_EQ(0u, result->size);%(gl_error_test)s
6129 self.WriteInvalidUnitTest(func, file, invalid_test, *extras)
6131 class ArrayArgTypeHandler(TypeHandler):
6132 """Base class for type handlers that handle args that are arrays"""
6134 def __init__(self):
6135 TypeHandler.__init__(self)
6137 def GetArrayType(self, func):
6138 """Returns the type of the element in the element array being PUT to."""
6139 for arg in func.GetOriginalArgs():
6140 if arg.IsPointer():
6141 element_type = arg.GetPointedType()
6142 return element_type
6144 # Special case: array type handler is used for a function that is forwarded
6145 # to the actual array type implementation
6146 element_type = func.GetOriginalArgs()[-1].type
6147 assert all(arg.type == element_type \
6148 for arg in func.GetOriginalArgs()[-self.GetArrayCount(func):])
6149 return element_type
6151 def GetArrayCount(self, func):
6152 """Returns the count of the elements in the array being PUT to."""
6153 return func.GetInfo('count')
6155 class PUTHandler(ArrayArgTypeHandler):
6156 """Handler for glTexParameter_v, glVertexAttrib_v functions."""
6158 def __init__(self):
6159 ArrayArgTypeHandler.__init__(self)
6161 def WriteServiceUnitTest(self, func, file, *extras):
6162 """Writes the service unit test for a command."""
6163 expected_call = "EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));"
6164 if func.GetInfo("first_element_only"):
6165 gl_arg_strings = [
6166 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()
6168 gl_arg_strings[-1] = "*" + gl_arg_strings[-1]
6169 expected_call = ("EXPECT_CALL(*gl_, %%(gl_func_name)s(%s));" %
6170 ", ".join(gl_arg_strings))
6171 valid_test = """
6172 TEST_P(%(test_name)s, %(name)sValidArgs) {
6173 SpecializedSetup<cmds::%(name)s, 0>(true);
6174 cmds::%(name)s cmd;
6175 cmd.Init(%(args)s);
6176 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6177 %(expected_call)s
6178 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6179 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6182 extra = {
6183 'data_type': self.GetArrayType(func),
6184 'data_value': func.GetInfo('data_value') or '0',
6185 'expected_call': expected_call,
6187 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6189 invalid_test = """
6190 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6191 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
6192 SpecializedSetup<cmds::%(name)s, 0>(false);
6193 cmds::%(name)s cmd;
6194 cmd.Init(%(args)s);
6195 GetSharedMemoryAs<%(data_type)s*>()[0] = %(data_value)s;
6196 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
6199 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6201 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6202 """Writes the service unit test for a command."""
6203 valid_test = """
6204 TEST_P(%(test_name)s, %(name)sValidArgs) {
6205 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6206 SpecializedSetup<cmds::%(name)s, 0>(true);
6207 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6208 cmd.Init(%(gl_args)s, &temp[0]);
6209 EXPECT_CALL(
6210 *gl_,
6211 %(gl_func_name)s(%(gl_args)s, %(data_ref)sreinterpret_cast<
6212 %(data_type)s*>(ImmediateDataAddress(&cmd))));"""
6213 if func.IsUnsafe():
6214 valid_test += """
6215 decoder_->set_unsafe_es3_apis_enabled(true);"""
6216 valid_test += """
6217 EXPECT_EQ(error::kNoError,
6218 ExecuteImmediateCmd(cmd, sizeof(temp)));
6219 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6220 if func.IsUnsafe():
6221 valid_test += """
6222 decoder_->set_unsafe_es3_apis_enabled(false);
6223 EXPECT_EQ(error::kUnknownCommand,
6224 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6225 valid_test += """
6228 gl_arg_strings = [
6229 arg.GetValidGLArg(func) for arg in func.GetOriginalArgs()[0:-1]
6231 gl_any_strings = ["_"] * len(gl_arg_strings)
6233 extra = {
6234 'data_ref': ("*" if func.GetInfo('first_element_only') else ""),
6235 'data_type': self.GetArrayType(func),
6236 'data_count': self.GetArrayCount(func),
6237 'data_value': func.GetInfo('data_value') or '0',
6238 'gl_args': ", ".join(gl_arg_strings),
6239 'gl_any_args': ", ".join(gl_any_strings),
6241 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6243 invalid_test = """
6244 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6245 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();"""
6246 if func.IsUnsafe():
6247 invalid_test += """
6248 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(1);
6250 else:
6251 invalid_test += """
6252 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6254 invalid_test += """
6255 SpecializedSetup<cmds::%(name)s, 0>(false);
6256 %(data_type)s temp[%(data_count)s] = { %(data_value)s, };
6257 cmd.Init(%(all_but_last_args)s, &temp[0]);"""
6258 if func.IsUnsafe():
6259 invalid_test += """
6260 decoder_->set_unsafe_es3_apis_enabled(true);
6261 EXPECT_EQ(error::%(parse_result)s,
6262 ExecuteImmediateCmd(cmd, sizeof(temp)));
6263 decoder_->set_unsafe_es3_apis_enabled(false);
6266 else:
6267 invalid_test += """
6268 EXPECT_EQ(error::%(parse_result)s,
6269 ExecuteImmediateCmd(cmd, sizeof(temp)));
6270 %(gl_error_test)s
6273 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6275 def WriteGetDataSizeCode(self, func, file):
6276 """Overrriden from TypeHandler."""
6277 code = """ uint32_t data_size;
6278 if (!ComputeDataSize(1, sizeof(%s), %d, &data_size)) {
6279 return error::kOutOfBounds;
6282 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6283 if func.IsImmediate():
6284 file.Write(" if (data_size > immediate_data_size) {\n")
6285 file.Write(" return error::kOutOfBounds;\n")
6286 file.Write(" }\n")
6288 def __NeedsToCalcDataCount(self, func):
6289 use_count_func = func.GetInfo('use_count_func')
6290 return use_count_func != None and use_count_func != False
6292 def WriteGLES2Implementation(self, func, file):
6293 """Overrriden from TypeHandler."""
6294 impl_func = func.GetInfo('impl_func')
6295 if (impl_func != None and impl_func != True):
6296 return;
6297 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6298 (func.return_type, func.original_name,
6299 func.MakeTypedOriginalArgString("")))
6300 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6301 func.WriteDestinationInitalizationValidation(file)
6302 self.WriteClientGLCallLog(func, file)
6304 if self.__NeedsToCalcDataCount(func):
6305 file.Write(" size_t count = GLES2Util::Calc%sDataCount(%s);\n" %
6306 (func.name, func.GetOriginalArgs()[0].name))
6307 file.Write(" DCHECK_LE(count, %du);\n" % self.GetArrayCount(func))
6308 else:
6309 file.Write(" size_t count = %d;" % self.GetArrayCount(func))
6310 file.Write(" for (size_t ii = 0; ii < count; ++ii)\n")
6311 file.Write(' GPU_CLIENT_LOG("value[" << ii << "]: " << %s[ii]);\n' %
6312 func.GetLastOriginalArg().name)
6313 for arg in func.GetOriginalArgs():
6314 arg.WriteClientSideValidationCode(file, func)
6315 file.Write(" helper_->%sImmediate(%s);\n" %
6316 (func.name, func.MakeOriginalArgString("")))
6317 file.Write(" CheckGLError();\n")
6318 file.Write("}\n")
6319 file.Write("\n")
6321 def WriteGLES2ImplementationUnitTest(self, func, file):
6322 """Writes the GLES2 Implemention unit test."""
6323 client_test = func.GetInfo('client_test')
6324 if (client_test != None and client_test != True):
6325 return;
6326 code = """
6327 TEST_F(GLES2ImplementationTest, %(name)s) {
6328 %(type)s data[%(count)d] = {0};
6329 struct Cmds {
6330 cmds::%(name)sImmediate cmd;
6331 %(type)s data[%(count)d];
6334 for (int jj = 0; jj < %(count)d; ++jj) {
6335 data[jj] = static_cast<%(type)s>(jj);
6337 Cmds expected;
6338 expected.cmd.Init(%(cmd_args)s, &data[0]);
6339 gl_->%(name)s(%(args)s, &data[0]);
6340 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6343 cmd_arg_strings = [
6344 arg.GetValidClientSideCmdArg(func) for arg in func.GetCmdArgs()[0:-2]
6346 gl_arg_strings = [
6347 arg.GetValidClientSideArg(func) for arg in func.GetOriginalArgs()[0:-1]
6350 file.Write(code % {
6351 'name': func.name,
6352 'type': self.GetArrayType(func),
6353 'count': self.GetArrayCount(func),
6354 'args': ", ".join(gl_arg_strings),
6355 'cmd_args': ", ".join(cmd_arg_strings),
6358 def WriteImmediateCmdComputeSize(self, func, file):
6359 """Overrriden from TypeHandler."""
6360 file.Write(" static uint32_t ComputeDataSize() {\n")
6361 file.Write(" return static_cast<uint32_t>(\n")
6362 file.Write(" sizeof(%s) * %d);\n" %
6363 (self.GetArrayType(func), self.GetArrayCount(func)))
6364 file.Write(" }\n")
6365 file.Write("\n")
6366 if self.__NeedsToCalcDataCount(func):
6367 file.Write(" static uint32_t ComputeEffectiveDataSize(%s %s) {\n" %
6368 (func.GetOriginalArgs()[0].type,
6369 func.GetOriginalArgs()[0].name))
6370 file.Write(" return static_cast<uint32_t>(\n")
6371 file.Write(" sizeof(%s) * GLES2Util::Calc%sDataCount(%s));\n" %
6372 (self.GetArrayType(func), func.original_name,
6373 func.GetOriginalArgs()[0].name))
6374 file.Write(" }\n")
6375 file.Write("\n")
6376 file.Write(" static uint32_t ComputeSize() {\n")
6377 file.Write(" return static_cast<uint32_t>(\n")
6378 file.Write(
6379 " sizeof(ValueType) + ComputeDataSize());\n")
6380 file.Write(" }\n")
6381 file.Write("\n")
6383 def WriteImmediateCmdSetHeader(self, func, file):
6384 """Overrriden from TypeHandler."""
6385 file.Write(" void SetHeader() {\n")
6386 file.Write(
6387 " header.SetCmdByTotalSize<ValueType>(ComputeSize());\n")
6388 file.Write(" }\n")
6389 file.Write("\n")
6391 def WriteImmediateCmdInit(self, func, file):
6392 """Overrriden from TypeHandler."""
6393 last_arg = func.GetLastOriginalArg()
6394 file.Write(" void Init(%s, %s _%s) {\n" %
6395 (func.MakeTypedCmdArgString("_"),
6396 last_arg.type, last_arg.name))
6397 file.Write(" SetHeader();\n")
6398 args = func.GetCmdArgs()
6399 for arg in args:
6400 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6401 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6402 if self.__NeedsToCalcDataCount(func):
6403 file.Write(" _%s, ComputeEffectiveDataSize(%s));" %
6404 (last_arg.name, func.GetOriginalArgs()[0].name))
6405 file.Write("""
6406 DCHECK_GE(ComputeDataSize(), ComputeEffectiveDataSize(%(arg)s));
6407 char* pointer = reinterpret_cast<char*>(ImmediateDataAddress(this)) +
6408 ComputeEffectiveDataSize(%(arg)s);
6409 memset(pointer, 0, ComputeDataSize() - ComputeEffectiveDataSize(%(arg)s));
6410 """ % { 'arg': func.GetOriginalArgs()[0].name, })
6411 else:
6412 file.Write(" _%s, ComputeDataSize());\n" % last_arg.name)
6413 file.Write(" }\n")
6414 file.Write("\n")
6416 def WriteImmediateCmdSet(self, func, file):
6417 """Overrriden from TypeHandler."""
6418 last_arg = func.GetLastOriginalArg()
6419 copy_args = func.MakeCmdArgString("_", False)
6420 file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
6421 (func.MakeTypedCmdArgString("_", True),
6422 last_arg.type, last_arg.name))
6423 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
6424 (copy_args, last_arg.name))
6425 file.Write(" const uint32_t size = ComputeSize();\n")
6426 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6427 "cmd, size);\n")
6428 file.Write(" }\n")
6429 file.Write("\n")
6431 def WriteImmediateCmdHelper(self, func, file):
6432 """Overrriden from TypeHandler."""
6433 code = """ void %(name)s(%(typed_args)s) {
6434 const uint32_t size = gles2::cmds::%(name)s::ComputeSize();
6435 gles2::cmds::%(name)s* c =
6436 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6437 if (c) {
6438 c->Init(%(args)s);
6443 file.Write(code % {
6444 "name": func.name,
6445 "typed_args": func.MakeTypedOriginalArgString(""),
6446 "args": func.MakeOriginalArgString(""),
6449 def WriteImmediateFormatTest(self, func, file):
6450 """Overrriden from TypeHandler."""
6451 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6452 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6453 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
6454 for v in range(0, self.GetArrayCount(func)):
6455 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6456 (self.GetArrayType(func), v))
6457 file.Write(" };\n")
6458 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6459 (func.name, func.name))
6460 file.Write(" void* next_cmd = cmd.Set(\n")
6461 file.Write(" &cmd")
6462 args = func.GetCmdArgs()
6463 for value, arg in enumerate(args):
6464 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 11))
6465 file.Write(",\n data);\n")
6466 args = func.GetCmdArgs()
6467 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n"
6468 % func.name)
6469 file.Write(" cmd.header.command);\n")
6470 file.Write(" EXPECT_EQ(sizeof(cmd) +\n")
6471 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)),\n")
6472 file.Write(" cmd.header.size * 4u);\n")
6473 for value, arg in enumerate(args):
6474 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6475 (arg.type, value + 11, arg.name))
6476 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6477 file.Write(" next_cmd, sizeof(cmd) +\n")
6478 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6479 file.Write(" // TODO(gman): Check that data was inserted;\n")
6480 file.Write("}\n")
6481 file.Write("\n")
6484 class PUTnHandler(ArrayArgTypeHandler):
6485 """Handler for PUTn 'glUniform__v' type functions."""
6487 def __init__(self):
6488 ArrayArgTypeHandler.__init__(self)
6490 def WriteServiceUnitTest(self, func, file, *extras):
6491 """Overridden from TypeHandler."""
6492 ArrayArgTypeHandler.WriteServiceUnitTest(self, func, file, *extras)
6494 valid_test = """
6495 TEST_P(%(test_name)s, %(name)sValidArgsCountTooLarge) {
6496 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
6497 SpecializedSetup<cmds::%(name)s, 0>(true);
6498 cmds::%(name)s cmd;
6499 cmd.Init(%(args)s);
6500 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
6501 EXPECT_EQ(GL_NO_ERROR, GetGLError());
6504 gl_arg_strings = []
6505 arg_strings = []
6506 for count, arg in enumerate(func.GetOriginalArgs()):
6507 # hardcoded to match unit tests.
6508 if count == 0:
6509 # the location of the second element of the 2nd uniform.
6510 # defined in GLES2DecoderBase::SetupShaderForUniform
6511 gl_arg_strings.append("3")
6512 arg_strings.append("ProgramManager::MakeFakeLocation(1, 1)")
6513 elif count == 1:
6514 # the number of elements that gl will be called with.
6515 gl_arg_strings.append("3")
6516 # the number of elements requested in the command.
6517 arg_strings.append("5")
6518 else:
6519 gl_arg_strings.append(arg.GetValidGLArg(func))
6520 if not arg.IsConstant():
6521 arg_strings.append(arg.GetValidArg(func))
6522 extra = {
6523 'gl_args': ", ".join(gl_arg_strings),
6524 'args': ", ".join(arg_strings),
6526 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6528 def WriteImmediateServiceUnitTest(self, func, file, *extras):
6529 """Overridden from TypeHandler."""
6530 valid_test = """
6531 TEST_P(%(test_name)s, %(name)sValidArgs) {
6532 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6533 EXPECT_CALL(
6534 *gl_,
6535 %(gl_func_name)s(%(gl_args)s,
6536 reinterpret_cast<%(data_type)s*>(ImmediateDataAddress(&cmd))));
6537 SpecializedSetup<cmds::%(name)s, 0>(true);
6538 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6539 cmd.Init(%(args)s, &temp[0]);"""
6540 if func.IsUnsafe():
6541 valid_test += """
6542 decoder_->set_unsafe_es3_apis_enabled(true);"""
6543 valid_test += """
6544 EXPECT_EQ(error::kNoError,
6545 ExecuteImmediateCmd(cmd, sizeof(temp)));
6546 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
6547 if func.IsUnsafe():
6548 valid_test += """
6549 decoder_->set_unsafe_es3_apis_enabled(false);
6550 EXPECT_EQ(error::kUnknownCommand,
6551 ExecuteImmediateCmd(cmd, sizeof(temp)));"""
6552 valid_test += """
6555 gl_arg_strings = []
6556 gl_any_strings = []
6557 arg_strings = []
6558 for arg in func.GetOriginalArgs()[0:-1]:
6559 gl_arg_strings.append(arg.GetValidGLArg(func))
6560 gl_any_strings.append("_")
6561 if not arg.IsConstant():
6562 arg_strings.append(arg.GetValidArg(func))
6563 extra = {
6564 'data_type': self.GetArrayType(func),
6565 'data_count': self.GetArrayCount(func),
6566 'args': ", ".join(arg_strings),
6567 'gl_args': ", ".join(gl_arg_strings),
6568 'gl_any_args': ", ".join(gl_any_strings),
6570 self.WriteValidUnitTest(func, file, valid_test, extra, *extras)
6572 invalid_test = """
6573 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
6574 cmds::%(name)s& cmd = *GetImmediateAs<cmds::%(name)s>();
6575 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_any_args)s, _)).Times(0);
6576 SpecializedSetup<cmds::%(name)s, 0>(false);
6577 %(data_type)s temp[%(data_count)s * 2] = { 0, };
6578 cmd.Init(%(all_but_last_args)s, &temp[0]);
6579 EXPECT_EQ(error::%(parse_result)s,
6580 ExecuteImmediateCmd(cmd, sizeof(temp)));%(gl_error_test)s
6583 self.WriteInvalidUnitTest(func, file, invalid_test, extra, *extras)
6585 def WriteGetDataSizeCode(self, func, file):
6586 """Overrriden from TypeHandler."""
6587 code = """ uint32_t data_size;
6588 if (!ComputeDataSize(count, sizeof(%s), %d, &data_size)) {
6589 return error::kOutOfBounds;
6592 file.Write(code % (self.GetArrayType(func), self.GetArrayCount(func)))
6593 if func.IsImmediate():
6594 file.Write(" if (data_size > immediate_data_size) {\n")
6595 file.Write(" return error::kOutOfBounds;\n")
6596 file.Write(" }\n")
6598 def WriteGLES2Implementation(self, func, file):
6599 """Overrriden from TypeHandler."""
6600 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6601 (func.return_type, func.original_name,
6602 func.MakeTypedOriginalArgString("")))
6603 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6604 func.WriteDestinationInitalizationValidation(file)
6605 self.WriteClientGLCallLog(func, file)
6606 last_pointer_name = func.GetLastOriginalPointerArg().name
6607 file.Write(""" GPU_CLIENT_LOG_CODE_BLOCK({
6608 for (GLsizei i = 0; i < count; ++i) {
6609 """)
6610 values_str = ' << ", " << '.join(
6611 ["%s[%d + i * %d]" % (
6612 last_pointer_name, ndx, self.GetArrayCount(func)) for ndx in range(
6613 0, self.GetArrayCount(func))])
6614 file.Write(' GPU_CLIENT_LOG(" " << i << ": " << %s);\n' % values_str)
6615 file.Write(" }\n });\n")
6616 for arg in func.GetOriginalArgs():
6617 arg.WriteClientSideValidationCode(file, func)
6618 file.Write(" helper_->%sImmediate(%s);\n" %
6619 (func.name, func.MakeInitString("")))
6620 file.Write(" CheckGLError();\n")
6621 file.Write("}\n")
6622 file.Write("\n")
6624 def WriteGLES2ImplementationUnitTest(self, func, file):
6625 """Writes the GLES2 Implemention unit test."""
6626 code = """
6627 TEST_F(GLES2ImplementationTest, %(name)s) {
6628 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6629 struct Cmds {
6630 cmds::%(name)sImmediate cmd;
6631 %(type)s data[%(count_param)d][%(count)d];
6634 Cmds expected;
6635 for (int ii = 0; ii < %(count_param)d; ++ii) {
6636 for (int jj = 0; jj < %(count)d; ++jj) {
6637 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6640 expected.cmd.Init(%(cmd_args)s);
6641 gl_->%(name)s(%(args)s);
6642 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6645 cmd_arg_strings = []
6646 for arg in func.GetCmdArgs():
6647 if arg.name.endswith("_shm_id"):
6648 cmd_arg_strings.append("&data[0][0]")
6649 elif arg.name.endswith("_shm_offset"):
6650 continue
6651 else:
6652 cmd_arg_strings.append(arg.GetValidClientSideCmdArg(func))
6653 gl_arg_strings = []
6654 count_param = 0
6655 for arg in func.GetOriginalArgs():
6656 if arg.IsPointer():
6657 valid_value = "&data[0][0]"
6658 else:
6659 valid_value = arg.GetValidClientSideArg(func)
6660 gl_arg_strings.append(valid_value)
6661 if arg.name == "count":
6662 count_param = int(valid_value)
6663 file.Write(code % {
6664 'name': func.name,
6665 'type': self.GetArrayType(func),
6666 'count': self.GetArrayCount(func),
6667 'args': ", ".join(gl_arg_strings),
6668 'cmd_args': ", ".join(cmd_arg_strings),
6669 'count_param': count_param,
6672 # Test constants for invalid values, as they are not tested by the
6673 # service.
6674 constants = [
6675 arg for arg in func.GetOriginalArgs()[0:-1] if arg.IsConstant()
6677 if not constants:
6678 return
6680 code = """
6681 TEST_F(GLES2ImplementationTest, %(name)sInvalidConstantArg%(invalid_index)d) {
6682 %(type)s data[%(count_param)d][%(count)d] = {{0}};
6683 for (int ii = 0; ii < %(count_param)d; ++ii) {
6684 for (int jj = 0; jj < %(count)d; ++jj) {
6685 data[ii][jj] = static_cast<%(type)s>(ii * %(count)d + jj);
6688 gl_->%(name)s(%(args)s);
6689 EXPECT_TRUE(NoCommandsWritten());
6690 EXPECT_EQ(%(gl_error)s, CheckError());
6693 for invalid_arg in constants:
6694 gl_arg_strings = []
6695 invalid = invalid_arg.GetInvalidArg(func)
6696 for arg in func.GetOriginalArgs():
6697 if arg is invalid_arg:
6698 gl_arg_strings.append(invalid[0])
6699 elif arg.IsPointer():
6700 gl_arg_strings.append("&data[0][0]")
6701 else:
6702 valid_value = arg.GetValidClientSideArg(func)
6703 gl_arg_strings.append(valid_value)
6704 if arg.name == "count":
6705 count_param = int(valid_value)
6707 file.Write(code % {
6708 'name': func.name,
6709 'invalid_index': func.GetOriginalArgs().index(invalid_arg),
6710 'type': self.GetArrayType(func),
6711 'count': self.GetArrayCount(func),
6712 'args': ", ".join(gl_arg_strings),
6713 'gl_error': invalid[2],
6714 'count_param': count_param,
6718 def WriteImmediateCmdComputeSize(self, func, file):
6719 """Overrriden from TypeHandler."""
6720 file.Write(" static uint32_t ComputeDataSize(GLsizei count) {\n")
6721 file.Write(" return static_cast<uint32_t>(\n")
6722 file.Write(" sizeof(%s) * %d * count); // NOLINT\n" %
6723 (self.GetArrayType(func), self.GetArrayCount(func)))
6724 file.Write(" }\n")
6725 file.Write("\n")
6726 file.Write(" static uint32_t ComputeSize(GLsizei count) {\n")
6727 file.Write(" return static_cast<uint32_t>(\n")
6728 file.Write(
6729 " sizeof(ValueType) + ComputeDataSize(count)); // NOLINT\n")
6730 file.Write(" }\n")
6731 file.Write("\n")
6733 def WriteImmediateCmdSetHeader(self, func, file):
6734 """Overrriden from TypeHandler."""
6735 file.Write(" void SetHeader(GLsizei count) {\n")
6736 file.Write(
6737 " header.SetCmdByTotalSize<ValueType>(ComputeSize(count));\n")
6738 file.Write(" }\n")
6739 file.Write("\n")
6741 def WriteImmediateCmdInit(self, func, file):
6742 """Overrriden from TypeHandler."""
6743 file.Write(" void Init(%s) {\n" %
6744 func.MakeTypedInitString("_"))
6745 file.Write(" SetHeader(_count);\n")
6746 args = func.GetCmdArgs()
6747 for arg in args:
6748 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
6749 file.Write(" memcpy(ImmediateDataAddress(this),\n")
6750 pointer_arg = func.GetLastOriginalPointerArg()
6751 file.Write(" _%s, ComputeDataSize(_count));\n" % pointer_arg.name)
6752 file.Write(" }\n")
6753 file.Write("\n")
6755 def WriteImmediateCmdSet(self, func, file):
6756 """Overrriden from TypeHandler."""
6757 file.Write(" void* Set(void* cmd%s) {\n" %
6758 func.MakeTypedInitString("_", True))
6759 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" %
6760 func.MakeInitString("_"))
6761 file.Write(" const uint32_t size = ComputeSize(_count);\n")
6762 file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
6763 "cmd, size);\n")
6764 file.Write(" }\n")
6765 file.Write("\n")
6767 def WriteImmediateCmdHelper(self, func, file):
6768 """Overrriden from TypeHandler."""
6769 code = """ void %(name)s(%(typed_args)s) {
6770 const uint32_t size = gles2::cmds::%(name)s::ComputeSize(count);
6771 gles2::cmds::%(name)s* c =
6772 GetImmediateCmdSpaceTotalSize<gles2::cmds::%(name)s>(size);
6773 if (c) {
6774 c->Init(%(args)s);
6779 file.Write(code % {
6780 "name": func.name,
6781 "typed_args": func.MakeTypedInitString(""),
6782 "args": func.MakeInitString("")
6785 def WriteImmediateFormatTest(self, func, file):
6786 """Overrriden from TypeHandler."""
6787 args = func.GetOriginalArgs()
6788 count_param = 0
6789 for arg in args:
6790 if arg.name == "count":
6791 count_param = int(arg.GetValidClientSideCmdArg(func))
6792 file.Write("TEST_F(GLES2FormatTest, %s) {\n" % func.name)
6793 file.Write(" const int kSomeBaseValueToTestWith = 51;\n")
6794 file.Write(" static %s data[] = {\n" % self.GetArrayType(func))
6795 for v in range(0, self.GetArrayCount(func) * count_param):
6796 file.Write(" static_cast<%s>(kSomeBaseValueToTestWith + %d),\n" %
6797 (self.GetArrayType(func), v))
6798 file.Write(" };\n")
6799 file.Write(" cmds::%s& cmd = *GetBufferAs<cmds::%s>();\n" %
6800 (func.name, func.name))
6801 file.Write(" const GLsizei kNumElements = %d;\n" % count_param)
6802 file.Write(" const size_t kExpectedCmdSize =\n")
6803 file.Write(" sizeof(cmd) + kNumElements * sizeof(%s) * %d;\n" %
6804 (self.GetArrayType(func), self.GetArrayCount(func)))
6805 file.Write(" void* next_cmd = cmd.Set(\n")
6806 file.Write(" &cmd")
6807 for value, arg in enumerate(args):
6808 if arg.IsPointer():
6809 file.Write(",\n data")
6810 elif arg.IsConstant():
6811 continue
6812 else:
6813 file.Write(",\n static_cast<%s>(%d)" % (arg.type, value + 1))
6814 file.Write(");\n")
6815 file.Write(" EXPECT_EQ(static_cast<uint32_t>(cmds::%s::kCmdId),\n" %
6816 func.name)
6817 file.Write(" cmd.header.command);\n")
6818 file.Write(" EXPECT_EQ(kExpectedCmdSize, cmd.header.size * 4u);\n")
6819 for value, arg in enumerate(args):
6820 if arg.IsPointer() or arg.IsConstant():
6821 continue
6822 file.Write(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);\n" %
6823 (arg.type, value + 1, arg.name))
6824 file.Write(" CheckBytesWrittenMatchesExpectedSize(\n")
6825 file.Write(" next_cmd, sizeof(cmd) +\n")
6826 file.Write(" RoundSizeToMultipleOfEntries(sizeof(data)));\n")
6827 file.Write(" // TODO(gman): Check that data was inserted;\n")
6828 file.Write("}\n")
6829 file.Write("\n")
6831 class PUTSTRHandler(ArrayArgTypeHandler):
6832 """Handler for functions that pass a string array."""
6834 def __init__(self):
6835 ArrayArgTypeHandler.__init__(self)
6837 def __GetDataArg(self, func):
6838 """Return the argument that points to the 2D char arrays"""
6839 for arg in func.GetOriginalArgs():
6840 if arg.IsPointer2D():
6841 return arg
6842 return None
6844 def __GetLengthArg(self, func):
6845 """Return the argument that holds length for each char array"""
6846 for arg in func.GetOriginalArgs():
6847 if arg.IsPointer() and not arg.IsPointer2D():
6848 return arg
6849 return None
6851 def WriteGLES2Implementation(self, func, file):
6852 """Overrriden from TypeHandler."""
6853 file.Write("%s GLES2Implementation::%s(%s) {\n" %
6854 (func.return_type, func.original_name,
6855 func.MakeTypedOriginalArgString("")))
6856 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
6857 func.WriteDestinationInitalizationValidation(file)
6858 self.WriteClientGLCallLog(func, file)
6859 data_arg = self.__GetDataArg(func)
6860 length_arg = self.__GetLengthArg(func)
6861 log_code_block = """ GPU_CLIENT_LOG_CODE_BLOCK({
6862 for (GLsizei ii = 0; ii < count; ++ii) {
6863 if (%(data)s[ii]) {"""
6864 if length_arg == None:
6865 log_code_block += """
6866 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");"""
6867 else:
6868 log_code_block += """
6869 if (%(length)s && %(length)s[ii] >= 0) {
6870 const std::string my_str(%(data)s[ii], %(length)s[ii]);
6871 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << my_str << "\\n---");
6872 } else {
6873 GPU_CLIENT_LOG(" " << ii << ": ---\\n" << %(data)s[ii] << "\\n---");
6874 }"""
6875 log_code_block += """
6876 } else {
6877 GPU_CLIENT_LOG(" " << ii << ": NULL");
6882 file.Write(log_code_block % {
6883 'data': data_arg.name,
6884 'length': length_arg.name if not length_arg == None else ''
6886 for arg in func.GetOriginalArgs():
6887 arg.WriteClientSideValidationCode(file, func)
6889 bucket_args = []
6890 for arg in func.GetOriginalArgs():
6891 if arg.name == 'count' or arg == self.__GetLengthArg(func):
6892 continue
6893 if arg == self.__GetDataArg(func):
6894 bucket_args.append('kResultBucketId')
6895 else:
6896 bucket_args.append(arg.name)
6897 code_block = """
6898 if (!PackStringsToBucket(count, %(data)s, %(length)s, "gl%(func_name)s")) {
6899 return;
6901 helper_->%(func_name)sBucket(%(bucket_args)s);
6902 helper_->SetBucketSize(kResultBucketId, 0);
6903 CheckGLError();
6907 file.Write(code_block % {
6908 'data': data_arg.name,
6909 'length': length_arg.name if not length_arg == None else 'NULL',
6910 'func_name': func.name,
6911 'bucket_args': ', '.join(bucket_args),
6914 def WriteGLES2ImplementationUnitTest(self, func, file):
6915 """Overrriden from TypeHandler."""
6916 code = """
6917 TEST_F(GLES2ImplementationTest, %(name)s) {
6918 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
6919 const char* kString1 = "happy";
6920 const char* kString2 = "ending";
6921 const size_t kString1Size = ::strlen(kString1) + 1;
6922 const size_t kString2Size = ::strlen(kString2) + 1;
6923 const size_t kHeaderSize = sizeof(GLint) * 3;
6924 const size_t kSourceSize = kHeaderSize + kString1Size + kString2Size;
6925 const size_t kPaddedHeaderSize =
6926 transfer_buffer_->RoundToAlignment(kHeaderSize);
6927 const size_t kPaddedString1Size =
6928 transfer_buffer_->RoundToAlignment(kString1Size);
6929 const size_t kPaddedString2Size =
6930 transfer_buffer_->RoundToAlignment(kString2Size);
6931 struct Cmds {
6932 cmd::SetBucketSize set_bucket_size;
6933 cmd::SetBucketData set_bucket_header;
6934 cmd::SetToken set_token1;
6935 cmd::SetBucketData set_bucket_data1;
6936 cmd::SetToken set_token2;
6937 cmd::SetBucketData set_bucket_data2;
6938 cmd::SetToken set_token3;
6939 cmds::%(name)sBucket cmd_bucket;
6940 cmd::SetBucketSize clear_bucket_size;
6943 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
6944 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedString1Size);
6945 ExpectedMemoryInfo mem2 = GetExpectedMemory(kPaddedString2Size);
6947 Cmds expected;
6948 expected.set_bucket_size.Init(kBucketId, kSourceSize);
6949 expected.set_bucket_header.Init(
6950 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
6951 expected.set_token1.Init(GetNextToken());
6952 expected.set_bucket_data1.Init(
6953 kBucketId, kHeaderSize, kString1Size, mem1.id, mem1.offset);
6954 expected.set_token2.Init(GetNextToken());
6955 expected.set_bucket_data2.Init(
6956 kBucketId, kHeaderSize + kString1Size, kString2Size, mem2.id,
6957 mem2.offset);
6958 expected.set_token3.Init(GetNextToken());
6959 expected.cmd_bucket.Init(%(bucket_args)s);
6960 expected.clear_bucket_size.Init(kBucketId, 0);
6961 const char* kStrings[] = { kString1, kString2 };
6962 gl_->%(name)s(%(gl_args)s);
6963 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
6966 gl_args = []
6967 bucket_args = []
6968 for arg in func.GetOriginalArgs():
6969 if arg == self.__GetDataArg(func):
6970 gl_args.append('kStrings')
6971 bucket_args.append('kBucketId')
6972 elif arg == self.__GetLengthArg(func):
6973 gl_args.append('NULL')
6974 elif arg.name == 'count':
6975 gl_args.append('2')
6976 else:
6977 gl_args.append(arg.GetValidClientSideArg(func))
6978 bucket_args.append(arg.GetValidClientSideArg(func))
6979 file.Write(code % {
6980 'name': func.name,
6981 'gl_args': ", ".join(gl_args),
6982 'bucket_args': ", ".join(bucket_args),
6985 if self.__GetLengthArg(func) == None:
6986 return
6987 code = """
6988 TEST_F(GLES2ImplementationTest, %(name)sWithLength) {
6989 const uint32 kBucketId = GLES2Implementation::kResultBucketId;
6990 const char* kString = "foobar******";
6991 const size_t kStringSize = 6; // We only need "foobar".
6992 const size_t kHeaderSize = sizeof(GLint) * 2;
6993 const size_t kSourceSize = kHeaderSize + kStringSize + 1;
6994 const size_t kPaddedHeaderSize =
6995 transfer_buffer_->RoundToAlignment(kHeaderSize);
6996 const size_t kPaddedStringSize =
6997 transfer_buffer_->RoundToAlignment(kStringSize + 1);
6998 struct Cmds {
6999 cmd::SetBucketSize set_bucket_size;
7000 cmd::SetBucketData set_bucket_header;
7001 cmd::SetToken set_token1;
7002 cmd::SetBucketData set_bucket_data;
7003 cmd::SetToken set_token2;
7004 cmds::ShaderSourceBucket shader_source_bucket;
7005 cmd::SetBucketSize clear_bucket_size;
7008 ExpectedMemoryInfo mem0 = GetExpectedMemory(kPaddedHeaderSize);
7009 ExpectedMemoryInfo mem1 = GetExpectedMemory(kPaddedStringSize);
7011 Cmds expected;
7012 expected.set_bucket_size.Init(kBucketId, kSourceSize);
7013 expected.set_bucket_header.Init(
7014 kBucketId, 0, kHeaderSize, mem0.id, mem0.offset);
7015 expected.set_token1.Init(GetNextToken());
7016 expected.set_bucket_data.Init(
7017 kBucketId, kHeaderSize, kStringSize + 1, mem1.id, mem1.offset);
7018 expected.set_token2.Init(GetNextToken());
7019 expected.shader_source_bucket.Init(%(bucket_args)s);
7020 expected.clear_bucket_size.Init(kBucketId, 0);
7021 const char* kStrings[] = { kString };
7022 const GLint kLength[] = { kStringSize };
7023 gl_->%(name)s(%(gl_args)s);
7024 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7027 gl_args = []
7028 for arg in func.GetOriginalArgs():
7029 if arg == self.__GetDataArg(func):
7030 gl_args.append('kStrings')
7031 elif arg == self.__GetLengthArg(func):
7032 gl_args.append('kLength')
7033 elif arg.name == 'count':
7034 gl_args.append('1')
7035 else:
7036 gl_args.append(arg.GetValidClientSideArg(func))
7037 file.Write(code % {
7038 'name': func.name,
7039 'gl_args': ", ".join(gl_args),
7040 'bucket_args': ", ".join(bucket_args),
7043 def WriteBucketServiceUnitTest(self, func, file, *extras):
7044 """Overrriden from TypeHandler."""
7045 cmd_args = []
7046 cmd_args_with_invalid_id = []
7047 gl_args = []
7048 for index, arg in enumerate(func.GetOriginalArgs()):
7049 if arg == self.__GetLengthArg(func):
7050 gl_args.append('_')
7051 elif arg.name == 'count':
7052 gl_args.append('1')
7053 elif arg == self.__GetDataArg(func):
7054 cmd_args.append('kBucketId')
7055 cmd_args_with_invalid_id.append('kBucketId')
7056 gl_args.append('_')
7057 elif index == 0: # Resource ID arg
7058 cmd_args.append(arg.GetValidArg(func))
7059 cmd_args_with_invalid_id.append('kInvalidClientId')
7060 gl_args.append(arg.GetValidGLArg(func))
7061 else:
7062 cmd_args.append(arg.GetValidArg(func))
7063 cmd_args_with_invalid_id.append(arg.GetValidArg(func))
7064 gl_args.append(arg.GetValidGLArg(func))
7066 test = """
7067 TEST_P(%(test_name)s, %(name)sValidArgs) {
7068 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7069 const uint32 kBucketId = 123;
7070 const char kSource0[] = "hello";
7071 const char* kSource[] = { kSource0 };
7072 const char kValidStrEnd = 0;
7073 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7074 cmds::%(name)s cmd;
7075 cmd.Init(%(cmd_args)s);
7076 decoder_->set_unsafe_es3_apis_enabled(true);
7077 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));"""
7078 if func.IsUnsafe():
7079 test += """
7080 decoder_->set_unsafe_es3_apis_enabled(false);
7081 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));
7083 test += """
7086 self.WriteValidUnitTest(func, file, test, {
7087 'cmd_args': ", ".join(cmd_args),
7088 'gl_args': ", ".join(gl_args),
7089 }, *extras)
7091 test = """
7092 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7093 const uint32 kBucketId = 123;
7094 const char kSource0[] = "hello";
7095 const char* kSource[] = { kSource0 };
7096 const char kValidStrEnd = 0;
7097 decoder_->set_unsafe_es3_apis_enabled(true);
7098 cmds::%(name)s cmd;
7099 // Test no bucket.
7100 cmd.Init(%(cmd_args)s);
7101 EXPECT_NE(error::kNoError, ExecuteCmd(cmd));
7102 // Test invalid client.
7103 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kValidStrEnd);
7104 cmd.Init(%(cmd_args_with_invalid_id)s);
7105 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7106 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7109 self.WriteValidUnitTest(func, file, test, {
7110 'cmd_args': ", ".join(cmd_args),
7111 'cmd_args_with_invalid_id': ", ".join(cmd_args_with_invalid_id),
7112 }, *extras)
7114 test = """
7115 TEST_P(%(test_name)s, %(name)sInvalidHeader) {
7116 const uint32 kBucketId = 123;
7117 const char kSource0[] = "hello";
7118 const char* kSource[] = { kSource0 };
7119 const char kValidStrEnd = 0;
7120 const GLsizei kCount = static_cast<GLsizei>(arraysize(kSource));
7121 const GLsizei kTests[] = {
7122 kCount + 1,
7124 std::numeric_limits<GLsizei>::max(),
7127 decoder_->set_unsafe_es3_apis_enabled(true);
7128 for (size_t ii = 0; ii < arraysize(kTests); ++ii) {
7129 SetBucketAsCStrings(kBucketId, 1, kSource, kTests[ii], kValidStrEnd);
7130 cmds::%(name)s cmd;
7131 cmd.Init(%(cmd_args)s);
7132 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7136 self.WriteValidUnitTest(func, file, test, {
7137 'cmd_args': ", ".join(cmd_args),
7138 }, *extras)
7140 test = """
7141 TEST_P(%(test_name)s, %(name)sInvalidStringEnding) {
7142 const uint32 kBucketId = 123;
7143 const char kSource0[] = "hello";
7144 const char* kSource[] = { kSource0 };
7145 const char kInvalidStrEnd = '*';
7146 SetBucketAsCStrings(kBucketId, 1, kSource, 1, kInvalidStrEnd);
7147 cmds::%(name)s cmd;
7148 cmd.Init(%(cmd_args)s);
7149 decoder_->set_unsafe_es3_apis_enabled(true);
7150 EXPECT_EQ(error::kInvalidArguments, ExecuteCmd(cmd));
7153 self.WriteValidUnitTest(func, file, test, {
7154 'cmd_args': ", ".join(cmd_args),
7155 }, *extras)
7158 class PUTXnHandler(ArrayArgTypeHandler):
7159 """Handler for glUniform?f functions."""
7160 def __init__(self):
7161 ArrayArgTypeHandler.__init__(self)
7163 def WriteHandlerImplementation(self, func, file):
7164 """Overrriden from TypeHandler."""
7165 code = """ %(type)s temp[%(count)s] = { %(values)s};"""
7166 if func.IsUnsafe():
7167 code += """
7168 gl%(name)sv(%(location)s, 1, &temp[0]);
7170 else:
7171 code += """
7172 Do%(name)sv(%(location)s, 1, &temp[0]);
7174 values = ""
7175 args = func.GetOriginalArgs()
7176 count = int(self.GetArrayCount(func))
7177 num_args = len(args)
7178 for ii in range(count):
7179 values += "%s, " % args[len(args) - count + ii].name
7181 file.Write(code % {
7182 'name': func.name,
7183 'count': self.GetArrayCount(func),
7184 'type': self.GetArrayType(func),
7185 'location': args[0].name,
7186 'args': func.MakeOriginalArgString(""),
7187 'values': values,
7190 def WriteServiceUnitTest(self, func, file, *extras):
7191 """Overrriden from TypeHandler."""
7192 valid_test = """
7193 TEST_P(%(test_name)s, %(name)sValidArgs) {
7194 EXPECT_CALL(*gl_, %(name)sv(%(local_args)s));
7195 SpecializedSetup<cmds::%(name)s, 0>(true);
7196 cmds::%(name)s cmd;
7197 cmd.Init(%(args)s);"""
7198 if func.IsUnsafe():
7199 valid_test += """
7200 decoder_->set_unsafe_es3_apis_enabled(true);"""
7201 valid_test += """
7202 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7203 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7204 if func.IsUnsafe():
7205 valid_test += """
7206 decoder_->set_unsafe_es3_apis_enabled(false);
7207 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7208 valid_test += """
7211 args = func.GetOriginalArgs()
7212 local_args = "%s, 1, _" % args[0].GetValidGLArg(func)
7213 self.WriteValidUnitTest(func, file, valid_test, {
7214 'name': func.name,
7215 'count': self.GetArrayCount(func),
7216 'local_args': local_args,
7217 }, *extras)
7219 invalid_test = """
7220 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7221 EXPECT_CALL(*gl_, %(name)sv(_, _, _).Times(0);
7222 SpecializedSetup<cmds::%(name)s, 0>(false);
7223 cmds::%(name)s cmd;
7224 cmd.Init(%(args)s);
7225 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7228 self.WriteInvalidUnitTest(func, file, invalid_test, {
7229 'name': func.GetInfo('name'),
7230 'count': self.GetArrayCount(func),
7234 class GLcharHandler(CustomHandler):
7235 """Handler for functions that pass a single string ."""
7237 def __init__(self):
7238 CustomHandler.__init__(self)
7240 def WriteImmediateCmdComputeSize(self, func, file):
7241 """Overrriden from TypeHandler."""
7242 file.Write(" static uint32_t ComputeSize(uint32_t data_size) {\n")
7243 file.Write(" return static_cast<uint32_t>(\n")
7244 file.Write(" sizeof(ValueType) + data_size); // NOLINT\n")
7245 file.Write(" }\n")
7247 def WriteImmediateCmdSetHeader(self, func, file):
7248 """Overrriden from TypeHandler."""
7249 code = """
7250 void SetHeader(uint32_t data_size) {
7251 header.SetCmdBySize<ValueType>(data_size);
7254 file.Write(code)
7256 def WriteImmediateCmdInit(self, func, file):
7257 """Overrriden from TypeHandler."""
7258 last_arg = func.GetLastOriginalArg()
7259 args = func.GetCmdArgs()
7260 set_code = []
7261 for arg in args:
7262 set_code.append(" %s = _%s;" % (arg.name, arg.name))
7263 code = """
7264 void Init(%(typed_args)s, uint32_t _data_size) {
7265 SetHeader(_data_size);
7266 %(set_code)s
7267 memcpy(ImmediateDataAddress(this), _%(last_arg)s, _data_size);
7271 file.Write(code % {
7272 "typed_args": func.MakeTypedArgString("_"),
7273 "set_code": "\n".join(set_code),
7274 "last_arg": last_arg.name
7277 def WriteImmediateCmdSet(self, func, file):
7278 """Overrriden from TypeHandler."""
7279 last_arg = func.GetLastOriginalArg()
7280 file.Write(" void* Set(void* cmd%s, uint32_t _data_size) {\n" %
7281 func.MakeTypedCmdArgString("_", True))
7282 file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _data_size);\n" %
7283 func.MakeCmdArgString("_"))
7284 file.Write(" return NextImmediateCmdAddress<ValueType>("
7285 "cmd, _data_size);\n")
7286 file.Write(" }\n")
7287 file.Write("\n")
7289 def WriteImmediateCmdHelper(self, func, file):
7290 """Overrriden from TypeHandler."""
7291 code = """ void %(name)s(%(typed_args)s) {
7292 const uint32_t data_size = strlen(name);
7293 gles2::cmds::%(name)s* c =
7294 GetImmediateCmdSpace<gles2::cmds::%(name)s>(data_size);
7295 if (c) {
7296 c->Init(%(args)s, data_size);
7301 file.Write(code % {
7302 "name": func.name,
7303 "typed_args": func.MakeTypedOriginalArgString(""),
7304 "args": func.MakeOriginalArgString(""),
7308 def WriteImmediateFormatTest(self, func, file):
7309 """Overrriden from TypeHandler."""
7310 init_code = []
7311 check_code = []
7312 all_but_last_arg = func.GetCmdArgs()[:-1]
7313 for value, arg in enumerate(all_but_last_arg):
7314 init_code.append(" static_cast<%s>(%d)," % (arg.type, value + 11))
7315 for value, arg in enumerate(all_but_last_arg):
7316 check_code.append(" EXPECT_EQ(static_cast<%s>(%d), cmd.%s);" %
7317 (arg.type, value + 11, arg.name))
7318 code = """
7319 TEST_F(GLES2FormatTest, %(func_name)s) {
7320 cmds::%(func_name)s& cmd = *GetBufferAs<cmds::%(func_name)s>();
7321 static const char* const test_str = \"test string\";
7322 void* next_cmd = cmd.Set(
7323 &cmd,
7324 %(init_code)s
7325 test_str,
7326 strlen(test_str));
7327 EXPECT_EQ(static_cast<uint32_t>(cmds::%(func_name)s::kCmdId),
7328 cmd.header.command);
7329 EXPECT_EQ(sizeof(cmd) +
7330 RoundSizeToMultipleOfEntries(strlen(test_str)),
7331 cmd.header.size * 4u);
7332 EXPECT_EQ(static_cast<char*>(next_cmd),
7333 reinterpret_cast<char*>(&cmd) + sizeof(cmd) +
7334 RoundSizeToMultipleOfEntries(strlen(test_str)));
7335 %(check_code)s
7336 EXPECT_EQ(static_cast<uint32_t>(strlen(test_str)), cmd.data_size);
7337 EXPECT_EQ(0, memcmp(test_str, ImmediateDataAddress(&cmd), strlen(test_str)));
7338 CheckBytesWritten(
7339 next_cmd,
7340 sizeof(cmd) + RoundSizeToMultipleOfEntries(strlen(test_str)),
7341 sizeof(cmd) + strlen(test_str));
7345 file.Write(code % {
7346 'func_name': func.name,
7347 'init_code': "\n".join(init_code),
7348 'check_code': "\n".join(check_code),
7352 class GLcharNHandler(CustomHandler):
7353 """Handler for functions that pass a single string with an optional len."""
7355 def __init__(self):
7356 CustomHandler.__init__(self)
7358 def InitFunction(self, func):
7359 """Overrriden from TypeHandler."""
7360 func.cmd_args = []
7361 func.AddCmdArg(Argument('bucket_id', 'GLuint'))
7363 def NeedsDataTransferFunction(self, func):
7364 """Overriden from TypeHandler."""
7365 return False
7367 def AddBucketFunction(self, generator, func):
7368 """Overrriden from TypeHandler."""
7369 pass
7371 def WriteServiceImplementation(self, func, file):
7372 """Overrriden from TypeHandler."""
7373 self.WriteServiceHandlerFunctionHeader(func, file)
7374 file.Write("""
7375 GLuint bucket_id = static_cast<GLuint>(c.%(bucket_id)s);
7376 Bucket* bucket = GetBucket(bucket_id);
7377 if (!bucket || bucket->size() == 0) {
7378 return error::kInvalidArguments;
7380 std::string str;
7381 if (!bucket->GetAsString(&str)) {
7382 return error::kInvalidArguments;
7384 %(gl_func_name)s(0, str.c_str());
7385 return error::kNoError;
7388 """ % {
7389 'name': func.name,
7390 'gl_func_name': func.GetGLFunctionName(),
7391 'bucket_id': func.cmd_args[0].name,
7395 class IsHandler(TypeHandler):
7396 """Handler for glIs____ type and glGetError functions."""
7398 def __init__(self):
7399 TypeHandler.__init__(self)
7401 def InitFunction(self, func):
7402 """Overrriden from TypeHandler."""
7403 func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
7404 func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
7405 if func.GetInfo('result') == None:
7406 func.AddInfo('result', ['uint32_t'])
7408 def WriteServiceUnitTest(self, func, file, *extras):
7409 """Overrriden from TypeHandler."""
7410 valid_test = """
7411 TEST_P(%(test_name)s, %(name)sValidArgs) {
7412 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s));
7413 SpecializedSetup<cmds::%(name)s, 0>(true);
7414 cmds::%(name)s cmd;
7415 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);"""
7416 if func.IsUnsafe():
7417 valid_test += """
7418 decoder_->set_unsafe_es3_apis_enabled(true);"""
7419 valid_test += """
7420 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7421 EXPECT_EQ(GL_NO_ERROR, GetGLError());"""
7422 if func.IsUnsafe():
7423 valid_test += """
7424 decoder_->set_unsafe_es3_apis_enabled(false);
7425 EXPECT_EQ(error::kUnknownCommand, ExecuteCmd(cmd));"""
7426 valid_test += """
7429 comma = ""
7430 if len(func.GetOriginalArgs()):
7431 comma =", "
7432 self.WriteValidUnitTest(func, file, valid_test, {
7433 'comma': comma,
7434 }, *extras)
7436 invalid_test = """
7437 TEST_P(%(test_name)s, %(name)sInvalidArgs%(arg_index)d_%(value_index)d) {
7438 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7439 SpecializedSetup<cmds::%(name)s, 0>(false);
7440 cmds::%(name)s cmd;
7441 cmd.Init(%(args)s%(comma)sshared_memory_id_, shared_memory_offset_);
7442 EXPECT_EQ(error::%(parse_result)s, ExecuteCmd(cmd));%(gl_error_test)s
7445 self.WriteInvalidUnitTest(func, file, invalid_test, {
7446 'comma': comma,
7447 }, *extras)
7449 invalid_test = """
7450 TEST_P(%(test_name)s, %(name)sInvalidArgsBadSharedMemoryId) {
7451 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s)).Times(0);
7452 SpecializedSetup<cmds::%(name)s, 0>(false);"""
7453 if func.IsUnsafe():
7454 invalid_test += """
7455 decoder_->set_unsafe_es3_apis_enabled(true);"""
7456 invalid_test += """
7457 cmds::%(name)s cmd;
7458 cmd.Init(%(args)s%(comma)skInvalidSharedMemoryId, shared_memory_offset_);
7459 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));
7460 cmd.Init(%(args)s%(comma)sshared_memory_id_, kInvalidSharedMemoryOffset);
7461 EXPECT_EQ(error::kOutOfBounds, ExecuteCmd(cmd));"""
7462 if func.IsUnsafe():
7463 invalid_test += """
7464 decoder_->set_unsafe_es3_apis_enabled(true);"""
7465 invalid_test += """
7468 self.WriteValidUnitTest(func, file, invalid_test, {
7469 'comma': comma,
7470 }, *extras)
7472 def WriteServiceImplementation(self, func, file):
7473 """Overrriden from TypeHandler."""
7474 self.WriteServiceHandlerFunctionHeader(func, file)
7475 args = func.GetOriginalArgs()
7476 for arg in args:
7477 arg.WriteGetCode(file)
7479 code = """ typedef cmds::%(func_name)s::Result Result;
7480 Result* result_dst = GetSharedMemoryAs<Result*>(
7481 c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
7482 if (!result_dst) {
7483 return error::kOutOfBounds;
7486 file.Write(code % {'func_name': func.name})
7487 func.WriteHandlerValidation(file)
7488 if func.IsUnsafe():
7489 assert func.GetInfo('id_mapping')
7490 assert len(func.GetInfo('id_mapping')) == 1
7491 assert len(args) == 1
7492 id_type = func.GetInfo('id_mapping')[0]
7493 file.Write(" %s service_%s = 0;\n" % (args[0].type, id_type.lower()))
7494 file.Write(" *result_dst = group_->Get%sServiceId(%s, &service_%s);\n" %
7495 (id_type, id_type.lower(), id_type.lower()))
7496 else:
7497 file.Write(" *result_dst = %s(%s);\n" %
7498 (func.GetGLFunctionName(), func.MakeOriginalArgString("")))
7499 file.Write(" return error::kNoError;\n")
7500 file.Write("}\n")
7501 file.Write("\n")
7503 def WriteGLES2Implementation(self, func, file):
7504 """Overrriden from TypeHandler."""
7505 impl_func = func.GetInfo('impl_func')
7506 if impl_func == None or impl_func == True:
7507 error_value = func.GetInfo("error_value") or "GL_FALSE"
7508 file.Write("%s GLES2Implementation::%s(%s) {\n" %
7509 (func.return_type, func.original_name,
7510 func.MakeTypedOriginalArgString("")))
7511 file.Write(" GPU_CLIENT_SINGLE_THREAD_CHECK();\n")
7512 self.WriteTraceEvent(func, file)
7513 func.WriteDestinationInitalizationValidation(file)
7514 self.WriteClientGLCallLog(func, file)
7515 file.Write(" typedef cmds::%s::Result Result;\n" % func.name)
7516 file.Write(" Result* result = GetResultAs<Result*>();\n")
7517 file.Write(" if (!result) {\n")
7518 file.Write(" return %s;\n" % error_value)
7519 file.Write(" }\n")
7520 file.Write(" *result = 0;\n")
7521 assert len(func.GetOriginalArgs()) == 1
7522 id_arg = func.GetOriginalArgs()[0]
7523 if id_arg.type == 'GLsync':
7524 arg_string = "ToGLuint(%s)" % func.MakeOriginalArgString("")
7525 else:
7526 arg_string = func.MakeOriginalArgString("")
7527 file.Write(
7528 " helper_->%s(%s, GetResultShmId(), GetResultShmOffset());\n" %
7529 (func.name, arg_string))
7530 file.Write(" WaitForCmd();\n")
7531 file.Write(" %s result_value = *result" % func.return_type)
7532 if func.return_type == "GLboolean":
7533 file.Write(" != 0")
7534 file.Write(';\n GPU_CLIENT_LOG("returned " << result_value);\n')
7535 file.Write(" CheckGLError();\n")
7536 file.Write(" return result_value;\n")
7537 file.Write("}\n")
7538 file.Write("\n")
7540 def WriteGLES2ImplementationUnitTest(self, func, file):
7541 """Overrriden from TypeHandler."""
7542 client_test = func.GetInfo('client_test')
7543 if client_test == None or client_test == True:
7544 code = """
7545 TEST_F(GLES2ImplementationTest, %(name)s) {
7546 struct Cmds {
7547 cmds::%(name)s cmd;
7550 Cmds expected;
7551 ExpectedMemoryInfo result1 =
7552 GetExpectedResultMemory(sizeof(cmds::%(name)s::Result));
7553 expected.cmd.Init(%(cmd_id_value)s, result1.id, result1.offset);
7555 EXPECT_CALL(*command_buffer(), OnFlush())
7556 .WillOnce(SetMemory(result1.ptr, uint32_t(GL_TRUE)))
7557 .RetiresOnSaturation();
7559 GLboolean result = gl_->%(name)s(%(gl_id_value)s);
7560 EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
7561 EXPECT_TRUE(result);
7564 args = func.GetOriginalArgs()
7565 assert len(args) == 1
7566 file.Write(code % {
7567 'name': func.name,
7568 'cmd_id_value': args[0].GetValidClientSideCmdArg(func),
7569 'gl_id_value': args[0].GetValidClientSideArg(func) })
7572 class STRnHandler(TypeHandler):
7573 """Handler for GetProgramInfoLog, GetShaderInfoLog, GetShaderSource, and
7574 GetTranslatedShaderSourceANGLE."""
7576 def __init__(self):
7577 TypeHandler.__init__(self)
7579 def InitFunction(self, func):
7580 """Overrriden from TypeHandler."""
7581 # remove all but the first cmd args.
7582 cmd_args = func.GetCmdArgs()
7583 func.ClearCmdArgs()
7584 func.AddCmdArg(cmd_args[0])
7585 # add on a bucket id.
7586 func.AddCmdArg(Argument('bucket_id', 'uint32_t'))
7588 def WriteGLES2Implementation(self, func, file):
7589 """Overrriden from TypeHandler."""
7590 code_1 = """%(return_type)s GLES2Implementation::%(func_name)s(%(args)s) {
7591 GPU_CLIENT_SINGLE_THREAD_CHECK();
7593 code_2 = """ GPU_CLIENT_LOG("[" << GetLogPrefix()
7594 << "] gl%(func_name)s" << "("
7595 << %(arg0)s << ", "
7596 << %(arg1)s << ", "
7597 << static_cast<void*>(%(arg2)s) << ", "
7598 << static_cast<void*>(%(arg3)s) << ")");
7599 helper_->SetBucketSize(kResultBucketId, 0);
7600 helper_->%(func_name)s(%(id_name)s, kResultBucketId);
7601 std::string str;
7602 GLsizei max_size = 0;
7603 if (GetBucketAsString(kResultBucketId, &str)) {
7604 if (bufsize > 0) {
7605 max_size =
7606 std::min(static_cast<size_t>(%(bufsize_name)s) - 1, str.size());
7607 memcpy(%(dest_name)s, str.c_str(), max_size);
7608 %(dest_name)s[max_size] = '\\0';
7609 GPU_CLIENT_LOG("------\\n" << %(dest_name)s << "\\n------");
7612 if (%(length_name)s != NULL) {
7613 *%(length_name)s = max_size;
7615 CheckGLError();
7618 args = func.GetOriginalArgs()
7619 str_args = {
7620 'return_type': func.return_type,
7621 'func_name': func.original_name,
7622 'args': func.MakeTypedOriginalArgString(""),
7623 'id_name': args[0].name,
7624 'bufsize_name': args[1].name,
7625 'length_name': args[2].name,
7626 'dest_name': args[3].name,
7627 'arg0': args[0].name,
7628 'arg1': args[1].name,
7629 'arg2': args[2].name,
7630 'arg3': args[3].name,
7632 file.Write(code_1 % str_args)
7633 func.WriteDestinationInitalizationValidation(file)
7634 file.Write(code_2 % str_args)
7636 def WriteServiceUnitTest(self, func, file, *extras):
7637 """Overrriden from TypeHandler."""
7638 valid_test = """
7639 TEST_P(%(test_name)s, %(name)sValidArgs) {
7640 const char* kInfo = "hello";
7641 const uint32_t kBucketId = 123;
7642 SpecializedSetup<cmds::%(name)s, 0>(true);
7643 %(expect_len_code)s
7644 EXPECT_CALL(*gl_, %(gl_func_name)s(%(gl_args)s))
7645 .WillOnce(DoAll(SetArgumentPointee<2>(strlen(kInfo)),
7646 SetArrayArgument<3>(kInfo, kInfo + strlen(kInfo) + 1)));
7647 cmds::%(name)s cmd;
7648 cmd.Init(%(args)s);
7649 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7650 CommonDecoder::Bucket* bucket = decoder_->GetBucket(kBucketId);
7651 ASSERT_TRUE(bucket != NULL);
7652 EXPECT_EQ(strlen(kInfo) + 1, bucket->size());
7653 EXPECT_EQ(0, memcmp(bucket->GetData(0, bucket->size()), kInfo,
7654 bucket->size()));
7655 EXPECT_EQ(GL_NO_ERROR, GetGLError());
7658 args = func.GetOriginalArgs()
7659 id_name = args[0].GetValidGLArg(func)
7660 get_len_func = func.GetInfo('get_len_func')
7661 get_len_enum = func.GetInfo('get_len_enum')
7662 sub = {
7663 'id_name': id_name,
7664 'get_len_func': get_len_func,
7665 'get_len_enum': get_len_enum,
7666 'gl_args': '%s, strlen(kInfo) + 1, _, _' %
7667 args[0].GetValidGLArg(func),
7668 'args': '%s, kBucketId' % args[0].GetValidArg(func),
7669 'expect_len_code': '',
7671 if get_len_func and get_len_func[0:2] == 'gl':
7672 sub['expect_len_code'] = (
7673 " EXPECT_CALL(*gl_, %s(%s, %s, _))\n"
7674 " .WillOnce(SetArgumentPointee<2>(strlen(kInfo) + 1));") % (
7675 get_len_func[2:], id_name, get_len_enum)
7676 self.WriteValidUnitTest(func, file, valid_test, sub, *extras)
7678 invalid_test = """
7679 TEST_P(%(test_name)s, %(name)sInvalidArgs) {
7680 const uint32_t kBucketId = 123;
7681 EXPECT_CALL(*gl_, %(gl_func_name)s(_, _, _, _))
7682 .Times(0);
7683 cmds::%(name)s cmd;
7684 cmd.Init(kInvalidClientId, kBucketId);
7685 EXPECT_EQ(error::kNoError, ExecuteCmd(cmd));
7686 EXPECT_EQ(GL_INVALID_VALUE, GetGLError());
7689 self.WriteValidUnitTest(func, file, invalid_test, *extras)
7691 def WriteServiceImplementation(self, func, file):
7692 """Overrriden from TypeHandler."""
7693 pass
7695 class NamedType(object):
7696 """A class that represents a type of an argument in a client function.
7698 A type of an argument that is to be passed through in the command buffer
7699 command. Currently used only for the arguments that are specificly named in
7700 the 'cmd_buffer_functions.txt' file, mostly enums.
7703 def __init__(self, info):
7704 assert not 'is_complete' in info or info['is_complete'] == True
7705 self.info = info
7706 self.valid = info['valid']
7707 if 'invalid' in info:
7708 self.invalid = info['invalid']
7709 else:
7710 self.invalid = []
7711 if 'valid_es3' in info:
7712 self.valid_es3 = info['valid_es3']
7713 else:
7714 self.valid_es3 = []
7715 if 'deprecated_es3' in info:
7716 self.deprecated_es3 = info['deprecated_es3']
7717 else:
7718 self.deprecated_es3 = []
7720 def GetType(self):
7721 return self.info['type']
7723 def GetInvalidValues(self):
7724 return self.invalid
7726 def GetValidValues(self):
7727 return self.valid
7729 def GetValidValuesES3(self):
7730 return self.valid_es3
7732 def GetDeprecatedValuesES3(self):
7733 return self.deprecated_es3
7735 def IsConstant(self):
7736 if not 'is_complete' in self.info:
7737 return False
7739 return len(self.GetValidValues()) == 1
7741 def GetConstantValue(self):
7742 return self.GetValidValues()[0]
7744 class Argument(object):
7745 """A class that represents a function argument."""
7747 cmd_type_map_ = {
7748 'GLenum': 'uint32_t',
7749 'GLint': 'int32_t',
7750 'GLintptr': 'int32_t',
7751 'GLsizei': 'int32_t',
7752 'GLsizeiptr': 'int32_t',
7753 'GLfloat': 'float',
7754 'GLclampf': 'float',
7756 need_validation_ = ['GLsizei*', 'GLboolean*', 'GLenum*', 'GLint*']
7758 def __init__(self, name, type):
7759 self.name = name
7760 self.optional = type.endswith("Optional*")
7761 if self.optional:
7762 type = type[:-9] + "*"
7763 self.type = type
7765 if type in self.cmd_type_map_:
7766 self.cmd_type = self.cmd_type_map_[type]
7767 else:
7768 self.cmd_type = 'uint32_t'
7770 def IsPointer(self):
7771 """Returns true if argument is a pointer."""
7772 return False
7774 def IsPointer2D(self):
7775 """Returns true if argument is a 2D pointer."""
7776 return False
7778 def IsConstant(self):
7779 """Returns true if the argument has only one valid value."""
7780 return False
7782 def AddCmdArgs(self, args):
7783 """Adds command arguments for this argument to the given list."""
7784 if not self.IsConstant():
7785 return args.append(self)
7787 def AddInitArgs(self, args):
7788 """Adds init arguments for this argument to the given list."""
7789 if not self.IsConstant():
7790 return args.append(self)
7792 def GetValidArg(self, func):
7793 """Gets a valid value for this argument."""
7794 valid_arg = func.GetValidArg(self)
7795 if valid_arg != None:
7796 return valid_arg
7798 index = func.GetOriginalArgs().index(self)
7799 return str(index + 1)
7801 def GetValidClientSideArg(self, func):
7802 """Gets a valid value for this argument."""
7803 valid_arg = func.GetValidArg(self)
7804 if valid_arg != None:
7805 return valid_arg
7807 if self.IsPointer():
7808 return 'nullptr'
7809 index = func.GetOriginalArgs().index(self)
7810 if self.type == 'GLsync':
7811 return ("reinterpret_cast<GLsync>(%d)" % (index + 1))
7812 return str(index + 1)
7814 def GetValidClientSideCmdArg(self, func):
7815 """Gets a valid value for this argument."""
7816 valid_arg = func.GetValidArg(self)
7817 if valid_arg != None:
7818 return valid_arg
7819 try:
7820 index = func.GetOriginalArgs().index(self)
7821 return str(index + 1)
7822 except ValueError:
7823 pass
7824 index = func.GetCmdArgs().index(self)
7825 return str(index + 1)
7827 def GetValidGLArg(self, func):
7828 """Gets a valid GL value for this argument."""
7829 value = self.GetValidArg(func)
7830 if self.type == 'GLsync':
7831 return ("reinterpret_cast<GLsync>(%s)" % value)
7832 return value
7834 def GetValidNonCachedClientSideArg(self, func):
7835 """Returns a valid value for this argument in a GL call.
7836 Using the value will produce a command buffer service invocation.
7837 Returns None if there is no such value."""
7838 value = '123'
7839 if self.type == 'GLsync':
7840 return ("reinterpret_cast<GLsync>(%s)" % value)
7841 return value
7843 def GetValidNonCachedClientSideCmdArg(self, func):
7844 """Returns a valid value for this argument in a command buffer command.
7845 Calling the GL function with the value returned by
7846 GetValidNonCachedClientSideArg will result in a command buffer command
7847 that contains the value returned by this function. """
7848 return '123'
7850 def GetNumInvalidValues(self, func):
7851 """returns the number of invalid values to be tested."""
7852 return 0
7854 def GetInvalidArg(self, index):
7855 """returns an invalid value and expected parse result by index."""
7856 return ("---ERROR0---", "---ERROR2---", None)
7858 def GetLogArg(self):
7859 """Get argument appropriate for LOG macro."""
7860 if self.type == 'GLboolean':
7861 return 'GLES2Util::GetStringBool(%s)' % self.name
7862 if self.type == 'GLenum':
7863 return 'GLES2Util::GetStringEnum(%s)' % self.name
7864 return self.name
7866 def WriteGetCode(self, file):
7867 """Writes the code to get an argument from a command structure."""
7868 if self.type == 'GLsync':
7869 my_type = 'GLuint'
7870 else:
7871 my_type = self.type
7872 file.Write(" %s %s = static_cast<%s>(c.%s);\n" %
7873 (my_type, self.name, my_type, self.name))
7875 def WriteValidationCode(self, file, func):
7876 """Writes the validation code for an argument."""
7877 pass
7879 def WriteClientSideValidationCode(self, file, func):
7880 """Writes the validation code for an argument."""
7881 pass
7883 def WriteDestinationInitalizationValidation(self, file, func):
7884 """Writes the client side destintion initialization validation."""
7885 pass
7887 def WriteDestinationInitalizationValidatationIfNeeded(self, file, func):
7888 """Writes the client side destintion initialization validation if needed."""
7889 parts = self.type.split(" ")
7890 if len(parts) > 1:
7891 return
7892 if parts[0] in self.need_validation_:
7893 file.Write(
7894 " GPU_CLIENT_VALIDATE_DESTINATION_%sINITALIZATION(%s, %s);\n" %
7895 ("OPTIONAL_" if self.optional else "", self.type[:-1], self.name))
7898 def WriteGetAddress(self, file):
7899 """Writes the code to get the address this argument refers to."""
7900 pass
7902 def GetImmediateVersion(self):
7903 """Gets the immediate version of this argument."""
7904 return self
7906 def GetBucketVersion(self):
7907 """Gets the bucket version of this argument."""
7908 return self
7911 class BoolArgument(Argument):
7912 """class for GLboolean"""
7914 def __init__(self, name, type):
7915 Argument.__init__(self, name, 'GLboolean')
7917 def GetValidArg(self, func):
7918 """Gets a valid value for this argument."""
7919 return 'true'
7921 def GetValidClientSideArg(self, func):
7922 """Gets a valid value for this argument."""
7923 return 'true'
7925 def GetValidClientSideCmdArg(self, func):
7926 """Gets a valid value for this argument."""
7927 return 'true'
7929 def GetValidGLArg(self, func):
7930 """Gets a valid GL value for this argument."""
7931 return 'true'
7934 class UniformLocationArgument(Argument):
7935 """class for uniform locations."""
7937 def __init__(self, name):
7938 Argument.__init__(self, name, "GLint")
7940 def WriteGetCode(self, file):
7941 """Writes the code to get an argument from a command structure."""
7942 code = """ %s %s = static_cast<%s>(c.%s);
7944 file.Write(code % (self.type, self.name, self.type, self.name))
7946 class DataSizeArgument(Argument):
7947 """class for data_size which Bucket commands do not need."""
7949 def __init__(self, name):
7950 Argument.__init__(self, name, "uint32_t")
7952 def GetBucketVersion(self):
7953 return None
7956 class SizeArgument(Argument):
7957 """class for GLsizei and GLsizeiptr."""
7959 def __init__(self, name, type):
7960 Argument.__init__(self, name, type)
7962 def GetNumInvalidValues(self, func):
7963 """overridden from Argument."""
7964 if func.IsImmediate():
7965 return 0
7966 return 1
7968 def GetInvalidArg(self, index):
7969 """overridden from Argument."""
7970 return ("-1", "kNoError", "GL_INVALID_VALUE")
7972 def WriteValidationCode(self, file, func):
7973 """overridden from Argument."""
7974 if func.IsUnsafe():
7975 return
7976 code = """ if (%(var_name)s < 0) {
7977 LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
7978 return error::kNoError;
7981 file.Write(code % {
7982 "var_name": self.name,
7983 "func_name": func.original_name,
7986 def WriteClientSideValidationCode(self, file, func):
7987 """overridden from Argument."""
7988 code = """ if (%(var_name)s < 0) {
7989 SetGLError(GL_INVALID_VALUE, "gl%(func_name)s", "%(var_name)s < 0");
7990 return;
7993 file.Write(code % {
7994 "var_name": self.name,
7995 "func_name": func.original_name,
7999 class SizeNotNegativeArgument(SizeArgument):
8000 """class for GLsizeiNotNegative. It's NEVER allowed to be negative"""
8002 def __init__(self, name, type, gl_type):
8003 SizeArgument.__init__(self, name, gl_type)
8005 def GetInvalidArg(self, index):
8006 """overridden from SizeArgument."""
8007 return ("-1", "kOutOfBounds", "GL_NO_ERROR")
8009 def WriteValidationCode(self, file, func):
8010 """overridden from SizeArgument."""
8011 pass
8014 class EnumBaseArgument(Argument):
8015 """Base class for EnumArgument, IntArgument, BitfieldArgument, and
8016 ValidatedBoolArgument."""
8018 def __init__(self, name, gl_type, type, gl_error):
8019 Argument.__init__(self, name, gl_type)
8021 self.local_type = type
8022 self.gl_error = gl_error
8023 name = type[len(gl_type):]
8024 self.type_name = name
8025 self.named_type = NamedType(_NAMED_TYPE_INFO[name])
8027 def IsConstant(self):
8028 return self.named_type.IsConstant()
8030 def GetConstantValue(self):
8031 return self.named_type.GetConstantValue()
8033 def WriteValidationCode(self, file, func):
8034 if func.IsUnsafe():
8035 return
8036 if self.named_type.IsConstant():
8037 return
8038 file.Write(" if (!validators_->%s.IsValid(%s)) {\n" %
8039 (ToUnderscore(self.type_name), self.name))
8040 if self.gl_error == "GL_INVALID_ENUM":
8041 file.Write(
8042 " LOCAL_SET_GL_ERROR_INVALID_ENUM(\"gl%s\", %s, \"%s\");\n" %
8043 (func.original_name, self.name, self.name))
8044 else:
8045 file.Write(
8046 " LOCAL_SET_GL_ERROR(%s, \"gl%s\", \"%s %s\");\n" %
8047 (self.gl_error, func.original_name, self.name, self.gl_error))
8048 file.Write(" return error::kNoError;\n")
8049 file.Write(" }\n")
8051 def WriteClientSideValidationCode(self, file, func):
8052 if not self.named_type.IsConstant():
8053 return
8054 file.Write(" if (%s != %s) {" % (self.name,
8055 self.GetConstantValue()))
8056 file.Write(
8057 " SetGLError(%s, \"gl%s\", \"%s %s\");\n" %
8058 (self.gl_error, func.original_name, self.name, self.gl_error))
8059 if func.return_type == "void":
8060 file.Write(" return;\n")
8061 else:
8062 file.Write(" return %s;\n" % func.GetErrorReturnString())
8063 file.Write(" }\n")
8065 def GetValidArg(self, func):
8066 valid_arg = func.GetValidArg(self)
8067 if valid_arg != None:
8068 return valid_arg
8069 valid = self.named_type.GetValidValues()
8070 if valid:
8071 num_valid = len(valid)
8072 return valid[0]
8074 index = func.GetOriginalArgs().index(self)
8075 return str(index + 1)
8077 def GetValidClientSideArg(self, func):
8078 """Gets a valid value for this argument."""
8079 return self.GetValidArg(func)
8081 def GetValidClientSideCmdArg(self, func):
8082 """Gets a valid value for this argument."""
8083 valid_arg = func.GetValidArg(self)
8084 if valid_arg != None:
8085 return valid_arg
8087 valid = self.named_type.GetValidValues()
8088 if valid:
8089 num_valid = len(valid)
8090 return valid[0]
8092 try:
8093 index = func.GetOriginalArgs().index(self)
8094 return str(index + 1)
8095 except ValueError:
8096 pass
8097 index = func.GetCmdArgs().index(self)
8098 return str(index + 1)
8100 def GetValidGLArg(self, func):
8101 """Gets a valid value for this argument."""
8102 return self.GetValidArg(func)
8104 def GetNumInvalidValues(self, func):
8105 """returns the number of invalid values to be tested."""
8106 return len(self.named_type.GetInvalidValues())
8108 def GetInvalidArg(self, index):
8109 """returns an invalid value by index."""
8110 invalid = self.named_type.GetInvalidValues()
8111 if invalid:
8112 num_invalid = len(invalid)
8113 if index >= num_invalid:
8114 index = num_invalid - 1
8115 return (invalid[index], "kNoError", self.gl_error)
8116 return ("---ERROR1---", "kNoError", self.gl_error)
8119 class EnumArgument(EnumBaseArgument):
8120 """A class that represents a GLenum argument"""
8122 def __init__(self, name, type):
8123 EnumBaseArgument.__init__(self, name, "GLenum", type, "GL_INVALID_ENUM")
8125 def GetLogArg(self):
8126 """Overridden from Argument."""
8127 return ("GLES2Util::GetString%s(%s)" %
8128 (self.type_name, self.name))
8131 class IntArgument(EnumBaseArgument):
8132 """A class for a GLint argument that can only accept specific values.
8134 For example glTexImage2D takes a GLint for its internalformat
8135 argument instead of a GLenum.
8138 def __init__(self, name, type):
8139 EnumBaseArgument.__init__(self, name, "GLint", type, "GL_INVALID_VALUE")
8142 class ValidatedBoolArgument(EnumBaseArgument):
8143 """A class for a GLboolean argument that can only accept specific values.
8145 For example glUniformMatrix takes a GLboolean for it's transpose but it
8146 must be false.
8149 def __init__(self, name, type):
8150 EnumBaseArgument.__init__(self, name, "GLboolean", type, "GL_INVALID_VALUE")
8152 def GetLogArg(self):
8153 """Overridden from Argument."""
8154 return 'GLES2Util::GetStringBool(%s)' % self.name
8157 class BitFieldArgument(EnumBaseArgument):
8158 """A class for a GLbitfield argument that can only accept specific values.
8160 For example glFenceSync takes a GLbitfield for its flags argument bit it
8161 must be 0.
8164 def __init__(self, name, type):
8165 EnumBaseArgument.__init__(self, name, "GLbitfield", type,
8166 "GL_INVALID_VALUE")
8169 class ImmediatePointerArgument(Argument):
8170 """A class that represents an immediate argument to a function.
8172 An immediate argument is one where the data follows the command.
8175 def __init__(self, name, type):
8176 Argument.__init__(self, name, type)
8178 def IsPointer(self):
8179 return True
8181 def GetPointedType(self):
8182 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8183 assert match
8184 return match.groupdict()['element_type']
8186 def AddCmdArgs(self, args):
8187 """Overridden from Argument."""
8188 pass
8190 def WriteGetCode(self, file):
8191 """Overridden from Argument."""
8192 file.Write(
8193 " %s %s = GetImmediateDataAs<%s>(\n" %
8194 (self.type, self.name, self.type))
8195 file.Write(" c, data_size, immediate_data_size);\n")
8197 def WriteValidationCode(self, file, func):
8198 """Overridden from Argument."""
8199 if self.optional:
8200 return
8201 file.Write(" if (%s == NULL) {\n" % self.name)
8202 file.Write(" return error::kOutOfBounds;\n")
8203 file.Write(" }\n")
8205 def GetImmediateVersion(self):
8206 """Overridden from Argument."""
8207 return None
8209 def WriteDestinationInitalizationValidation(self, file, func):
8210 """Overridden from Argument."""
8211 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8213 def GetLogArg(self):
8214 """Overridden from Argument."""
8215 return "static_cast<const void*>(%s)" % self.name
8218 class PointerArgument(Argument):
8219 """A class that represents a pointer argument to a function."""
8221 def __init__(self, name, type):
8222 Argument.__init__(self, name, type)
8224 def IsPointer(self):
8225 """Overridden from Argument."""
8226 return True
8228 def IsPointer2D(self):
8229 """Overridden from Argument."""
8230 return self.type.count('*') == 2
8232 def GetPointedType(self):
8233 match = re.match('(const\s+)?(?P<element_type>[\w]+)\s*\*', self.type)
8234 assert match
8235 return match.groupdict()['element_type']
8237 def GetValidArg(self, func):
8238 """Overridden from Argument."""
8239 return "shared_memory_id_, shared_memory_offset_"
8241 def GetValidGLArg(self, func):
8242 """Overridden from Argument."""
8243 return "reinterpret_cast<%s>(shared_memory_address_)" % self.type
8245 def GetNumInvalidValues(self, func):
8246 """Overridden from Argument."""
8247 return 2
8249 def GetInvalidArg(self, index):
8250 """Overridden from Argument."""
8251 if index == 0:
8252 return ("kInvalidSharedMemoryId, 0", "kOutOfBounds", None)
8253 else:
8254 return ("shared_memory_id_, kInvalidSharedMemoryOffset",
8255 "kOutOfBounds", None)
8257 def GetLogArg(self):
8258 """Overridden from Argument."""
8259 return "static_cast<const void*>(%s)" % self.name
8261 def AddCmdArgs(self, args):
8262 """Overridden from Argument."""
8263 args.append(Argument("%s_shm_id" % self.name, 'uint32_t'))
8264 args.append(Argument("%s_shm_offset" % self.name, 'uint32_t'))
8266 def WriteGetCode(self, file):
8267 """Overridden from Argument."""
8268 file.Write(
8269 " %s %s = GetSharedMemoryAs<%s>(\n" %
8270 (self.type, self.name, self.type))
8271 file.Write(
8272 " c.%s_shm_id, c.%s_shm_offset, data_size);\n" %
8273 (self.name, self.name))
8275 def WriteGetAddress(self, file):
8276 """Overridden from Argument."""
8277 file.Write(
8278 " %s %s = GetSharedMemoryAs<%s>(\n" %
8279 (self.type, self.name, self.type))
8280 file.Write(
8281 " %s_shm_id, %s_shm_offset, %s_size);\n" %
8282 (self.name, self.name, self.name))
8284 def WriteValidationCode(self, file, func):
8285 """Overridden from Argument."""
8286 if self.optional:
8287 return
8288 file.Write(" if (%s == NULL) {\n" % self.name)
8289 file.Write(" return error::kOutOfBounds;\n")
8290 file.Write(" }\n")
8292 def GetImmediateVersion(self):
8293 """Overridden from Argument."""
8294 return ImmediatePointerArgument(self.name, self.type)
8296 def GetBucketVersion(self):
8297 """Overridden from Argument."""
8298 if self.type.find('char') >= 0:
8299 if self.IsPointer2D():
8300 return InputStringArrayBucketArgument(self.name, self.type)
8301 return InputStringBucketArgument(self.name, self.type)
8302 return BucketPointerArgument(self.name, self.type)
8304 def WriteDestinationInitalizationValidation(self, file, func):
8305 """Overridden from Argument."""
8306 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8309 class BucketPointerArgument(PointerArgument):
8310 """A class that represents an bucket argument to a function."""
8312 def __init__(self, name, type):
8313 Argument.__init__(self, name, type)
8315 def AddCmdArgs(self, args):
8316 """Overridden from Argument."""
8317 pass
8319 def WriteGetCode(self, file):
8320 """Overridden from Argument."""
8321 file.Write(
8322 " %s %s = bucket->GetData(0, data_size);\n" %
8323 (self.type, self.name))
8325 def WriteValidationCode(self, file, func):
8326 """Overridden from Argument."""
8327 pass
8329 def GetImmediateVersion(self):
8330 """Overridden from Argument."""
8331 return None
8333 def WriteDestinationInitalizationValidation(self, file, func):
8334 """Overridden from Argument."""
8335 self.WriteDestinationInitalizationValidatationIfNeeded(file, func)
8337 def GetLogArg(self):
8338 """Overridden from Argument."""
8339 return "static_cast<const void*>(%s)" % self.name
8342 class InputStringBucketArgument(Argument):
8343 """A string input argument where the string is passed in a bucket."""
8345 def __init__(self, name, type):
8346 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8348 def IsPointer(self):
8349 """Overridden from Argument."""
8350 return True
8352 def IsPointer2D(self):
8353 """Overridden from Argument."""
8354 return False
8357 class InputStringArrayBucketArgument(Argument):
8358 """A string array input argument where the strings are passed in a bucket."""
8360 def __init__(self, name, type):
8361 Argument.__init__(self, name + "_bucket_id", "uint32_t")
8362 self._original_name = name
8364 def WriteGetCode(self, file):
8365 """Overridden from Argument."""
8366 code = """
8367 Bucket* bucket = GetBucket(c.%(name)s);
8368 if (!bucket) {
8369 return error::kInvalidArguments;
8371 GLsizei count = 0;
8372 std::vector<char*> strs;
8373 std::vector<GLint> len;
8374 if (!bucket->GetAsStrings(&count, &strs, &len)) {
8375 return error::kInvalidArguments;
8377 const char** %(original_name)s =
8378 strs.size() > 0 ? const_cast<const char**>(&strs[0]) : NULL;
8379 const GLint* length =
8380 len.size() > 0 ? const_cast<const GLint*>(&len[0]) : NULL;
8381 (void)length;
8383 file.Write(code % {
8384 'name': self.name,
8385 'original_name': self._original_name,
8388 def GetValidArg(self, func):
8389 return "kNameBucketId"
8391 def GetValidGLArg(self, func):
8392 return "_"
8394 def IsPointer(self):
8395 """Overridden from Argument."""
8396 return True
8398 def IsPointer2D(self):
8399 """Overridden from Argument."""
8400 return True
8403 class ResourceIdArgument(Argument):
8404 """A class that represents a resource id argument to a function."""
8406 def __init__(self, name, type):
8407 match = re.match("(GLid\w+)", type)
8408 self.resource_type = match.group(1)[4:]
8409 if self.resource_type == "Sync":
8410 type = type.replace(match.group(1), "GLsync")
8411 else:
8412 type = type.replace(match.group(1), "GLuint")
8413 Argument.__init__(self, name, type)
8415 def WriteGetCode(self, file):
8416 """Overridden from Argument."""
8417 if self.type == "GLsync":
8418 my_type = "GLuint"
8419 else:
8420 my_type = self.type
8421 file.Write(" %s %s = c.%s;\n" % (my_type, self.name, self.name))
8423 def GetValidArg(self, func):
8424 return "client_%s_id_" % self.resource_type.lower()
8426 def GetValidGLArg(self, func):
8427 if self.resource_type == "Sync":
8428 return "reinterpret_cast<GLsync>(kService%sId)" % self.resource_type
8429 return "kService%sId" % self.resource_type
8432 class ResourceIdBindArgument(Argument):
8433 """Represents a resource id argument to a bind function."""
8435 def __init__(self, name, type):
8436 match = re.match("(GLidBind\w+)", type)
8437 self.resource_type = match.group(1)[8:]
8438 type = type.replace(match.group(1), "GLuint")
8439 Argument.__init__(self, name, type)
8441 def WriteGetCode(self, file):
8442 """Overridden from Argument."""
8443 code = """ %(type)s %(name)s = c.%(name)s;
8445 file.Write(code % {'type': self.type, 'name': self.name})
8447 def GetValidArg(self, func):
8448 return "client_%s_id_" % self.resource_type.lower()
8450 def GetValidGLArg(self, func):
8451 return "kService%sId" % self.resource_type
8454 class ResourceIdZeroArgument(Argument):
8455 """Represents a resource id argument to a function that can be zero."""
8457 def __init__(self, name, type):
8458 match = re.match("(GLidZero\w+)", type)
8459 self.resource_type = match.group(1)[8:]
8460 type = type.replace(match.group(1), "GLuint")
8461 Argument.__init__(self, name, type)
8463 def WriteGetCode(self, file):
8464 """Overridden from Argument."""
8465 file.Write(" %s %s = c.%s;\n" % (self.type, self.name, self.name))
8467 def GetValidArg(self, func):
8468 return "client_%s_id_" % self.resource_type.lower()
8470 def GetValidGLArg(self, func):
8471 return "kService%sId" % self.resource_type
8473 def GetNumInvalidValues(self, func):
8474 """returns the number of invalid values to be tested."""
8475 return 1
8477 def GetInvalidArg(self, index):
8478 """returns an invalid value by index."""
8479 return ("kInvalidClientId", "kNoError", "GL_INVALID_VALUE")
8482 class Function(object):
8483 """A class that represents a function."""
8485 type_handlers = {
8486 '': TypeHandler(),
8487 'Bind': BindHandler(),
8488 'Create': CreateHandler(),
8489 'Custom': CustomHandler(),
8490 'Data': DataHandler(),
8491 'Delete': DeleteHandler(),
8492 'DELn': DELnHandler(),
8493 'GENn': GENnHandler(),
8494 'GETn': GETnHandler(),
8495 'GLchar': GLcharHandler(),
8496 'GLcharN': GLcharNHandler(),
8497 'HandWritten': HandWrittenHandler(),
8498 'Is': IsHandler(),
8499 'Manual': ManualHandler(),
8500 'PUT': PUTHandler(),
8501 'PUTn': PUTnHandler(),
8502 'PUTSTR': PUTSTRHandler(),
8503 'PUTXn': PUTXnHandler(),
8504 'StateSet': StateSetHandler(),
8505 'StateSetRGBAlpha': StateSetRGBAlphaHandler(),
8506 'StateSetFrontBack': StateSetFrontBackHandler(),
8507 'StateSetFrontBackSeparate': StateSetFrontBackSeparateHandler(),
8508 'StateSetNamedParameter': StateSetNamedParameter(),
8509 'STRn': STRnHandler(),
8510 'Todo': TodoHandler(),
8513 def __init__(self, name, info):
8514 self.name = name
8515 self.original_name = info['original_name']
8517 self.original_args = self.ParseArgs(info['original_args'])
8519 if 'cmd_args' in info:
8520 self.args_for_cmds = self.ParseArgs(info['cmd_args'])
8521 else:
8522 self.args_for_cmds = self.original_args[:]
8524 self.return_type = info['return_type']
8525 if self.return_type != 'void':
8526 self.return_arg = CreateArg(info['return_type'] + " result")
8527 else:
8528 self.return_arg = None
8530 self.num_pointer_args = sum(
8531 [1 for arg in self.args_for_cmds if arg.IsPointer()])
8532 if self.num_pointer_args > 0:
8533 for arg in reversed(self.original_args):
8534 if arg.IsPointer():
8535 self.last_original_pointer_arg = arg
8536 break
8537 else:
8538 self.last_original_pointer_arg = None
8539 self.info = info
8540 self.type_handler = self.type_handlers[info['type']]
8541 self.can_auto_generate = (self.num_pointer_args == 0 and
8542 info['return_type'] == "void")
8543 self.InitFunction()
8545 def ParseArgs(self, arg_string):
8546 """Parses a function arg string."""
8547 args = []
8548 parts = arg_string.split(',')
8549 for arg_string in parts:
8550 arg = CreateArg(arg_string)
8551 if arg:
8552 args.append(arg)
8553 return args
8555 def IsType(self, type_name):
8556 """Returns true if function is a certain type."""
8557 return self.info['type'] == type_name
8559 def InitFunction(self):
8560 """Creates command args and calls the init function for the type handler.
8562 Creates argument lists for command buffer commands, eg. self.cmd_args and
8563 self.init_args.
8564 Calls the type function initialization.
8565 Override to create different kind of command buffer command argument lists.
8567 self.cmd_args = []
8568 for arg in self.args_for_cmds:
8569 arg.AddCmdArgs(self.cmd_args)
8571 self.init_args = []
8572 for arg in self.args_for_cmds:
8573 arg.AddInitArgs(self.init_args)
8575 if self.return_arg:
8576 self.init_args.append(self.return_arg)
8578 self.type_handler.InitFunction(self)
8580 def IsImmediate(self):
8581 """Returns whether the function is immediate data function or not."""
8582 return False
8584 def IsUnsafe(self):
8585 """Returns whether the function has service side validation or not."""
8586 return self.GetInfo('unsafe', False)
8588 def GetInfo(self, name, default = None):
8589 """Returns a value from the function info for this function."""
8590 if name in self.info:
8591 return self.info[name]
8592 return default
8594 def GetValidArg(self, arg):
8595 """Gets a valid argument value for the parameter arg from the function info
8596 if one exists."""
8597 try:
8598 index = self.GetOriginalArgs().index(arg)
8599 except ValueError:
8600 return None
8602 valid_args = self.GetInfo('valid_args')
8603 if valid_args and str(index) in valid_args:
8604 return valid_args[str(index)]
8605 return None
8607 def AddInfo(self, name, value):
8608 """Adds an info."""
8609 self.info[name] = value
8611 def IsExtension(self):
8612 return self.GetInfo('extension') or self.GetInfo('extension_flag')
8614 def IsCoreGLFunction(self):
8615 return (not self.IsExtension() and
8616 not self.GetInfo('pepper_interface') and
8617 not self.IsUnsafe())
8619 def InPepperInterface(self, interface):
8620 ext = self.GetInfo('pepper_interface')
8621 if not interface.GetName():
8622 return self.IsCoreGLFunction()
8623 return ext == interface.GetName()
8625 def InAnyPepperExtension(self):
8626 return self.IsCoreGLFunction() or self.GetInfo('pepper_interface')
8628 def GetErrorReturnString(self):
8629 if self.GetInfo("error_return"):
8630 return self.GetInfo("error_return")
8631 elif self.return_type == "GLboolean":
8632 return "GL_FALSE"
8633 elif "*" in self.return_type:
8634 return "NULL"
8635 return "0"
8637 def GetGLFunctionName(self):
8638 """Gets the function to call to execute GL for this command."""
8639 if self.GetInfo('decoder_func'):
8640 return self.GetInfo('decoder_func')
8641 return "gl%s" % self.original_name
8643 def GetGLTestFunctionName(self):
8644 gl_func_name = self.GetInfo('gl_test_func')
8645 if gl_func_name == None:
8646 gl_func_name = self.GetGLFunctionName()
8647 if gl_func_name.startswith("gl"):
8648 gl_func_name = gl_func_name[2:]
8649 else:
8650 gl_func_name = self.original_name
8651 return gl_func_name
8653 def GetDataTransferMethods(self):
8654 return self.GetInfo('data_transfer_methods',
8655 ['immediate' if self.num_pointer_args == 1 else 'shm'])
8657 def AddCmdArg(self, arg):
8658 """Adds a cmd argument to this function."""
8659 self.cmd_args.append(arg)
8661 def GetCmdArgs(self):
8662 """Gets the command args for this function."""
8663 return self.cmd_args
8665 def ClearCmdArgs(self):
8666 """Clears the command args for this function."""
8667 self.cmd_args = []
8669 def GetCmdConstants(self):
8670 """Gets the constants for this function."""
8671 return [arg for arg in self.args_for_cmds if arg.IsConstant()]
8673 def GetInitArgs(self):
8674 """Gets the init args for this function."""
8675 return self.init_args
8677 def GetOriginalArgs(self):
8678 """Gets the original arguments to this function."""
8679 return self.original_args
8681 def GetLastOriginalArg(self):
8682 """Gets the last original argument to this function."""
8683 return self.original_args[len(self.original_args) - 1]
8685 def GetLastOriginalPointerArg(self):
8686 return self.last_original_pointer_arg
8688 def GetResourceIdArg(self):
8689 for arg in self.original_args:
8690 if hasattr(arg, 'resource_type'):
8691 return arg
8692 return None
8694 def _MaybePrependComma(self, arg_string, add_comma):
8695 """Adds a comma if arg_string is not empty and add_comma is true."""
8696 comma = ""
8697 if add_comma and len(arg_string):
8698 comma = ", "
8699 return "%s%s" % (comma, arg_string)
8701 def MakeTypedOriginalArgString(self, prefix, add_comma = False):
8702 """Gets a list of arguments as they are in GL."""
8703 args = self.GetOriginalArgs()
8704 arg_string = ", ".join(
8705 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8706 return self._MaybePrependComma(arg_string, add_comma)
8708 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
8709 """Gets the list of arguments as they are in GL."""
8710 args = self.GetOriginalArgs()
8711 arg_string = separator.join(
8712 ["%s%s" % (prefix, arg.name) for arg in args])
8713 return self._MaybePrependComma(arg_string, add_comma)
8715 def MakeTypedHelperArgString(self, prefix, add_comma = False):
8716 """Gets a list of typed GL arguments after removing unneeded arguments."""
8717 args = self.GetOriginalArgs()
8718 arg_string = ", ".join(
8719 ["%s %s%s" % (
8720 arg.type,
8721 prefix,
8722 arg.name,
8723 ) for arg in args if not arg.IsConstant()])
8724 return self._MaybePrependComma(arg_string, add_comma)
8726 def MakeHelperArgString(self, prefix, add_comma = False, separator = ", "):
8727 """Gets a list of GL arguments after removing unneeded arguments."""
8728 args = self.GetOriginalArgs()
8729 arg_string = separator.join(
8730 ["%s%s" % (prefix, arg.name)
8731 for arg in args if not arg.IsConstant()])
8732 return self._MaybePrependComma(arg_string, add_comma)
8734 def MakeTypedPepperArgString(self, prefix):
8735 """Gets a list of arguments as they need to be for Pepper."""
8736 if self.GetInfo("pepper_args"):
8737 return self.GetInfo("pepper_args")
8738 else:
8739 return self.MakeTypedOriginalArgString(prefix, False)
8741 def MapCTypeToPepperIdlType(self, ctype, is_for_return_type=False):
8742 """Converts a C type name to the corresponding Pepper IDL type."""
8743 idltype = {
8744 'char*': '[out] str_t',
8745 'const GLchar* const*': '[out] cstr_t',
8746 'const char*': 'cstr_t',
8747 'const void*': 'mem_t',
8748 'void*': '[out] mem_t',
8749 'void**': '[out] mem_ptr_t',
8750 }.get(ctype, ctype)
8751 # We use "GLxxx_ptr_t" for "GLxxx*".
8752 matched = re.match(r'(const )?(GL\w+)\*$', ctype)
8753 if matched:
8754 idltype = matched.group(2) + '_ptr_t'
8755 if not matched.group(1):
8756 idltype = '[out] ' + idltype
8757 # If an in/out specifier is not specified yet, prepend [in].
8758 if idltype[0] != '[':
8759 idltype = '[in] ' + idltype
8760 # Strip the in/out specifier for a return type.
8761 if is_for_return_type:
8762 idltype = re.sub(r'\[\w+\] ', '', idltype)
8763 return idltype
8765 def MakeTypedPepperIdlArgStrings(self):
8766 """Gets a list of arguments as they need to be for Pepper IDL."""
8767 args = self.GetOriginalArgs()
8768 return ["%s %s" % (self.MapCTypeToPepperIdlType(arg.type), arg.name)
8769 for arg in args]
8771 def GetPepperName(self):
8772 if self.GetInfo("pepper_name"):
8773 return self.GetInfo("pepper_name")
8774 return self.name
8776 def MakeTypedCmdArgString(self, prefix, add_comma = False):
8777 """Gets a typed list of arguments as they need to be for command buffers."""
8778 args = self.GetCmdArgs()
8779 arg_string = ", ".join(
8780 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8781 return self._MaybePrependComma(arg_string, add_comma)
8783 def MakeCmdArgString(self, prefix, add_comma = False):
8784 """Gets the list of arguments as they need to be for command buffers."""
8785 args = self.GetCmdArgs()
8786 arg_string = ", ".join(
8787 ["%s%s" % (prefix, arg.name) for arg in args])
8788 return self._MaybePrependComma(arg_string, add_comma)
8790 def MakeTypedInitString(self, prefix, add_comma = False):
8791 """Gets a typed list of arguments as they need to be for cmd Init/Set."""
8792 args = self.GetInitArgs()
8793 arg_string = ", ".join(
8794 ["%s %s%s" % (arg.type, prefix, arg.name) for arg in args])
8795 return self._MaybePrependComma(arg_string, add_comma)
8797 def MakeInitString(self, prefix, add_comma = False):
8798 """Gets the list of arguments as they need to be for cmd Init/Set."""
8799 args = self.GetInitArgs()
8800 arg_string = ", ".join(
8801 ["%s%s" % (prefix, arg.name) for arg in args])
8802 return self._MaybePrependComma(arg_string, add_comma)
8804 def MakeLogArgString(self):
8805 """Makes a string of the arguments for the LOG macros"""
8806 args = self.GetOriginalArgs()
8807 return ' << ", " << '.join([arg.GetLogArg() for arg in args])
8809 def WriteCommandDescription(self, file):
8810 """Writes a description of the command."""
8811 file.Write("//! Command that corresponds to gl%s.\n" % self.original_name)
8813 def WriteHandlerValidation(self, file):
8814 """Writes validation code for the function."""
8815 for arg in self.GetOriginalArgs():
8816 arg.WriteValidationCode(file, self)
8817 self.WriteValidationCode(file)
8819 def WriteHandlerImplementation(self, file):
8820 """Writes the handler implementation for this command."""
8821 self.type_handler.WriteHandlerImplementation(self, file)
8823 def WriteValidationCode(self, file):
8824 """Writes the validation code for a command."""
8825 pass
8827 def WriteCmdFlag(self, file):
8828 """Writes the cmd cmd_flags constant."""
8829 flags = []
8830 # By default trace only at the highest level 3.
8831 trace_level = int(self.GetInfo('trace_level', default = 3))
8832 if trace_level not in xrange(0, 4):
8833 raise KeyError("Unhandled trace_level: %d" % trace_level)
8835 flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level)
8837 if len(flags) > 0:
8838 cmd_flags = ' | '.join(flags)
8839 else:
8840 cmd_flags = 0
8842 file.Write(" static const uint8 cmd_flags = %s;\n" % cmd_flags)
8845 def WriteCmdArgFlag(self, file):
8846 """Writes the cmd kArgFlags constant."""
8847 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kFixed;\n")
8849 def WriteCmdComputeSize(self, file):
8850 """Writes the ComputeSize function for the command."""
8851 file.Write(" static uint32_t ComputeSize() {\n")
8852 file.Write(
8853 " return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT\n")
8854 file.Write(" }\n")
8855 file.Write("\n")
8857 def WriteCmdSetHeader(self, file):
8858 """Writes the cmd's SetHeader function."""
8859 file.Write(" void SetHeader() {\n")
8860 file.Write(" header.SetCmd<ValueType>();\n")
8861 file.Write(" }\n")
8862 file.Write("\n")
8864 def WriteCmdInit(self, file):
8865 """Writes the cmd's Init function."""
8866 file.Write(" void Init(%s) {\n" % self.MakeTypedCmdArgString("_"))
8867 file.Write(" SetHeader();\n")
8868 args = self.GetCmdArgs()
8869 for arg in args:
8870 file.Write(" %s = _%s;\n" % (arg.name, arg.name))
8871 file.Write(" }\n")
8872 file.Write("\n")
8874 def WriteCmdSet(self, file):
8875 """Writes the cmd's Set function."""
8876 copy_args = self.MakeCmdArgString("_", False)
8877 file.Write(" void* Set(void* cmd%s) {\n" %
8878 self.MakeTypedCmdArgString("_", True))
8879 file.Write(" static_cast<ValueType*>(cmd)->Init(%s);\n" % copy_args)
8880 file.Write(" return NextCmdAddress<ValueType>(cmd);\n")
8881 file.Write(" }\n")
8882 file.Write("\n")
8884 def WriteStruct(self, file):
8885 self.type_handler.WriteStruct(self, file)
8887 def WriteDocs(self, file):
8888 self.type_handler.WriteDocs(self, file)
8890 def WriteCmdHelper(self, file):
8891 """Writes the cmd's helper."""
8892 self.type_handler.WriteCmdHelper(self, file)
8894 def WriteServiceImplementation(self, file):
8895 """Writes the service implementation for a command."""
8896 self.type_handler.WriteServiceImplementation(self, file)
8898 def WriteServiceUnitTest(self, file, *extras):
8899 """Writes the service implementation for a command."""
8900 self.type_handler.WriteServiceUnitTest(self, file, *extras)
8902 def WriteGLES2CLibImplementation(self, file):
8903 """Writes the GLES2 C Lib Implemention."""
8904 self.type_handler.WriteGLES2CLibImplementation(self, file)
8906 def WriteGLES2InterfaceHeader(self, file):
8907 """Writes the GLES2 Interface declaration."""
8908 self.type_handler.WriteGLES2InterfaceHeader(self, file)
8910 def WriteGLES2InterfaceStub(self, file):
8911 """Writes the GLES2 Interface Stub declaration."""
8912 self.type_handler.WriteGLES2InterfaceStub(self, file)
8914 def WriteGLES2InterfaceStubImpl(self, file):
8915 """Writes the GLES2 Interface Stub declaration."""
8916 self.type_handler.WriteGLES2InterfaceStubImpl(self, file)
8918 def WriteGLES2ImplementationHeader(self, file):
8919 """Writes the GLES2 Implemention declaration."""
8920 self.type_handler.WriteGLES2ImplementationHeader(self, file)
8922 def WriteGLES2Implementation(self, file):
8923 """Writes the GLES2 Implemention definition."""
8924 self.type_handler.WriteGLES2Implementation(self, file)
8926 def WriteGLES2TraceImplementationHeader(self, file):
8927 """Writes the GLES2 Trace Implemention declaration."""
8928 self.type_handler.WriteGLES2TraceImplementationHeader(self, file)
8930 def WriteGLES2TraceImplementation(self, file):
8931 """Writes the GLES2 Trace Implemention definition."""
8932 self.type_handler.WriteGLES2TraceImplementation(self, file)
8934 def WriteGLES2Header(self, file):
8935 """Writes the GLES2 Implemention unit test."""
8936 self.type_handler.WriteGLES2Header(self, file)
8938 def WriteGLES2ImplementationUnitTest(self, file):
8939 """Writes the GLES2 Implemention unit test."""
8940 self.type_handler.WriteGLES2ImplementationUnitTest(self, file)
8942 def WriteDestinationInitalizationValidation(self, file):
8943 """Writes the client side destintion initialization validation."""
8944 self.type_handler.WriteDestinationInitalizationValidation(self, file)
8946 def WriteFormatTest(self, file):
8947 """Writes the cmd's format test."""
8948 self.type_handler.WriteFormatTest(self, file)
8951 class PepperInterface(object):
8952 """A class that represents a function."""
8954 def __init__(self, info):
8955 self.name = info["name"]
8956 self.dev = info["dev"]
8958 def GetName(self):
8959 return self.name
8961 def GetInterfaceName(self):
8962 upperint = ""
8963 dev = ""
8964 if self.name:
8965 upperint = "_" + self.name.upper()
8966 if self.dev:
8967 dev = "_DEV"
8968 return "PPB_OPENGLES2%s%s_INTERFACE" % (upperint, dev)
8970 def GetInterfaceString(self):
8971 dev = ""
8972 if self.dev:
8973 dev = "(Dev)"
8974 return "PPB_OpenGLES2%s%s" % (self.name, dev)
8976 def GetStructName(self):
8977 dev = ""
8978 if self.dev:
8979 dev = "_Dev"
8980 return "PPB_OpenGLES2%s%s" % (self.name, dev)
8983 class ImmediateFunction(Function):
8984 """A class that represnets an immediate function command."""
8986 def __init__(self, func):
8987 Function.__init__(
8988 self,
8989 "%sImmediate" % func.name,
8990 func.info)
8992 def InitFunction(self):
8993 # Override args in original_args and args_for_cmds with immediate versions
8994 # of the args.
8996 new_original_args = []
8997 for arg in self.original_args:
8998 new_arg = arg.GetImmediateVersion()
8999 if new_arg:
9000 new_original_args.append(new_arg)
9001 self.original_args = new_original_args
9003 new_args_for_cmds = []
9004 for arg in self.args_for_cmds:
9005 new_arg = arg.GetImmediateVersion()
9006 if new_arg:
9007 new_args_for_cmds.append(new_arg)
9009 self.args_for_cmds = new_args_for_cmds
9011 Function.InitFunction(self)
9013 def IsImmediate(self):
9014 return True
9016 def WriteCommandDescription(self, file):
9017 """Overridden from Function"""
9018 file.Write("//! Immediate version of command that corresponds to gl%s.\n" %
9019 self.original_name)
9021 def WriteServiceImplementation(self, file):
9022 """Overridden from Function"""
9023 self.type_handler.WriteImmediateServiceImplementation(self, file)
9025 def WriteHandlerImplementation(self, file):
9026 """Overridden from Function"""
9027 self.type_handler.WriteImmediateHandlerImplementation(self, file)
9029 def WriteServiceUnitTest(self, file, *extras):
9030 """Writes the service implementation for a command."""
9031 self.type_handler.WriteImmediateServiceUnitTest(self, file, *extras)
9033 def WriteValidationCode(self, file):
9034 """Overridden from Function"""
9035 self.type_handler.WriteImmediateValidationCode(self, file)
9037 def WriteCmdArgFlag(self, file):
9038 """Overridden from Function"""
9039 file.Write(" static const cmd::ArgFlags kArgFlags = cmd::kAtLeastN;\n")
9041 def WriteCmdComputeSize(self, file):
9042 """Overridden from Function"""
9043 self.type_handler.WriteImmediateCmdComputeSize(self, file)
9045 def WriteCmdSetHeader(self, file):
9046 """Overridden from Function"""
9047 self.type_handler.WriteImmediateCmdSetHeader(self, file)
9049 def WriteCmdInit(self, file):
9050 """Overridden from Function"""
9051 self.type_handler.WriteImmediateCmdInit(self, file)
9053 def WriteCmdSet(self, file):
9054 """Overridden from Function"""
9055 self.type_handler.WriteImmediateCmdSet(self, file)
9057 def WriteCmdHelper(self, file):
9058 """Overridden from Function"""
9059 self.type_handler.WriteImmediateCmdHelper(self, file)
9061 def WriteFormatTest(self, file):
9062 """Overridden from Function"""
9063 self.type_handler.WriteImmediateFormatTest(self, file)
9066 class BucketFunction(Function):
9067 """A class that represnets a bucket version of a function command."""
9069 def __init__(self, func):
9070 Function.__init__(
9071 self,
9072 "%sBucket" % func.name,
9073 func.info)
9075 def InitFunction(self):
9076 # Override args in original_args and args_for_cmds with bucket versions
9077 # of the args.
9079 new_original_args = []
9080 for arg in self.original_args:
9081 new_arg = arg.GetBucketVersion()
9082 if new_arg:
9083 new_original_args.append(new_arg)
9084 self.original_args = new_original_args
9086 new_args_for_cmds = []
9087 for arg in self.args_for_cmds:
9088 new_arg = arg.GetBucketVersion()
9089 if new_arg:
9090 new_args_for_cmds.append(new_arg)
9092 self.args_for_cmds = new_args_for_cmds
9094 Function.InitFunction(self)
9096 def WriteCommandDescription(self, file):
9097 """Overridden from Function"""
9098 file.Write("//! Bucket version of command that corresponds to gl%s.\n" %
9099 self.original_name)
9101 def WriteServiceImplementation(self, file):
9102 """Overridden from Function"""
9103 self.type_handler.WriteBucketServiceImplementation(self, file)
9105 def WriteHandlerImplementation(self, file):
9106 """Overridden from Function"""
9107 self.type_handler.WriteBucketHandlerImplementation(self, file)
9109 def WriteServiceUnitTest(self, file, *extras):
9110 """Overridden from Function"""
9111 self.type_handler.WriteBucketServiceUnitTest(self, file, *extras)
9113 def MakeOriginalArgString(self, prefix, add_comma = False, separator = ", "):
9114 """Overridden from Function"""
9115 args = self.GetOriginalArgs()
9116 arg_string = separator.join(
9117 ["%s%s" % (prefix, arg.name[0:-10] if arg.name.endswith("_bucket_id")
9118 else arg.name) for arg in args])
9119 return super(BucketFunction, self)._MaybePrependComma(arg_string, add_comma)
9122 def CreateArg(arg_string):
9123 """Creates an Argument."""
9124 arg_parts = arg_string.split()
9125 if len(arg_parts) == 1 and arg_parts[0] == 'void':
9126 return None
9127 # Is this a pointer argument?
9128 elif arg_string.find('*') >= 0:
9129 return PointerArgument(
9130 arg_parts[-1],
9131 " ".join(arg_parts[0:-1]))
9132 # Is this a resource argument? Must come after pointer check.
9133 elif arg_parts[0].startswith('GLidBind'):
9134 return ResourceIdBindArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9135 elif arg_parts[0].startswith('GLidZero'):
9136 return ResourceIdZeroArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9137 elif arg_parts[0].startswith('GLid'):
9138 return ResourceIdArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9139 elif arg_parts[0].startswith('GLenum') and len(arg_parts[0]) > 6:
9140 return EnumArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9141 elif arg_parts[0].startswith('GLbitfield') and len(arg_parts[0]) > 10:
9142 return BitFieldArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9143 elif arg_parts[0].startswith('GLboolean') and len(arg_parts[0]) > 9:
9144 return ValidatedBoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9145 elif arg_parts[0].startswith('GLboolean'):
9146 return BoolArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9147 elif arg_parts[0].startswith('GLintUniformLocation'):
9148 return UniformLocationArgument(arg_parts[-1])
9149 elif (arg_parts[0].startswith('GLint') and len(arg_parts[0]) > 5 and
9150 not arg_parts[0].startswith('GLintptr')):
9151 return IntArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9152 elif (arg_parts[0].startswith('GLsizeiNotNegative') or
9153 arg_parts[0].startswith('GLintptrNotNegative')):
9154 return SizeNotNegativeArgument(arg_parts[-1],
9155 " ".join(arg_parts[0:-1]),
9156 arg_parts[0][0:-11])
9157 elif arg_parts[0].startswith('GLsize'):
9158 return SizeArgument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9159 else:
9160 return Argument(arg_parts[-1], " ".join(arg_parts[0:-1]))
9163 class GLGenerator(object):
9164 """A class to generate GL command buffers."""
9166 _function_re = re.compile(r'GL_APICALL(.*?)GL_APIENTRY (.*?) \((.*?)\);')
9168 def __init__(self, verbose):
9169 self.original_functions = []
9170 self.functions = []
9171 self.verbose = verbose
9172 self.errors = 0
9173 self.pepper_interfaces = []
9174 self.interface_info = {}
9175 self.generated_cpp_filenames = []
9177 for interface in _PEPPER_INTERFACES:
9178 interface = PepperInterface(interface)
9179 self.pepper_interfaces.append(interface)
9180 self.interface_info[interface.GetName()] = interface
9182 def AddFunction(self, func):
9183 """Adds a function."""
9184 self.functions.append(func)
9186 def GetFunctionInfo(self, name):
9187 """Gets a type info for the given function name."""
9188 if name in _FUNCTION_INFO:
9189 func_info = _FUNCTION_INFO[name].copy()
9190 else:
9191 func_info = {}
9193 if not 'type' in func_info:
9194 func_info['type'] = ''
9196 return func_info
9198 def Log(self, msg):
9199 """Prints something if verbose is true."""
9200 if self.verbose:
9201 print msg
9203 def Error(self, msg):
9204 """Prints an error."""
9205 print "Error: %s" % msg
9206 self.errors += 1
9208 def WriteLicense(self, file):
9209 """Writes the license."""
9210 file.Write(_LICENSE)
9212 def WriteNamespaceOpen(self, file):
9213 """Writes the code for the namespace."""
9214 file.Write("namespace gpu {\n")
9215 file.Write("namespace gles2 {\n")
9216 file.Write("\n")
9218 def WriteNamespaceClose(self, file):
9219 """Writes the code to close the namespace."""
9220 file.Write("} // namespace gles2\n")
9221 file.Write("} // namespace gpu\n")
9222 file.Write("\n")
9224 def ParseGLH(self, filename):
9225 """Parses the cmd_buffer_functions.txt file and extracts the functions"""
9226 f = open(filename, "r")
9227 functions = f.read()
9228 f.close()
9229 for line in functions.splitlines():
9230 match = self._function_re.match(line)
9231 if match:
9232 func_name = match.group(2)[2:]
9233 func_info = self.GetFunctionInfo(func_name)
9234 if func_info['type'] == 'Noop':
9235 continue
9237 parsed_func_info = {
9238 'original_name': func_name,
9239 'original_args': match.group(3),
9240 'return_type': match.group(1).strip(),
9243 for k in parsed_func_info.keys():
9244 if not k in func_info:
9245 func_info[k] = parsed_func_info[k]
9247 f = Function(func_name, func_info)
9248 self.original_functions.append(f)
9250 #for arg in f.GetOriginalArgs():
9251 # if not isinstance(arg, EnumArgument) and arg.type == 'GLenum':
9252 # self.Log("%s uses bare GLenum %s." % (func_name, arg.name))
9254 gen_cmd = f.GetInfo('gen_cmd')
9255 if gen_cmd == True or gen_cmd == None:
9256 if f.type_handler.NeedsDataTransferFunction(f):
9257 methods = f.GetDataTransferMethods()
9258 if 'immediate' in methods:
9259 self.AddFunction(ImmediateFunction(f))
9260 if 'bucket' in methods:
9261 self.AddFunction(BucketFunction(f))
9262 if 'shm' in methods:
9263 self.AddFunction(f)
9264 else:
9265 self.AddFunction(f)
9267 self.Log("Auto Generated Functions : %d" %
9268 len([f for f in self.functions if f.can_auto_generate or
9269 (not f.IsType('') and not f.IsType('Custom') and
9270 not f.IsType('Todo'))]))
9272 funcs = [f for f in self.functions if not f.can_auto_generate and
9273 (f.IsType('') or f.IsType('Custom') or f.IsType('Todo'))]
9274 self.Log("Non Auto Generated Functions: %d" % len(funcs))
9276 for f in funcs:
9277 self.Log(" %-10s %-20s gl%s" % (f.info['type'], f.return_type, f.name))
9279 def WriteCommandIds(self, filename):
9280 """Writes the command buffer format"""
9281 file = CHeaderWriter(filename)
9282 file.Write("#define GLES2_COMMAND_LIST(OP) \\\n")
9283 id = 256
9284 for func in self.functions:
9285 file.Write(" %-60s /* %d */ \\\n" %
9286 ("OP(%s)" % func.name, id))
9287 id += 1
9288 file.Write("\n")
9290 file.Write("enum CommandId {\n")
9291 file.Write(" kStartPoint = cmd::kLastCommonId, "
9292 "// All GLES2 commands start after this.\n")
9293 file.Write("#define GLES2_CMD_OP(name) k ## name,\n")
9294 file.Write(" GLES2_COMMAND_LIST(GLES2_CMD_OP)\n")
9295 file.Write("#undef GLES2_CMD_OP\n")
9296 file.Write(" kNumCommands\n")
9297 file.Write("};\n")
9298 file.Write("\n")
9299 file.Close()
9300 self.generated_cpp_filenames.append(file.filename)
9302 def WriteFormat(self, filename):
9303 """Writes the command buffer format"""
9304 file = CHeaderWriter(filename)
9305 # Forward declaration of a few enums used in constant argument
9306 # to avoid including GL header files.
9307 enum_defines = {
9308 'GL_SYNC_GPU_COMMANDS_COMPLETE': '0x9117',
9309 'GL_SYNC_FLUSH_COMMANDS_BIT': '0x00000001',
9311 file.Write('\n')
9312 for enum in enum_defines:
9313 file.Write("#define %s %s\n" % (enum, enum_defines[enum]))
9314 file.Write('\n')
9315 for func in self.functions:
9316 if True:
9317 #gen_cmd = func.GetInfo('gen_cmd')
9318 #if gen_cmd == True or gen_cmd == None:
9319 func.WriteStruct(file)
9320 file.Write("\n")
9321 file.Close()
9322 self.generated_cpp_filenames.append(file.filename)
9324 def WriteDocs(self, filename):
9325 """Writes the command buffer doc version of the commands"""
9326 file = CWriter(filename)
9327 for func in self.functions:
9328 if True:
9329 #gen_cmd = func.GetInfo('gen_cmd')
9330 #if gen_cmd == True or gen_cmd == None:
9331 func.WriteDocs(file)
9332 file.Write("\n")
9333 file.Close()
9334 self.generated_cpp_filenames.append(file.filename)
9336 def WriteFormatTest(self, filename):
9337 """Writes the command buffer format test."""
9338 file = CHeaderWriter(
9339 filename,
9340 "// This file contains unit tests for gles2 commmands\n"
9341 "// It is included by gles2_cmd_format_test.cc\n"
9342 "\n")
9344 for func in self.functions:
9345 if True:
9346 #gen_cmd = func.GetInfo('gen_cmd')
9347 #if gen_cmd == True or gen_cmd == None:
9348 func.WriteFormatTest(file)
9350 file.Close()
9351 self.generated_cpp_filenames.append(file.filename)
9353 def WriteCmdHelperHeader(self, filename):
9354 """Writes the gles2 command helper."""
9355 file = CHeaderWriter(filename)
9357 for func in self.functions:
9358 if True:
9359 #gen_cmd = func.GetInfo('gen_cmd')
9360 #if gen_cmd == True or gen_cmd == None:
9361 func.WriteCmdHelper(file)
9363 file.Close()
9364 self.generated_cpp_filenames.append(file.filename)
9366 def WriteServiceContextStateHeader(self, filename):
9367 """Writes the service context state header."""
9368 file = CHeaderWriter(
9369 filename,
9370 "// It is included by context_state.h\n")
9371 file.Write("struct EnableFlags {\n")
9372 file.Write(" EnableFlags();\n")
9373 for capability in _CAPABILITY_FLAGS:
9374 file.Write(" bool %s;\n" % capability['name'])
9375 file.Write(" bool cached_%s;\n" % capability['name'])
9376 file.Write("};\n\n")
9378 for state_name in sorted(_STATES.keys()):
9379 state = _STATES[state_name]
9380 for item in state['states']:
9381 if isinstance(item['default'], list):
9382 file.Write("%s %s[%d];\n" % (item['type'], item['name'],
9383 len(item['default'])))
9384 else:
9385 file.Write("%s %s;\n" % (item['type'], item['name']))
9387 if item.get('cached', False):
9388 if isinstance(item['default'], list):
9389 file.Write("%s cached_%s[%d];\n" % (item['type'], item['name'],
9390 len(item['default'])))
9391 else:
9392 file.Write("%s cached_%s;\n" % (item['type'], item['name']))
9394 file.Write("\n")
9396 file.Write("""
9397 inline void SetDeviceCapabilityState(GLenum cap, bool enable) {
9398 switch (cap) {
9399 """)
9400 for capability in _CAPABILITY_FLAGS:
9401 file.Write("""\
9402 case GL_%s:
9403 """ % capability['name'].upper())
9404 file.Write("""\
9405 if (enable_flags.cached_%(name)s == enable &&
9406 !ignore_cached_state)
9407 return;
9408 enable_flags.cached_%(name)s = enable;
9409 break;
9410 """ % capability)
9412 file.Write("""\
9413 default:
9414 NOTREACHED();
9415 return;
9417 if (enable)
9418 glEnable(cap);
9419 else
9420 glDisable(cap);
9422 """)
9424 file.Close()
9425 self.generated_cpp_filenames.append(file.filename)
9427 def WriteClientContextStateHeader(self, filename):
9428 """Writes the client context state header."""
9429 file = CHeaderWriter(
9430 filename,
9431 "// It is included by client_context_state.h\n")
9432 file.Write("struct EnableFlags {\n")
9433 file.Write(" EnableFlags();\n")
9434 for capability in _CAPABILITY_FLAGS:
9435 file.Write(" bool %s;\n" % capability['name'])
9436 file.Write("};\n\n")
9438 file.Close()
9439 self.generated_cpp_filenames.append(file.filename)
9441 def WriteContextStateGetters(self, file, class_name):
9442 """Writes the state getters."""
9443 for gl_type in ["GLint", "GLfloat"]:
9444 file.Write("""
9445 bool %s::GetStateAs%s(
9446 GLenum pname, %s* params, GLsizei* num_written) const {
9447 switch (pname) {
9448 """ % (class_name, gl_type, gl_type))
9449 for state_name in sorted(_STATES.keys()):
9450 state = _STATES[state_name]
9451 if 'enum' in state:
9452 file.Write(" case %s:\n" % state['enum'])
9453 file.Write(" *num_written = %d;\n" % len(state['states']))
9454 file.Write(" if (params) {\n")
9455 for ndx,item in enumerate(state['states']):
9456 file.Write(" params[%d] = static_cast<%s>(%s);\n" %
9457 (ndx, gl_type, item['name']))
9458 file.Write(" }\n")
9459 file.Write(" return true;\n")
9460 else:
9461 for item in state['states']:
9462 file.Write(" case %s:\n" % item['enum'])
9463 if isinstance(item['default'], list):
9464 item_len = len(item['default'])
9465 file.Write(" *num_written = %d;\n" % item_len)
9466 file.Write(" if (params) {\n")
9467 if item['type'] == gl_type:
9468 file.Write(" memcpy(params, %s, sizeof(%s) * %d);\n" %
9469 (item['name'], item['type'], item_len))
9470 else:
9471 file.Write(" for (size_t i = 0; i < %s; ++i) {\n" %
9472 item_len)
9473 file.Write(" params[i] = %s;\n" %
9474 (GetGLGetTypeConversion(gl_type, item['type'],
9475 "%s[i]" % item['name'])))
9476 file.Write(" }\n");
9477 else:
9478 file.Write(" *num_written = 1;\n")
9479 file.Write(" if (params) {\n")
9480 file.Write(" params[0] = %s;\n" %
9481 (GetGLGetTypeConversion(gl_type, item['type'],
9482 item['name'])))
9483 file.Write(" }\n")
9484 file.Write(" return true;\n")
9485 for capability in _CAPABILITY_FLAGS:
9486 file.Write(" case GL_%s:\n" % capability['name'].upper())
9487 file.Write(" *num_written = 1;\n")
9488 file.Write(" if (params) {\n")
9489 file.Write(
9490 " params[0] = static_cast<%s>(enable_flags.%s);\n" %
9491 (gl_type, capability['name']))
9492 file.Write(" }\n")
9493 file.Write(" return true;\n")
9494 file.Write(""" default:
9495 return false;
9498 """)
9500 def WriteServiceContextStateImpl(self, filename):
9501 """Writes the context state service implementation."""
9502 file = CHeaderWriter(
9503 filename,
9504 "// It is included by context_state.cc\n")
9505 code = []
9506 for capability in _CAPABILITY_FLAGS:
9507 code.append("%s(%s)" %
9508 (capability['name'],
9509 ('false', 'true')['default' in capability]))
9510 code.append("cached_%s(%s)" %
9511 (capability['name'],
9512 ('false', 'true')['default' in capability]))
9513 file.Write("ContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9514 ",\n ".join(code))
9515 file.Write("\n")
9517 file.Write("void ContextState::Initialize() {\n")
9518 for state_name in sorted(_STATES.keys()):
9519 state = _STATES[state_name]
9520 for item in state['states']:
9521 if isinstance(item['default'], list):
9522 for ndx, value in enumerate(item['default']):
9523 file.Write(" %s[%d] = %s;\n" % (item['name'], ndx, value))
9524 else:
9525 file.Write(" %s = %s;\n" % (item['name'], item['default']))
9526 if item.get('cached', False):
9527 if isinstance(item['default'], list):
9528 for ndx, value in enumerate(item['default']):
9529 file.Write(" cached_%s[%d] = %s;\n" % (item['name'], ndx, value))
9530 else:
9531 file.Write(" cached_%s = %s;\n" % (item['name'], item['default']))
9532 file.Write("}\n")
9534 file.Write("""
9535 void ContextState::InitCapabilities(const ContextState* prev_state) const {
9536 """)
9537 def WriteCapabilities(test_prev):
9538 for capability in _CAPABILITY_FLAGS:
9539 capability_name = capability['name']
9540 if test_prev:
9541 file.Write(""" if (prev_state->enable_flags.cached_%s !=
9542 enable_flags.cached_%s)\n""" %
9543 (capability_name, capability_name))
9544 file.Write(" EnableDisable(GL_%s, enable_flags.cached_%s);\n" %
9545 (capability_name.upper(), capability_name))
9547 file.Write(" if (prev_state) {")
9548 WriteCapabilities(True)
9549 file.Write(" } else {")
9550 WriteCapabilities(False)
9551 file.Write(" }")
9553 file.Write("""}
9555 void ContextState::InitState(const ContextState *prev_state) const {
9556 """)
9558 def WriteStates(test_prev):
9559 # We need to sort the keys so the expectations match
9560 for state_name in sorted(_STATES.keys()):
9561 state = _STATES[state_name]
9562 if state['type'] == 'FrontBack':
9563 num_states = len(state['states'])
9564 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
9565 if test_prev:
9566 file.Write(" if (")
9567 args = []
9568 for place, item in enumerate(group):
9569 item_name = CachedStateName(item)
9570 args.append('%s' % item_name)
9571 if test_prev:
9572 if place > 0:
9573 file.Write(' ||\n')
9574 file.Write("(%s != prev_state->%s)" % (item_name, item_name))
9575 if test_prev:
9576 file.Write(")\n")
9577 file.Write(
9578 " gl%s(%s, %s);\n" %
9579 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
9580 elif state['type'] == 'NamedParameter':
9581 for item in state['states']:
9582 item_name = CachedStateName(item)
9584 if 'extension_flag' in item:
9585 file.Write(" if (feature_info_->feature_flags().%s) {\n " %
9586 item['extension_flag'])
9587 if test_prev:
9588 if isinstance(item['default'], list):
9589 file.Write(" if (memcmp(prev_state->%s, %s, "
9590 "sizeof(%s) * %d)) {\n" %
9591 (item_name, item_name, item['type'],
9592 len(item['default'])))
9593 else:
9594 file.Write(" if (prev_state->%s != %s) {\n " %
9595 (item_name, item_name))
9596 file.Write(" gl%s(%s, %s);\n" %
9597 (state['func'],
9598 (item['enum_set']
9599 if 'enum_set' in item else item['enum']),
9600 item['name']))
9601 if test_prev:
9602 if 'extension_flag' in item:
9603 file.Write(" ")
9604 file.Write(" }")
9605 if 'extension_flag' in item:
9606 file.Write(" }")
9607 else:
9608 if 'extension_flag' in state:
9609 file.Write(" if (feature_info_->feature_flags().%s)\n " %
9610 state['extension_flag'])
9611 if test_prev:
9612 file.Write(" if (")
9613 args = []
9614 for place, item in enumerate(state['states']):
9615 item_name = CachedStateName(item)
9616 args.append('%s' % item_name)
9617 if test_prev:
9618 if place > 0:
9619 file.Write(' ||\n')
9620 file.Write("(%s != prev_state->%s)" %
9621 (item_name, item_name))
9622 if test_prev:
9623 file.Write(" )\n")
9624 file.Write(" gl%s(%s);\n" % (state['func'], ", ".join(args)))
9626 file.Write(" if (prev_state) {")
9627 WriteStates(True)
9628 file.Write(" } else {")
9629 WriteStates(False)
9630 file.Write(" }")
9631 file.Write("}\n")
9633 file.Write("""bool ContextState::GetEnabled(GLenum cap) const {
9634 switch (cap) {
9635 """)
9636 for capability in _CAPABILITY_FLAGS:
9637 file.Write(" case GL_%s:\n" % capability['name'].upper())
9638 file.Write(" return enable_flags.%s;\n" % capability['name'])
9639 file.Write(""" default:
9640 NOTREACHED();
9641 return false;
9644 """)
9646 self.WriteContextStateGetters(file, "ContextState")
9647 file.Close()
9648 self.generated_cpp_filenames.append(file.filename)
9650 def WriteClientContextStateImpl(self, filename):
9651 """Writes the context state client side implementation."""
9652 file = CHeaderWriter(
9653 filename,
9654 "// It is included by client_context_state.cc\n")
9655 code = []
9656 for capability in _CAPABILITY_FLAGS:
9657 code.append("%s(%s)" %
9658 (capability['name'],
9659 ('false', 'true')['default' in capability]))
9660 file.Write(
9661 "ClientContextState::EnableFlags::EnableFlags()\n : %s {\n}\n" %
9662 ",\n ".join(code))
9663 file.Write("\n")
9665 file.Write("""
9666 bool ClientContextState::SetCapabilityState(
9667 GLenum cap, bool enabled, bool* changed) {
9668 *changed = false;
9669 switch (cap) {
9670 """)
9671 for capability in _CAPABILITY_FLAGS:
9672 file.Write(" case GL_%s:\n" % capability['name'].upper())
9673 file.Write(""" if (enable_flags.%(name)s != enabled) {
9674 *changed = true;
9675 enable_flags.%(name)s = enabled;
9677 return true;
9678 """ % capability)
9679 file.Write(""" default:
9680 return false;
9683 """)
9684 file.Write("""bool ClientContextState::GetEnabled(
9685 GLenum cap, bool* enabled) const {
9686 switch (cap) {
9687 """)
9688 for capability in _CAPABILITY_FLAGS:
9689 file.Write(" case GL_%s:\n" % capability['name'].upper())
9690 file.Write(" *enabled = enable_flags.%s;\n" % capability['name'])
9691 file.Write(" return true;\n")
9692 file.Write(""" default:
9693 return false;
9696 """)
9697 file.Close()
9698 self.generated_cpp_filenames.append(file.filename)
9700 def WriteServiceImplementation(self, filename):
9701 """Writes the service decorder implementation."""
9702 file = CHeaderWriter(
9703 filename,
9704 "// It is included by gles2_cmd_decoder.cc\n")
9706 for func in self.functions:
9707 if True:
9708 #gen_cmd = func.GetInfo('gen_cmd')
9709 #if gen_cmd == True or gen_cmd == None:
9710 func.WriteServiceImplementation(file)
9712 file.Write("""
9713 bool GLES2DecoderImpl::SetCapabilityState(GLenum cap, bool enabled) {
9714 switch (cap) {
9715 """)
9716 for capability in _CAPABILITY_FLAGS:
9717 file.Write(" case GL_%s:\n" % capability['name'].upper())
9718 if 'state_flag' in capability:
9720 file.Write("""\
9721 state_.enable_flags.%(name)s = enabled;
9722 if (state_.enable_flags.cached_%(name)s != enabled
9723 || state_.ignore_cached_state) {
9724 %(state_flag)s = true;
9726 return false;
9727 """ % capability)
9728 else:
9729 file.Write("""\
9730 state_.enable_flags.%(name)s = enabled;
9731 if (state_.enable_flags.cached_%(name)s != enabled
9732 || state_.ignore_cached_state) {
9733 state_.enable_flags.cached_%(name)s = enabled;
9734 return true;
9736 return false;
9737 """ % capability)
9738 file.Write(""" default:
9739 NOTREACHED();
9740 return false;
9743 """)
9744 file.Close()
9745 self.generated_cpp_filenames.append(file.filename)
9747 def WriteServiceUnitTests(self, filename):
9748 """Writes the service decorder unit tests."""
9749 num_tests = len(self.functions)
9750 FUNCTIONS_PER_FILE = 98 # hard code this so it doesn't change.
9751 count = 0
9752 for test_num in range(0, num_tests, FUNCTIONS_PER_FILE):
9753 count += 1
9754 name = filename % count
9755 file = CHeaderWriter(
9756 name,
9757 "// It is included by gles2_cmd_decoder_unittest_%d.cc\n" % count)
9758 test_name = 'GLES2DecoderTest%d' % count
9759 end = test_num + FUNCTIONS_PER_FILE
9760 if end > num_tests:
9761 end = num_tests
9762 for idx in range(test_num, end):
9763 func = self.functions[idx]
9765 # Do any filtering of the functions here, so that the functions
9766 # will not move between the numbered files if filtering properties
9767 # are changed.
9768 if func.GetInfo('extension_flag'):
9769 continue
9771 if True:
9772 #gen_cmd = func.GetInfo('gen_cmd')
9773 #if gen_cmd == True or gen_cmd == None:
9774 if func.GetInfo('unit_test') == False:
9775 file.Write("// TODO(gman): %s\n" % func.name)
9776 else:
9777 func.WriteServiceUnitTest(file, {
9778 'test_name': test_name
9780 file.Close()
9781 self.generated_cpp_filenames.append(file.filename)
9782 file = CHeaderWriter(
9783 filename % 0,
9784 "// It is included by gles2_cmd_decoder_unittest_base.cc\n")
9785 file.Write(
9786 """void GLES2DecoderTestBase::SetupInitCapabilitiesExpectations() {
9787 """)
9788 for capability in _CAPABILITY_FLAGS:
9789 file.Write(" ExpectEnableDisable(GL_%s, %s);\n" %
9790 (capability['name'].upper(),
9791 ('false', 'true')['default' in capability]))
9792 file.Write("""}
9794 void GLES2DecoderTestBase::SetupInitStateExpectations() {
9795 """)
9797 # We need to sort the keys so the expectations match
9798 for state_name in sorted(_STATES.keys()):
9799 state = _STATES[state_name]
9800 if state['type'] == 'FrontBack':
9801 num_states = len(state['states'])
9802 for ndx, group in enumerate(Grouper(num_states / 2, state['states'])):
9803 args = []
9804 for item in group:
9805 if 'expected' in item:
9806 args.append(item['expected'])
9807 else:
9808 args.append(item['default'])
9809 file.Write(
9810 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
9811 (state['func'], ('GL_FRONT', 'GL_BACK')[ndx], ", ".join(args)))
9812 file.Write(" .Times(1)\n")
9813 file.Write(" .RetiresOnSaturation();\n")
9814 elif state['type'] == 'NamedParameter':
9815 for item in state['states']:
9816 if 'extension_flag' in item:
9817 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
9818 item['extension_flag'])
9819 file.Write(" ")
9820 expect_value = item['default']
9821 if isinstance(expect_value, list):
9822 # TODO: Currently we do not check array values.
9823 expect_value = "_"
9825 file.Write(
9826 " EXPECT_CALL(*gl_, %s(%s, %s))\n" %
9827 (state['func'],
9828 (item['enum_set']
9829 if 'enum_set' in item else item['enum']),
9830 expect_value))
9831 file.Write(" .Times(1)\n")
9832 file.Write(" .RetiresOnSaturation();\n")
9833 if 'extension_flag' in item:
9834 file.Write(" }\n")
9835 else:
9836 if 'extension_flag' in state:
9837 file.Write(" if (group_->feature_info()->feature_flags().%s) {\n" %
9838 state['extension_flag'])
9839 file.Write(" ")
9840 args = []
9841 for item in state['states']:
9842 if 'expected' in item:
9843 args.append(item['expected'])
9844 else:
9845 args.append(item['default'])
9846 # TODO: Currently we do not check array values.
9847 args = ["_" if isinstance(arg, list) else arg for arg in args]
9848 file.Write(" EXPECT_CALL(*gl_, %s(%s))\n" %
9849 (state['func'], ", ".join(args)))
9850 file.Write(" .Times(1)\n")
9851 file.Write(" .RetiresOnSaturation();\n")
9852 if 'extension_flag' in state:
9853 file.Write(" }\n")
9854 file.Write("""}
9855 """)
9856 file.Close()
9857 self.generated_cpp_filenames.append(file.filename)
9859 def WriteServiceUnitTestsForExtensions(self, filename):
9860 """Writes the service decorder unit tests for functions with extension_flag.
9862 The functions are special in that they need a specific unit test
9863 baseclass to turn on the extension.
9865 functions = [f for f in self.functions if f.GetInfo('extension_flag')]
9866 file = CHeaderWriter(
9867 filename,
9868 "// It is included by gles2_cmd_decoder_unittest_extensions.cc\n")
9869 for func in functions:
9870 if True:
9871 if func.GetInfo('unit_test') == False:
9872 file.Write("// TODO(gman): %s\n" % func.name)
9873 else:
9874 extension = ToCamelCase(
9875 ToGLExtensionString(func.GetInfo('extension_flag')))
9876 func.WriteServiceUnitTest(file, {
9877 'test_name': 'GLES2DecoderTestWith%s' % extension
9880 file.Close()
9881 self.generated_cpp_filenames.append(file.filename)
9883 def WriteGLES2Header(self, filename):
9884 """Writes the GLES2 header."""
9885 file = CHeaderWriter(
9886 filename,
9887 "// This file contains Chromium-specific GLES2 declarations.\n\n")
9889 for func in self.original_functions:
9890 func.WriteGLES2Header(file)
9892 file.Write("\n")
9893 file.Close()
9894 self.generated_cpp_filenames.append(file.filename)
9896 def WriteGLES2CLibImplementation(self, filename):
9897 """Writes the GLES2 c lib implementation."""
9898 file = CHeaderWriter(
9899 filename,
9900 "// These functions emulate GLES2 over command buffers.\n")
9902 for func in self.original_functions:
9903 func.WriteGLES2CLibImplementation(file)
9905 file.Write("""
9906 namespace gles2 {
9908 extern const NameToFunc g_gles2_function_table[] = {
9909 """)
9910 for func in self.original_functions:
9911 file.Write(
9912 ' { "gl%s", reinterpret_cast<GLES2FunctionPointer>(gl%s), },\n' %
9913 (func.name, func.name))
9914 file.Write(""" { NULL, NULL, },
9917 } // namespace gles2
9918 """)
9919 file.Close()
9920 self.generated_cpp_filenames.append(file.filename)
9922 def WriteGLES2InterfaceHeader(self, filename):
9923 """Writes the GLES2 interface header."""
9924 file = CHeaderWriter(
9925 filename,
9926 "// This file is included by gles2_interface.h to declare the\n"
9927 "// GL api functions.\n")
9928 for func in self.original_functions:
9929 func.WriteGLES2InterfaceHeader(file)
9930 file.Close()
9931 self.generated_cpp_filenames.append(file.filename)
9933 def WriteGLES2InterfaceStub(self, filename):
9934 """Writes the GLES2 interface stub header."""
9935 file = CHeaderWriter(
9936 filename,
9937 "// This file is included by gles2_interface_stub.h.\n")
9938 for func in self.original_functions:
9939 func.WriteGLES2InterfaceStub(file)
9940 file.Close()
9941 self.generated_cpp_filenames.append(file.filename)
9943 def WriteGLES2InterfaceStubImpl(self, filename):
9944 """Writes the GLES2 interface header."""
9945 file = CHeaderWriter(
9946 filename,
9947 "// This file is included by gles2_interface_stub.cc.\n")
9948 for func in self.original_functions:
9949 func.WriteGLES2InterfaceStubImpl(file)
9950 file.Close()
9951 self.generated_cpp_filenames.append(file.filename)
9953 def WriteGLES2ImplementationHeader(self, filename):
9954 """Writes the GLES2 Implementation header."""
9955 file = CHeaderWriter(
9956 filename,
9957 "// This file is included by gles2_implementation.h to declare the\n"
9958 "// GL api functions.\n")
9959 for func in self.original_functions:
9960 func.WriteGLES2ImplementationHeader(file)
9961 file.Close()
9962 self.generated_cpp_filenames.append(file.filename)
9964 def WriteGLES2Implementation(self, filename):
9965 """Writes the GLES2 Implementation."""
9966 file = CHeaderWriter(
9967 filename,
9968 "// This file is included by gles2_implementation.cc to define the\n"
9969 "// GL api functions.\n")
9970 for func in self.original_functions:
9971 func.WriteGLES2Implementation(file)
9972 file.Close()
9973 self.generated_cpp_filenames.append(file.filename)
9975 def WriteGLES2TraceImplementationHeader(self, filename):
9976 """Writes the GLES2 Trace Implementation header."""
9977 file = CHeaderWriter(
9978 filename,
9979 "// This file is included by gles2_trace_implementation.h\n")
9980 for func in self.original_functions:
9981 func.WriteGLES2TraceImplementationHeader(file)
9982 file.Close()
9983 self.generated_cpp_filenames.append(file.filename)
9985 def WriteGLES2TraceImplementation(self, filename):
9986 """Writes the GLES2 Trace Implementation."""
9987 file = CHeaderWriter(
9988 filename,
9989 "// This file is included by gles2_trace_implementation.cc\n")
9990 for func in self.original_functions:
9991 func.WriteGLES2TraceImplementation(file)
9992 file.Close()
9993 self.generated_cpp_filenames.append(file.filename)
9995 def WriteGLES2ImplementationUnitTests(self, filename):
9996 """Writes the GLES2 helper header."""
9997 file = CHeaderWriter(
9998 filename,
9999 "// This file is included by gles2_implementation.h to declare the\n"
10000 "// GL api functions.\n")
10001 for func in self.original_functions:
10002 func.WriteGLES2ImplementationUnitTest(file)
10003 file.Close()
10004 self.generated_cpp_filenames.append(file.filename)
10006 def WriteServiceUtilsHeader(self, filename):
10007 """Writes the gles2 auto generated utility header."""
10008 file = CHeaderWriter(filename)
10009 for name in sorted(_NAMED_TYPE_INFO.keys()):
10010 named_type = NamedType(_NAMED_TYPE_INFO[name])
10011 if named_type.IsConstant():
10012 continue
10013 file.Write("ValueValidator<%s> %s;\n" %
10014 (named_type.GetType(), ToUnderscore(name)))
10015 file.Write("\n")
10016 file.Close()
10017 self.generated_cpp_filenames.append(file.filename)
10019 def WriteServiceUtilsImplementation(self, filename):
10020 """Writes the gles2 auto generated utility implementation."""
10021 file = CHeaderWriter(filename)
10022 names = sorted(_NAMED_TYPE_INFO.keys())
10023 for name in names:
10024 named_type = NamedType(_NAMED_TYPE_INFO[name])
10025 if named_type.IsConstant():
10026 continue
10027 if named_type.GetValidValues():
10028 file.Write("static const %s valid_%s_table[] = {\n" %
10029 (named_type.GetType(), ToUnderscore(name)))
10030 for value in named_type.GetValidValues():
10031 file.Write(" %s,\n" % value)
10032 file.Write("};\n")
10033 file.Write("\n")
10034 if named_type.GetValidValuesES3():
10035 file.Write("static const %s valid_%s_table_es3[] = {\n" %
10036 (named_type.GetType(), ToUnderscore(name)))
10037 for value in named_type.GetValidValuesES3():
10038 file.Write(" %s,\n" % value)
10039 file.Write("};\n")
10040 file.Write("\n")
10041 if named_type.GetDeprecatedValuesES3():
10042 file.Write("static const %s deprecated_%s_table_es3[] = {\n" %
10043 (named_type.GetType(), ToUnderscore(name)))
10044 for value in named_type.GetDeprecatedValuesES3():
10045 file.Write(" %s,\n" % value)
10046 file.Write("};\n")
10047 file.Write("\n")
10048 file.Write("Validators::Validators()")
10049 pre = ' : '
10050 for count, name in enumerate(names):
10051 named_type = NamedType(_NAMED_TYPE_INFO[name])
10052 if named_type.IsConstant():
10053 continue
10054 if named_type.GetValidValues():
10055 code = """%(pre)s%(name)s(
10056 valid_%(name)s_table, arraysize(valid_%(name)s_table))"""
10057 else:
10058 code = "%(pre)s%(name)s()"
10059 file.Write(code % {
10060 'name': ToUnderscore(name),
10061 'pre': pre,
10063 pre = ',\n '
10064 file.Write(" {\n");
10065 file.Write("}\n\n");
10067 file.Write("void Validators::UpdateValuesES3() {\n")
10068 for name in names:
10069 named_type = NamedType(_NAMED_TYPE_INFO[name])
10070 if named_type.GetDeprecatedValuesES3():
10071 code = """ %(name)s.RemoveValues(
10072 deprecated_%(name)s_table_es3, arraysize(deprecated_%(name)s_table_es3));
10074 file.Write(code % {
10075 'name': ToUnderscore(name),
10077 if named_type.GetValidValuesES3():
10078 code = """ %(name)s.AddValues(
10079 valid_%(name)s_table_es3, arraysize(valid_%(name)s_table_es3));
10081 file.Write(code % {
10082 'name': ToUnderscore(name),
10084 file.Write("}\n\n");
10085 file.Close()
10086 self.generated_cpp_filenames.append(file.filename)
10088 def WriteCommonUtilsHeader(self, filename):
10089 """Writes the gles2 common utility header."""
10090 file = CHeaderWriter(filename)
10091 type_infos = sorted(_NAMED_TYPE_INFO.keys())
10092 for type_info in type_infos:
10093 if _NAMED_TYPE_INFO[type_info]['type'] == 'GLenum':
10094 file.Write("static std::string GetString%s(uint32_t value);\n" %
10095 type_info)
10096 file.Write("\n")
10097 file.Close()
10098 self.generated_cpp_filenames.append(file.filename)
10100 def WriteCommonUtilsImpl(self, filename):
10101 """Writes the gles2 common utility header."""
10102 enum_re = re.compile(r'\#define\s+(GL_[a-zA-Z0-9_]+)\s+([0-9A-Fa-fx]+)')
10103 dict = {}
10104 for fname in ['third_party/khronos/GLES2/gl2.h',
10105 'third_party/khronos/GLES2/gl2ext.h',
10106 'third_party/khronos/GLES3/gl3.h',
10107 'gpu/GLES2/gl2chromium.h',
10108 'gpu/GLES2/gl2extchromium.h']:
10109 lines = open(fname).readlines()
10110 for line in lines:
10111 m = enum_re.match(line)
10112 if m:
10113 name = m.group(1)
10114 value = m.group(2)
10115 if len(value) <= 10:
10116 if not value in dict:
10117 dict[value] = name
10118 # check our own _CHROMIUM macro conflicts with khronos GL headers.
10119 elif dict[value] != name and (name.endswith('_CHROMIUM') or
10120 dict[value].endswith('_CHROMIUM')):
10121 self.Error("code collision: %s and %s have the same code %s" %
10122 (dict[value], name, value))
10124 file = CHeaderWriter(filename)
10125 file.Write("static const GLES2Util::EnumToString "
10126 "enum_to_string_table[] = {\n")
10127 for value in dict:
10128 file.Write(' { %s, "%s", },\n' % (value, dict[value]))
10129 file.Write("""};
10131 const GLES2Util::EnumToString* const GLES2Util::enum_to_string_table_ =
10132 enum_to_string_table;
10133 const size_t GLES2Util::enum_to_string_table_len_ =
10134 sizeof(enum_to_string_table) / sizeof(enum_to_string_table[0]);
10136 """)
10138 enums = sorted(_NAMED_TYPE_INFO.keys())
10139 for enum in enums:
10140 if _NAMED_TYPE_INFO[enum]['type'] == 'GLenum':
10141 file.Write("std::string GLES2Util::GetString%s(uint32_t value) {\n" %
10142 enum)
10143 valid_list = _NAMED_TYPE_INFO[enum]['valid']
10144 if 'valid_es3' in _NAMED_TYPE_INFO[enum]:
10145 valid_list = valid_list + _NAMED_TYPE_INFO[enum]['valid_es3']
10146 assert len(valid_list) == len(set(valid_list))
10147 if len(valid_list) > 0:
10148 file.Write(" static const EnumToString string_table[] = {\n")
10149 for value in valid_list:
10150 file.Write(' { %s, "%s" },\n' % (value, value))
10151 file.Write(""" };
10152 return GLES2Util::GetQualifiedEnumString(
10153 string_table, arraysize(string_table), value);
10156 """)
10157 else:
10158 file.Write(""" return GLES2Util::GetQualifiedEnumString(
10159 NULL, 0, value);
10162 """)
10163 file.Close()
10164 self.generated_cpp_filenames.append(file.filename)
10166 def WritePepperGLES2Interface(self, filename, dev):
10167 """Writes the Pepper OpenGLES interface definition."""
10168 file = CWriter(filename)
10169 file.Write(_LICENSE)
10170 file.Write(_DO_NOT_EDIT_WARNING)
10172 file.Write("label Chrome {\n")
10173 file.Write(" M39 = 1.0\n")
10174 file.Write("};\n\n")
10176 if not dev:
10177 # Declare GL types.
10178 file.Write("[version=1.0]\n")
10179 file.Write("describe {\n")
10180 for gltype in ['GLbitfield', 'GLboolean', 'GLbyte', 'GLclampf',
10181 'GLclampx', 'GLenum', 'GLfixed', 'GLfloat', 'GLint',
10182 'GLintptr', 'GLshort', 'GLsizei', 'GLsizeiptr',
10183 'GLubyte', 'GLuint', 'GLushort']:
10184 file.Write(" %s;\n" % gltype)
10185 file.Write(" %s_ptr_t;\n" % gltype)
10186 file.Write("};\n\n")
10188 # C level typedefs.
10189 file.Write("#inline c\n")
10190 file.Write("#include \"ppapi/c/pp_resource.h\"\n")
10191 if dev:
10192 file.Write("#include \"ppapi/c/ppb_opengles2.h\"\n\n")
10193 else:
10194 file.Write("\n#ifndef __gl2_h_\n")
10195 for (k, v) in _GL_TYPES.iteritems():
10196 file.Write("typedef %s %s;\n" % (v, k))
10197 file.Write("#ifdef _WIN64\n")
10198 for (k, v) in _GL_TYPES_64.iteritems():
10199 file.Write("typedef %s %s;\n" % (v, k))
10200 file.Write("#else\n")
10201 for (k, v) in _GL_TYPES_32.iteritems():
10202 file.Write("typedef %s %s;\n" % (v, k))
10203 file.Write("#endif // _WIN64\n")
10204 file.Write("#endif // __gl2_h_\n\n")
10205 file.Write("#endinl\n")
10207 for interface in self.pepper_interfaces:
10208 if interface.dev != dev:
10209 continue
10210 # Historically, we provide OpenGLES2 interfaces with struct
10211 # namespace. Not to break code which uses the interface as
10212 # "struct OpenGLES2", we put it in struct namespace.
10213 file.Write('\n[macro="%s", force_struct_namespace]\n' %
10214 interface.GetInterfaceName())
10215 file.Write("interface %s {\n" % interface.GetStructName())
10216 for func in self.original_functions:
10217 if not func.InPepperInterface(interface):
10218 continue
10220 ret_type = func.MapCTypeToPepperIdlType(func.return_type,
10221 is_for_return_type=True)
10222 func_prefix = " %s %s(" % (ret_type, func.GetPepperName())
10223 file.Write(func_prefix)
10224 file.Write("[in] PP_Resource context")
10225 for arg in func.MakeTypedPepperIdlArgStrings():
10226 file.Write(",\n" + " " * len(func_prefix) + arg)
10227 file.Write(");\n")
10228 file.Write("};\n\n")
10231 file.Close()
10233 def WritePepperGLES2Implementation(self, filename):
10234 """Writes the Pepper OpenGLES interface implementation."""
10236 file = CWriter(filename)
10237 file.Write(_LICENSE)
10238 file.Write(_DO_NOT_EDIT_WARNING)
10240 file.Write("#include \"ppapi/shared_impl/ppb_opengles2_shared.h\"\n\n")
10241 file.Write("#include \"base/logging.h\"\n")
10242 file.Write("#include \"gpu/command_buffer/client/gles2_implementation.h\"\n")
10243 file.Write("#include \"ppapi/shared_impl/ppb_graphics_3d_shared.h\"\n")
10244 file.Write("#include \"ppapi/thunk/enter.h\"\n\n")
10246 file.Write("namespace ppapi {\n\n")
10247 file.Write("namespace {\n\n")
10249 file.Write("typedef thunk::EnterResource<thunk::PPB_Graphics3D_API>"
10250 " Enter3D;\n\n")
10252 file.Write("gpu::gles2::GLES2Implementation* ToGles2Impl(Enter3D*"
10253 " enter) {\n")
10254 file.Write(" DCHECK(enter);\n")
10255 file.Write(" DCHECK(enter->succeeded());\n")
10256 file.Write(" return static_cast<PPB_Graphics3D_Shared*>(enter->object())->"
10257 "gles2_impl();\n");
10258 file.Write("}\n\n");
10260 for func in self.original_functions:
10261 if not func.InAnyPepperExtension():
10262 continue
10264 original_arg = func.MakeTypedPepperArgString("")
10265 context_arg = "PP_Resource context_id"
10266 if len(original_arg):
10267 arg = context_arg + ", " + original_arg
10268 else:
10269 arg = context_arg
10270 file.Write("%s %s(%s) {\n" %
10271 (func.return_type, func.GetPepperName(), arg))
10272 file.Write(" Enter3D enter(context_id, true);\n")
10273 file.Write(" if (enter.succeeded()) {\n")
10275 return_str = "" if func.return_type == "void" else "return "
10276 file.Write(" %sToGles2Impl(&enter)->%s(%s);\n" %
10277 (return_str, func.original_name,
10278 func.MakeOriginalArgString("")))
10279 file.Write(" }")
10280 if func.return_type == "void":
10281 file.Write("\n")
10282 else:
10283 file.Write(" else {\n")
10284 file.Write(" return %s;\n" % func.GetErrorReturnString())
10285 file.Write(" }\n")
10286 file.Write("}\n\n")
10288 file.Write("} // namespace\n")
10290 for interface in self.pepper_interfaces:
10291 file.Write("const %s* PPB_OpenGLES2_Shared::Get%sInterface() {\n" %
10292 (interface.GetStructName(), interface.GetName()))
10293 file.Write(" static const struct %s "
10294 "ppb_opengles2 = {\n" % interface.GetStructName())
10295 file.Write(" &")
10296 file.Write(",\n &".join(
10297 f.GetPepperName() for f in self.original_functions
10298 if f.InPepperInterface(interface)))
10299 file.Write("\n")
10301 file.Write(" };\n")
10302 file.Write(" return &ppb_opengles2;\n")
10303 file.Write("}\n")
10305 file.Write("} // namespace ppapi\n")
10306 file.Close()
10307 self.generated_cpp_filenames.append(file.filename)
10309 def WriteGLES2ToPPAPIBridge(self, filename):
10310 """Connects GLES2 helper library to PPB_OpenGLES2 interface"""
10312 file = CWriter(filename)
10313 file.Write(_LICENSE)
10314 file.Write(_DO_NOT_EDIT_WARNING)
10316 file.Write("#ifndef GL_GLEXT_PROTOTYPES\n")
10317 file.Write("#define GL_GLEXT_PROTOTYPES\n")
10318 file.Write("#endif\n")
10319 file.Write("#include <GLES2/gl2.h>\n")
10320 file.Write("#include <GLES2/gl2ext.h>\n")
10321 file.Write("#include \"ppapi/lib/gl/gles2/gl2ext_ppapi.h\"\n\n")
10323 for func in self.original_functions:
10324 if not func.InAnyPepperExtension():
10325 continue
10327 interface = self.interface_info[func.GetInfo('pepper_interface') or '']
10329 file.Write("%s GL_APIENTRY gl%s(%s) {\n" %
10330 (func.return_type, func.GetPepperName(),
10331 func.MakeTypedPepperArgString("")))
10332 return_str = "" if func.return_type == "void" else "return "
10333 interface_str = "glGet%sInterfacePPAPI()" % interface.GetName()
10334 original_arg = func.MakeOriginalArgString("")
10335 context_arg = "glGetCurrentContextPPAPI()"
10336 if len(original_arg):
10337 arg = context_arg + ", " + original_arg
10338 else:
10339 arg = context_arg
10340 if interface.GetName():
10341 file.Write(" const struct %s* ext = %s;\n" %
10342 (interface.GetStructName(), interface_str))
10343 file.Write(" if (ext)\n")
10344 file.Write(" %sext->%s(%s);\n" %
10345 (return_str, func.GetPepperName(), arg))
10346 if return_str:
10347 file.Write(" %s0;\n" % return_str)
10348 else:
10349 file.Write(" %s%s->%s(%s);\n" %
10350 (return_str, interface_str, func.GetPepperName(), arg))
10351 file.Write("}\n\n")
10352 file.Close()
10353 self.generated_cpp_filenames.append(file.filename)
10355 def WriteMojoGLCallVisitor(self, filename):
10356 """Provides the GL implementation for mojo"""
10357 file = CWriter(filename)
10358 file.Write(_LICENSE)
10359 file.Write(_DO_NOT_EDIT_WARNING)
10361 for func in self.original_functions:
10362 if not func.IsCoreGLFunction():
10363 continue
10364 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10365 (func.name, func.return_type,
10366 func.MakeTypedOriginalArgString(""),
10367 func.MakeOriginalArgString("")))
10369 file.Close()
10370 self.generated_cpp_filenames.append(file.filename)
10372 def WriteMojoGLCallVisitorForExtension(self, filename, extension):
10373 """Provides the GL implementation for mojo for a particular extension"""
10374 file = CWriter(filename)
10375 file.Write(_LICENSE)
10376 file.Write(_DO_NOT_EDIT_WARNING)
10378 for func in self.original_functions:
10379 if func.GetInfo("extension") != extension:
10380 continue
10381 file.Write("VISIT_GL_CALL(%s, %s, (%s), (%s))\n" %
10382 (func.name, func.return_type,
10383 func.MakeTypedOriginalArgString(""),
10384 func.MakeOriginalArgString("")))
10386 file.Close()
10387 self.generated_cpp_filenames.append(file.filename)
10389 def Format(generated_files):
10390 formatter = "clang-format"
10391 if platform.system() == "Windows":
10392 formatter += ".bat"
10393 for filename in generated_files:
10394 call([formatter, "-i", "-style=chromium", filename])
10396 def main(argv):
10397 """This is the main function."""
10398 parser = OptionParser()
10399 parser.add_option(
10400 "--output-dir",
10401 help="base directory for resulting files, under chrome/src. default is "
10402 "empty. Use this if you want the result stored under gen.")
10403 parser.add_option(
10404 "-v", "--verbose", action="store_true",
10405 help="prints more output.")
10407 (options, args) = parser.parse_args(args=argv)
10409 # Add in states and capabilites to GLState
10410 gl_state_valid = _NAMED_TYPE_INFO['GLState']['valid']
10411 for state_name in sorted(_STATES.keys()):
10412 state = _STATES[state_name]
10413 if 'extension_flag' in state:
10414 continue
10415 if 'enum' in state:
10416 if not state['enum'] in gl_state_valid:
10417 gl_state_valid.append(state['enum'])
10418 else:
10419 for item in state['states']:
10420 if 'extension_flag' in item:
10421 continue
10422 if not item['enum'] in gl_state_valid:
10423 gl_state_valid.append(item['enum'])
10424 for capability in _CAPABILITY_FLAGS:
10425 valid_value = "GL_%s" % capability['name'].upper()
10426 if not valid_value in gl_state_valid:
10427 gl_state_valid.append(valid_value)
10429 # This script lives under gpu/command_buffer, cd to base directory.
10430 os.chdir(os.path.dirname(__file__) + "/../..")
10431 base_dir = os.getcwd()
10432 gen = GLGenerator(options.verbose)
10433 gen.ParseGLH("gpu/command_buffer/cmd_buffer_functions.txt")
10435 # Support generating files under gen/
10436 if options.output_dir != None:
10437 os.chdir(options.output_dir)
10439 gen.WritePepperGLES2Interface("ppapi/api/ppb_opengles2.idl", False)
10440 gen.WritePepperGLES2Interface("ppapi/api/dev/ppb_opengles2ext_dev.idl", True)
10441 gen.WriteGLES2ToPPAPIBridge("ppapi/lib/gl/gles2/gles2.c")
10442 gen.WritePepperGLES2Implementation(
10443 "ppapi/shared_impl/ppb_opengles2_shared.cc")
10444 os.chdir(base_dir)
10445 gen.WriteCommandIds("gpu/command_buffer/common/gles2_cmd_ids_autogen.h")
10446 gen.WriteFormat("gpu/command_buffer/common/gles2_cmd_format_autogen.h")
10447 gen.WriteFormatTest(
10448 "gpu/command_buffer/common/gles2_cmd_format_test_autogen.h")
10449 gen.WriteGLES2InterfaceHeader(
10450 "gpu/command_buffer/client/gles2_interface_autogen.h")
10451 gen.WriteGLES2InterfaceStub(
10452 "gpu/command_buffer/client/gles2_interface_stub_autogen.h")
10453 gen.WriteGLES2InterfaceStubImpl(
10454 "gpu/command_buffer/client/gles2_interface_stub_impl_autogen.h")
10455 gen.WriteGLES2ImplementationHeader(
10456 "gpu/command_buffer/client/gles2_implementation_autogen.h")
10457 gen.WriteGLES2Implementation(
10458 "gpu/command_buffer/client/gles2_implementation_impl_autogen.h")
10459 gen.WriteGLES2ImplementationUnitTests(
10460 "gpu/command_buffer/client/gles2_implementation_unittest_autogen.h")
10461 gen.WriteGLES2TraceImplementationHeader(
10462 "gpu/command_buffer/client/gles2_trace_implementation_autogen.h")
10463 gen.WriteGLES2TraceImplementation(
10464 "gpu/command_buffer/client/gles2_trace_implementation_impl_autogen.h")
10465 gen.WriteGLES2CLibImplementation(
10466 "gpu/command_buffer/client/gles2_c_lib_autogen.h")
10467 gen.WriteCmdHelperHeader(
10468 "gpu/command_buffer/client/gles2_cmd_helper_autogen.h")
10469 gen.WriteServiceImplementation(
10470 "gpu/command_buffer/service/gles2_cmd_decoder_autogen.h")
10471 gen.WriteServiceContextStateHeader(
10472 "gpu/command_buffer/service/context_state_autogen.h")
10473 gen.WriteServiceContextStateImpl(
10474 "gpu/command_buffer/service/context_state_impl_autogen.h")
10475 gen.WriteClientContextStateHeader(
10476 "gpu/command_buffer/client/client_context_state_autogen.h")
10477 gen.WriteClientContextStateImpl(
10478 "gpu/command_buffer/client/client_context_state_impl_autogen.h")
10479 gen.WriteServiceUnitTests(
10480 "gpu/command_buffer/service/gles2_cmd_decoder_unittest_%d_autogen.h")
10481 gen.WriteServiceUnitTestsForExtensions(
10482 "gpu/command_buffer/service/"
10483 "gles2_cmd_decoder_unittest_extensions_autogen.h")
10484 gen.WriteServiceUtilsHeader(
10485 "gpu/command_buffer/service/gles2_cmd_validation_autogen.h")
10486 gen.WriteServiceUtilsImplementation(
10487 "gpu/command_buffer/service/"
10488 "gles2_cmd_validation_implementation_autogen.h")
10489 gen.WriteCommonUtilsHeader(
10490 "gpu/command_buffer/common/gles2_cmd_utils_autogen.h")
10491 gen.WriteCommonUtilsImpl(
10492 "gpu/command_buffer/common/gles2_cmd_utils_implementation_autogen.h")
10493 gen.WriteGLES2Header("gpu/GLES2/gl2chromium_autogen.h")
10494 mojo_gles2_prefix = ("third_party/mojo/src/mojo/public/c/gles2/"
10495 "gles2_call_visitor")
10496 gen.WriteMojoGLCallVisitor(mojo_gles2_prefix + "_autogen.h")
10497 gen.WriteMojoGLCallVisitorForExtension(
10498 mojo_gles2_prefix + "_chromium_texture_mailbox_autogen.h",
10499 "CHROMIUM_texture_mailbox")
10500 gen.WriteMojoGLCallVisitorForExtension(
10501 mojo_gles2_prefix + "_chromium_sync_point_autogen.h",
10502 "CHROMIUM_sync_point")
10504 Format(gen.generated_cpp_filenames)
10506 if gen.errors > 0:
10507 print "%d errors" % gen.errors
10508 return 1
10509 return 0
10512 if __name__ == '__main__':
10513 sys.exit(main(sys.argv[1:]))